blob: 65675a44bf695a26a786c4b08237fb250df5a758 [file] [log] [blame]
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001.. FIXME: move to the stylesheet or Sphinx plugin
2
3.. raw:: html
4
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; }
Dmitri Gribenkob22acbb2012-12-16 11:25:45 +00009
10 /*
Dmitri Gribenko24ee6ea2012-12-16 19:55:39 +000011 * Automatic numbering is described in this article:
Dmitri Gribenkob22acbb2012-12-16 11:25:45 +000012 * http://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 ordered
17 * 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 bullets
26 }
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 }
Dmitri Gribenko94b21a12012-12-13 16:04:37 +000055 </style>
56
57.. role:: arc-term
58.. role:: revision
59.. role:: when-revised
60
Dmitri Gribenkob22acbb2012-12-16 11:25:45 +000061==============================================
62Objective-C Automatic Reference Counting (ARC)
63==============================================
64
65.. contents::
66 :local:
Dmitri Gribenko94b21a12012-12-13 16:04:37 +000067
68.. _arc.meta:
69
Dmitri Gribenko94b21a12012-12-13 16:04:37 +000070About this document
71===================
72
73.. _arc.meta.purpose:
74
75Purpose
Sean Silvab34b8052012-12-16 00:23:40 +000076-------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +000077
78The first and primary purpose of this document is to serve as a complete
79technical specification of Automatic Reference Counting. Given a core
80Objective-C compiler and runtime, it should be possible to write a compiler and
81runtime which implements these new semantics.
82
83The secondary purpose is to act as a rationale for why ARC was designed in this
84way. This should remain tightly focused on the technical design and should not
85stray into marketing speculation.
86
87.. _arc.meta.background:
88
89Background
Sean Silvab34b8052012-12-16 00:23:40 +000090----------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +000091
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:`block
96pointers`, which are represented like a normal pointer. A block may capture
97values from local variables; when this occurs, memory must be dynamically
98allocated. The initial allocation is done on the stack, but the runtime
99provides a ``Block_copy`` function which, given a block pointer, either copies
100the underlying block object to the heap, setting its reference count to 1 and
101returning the new block pointer, or (if the block object is already on the
102heap) increases its reference count by 1. The paired function is
103``Block_release``, which decreases the reference count by 1 and destroys the
104object if the count reaches zero and is on the heap.
105
106Objective-C is a set of language extensions, significant enough to be
107considered a different language. It is a strict superset of C. The extensions
108can also be imposed on C++, producing a language called Objective-C++. The
109primary feature is a single-inheritance object system; we briefly describe the
110modern dialect.
111
112Objective-C defines a new type kind, collectively called the :arc-term:`object
113pointer types`. This kind has two notable builtin members, ``id`` and
114``Class``; ``id`` is the final supertype of all object pointers. The validity
115of conversions between object pointer types is not checked at runtime. Users
116may define :arc-term:`classes`; each class is a type, and the pointer to that
117type is an object pointer type. A class may have a superclass; its pointer
118type is a subtype of its superclass's pointer type. A class has a set of
119:arc-term:`ivars`, fields which appear on all instances of that class. For
120every class *T* there's an associated metaclass; it has no fields, its
121superclass is the metaclass of *T*'s superclass, and its metaclass is a global
122class. Every class has a global object whose class is the class's metaclass;
123metaclasses have no associated type, so pointers to this object have type
124``Class``.
125
126A class declaration (``@interface``) declares a set of :arc-term:`methods`. A
127method 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 the
129number of formal arguments. A method may be an instance method, in which case
130it can be invoked on objects of the class, or a class method, in which case it
131can be invoked on objects of the metaclass. A method may be invoked by
132providing an object (called the :arc-term:`receiver`) and a list of formal
133arguments interspersed with the selector, like so:
134
135.. code-block:: objc
136
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 the
142actual receiver is the class object for that class, or (within method
143definitions) it may be ``super``, in which case the lookup algorithm starts
144with the static superclass instead of the dynamic class. The actual methods
145dynamically found in a class are not those declared in the ``@interface``, but
146those defined in a separate ``@implementation`` declaration; however, when
147compiling a call, typechecking is done based on the methods declared in the
148``@interface``.
149
150Method declarations may also be grouped into :arc-term:`protocols`, which are not
151inherently associated with any class, but which classes may claim to follow.
152Object pointer types may be qualified with additional protocols that the object
153is known to support.
154
155:arc-term:`Class extensions` are collections of ivars and methods, designed to
156allow a class's ``@interface`` to be split across multiple files; however,
157there is still a primary implementation file which must see the
158``@interface``\ s of all class extensions. :arc-term:`Categories` allow
159methods (but not ivars) to be declared *post hoc* on an arbitrary class; the
160methods in the category's ``@implementation`` will be dynamically added to that
161class's method tables which the category is loaded at runtime, replacing those
162methods in case of a collision.
163
164In the standard environment, objects are allocated on the heap, and their
165lifetime is manually managed using a reference count. This is done using two
166instance methods which all classes are expected to implement: ``retain``
167increases the object's reference count by 1, whereas ``release`` decreases it
168by 1 and calls the instance method ``dealloc`` if the count reaches 0. To
169simplify certain operations, there is also an :arc-term:`autorelease pool`, a
170thread-local list of objects to call ``release`` on later; an object can be
171added to this pool by calling ``autorelease`` on it.
172
173Block pointers may be converted to type ``id``; block objects are laid out in a
174way that makes them compatible with Objective-C objects. There is a builtin
175class that all block objects are considered to be objects of; this class
176implements ``retain`` by adjusting the reference count, not by calling
177``Block_copy``.
178
179.. _arc.meta.evolution:
180
181Evolution
Sean Silvab34b8052012-12-16 00:23:40 +0000182---------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000183
184ARC is under continual evolution, and this document must be updated as the
185language progresses.
186
187If a change increases the expressiveness of the language, for example by
188lifting a restriction or by adding new syntax, the change will be annotated
189with a revision marker, like so:
190
191 ARC applies to Objective-C pointer types, block pointer types, and
192 :when-revised:`[beginning Apple 8.0, LLVM 3.8]` :revision:`BPTRs declared
193 within` ``extern "BCPL"`` blocks.
194
195For now, it is sensible to version this document by the releases of its sole
196implementation (and its host project), clang. "LLVM X.Y" refers to an
197open-source release of clang from the LLVM project. "Apple X.Y" refers to an
198Apple-provided release of the Apple LLVM Compiler. Other organizations that
199prepare their own, separately-versioned clang releases and wish to maintain
200similar information in this document should send requests to cfe-dev.
201
202If a change decreases the expressiveness of the language, for example by
203imposing a new restriction, this should be taken as an oversight in the
204original specification and something to be avoided in all versions. Such
205changes are generally to be avoided.
206
207.. _arc.general:
208
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000209General
210=======
211
212Automatic Reference Counting implements automatic memory management for
213Objective-C objects and blocks, freeing the programmer from the need to
214explicitly insert retains and releases. It does not provide a cycle collector;
215users must explicitly manage the lifetime of their objects, breaking cycles
216manually or with weak or unsafe references.
217
218ARC may be explicitly enabled with the compiler flag ``-fobjc-arc``. It may
219also be explicitly disabled with the compiler flag ``-fno-objc-arc``. The last
220of these two flags appearing on the compile line "wins".
221
222If ARC is enabled, ``__has_feature(objc_arc)`` will expand to 1 in the
223preprocessor. For more information about ``__has_feature``, see the
224:ref:`language extensions <langext-__has_feature-__has_extension>` document.
225
226.. _arc.objects:
227
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000228Retainable object pointers
229==========================
230
231This section describes retainable object pointers, their basic operations, and
232the restrictions imposed on their use under ARC. Note in particular that it
233covers the rules for pointer *values* (patterns of bits indicating the location
234of a pointed-to object), not pointer *objects* (locations in memory which store
235pointer values). The rules for objects are covered in the next section.
236
237A :arc-term:`retainable object pointer` (or "retainable pointer") is a value of
238a :arc-term:`retainable object pointer type` ("retainable type"). There are
239three kinds of retainable object pointer types:
240
241* block pointers (formed by applying the caret (``^``) declarator sigil to a
242 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 to
247ARC's semantics and restrictions.
248
249.. admonition:: Rationale
250
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 retains
253 and releases manually. In general, there are three requirements in order for
254 a compiler-supported reference-count system to provide reliable
255 interoperation:
256
257 * The type system must reliably identify which objects are to be managed. An
258 ``int*`` might be a pointer to a ``malloc``'ed array, or it might be an
259 interior pointer to such an array, or it might point to some field or local
260 variable. In contrast, values of the retainable object pointer types are
261 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 incrementing
265 and decrementing retain counts. Supporting single-ownership objects
266 requires a lot more explicit mediation in the language.
267
268 * There must be reliable conventions for whether and when "ownership" is
269 passed between caller and callee, for both arguments and return values.
270 Objective-C methods follow such a convention very reliably, at least for
271 system libraries on Mac OS X, and functions always pass objects at +0. The
272 C-based APIs for Core Foundation objects, on the other hand, have much more
273 varied transfer semantics.
274
275The use of ``__attribute__((NSObject))`` typedefs is not recommended. If it's
276absolutely necessary to use this attribute, be very explicit about using the
277typedef, and do not assume that it will be preserved by language features like
278``__typeof`` and C++ template argument substitution.
279
280.. admonition:: Rationale
281
282 Any compiler operation which incidentally strips type "sugar" from a type
283 will yield a type without the attribute, which may result in unexpected
284 behavior.
285
286.. _arc.objects.retains:
287
288Retain count semantics
Sean Silvab34b8052012-12-16 00:23:40 +0000289----------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000290
291A retainable object pointer is either a :arc-term:`null pointer` or a pointer
292to a valid object. Furthermore, if it has block pointer type and is not
293``null`` then it must actually be a pointer to a block object, and if it has
294``Class`` type (possibly protocol-qualified) then it must actually be a pointer
295to a class object. Otherwise ARC does not enforce the Objective-C type system
296as 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" retaining
300operations. Specifically, the object must be laid out such that the
301Objective-C message send machinery can successfully send it the following
302messages:
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 term
309:arc-term:`high-level semantics` is an intentionally vague term; the intent is
310that programmers must implement these methods in a way such that the compiler,
311modifying code in ways it deems safe according to these constraints, will not
312violate their requirements. For example, if the user puts logging statements
313in ``retain``, they should not be surprised if those statements are executed
314more or less often depending on optimization settings. These constraints are
315not exhaustive of the optimization opportunities: values held in local
316variables are subject to additional restrictions, described later in this
317document.
318
319It is undefined behavior if a computation history featuring a send of
320``retain`` followed by a send of ``release`` to the same object, with no
321intervening ``release`` on that object, is not equivalent under the high-level
322semantics to a computation history in which these sends are removed. Note that
323this implies that these methods may not raise exceptions.
324
325It is undefined behavior if a computation history features any use whatsoever
326of an object following the completion of a send of ``release`` that is not
327preceded by a send of ``retain`` to the same object.
328
329The behavior of ``autorelease`` must be equivalent to sending ``release`` when
330one of the autorelease pools currently in scope is popped. It may not throw an
331exception.
332
333When the semantics call for performing one of these operations on a retainable
334object 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 additional
337:ref:`optimization rules <arc.optimization>` which permit the removal or
338optimization of operations based on local knowledge of data flow. The
339semantics describe the high-level behaviors that the compiler implements, not
340an exact sequence of operations that a program will be compiled into.
341
342.. _arc.objects.operands:
343
344Retainable object pointers as operands and arguments
Sean Silvab34b8052012-12-16 00:23:40 +0000345----------------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000346
347In general, ARC does not perform retain or release operations when simply using
348a retainable object pointer as an operand within an expression. This includes:
349
350* loading a retainable pointer from an object with non-weak :ref:`ownership
351 <arc.ownership>`,
352* passing a retainable pointer as an argument to a function or method, and
353* receiving a retainable pointer as the result of a function or method call.
354
355.. admonition:: Rationale
356
357 While this might seem uncontroversial, it is actually unsafe when multiple
358 expressions are evaluated in "parallel", as with binary operators and calls,
359 because (for example) one expression might load from an object while another
360 writes to it. However, C and C++ already call this undefined behavior
361 because the evaluations are unsequenced, and ARC simply exploits that here to
362 avoid needing to retain arguments across a large number of calls.
363
364The remainder of this section describes exceptions to these rules, how those
365exceptions are detected, and what those exceptions imply semantically.
366
367.. _arc.objects.operands.consumed:
368
369Consumed parameters
Sean Silvab34b8052012-12-16 00:23:40 +0000370^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000371
372A function or method parameter of retainable object pointer type may be marked
373as :arc-term:`consumed`, signifying that the callee expects to take ownership
374of a +1 retain count. This is done by adding the ``ns_consumed`` attribute to
375the parameter declaration, like so:
376
377.. code-block:: objc
378
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 of
383the parameter. It controls only how the argument is passed and received.
384
385When passing such an argument, ARC retains the argument prior to making the
386call.
387
388When receiving such an argument, ARC releases the argument at the end of the
389function, subject to the usual optimizations for local values.
390
391.. admonition:: Rationale
392
393 This formalizes direct transfers of ownership from a caller to a callee. The
394 most common scenario here is passing the ``self`` parameter to ``init``, but
395 it is useful to generalize. Typically, local optimization will remove any
396 extra retains and releases: on the caller side the retain will be merged with
397 a +1 source, and on the callee side the release will be rolled into the
398 initialization of the parameter.
399
400The implicit ``self`` parameter of a method may be marked as consumed by adding
401``__attribute__((ns_consumes_self))`` to the method declaration. Methods in
402the ``init`` :ref:`family <arc.method-families>` are treated as if they were
403implicitly marked with this attribute.
404
405It is undefined behavior if an Objective-C message send to a method with
406``ns_consumed`` parameters (other than self) is made with a null receiver. It
407is undefined behavior if the method to which an Objective-C message send
408statically resolves to has a different set of ``ns_consumed`` parameters than
409the method it dynamically resolves to. It is undefined behavior if a block or
410function call is made through a static type with a different set of
411``ns_consumed`` parameters than the implementation of the called block or
412function.
413
414.. admonition:: Rationale
415
416 Consumed parameters with null receiver are a guaranteed leak. Mismatches
417 with consumed parameters will cause over-retains or over-releases, depending
418 on the direction. The rule about function calls is really just an
419 application of the existing C/C++ rule about calling functions through an
420 incompatible function type, but it's useful to state it explicitly.
421
422.. _arc.object.operands.retained-return-values:
423
424Retained return values
Sean Silvab34b8052012-12-16 00:23:40 +0000425^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000426
427A function or method which returns a retainable object pointer type may be
428marked as returning a retained value, signifying that the caller expects to take
429ownership of a +1 retain count. This is done by adding the
430``ns_returns_retained`` attribute to the function or method declaration, like
431so:
432
433.. code-block:: objc
434
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 the
441point 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 the
444value at the end of the full-expression it is contained within, subject to the
445usual optimizations for local values.
446
447.. admonition:: Rationale
448
449 This formalizes direct transfers of ownership from a callee to a caller. The
450 most common scenario this models is the retained return from ``init``,
451 ``alloc``, ``new``, and ``copy`` methods, but there are other cases in the
452 frameworks. After optimization there are typically no extra retains and
453 releases required.
454
455Methods in the ``alloc``, ``copy``, ``init``, ``mutableCopy``, and ``new``
456:ref:`families <arc.method-families>` are implicitly marked
457``__attribute__((ns_returns_retained))``. This may be suppressed by explicitly
458marking the method ``__attribute__((ns_returns_not_retained))``.
459
460It is undefined behavior if the method to which an Objective-C message send
461statically resolves has different retain semantics on its result from the
462method it dynamically resolves to. It is undefined behavior if a block or
463function call is made through a static type with different retain semantics on
464its result from the implementation of the called block or function.
465
466.. admonition:: Rationale
467
468 Mismatches with returned results will cause over-retains or over-releases,
469 depending on the direction. Again, the rule about function calls is really
470 just an application of the existing C/C++ rule about calling functions
471 through an incompatible function type.
472
473.. _arc.objects.operands.unretained-returns:
474
475Unretained return values
Sean Silvab34b8052012-12-16 00:23:40 +0000476^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000477
478A method or function which returns a retainable object type but does not return
479a retained value must ensure that the object is still valid across the return
480boundary.
481
482When returning from such a function or method, ARC retains the value at the
483point of evaluation of the return statement, then leaves all local scopes, and
484then balances out the retain while ensuring that the value lives across the
485call boundary. In the worst case, this may involve an ``autorelease``, but
486callers 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 elect
489to do something to shorten the lifetime of the returned value.
490
491.. admonition:: Rationale
492
493 It is common in non-ARC code to not return an autoreleased value; therefore
494 the convention does not force either path. It is convenient to not be
495 required to do unnecessary retains and autoreleases; this permits
496 optimizations such as eliding retain/autoreleases when it can be shown that
497 the original pointer will still be valid at the point of return.
498
499A method or function may be marked with
500``__attribute__((ns_returns_autoreleased))`` to indicate that it returns a
501pointer which is guaranteed to be valid at least as long as the innermost
502autorelease pool. There are no additional semantics enforced in the definition
503of such a method; it merely enables optimizations in callers.
504
505.. _arc.objects.operands.casts:
506
507Bridged casts
Sean Silvab34b8052012-12-16 00:23:40 +0000508^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000509
510A :arc-term:`bridged cast` is a C-style cast annotated with one of three
511keywords:
512
513* ``(__bridge T) op`` casts the operand to the destination type ``T``. If
514 ``T`` is a retainable object pointer type, then ``op`` must have a
515 non-retainable pointer type. If ``T`` is a non-retainable pointer type,
516 then ``op`` must have a retainable object pointer type. Otherwise the cast
517 is ill-formed. There is no transfer of ownership, and ARC inserts no retain
518 operations.
519* ``(__bridge_retained T) op`` casts the operand, which must have retainable
520 object pointer type, to the destination type, which must be a non-retainable
521 pointer type. ARC retains the value, subject to the usual optimizations on
522 local values, and the recipient is responsible for balancing that +1.
523* ``(__bridge_transfer T) op`` casts the operand, which must have
524 non-retainable pointer type, to the destination type, which must be a
525 retainable object pointer type. ARC will release the value at the end of
526 the enclosing full-expression, subject to the usual optimizations on local
527 values.
528
529These casts are required in order to transfer objects in and out of ARC
530control; see the rationale in the section on :ref:`conversion of retainable
531object pointers <arc.objects.restrictions.conversion>`.
532
533Using a ``__bridge_retained`` or ``__bridge_transfer`` cast purely to convince
534ARC to emit an unbalanced retain or release, respectively, is poor form.
535
536.. _arc.objects.restrictions:
537
538Restrictions
Sean Silvab34b8052012-12-16 00:23:40 +0000539------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000540
541.. _arc.objects.restrictions.conversion:
542
543Conversion of retainable object pointers
Sean Silvab34b8052012-12-16 00:23:40 +0000544^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000545
546In general, a program which attempts to implicitly or explicitly convert a
547value of retainable object pointer type to any non-retainable type, or
548vice-versa, is ill-formed. For example, an Objective-C object pointer shall
549not be converted to ``void*``. As an exception, cast to ``intptr_t`` is
550allowed because such casts are not transferring ownership. The :ref:`bridged
551casts <arc.objects.operands.casts>` may be used to perform these conversions
552where necessary.
553
554.. admonition:: Rationale
555
556 We cannot ensure the correct management of the lifetime of objects if they
557 may be freely passed around as unmanaged types. The bridged casts are
558 provided so that the programmer may explicitly describe whether the cast
559 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 semantics
Sean Silvab34b8052012-12-16 00:23:40 +0000566^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000567
568:when-revised:`[beginning Apple 4.0, LLVM 3.1]`
569:revision:`These exceptions have been greatly expanded; they previously applied
570only to a much-reduced subset which is difficult to categorize but which
571included null pointers, message sends (under the given rules), and the various
572global constants.`
573
574An unbridged conversion to a retainable object pointer type from a type other
575than a retainable object pointer type is ill-formed, as discussed above, unless
576the operand of the cast has a syntactic form which is known retained, known
577unretained, 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 pointer
583 type <arc.misc.c-retainable>`, or
584* a null pointer constant.
585
586An expression is :arc-term:`known unretained` if it is an rvalue of :ref:`C
587retainable pointer type <arc.misc.c-retainable>` and it is:
588
589* a direct call to a function, and either that function has the
590 ``cf_returns_not_retained`` attribute or it is an :ref:`audited
591 <arc.misc.c-retainable.audit>` function that does not have the
592 ``cf_returns_retained`` attribute and does not follow the create/copy naming
593 convention,
594* a message send, and the declared method either has the
595 ``cf_returns_not_retained`` attribute or it has neither the
596 ``cf_returns_retained`` attribute nor a :ref:`selector family
597 <arc.method-families>` that implies a retained result.
598
599An expression is :arc-term:`known retained` if it is an rvalue of :ref:`C
600retainable pointer type <arc.misc.c-retainable>` and it is:
601
602* a message send, and the declared method either has the
603 ``cf_returns_retained`` attribute, or it does not have the
604 ``cf_returns_not_retained`` attribute but it does have a :ref:`selector
605 family <arc.method-families>` that implies a retained result.
606
607Furthermore:
608
609* a comma expression is classified according to its right-hand side,
610* a statement expression is classified according to its result expression, if
611 it has one,
612* an lvalue-to-rvalue conversion applied to an Objective-C property lvalue is
613 classified according to the underlying message send, and
614* a conditional operator is classified according to its second and third
615 operands, if they agree in classification, or else the other if one is known
616 retain-agnostic.
617
618If the cast operand is known retained, the conversion is treated as a
619``__bridge_transfer`` cast. If the cast operand is known unretained or known
620retain-agnostic, the conversion is treated as a ``__bridge`` cast.
621
622.. admonition:: Rationale
623
624 Bridging casts are annoying. Absent the ability to completely automate the
625 management of CF objects, however, we are left with relatively poor attempts
626 to reduce the need for a glut of explicit bridges. Hence these rules.
627
628 We've so far consciously refrained from implicitly turning retained CF
629 results from function calls into ``__bridge_transfer`` casts. The worry is
630 that some code patterns --- for example, creating a CF value, assigning it
631 to an ObjC-typed local, and then calling ``CFRelease`` when done --- are a
632 bit too likely to be accidentally accepted, leading to mysterious behavior.
633
634.. _arc.objects.restrictions.conversion-exception-contextual:
635
636Conversion from retainable object pointer type in certain contexts
Sean Silvab34b8052012-12-16 00:23:40 +0000637^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000638
639:when-revised:`[beginning Apple 4.0, LLVM 3.1]`
640
641If an expression of retainable object pointer type is explicitly cast to a
642:ref:`C retainable pointer type <arc.misc.c-retainable>`, the program is
643ill-formed as discussed above unless the result is immediately used:
644
645* to initialize a parameter in an Objective-C message send where the parameter
646 is not marked with the ``cf_consumed`` attribute, or
647* to initialize a parameter in a direct call to an
648 :ref:`audited <arc.misc.c-retainable.audit>` function where the parameter is
649 not marked with the ``cf_consumed`` attribute.
650
651.. admonition:: Rationale
652
653 Consumed parameters are left out because ARC would naturally balance them
654 with a retain, which was judged too treacherous. This is in part because
655 several of the most common consuming functions are in the ``Release`` family,
656 and it would be quite unfortunate for explicit releases to be silently
657 balanced out in this way.
658
659.. _arc.ownership:
660
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000661Ownership qualification
662=======================
663
664This section describes the behavior of *objects* of retainable object pointer
665type; that is, locations in memory which store retainable object pointers.
666
667A type is a :arc-term:`retainable object owner type` if it is a retainable
668object pointer type or an array type whose element type is a retainable object
669owner type.
670
671An :arc-term:`ownership qualifier` is a type qualifier which applies only to
672retainable object owner types. An array type is ownership-qualified according
673to its element type, and adding an ownership qualifier to an array type so
674qualifies its element type.
675
676A program is ill-formed if it attempts to apply an ownership qualifier to a
677type which is already ownership-qualified, even if it is the same qualifier.
678There is a single exception to this rule: an ownership qualifier may be applied
679to a substituted template type parameter, which overrides the ownership
680qualifier provided by the template argument.
681
John McCallb2381b12013-03-01 07:58:16 +0000682When forming a function type, the result type is adjusted so that any
683top-level ownership qualifier is deleted.
684
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000685Except as described under the :ref:`inference rules <arc.ownership.inference>`,
686a program is ill-formed if it attempts to form a pointer or reference type to a
687retainable object owner type which lacks an ownership qualifier.
688
689.. admonition:: Rationale
690
691 These rules, together with the inference rules, ensure that all objects and
692 lvalues of retainable object pointer type have an ownership qualifier. The
693 ability to override an ownership qualifier during template substitution is
694 required to counteract the :ref:`inference of __strong for template type
John McCallb2381b12013-03-01 07:58:16 +0000695 arguments <arc.ownership.inference.template.arguments>`. Ownership qualifiers
696 on return types are dropped because they serve no purpose there except to
697 cause spurious problems with overloading and templates.
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000698
699There are four ownership qualifiers:
700
701* ``__autoreleasing``
702* ``__strong``
703* ``__unsafe_unretained``
704* ``__weak``
705
706A type is :arc-term:`nontrivially ownership-qualified` if it is qualified with
707``__autoreleasing``, ``__strong``, or ``__weak``.
708
709.. _arc.ownership.spelling:
710
711Spelling
Sean Silvab34b8052012-12-16 00:23:40 +0000712--------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000713
714The names of the ownership qualifiers are reserved for the implementation. A
715program may not assume that they are or are not implemented with macros, or
716what those macros expand to.
717
718An ownership qualifier may be written anywhere that any other type qualifier
719may be written.
720
721If an ownership qualifier appears in the *declaration-specifiers*, the
722following rules apply:
723
724* if the type specifier is a retainable object owner type, the qualifier
John McCallb2381b12013-03-01 07:58:16 +0000725 initially applies to that type;
726
727* otherwise, if the outermost non-array declarator is a pointer
728 or block pointer declarator, the qualifier initially applies to
729 that type;
730
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000731* otherwise the program is ill-formed.
732
John McCallb2381b12013-03-01 07:58:16 +0000733* If the qualifier is so applied at a position in the declaration
734 where the next-innermost declarator is a function declarator, and
735 there is an block declarator within that function declarator, then
736 the qualifier applies instead to that block declarator and this rule
737 is considered afresh beginning from the new position.
738
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000739If an ownership qualifier appears on the declarator name, or on the declared
John McCallb2381b12013-03-01 07:58:16 +0000740object, it is applied to the innermost pointer or block-pointer type.
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000741
742If an ownership qualifier appears anywhere else in a declarator, it applies to
743the type there.
744
John McCallb2381b12013-03-01 07:58:16 +0000745.. admonition:: Rationale
746
747 Ownership qualifiers are like ``const`` and ``volatile`` in the sense
748 that they may sensibly apply at multiple distinct positions within a
749 declarator. However, unlike those qualifiers, there are many
750 situations where they are not meaningful, and so we make an effort
751 to "move" the qualifier to a place where it will be meaningful. The
752 general goal is to allow the programmer to write, say, ``__strong``
753 before the entire declaration and have it apply in the leftmost
754 sensible place.
755
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000756.. _arc.ownership.spelling.property:
757
758Property declarations
Sean Silvab34b8052012-12-16 00:23:40 +0000759^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000760
761A property of retainable object pointer type may have ownership. If the
762property's type is ownership-qualified, then the property has that ownership.
763If the property has one of the following modifiers, then the property has the
764corresponding ownership. A property is ill-formed if it has conflicting
765sources of ownership, or if it has redundant ownership modifiers, or if it has
766``__autoreleasing`` ownership.
767
768* ``assign`` implies ``__unsafe_unretained`` ownership.
769* ``copy`` implies ``__strong`` ownership, as well as the usual behavior of
770 copy semantics on the setter.
771* ``retain`` implies ``__strong`` ownership.
772* ``strong`` implies ``__strong`` ownership.
773* ``unsafe_unretained`` implies ``__unsafe_unretained`` ownership.
774* ``weak`` implies ``__weak`` ownership.
775
776With the exception of ``weak``, these modifiers are available in non-ARC
777modes.
778
779A property's specified ownership is preserved in its metadata, but otherwise
780the meaning is purely conventional unless the property is synthesized. If a
781property is synthesized, then the :arc-term:`associated instance variable` is
782the instance variable which is named, possibly implicitly, by the
783``@synthesize`` declaration. If the associated instance variable already
784exists, then its ownership qualification must equal the ownership of the
785property; otherwise, the instance variable is created with that ownership
786qualification.
787
788A property of retainable object pointer type which is synthesized without a
789source of ownership has the ownership of its associated instance variable, if it
790already exists; otherwise, :when-revised:`[beginning Apple 3.1, LLVM 3.1]`
791:revision:`its ownership is implicitly` ``strong``. Prior to this revision, it
792was ill-formed to synthesize such a property.
793
794.. admonition:: Rationale
795
796 Using ``strong`` by default is safe and consistent with the generic ARC rule
797 about :ref:`inferring ownership <arc.ownership.inference.variables>`. It is,
798 unfortunately, inconsistent with the non-ARC rule which states that such
799 properties are implicitly ``assign``. However, that rule is clearly
800 untenable in ARC, since it leads to default-unsafe code. The main merit to
801 banning the properties is to avoid confusion with non-ARC practice, which did
802 not ultimately strike us as sufficient to justify requiring extra syntax and
803 (more importantly) forcing novices to understand ownership rules just to
804 declare a property when the default is so reasonable. Changing the rule away
805 from non-ARC practice was acceptable because we had conservatively banned the
806 synthesis in order to give ourselves exactly this leeway.
807
808Applying ``__attribute__((NSObject))`` to a property not of retainable object
809pointer type has the same behavior it does outside of ARC: it requires the
810property type to be some sort of pointer and permits the use of modifiers other
811than ``assign``. These modifiers only affect the synthesized getter and
812setter; direct accesses to the ivar (even if synthesized) still have primitive
813semantics, and the value in the ivar will not be automatically released during
814deallocation.
815
816.. _arc.ownership.semantics:
817
818Semantics
Sean Silvab34b8052012-12-16 00:23:40 +0000819---------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000820
821There are five :arc-term:`managed operations` which may be performed on an
822object of retainable object pointer type. Each qualifier specifies different
823semantics for each of these operations. It is still undefined behavior to
824access an object outside of its lifetime.
825
826A load or store with "primitive semantics" has the same semantics as the
827respective operation would have on an ``void*`` lvalue with the same alignment
828and non-ownership qualification.
829
830:arc-term:`Reading` occurs when performing a lvalue-to-rvalue conversion on an
831object lvalue.
832
833* For ``__weak`` objects, the current pointee is retained and then released at
834 the end of the current full-expression. This must execute atomically with
835 respect to assignments and to the final release of the pointee.
836* For all other objects, the lvalue is loaded with primitive semantics.
837
838:arc-term:`Assignment` occurs when evaluating an assignment operator. The
839semantics vary based on the qualification:
840
841* For ``__strong`` objects, the new pointee is first retained; second, the
842 lvalue is loaded with primitive semantics; third, the new pointee is stored
843 into the lvalue with primitive semantics; and finally, the old pointee is
844 released. This is not performed atomically; external synchronization must be
845 used to make this safe in the face of concurrent loads and stores.
846* For ``__weak`` objects, the lvalue is updated to point to the new pointee,
847 unless the new pointee is an object currently undergoing deallocation, in
848 which case the lvalue is updated to a null pointer. This must execute
849 atomically with respect to other assignments to the object, to reads from the
850 object, and to the final release of the new pointee.
851* For ``__unsafe_unretained`` objects, the new pointee is stored into the
852 lvalue using primitive semantics.
853* For ``__autoreleasing`` objects, the new pointee is retained, autoreleased,
854 and stored into the lvalue using primitive semantics.
855
856:arc-term:`Initialization` occurs when an object's lifetime begins, which
857depends on its storage duration. Initialization proceeds in two stages:
858
859#. First, a null pointer is stored into the lvalue using primitive semantics.
860 This step is skipped if the object is ``__unsafe_unretained``.
861#. Second, if the object has an initializer, that expression is evaluated and
862 then assigned into the object using the usual assignment semantics.
863
864:arc-term:`Destruction` occurs when an object's lifetime ends. In all cases it
865is semantically equivalent to assigning a null pointer to the object, with the
866proviso that of course the object cannot be legally read after the object's
867lifetime ends.
868
869:arc-term:`Moving` occurs in specific situations where an lvalue is "moved
870from", meaning that its current pointee will be used but the object may be left
871in a different (but still valid) state. This arises with ``__block`` variables
872and rvalue references in C++. For ``__strong`` lvalues, moving is equivalent
873to loading the lvalue with primitive semantics, writing a null pointer to it
874with primitive semantics, and then releasing the result of the load at the end
875of the current full-expression. For all other lvalues, moving is equivalent to
876reading the object.
877
878.. _arc.ownership.restrictions:
879
880Restrictions
Sean Silvab34b8052012-12-16 00:23:40 +0000881------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000882
883.. _arc.ownership.restrictions.weak:
884
885Weak-unavailable types
Sean Silvab34b8052012-12-16 00:23:40 +0000886^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000887
888It is explicitly permitted for Objective-C classes to not support ``__weak``
889references. It is undefined behavior to perform an operation with weak
890assignment semantics with a pointer to an Objective-C object whose class does
891not support ``__weak`` references.
892
893.. admonition:: Rationale
894
895 Historically, it has been possible for a class to provide its own
896 reference-count implementation by overriding ``retain``, ``release``, etc.
897 However, weak references to an object require coordination with its class's
898 reference-count implementation because, among other things, weak loads and
899 stores must be atomic with respect to the final release. Therefore, existing
900 custom reference-count implementations will generally not support weak
901 references without additional effort. This is unavoidable without breaking
902 binary compatibility.
903
904A class may indicate that it does not support weak references by providing the
905``objc_arc_weak_unavailable`` attribute on the class's interface declaration. A
906retainable object pointer type is **weak-unavailable** if
907is a pointer to an (optionally protocol-qualified) Objective-C class ``T`` where
908``T`` or one of its superclasses has the ``objc_arc_weak_unavailable``
909attribute. A program is ill-formed if it applies the ``__weak`` ownership
910qualifier to a weak-unavailable type or if the value operand of a weak
911assignment operation has a weak-unavailable type.
912
913.. _arc.ownership.restrictions.autoreleasing:
914
915Storage duration of ``__autoreleasing`` objects
Sean Silvab34b8052012-12-16 00:23:40 +0000916^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000917
918A program is ill-formed if it declares an ``__autoreleasing`` object of
919non-automatic storage duration. A program is ill-formed if it captures an
920``__autoreleasing`` object in a block or, unless by reference, in a C++11
921lambda.
922
923.. admonition:: Rationale
924
925 Autorelease pools are tied to the current thread and scope by their nature.
926 While it is possible to have temporary objects whose instance variables are
927 filled with autoreleased objects, there is no way that ARC can provide any
928 sort of safety guarantee there.
929
930It is undefined behavior if a non-null pointer is assigned to an
931``__autoreleasing`` object while an autorelease pool is in scope and then that
932object is read after the autorelease pool's scope is left.
933
934.. _arc.ownership.restrictions.conversion.indirect:
935
936Conversion of pointers to ownership-qualified types
Sean Silvab34b8052012-12-16 00:23:40 +0000937^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000938
939A program is ill-formed if an expression of type ``T*`` is converted,
940explicitly or implicitly, to the type ``U*``, where ``T`` and ``U`` have
941different ownership qualification, unless:
942
943* ``T`` is qualified with ``__strong``, ``__autoreleasing``, or
944 ``__unsafe_unretained``, and ``U`` is qualified with both ``const`` and
945 ``__unsafe_unretained``; or
946* either ``T`` or ``U`` is ``cv void``, where ``cv`` is an optional sequence
947 of non-ownership qualifiers; or
948* the conversion is requested with a ``reinterpret_cast`` in Objective-C++; or
949* the conversion is a well-formed :ref:`pass-by-writeback
950 <arc.ownership.restrictions.pass_by_writeback>`.
951
952The analogous rule applies to ``T&`` and ``U&`` in Objective-C++.
953
954.. admonition:: Rationale
955
956 These rules provide a reasonable level of type-safety for indirect pointers,
957 as long as the underlying memory is not deallocated. The conversion to
958 ``const __unsafe_unretained`` is permitted because the semantics of reads are
959 equivalent across all these ownership semantics, and that's a very useful and
960 common pattern. The interconversion with ``void*`` is useful for allocating
961 memory or otherwise escaping the type system, but use it carefully.
962 ``reinterpret_cast`` is considered to be an obvious enough sign of taking
963 responsibility for any problems.
964
965It is undefined behavior to access an ownership-qualified object through an
966lvalue of a differently-qualified type, except that any non-``__weak`` object
967may be read through an ``__unsafe_unretained`` lvalue.
968
969It is undefined behavior if a managed operation is performed on a ``__strong``
970or ``__weak`` object without a guarantee that it contains a primitive zero
971bit-pattern, or if the storage for such an object is freed or reused without the
972object being first assigned a null pointer.
973
974.. admonition:: Rationale
975
976 ARC cannot differentiate between an assignment operator which is intended to
977 "initialize" dynamic memory and one which is intended to potentially replace
978 a value. Therefore the object's pointer must be valid before letting ARC at
979 it. Similarly, C and Objective-C do not provide any language hooks for
980 destroying objects held in dynamic memory, so it is the programmer's
981 responsibility to avoid leaks (``__strong`` objects) and consistency errors
982 (``__weak`` objects).
983
984These requirements are followed automatically in Objective-C++ when creating
985objects of retainable object owner type with ``new`` or ``new[]`` and destroying
986them with ``delete``, ``delete[]``, or a pseudo-destructor expression. Note
987that arrays of nontrivially-ownership-qualified type are not ABI compatible with
988non-ARC code because the element type is non-POD: such arrays that are
989``new[]``'d in ARC translation units cannot be ``delete[]``'d in non-ARC
990translation units and vice-versa.
991
992.. _arc.ownership.restrictions.pass_by_writeback:
993
994Passing to an out parameter by writeback
Sean Silvab34b8052012-12-16 00:23:40 +0000995^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +0000996
997If the argument passed to a parameter of type ``T __autoreleasing *`` has type
998``U oq *``, where ``oq`` is an ownership qualifier, then the argument is a
999candidate for :arc-term:`pass-by-writeback`` if:
1000
1001* ``oq`` is ``__strong`` or ``__weak``, and
1002* it would be legal to initialize a ``T __strong *`` with a ``U __strong *``.
1003
1004For purposes of overload resolution, an implicit conversion sequence requiring
1005a pass-by-writeback is always worse than an implicit conversion sequence not
1006requiring a pass-by-writeback.
1007
1008The pass-by-writeback is ill-formed if the argument expression does not have a
1009legal form:
1010
1011* ``&var``, where ``var`` is a scalar variable of automatic storage duration
1012 with retainable object pointer type
1013* a conditional expression where the second and third operands are both legal
1014 forms
1015* a cast whose operand is a legal form
1016* a null pointer constant
1017
1018.. admonition:: Rationale
1019
1020 The restriction in the form of the argument serves two purposes. First, it
1021 makes it impossible to pass the address of an array to the argument, which
1022 serves to protect against an otherwise serious risk of mis-inferring an
1023 "array" argument as an out-parameter. Second, it makes it much less likely
1024 that the user will see confusing aliasing problems due to the implementation,
1025 below, where their store to the writeback temporary is not immediately seen
1026 in the original argument variable.
1027
1028A pass-by-writeback is evaluated as follows:
1029
1030#. The argument is evaluated to yield a pointer ``p`` of type ``U oq *``.
1031#. If ``p`` is a null pointer, then a null pointer is passed as the argument,
1032 and no further work is required for the pass-by-writeback.
1033#. Otherwise, a temporary of type ``T __autoreleasing`` is created and
1034 initialized to a null pointer.
1035#. If the parameter is not an Objective-C method parameter marked ``out``,
1036 then ``*p`` is read, and the result is written into the temporary with
1037 primitive semantics.
1038#. The address of the temporary is passed as the argument to the actual call.
1039#. After the call completes, the temporary is loaded with primitive
1040 semantics, and that value is assigned into ``*p``.
1041
1042.. admonition:: Rationale
1043
1044 This is all admittedly convoluted. In an ideal world, we would see that a
1045 local variable is being passed to an out-parameter and retroactively modify
1046 its type to be ``__autoreleasing`` rather than ``__strong``. This would be
1047 remarkably difficult and not always well-founded under the C type system.
1048 However, it was judged unacceptably invasive to require programmers to write
1049 ``__autoreleasing`` on all the variables they intend to use for
1050 out-parameters. This was the least bad solution.
1051
1052.. _arc.ownership.restrictions.records:
1053
1054Ownership-qualified fields of structs and unions
Sean Silvab34b8052012-12-16 00:23:40 +00001055^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001056
1057A program is ill-formed if it declares a member of a C struct or union to have
1058a nontrivially ownership-qualified type.
1059
1060.. admonition:: Rationale
1061
1062 The resulting type would be non-POD in the C++ sense, but C does not give us
1063 very good language tools for managing the lifetime of aggregates, so it is
1064 more convenient to simply forbid them. It is still possible to manage this
1065 with a ``void*`` or an ``__unsafe_unretained`` object.
1066
1067This restriction does not apply in Objective-C++. However, nontrivally
1068ownership-qualified types are considered non-POD: in C++11 terms, they are not
1069trivially default constructible, copy constructible, move constructible, copy
1070assignable, move assignable, or destructible. It is a violation of C++'s One
1071Definition Rule to use a class outside of ARC that, under ARC, would have a
1072nontrivially ownership-qualified member.
1073
1074.. admonition:: Rationale
1075
1076 Unlike in C, we can express all the necessary ARC semantics for
1077 ownership-qualified subobjects as suboperations of the (default) special
1078 member functions for the class. These functions then become non-trivial.
1079 This has the non-obvious result that the class will have a non-trivial copy
1080 constructor and non-trivial destructor; if this would not normally be true
1081 outside of ARC, objects of the type will be passed and returned in an
1082 ABI-incompatible manner.
1083
1084.. _arc.ownership.inference:
1085
1086Ownership inference
Sean Silvab34b8052012-12-16 00:23:40 +00001087-------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001088
1089.. _arc.ownership.inference.variables:
1090
1091Objects
Sean Silvab34b8052012-12-16 00:23:40 +00001092^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001093
1094If an object is declared with retainable object owner type, but without an
1095explicit ownership qualifier, its type is implicitly adjusted to have
1096``__strong`` qualification.
1097
1098As a special case, if the object's base type is ``Class`` (possibly
1099protocol-qualified), the type is adjusted to have ``__unsafe_unretained``
1100qualification instead.
1101
1102.. _arc.ownership.inference.indirect_parameters:
1103
1104Indirect parameters
Sean Silvab34b8052012-12-16 00:23:40 +00001105^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001106
1107If a function or method parameter has type ``T*``, where ``T`` is an
1108ownership-unqualified retainable object pointer type, then:
1109
1110* if ``T`` is ``const``-qualified or ``Class``, then it is implicitly
1111 qualified with ``__unsafe_unretained``;
1112* otherwise, it is implicitly qualified with ``__autoreleasing``.
1113
1114.. admonition:: Rationale
1115
1116 ``__autoreleasing`` exists mostly for this case, the Cocoa convention for
1117 out-parameters. Since a pointer to ``const`` is obviously not an
1118 out-parameter, we instead use a type more useful for passing arrays. If the
1119 user instead intends to pass in a *mutable* array, inferring
1120 ``__autoreleasing`` is the wrong thing to do; this directs some of the
1121 caution in the following rules about writeback.
1122
1123Such a type written anywhere else would be ill-formed by the general rule
1124requiring ownership qualifiers.
1125
1126This rule does not apply in Objective-C++ if a parameter's type is dependent in
1127a template pattern and is only *instantiated* to a type which would be a
1128pointer to an unqualified retainable object pointer type. Such code is still
1129ill-formed.
1130
1131.. admonition:: Rationale
1132
1133 The convention is very unlikely to be intentional in template code.
1134
1135.. _arc.ownership.inference.template.arguments:
1136
1137Template arguments
Sean Silvab34b8052012-12-16 00:23:40 +00001138^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001139
1140If a template argument for a template type parameter is an retainable object
1141owner type that does not have an explicit ownership qualifier, it is adjusted
1142to have ``__strong`` qualification. This adjustment occurs regardless of
1143whether the template argument was deduced or explicitly specified.
1144
1145.. admonition:: Rationale
1146
1147 ``__strong`` is a useful default for containers (e.g., ``std::vector<id>``),
1148 which would otherwise require explicit qualification. Moreover, unqualified
1149 retainable object pointer types are unlikely to be useful within templates,
1150 since they generally need to have a qualifier applied to the before being
1151 used.
1152
1153.. _arc.method-families:
1154
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001155Method families
1156===============
1157
1158An Objective-C method may fall into a :arc-term:`method family`, which is a
1159conventional set of behaviors ascribed to it by the Cocoa conventions.
1160
1161A method is in a certain method family if:
1162
1163* it has a ``objc_method_family`` attribute placing it in that family; or if
1164 not that,
1165* it does not have an ``objc_method_family`` attribute placing it in a
1166 different or no family, and
1167* its selector falls into the corresponding selector family, and
1168* its signature obeys the added restrictions of the method family.
1169
1170A selector is in a certain selector family if, ignoring any leading
1171underscores, the first component of the selector either consists entirely of
1172the name of the method family or it begins with that name followed by a
1173character other than a lowercase letter. For example, ``_perform:with:`` and
1174``performWith:`` would fall into the ``perform`` family (if we recognized one),
1175but ``performing:with`` would not.
1176
1177The families and their added restrictions are:
1178
1179* ``alloc`` methods must return a retainable object pointer type.
1180* ``copy`` methods must return a retainable object pointer type.
1181* ``mutableCopy`` methods must return a retainable object pointer type.
1182* ``new`` methods must return a retainable object pointer type.
1183* ``init`` methods must be instance methods and must return an Objective-C
1184 pointer type. Additionally, a program is ill-formed if it declares or
1185 contains a call to an ``init`` method whose return type is neither ``id`` nor
1186 a pointer to a super-class or sub-class of the declaring class (if the method
1187 was declared on a class) or the static receiver type of the call (if it was
1188 declared on a protocol).
1189
1190 .. admonition:: Rationale
1191
1192 There are a fair number of existing methods with ``init``-like selectors
1193 which nonetheless don't follow the ``init`` conventions. Typically these
1194 are either accidental naming collisions or helper methods called during
1195 initialization. Because of the peculiar retain/release behavior of
1196 ``init`` methods, it's very important not to treat these methods as
1197 ``init`` methods if they aren't meant to be. It was felt that implicitly
1198 defining these methods out of the family based on the exact relationship
1199 between the return type and the declaring class would be much too subtle
1200 and fragile. Therefore we identify a small number of legitimate-seeming
1201 return types and call everything else an error. This serves the secondary
1202 purpose of encouraging programmers not to accidentally give methods names
1203 in the ``init`` family.
1204
1205 Note that a method with an ``init``-family selector which returns a
1206 non-Objective-C type (e.g. ``void``) is perfectly well-formed; it simply
1207 isn't in the ``init`` family.
1208
1209A program is ill-formed if a method's declarations, implementations, and
1210overrides do not all have the same method family.
1211
1212.. _arc.family.attribute:
1213
1214Explicit method family control
Sean Silvab34b8052012-12-16 00:23:40 +00001215------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001216
1217A method may be annotated with the ``objc_method_family`` attribute to
1218precisely control which method family it belongs to. If a method in an
1219``@implementation`` does not have this attribute, but there is a method
1220declared in the corresponding ``@interface`` that does, then the attribute is
1221copied to the declaration in the ``@implementation``. The attribute is
1222available outside of ARC, and may be tested for with the preprocessor query
1223``__has_attribute(objc_method_family)``.
1224
1225The attribute is spelled
1226``__attribute__((objc_method_family(`` *family* ``)))``. If *family* is
1227``none``, the method has no family, even if it would otherwise be considered to
1228have one based on its selector and type. Otherwise, *family* must be one of
1229``alloc``, ``copy``, ``init``, ``mutableCopy``, or ``new``, in which case the
1230method is considered to belong to the corresponding family regardless of its
1231selector. It is an error if a method that is explicitly added to a family in
1232this way does not meet the requirements of the family other than the selector
1233naming convention.
1234
1235.. admonition:: Rationale
1236
1237 The rules codified in this document describe the standard conventions of
1238 Objective-C. However, as these conventions have not heretofore been enforced
1239 by an unforgiving mechanical system, they are only imperfectly kept,
1240 especially as they haven't always even been precisely defined. While it is
1241 possible to define low-level ownership semantics with attributes like
1242 ``ns_returns_retained``, this attribute allows the user to communicate
1243 semantic intent, which is of use both to ARC (which, e.g., treats calls to
1244 ``init`` specially) and the static analyzer.
1245
1246.. _arc.family.semantics:
1247
1248Semantics of method families
Sean Silvab34b8052012-12-16 00:23:40 +00001249----------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001250
1251A method's membership in a method family may imply non-standard semantics for
1252its parameters and return type.
1253
1254Methods in the ``alloc``, ``copy``, ``mutableCopy``, and ``new`` families ---
1255that is, methods in all the currently-defined families except ``init`` ---
1256implicitly :ref:`return a retained object
1257<arc.object.operands.retained-return-values>` as if they were annotated with
1258the ``ns_returns_retained`` attribute. This can be overridden by annotating
1259the method with either of the ``ns_returns_autoreleased`` or
1260``ns_returns_not_retained`` attributes.
1261
1262Properties also follow same naming rules as methods. This means that those in
1263the ``alloc``, ``copy``, ``mutableCopy``, and ``new`` families provide access
1264to :ref:`retained objects <arc.object.operands.retained-return-values>`. This
1265can be overridden by annotating the property with ``ns_returns_not_retained``
1266attribute.
1267
1268.. _arc.family.semantics.init:
1269
1270Semantics of ``init``
Sean Silvab34b8052012-12-16 00:23:40 +00001271^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001272
1273Methods in the ``init`` family implicitly :ref:`consume
1274<arc.objects.operands.consumed>` their ``self`` parameter and :ref:`return a
1275retained object <arc.object.operands.retained-return-values>`. Neither of
1276these properties can be altered through attributes.
1277
1278A call to an ``init`` method with a receiver that is either ``self`` (possibly
1279parenthesized or casted) or ``super`` is called a :arc-term:`delegate init
1280call`. It is an error for a delegate init call to be made except from an
1281``init`` method, and excluding blocks within such methods.
1282
1283As an exception to the :ref:`usual rule <arc.misc.self>`, the variable ``self``
1284is mutable in an ``init`` method and has the usual semantics for a ``__strong``
1285variable. However, it is undefined behavior and the program is ill-formed, no
1286diagnostic required, if an ``init`` method attempts to use the previous value
1287of ``self`` after the completion of a delegate init call. It is conventional,
1288but not required, for an ``init`` method to return ``self``.
1289
1290It is undefined behavior for a program to cause two or more calls to ``init``
1291methods on the same object, except that each ``init`` method invocation may
1292perform at most one delegate init call.
1293
1294.. _arc.family.semantics.result_type:
1295
1296Related result types
Sean Silvab34b8052012-12-16 00:23:40 +00001297^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001298
1299Certain methods are candidates to have :arc-term:`related result types`:
1300
1301* class methods in the ``alloc`` and ``new`` method families
1302* instance methods in the ``init`` family
1303* the instance method ``self``
1304* outside of ARC, the instance methods ``retain`` and ``autorelease``
1305
1306If the formal result type of such a method is ``id`` or protocol-qualified
1307``id``, or a type equal to the declaring class or a superclass, then it is said
1308to have a related result type. In this case, when invoked in an explicit
1309message send, it is assumed to return a type related to the type of the
1310receiver:
1311
1312* if it is a class method, and the receiver is a class name ``T``, the message
1313 send expression has type ``T*``; otherwise
1314* if it is an instance method, and the receiver has type ``T``, the message
1315 send expression has type ``T``; otherwise
1316* the message send expression has the normal result type of the method.
1317
1318This is a new rule of the Objective-C language and applies outside of ARC.
1319
1320.. admonition:: Rationale
1321
1322 ARC's automatic code emission is more prone than most code to signature
1323 errors, i.e. errors where a call was emitted against one method signature,
1324 but the implementing method has an incompatible signature. Having more
1325 precise type information helps drastically lower this risk, as well as
1326 catching a number of latent bugs.
1327
1328.. _arc.optimization:
1329
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001330Optimization
1331============
1332
1333ARC applies aggressive rules for the optimization of local behavior. These
1334rules are based around a core assumption of :arc-term:`local balancing`: that
1335other code will perform retains and releases as necessary (and only as
1336necessary) for its own safety, and so the optimizer does not need to consider
1337global properties of the retain and release sequence. For example, if a retain
1338and release immediately bracket a call, the optimizer can delete the retain and
1339release on the assumption that the called function will not do a constant
1340number of unmotivated releases followed by a constant number of "balancing"
1341retains, such that the local retain/release pair is the only thing preventing
1342the called function from ending up with a dangling reference.
1343
1344The optimizer assumes that when a new value enters local control, e.g. from a
1345load of a non-local object or as the result of a function call, it is
1346instaneously valid. Subsequently, a retain and release of a value are
1347necessary on a computation path only if there is a use of that value before the
1348release and after any operation which might cause a release of the value
1349(including indirectly or non-locally), and only if the value is not
1350demonstrably already retained.
1351
1352The complete optimization rules are quite complicated, but it would still be
1353useful to document them here.
1354
1355.. _arc.optimization.precise:
1356
1357Precise lifetime semantics
Sean Silvab34b8052012-12-16 00:23:40 +00001358--------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001359
1360In general, ARC maintains an invariant that a retainable object pointer held in
1361a ``__strong`` object will be retained for the full formal lifetime of the
1362object. Objects subject to this invariant have :arc-term:`precise lifetime
1363semantics`.
1364
1365By default, local variables of automatic storage duration do not have precise
1366lifetime semantics. Such objects are simply strong references which hold
1367values of retainable object pointer type, and these values are still fully
1368subject to the optimizations on values under local control.
1369
1370.. admonition:: Rationale
1371
1372 Applying these precise-lifetime semantics strictly would be prohibitive.
1373 Many useful optimizations that might theoretically decrease the lifetime of
1374 an object would be rendered impossible. Essentially, it promises too much.
1375
1376A local variable of retainable object owner type and automatic storage duration
1377may be annotated with the ``objc_precise_lifetime`` attribute to indicate that
1378it should be considered to be an object with precise lifetime semantics.
1379
1380.. admonition:: Rationale
1381
1382 Nonetheless, it is sometimes useful to be able to force an object to be
1383 released at a precise time, even if that object does not appear to be used.
1384 This is likely to be uncommon enough that the syntactic weight of explicitly
1385 requesting these semantics will not be burdensome, and may even make the code
1386 clearer.
1387
1388.. _arc.misc:
1389
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001390Miscellaneous
1391=============
1392
1393.. _arc.misc.special_methods:
1394
1395Special methods
Sean Silvab34b8052012-12-16 00:23:40 +00001396---------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001397
1398.. _arc.misc.special_methods.retain:
1399
1400Memory management methods
Sean Silvab34b8052012-12-16 00:23:40 +00001401^^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001402
1403A program is ill-formed if it contains a method definition, message send, or
1404``@selector`` expression for any of the following selectors:
1405
1406* ``autorelease``
1407* ``release``
1408* ``retain``
1409* ``retainCount``
1410
1411.. admonition:: Rationale
1412
1413 ``retainCount`` is banned because ARC robs it of consistent semantics. The
1414 others were banned after weighing three options for how to deal with message
1415 sends:
1416
1417 **Honoring** them would work out very poorly if a programmer naively or
1418 accidentally tried to incorporate code written for manual retain/release code
1419 into an ARC program. At best, such code would do twice as much work as
1420 necessary; quite frequently, however, ARC and the explicit code would both
1421 try to balance the same retain, leading to crashes. The cost is losing the
1422 ability to perform "unrooted" retains, i.e. retains not logically
1423 corresponding to a strong reference in the object graph.
1424
1425 **Ignoring** them would badly violate user expectations about their code.
1426 While it *would* make it easier to develop code simultaneously for ARC and
1427 non-ARC, there is very little reason to do so except for certain library
1428 developers. ARC and non-ARC translation units share an execution model and
1429 can seamlessly interoperate. Within a translation unit, a developer who
1430 faithfully maintains their code in non-ARC mode is suffering all the
1431 restrictions of ARC for zero benefit, while a developer who isn't testing the
1432 non-ARC mode is likely to be unpleasantly surprised if they try to go back to
1433 it.
1434
1435 **Banning** them has the disadvantage of making it very awkward to migrate
1436 existing code to ARC. The best answer to that, given a number of other
1437 changes and restrictions in ARC, is to provide a specialized tool to assist
1438 users in that migration.
1439
1440 Implementing these methods was banned because they are too integral to the
1441 semantics of ARC; many tricks which worked tolerably under manual reference
1442 counting will misbehave if ARC performs an ephemeral extra retain or two. If
1443 absolutely required, it is still possible to implement them in non-ARC code,
1444 for example in a category; the implementations must obey the :ref:`semantics
1445 <arc.objects.retains>` laid out elsewhere in this document.
1446
1447.. _arc.misc.special_methods.dealloc:
1448
1449``dealloc``
Sean Silvab34b8052012-12-16 00:23:40 +00001450^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001451
1452A program is ill-formed if it contains a message send or ``@selector``
1453expression for the selector ``dealloc``.
1454
1455.. admonition:: Rationale
1456
1457 There are no legitimate reasons to call ``dealloc`` directly.
1458
1459A class may provide a method definition for an instance method named
1460``dealloc``. This method will be called after the final ``release`` of the
1461object but before it is deallocated or any of its instance variables are
1462destroyed. The superclass's implementation of ``dealloc`` will be called
1463automatically when the method returns.
1464
1465.. admonition:: Rationale
1466
1467 Even though ARC destroys instance variables automatically, there are still
1468 legitimate reasons to write a ``dealloc`` method, such as freeing
1469 non-retainable resources. Failing to call ``[super dealloc]`` in such a
1470 method is nearly always a bug. Sometimes, the object is simply trying to
1471 prevent itself from being destroyed, but ``dealloc`` is really far too late
1472 for the object to be raising such objections. Somewhat more legitimately, an
1473 object may have been pool-allocated and should not be deallocated with
1474 ``free``; for now, this can only be supported with a ``dealloc``
1475 implementation outside of ARC. Such an implementation must be very careful
1476 to do all the other work that ``NSObject``'s ``dealloc`` would, which is
1477 outside the scope of this document to describe.
1478
1479The instance variables for an ARC-compiled class will be destroyed at some
1480point after control enters the ``dealloc`` method for the root class of the
1481class. The ordering of the destruction of instance variables is unspecified,
1482both within a single class and between subclasses and superclasses.
1483
1484.. admonition:: Rationale
1485
1486 The traditional, non-ARC pattern for destroying instance variables is to
1487 destroy them immediately before calling ``[super dealloc]``. Unfortunately,
1488 message sends from the superclass are quite capable of reaching methods in
1489 the subclass, and those methods may well read or write to those instance
1490 variables. Making such message sends from dealloc is generally discouraged,
1491 since the subclass may well rely on other invariants that were broken during
1492 ``dealloc``, but it's not so inescapably dangerous that we felt comfortable
1493 calling it undefined behavior. Therefore we chose to delay destroying the
1494 instance variables to a point at which message sends are clearly disallowed:
1495 the point at which the root class's deallocation routines take over.
1496
1497 In most code, the difference is not observable. It can, however, be observed
1498 if an instance variable holds a strong reference to an object whose
1499 deallocation will trigger a side-effect which must be carefully ordered with
1500 respect to the destruction of the super class. Such code violates the design
1501 principle that semantically important behavior should be explicit. A simple
1502 fix is to clear the instance variable manually during ``dealloc``; a more
1503 holistic solution is to move semantically important side-effects out of
1504 ``dealloc`` and into a separate teardown phase which can rely on working with
1505 well-formed objects.
1506
1507.. _arc.misc.autoreleasepool:
1508
1509``@autoreleasepool``
Sean Silvab34b8052012-12-16 00:23:40 +00001510--------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001511
1512To simplify the use of autorelease pools, and to bring them under the control
1513of the compiler, a new kind of statement is available in Objective-C. It is
1514written ``@autoreleasepool`` followed by a *compound-statement*, i.e. by a new
1515scope delimited by curly braces. Upon entry to this block, the current state
1516of the autorelease pool is captured. When the block is exited normally,
1517whether by fallthrough or directed control flow (such as ``return`` or
1518``break``), the autorelease pool is restored to the saved state, releasing all
1519the objects in it. When the block is exited with an exception, the pool is not
1520drained.
1521
1522``@autoreleasepool`` may be used in non-ARC translation units, with equivalent
1523semantics.
1524
1525A program is ill-formed if it refers to the ``NSAutoreleasePool`` class.
1526
1527.. admonition:: Rationale
1528
1529 Autorelease pools are clearly important for the compiler to reason about, but
1530 it is far too much to expect the compiler to accurately reason about control
1531 dependencies between two calls. It is also very easy to accidentally forget
1532 to drain an autorelease pool when using the manual API, and this can
1533 significantly inflate the process's high-water-mark. The introduction of a
1534 new scope is unfortunate but basically required for sane interaction with the
1535 rest of the language. Not draining the pool during an unwind is apparently
1536 required by the Objective-C exceptions implementation.
1537
1538.. _arc.misc.self:
1539
1540``self``
Sean Silvab34b8052012-12-16 00:23:40 +00001541--------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001542
1543The ``self`` parameter variable of an Objective-C method is never actually
1544retained by the implementation. It is undefined behavior, or at least
1545dangerous, to cause an object to be deallocated during a message send to that
1546object.
1547
1548To make this safe, for Objective-C instance methods ``self`` is implicitly
1549``const`` unless the method is in the :ref:`init family
1550<arc.family.semantics.init>`. Further, ``self`` is **always** implicitly
1551``const`` within a class method.
1552
1553.. admonition:: Rationale
1554
1555 The cost of retaining ``self`` in all methods was found to be prohibitive, as
1556 it tends to be live across calls, preventing the optimizer from proving that
1557 the retain and release are unnecessary --- for good reason, as it's quite
1558 possible in theory to cause an object to be deallocated during its execution
1559 without this retain and release. Since it's extremely uncommon to actually
1560 do so, even unintentionally, and since there's no natural way for the
1561 programmer to remove this retain/release pair otherwise (as there is for
1562 other parameters by, say, making the variable ``__unsafe_unretained``), we
1563 chose to make this optimizing assumption and shift some amount of risk to the
1564 user.
1565
1566.. _arc.misc.enumeration:
1567
1568Fast enumeration iteration variables
Sean Silvab34b8052012-12-16 00:23:40 +00001569------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001570
1571If a variable is declared in the condition of an Objective-C fast enumeration
1572loop, and the variable has no explicit ownership qualifier, then it is
1573qualified with ``const __strong`` and objects encountered during the
1574enumeration are not actually retained.
1575
1576.. admonition:: Rationale
1577
1578 This is an optimization made possible because fast enumeration loops promise
1579 to keep the objects retained during enumeration, and the collection itself
1580 cannot be synchronously modified. It can be overridden by explicitly
1581 qualifying the variable with ``__strong``, which will make the variable
1582 mutable again and cause the loop to retain the objects it encounters.
1583
1584.. _arc.misc.blocks:
1585
1586Blocks
Sean Silvab34b8052012-12-16 00:23:40 +00001587------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001588
1589The implicit ``const`` capture variables created when evaluating a block
1590literal expression have the same ownership semantics as the local variables
1591they capture. The capture is performed by reading from the captured variable
1592and initializing the capture variable with that value; the capture variable is
1593destroyed when the block literal is, i.e. at the end of the enclosing scope.
1594
1595The :ref:`inference <arc.ownership.inference>` rules apply equally to
1596``__block`` variables, which is a shift in semantics from non-ARC, where
1597``__block`` variables did not implicitly retain during capture.
1598
1599``__block`` variables of retainable object owner type are moved off the stack
1600by initializing the heap copy with the result of moving from the stack copy.
1601
1602With the exception of retains done as part of initializing a ``__strong``
1603parameter variable or reading a ``__weak`` variable, whenever these semantics
1604call for retaining a value of block-pointer type, it has the effect of a
1605``Block_copy``. The optimizer may remove such copies when it sees that the
1606result is used only as an argument to a call.
1607
1608.. _arc.misc.exceptions:
1609
1610Exceptions
Sean Silvab34b8052012-12-16 00:23:40 +00001611----------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001612
1613By default in Objective C, ARC is not exception-safe for normal releases:
1614
1615* It does not end the lifetime of ``__strong`` variables when their scopes are
1616 abnormally terminated by an exception.
1617* It does not perform releases which would occur at the end of a
1618 full-expression if that full-expression throws an exception.
1619
1620A program may be compiled with the option ``-fobjc-arc-exceptions`` in order to
1621enable these, or with the option ``-fno-objc-arc-exceptions`` to explicitly
1622disable them, with the last such argument "winning".
1623
1624.. admonition:: Rationale
1625
1626 The standard Cocoa convention is that exceptions signal programmer error and
1627 are not intended to be recovered from. Making code exceptions-safe by
1628 default would impose severe runtime and code size penalties on code that
1629 typically does not actually care about exceptions safety. Therefore,
1630 ARC-generated code leaks by default on exceptions, which is just fine if the
1631 process is going to be immediately terminated anyway. Programs which do care
1632 about recovering from exceptions should enable the option.
1633
1634In Objective-C++, ``-fobjc-arc-exceptions`` is enabled by default.
1635
1636.. admonition:: Rationale
1637
1638 C++ already introduces pervasive exceptions-cleanup code of the sort that ARC
1639 introduces. C++ programmers who have not already disabled exceptions are
1640 much more likely to actual require exception-safety.
1641
1642ARC does end the lifetimes of ``__weak`` objects when an exception terminates
1643their scope unless exceptions are disabled in the compiler.
1644
1645.. admonition:: Rationale
1646
1647 The consequence of a local ``__weak`` object not being destroyed is very
1648 likely to be corruption of the Objective-C runtime, so we want to be safer
1649 here. Of course, potentially massive leaks are about as likely to take down
1650 the process as this corruption is if the program does try to recover from
1651 exceptions.
1652
1653.. _arc.misc.interior:
1654
1655Interior pointers
Sean Silvab34b8052012-12-16 00:23:40 +00001656-----------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001657
1658An Objective-C method returning a non-retainable pointer may be annotated with
1659the ``objc_returns_inner_pointer`` attribute to indicate that it returns a
1660handle to the internal data of an object, and that this reference will be
1661invalidated if the object is destroyed. When such a message is sent to an
1662object, the object's lifetime will be extended until at least the earliest of:
1663
1664* the last use of the returned pointer, or any pointer derived from it, in the
1665 calling function or
1666* the autorelease pool is restored to a previous state.
1667
1668.. admonition:: Rationale
1669
1670 Rationale: not all memory and resources are managed with reference counts; it
1671 is common for objects to manage private resources in their own, private way.
1672 Typically these resources are completely encapsulated within the object, but
1673 some classes offer their users direct access for efficiency. If ARC is not
1674 aware of methods that return such "interior" pointers, its optimizations can
1675 cause the owning object to be reclaimed too soon. This attribute informs ARC
1676 that it must tread lightly.
1677
1678 The extension rules are somewhat intentionally vague. The autorelease pool
1679 limit is there to permit a simple implementation to simply retain and
1680 autorelease the receiver. The other limit permits some amount of
1681 optimization. The phrase "derived from" is intended to encompass the results
1682 both of pointer transformations, such as casts and arithmetic, and of loading
1683 from such derived pointers; furthermore, it applies whether or not such
1684 derivations are applied directly in the calling code or by other utility code
1685 (for example, the C library routine ``strchr``). However, the implementation
1686 never need account for uses after a return from the code which calls the
1687 method returning an interior pointer.
1688
1689As an exception, no extension is required if the receiver is loaded directly
1690from a ``__strong`` object with :ref:`precise lifetime semantics
1691<arc.optimization.precise>`.
1692
1693.. admonition:: Rationale
1694
1695 Implicit autoreleases carry the risk of significantly inflating memory use,
1696 so it's important to provide users a way of avoiding these autoreleases.
1697 Tying this to precise lifetime semantics is ideal, as for local variables
1698 this requires a very explicit annotation, which allows ARC to trust the user
1699 with good cheer.
1700
1701.. _arc.misc.c-retainable:
1702
1703C retainable pointer types
Sean Silvab34b8052012-12-16 00:23:40 +00001704--------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001705
Michael Gottesman080dc522013-01-08 23:55:10 +00001706A type is a :arc-term:`C retainable pointer type` if it is a pointer to
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001707(possibly qualified) ``void`` or a pointer to a (possibly qualifier) ``struct``
1708or ``class`` type.
1709
1710.. admonition:: Rationale
1711
1712 ARC does not manage pointers of CoreFoundation type (or any of the related
1713 families of retainable C pointers which interoperate with Objective-C for
1714 retain/release operation). In fact, ARC does not even know how to
1715 distinguish these types from arbitrary C pointer types. The intent of this
1716 concept is to filter out some obviously non-object types while leaving a hook
1717 for later tightening if a means of exhaustively marking CF types is made
1718 available.
1719
1720.. _arc.misc.c-retainable.audit:
1721
1722Auditing of C retainable pointer interfaces
Sean Silvab34b8052012-12-16 00:23:40 +00001723^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001724
1725:when-revised:`[beginning Apple 4.0, LLVM 3.1]`
1726
1727A C function may be marked with the ``cf_audited_transfer`` attribute to
1728express that, except as otherwise marked with attributes, it obeys the
1729parameter (consuming vs. non-consuming) and return (retained vs. non-retained)
1730conventions for a C function of its name, namely:
1731
1732* A parameter of C retainable pointer type is assumed to not be consumed
1733 unless it is marked with the ``cf_consumed`` attribute, and
1734* A result of C retainable pointer type is assumed to not be returned retained
1735 unless the function is either marked ``cf_returns_retained`` or it follows
1736 the create/copy naming convention and is not marked
1737 ``cf_returns_not_retained``.
1738
1739A function obeys the :arc-term:`create/copy` naming convention if its name
1740contains as a substring:
1741
1742* either "Create" or "Copy" not followed by a lowercase letter, or
1743* either "create" or "copy" not followed by a lowercase letter and
1744 not preceded by any letter, whether uppercase or lowercase.
1745
1746A second attribute, ``cf_unknown_transfer``, signifies that a function's
1747transfer semantics cannot be accurately captured using any of these
1748annotations. A program is ill-formed if it annotates the same function with
1749both ``cf_audited_transfer`` and ``cf_unknown_transfer``.
1750
1751A pragma is provided to facilitate the mass annotation of interfaces:
1752
1753.. code-block:: objc
1754
1755 #pragma clang arc_cf_code_audited begin
1756 ...
1757 #pragma clang arc_cf_code_audited end
1758
1759All C functions declared within the extent of this pragma are treated as if
1760annotated with the ``cf_audited_transfer`` attribute unless they otherwise have
1761the ``cf_unknown_transfer`` attribute. The pragma is accepted in all language
1762modes. A program is ill-formed if it attempts to change files, whether by
1763including a file or ending the current file, within the extent of this pragma.
1764
1765It is possible to test for all the features in this section with
1766``__has_feature(arc_cf_code_audited)``.
1767
1768.. admonition:: Rationale
1769
1770 A significant inconvenience in ARC programming is the necessity of
1771 interacting with APIs based around C retainable pointers. These features are
1772 designed to make it relatively easy for API authors to quickly review and
1773 annotate their interfaces, in turn improving the fidelity of tools such as
1774 the static analyzer and ARC. The single-file restriction on the pragma is
1775 designed to eliminate the risk of accidentally annotating some other header's
1776 interfaces.
1777
1778.. _arc.runtime:
1779
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001780Runtime support
1781===============
1782
1783This section describes the interaction between the ARC runtime and the code
1784generated by the ARC compiler. This is not part of the ARC language
1785specification; instead, it is effectively a language-specific ABI supplement,
1786akin to the "Itanium" generic ABI for C++.
1787
1788Ownership qualification does not alter the storage requirements for objects,
1789except that it is undefined behavior if a ``__weak`` object is inadequately
1790aligned for an object of type ``id``. The other qualifiers may be used on
1791explicitly under-aligned memory.
1792
1793The runtime tracks ``__weak`` objects which holds non-null values. It is
1794undefined behavior to direct modify a ``__weak`` object which is being tracked
1795by the runtime except through an
1796:ref:`objc_storeWeak <arc.runtime.objc_storeWeak>`,
1797:ref:`objc_destroyWeak <arc.runtime.objc_destroyWeak>`, or
1798:ref:`objc_moveWeak <arc.runtime.objc_moveWeak>` call.
1799
1800The runtime must provide a number of new entrypoints which the compiler may
1801emit, which are described in the remainder of this section.
1802
1803.. admonition:: Rationale
1804
1805 Several of these functions are semantically equivalent to a message send; we
1806 emit calls to C functions instead because:
1807
1808 * the machine code to do so is significantly smaller,
1809 * it is much easier to recognize the C functions in the ARC optimizer, and
1810 * a sufficient sophisticated runtime may be able to avoid the message send in
1811 common cases.
1812
1813 Several other of these functions are "fused" operations which can be
1814 described entirely in terms of other operations. We use the fused operations
1815 primarily as a code-size optimization, although in some cases there is also a
1816 real potential for avoiding redundant operations in the runtime.
1817
1818.. _arc.runtime.objc_autorelease:
1819
1820``id objc_autorelease(id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00001821----------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001822
1823*Precondition:* ``value`` is null or a pointer to a valid object.
1824
1825If ``value`` is null, this call has no effect. Otherwise, it adds the object
1826to the innermost autorelease pool exactly as if the object had been sent the
1827``autorelease`` message.
1828
1829Always returns ``value``.
1830
1831.. _arc.runtime.objc_autoreleasePoolPop:
1832
1833``void objc_autoreleasePoolPop(void *pool);``
Sean Silvab34b8052012-12-16 00:23:40 +00001834---------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001835
1836*Precondition:* ``pool`` is the result of a previous call to
1837:ref:`objc_autoreleasePoolPush <arc.runtime.objc_autoreleasePoolPush>` on the
1838current thread, where neither ``pool`` nor any enclosing pool have previously
1839been popped.
1840
1841Releases all the objects added to the given autorelease pool and any
1842autorelease pools it encloses, then sets the current autorelease pool to the
1843pool directly enclosing ``pool``.
1844
1845.. _arc.runtime.objc_autoreleasePoolPush:
1846
1847``void *objc_autoreleasePoolPush(void);``
Sean Silvab34b8052012-12-16 00:23:40 +00001848-----------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001849
1850Creates a new autorelease pool that is enclosed by the current pool, makes that
1851the current pool, and returns an opaque "handle" to it.
1852
1853.. admonition:: Rationale
1854
1855 While the interface is described as an explicit hierarchy of pools, the rules
1856 allow the implementation to just keep a stack of objects, using the stack
1857 depth as the opaque pool handle.
1858
1859.. _arc.runtime.objc_autoreleaseReturnValue:
1860
1861``id objc_autoreleaseReturnValue(id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00001862---------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001863
1864*Precondition:* ``value`` is null or a pointer to a valid object.
1865
1866If ``value`` is null, this call has no effect. Otherwise, it makes a best
1867effort to hand off ownership of a retain count on the object to a call to
1868:ref:`objc_retainAutoreleasedReturnValue
1869<arc.runtime.objc_retainAutoreleasedReturnValue>` for the same object in an
1870enclosing call frame. If this is not possible, the object is autoreleased as
1871above.
1872
1873Always returns ``value``.
1874
1875.. _arc.runtime.objc_copyWeak:
1876
1877``void objc_copyWeak(id *dest, id *src);``
Sean Silvab34b8052012-12-16 00:23:40 +00001878------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001879
1880*Precondition:* ``src`` is a valid pointer which either contains a null pointer
1881or has been registered as a ``__weak`` object. ``dest`` is a valid pointer
1882which has not been registered as a ``__weak`` object.
1883
1884``dest`` is initialized to be equivalent to ``src``, potentially registering it
1885with the runtime. Equivalent to the following code:
1886
1887.. code-block:: objc
1888
1889 void objc_copyWeak(id *dest, id *src) {
1890 objc_release(objc_initWeak(dest, objc_loadWeakRetained(src)));
1891 }
1892
1893Must be atomic with respect to calls to ``objc_storeWeak`` on ``src``.
1894
1895.. _arc.runtime.objc_destroyWeak:
1896
1897``void objc_destroyWeak(id *object);``
Sean Silvab34b8052012-12-16 00:23:40 +00001898--------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001899
1900*Precondition:* ``object`` is a valid pointer which either contains a null
1901pointer or has been registered as a ``__weak`` object.
1902
1903``object`` is unregistered as a weak object, if it ever was. The current value
1904of ``object`` is left unspecified; otherwise, equivalent to the following code:
1905
1906.. code-block:: objc
1907
1908 void objc_destroyWeak(id *object) {
1909 objc_storeWeak(object, nil);
1910 }
1911
1912Does not need to be atomic with respect to calls to ``objc_storeWeak`` on
1913``object``.
1914
1915.. _arc.runtime.objc_initWeak:
1916
1917``id objc_initWeak(id *object, id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00001918-------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001919
1920*Precondition:* ``object`` is a valid pointer which has not been registered as
1921a ``__weak`` object. ``value`` is null or a pointer to a valid object.
1922
1923If ``value`` is a null pointer or the object to which it points has begun
1924deallocation, ``object`` is zero-initialized. Otherwise, ``object`` is
1925registered as a ``__weak`` object pointing to ``value``. Equivalent to the
1926following code:
1927
1928.. code-block:: objc
1929
1930 id objc_initWeak(id *object, id value) {
1931 *object = nil;
1932 return objc_storeWeak(object, value);
1933 }
1934
1935Returns the value of ``object`` after the call.
1936
1937Does not need to be atomic with respect to calls to ``objc_storeWeak`` on
1938``object``.
1939
1940.. _arc.runtime.objc_loadWeak:
1941
1942``id objc_loadWeak(id *object);``
Sean Silvab34b8052012-12-16 00:23:40 +00001943---------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001944
1945*Precondition:* ``object`` is a valid pointer which either contains a null
1946pointer or has been registered as a ``__weak`` object.
1947
1948If ``object`` is registered as a ``__weak`` object, and the last value stored
1949into ``object`` has not yet been deallocated or begun deallocation, retains and
1950autoreleases that value and returns it. Otherwise returns null. Equivalent to
1951the following code:
1952
1953.. code-block:: objc
1954
1955 id objc_loadWeak(id *object) {
1956 return objc_autorelease(objc_loadWeakRetained(object));
1957 }
1958
1959Must be atomic with respect to calls to ``objc_storeWeak`` on ``object``.
1960
1961.. admonition:: Rationale
1962
1963 Loading weak references would be inherently prone to race conditions without
1964 the retain.
1965
1966.. _arc.runtime.objc_loadWeakRetained:
1967
1968``id objc_loadWeakRetained(id *object);``
Sean Silvab34b8052012-12-16 00:23:40 +00001969-----------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001970
1971*Precondition:* ``object`` is a valid pointer which either contains a null
1972pointer or has been registered as a ``__weak`` object.
1973
1974If ``object`` is registered as a ``__weak`` object, and the last value stored
1975into ``object`` has not yet been deallocated or begun deallocation, retains
1976that value and returns it. Otherwise returns null.
1977
1978Must be atomic with respect to calls to ``objc_storeWeak`` on ``object``.
1979
1980.. _arc.runtime.objc_moveWeak:
1981
1982``void objc_moveWeak(id *dest, id *src);``
Sean Silvab34b8052012-12-16 00:23:40 +00001983------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00001984
1985*Precondition:* ``src`` is a valid pointer which either contains a null pointer
1986or has been registered as a ``__weak`` object. ``dest`` is a valid pointer
1987which has not been registered as a ``__weak`` object.
1988
1989``dest`` is initialized to be equivalent to ``src``, potentially registering it
1990with the runtime. ``src`` may then be left in its original state, in which
1991case this call is equivalent to :ref:`objc_copyWeak
1992<arc.runtime.objc_copyWeak>`, or it may be left as null.
1993
1994Must be atomic with respect to calls to ``objc_storeWeak`` on ``src``.
1995
1996.. _arc.runtime.objc_release:
1997
1998``void objc_release(id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00001999--------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002000
2001*Precondition:* ``value`` is null or a pointer to a valid object.
2002
2003If ``value`` is null, this call has no effect. Otherwise, it performs a
2004release operation exactly as if the object had been sent the ``release``
2005message.
2006
2007.. _arc.runtime.objc_retain:
2008
2009``id objc_retain(id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00002010-----------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002011
2012*Precondition:* ``value`` is null or a pointer to a valid object.
2013
2014If ``value`` is null, this call has no effect. Otherwise, it performs a retain
2015operation exactly as if the object had been sent the ``retain`` message.
2016
2017Always returns ``value``.
2018
2019.. _arc.runtime.objc_retainAutorelease:
2020
2021``id objc_retainAutorelease(id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00002022----------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002023
2024*Precondition:* ``value`` is null or a pointer to a valid object.
2025
2026If ``value`` is null, this call has no effect. Otherwise, it performs a retain
2027operation followed by an autorelease operation. Equivalent to the following
2028code:
2029
2030.. code-block:: objc
2031
2032 id objc_retainAutorelease(id value) {
2033 return objc_autorelease(objc_retain(value));
2034 }
2035
2036Always returns ``value``.
2037
2038.. _arc.runtime.objc_retainAutoreleaseReturnValue:
2039
2040``id objc_retainAutoreleaseReturnValue(id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00002041---------------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002042
2043*Precondition:* ``value`` is null or a pointer to a valid object.
2044
2045If ``value`` is null, this call has no effect. Otherwise, it performs a retain
2046operation followed by the operation described in
2047:ref:`objc_autoreleaseReturnValue <arc.runtime.objc_autoreleaseReturnValue>`.
2048Equivalent to the following code:
2049
2050.. code-block:: objc
2051
2052 id objc_retainAutoreleaseReturnValue(id value) {
2053 return objc_autoreleaseReturnValue(objc_retain(value));
2054 }
2055
2056Always returns ``value``.
2057
2058.. _arc.runtime.objc_retainAutoreleasedReturnValue:
2059
2060``id objc_retainAutoreleasedReturnValue(id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00002061----------------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002062
2063*Precondition:* ``value`` is null or a pointer to a valid object.
2064
2065If ``value`` is null, this call has no effect. Otherwise, it attempts to
2066accept a hand off of a retain count from a call to
2067:ref:`objc_autoreleaseReturnValue <arc.runtime.objc_autoreleaseReturnValue>` on
2068``value`` in a recently-called function or something it calls. If that fails,
2069it performs a retain operation exactly like :ref:`objc_retain
2070<arc.runtime.objc_retain>`.
2071
2072Always returns ``value``.
2073
2074.. _arc.runtime.objc_retainBlock:
2075
2076``id objc_retainBlock(id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00002077----------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002078
2079*Precondition:* ``value`` is null or a pointer to a valid block object.
2080
2081If ``value`` is null, this call has no effect. Otherwise, if the block pointed
2082to by ``value`` is still on the stack, it is copied to the heap and the address
2083of the copy is returned. Otherwise a retain operation is performed on the
2084block exactly as if it had been sent the ``retain`` message.
2085
2086.. _arc.runtime.objc_storeStrong:
2087
2088``id objc_storeStrong(id *object, id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00002089----------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002090
2091*Precondition:* ``object`` is a valid pointer to a ``__strong`` object which is
2092adequately aligned for a pointer. ``value`` is null or a pointer to a valid
2093object.
2094
2095Performs the complete sequence for assigning to a ``__strong`` object of
Michael Gottesman644367c2013-02-22 00:16:48 +00002096non-block type [*]_. Equivalent to the following code:
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002097
2098.. code-block:: objc
2099
2100 id objc_storeStrong(id *object, id value) {
2101 value = [value retain];
2102 id oldValue = *object;
2103 *object = value;
2104 [oldValue release];
2105 return value;
2106 }
2107
2108Always returns ``value``.
2109
Michael Gottesman644367c2013-02-22 00:16:48 +00002110.. [*] This does not imply that a ``__strong`` object of block type is an
2111 invalid argument to this function. Rather it implies that an ``objc_retain``
2112 and not an ``objc_retainBlock`` operation will be emitted if the argument is
2113 a block.
2114
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002115.. _arc.runtime.objc_storeWeak:
2116
2117``id objc_storeWeak(id *object, id value);``
Sean Silvab34b8052012-12-16 00:23:40 +00002118--------------------------------------------
Dmitri Gribenko94b21a12012-12-13 16:04:37 +00002119
2120*Precondition:* ``object`` is a valid pointer which either contains a null
2121pointer or has been registered as a ``__weak`` object. ``value`` is null or a
2122pointer to a valid object.
2123
2124If ``value`` is a null pointer or the object to which it points has begun
2125deallocation, ``object`` is assigned null and unregistered as a ``__weak``
2126object. Otherwise, ``object`` is registered as a ``__weak`` object or has its
2127registration updated to point to ``value``.
2128
2129Returns the value of ``object`` after the call.
2130