2675 lines · plain
1.. FIXME: move to the stylesheet or Sphinx plugin2 3.. raw:: html4 5 <style>6 .arc-term { font-style: italic; font-weight: bold; }7 .revision { font-style: italic; }8 .when-revised { font-weight: bold; font-style: normal; }9 10 /*11 * Automatic numbering is described in this article:12 * https://dev.opera.com/articles/view/automatic-numbering-with-css-counters/13 */14 /*15 * Automatic numbering for the TOC.16 * This is wrong from the semantics point of view, since it is an ordered17 * list, but uses "ul" tag.18 */19 div#contents.contents.local ul {20 counter-reset: toc-section;21 list-style-type: none;22 }23 div#contents.contents.local ul li {24 counter-increment: toc-section;25 background: none; // Remove bullets26 }27 div#contents.contents.local ul li a.reference:before {28 content: counters(toc-section, ".") " ";29 }30 31 /* Automatic numbering for the body. */32 body {33 counter-reset: section subsection subsubsection;34 }35 .section h2 {36 counter-reset: subsection subsubsection;37 counter-increment: section;38 }39 .section h2 a.toc-backref:before {40 content: counter(section) " ";41 }42 .section h3 {43 counter-reset: subsubsection;44 counter-increment: subsection;45 }46 .section h3 a.toc-backref:before {47 content: counter(section) "." counter(subsection) " ";48 }49 .section h4 {50 counter-increment: subsubsection;51 }52 .section h4 a.toc-backref:before {53 content: counter(section) "." counter(subsection) "." counter(subsubsection) " ";54 }55 </style>56 57.. role:: arc-term58.. role:: revision59.. role:: when-revised60 61==============================================62Objective-C Automatic Reference Counting (ARC)63==============================================64 65.. contents::66 :local:67 68.. _arc.meta:69 70About this document71===================72 73.. _arc.meta.purpose:74 75Purpose76-------77 78The first and primary purpose of this document is to serve as a complete79technical specification of Automatic Reference Counting. Given a core80Objective-C compiler and runtime, it should be possible to write a compiler and81runtime which implements these new semantics.82 83The secondary purpose is to act as a rationale for why ARC was designed in this84way. This should remain tightly focused on the technical design and should not85stray into marketing speculation.86 87.. _arc.meta.background:88 89Background90----------91 92This document assumes a basic familiarity with C.93 94:arc-term:`Blocks` are a C language extension for creating anonymous functions.95Users interact with and transfer block objects using :arc-term:`block96pointers`, which are represented like a normal pointer. A block may capture97values from local variables; when this occurs, memory must be dynamically98allocated. The initial allocation is done on the stack, but the runtime99provides a ``Block_copy`` function which, given a block pointer, either copies100the underlying block object to the heap, setting its reference count to 1 and101returning the new block pointer, or (if the block object is already on the102heap) increases its reference count by 1. The paired function is103``Block_release``, which decreases the reference count by 1 and destroys the104object if the count reaches zero and is on the heap.105 106Objective-C is a set of language extensions, significant enough to be107considered a different language. It is a strict superset of C. The extensions108can also be imposed on C++, producing a language called Objective-C++. The109primary feature is a single-inheritance object system; we briefly describe the110modern dialect.111 112Objective-C defines a new type kind, collectively called the :arc-term:`object113pointer types`. This kind has two notable builtin members, ``id`` and114``Class``; ``id`` is the final supertype of all object pointers. The validity115of conversions between object pointer types is not checked at runtime. Users116may define :arc-term:`classes`; each class is a type, and the pointer to that117type is an object pointer type. A class may have a superclass; its pointer118type is a subtype of its superclass's pointer type. A class has a set of119:arc-term:`ivars`, fields which appear on all instances of that class. For120every class *T* there's an associated metaclass; it has no fields, its121superclass is the metaclass of *T*'s superclass, and its metaclass is a global122class. Every class has a global object whose class is the class's metaclass;123metaclasses have no associated type, so pointers to this object have type124``Class``.125 126A class declaration (``@interface``) declares a set of :arc-term:`methods`. A127method has a return type, a list of argument types, and a :arc-term:`selector`:128a name like ``foo:bar:baz:``, where the number of colons corresponds to the129number of formal arguments. A method may be an instance method, in which case130it can be invoked on objects of the class, or a class method, in which case it131can be invoked on objects of the metaclass. A method may be invoked by132providing an object (called the :arc-term:`receiver`) and a list of formal133arguments interspersed with the selector, like so:134 135.. code-block:: objc136 137 [receiver foo: fooArg bar: barArg baz: bazArg]138 139This looks in the dynamic class of the receiver for a method with this name,140then in that class's superclass, etc., until it finds something it can execute.141The receiver "expression" may also be the name of a class, in which case the142actual receiver is the class object for that class, or (within method143definitions) it may be ``super``, in which case the lookup algorithm starts144with the static superclass instead of the dynamic class. The actual methods145dynamically found in a class are not those declared in the ``@interface``, but146those defined in a separate ``@implementation`` declaration; however, when147compiling a call, typechecking is done based on the methods declared in the148``@interface``.149 150Method declarations may also be grouped into :arc-term:`protocols`, which are not151inherently associated with any class, but which classes may claim to follow.152Object pointer types may be qualified with additional protocols that the object153is known to support.154 155:arc-term:`Class extensions` are collections of ivars and methods, designed to156allow a class's ``@interface`` to be split across multiple files; however,157there is still a primary implementation file which must see the158``@interface``\ s of all class extensions. :arc-term:`Categories` allow159methods (but not ivars) to be declared *post hoc* on an arbitrary class; the160methods in the category's ``@implementation`` will be dynamically added to that161class's method tables which the category is loaded at runtime, replacing those162methods in case of a collision.163 164In the standard environment, objects are allocated on the heap, and their165lifetime is manually managed using a reference count. This is done using two166instance methods which all classes are expected to implement: ``retain``167increases the object's reference count by 1, whereas ``release`` decreases it168by 1 and calls the instance method ``dealloc`` if the count reaches 0. To169simplify certain operations, there is also an :arc-term:`autorelease pool`, a170thread-local list of objects to call ``release`` on later; an object can be171added to this pool by calling ``autorelease`` on it.172 173Block pointers may be converted to type ``id``; block objects are laid out in a174way that makes them compatible with Objective-C objects. There is a builtin175class that all block objects are considered to be objects of; this class176implements ``retain`` by adjusting the reference count, not by calling177``Block_copy``.178 179.. _arc.meta.evolution:180 181Evolution182---------183 184ARC is under continual evolution, and this document must be updated as the185language progresses.186 187If a change increases the expressiveness of the language, for example by188lifting a restriction or by adding new syntax, the change will be annotated189with a revision marker, like so:190 191 ARC applies to Objective-C pointer types, block pointer types, and192 :when-revised:`[beginning Apple 8.0, LLVM 3.8]` :revision:`BPTRs declared193 within` ``extern "BCPL"`` blocks.194 195For now, it is sensible to version this document by the releases of its sole196implementation (and its host project), clang. "LLVM X.Y" refers to an197open-source release of clang from the LLVM project. "Apple X.Y" refers to an198Apple-provided release of the Apple LLVM Compiler. Other organizations that199prepare their own, separately-versioned clang releases and wish to maintain200similar information in this document should send requests to cfe-dev.201 202If a change decreases the expressiveness of the language, for example by203imposing a new restriction, this should be taken as an oversight in the204original specification and something to be avoided in all versions. Such205changes are generally to be avoided.206 207.. _arc.general:208 209General210=======211 212Automatic Reference Counting implements automatic memory management for213Objective-C objects and blocks, freeing the programmer from the need to214explicitly insert retains and releases. It does not provide a cycle collector;215users must explicitly manage the lifetime of their objects, breaking cycles216manually or with weak or unsafe references.217 218ARC may be explicitly enabled with the compiler flag ``-fobjc-arc``. It may219also be explicitly disabled with the compiler flag ``-fno-objc-arc``. The last220of these two flags appearing on the compile line "wins".221 222If ARC is enabled, ``__has_feature(objc_arc)`` will expand to 1 in the223preprocessor. For more information about ``__has_feature``, see the224:ref:`language extensions <langext-__has_feature-__has_extension>` document.225 226.. _arc.objects:227 228Retainable object pointers229==========================230 231This section describes retainable object pointers, their basic operations, and232the restrictions imposed on their use under ARC. Note in particular that it233covers the rules for pointer *values* (patterns of bits indicating the location234of a pointed-to object), not pointer *objects* (locations in memory which store235pointer values). The rules for objects are covered in the next section.236 237A :arc-term:`retainable object pointer` (or "retainable pointer") is a value of238a :arc-term:`retainable object pointer type` ("retainable type"). There are239three kinds of retainable object pointer types:240 241* block pointers (formed by applying the caret (``^``) declarator sigil to a242 function type)243* Objective-C object pointers (``id``, ``Class``, ``NSFoo*``, etc.)244* typedefs marked with ``__attribute__((NSObject))``245 246Other pointer types, such as ``int*`` and ``CFStringRef``, are not subject to247ARC's semantics and restrictions.248 249.. admonition:: Rationale250 251 We are not at liberty to require all code to be recompiled with ARC;252 therefore, ARC must interoperate with Objective-C code which manages retains253 and releases manually. In general, there are three requirements in order for254 a compiler-supported reference-count system to provide reliable255 interoperation:256 257 * The type system must reliably identify which objects are to be managed. An258 ``int*`` might be a pointer to a ``malloc``'ed array, or it might be an259 interior pointer to such an array, or it might point to some field or local260 variable. In contrast, values of the retainable object pointer types are261 never interior.262 263 * The type system must reliably indicate how to manage objects of a type.264 This usually means that the type must imply a procedure for incrementing265 and decrementing retain counts. Supporting single-ownership objects266 requires a lot more explicit mediation in the language.267 268 * There must be reliable conventions for whether and when "ownership" is269 passed between caller and callee, for both arguments and return values.270 Objective-C methods follow such a convention very reliably, at least for271 system libraries on macOS, and functions always pass objects at +0. The272 C-based APIs for Core Foundation objects, on the other hand, have much more273 varied transfer semantics.274 275The use of ``__attribute__((NSObject))`` typedefs is not recommended. If it's276absolutely necessary to use this attribute, be very explicit about using the277typedef, and do not assume that it will be preserved by language features like278``__typeof`` and C++ template argument substitution.279 280.. admonition:: Rationale281 282 Any compiler operation which incidentally strips type "sugar" from a type283 will yield a type without the attribute, which may result in unexpected284 behavior.285 286.. _arc.objects.retains:287 288Retain count semantics289----------------------290 291A retainable object pointer is either a :arc-term:`null pointer` or a pointer292to a valid object. Furthermore, if it has block pointer type and is not293``null`` then it must actually be a pointer to a block object, and if it has294``Class`` type (possibly protocol-qualified) then it must actually be a pointer295to a class object. Otherwise ARC does not enforce the Objective-C type system296as long as the implementing methods follow the signature of the static type.297It is undefined behavior if ARC is exposed to an invalid pointer.298 299For ARC's purposes, a valid object is one with "well-behaved" retaining300operations. Specifically, the object must be laid out such that the301Objective-C message send machinery can successfully send it the following302messages:303 304* ``retain``, taking no arguments and returning a pointer to the object.305* ``release``, taking no arguments and returning ``void``.306* ``autorelease``, taking no arguments and returning a pointer to the object.307 308The behavior of these methods is constrained in the following ways. The term309:arc-term:`high-level semantics` is an intentionally vague term; the intent is310that programmers must implement these methods in a way such that the compiler,311modifying code in ways it deems safe according to these constraints, will not312violate their requirements. For example, if the user puts logging statements313in ``retain``, they should not be surprised if those statements are executed314more or less often depending on optimization settings. These constraints are315not exhaustive of the optimization opportunities: values held in local316variables are subject to additional restrictions, described later in this317document.318 319It is undefined behavior if a computation history featuring a send of320``retain`` followed by a send of ``release`` to the same object, with no321intervening ``release`` on that object, is not equivalent under the high-level322semantics to a computation history in which these sends are removed. Note that323this implies that these methods may not raise exceptions.324 325It is undefined behavior if a computation history features any use whatsoever326of an object following the completion of a send of ``release`` that is not327preceded by a send of ``retain`` to the same object.328 329The behavior of ``autorelease`` must be equivalent to sending ``release`` when330one of the autorelease pools currently in scope is popped. It may not throw an331exception.332 333When the semantics call for performing one of these operations on a retainable334object pointer, if that pointer is ``null`` then the effect is a no-op.335 336All of the semantics described in this document are subject to additional337:ref:`optimization rules <arc.optimization>` which permit the removal or338optimization of operations based on local knowledge of data flow. The339semantics describe the high-level behaviors that the compiler implements, not340an exact sequence of operations that a program will be compiled into.341 342.. _arc.objects.operands:343 344Retainable object pointers as operands and arguments345----------------------------------------------------346 347In general, ARC does not perform retain or release operations when simply using348a retainable object pointer as an operand within an expression. This includes:349 350* loading a retainable pointer from an object with non-weak :ref:`ownership351 <arc.ownership>`,352* passing a retainable pointer as an argument to a function or method, and353* receiving a retainable pointer as the result of a function or method call.354 355.. admonition:: Rationale356 357 While this might seem uncontroversial, it is actually unsafe when multiple358 expressions are evaluated in "parallel", as with binary operators and calls,359 because (for example) one expression might load from an object while another360 writes to it. However, C and C++ already call this undefined behavior361 because the evaluations are unsequenced, and ARC simply exploits that here to362 avoid needing to retain arguments across a large number of calls.363 364The remainder of this section describes exceptions to these rules, how those365exceptions are detected, and what those exceptions imply semantically.366 367.. _arc.objects.operands.consumed:368 369Consumed parameters370^^^^^^^^^^^^^^^^^^^371 372A function or method parameter of retainable object pointer type may be marked373as :arc-term:`consumed`, signifying that the callee expects to take ownership374of a +1 retain count. This is done by adding the ``ns_consumed`` attribute to375the parameter declaration, like so:376 377.. code-block:: objc378 379 void foo(__attribute((ns_consumed)) id x);380 - (void) foo: (id) __attribute((ns_consumed)) x;381 382This attribute is part of the type of the function or method, not the type of383the parameter. It controls only how the argument is passed and received.384 385When passing such an argument, ARC retains the argument prior to making the386call.387 388When receiving such an argument, ARC releases the argument at the end of the389function, subject to the usual optimizations for local values.390 391.. admonition:: Rationale392 393 This formalizes direct transfers of ownership from a caller to a callee. The394 most common scenario here is passing the ``self`` parameter to ``init``, but395 it is useful to generalize. Typically, local optimization will remove any396 extra retains and releases: on the caller side the retain will be merged with397 a +1 source, and on the callee side the release will be rolled into the398 initialization of the parameter.399 400The implicit ``self`` parameter of a method may be marked as consumed by adding401``__attribute__((ns_consumes_self))`` to the method declaration. Methods in402the ``init`` :ref:`family <arc.method-families>` are treated as if they were403implicitly marked with this attribute.404 405It is undefined behavior if an Objective-C message send to a method with406``ns_consumed`` parameters (other than self) is made with a null receiver. It407is undefined behavior if the method to which an Objective-C message send408statically resolves to has a different set of ``ns_consumed`` parameters than409the method it dynamically resolves to. It is undefined behavior if a block or410function call is made through a static type with a different set of411``ns_consumed`` parameters than the implementation of the called block or412function.413 414.. admonition:: Rationale415 416 Consumed parameters with null receiver are a guaranteed leak. Mismatches417 with consumed parameters will cause over-retains or over-releases, depending418 on the direction. The rule about function calls is really just an419 application of the existing C/C++ rule about calling functions through an420 incompatible function type, but it's useful to state it explicitly.421 422.. _arc.object.operands.retained-return-values:423 424Retained return values425^^^^^^^^^^^^^^^^^^^^^^426 427A function or method which returns a retainable object pointer type may be428marked as returning a retained value, signifying that the caller expects to take429ownership of a +1 retain count. This is done by adding the430``ns_returns_retained`` attribute to the function or method declaration, like431so:432 433.. code-block:: objc434 435 id foo(void) __attribute((ns_returns_retained));436 - (id) foo __attribute((ns_returns_retained));437 438This attribute is part of the type of the function or method.439 440When returning from such a function or method, ARC retains the value at the441point of evaluation of the return statement, before leaving all local scopes.442 443When receiving a return result from such a function or method, ARC releases the444value at the end of the full-expression it is contained within, subject to the445usual optimizations for local values.446 447.. admonition:: Rationale448 449 This formalizes direct transfers of ownership from a callee to a caller. The450 most common scenario this models is the retained return from ``init``,451 ``alloc``, ``new``, and ``copy`` methods, but there are other cases in the452 frameworks. After optimization there are typically no extra retains and453 releases required.454 455Methods in the ``alloc``, ``copy``, ``init``, ``mutableCopy``, and ``new``456:ref:`families <arc.method-families>` are implicitly marked457``__attribute__((ns_returns_retained))``. This may be suppressed by explicitly458marking the method ``__attribute__((ns_returns_not_retained))``.459 460It is undefined behavior if the method to which an Objective-C message send461statically resolves has different retain semantics on its result from the462method it dynamically resolves to. It is undefined behavior if a block or463function call is made through a static type with different retain semantics on464its result from the implementation of the called block or function.465 466.. admonition:: Rationale467 468 Mismatches with returned results will cause over-retains or over-releases,469 depending on the direction. Again, the rule about function calls is really470 just an application of the existing C/C++ rule about calling functions471 through an incompatible function type.472 473.. _arc.objects.operands.unretained-returns:474 475Unretained return values476^^^^^^^^^^^^^^^^^^^^^^^^477 478A method or function which returns a retainable object type but does not return479a retained value must ensure that the object is still valid across the return480boundary.481 482When returning from such a function or method, ARC retains the value at the483point of evaluation of the return statement, then leaves all local scopes, and484then balances out the retain while ensuring that the value lives across the485call boundary. In the worst case, this may involve an ``autorelease``, but486callers must not assume that the value is actually in the autorelease pool.487 488ARC performs no extra mandatory work on the caller side, although it may elect489to do something to shorten the lifetime of the returned value.490 491.. admonition:: Rationale492 493 It is common in non-ARC code to not return an autoreleased value; therefore494 the convention does not force either path. It is convenient to not be495 required to do unnecessary retains and autoreleases; this permits496 optimizations such as eliding retain/autoreleases when it can be shown that497 the original pointer will still be valid at the point of return.498 499A method or function may be marked with500``__attribute__((ns_returns_autoreleased))`` to indicate that it returns a501pointer which is guaranteed to be valid at least as long as the innermost502autorelease pool. There are no additional semantics enforced in the definition503of such a method; it merely enables optimizations in callers.504 505.. _arc.objects.operands.casts:506 507Bridged casts508^^^^^^^^^^^^^509 510A :arc-term:`bridged cast` is a C-style cast annotated with one of three511keywords:512 513* ``(__bridge T) op`` casts the operand to the destination type ``T``. If514 ``T`` is a retainable object pointer type, then ``op`` must have a515 non-retainable pointer type. If ``T`` is a non-retainable pointer type,516 then ``op`` must have a retainable object pointer type. Otherwise the cast517 is ill-formed. There is no transfer of ownership, and ARC inserts no retain518 operations.519* ``(__bridge_retained T) op`` casts the operand, which must have retainable520 object pointer type, to the destination type, which must be a non-retainable521 pointer type. ARC retains the value, subject to the usual optimizations on522 local values, and the recipient is responsible for balancing that +1.523* ``(__bridge_transfer T) op`` casts the operand, which must have524 non-retainable pointer type, to the destination type, which must be a525 retainable object pointer type. ARC will release the value at the end of526 the enclosing full-expression, subject to the usual optimizations on local527 values.528 529These casts are required in order to transfer objects in and out of ARC530control; see the rationale in the section on :ref:`conversion of retainable531object pointers <arc.objects.restrictions.conversion>`.532 533Using a ``__bridge_retained`` or ``__bridge_transfer`` cast purely to convince534ARC to emit an unbalanced retain or release, respectively, is poor form.535 536.. _arc.objects.restrictions:537 538Restrictions539------------540 541.. _arc.objects.restrictions.conversion:542 543Conversion of retainable object pointers544^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^545 546In general, a program which attempts to implicitly or explicitly convert a547value of retainable object pointer type to any non-retainable type, or548vice-versa, is ill-formed. For example, an Objective-C object pointer shall549not be converted to ``void*``. As an exception, cast to ``intptr_t`` is550allowed because such casts are not transferring ownership. The :ref:`bridged551casts <arc.objects.operands.casts>` may be used to perform these conversions552where necessary.553 554.. admonition:: Rationale555 556 We cannot ensure the correct management of the lifetime of objects if they557 may be freely passed around as unmanaged types. The bridged casts are558 provided so that the programmer may explicitly describe whether the cast559 transfers control into or out of ARC.560 561However, the following exceptions apply.562 563.. _arc.objects.restrictions.conversion.with.known.semantics:564 565Conversion to retainable object pointer type of expressions with known semantics566^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^567 568:when-revised:`[beginning Apple 4.0, LLVM 3.1]`569:revision:`These exceptions have been greatly expanded; they previously applied570only to a much-reduced subset which is difficult to categorize but which571included null pointers, message sends (under the given rules), and the various572global constants.`573 574An unbridged conversion to a retainable object pointer type from a type other575than a retainable object pointer type is ill-formed, as discussed above, unless576the operand of the cast has a syntactic form which is known retained, known577unretained, or known retain-agnostic.578 579An expression is :arc-term:`known retain-agnostic` if it is:580 581* an Objective-C string literal,582* a load from a ``const`` system global variable of :ref:`C retainable pointer583 type <arc.misc.c-retainable>`, or584* a null pointer constant.585 586An expression is :arc-term:`known unretained` if it is an rvalue of :ref:`C587retainable pointer type <arc.misc.c-retainable>` and it is:588 589* a direct call to a function, and either that function has the590 ``cf_returns_not_retained`` attribute or it is an :ref:`audited591 <arc.misc.c-retainable.audit>` function that does not have the592 ``cf_returns_retained`` attribute and does not follow the create/copy naming593 convention,594* a message send, and the declared method either has the595 ``cf_returns_not_retained`` attribute or it has neither the596 ``cf_returns_retained`` attribute nor a :ref:`selector family597 <arc.method-families>` that implies a retained result, or598* :when-revised:`[beginning LLVM 3.6]` :revision:`a load from a` ``const``599 :revision:`non-system global variable.`600 601An expression is :arc-term:`known retained` if it is an rvalue of :ref:`C602retainable pointer type <arc.misc.c-retainable>` and it is:603 604* a message send, and the declared method either has the605 ``cf_returns_retained`` attribute, or it does not have the606 ``cf_returns_not_retained`` attribute but it does have a :ref:`selector607 family <arc.method-families>` that implies a retained result.608 609Furthermore:610 611* a comma expression is classified according to its right-hand side,612* a statement expression is classified according to its result expression, if613 it has one,614* an lvalue-to-rvalue conversion applied to an Objective-C property lvalue is615 classified according to the underlying message send, and616* a conditional operator is classified according to its second and third617 operands, if they agree in classification, or else the other if one is known618 retain-agnostic.619 620If the cast operand is known retained, the conversion is treated as a621``__bridge_transfer`` cast. If the cast operand is known unretained or known622retain-agnostic, the conversion is treated as a ``__bridge`` cast.623 624.. admonition:: Rationale625 626 Bridging casts are annoying. Absent the ability to completely automate the627 management of CF objects, however, we are left with relatively poor attempts628 to reduce the need for a glut of explicit bridges. Hence these rules.629 630 We've so far consciously refrained from implicitly turning retained CF631 results from function calls into ``__bridge_transfer`` casts. The worry is632 that some code patterns --- for example, creating a CF value, assigning it633 to an ObjC-typed local, and then calling ``CFRelease`` when done --- are a634 bit too likely to be accidentally accepted, leading to mysterious behavior.635 636 For loads from ``const`` global variables of :ref:`C retainable pointer type637 <arc.misc.c-retainable>`, it is reasonable to assume that global system638 constants were initialized with true constants (e.g. string literals), but639 user constants might have been initialized with something dynamically640 allocated, using a global initializer.641 642.. _arc.objects.restrictions.conversion-exception-contextual:643 644Conversion from retainable object pointer type in certain contexts645^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^646 647:when-revised:`[beginning Apple 4.0, LLVM 3.1]`648 649If an expression of retainable object pointer type is explicitly cast to a650:ref:`C retainable pointer type <arc.misc.c-retainable>`, the program is651ill-formed as discussed above unless the result is immediately used:652 653* to initialize a parameter in an Objective-C message send where the parameter654 is not marked with the ``cf_consumed`` attribute, or655* to initialize a parameter in a direct call to an656 :ref:`audited <arc.misc.c-retainable.audit>` function where the parameter is657 not marked with the ``cf_consumed`` attribute.658 659.. admonition:: Rationale660 661 Consumed parameters are left out because ARC would naturally balance them662 with a retain, which was judged too treacherous. This is in part because663 several of the most common consuming functions are in the ``Release`` family,664 and it would be quite unfortunate for explicit releases to be silently665 balanced out in this way.666 667.. _arc.ownership:668 669Ownership qualification670=======================671 672This section describes the behavior of *objects* of retainable object pointer673type; that is, locations in memory which store retainable object pointers.674 675A type is a :arc-term:`retainable object owner type` if it is a retainable676object pointer type or an array type whose element type is a retainable object677owner type.678 679An :arc-term:`ownership qualifier` is a type qualifier which applies only to680retainable object owner types. An array type is ownership-qualified according681to its element type, and adding an ownership qualifier to an array type so682qualifies its element type.683 684A program is ill-formed if it attempts to apply an ownership qualifier to a685type which is already ownership-qualified, even if it is the same qualifier.686There is a single exception to this rule: an ownership qualifier may be applied687to a substituted template type parameter, which overrides the ownership688qualifier provided by the template argument.689 690When forming a function type, the result type is adjusted so that any691top-level ownership qualifier is deleted.692 693Except as described under the :ref:`inference rules <arc.ownership.inference>`,694a program is ill-formed if it attempts to form a pointer or reference type to a695retainable object owner type which lacks an ownership qualifier.696 697.. admonition:: Rationale698 699 These rules, together with the inference rules, ensure that all objects and700 lvalues of retainable object pointer type have an ownership qualifier. The701 ability to override an ownership qualifier during template substitution is702 required to counteract the :ref:`inference of __strong for template type703 arguments <arc.ownership.inference.template.arguments>`. Ownership qualifiers704 on return types are dropped because they serve no purpose there except to705 cause spurious problems with overloading and templates.706 707There are four ownership qualifiers:708 709* ``__autoreleasing``710* ``__strong``711* ``__unsafe_unretained``712* ``__weak``713 714A type is :arc-term:`nontrivially ownership-qualified` if it is qualified with715``__autoreleasing``, ``__strong``, or ``__weak``.716 717.. _arc.ownership.spelling:718 719Spelling720--------721 722The names of the ownership qualifiers are reserved for the implementation. A723program may not assume that they are or are not implemented with macros, or724what those macros expand to.725 726An ownership qualifier may be written anywhere that any other type qualifier727may be written.728 729If an ownership qualifier appears in the *declaration-specifiers*, the730following rules apply:731 732* if the type specifier is a retainable object owner type, the qualifier733 initially applies to that type;734 735* otherwise, if the outermost non-array declarator is a pointer736 or block pointer declarator, the qualifier initially applies to737 that type;738 739* otherwise the program is ill-formed.740 741* If the qualifier is so applied at a position in the declaration742 where the next-innermost declarator is a function declarator, and743 there is a block declarator within that function declarator, then744 the qualifier applies instead to that block declarator and this rule745 is considered afresh beginning from the new position.746 747If an ownership qualifier appears on the declarator name, or on the declared748object, it is applied to the innermost pointer or block-pointer type.749 750If an ownership qualifier appears anywhere else in a declarator, it applies to751the type there.752 753.. admonition:: Rationale754 755 Ownership qualifiers are like ``const`` and ``volatile`` in the sense756 that they may sensibly apply at multiple distinct positions within a757 declarator. However, unlike those qualifiers, there are many758 situations where they are not meaningful, and so we make an effort759 to "move" the qualifier to a place where it will be meaningful. The760 general goal is to allow the programmer to write, say, ``__strong``761 before the entire declaration and have it apply in the leftmost762 sensible place.763 764.. _arc.ownership.spelling.property:765 766Property declarations767^^^^^^^^^^^^^^^^^^^^^768 769A property of retainable object pointer type may have ownership. If the770property's type is ownership-qualified, then the property has that ownership.771If the property has one of the following modifiers, then the property has the772corresponding ownership. A property is ill-formed if it has conflicting773sources of ownership, or if it has redundant ownership modifiers, or if it has774``__autoreleasing`` ownership.775 776* ``assign`` implies ``__unsafe_unretained`` ownership.777* ``copy`` implies ``__strong`` ownership, as well as the usual behavior of778 copy semantics on the setter.779* ``retain`` implies ``__strong`` ownership.780* ``strong`` implies ``__strong`` ownership.781* ``unsafe_unretained`` implies ``__unsafe_unretained`` ownership.782* ``weak`` implies ``__weak`` ownership.783 784With the exception of ``weak``, these modifiers are available in non-ARC785modes.786 787A property's specified ownership is preserved in its metadata, but otherwise788the meaning is purely conventional unless the property is synthesized. If a789property is synthesized, then the :arc-term:`associated instance variable` is790the instance variable which is named, possibly implicitly, by the791``@synthesize`` declaration. If the associated instance variable already792exists, then its ownership qualification must equal the ownership of the793property; otherwise, the instance variable is created with that ownership794qualification.795 796A property of retainable object pointer type which is synthesized without a797source of ownership has the ownership of its associated instance variable, if it798already exists; otherwise, :when-revised:`[beginning Apple 3.1, LLVM 3.1]`799:revision:`its ownership is implicitly` ``strong``. Prior to this revision, it800was ill-formed to synthesize such a property.801 802.. admonition:: Rationale803 804 Using ``strong`` by default is safe and consistent with the generic ARC rule805 about :ref:`inferring ownership <arc.ownership.inference.variables>`. It is,806 unfortunately, inconsistent with the non-ARC rule which states that such807 properties are implicitly ``assign``. However, that rule is clearly808 untenable in ARC, since it leads to default-unsafe code. The main merit to809 banning the properties is to avoid confusion with non-ARC practice, which did810 not ultimately strike us as sufficient to justify requiring extra syntax and811 (more importantly) forcing novices to understand ownership rules just to812 declare a property when the default is so reasonable. Changing the rule away813 from non-ARC practice was acceptable because we had conservatively banned the814 synthesis in order to give ourselves exactly this leeway.815 816Applying ``__attribute__((NSObject))`` to a property not of retainable object817pointer type has the same behavior it does outside of ARC: it requires the818property type to be some sort of pointer and permits the use of modifiers other819than ``assign``. These modifiers only affect the synthesized getter and820setter; direct accesses to the ivar (even if synthesized) still have primitive821semantics, and the value in the ivar will not be automatically released during822deallocation.823 824.. _arc.ownership.semantics:825 826Semantics827---------828 829There are five :arc-term:`managed operations` which may be performed on an830object of retainable object pointer type. Each qualifier specifies different831semantics for each of these operations. It is still undefined behavior to832access an object outside of its lifetime.833 834A load or store with "primitive semantics" has the same semantics as the835respective operation would have on an ``void*`` lvalue with the same alignment836and non-ownership qualification.837 838:arc-term:`Reading` occurs when performing a lvalue-to-rvalue conversion on an839object lvalue.840 841* For ``__weak`` objects, the current pointee is retained and then released at842 the end of the current full-expression. In particular, messaging a ``__weak``843 object keeps the object retained until the end of the full expression.844 845 .. code-block:: objc846 847 __weak MyObject *weakObj;848 849 void foo() {850 // weakObj is retained before the message send and released at the end of851 // the full expression.852 [weakObj m];853 }854 855 This must execute atomically with respect to assignments and to the final856 release of the pointee.857* For all other objects, the lvalue is loaded with primitive semantics.858 859:arc-term:`Assignment` occurs when evaluating an assignment operator. The860semantics vary based on the qualification:861 862* For ``__strong`` objects, the new pointee is first retained; second, the863 lvalue is loaded with primitive semantics; third, the new pointee is stored864 into the lvalue with primitive semantics; and finally, the old pointee is865 released. This is not performed atomically; external synchronization must be866 used to make this safe in the face of concurrent loads and stores.867* For ``__weak`` objects, the lvalue is updated to point to the new pointee,868 unless the new pointee is an object currently undergoing deallocation, in869 which case the lvalue is updated to a null pointer. This must execute870 atomically with respect to other assignments to the object, to reads from the871 object, and to the final release of the new pointee.872* For ``__unsafe_unretained`` objects, the new pointee is stored into the873 lvalue using primitive semantics.874* For ``__autoreleasing`` objects, the new pointee is retained, autoreleased,875 and stored into the lvalue using primitive semantics.876 877:arc-term:`Initialization` occurs when an object's lifetime begins, which878depends on its storage duration. Initialization proceeds in two stages:879 880#. First, a null pointer is stored into the lvalue using primitive semantics.881 This step is skipped if the object is ``__unsafe_unretained``.882#. Second, if the object has an initializer, that expression is evaluated and883 then assigned into the object using the usual assignment semantics.884 885:arc-term:`Destruction` occurs when an object's lifetime ends. In all cases it886is semantically equivalent to assigning a null pointer to the object, with the887proviso that of course the object cannot be legally read after the object's888lifetime ends.889 890:arc-term:`Moving` occurs in specific situations where an lvalue is "moved891from", meaning that its current pointee will be used but the object may be left892in a different (but still valid) state. This arises with ``__block`` variables893and rvalue references in C++. For ``__strong`` lvalues, moving is equivalent894to loading the lvalue with primitive semantics, writing a null pointer to it895with primitive semantics, and then releasing the result of the load at the end896of the current full-expression. For all other lvalues, moving is equivalent to897reading the object.898 899.. _arc.ownership.restrictions:900 901Restrictions902------------903 904.. _arc.ownership.restrictions.weak:905 906Weak-unavailable types907^^^^^^^^^^^^^^^^^^^^^^908 909It is explicitly permitted for Objective-C classes to not support ``__weak``910references. It is undefined behavior to perform an operation with weak911assignment semantics with a pointer to an Objective-C object whose class does912not support ``__weak`` references.913 914.. admonition:: Rationale915 916 Historically, it has been possible for a class to provide its own917 reference-count implementation by overriding ``retain``, ``release``, etc.918 However, weak references to an object require coordination with its class's919 reference-count implementation because, among other things, weak loads and920 stores must be atomic with respect to the final release. Therefore, existing921 custom reference-count implementations will generally not support weak922 references without additional effort. This is unavoidable without breaking923 binary compatibility.924 925A class may indicate that it does not support weak references by providing the926``objc_arc_weak_reference_unavailable`` attribute on the class's interface declaration. A927retainable object pointer type is **weak-unavailable** if it928is a pointer to an (optionally protocol-qualified) Objective-C class ``T`` where929``T`` or one of its superclasses has the ``objc_arc_weak_reference_unavailable``930attribute. A program is ill-formed if it applies the ``__weak`` ownership931qualifier to a weak-unavailable type or if the value operand of a weak932assignment operation has a weak-unavailable type.933 934.. _arc.ownership.restrictions.autoreleasing:935 936Storage duration of ``__autoreleasing`` objects937^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^938 939A program is ill-formed if it declares an ``__autoreleasing`` object of940non-automatic storage duration. A program is ill-formed if it captures an941``__autoreleasing`` object in a block or, unless by reference, in a C++11942lambda.943 944.. admonition:: Rationale945 946 Autorelease pools are tied to the current thread and scope by their nature.947 While it is possible to have temporary objects whose instance variables are948 filled with autoreleased objects, there is no way that ARC can provide any949 sort of safety guarantee there.950 951It is undefined behavior if a non-null pointer is assigned to an952``__autoreleasing`` object while an autorelease pool is in scope and then that953object is read after the autorelease pool's scope is left.954 955.. _arc.ownership.restrictions.conversion.indirect:956 957Conversion of pointers to ownership-qualified types958^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^959 960A program is ill-formed if an expression of type ``T*`` is converted,961explicitly or implicitly, to the type ``U*``, where ``T`` and ``U`` have962different ownership qualification, unless:963 964* ``T`` is qualified with ``__strong``, ``__autoreleasing``, or965 ``__unsafe_unretained``, and ``U`` is qualified with both ``const`` and966 ``__unsafe_unretained``; or967* either ``T`` or ``U`` is ``cv void``, where ``cv`` is an optional sequence968 of non-ownership qualifiers; or969* the conversion is requested with a ``reinterpret_cast`` in Objective-C++; or970* the conversion is a well-formed :ref:`pass-by-writeback971 <arc.ownership.restrictions.pass_by_writeback>`.972 973The analogous rule applies to ``T&`` and ``U&`` in Objective-C++.974 975.. admonition:: Rationale976 977 These rules provide a reasonable level of type-safety for indirect pointers,978 as long as the underlying memory is not deallocated. The conversion to979 ``const __unsafe_unretained`` is permitted because the semantics of reads are980 equivalent across all these ownership semantics, and that's a very useful and981 common pattern. The interconversion with ``void*`` is useful for allocating982 memory or otherwise escaping the type system, but use it carefully.983 ``reinterpret_cast`` is considered to be an obvious enough sign of taking984 responsibility for any problems.985 986It is undefined behavior to access an ownership-qualified object through an987lvalue of a differently-qualified type, except that any non-``__weak`` object988may be read through an ``__unsafe_unretained`` lvalue.989 990It is undefined behavior if the storage of a ``__strong`` or ``__weak``991object is not properly initialized before the first managed operation992is performed on the object, or if the storage of such an object is freed993or reused before the object has been properly deinitialized. Storage for994a ``__strong`` or ``__weak`` object may be properly initialized by filling995it with the representation of a null pointer, e.g. by acquiring the memory996with ``calloc`` or using ``bzero`` to zero it out. A ``__strong`` or997``__weak`` object may be properly deinitialized by assigning a null pointer998into it. A ``__strong`` object may also be properly initialized999by copying into it (e.g. with ``memcpy``) the representation of a1000different ``__strong`` object whose storage has been properly initialized;1001doing this properly deinitializes the source object and causes its storage1002to no longer be properly initialized. A ``__weak`` object may not be1003representation-copied in this way.1004 1005These requirements are followed automatically for objects whose1006initialization and deinitialization are under the control of ARC:1007 1008* objects of static, automatic, and temporary storage duration1009* instance variables of Objective-C objects1010* elements of arrays where the array object's initialization and1011 deinitialization are under the control of ARC1012* fields of Objective-C struct types where the struct object's1013 initialization and deinitialization are under the control of ARC1014* non-static data members of Objective-C++ non-union class types1015* Objective-C++ objects and arrays of dynamic storage duration created1016 with the ``new`` or ``new[]`` operators and destroyed with the1017 corresponding ``delete`` or ``delete[]`` operator1018 1019They are not followed automatically for these objects:1020 1021* objects of dynamic storage duration created in other memory, such as1022 that returned by ``malloc``1023* union members1024 1025.. admonition:: Rationale1026 1027 ARC must perform special operations when initializing an object and1028 when destroying it. In many common situations, ARC knows when an1029 object is created and when it is destroyed and can ensure that these1030 operations are performed correctly. Otherwise, however, ARC requires1031 programmer cooperation to establish its initialization invariants1032 because it is infeasible for ARC to dynamically infer whether they1033 are intact. For example, there is no syntactic difference in C between1034 an assignment that is intended by the programmer to initialize a variable1035 and one that is intended to replace the existing value stored there,1036 but ARC must perform one operation or the other. ARC chooses to always1037 assume that objects are initialized (except when it is in charge of1038 initializing them) because the only workable alternative would be to1039 ban all code patterns that could potentially be used to access1040 uninitialized memory, and that would be too limiting. In practice,1041 this is rarely a problem because programmers do not generally need to1042 work with objects for which the requirements are not handled1043 automatically.1044 1045Note that dynamically-allocated Objective-C++ arrays of1046nontrivially-ownership-qualified type are not ABI-compatible with non-ARC1047code because the non-ARC code will consider the element type to be POD.1048Such arrays that are ``new[]``'d in ARC translation units cannot be1049``delete[]``'d in non-ARC translation units and vice-versa.1050 1051.. _arc.ownership.restrictions.pass_by_writeback:1052 1053Passing to an out parameter by writeback1054^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1055 1056If the argument passed to a parameter of type ``T __autoreleasing *`` has type1057``U oq *``, where ``oq`` is an ownership qualifier, then the argument is a1058candidate for :arc-term:`pass-by-writeback`` if:1059 1060* ``oq`` is ``__strong`` or ``__weak``, and1061* it would be legal to initialize a ``T __strong *`` with a ``U __strong *``.1062 1063For purposes of overload resolution, an implicit conversion sequence requiring1064a pass-by-writeback is always worse than an implicit conversion sequence not1065requiring a pass-by-writeback.1066 1067The pass-by-writeback is ill-formed if the argument expression does not have a1068legal form:1069 1070* ``&var``, where ``var`` is a scalar variable of automatic storage duration1071 with retainable object pointer type1072* a conditional expression where the second and third operands are both legal1073 forms1074* a cast whose operand is a legal form1075* a null pointer constant1076 1077.. admonition:: Rationale1078 1079 The restriction in the form of the argument serves two purposes. First, it1080 makes it impossible to pass the address of an array to the argument, which1081 serves to protect against an otherwise serious risk of mis-inferring an1082 "array" argument as an out-parameter. Second, it makes it much less likely1083 that the user will see confusing aliasing problems due to the implementation,1084 below, where their store to the writeback temporary is not immediately seen1085 in the original argument variable.1086 1087A pass-by-writeback is evaluated as follows:1088 1089#. The argument is evaluated to yield a pointer ``p`` of type ``U oq *``.1090#. If ``p`` is a null pointer, then a null pointer is passed as the argument,1091 and no further work is required for the pass-by-writeback.1092#. Otherwise, a temporary of type ``T __autoreleasing`` is created and1093 initialized to a null pointer.1094#. If the parameter is not an Objective-C method parameter marked ``out``,1095 then ``*p`` is read, and the result is written into the temporary with1096 primitive semantics.1097#. The address of the temporary is passed as the argument to the actual call.1098#. After the call completes, the temporary is loaded with primitive1099 semantics, and that value is assigned into ``*p``.1100 1101.. admonition:: Rationale1102 1103 This is all admittedly convoluted. In an ideal world, we would see that a1104 local variable is being passed to an out-parameter and retroactively modify1105 its type to be ``__autoreleasing`` rather than ``__strong``. This would be1106 remarkably difficult and not always well-founded under the C type system.1107 However, it was judged unacceptably invasive to require programmers to write1108 ``__autoreleasing`` on all the variables they intend to use for1109 out-parameters. This was the least bad solution.1110 1111.. _arc.ownership.restrictions.records:1112 1113Ownership-qualified fields of structs and unions1114^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1115 1116A member of a struct or union may be declared to have ownership-qualified1117type. If the type is qualified with ``__unsafe_unretained``, the semantics1118of the containing aggregate are unchanged from the semantics of an unqualified type in a non-ARC mode. If the type is qualified with ``__autoreleasing``, the program is ill-formed. Otherwise, if the type is nontrivially ownership-qualified, additional rules apply.1119 1120Both Objective-C and Objective-C++ support nontrivially ownership-qualified1121fields. Due to formal differences between the standards, the formal1122treatment is different; however, the basic language model is intended to1123be the same for identical code.1124 1125.. admonition:: Rationale1126 1127 Permitting ``__strong`` and ``__weak`` references in aggregate types1128 allows programmers to take advantage of the normal language tools of1129 C and C++ while still automatically managing memory. While it is1130 usually simpler and more idiomatic to use Objective-C objects for1131 secondary data structures, doing so can introduce extra allocation1132 and message-send overhead, which can cause unacceptable1133 performance. Using structs can resolve some of this tension.1134 1135 ``__autoreleasing`` is forbidden because it is treacherous to rely1136 on autoreleases as an ownership tool outside of a function-local1137 contexts.1138 1139 Earlier releases of Clang permitted ``__strong`` and ``__weak`` only1140 references in Objective-C++ classes, not in Objective-C. This1141 restriction was an undesirable short-term constraint arising from the1142 complexity of adding support for non-trivial struct types to C.1143 1144In Objective-C++, nontrivially ownership-qualified types are treated1145for nearly all purposes as if they were class types with non-trivial1146default constructors, copy constructors, move constructors, copy assignment1147operators, move assignment operators, and destructors. This includes the1148determination of the triviality of special members of classes with a1149non-static data member of such a type.1150 1151In Objective-C, the definition cannot be so succinct: because the C1152standard lacks rules for non-trivial types, those rules must first be1153developed. They are given in the next section. The intent is that these1154rules are largely consistent with the rules of C++ for code expressible1155in both languages.1156 1157Formal rules for non-trivial types in C1158~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~1159 1160The following are base rules which can be added to C to support1161implementation-defined non-trivial types.1162 1163A type in C is said to be *non-trivial to copy*, *non-trivial to destroy*,1164or *non-trivial to default-initialize* if:1165 1166- it is a struct or union containing a member whose type is non-trivial1167 to (respectively) copy, destroy, or default-initialize;1168 1169- it is a qualified type whose unqualified type is non-trivial to1170 (respectively) copy, destroy, or default-initialize (for at least1171 the standard C qualifiers); or1172 1173- it is an array type whose element type is non-trivial to (respectively)1174 copy, destroy, or default-initialize.1175 1176A type in C is said to be *illegal to copy*, *illegal to destroy*, or1177*illegal to default-initialize* if:1178 1179- it is a union which contains a member whose type is either illegal1180 or non-trivial to (respectively) copy, destroy, or initialize;1181 1182- it is a qualified type whose unqualified type is illegal to1183 (respectively) copy, destroy, or default-initialize (for at least1184 the standard C qualifiers); or1185 1186- it is an array type whose element type is illegal to (respectively)1187 copy, destroy, or default-initialize.1188 1189No type describable under the rules of the C standard shall be either1190non-trivial or illegal to copy, destroy, or default-initialize.1191An implementation may provide additional types which have one or more1192of these properties.1193 1194An expression calls for a type to be copied if it:1195 1196- passes an argument of that type to a function call,1197- defines a function which declares a parameter of that type,1198- calls or defines a function which returns a value of that type,1199- assigns to an l-value of that type, or1200- converts an l-value of that type to an r-value.1201 1202A program calls for a type to be destroyed if it:1203 1204- passes an argument of that type to a function call,1205- defines a function which declares a parameter of that type,1206- calls or defines a function which returns a value of that type,1207- creates an object of automatic storage duration of that type,1208- assigns to an l-value of that type, or1209- converts an l-value of that type to an r-value.1210 1211A program calls for a type to be default-initialized if it:1212 1213- declares a variable of that type without an initializer.1214 1215An expression is ill-formed if calls for a type to be copied,1216destroyed, or default-initialized and that type is illegal to1217(respectively) copy, destroy, or default-initialize.1218 1219A program is ill-formed if it contains a function type specifier1220with a parameter or return type that is illegal to copy or1221destroy. If a function type specifier would be ill-formed for this1222reason except that the parameter or return type was incomplete at1223that point in the translation unit, the program is ill-formed but1224no diagnostic is required.1225 1226A ``goto`` or ``switch`` is ill-formed if it jumps into the scope of1227an object of automatic storage duration whose type is non-trivial to1228destroy.1229 1230C specifies that it is generally undefined behavior to access an l-value1231if there is no object of that type at that location. Implementations1232are often lenient about this, but non-trivial types generally require1233it to be enforced more strictly. The following rules apply:1234 1235The *static subobjects* of a type ``T`` at a location ``L`` are:1236 1237 - an object of type ``T`` spanning from ``L`` to ``L + sizeof(T)``;1238 1239 - if ``T`` is a struct type, then for each field ``f`` of that struct,1240 the static subobjects of ``T`` at location ``L + offsetof(T, .f)``; and1241 1242 - if ``T`` is the array type ``E[N]``, then for each ``i`` satisfying1243 ``0 <= i < N``, the static subobjects of ``E`` at location1244 ``L + i * sizeof(E)``.1245 1246If an l-value is converted to an r-value, then all static subobjects1247whose types are non-trivial to copy are accessed. If an l-value is1248assigned to, or if an object of automatic storage duration goes out of1249scope, then all static subobjects of types that are non-trivial to destroy1250are accessed.1251 1252A dynamic object is created at a location if an initialization initializes1253an object of that type there. A dynamic object ceases to exist at a1254location if the memory is repurposed. Memory is repurposed if it is1255freed or if a different dynamic object is created there, for example by1256assigning into a different union member. An implementation may provide1257additional rules for what constitutes creating or destroying a dynamic1258object.1259 1260If an object is accessed under these rules at a location where no such1261dynamic object exists, the program has undefined behavior.1262If memory for a location is repurposed while a dynamic object that is1263non-trivial to destroy exists at that location, the program has1264undefined behavior.1265 1266.. admonition:: Rationale1267 1268 While these rules are far less fine-grained than C++, they are1269 nonetheless sufficient to express a wide spectrum of types.1270 Types that express some sort of ownership will generally be non-trivial1271 to both copy and destroy and either non-trivial or illegal to1272 default-initialize. Types that don't express ownership may still1273 be non-trivial to copy because of some sort of address sensitivity;1274 for example, a relative reference. Distinguishing default1275 initialization allows types to impose policies about how they are1276 created.1277 1278 These rules assume that assignment into an l-value is always a1279 modification of an existing object rather than an initialization.1280 Assignment is then a compound operation where the old value is1281 read and destroyed, if necessary, and the new value is put into1282 place. These are the natural semantics of value propagation, where1283 all basic operations on the type come down to copies and destroys,1284 and everything else is just an optimization on top of those.1285 1286 The most glaring weakness of programming with non-trivial types in C1287 is that there are no language mechanisms (akin to C++'s placement1288 ``new`` and explicit destructor calls) for explicitly creating and1289 destroying objects. Clang should consider adding builtins for this1290 purpose, as well as for common optimizations like destructive1291 relocation.1292 1293Application of the formal C rules to nontrivial ownership qualifiers1294~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~1295 1296Nontrivially ownership-qualified types are considered non-trivial1297to copy, destroy, and default-initialize.1298 1299A dynamic object of nontrivially ownership-qualified type contingently1300exists at a location if the memory is filled with a zero pattern, e.g.1301by ``calloc`` or ``bzero``. Such an object can be safely accessed in1302all of the cases above, but its memory can also be safely repurposed.1303Assigning a null pointer into an l-value of ``__weak`` or1304``__strong``-qualified type accesses the dynamic object there (and thus1305may have undefined behavior if no such object exists), but afterwards1306the object's memory is guaranteed to be filled with a zero pattern1307and thus may be either further accessed or repurposed as needed.1308The upshot is that programs may safely initialize dynamically-allocated1309memory for nontrivially ownership-qualified types by ensuring it is zero-initialized, and they may safely deinitialize memory before1310freeing it by storing ``nil`` into any ``__strong`` or ``__weak``1311references previously created in that memory.1312 1313C/C++ compatibility for structs and unions with non-trivial members1314~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~1315 1316Structs and unions with non-trivial members are compatible in1317different language modes (e.g. between Objective-C and Objective-C++,1318or between ARC and non-ARC modes) under the following conditions:1319 1320- The types must be compatible ignoring ownership qualifiers according1321 to the baseline, non-ARC rules (e.g. C struct compatibility or C++'s1322 ODR). This condition implies a pairwise correspondence between1323 fields.1324 1325 Note that an Objective-C++ class with base classes, a user-provided1326 copy or move constructor, or a user-provided destructor is never1327 compatible with an Objective-C type.1328 1329- If two fields correspond as above, and at least one of the fields is1330 ownership-qualified, then:1331 1332 - the fields must be identically qualified, or else1333 1334 - one type must be unqualified (and thus declared in a non-ARC mode),1335 and the other type must be qualified with ``__unsafe_unretained``1336 or ``__strong``.1337 1338 Note that ``__weak`` fields must always be declared ``__weak`` because1339 of the need to pin those fields in memory and keep them properly1340 registered with the Objective-C runtime. Non-ARC modes may still1341 declare fields ``__weak`` by enabling ``-fobjc-weak``.1342 1343These compatibility rules permit a function that takes a parameter1344of non-trivial struct type to be written in ARC and called from1345non-ARC or vice-versa. The convention for this always transfers1346ownership of objects stored in ``__strong`` fields from the caller1347to the callee, just as for an ``ns_consumed`` argument. Therefore,1348non-ARC callers must ensure that such fields are initialized to a +11349reference, and non-ARC callees must balance that +1 by releasing the1350reference or transferring it as appropriate.1351 1352Likewise, a function returning a non-trivial struct may be written in1353ARC and called from non-ARC or vice-versa. The convention for this1354always transfers ownership of objects stored in ``__strong`` fields1355from the callee to the caller, and so callees must initialize such1356fields with +1 references, and callers must balance that +1 by releasing1357or transferring them.1358 1359Similar transfers of responsibility occur for ``__weak`` fields, but1360since both sides must use native ``__weak`` support to ensure1361calling convention compatibility, this transfer is always handled1362automatically by the compiler.1363 1364.. admonition:: Rationale1365 1366 In earlier releases, when non-trivial ownership was only permitted1367 on fields in Objective-C++, the ABI used for such classes was the1368 ordinary ABI for non-trivial C++ classes, which passes arguments and1369 returns indirectly and does not transfer responsibility for arguments.1370 When support for Objective-C structs was added, it was decided to1371 change to the current ABI for three reasons:1372 1373 - It permits ARC / non-ARC compatibility for structs containing only1374 ``__strong`` references, as long as the non-ARC side is careful about1375 transferring ownership.1376 1377 - It avoids unnecessary indirection for sufficiently small types that1378 the C ABI would prefer to pass in registers.1379 1380 - Given that struct arguments must be produced at +1 to satisfy C's1381 semantics of initializing the local parameter variable, transferring1382 ownership of that copy to the callee is generally better for ARC1383 optimization, since otherwise there will be releases in the caller1384 that are much harder to pair with transfers in the callee.1385 1386 Breaking compatibility with existing Objective-C++ structures was1387 considered an acceptable cost, as most Objective-C++ code does not have1388 binary-compatibility requirements. Any existing code which cannot accept1389 this compatibility break, which is necessarily Objective-C++, should1390 force the use of the standard C++ ABI by declaring an empty (but1391 non-defaulted) destructor.1392 1393.. _arc.ownership.inference:1394 1395Ownership inference1396-------------------1397 1398.. _arc.ownership.inference.variables:1399 1400Objects1401^^^^^^^1402 1403If an object is declared with retainable object owner type, but without an1404explicit ownership qualifier, its type is implicitly adjusted to have1405``__strong`` qualification.1406 1407As a special case, if the object's base type is ``Class`` (possibly1408protocol-qualified), the type is adjusted to have ``__unsafe_unretained``1409qualification instead.1410 1411.. _arc.ownership.inference.indirect_parameters:1412 1413Indirect parameters1414^^^^^^^^^^^^^^^^^^^1415 1416If a function or method parameter has type ``T*``, where ``T`` is an1417ownership-unqualified retainable object pointer type, then:1418 1419* if ``T`` is ``const``-qualified or ``Class``, then it is implicitly1420 qualified with ``__unsafe_unretained``;1421* otherwise, it is implicitly qualified with ``__autoreleasing``.1422 1423.. admonition:: Rationale1424 1425 ``__autoreleasing`` exists mostly for this case, the Cocoa convention for1426 out-parameters. Since a pointer to ``const`` is obviously not an1427 out-parameter, we instead use a type more useful for passing arrays. If the1428 user instead intends to pass in a *mutable* array, inferring1429 ``__autoreleasing`` is the wrong thing to do; this directs some of the1430 caution in the following rules about writeback.1431 1432Such a type written anywhere else would be ill-formed by the general rule1433requiring ownership qualifiers.1434 1435This rule does not apply in Objective-C++ if a parameter's type is dependent in1436a template pattern and is only *instantiated* to a type which would be a1437pointer to an unqualified retainable object pointer type. Such code is still1438ill-formed.1439 1440.. admonition:: Rationale1441 1442 The convention is very unlikely to be intentional in template code.1443 1444.. _arc.ownership.inference.template.arguments:1445 1446Template arguments1447^^^^^^^^^^^^^^^^^^1448 1449If a template argument for a template type parameter is a retainable object1450owner type that does not have an explicit ownership qualifier, it is adjusted1451to have ``__strong`` qualification. This adjustment occurs regardless of1452whether the template argument was deduced or explicitly specified.1453 1454.. admonition:: Rationale1455 1456 ``__strong`` is a useful default for containers (e.g., ``std::vector<id>``),1457 which would otherwise require explicit qualification. Moreover, unqualified1458 retainable object pointer types are unlikely to be useful within templates,1459 since they generally need to have a qualifier applied to the before being1460 used.1461 1462.. _arc.method-families:1463 1464Method families1465===============1466 1467An Objective-C method may fall into a :arc-term:`method family`, which is a1468conventional set of behaviors ascribed to it by the Cocoa conventions.1469 1470A method is in a certain method family if:1471 1472* it has a ``objc_method_family`` attribute placing it in that family; or if1473 not that,1474* it does not have an ``objc_method_family`` attribute placing it in a1475 different or no family, and1476* its selector falls into the corresponding selector family, and1477* its signature obeys the added restrictions of the method family.1478 1479A selector is in a certain selector family if, ignoring any leading1480underscores, the first component of the selector either consists entirely of1481the name of the method family or it begins with that name followed by a1482character other than a lowercase letter. For example, ``_perform:with:`` and1483``performWith:`` would fall into the ``perform`` family (if we recognized one),1484but ``performing:with`` would not.1485 1486The families and their added restrictions are:1487 1488* ``alloc`` methods must return a retainable object pointer type.1489* ``copy`` methods must return a retainable object pointer type.1490* ``mutableCopy`` methods must return a retainable object pointer type.1491* ``new`` methods must return a retainable object pointer type.1492* ``init`` methods must be instance methods and must return an Objective-C1493 pointer type. Additionally, a program is ill-formed if it declares or1494 contains a call to an ``init`` method whose return type is neither ``id`` nor1495 a pointer to a super-class or sub-class of the declaring class (if the method1496 was declared on a class) or the static receiver type of the call (if it was1497 declared on a protocol).1498 1499 .. admonition:: Rationale1500 1501 There are a fair number of existing methods with ``init``-like selectors1502 which nonetheless don't follow the ``init`` conventions. Typically these1503 are either accidental naming collisions or helper methods called during1504 initialization. Because of the peculiar retain/release behavior of1505 ``init`` methods, it's very important not to treat these methods as1506 ``init`` methods if they aren't meant to be. It was felt that implicitly1507 defining these methods out of the family based on the exact relationship1508 between the return type and the declaring class would be much too subtle1509 and fragile. Therefore we identify a small number of legitimate-seeming1510 return types and call everything else an error. This serves the secondary1511 purpose of encouraging programmers not to accidentally give methods names1512 in the ``init`` family.1513 1514 Note that a method with an ``init``-family selector which returns a1515 non-Objective-C type (e.g. ``void``) is perfectly well-formed; it simply1516 isn't in the ``init`` family.1517 1518A program is ill-formed if a method's declarations, implementations, and1519overrides do not all have the same method family.1520 1521.. _arc.family.attribute:1522 1523Explicit method family control1524------------------------------1525 1526A method may be annotated with the ``objc_method_family`` attribute to1527precisely control which method family it belongs to. If a method in an1528``@implementation`` does not have this attribute, but there is a method1529declared in the corresponding ``@interface`` that does, then the attribute is1530copied to the declaration in the ``@implementation``. The attribute is1531available outside of ARC, and may be tested for with the preprocessor query1532``__has_attribute(objc_method_family)``.1533 1534The attribute is spelled1535``__attribute__((objc_method_family(`` *family* ``)))``. If *family* is1536``none``, the method has no family, even if it would otherwise be considered to1537have one based on its selector and type. Otherwise, *family* must be one of1538``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``, in which case the1539method is considered to belong to the corresponding family regardless of its1540selector. It is an error if a method that is explicitly added to a family in1541this way does not meet the requirements of the family other than the selector1542naming convention.1543 1544.. admonition:: Rationale1545 1546 The rules codified in this document describe the standard conventions of1547 Objective-C. However, as these conventions have not heretofore been enforced1548 by an unforgiving mechanical system, they are only imperfectly kept,1549 especially as they haven't always even been precisely defined. While it is1550 possible to define low-level ownership semantics with attributes like1551 ``ns_returns_retained``, this attribute allows the user to communicate1552 semantic intent, which is of use both to ARC (which, e.g., treats calls to1553 ``init`` specially) and the static analyzer.1554 1555.. _arc.family.semantics:1556 1557Semantics of method families1558----------------------------1559 1560A method's membership in a method family may imply non-standard semantics for1561its parameters and return type.1562 1563Methods in the ``alloc``, ``copy``, ``mutableCopy``, and ``new`` families ---1564that is, methods in all the currently-defined families except ``init`` ---1565implicitly :ref:`return a retained object1566<arc.object.operands.retained-return-values>` as if they were annotated with1567the ``ns_returns_retained`` attribute. This can be overridden by annotating1568the method with either of the ``ns_returns_autoreleased`` or1569``ns_returns_not_retained`` attributes.1570 1571Properties also follow same naming rules as methods. This means that those in1572the ``alloc``, ``copy``, ``mutableCopy``, and ``new`` families provide access1573to :ref:`retained objects <arc.object.operands.retained-return-values>`. This1574can be overridden by annotating the property with ``ns_returns_not_retained``1575attribute.1576 1577.. _arc.family.semantics.init:1578 1579Semantics of ``init``1580^^^^^^^^^^^^^^^^^^^^^1581 1582Methods in the ``init`` family implicitly :ref:`consume1583<arc.objects.operands.consumed>` their ``self`` parameter and :ref:`return a1584retained object <arc.object.operands.retained-return-values>`. Neither of1585these properties can be altered through attributes.1586 1587A call to an ``init`` method with a receiver that is either ``self`` (possibly1588parenthesized or casted) or ``super`` is called a :arc-term:`delegate init1589call`. It is an error for a delegate init call to be made except from an1590``init`` method, and excluding blocks within such methods.1591 1592As an exception to the :ref:`usual rule <arc.misc.self>`, the variable ``self``1593is mutable in an ``init`` method and has the usual semantics for a ``__strong``1594variable. However, it is undefined behavior and the program is ill-formed, no1595diagnostic required, if an ``init`` method attempts to use the previous value1596of ``self`` after the completion of a delegate init call. It is conventional,1597but not required, for an ``init`` method to return ``self``.1598 1599It is undefined behavior for a program to cause two or more calls to ``init``1600methods on the same object, except that each ``init`` method invocation may1601perform at most one delegate init call.1602 1603.. _arc.family.semantics.result_type:1604 1605Related result types1606^^^^^^^^^^^^^^^^^^^^1607 1608Certain methods are candidates to have :arc-term:`related result types`:1609 1610* class methods in the ``alloc`` and ``new`` method families1611* instance methods in the ``init`` family1612* the instance method ``self``1613* outside of ARC, the instance methods ``retain`` and ``autorelease``1614 1615If the formal result type of such a method is ``id`` or protocol-qualified1616``id``, or a type equal to the declaring class or a superclass, then it is said1617to have a related result type. In this case, when invoked in an explicit1618message send, it is assumed to return a type related to the type of the1619receiver:1620 1621* if it is a class method, and the receiver is a class name ``T``, the message1622 send expression has type ``T*``; otherwise1623* if it is an instance method, and the receiver has type ``T``, the message1624 send expression has type ``T``; otherwise1625* the message send expression has the normal result type of the method.1626 1627This is a new rule of the Objective-C language and applies outside of ARC.1628 1629.. admonition:: Rationale1630 1631 ARC's automatic code emission is more prone than most code to signature1632 errors, i.e. errors where a call was emitted against one method signature,1633 but the implementing method has an incompatible signature. Having more1634 precise type information helps drastically lower this risk, as well as1635 catching a number of latent bugs.1636 1637.. _arc.optimization:1638 1639Optimization1640============1641 1642Within this section, the word :arc-term:`function` will be used to1643refer to any structured unit of code, be it a C function, an1644Objective-C method, or a block.1645 1646This specification describes ARC as performing specific ``retain`` and1647``release`` operations on retainable object pointers at specific1648points during the execution of a program. These operations make up a1649non-contiguous subsequence of the computation history of the program.1650The portion of this sequence for a particular retainable object1651pointer for which a specific function execution is directly1652responsible is the :arc-term:`formal local retain history` of the1653object pointer. The corresponding actual sequence executed is the1654`dynamic local retain history`.1655 1656However, under certain circumstances, ARC is permitted to re-order and1657eliminate operations in a manner which may alter the overall1658computation history beyond what is permitted by the general "as if"1659rule of C/C++ and the :ref:`restrictions <arc.objects.retains>` on1660the implementation of ``retain`` and ``release``.1661 1662.. admonition:: Rationale1663 1664 Specifically, ARC is sometimes permitted to optimize ``release``1665 operations in ways which might cause an object to be deallocated1666 before it would otherwise be. Without this, it would be almost1667 impossible to eliminate any ``retain``/``release`` pairs. For1668 example, consider the following code:1669 1670 .. code-block:: objc1671 1672 id x = _ivar;1673 [x foo];1674 1675 If we were not permitted in any event to shorten the lifetime of the1676 object in ``x``, then we would not be able to eliminate this retain1677 and release unless we could prove that the message send could not1678 modify ``_ivar`` (or deallocate ``self``). Since message sends are1679 opaque to the optimizer, this is not possible, and so ARC's hands1680 would be almost completely tied.1681 1682ARC makes no guarantees about the execution of a computation history1683which contains undefined behavior. In particular, ARC makes no1684guarantees in the presence of race conditions.1685 1686ARC may assume that any retainable object pointers it receives or1687generates are instantaneously valid from that point until a point1688which, by the concurrency model of the host language, happens-after1689the generation of the pointer and happens-before a release of that1690object (possibly via an aliasing pointer or indirectly due to1691destruction of a different object).1692 1693.. admonition:: Rationale1694 1695 There is very little point in trying to guarantee correctness in the1696 presence of race conditions. ARC does not have a stack-scanning1697 garbage collector, and guaranteeing the atomicity of every load and1698 store operation would be prohibitive and preclude a vast amount of1699 optimization.1700 1701ARC may assume that non-ARC code engages in sensible balancing1702behavior and does not rely on exact or minimum retain count values1703except as guaranteed by ``__strong`` object invariants or +1 transfer1704conventions. For example, if an object is provably double-retained1705and double-released, ARC may eliminate the inner retain and release;1706it does not need to guard against code which performs an unbalanced1707release followed by a "balancing" retain.1708 1709.. _arc.optimization.liveness:1710 1711Object liveness1712---------------1713 1714ARC may not allow a retainable object ``X`` to be deallocated at a1715time ``T`` in a computation history if:1716 1717* ``X`` is the value stored in a ``__strong`` object ``S`` with1718 :ref:`precise lifetime semantics <arc.optimization.precise>`, or1719 1720* ``X`` is the value stored in a ``__strong`` object ``S`` with1721 imprecise lifetime semantics and, at some point after ``T`` but1722 before the next store to ``S``, the computation history features a1723 load from ``S`` and in some way depends on the value loaded, or1724 1725* ``X`` is a value described as being released at the end of the1726 current full-expression and, at some point after ``T`` but before1727 the end of the full-expression, the computation history depends1728 on that value.1729 1730.. admonition:: Rationale1731 1732 The intent of the second rule is to say that objects held in normal1733 ``__strong`` local variables may be released as soon as the value in1734 the variable is no longer being used: either the variable stops1735 being used completely or a new value is stored in the variable.1736 1737 The intent of the third rule is to say that return values may be1738 released after they've been used.1739 1740A computation history depends on a pointer value ``P`` if it:1741 1742* performs a pointer comparison with ``P``,1743* loads from ``P``,1744* stores to ``P``,1745* depends on a pointer value ``Q`` derived via pointer arithmetic1746 from ``P`` (including an instance-variable or field access), or1747* depends on a pointer value ``Q`` loaded from ``P``.1748 1749Dependency applies only to values derived directly or indirectly from1750a particular expression result and does not occur merely because a1751separate pointer value dynamically aliases ``P``. Furthermore, this1752dependency is not carried by values that are stored to objects.1753 1754.. admonition:: Rationale1755 1756 The restrictions on dependency are intended to make this analysis1757 feasible by an optimizer with only incomplete information about a1758 program. Essentially, dependence is carried to "obvious" uses of a1759 pointer. Merely passing a pointer argument to a function does not1760 itself cause dependence, but since generally the optimizer will not1761 be able to prove that the function doesn't depend on that parameter,1762 it will be forced to conservatively assume it does.1763 1764 Dependency propagates to values loaded from a pointer because those1765 values might be invalidated by deallocating the object. For1766 example, given the code ``__strong id x = p->ivar;``, ARC must not1767 move the release of ``p`` to between the load of ``p->ivar`` and the1768 retain of that value for storing into ``x``.1769 1770 Dependency does not propagate through stores of dependent pointer1771 values because doing so would allow dependency to outlive the1772 full-expression which produced the original value. For example, the1773 address of an instance variable could be written to some global1774 location and then freely accessed during the lifetime of the local,1775 or a function could return an inner pointer of an object and store1776 it to a local. These cases would be potentially impossible to1777 reason about and so would basically prevent any optimizations based1778 on imprecise lifetime. There are also uncommon enough to make it1779 reasonable to require the precise-lifetime annotation if someone1780 really wants to rely on them.1781 1782 Dependency does propagate through return values of pointer type.1783 The compelling source of need for this rule is a property accessor1784 which returns an un-autoreleased result; the calling function must1785 have the chance to operate on the value, e.g. to retain it, before1786 ARC releases the original pointer. Note again, however, that1787 dependence does not survive a store, so ARC does not guarantee the1788 continued validity of the return value past the end of the1789 full-expression.1790 1791.. _arc.optimization.object_lifetime:1792 1793No object lifetime extension1794----------------------------1795 1796If, in the formal computation history of the program, an object ``X``1797has been deallocated by the time of an observable side-effect, then1798ARC must cause ``X`` to be deallocated by no later than the occurrence1799of that side-effect, except as influenced by the re-ordering of the1800destruction of objects.1801 1802.. admonition:: Rationale1803 1804 This rule is intended to prohibit ARC from observably extending the1805 lifetime of a retainable object, other than as specified in this1806 document. Together with the rule limiting the transformation of1807 releases, this rule requires ARC to eliminate retains and release1808 only in pairs.1809 1810 ARC's power to reorder the destruction of objects is critical to its1811 ability to do any optimization, for essentially the same reason that1812 it must retain the power to decrease the lifetime of an object.1813 Unfortunately, while it's generally poor style for the destruction1814 of objects to have arbitrary side-effects, it's certainly possible.1815 Hence the caveat.1816 1817.. _arc.optimization.precise:1818 1819Precise lifetime semantics1820--------------------------1821 1822In general, ARC maintains an invariant that a retainable object pointer held in1823a ``__strong`` object will be retained for the full formal lifetime of the1824object. Objects subject to this invariant have :arc-term:`precise lifetime1825semantics`.1826 1827By default, local variables of automatic storage duration do not have precise1828lifetime semantics. Such objects are simply strong references which hold1829values of retainable object pointer type, and these values are still fully1830subject to the optimizations on values under local control.1831 1832.. admonition:: Rationale1833 1834 Applying these precise-lifetime semantics strictly would be prohibitive.1835 Many useful optimizations that might theoretically decrease the lifetime of1836 an object would be rendered impossible. Essentially, it promises too much.1837 1838A local variable of retainable object owner type and automatic storage duration1839may be annotated with the ``objc_precise_lifetime`` attribute to indicate that1840it should be considered to be an object with precise lifetime semantics.1841 1842.. admonition:: Rationale1843 1844 Nonetheless, it is sometimes useful to be able to force an object to be1845 released at a precise time, even if that object does not appear to be used.1846 This is likely to be uncommon enough that the syntactic weight of explicitly1847 requesting these semantics will not be burdensome, and may even make the code1848 clearer.1849 1850.. _arc.misc:1851 1852Miscellaneous1853=============1854 1855.. _arc.misc.special_methods:1856 1857Special methods1858---------------1859 1860.. _arc.misc.special_methods.retain:1861 1862Memory management methods1863^^^^^^^^^^^^^^^^^^^^^^^^^1864 1865A program is ill-formed if it contains a method definition, message send, or1866``@selector`` expression for any of the following selectors:1867 1868* ``autorelease``1869* ``release``1870* ``retain``1871* ``retainCount``1872 1873.. admonition:: Rationale1874 1875 ``retainCount`` is banned because ARC robs it of consistent semantics. The1876 others were banned after weighing three options for how to deal with message1877 sends:1878 1879 **Honoring** them would work out very poorly if a programmer naively or1880 accidentally tried to incorporate code written for manual retain/release code1881 into an ARC program. At best, such code would do twice as much work as1882 necessary; quite frequently, however, ARC and the explicit code would both1883 try to balance the same retain, leading to crashes. The cost is losing the1884 ability to perform "unrooted" retains, i.e. retains not logically1885 corresponding to a strong reference in the object graph.1886 1887 **Ignoring** them would badly violate user expectations about their code.1888 While it *would* make it easier to develop code simultaneously for ARC and1889 non-ARC, there is very little reason to do so except for certain library1890 developers. ARC and non-ARC translation units share an execution model and1891 can seamlessly interoperate. Within a translation unit, a developer who1892 faithfully maintains their code in non-ARC mode is suffering all the1893 restrictions of ARC for zero benefit, while a developer who isn't testing the1894 non-ARC mode is likely to be unpleasantly surprised if they try to go back to1895 it.1896 1897 **Banning** them has the disadvantage of making it very awkward to migrate1898 existing code to ARC. The best answer to that, given a number of other1899 changes and restrictions in ARC, is to provide a specialized tool to assist1900 users in that migration.1901 1902 Implementing these methods was banned because they are too integral to the1903 semantics of ARC; many tricks which worked tolerably under manual reference1904 counting will misbehave if ARC performs an ephemeral extra retain or two. If1905 absolutely required, it is still possible to implement them in non-ARC code,1906 for example in a category; the implementations must obey the :ref:`semantics1907 <arc.objects.retains>` laid out elsewhere in this document.1908 1909.. _arc.misc.special_methods.dealloc:1910 1911``dealloc``1912^^^^^^^^^^^1913 1914A program is ill-formed if it contains a message send or ``@selector``1915expression for the selector ``dealloc``.1916 1917.. admonition:: Rationale1918 1919 There are no legitimate reasons to call ``dealloc`` directly.1920 1921A class may provide a method definition for an instance method named1922``dealloc``. This method will be called after the final ``release`` of the1923object but before it is deallocated or any of its instance variables are1924destroyed. The superclass's implementation of ``dealloc`` will be called1925automatically when the method returns.1926 1927.. admonition:: Rationale1928 1929 Even though ARC destroys instance variables automatically, there are still1930 legitimate reasons to write a ``dealloc`` method, such as freeing1931 non-retainable resources. Failing to call ``[super dealloc]`` in such a1932 method is nearly always a bug. Sometimes, the object is simply trying to1933 prevent itself from being destroyed, but ``dealloc`` is really far too late1934 for the object to be raising such objections. Somewhat more legitimately, an1935 object may have been pool-allocated and should not be deallocated with1936 ``free``; for now, this can only be supported with a ``dealloc``1937 implementation outside of ARC. Such an implementation must be very careful1938 to do all the other work that ``NSObject``'s ``dealloc`` would, which is1939 outside the scope of this document to describe.1940 1941The instance variables for an ARC-compiled class will be destroyed at some1942point after control enters the ``dealloc`` method for the root class of the1943class. The ordering of the destruction of instance variables is unspecified,1944both within a single class and between subclasses and superclasses.1945 1946.. admonition:: Rationale1947 1948 The traditional, non-ARC pattern for destroying instance variables is to1949 destroy them immediately before calling ``[super dealloc]``. Unfortunately,1950 message sends from the superclass are quite capable of reaching methods in1951 the subclass, and those methods may well read or write to those instance1952 variables. Making such message sends from dealloc is generally discouraged,1953 since the subclass may well rely on other invariants that were broken during1954 ``dealloc``, but it's not so inescapably dangerous that we felt comfortable1955 calling it undefined behavior. Therefore we chose to delay destroying the1956 instance variables to a point at which message sends are clearly disallowed:1957 the point at which the root class's deallocation routines take over.1958 1959 In most code, the difference is not observable. It can, however, be observed1960 if an instance variable holds a strong reference to an object whose1961 deallocation will trigger a side-effect which must be carefully ordered with1962 respect to the destruction of the super class. Such code violates the design1963 principle that semantically important behavior should be explicit. A simple1964 fix is to clear the instance variable manually during ``dealloc``; a more1965 holistic solution is to move semantically important side-effects out of1966 ``dealloc`` and into a separate teardown phase which can rely on working with1967 well-formed objects.1968 1969.. _arc.misc.autoreleasepool:1970 1971``@autoreleasepool``1972--------------------1973 1974To simplify the use of autorelease pools, and to bring them under the control1975of the compiler, a new kind of statement is available in Objective-C. It is1976written ``@autoreleasepool`` followed by a *compound-statement*, i.e. by a new1977scope delimited by curly braces. Upon entry to this block, the current state1978of the autorelease pool is captured. When the block is exited normally,1979whether by fallthrough or directed control flow (such as ``return`` or1980``break``), the autorelease pool is restored to the saved state, releasing all1981the objects in it. When the block is exited with an exception, the pool is not1982drained.1983 1984``@autoreleasepool`` may be used in non-ARC translation units, with equivalent1985semantics.1986 1987A program is ill-formed if it refers to the ``NSAutoreleasePool`` class.1988 1989.. admonition:: Rationale1990 1991 Autorelease pools are clearly important for the compiler to reason about, but1992 it is far too much to expect the compiler to accurately reason about control1993 dependencies between two calls. It is also very easy to accidentally forget1994 to drain an autorelease pool when using the manual API, and this can1995 significantly inflate the process's high-water-mark. The introduction of a1996 new scope is unfortunate but basically required for sane interaction with the1997 rest of the language. Not draining the pool during an unwind is apparently1998 required by the Objective-C exceptions implementation.1999 2000.. _arc.misc.externally_retained:2001 2002Externally-Retained Variables2003-----------------------------2004 2005In some situations, variables with strong ownership are considered2006externally-retained by the implementation. This means that the variable is2007retained elsewhere, and therefore the implementation can elide retaining and2008releasing its value. Such a variable is implicitly ``const`` for safety. In2009contrast with ``__unsafe_unretained``, an externally-retained variable still2010behaves as a strong variable outside of initialization and destruction. For2011instance, when an externally-retained variable is captured in a block the value2012of the variable is retained and released on block capture and destruction. It2013also affects C++ features such as lambda capture, ``decltype``, and template2014argument deduction.2015 2016Implicitly, the implementation assumes that the :ref:`self parameter in a2017non-init method <arc.misc.self>` and the :ref:`variable in a for-in loop2018<arc.misc.enumeration>` are externally-retained.2019 2020Externally-retained semantics can also be opted into with the2021``objc_externally_retained`` attribute. This attribute can apply to strong local2022variables, functions, methods, or blocks:2023 2024.. code-block:: objc2025 2026 @class WobbleAmount;2027 2028 @interface Widget : NSObject2029 -(void)wobble:(WobbleAmount *)amount;2030 @end2031 2032 @implementation Widget2033 2034 -(void)wobble:(WobbleAmount *)amount2035 __attribute__((objc_externally_retained)) {2036 // 'amount' and 'alias' aren't retained on entry, nor released on exit.2037 __attribute__((objc_externally_retained)) WobbleAmount *alias = amount;2038 }2039 @end2040 2041Annotating a function with this attribute makes every parameter with strong2042retainable object pointer type externally-retained, unless the variable was2043explicitly qualified with ``__strong``. For instance, ``first_param`` is2044externally-retained (and therefore ``const``) below, but not ``second_param``:2045 2046.. code-block:: objc2047 2048 __attribute__((objc_externally_retained))2049 void f(NSArray *first_param, __strong NSArray *second_param) {2050 // ...2051 }2052 2053You can test if your compiler has support for ``objc_externally_retained`` with2054``__has_attribute``:2055 2056.. code-block:: objc2057 2058 #if __has_attribute(objc_externally_retained)2059 // Use externally retained...2060 #endif2061 2062.. _arc.misc.self:2063 2064``self``2065--------2066 2067The ``self`` parameter variable of a non-init Objective-C method is considered2068:ref:`externally-retained <arc.misc.externally_retained>` by the implementation.2069It is undefined behavior, or at least dangerous, to cause an object to be2070deallocated during a message send to that object. In an init method, ``self``2071follows the :ref:``init family rules <arc.family.semantics.init>``.2072 2073.. admonition:: Rationale2074 2075 The cost of retaining ``self`` in all methods was found to be prohibitive, as2076 it tends to be live across calls, preventing the optimizer from proving that2077 the retain and release are unnecessary --- for good reason, as it's quite2078 possible in theory to cause an object to be deallocated during its execution2079 without this retain and release. Since it's extremely uncommon to actually2080 do so, even unintentionally, and since there's no natural way for the2081 programmer to remove this retain/release pair otherwise (as there is for2082 other parameters by, say, making the variable ``objc_externally_retained`` or2083 qualifying it with ``__unsafe_unretained``), we chose to make this optimizing2084 assumption and shift some amount of risk to the user.2085 2086.. _arc.misc.enumeration:2087 2088Fast enumeration iteration variables2089------------------------------------2090 2091If a variable is declared in the condition of an Objective-C fast enumeration2092loop, and the variable has no explicit ownership qualifier, then it is2093implicitly :ref:`externally-retained <arc.misc.externally_retained>` so that2094objects encountered during the enumeration are not actually retained and2095released.2096 2097.. admonition:: Rationale2098 2099 This is an optimization made possible because fast enumeration loops promise2100 to keep the objects retained during enumeration, and the collection itself2101 cannot be synchronously modified. It can be overridden by explicitly2102 qualifying the variable with ``__strong``, which will make the variable2103 mutable again and cause the loop to retain the objects it encounters.2104 2105.. _arc.misc.blocks:2106 2107Blocks2108------2109 2110The implicit ``const`` capture variables created when evaluating a block2111literal expression have the same ownership semantics as the local variables2112they capture. The capture is performed by reading from the captured variable2113and initializing the capture variable with that value; the capture variable is2114destroyed when the block literal is, i.e. at the end of the enclosing scope.2115 2116The :ref:`inference <arc.ownership.inference>` rules apply equally to2117``__block`` variables, which is a shift in semantics from non-ARC, where2118``__block`` variables did not implicitly retain during capture.2119 2120``__block`` variables of retainable object owner type are moved off the stack2121by initializing the heap copy with the result of moving from the stack copy.2122 2123With the exception of retains done as part of initializing a ``__strong``2124parameter variable or reading a ``__weak`` variable, whenever these semantics2125call for retaining a value of block-pointer type, it has the effect of a2126``Block_copy``. The optimizer may remove such copies when it sees that the2127result is used only as an argument to a call.2128 2129When a block pointer type is converted to a non-block pointer type (such as2130``id``), ``Block_copy`` is called. This is necessary because a block allocated2131on the stack won't get copied to the heap when the non-block pointer escapes.2132A block pointer is implicitly converted to ``id`` when it is passed to a2133function as a variadic argument.2134 2135.. _arc.misc.exceptions:2136 2137Exceptions2138----------2139 2140By default in Objective C, ARC is not exception-safe for normal releases:2141 2142* It does not end the lifetime of ``__strong`` variables when their scopes are2143 abnormally terminated by an exception.2144* It does not perform releases which would occur at the end of a2145 full-expression if that full-expression throws an exception.2146 2147A program may be compiled with the option ``-fobjc-arc-exceptions`` in order to2148enable these, or with the option ``-fno-objc-arc-exceptions`` to explicitly2149disable them, with the last such argument "winning".2150 2151.. admonition:: Rationale2152 2153 The standard Cocoa convention is that exceptions signal programmer error and2154 are not intended to be recovered from. Making code exceptions-safe by2155 default would impose severe runtime and code size penalties on code that2156 typically does not actually care about exceptions safety. Therefore,2157 ARC-generated code leaks by default on exceptions, which is just fine if the2158 process is going to be immediately terminated anyway. Programs which do care2159 about recovering from exceptions should enable the option.2160 2161In Objective-C++, ``-fobjc-arc-exceptions`` is enabled by default.2162 2163.. admonition:: Rationale2164 2165 C++ already introduces pervasive exceptions-cleanup code of the sort that ARC2166 introduces. C++ programmers who have not already disabled exceptions are2167 much more likely to actual require exception-safety.2168 2169ARC does end the lifetimes of ``__weak`` objects when an exception terminates2170their scope unless exceptions are disabled in the compiler.2171 2172.. admonition:: Rationale2173 2174 The consequence of a local ``__weak`` object not being destroyed is very2175 likely to be corruption of the Objective-C runtime, so we want to be safer2176 here. Of course, potentially massive leaks are about as likely to take down2177 the process as this corruption is if the program does try to recover from2178 exceptions.2179 2180.. _arc.misc.interior:2181 2182Interior pointers2183-----------------2184 2185An Objective-C method returning a non-retainable pointer may be annotated with2186the ``objc_returns_inner_pointer`` attribute to indicate that it returns a2187handle to the internal data of an object, and that this reference will be2188invalidated if the object is destroyed. When such a message is sent to an2189object, the object's lifetime will be extended until at least the earliest of:2190 2191* the last use of the returned pointer, or any pointer derived from it, in the2192 calling function or2193* the autorelease pool is restored to a previous state.2194 2195.. admonition:: Rationale2196 2197 Rationale: not all memory and resources are managed with reference counts; it2198 is common for objects to manage private resources in their own, private way.2199 Typically these resources are completely encapsulated within the object, but2200 some classes offer their users direct access for efficiency. If ARC is not2201 aware of methods that return such "interior" pointers, its optimizations can2202 cause the owning object to be reclaimed too soon. This attribute informs ARC2203 that it must tread lightly.2204 2205 The extension rules are somewhat intentionally vague. The autorelease pool2206 limit is there to permit a simple implementation to simply retain and2207 autorelease the receiver. The other limit permits some amount of2208 optimization. The phrase "derived from" is intended to encompass the results2209 both of pointer transformations, such as casts and arithmetic, and of loading2210 from such derived pointers; furthermore, it applies whether or not such2211 derivations are applied directly in the calling code or by other utility code2212 (for example, the C library routine ``strchr``). However, the implementation2213 never need account for uses after a return from the code which calls the2214 method returning an interior pointer.2215 2216As an exception, no extension is required if the receiver is loaded directly2217from a ``__strong`` object with :ref:`precise lifetime semantics2218<arc.optimization.precise>`.2219 2220.. admonition:: Rationale2221 2222 Implicit autoreleases carry the risk of significantly inflating memory use,2223 so it's important to provide users a way of avoiding these autoreleases.2224 Tying this to precise lifetime semantics is ideal, as for local variables2225 this requires a very explicit annotation, which allows ARC to trust the user2226 with good cheer.2227 2228.. _arc.misc.c-retainable:2229 2230C retainable pointer types2231--------------------------2232 2233A type is a :arc-term:`C retainable pointer type` if it is a pointer to2234(possibly qualified) ``void`` or a pointer to a (possibly qualifier) ``struct``2235or ``class`` type.2236 2237.. admonition:: Rationale2238 2239 ARC does not manage pointers of CoreFoundation type (or any of the related2240 families of retainable C pointers which interoperate with Objective-C for2241 retain/release operation). In fact, ARC does not even know how to2242 distinguish these types from arbitrary C pointer types. The intent of this2243 concept is to filter out some obviously non-object types while leaving a hook2244 for later tightening if a means of exhaustively marking CF types is made2245 available.2246 2247.. _arc.misc.c-retainable.audit:2248 2249Auditing of C retainable pointer interfaces2250^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^2251 2252:when-revised:`[beginning Apple 4.0, LLVM 3.1]`2253 2254A C function may be marked with the ``cf_audited_transfer`` attribute to2255express that, except as otherwise marked with attributes, it obeys the2256parameter (consuming vs. non-consuming) and return (retained vs. non-retained)2257conventions for a C function of its name, namely:2258 2259* A parameter of C retainable pointer type is assumed to not be consumed2260 unless it is marked with the ``cf_consumed`` attribute, and2261* A result of C retainable pointer type is assumed to not be returned retained2262 unless the function is either marked ``cf_returns_retained`` or it follows2263 the create/copy naming convention and is not marked2264 ``cf_returns_not_retained``.2265 2266A function obeys the :arc-term:`create/copy` naming convention if its name2267contains as a substring:2268 2269* either "Create" or "Copy" not followed by a lowercase letter, or2270* either "create" or "copy" not followed by a lowercase letter and2271 not preceded by any letter, whether uppercase or lowercase.2272 2273A second attribute, ``cf_unknown_transfer``, signifies that a function's2274transfer semantics cannot be accurately captured using any of these2275annotations. A program is ill-formed if it annotates the same function with2276both ``cf_audited_transfer`` and ``cf_unknown_transfer``.2277 2278A pragma is provided to facilitate the mass annotation of interfaces:2279 2280.. code-block:: objc2281 2282 #pragma clang arc_cf_code_audited begin2283 ...2284 #pragma clang arc_cf_code_audited end2285 2286All C functions declared within the extent of this pragma are treated as if2287annotated with the ``cf_audited_transfer`` attribute unless they otherwise have2288the ``cf_unknown_transfer`` attribute. The pragma is accepted in all language2289modes. A program is ill-formed if it attempts to change files, whether by2290including a file or ending the current file, within the extent of this pragma.2291 2292It is possible to test for all the features in this section with2293``__has_feature(arc_cf_code_audited)``.2294 2295.. admonition:: Rationale2296 2297 A significant inconvenience in ARC programming is the necessity of2298 interacting with APIs based around C retainable pointers. These features are2299 designed to make it relatively easy for API authors to quickly review and2300 annotate their interfaces, in turn improving the fidelity of tools such as2301 the static analyzer and ARC. The single-file restriction on the pragma is2302 designed to eliminate the risk of accidentally annotating some other header's2303 interfaces.2304 2305.. _arc.runtime:2306 2307Runtime support2308===============2309 2310This section describes the interaction between the ARC runtime and the code2311generated by the ARC compiler. This is not part of the ARC language2312specification; instead, it is effectively a language-specific ABI supplement,2313akin to the "Itanium" generic ABI for C++.2314 2315Ownership qualification does not alter the storage requirements for objects,2316except that it is undefined behavior if a ``__weak`` object is inadequately2317aligned for an object of type ``id``. The other qualifiers may be used on2318explicitly under-aligned memory.2319 2320The runtime tracks ``__weak`` objects which holds non-null values. It is2321undefined behavior to directly modify a ``__weak`` object which is being tracked2322by the runtime except through an2323:ref:`objc_storeWeak <arc.runtime.objc_storeWeak>`,2324:ref:`objc_destroyWeak <arc.runtime.objc_destroyWeak>`, or2325:ref:`objc_moveWeak <arc.runtime.objc_moveWeak>` call.2326 2327The runtime must provide a number of new entrypoints which the compiler may2328emit, which are described in the remainder of this section.2329 2330.. admonition:: Rationale2331 2332 Several of these functions are semantically equivalent to a message send; we2333 emit calls to C functions instead because:2334 2335 * the machine code to do so is significantly smaller,2336 * it is much easier to recognize the C functions in the ARC optimizer, and2337 * a sufficiently sophisticated runtime may be able to avoid the message send in2338 common cases.2339 2340 Several other of these functions are "fused" operations which can be2341 described entirely in terms of other operations. We use the fused operations2342 primarily as a code-size optimization, although in some cases there is also a2343 real potential for avoiding redundant operations in the runtime.2344 2345.. _arc.runtime.objc_autorelease:2346 2347``id objc_autorelease(id value);``2348----------------------------------2349 2350*Precondition:* ``value`` is null or a pointer to a valid object.2351 2352If ``value`` is null, this call has no effect. Otherwise, it adds the object2353to the innermost autorelease pool exactly as if the object had been sent the2354``autorelease`` message.2355 2356Always returns ``value``.2357 2358.. _arc.runtime.objc_autoreleasePoolPop:2359 2360``void objc_autoreleasePoolPop(void *pool);``2361---------------------------------------------2362 2363*Precondition:* ``pool`` is the result of a previous call to2364:ref:`objc_autoreleasePoolPush <arc.runtime.objc_autoreleasePoolPush>` on the2365current thread, where neither ``pool`` nor any enclosing pool have previously2366been popped.2367 2368Releases all the objects added to the given autorelease pool and any2369autorelease pools it encloses, then sets the current autorelease pool to the2370pool directly enclosing ``pool``.2371 2372.. _arc.runtime.objc_autoreleasePoolPush:2373 2374``void *objc_autoreleasePoolPush(void);``2375-----------------------------------------2376 2377Creates a new autorelease pool that is enclosed by the current pool, makes that2378the current pool, and returns an opaque "handle" to it.2379 2380.. admonition:: Rationale2381 2382 While the interface is described as an explicit hierarchy of pools, the rules2383 allow the implementation to just keep a stack of objects, using the stack2384 depth as the opaque pool handle.2385 2386.. _arc.runtime.objc_autoreleaseReturnValue:2387 2388``id objc_autoreleaseReturnValue(id value);``2389---------------------------------------------2390 2391*Precondition:* ``value`` is null or a pointer to a valid object.2392 2393If ``value`` is null, this call has no effect. Otherwise, it makes a best2394effort to hand off ownership of a retain count on the object to a call to2395:ref:`objc_retainAutoreleasedReturnValue2396<arc.runtime.objc_retainAutoreleasedReturnValue>` (or2397:ref:`objc_unsafeClaimAutoreleasedReturnValue2398<arc.runtime.objc_unsafeClaimAutoreleasedReturnValue>`) for the same object in2399an enclosing call frame. If this is not possible, the object is autoreleased as2400above.2401 2402Always returns ``value``.2403 2404.. _arc.runtime.objc_copyWeak:2405 2406``void objc_copyWeak(id *dest, id *src);``2407------------------------------------------2408 2409*Precondition:* ``src`` is a valid pointer which either contains a null pointer2410or has been registered as a ``__weak`` object. ``dest`` is a valid pointer2411which has not been registered as a ``__weak`` object.2412 2413``dest`` is initialized to be equivalent to ``src``, potentially registering it2414with the runtime. Equivalent to the following code:2415 2416.. code-block:: objc2417 2418 void objc_copyWeak(id *dest, id *src) {2419 objc_release(objc_initWeak(dest, objc_loadWeakRetained(src)));2420 }2421 2422Must be atomic with respect to calls to ``objc_storeWeak`` on ``src``.2423 2424.. _arc.runtime.objc_destroyWeak:2425 2426``void objc_destroyWeak(id *object);``2427--------------------------------------2428 2429*Precondition:* ``object`` is a valid pointer which either contains a null2430pointer or has been registered as a ``__weak`` object.2431 2432``object`` is unregistered as a weak object, if it ever was. The current value2433of ``object`` is left unspecified; otherwise, equivalent to the following code:2434 2435.. code-block:: objc2436 2437 void objc_destroyWeak(id *object) {2438 objc_storeWeak(object, nil);2439 }2440 2441Does not need to be atomic with respect to calls to ``objc_storeWeak`` on2442``object``.2443 2444.. _arc.runtime.objc_initWeak:2445 2446``id objc_initWeak(id *object, id value);``2447-------------------------------------------2448 2449*Precondition:* ``object`` is a valid pointer which has not been registered as2450a ``__weak`` object. ``value`` is null or a pointer to a valid object.2451 2452If ``value`` is a null pointer or the object to which it points has begun2453deallocation, ``object`` is zero-initialized. Otherwise, ``object`` is2454registered as a ``__weak`` object pointing to ``value``. Equivalent to the2455following code:2456 2457.. code-block:: objc2458 2459 id objc_initWeak(id *object, id value) {2460 *object = nil;2461 return objc_storeWeak(object, value);2462 }2463 2464Returns the value of ``object`` after the call.2465 2466Does not need to be atomic with respect to calls to ``objc_storeWeak`` on2467``object``.2468 2469.. _arc.runtime.objc_loadWeak:2470 2471``id objc_loadWeak(id *object);``2472---------------------------------2473 2474*Precondition:* ``object`` is a valid pointer which either contains a null2475pointer or has been registered as a ``__weak`` object.2476 2477If ``object`` is registered as a ``__weak`` object, and the last value stored2478into ``object`` has not yet been deallocated or begun deallocation, retains and2479autoreleases that value and returns it. Otherwise returns null. Equivalent to2480the following code:2481 2482.. code-block:: objc2483 2484 id objc_loadWeak(id *object) {2485 return objc_autorelease(objc_loadWeakRetained(object));2486 }2487 2488Must be atomic with respect to calls to ``objc_storeWeak`` on ``object``.2489 2490.. admonition:: Rationale2491 2492 Loading weak references would be inherently prone to race conditions without2493 the retain.2494 2495.. _arc.runtime.objc_loadWeakRetained:2496 2497``id objc_loadWeakRetained(id *object);``2498-----------------------------------------2499 2500*Precondition:* ``object`` is a valid pointer which either contains a null2501pointer or has been registered as a ``__weak`` object.2502 2503If ``object`` is registered as a ``__weak`` object, and the last value stored2504into ``object`` has not yet been deallocated or begun deallocation, retains2505that value and returns it. Otherwise returns null.2506 2507Must be atomic with respect to calls to ``objc_storeWeak`` on ``object``.2508 2509.. _arc.runtime.objc_moveWeak:2510 2511``void objc_moveWeak(id *dest, id *src);``2512------------------------------------------2513 2514*Precondition:* ``src`` is a valid pointer which either contains a null pointer2515or has been registered as a ``__weak`` object. ``dest`` is a valid pointer2516which has not been registered as a ``__weak`` object.2517 2518``dest`` is initialized to be equivalent to ``src``, potentially registering it2519with the runtime. ``src`` may then be left in its original state, in which2520case this call is equivalent to :ref:`objc_copyWeak2521<arc.runtime.objc_copyWeak>`, or it may be left as null.2522 2523Must be atomic with respect to calls to ``objc_storeWeak`` on ``src``.2524 2525.. _arc.runtime.objc_release:2526 2527``void objc_release(id value);``2528--------------------------------2529 2530*Precondition:* ``value`` is null or a pointer to a valid object.2531 2532If ``value`` is null, this call has no effect. Otherwise, it performs a2533release operation exactly as if the object had been sent the ``release``2534message.2535 2536.. _arc.runtime.objc_retain:2537 2538``id objc_retain(id value);``2539-----------------------------2540 2541*Precondition:* ``value`` is null or a pointer to a valid object.2542 2543If ``value`` is null, this call has no effect. Otherwise, it performs a retain2544operation exactly as if the object had been sent the ``retain`` message.2545 2546Always returns ``value``.2547 2548.. _arc.runtime.objc_retainAutorelease:2549 2550``id objc_retainAutorelease(id value);``2551----------------------------------------2552 2553*Precondition:* ``value`` is null or a pointer to a valid object.2554 2555If ``value`` is null, this call has no effect. Otherwise, it performs a retain2556operation followed by an autorelease operation. Equivalent to the following2557code:2558 2559.. code-block:: objc2560 2561 id objc_retainAutorelease(id value) {2562 return objc_autorelease(objc_retain(value));2563 }2564 2565Always returns ``value``.2566 2567.. _arc.runtime.objc_retainAutoreleaseReturnValue:2568 2569``id objc_retainAutoreleaseReturnValue(id value);``2570---------------------------------------------------2571 2572*Precondition:* ``value`` is null or a pointer to a valid object.2573 2574If ``value`` is null, this call has no effect. Otherwise, it performs a retain2575operation followed by the operation described in2576:ref:`objc_autoreleaseReturnValue <arc.runtime.objc_autoreleaseReturnValue>`.2577Equivalent to the following code:2578 2579.. code-block:: objc2580 2581 id objc_retainAutoreleaseReturnValue(id value) {2582 return objc_autoreleaseReturnValue(objc_retain(value));2583 }2584 2585Always returns ``value``.2586 2587.. _arc.runtime.objc_retainAutoreleasedReturnValue:2588 2589``id objc_retainAutoreleasedReturnValue(id value);``2590----------------------------------------------------2591 2592*Precondition:* ``value`` is null or a pointer to a valid object.2593 2594If ``value`` is null, this call has no effect. Otherwise, it attempts to2595accept a hand off of a retain count from a call to2596:ref:`objc_autoreleaseReturnValue <arc.runtime.objc_autoreleaseReturnValue>` on2597``value`` in a recently-called function or something it tail-calls. If that2598fails, it performs a retain operation exactly like :ref:`objc_retain2599<arc.runtime.objc_retain>`.2600 2601Always returns ``value``.2602 2603.. _arc.runtime.objc_retainBlock:2604 2605``id objc_retainBlock(id value);``2606----------------------------------2607 2608*Precondition:* ``value`` is null or a pointer to a valid block object.2609 2610If ``value`` is null, this call has no effect. Otherwise, if the block pointed2611to by ``value`` is still on the stack, it is copied to the heap and the address2612of the copy is returned. Otherwise a retain operation is performed on the2613block exactly as if it had been sent the ``retain`` message.2614 2615.. _arc.runtime.objc_storeStrong:2616 2617``void objc_storeStrong(id *object, id value);``2618------------------------------------------------2619 2620*Precondition:* ``object`` is a valid pointer to a ``__strong`` object which is2621adequately aligned for a pointer. ``value`` is null or a pointer to a valid2622object.2623 2624Performs the complete sequence for assigning to a ``__strong`` object of2625non-block type [*]_. Equivalent to the following code:2626 2627.. code-block:: objc2628 2629 void objc_storeStrong(id *object, id value) {2630 id oldValue = *object;2631 value = [value retain];2632 *object = value;2633 [oldValue release];2634 }2635 2636.. [*] This does not imply that a ``__strong`` object of block type is an2637 invalid argument to this function. Rather it implies that an ``objc_retain``2638 and not an ``objc_retainBlock`` operation will be emitted if the argument is2639 a block.2640 2641.. _arc.runtime.objc_storeWeak:2642 2643``id objc_storeWeak(id *object, id value);``2644--------------------------------------------2645 2646*Precondition:* ``object`` is a valid pointer which either contains a null2647pointer or has been registered as a ``__weak`` object. ``value`` is null or a2648pointer to a valid object.2649 2650If ``value`` is a null pointer or the object to which it points has begun2651deallocation, ``object`` is assigned null and unregistered as a ``__weak``2652object. Otherwise, ``object`` is registered as a ``__weak`` object or has its2653registration updated to point to ``value``.2654 2655Returns the value of ``object`` after the call.2656 2657.. _arc.runtime.objc_unsafeClaimAutoreleasedReturnValue:2658 2659``id objc_unsafeClaimAutoreleasedReturnValue(id value);``2660---------------------------------------------------------2661 2662*Precondition:* ``value`` is null or a pointer to a valid object.2663 2664If ``value`` is null, this call has no effect. Otherwise, it attempts to2665accept a hand off of a retain count from a call to2666:ref:`objc_autoreleaseReturnValue <arc.runtime.objc_autoreleaseReturnValue>` on2667``value`` in a recently-called function or something it tail-calls (in a manner2668similar to :ref:`objc_retainAutoreleasedReturnValue2669<arc.runtime.objc_retainAutoreleasedReturnValue>`). If that succeeds,2670it performs a release operation exactly like :ref:`objc_release2671<arc.runtime.objc_release>`. If the handoff fails, this call has no effect.2672 2673Always returns ``value``.2674 2675