blob: ff65f3be48016874b365d1d7c9f7515a997df39d [file] [log] [blame]
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
John McCall82467022011-06-15 21:21:53 +00003<html>
4<head>
5<title>Objective-C Automatic Reference Counting (ARC)</title>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00006<link type="text/css" rel="stylesheet" href="../menu.css">
7<link type="text/css" rel="stylesheet" href="../content.css">
John McCall82467022011-06-15 21:21:53 +00008<style type="text/css">
9/* Collapse the items in the ToC to the left. */
10div#toc ul {
11 padding-left: 0
12}
13
14/* Rationales appear in italic. */
15div.rationale {
16 font-style: italic
17}
18
John McCallf3d08a62011-06-18 07:31:30 +000019div.rationale em {
20 font-style: normal
21}
22
John McCall9da31cb2012-03-27 07:42:12 +000023/* Revisions are also italicized. */
24span.revision {
25 font-style: italic
26}
27
28span.whenRevised {
29 font-weight: bold;
30 font-style: normal
31}
32
John McCall82467022011-06-15 21:21:53 +000033div h1 { font-size: 2em; margin: .67em 0 }
34div div h1 { font-size: 1.5em; margin: .75em 0 }
35div div div h1 { font-size: 1.17em; margin: .83em 0 }
36div div div div h1 { margin: 1.12em 0 }
37
38span.term { font-style: italic; font-weight: bold }
39</style>
40
Benjamin Kramer665a8dc2012-01-15 15:26:07 +000041<script type="text/javascript">
John McCall82467022011-06-15 21:21:53 +000042/// A little script to recursively build a table of contents.
43function buildTOC(div, toc, ancestry) {
44 var children = div.childNodes;
45 var len = children.length;
46
47 var childNumber = 0;
48
49 var list = null;
50 for (var i = 0; i < len; ++i) {
51 var child = children[i];
52 if (child.nodeName != "DIV") continue;
53 if (child.getAttribute("class") == "rationale") continue;
54 if (child.id == "toc") continue;
55
56 // Okay, we're actually going to build a list node.
57 if (list === null) list = document.createElement("ul");
58
59 var childAncestry = ancestry + ++childNumber + ".";
60
61 var headerNode = child.childNodes[1];
62 var title = headerNode.innerHTML;
63 headerNode.insertBefore(document.createTextNode(childAncestry + " "),
64 headerNode.firstChild);
65
66 var item = document.createElement("li");
67 item.appendChild(document.createTextNode(childAncestry + " "));
68
69 var anchor = document.createElement("a");
70 anchor.href = "#" + child.id;
71 anchor.innerHTML = title;
72 item.appendChild(anchor);
73
74 buildTOC(child, item, childAncestry);
75
76 list.appendChild(item);
77 }
78 if (list) toc.appendChild(list);
79}
80
81function onLoad() {
82 var toc = document.getElementById("toc");
83 var content = document.getElementById("content");
84 buildTOC(content, toc, "");
85}
86window.onload = onLoad;
87
88</script>
89</head>
90<body>
91
92<!--#include virtual="../menu.html.incl"-->
93
94<div id="content">
95<h1>Automatic Reference Counting</h1>
96
97<div id="toc">
98</div>
99
100<div id="meta">
101<h1>About this document</h1>
102
103<div id="meta.purpose">
104<h1>Purpose</h1>
105
106<p>The first and primary purpose of this document is to serve as a
107complete technical specification of Automatic Reference Counting.
108Given a core Objective-C compiler and runtime, it should be possible
109to write a compiler and runtime which implements these new
110semantics.</p>
111
112<p>The secondary purpose is to act as a rationale for why ARC was
113designed in this way. This should remain tightly focused on the
114technical design and should not stray into marketing speculation.</p>
115
116</div> <!-- meta.purpose -->
117
118<div id="meta.background">
119<h1>Background</h1>
120
121<p>This document assumes a basic familiarity with C.</p>
122
123<p><span class="term">Blocks</span> are a C language extension for
124creating anonymous functions. Users interact with and transfer block
125objects using <span class="term">block pointers</span>, which are
126represented like a normal pointer. A block may capture values from
127local variables; when this occurs, memory must be dynamically
128allocated. The initial allocation is done on the stack, but the
129runtime provides a <tt>Block_copy</tt> function which, given a block
130pointer, either copies the underlying block object to the heap,
131setting its reference count to 1 and returning the new block pointer,
132or (if the block object is already on the heap) increases its
133reference count by 1. The paired function is <tt>Block_release</tt>,
134which decreases the reference count by 1 and destroys the object if
135the count reaches zero and is on the heap.</p>
136
137<p>Objective-C is a set of language extensions, significant enough to
138be considered a different language. It is a strict superset of C.
139The extensions can also be imposed on C++, producing a language called
140Objective-C++. The primary feature is a single-inheritance object
141system; we briefly describe the modern dialect.</p>
142
143<p>Objective-C defines a new type kind, collectively called
144the <span class="term">object pointer types</span>. This kind has two
145notable builtin members, <tt>id</tt> and <tt>Class</tt>; <tt>id</tt>
146is the final supertype of all object pointers. The validity of
147conversions between object pointer types is not checked at runtime.
148Users may define <span class="term">classes</span>; each class is a
149type, and the pointer to that type is an object pointer type. A class
150may have a superclass; its pointer type is a subtype of its
151superclass's pointer type. A class has a set
152of <span class="term">ivars</span>, fields which appear on all
153instances of that class. For every class <i>T</i> there's an
154associated metaclass; it has no fields, its superclass is the
155metaclass of <i>T</i>'s superclass, and its metaclass is a global
156class. Every class has a global object whose class is the
157class's metaclass; metaclasses have no associated type, so pointers to
158this object have type <tt>Class</tt>.</p>
159
160<p>A class declaration (<tt>@interface</tt>) declares a set
161of <span class="term">methods</span>. A method has a return type, a
162list of argument types, and a <span class="term">selector</span>: a
163name like <tt>foo:bar:baz:</tt>, where the number of colons
164corresponds to the number of formal arguments. A method may be an
165instance method, in which case it can be invoked on objects of the
166class, or a class method, in which case it can be invoked on objects
167of the metaclass. A method may be invoked by providing an object
168(called the <span class="term">receiver</span>) and a list of formal
169arguments interspersed with the selector, like so:</p>
170
171<pre>[receiver foo: fooArg bar: barArg baz: bazArg]</pre>
172
173<p>This looks in the dynamic class of the receiver for a method with
174this name, then in that class's superclass, etc., until it finds
175something it can execute. The receiver <q>expression</q> may also be
176the name of a class, in which case the actual receiver is the class
177object for that class, or (within method definitions) it may
178be <tt>super</tt>, in which case the lookup algorithm starts with the
179static superclass instead of the dynamic class. The actual methods
180dynamically found in a class are not those declared in the
181<tt>@interface</tt>, but those defined in a separate
182<tt>@implementation</tt> declaration; however, when compiling a
183call, typechecking is done based on the methods declared in the
184<tt>@interface</tt>.</p>
185
186<p>Method declarations may also be grouped into
187<span class="term">protocols</span>, which are not inherently
188associated with any class, but which classes may claim to follow.
189Object pointer types may be qualified with additional protocols that
190the object is known to support.</p>
191
192<p><span class="term">Class extensions</span> are collections of ivars
193and methods, designed to allow a class's <tt>@interface</tt> to be
194split across multiple files; however, there is still a primary
195implementation file which must see the <tt>@interface</tt>s of all
196class extensions.
197<span class="term">Categories</span> allow methods (but not ivars) to
198be declared <i>post hoc</i> on an arbitrary class; the methods in the
199category's <tt>@implementation</tt> will be dynamically added to that
200class's method tables which the category is loaded at runtime,
201replacing those methods in case of a collision.</p>
202
203<p>In the standard environment, objects are allocated on the heap, and
204their lifetime is manually managed using a reference count. This is
205done using two instance methods which all classes are expected to
206implement: <tt>retain</tt> increases the object's reference count by
2071, whereas <tt>release</tt> decreases it by 1 and calls the instance
208method <tt>dealloc</tt> if the count reaches 0. To simplify certain
209operations, there is also an <span class="term">autorelease
210pool</span>, a thread-local list of objects to call <tt>release</tt>
211on later; an object can be added to this pool by
212calling <tt>autorelease</tt> on it.</p>
213
214<p>Block pointers may be converted to type <tt>id</tt>; block objects
215are laid out in a way that makes them compatible with Objective-C
216objects. There is a builtin class that all block objects are
217considered to be objects of; this class implements <tt>retain</tt> by
218adjusting the reference count, not by calling <tt>Block_copy</tt>.</p>
219
220</div> <!-- meta.background -->
221
John McCall9da31cb2012-03-27 07:42:12 +0000222<div id="meta.evolution">
223<h1>Evolution</h1>
224
225<p>ARC is under continual evolution, and this document must be updated
226as the language progresses.</p>
227
228<p>If a change increases the expressiveness of the language, for
229example by lifting a restriction or by adding new syntax, the change
230will be annotated with a revision marker, like so:</p>
231
232<blockquote>
233 ARC applies to Objective-C pointer types, block pointer types, and
234 <span class="revision"><span class="whenRevised">[beginning Apple
235 8.0, LLVM 3.8]</span> BPTRs declared within <code>extern
236 "BCPL"</code> blocks</span>.
237</blockquote>
238
239<p>For now, it is sensible to version this document by the releases of
240its sole implementation (and its host project), clang.
241<q>LLVM X.Y</q> refers to an open-source release of clang from the
242LLVM project. <q>Apple X.Y</q> refers to an Apple-provided release of
243the Apple LLVM Compiler. Other organizations that prepare their own,
244separately-versioned clang releases and wish to maintain similar
245information in this document should send requests to cfe-dev.</p>
246
247<p>If a change decreases the expressiveness of the language, for
248example by imposing a new restriction, this should be taken as an
249oversight in the original specification and something to be avoided
250in all versions. Such changes are generally to be avoided.</p>
251
252</div> <!-- meta.evolution -->
253
John McCall82467022011-06-15 21:21:53 +0000254</div> <!-- meta -->
255
256<div id="general">
257<h1>General</h1>
258
259<p>Automatic Reference Counting implements automatic memory management
260for Objective-C objects and blocks, freeing the programmer from the
John McCall9da31cb2012-03-27 07:42:12 +0000261need to explicitly insert retains and releases. It does not provide a
262cycle collector; users must explicitly manage the lifetime of their
263objects, breaking cycles manually or with weak or unsafe
264references.</p>
John McCall82467022011-06-15 21:21:53 +0000265
266<p>ARC may be explicitly enabled with the compiler
267flag <tt>-fobjc-arc</tt>. It may also be explicitly disabled with the
268compiler flag <tt>-fno-objc-arc</tt>. The last of these two flags
269appearing on the compile line <q>wins</q>.</p>
270
271<p>If ARC is enabled, <tt>__has_feature(objc_arc)</tt> will expand to
2721 in the preprocessor. For more information about <tt>__has_feature</tt>,
273see the <a href="LanguageExtensions.html#__has_feature_extension">language
274extensions</a> document.</p>
275
John McCall9da31cb2012-03-27 07:42:12 +0000276</div> <!-- general -->
John McCall82467022011-06-15 21:21:53 +0000277
278<div id="objects">
279<h1>Retainable object pointers</h1>
280
281<p>This section describes retainable object pointers, their basic
282operations, and the restrictions imposed on their use under ARC. Note
283in particular that it covers the rules for pointer <em>values</em>
284(patterns of bits indicating the location of a pointed-to object), not
285pointer
286<em>objects</em> (locations in memory which store pointer values).
287The rules for objects are covered in the next section.</p>
288
289<p>A <span class="term">retainable object pointer</span>
290(or <q>retainable pointer</q>) is a value of
291a <span class="term">retainable object pointer type</span>
292(<q>retainable type</q>). There are three kinds of retainable object
293pointer types:</p>
294<ul>
295<li>block pointers (formed by applying the caret (<tt>^</tt>)
296declarator sigil to a function type)</li>
297<li>Objective-C object pointers (<tt>id</tt>, <tt>Class</tt>, <tt>NSFoo*</tt>, etc.)</li>
298<li>typedefs marked with <tt>__attribute__((NSObject))</tt></li>
299</ul>
300
301<p>Other pointer types, such as <tt>int*</tt> and <tt>CFStringRef</tt>,
302are not subject to ARC's semantics and restrictions.</p>
303
304<div class="rationale">
305
306<p>Rationale: We are not at liberty to require
307all code to be recompiled with ARC; therefore, ARC must interoperate
308with Objective-C code which manages retains and releases manually. In
309general, there are three requirements in order for a
310compiler-supported reference-count system to provide reliable
311interoperation:</p>
312
313<ul>
314<li>The type system must reliably identify which objects are to be
315managed. An <tt>int*</tt> might be a pointer to a <tt>malloc</tt>'ed
316array, or it might be a interior pointer to such an array, or it might
317point to some field or local variable. In contrast, values of the
318retainable object pointer types are never interior.</li>
319<li>The type system must reliably indicate how to
320manage objects of a type. This usually means that the type must imply
321a procedure for incrementing and decrementing retain counts.
322Supporting single-ownership objects requires a lot more explicit
323mediation in the language.</li>
324<li>There must be reliable conventions for whether and
325when <q>ownership</q> is passed between caller and callee, for both
326arguments and return values. Objective-C methods follow such a
327convention very reliably, at least for system libraries on Mac OS X,
328and functions always pass objects at +0. The C-based APIs for Core
329Foundation objects, on the other hand, have much more varied transfer
330semantics.</li>
331</ul>
332</div> <!-- rationale -->
333
334<p>The use of <tt>__attribute__((NSObject))</tt> typedefs is not
335recommended. If it's absolutely necessary to use this attribute, be
336very explicit about using the typedef, and do not assume that it will
337be preserved by language features like <tt>__typeof</tt> and C++
338template argument substitution.</p>
339
340<div class="rationale"><p>Rationale: any compiler operation which
341incidentally strips type <q>sugar</q> from a type will yield a type
342without the attribute, which may result in unexpected
343behavior.</p></div>
344
345<div id="objects.retains">
346<h1>Retain count semantics</h1>
347
348<p>A retainable object pointer is either a <span class="term">null
349pointer</span> or a pointer to a valid object. Furthermore, if it has
350block pointer type and is not <tt>null</tt> then it must actually be a
351pointer to a block object, and if it has <tt>Class</tt> type (possibly
352protocol-qualified) then it must actually be a pointer to a class
353object. Otherwise ARC does not enforce the Objective-C type system as
354long as the implementing methods follow the signature of the static
355type. It is undefined behavior if ARC is exposed to an invalid
356pointer.</p>
357
358<p>For ARC's purposes, a valid object is one with <q>well-behaved</q>
359retaining operations. Specifically, the object must be laid out such
360that the Objective-C message send machinery can successfully send it
361the following messages:</p>
362
363<ul>
364<li><tt>retain</tt>, taking no arguments and returning a pointer to
365the object.</li>
366<li><tt>release</tt>, taking no arguments and returning <tt>void</tt>.</li>
367<li><tt>autorelease</tt>, taking no arguments and returning a pointer
368to the object.</li>
369</ul>
370
371<p>The behavior of these methods is constrained in the following ways.
372The term <span class="term">high-level semantics</span> is an
373intentionally vague term; the intent is that programmers must
374implement these methods in a way such that the compiler, modifying
375code in ways it deems safe according to these constraints, will not
376violate their requirements. For example, if the user puts logging
377statements in <tt>retain</tt>, they should not be surprised if those
378statements are executed more or less often depending on optimization
379settings. These constraints are not exhaustive of the optimization
380opportunities: values held in local variables are subject to
381additional restrictions, described later in this document.</p>
382
383<p>It is undefined behavior if a computation history featuring a send
384of <tt>retain</tt> followed by a send of <tt>release</tt> to the same
385object, with no intervening <tt>release</tt> on that object, is not
386equivalent under the high-level semantics to a computation
387history in which these sends are removed. Note that this implies that
388these methods may not raise exceptions.</p>
389
390<p>It is undefined behavior if a computation history features any use
391whatsoever of an object following the completion of a send
392of <tt>release</tt> that is not preceded by a send of <tt>retain</tt>
393to the same object.</p>
394
395<p>The behavior of <tt>autorelease</tt> must be equivalent to sending
396<tt>release</tt> when one of the autorelease pools currently in scope
397is popped. It may not throw an exception.</p>
398
399<p>When the semantics call for performing one of these operations on a
400retainable object pointer, if that pointer is <tt>null</tt> then the
401effect is a no-op.</p>
402
403<p>All of the semantics described in this document are subject to
404additional <a href="#optimization">optimization rules</a> which permit
405the removal or optimization of operations based on local knowledge of
406data flow. The semantics describe the high-level behaviors that the
407compiler implements, not an exact sequence of operations that a
408program will be compiled into.</p>
409
410</div> <!-- objects.retains -->
411
412<div id="objects.operands">
413<h1>Retainable object pointers as operands and arguments</h1>
414
415<p>In general, ARC does not perform retain or release operations when
416simply using a retainable object pointer as an operand within an
417expression. This includes:</p>
418<ul>
419<li>loading a retainable pointer from an object with non-weak
420<a href="#ownership">ownership</a>,</li>
421<li>passing a retainable pointer as an argument to a function or
422method, and</li>
423<li>receiving a retainable pointer as the result of a function or
424method call.</li>
425</ul>
426
427<div class="rationale"><p>Rationale: while this might seem
428uncontroversial, it is actually unsafe when multiple expressions are
429evaluated in <q>parallel</q>, as with binary operators and calls,
430because (for example) one expression might load from an object while
431another writes to it. However, C and C++ already call this undefined
432behavior because the evaluations are unsequenced, and ARC simply
433exploits that here to avoid needing to retain arguments across a large
434number of calls.</p></div>
435
436<p>The remainder of this section describes exceptions to these rules,
437how those exceptions are detected, and what those exceptions imply
438semantically.</p>
439
440<div id="objects.operands.consumed">
441<h1>Consumed parameters</h1>
442
443<p>A function or method parameter of retainable object pointer type
444may be marked as <span class="term">consumed</span>, signifying that
445the callee expects to take ownership of a +1 retain count. This is
446done by adding the <tt>ns_consumed</tt> attribute to the parameter
447declaration, like so:</p>
448
449<pre>void foo(__attribute((ns_consumed)) id x);
450- (void) foo: (id) __attribute((ns_consumed)) x;</pre>
451
452<p>This attribute is part of the type of the function or method, not
453the type of the parameter. It controls only how the argument is
454passed and received.</p>
455
456<p>When passing such an argument, ARC retains the argument prior to
457making the call.</p>
458
459<p>When receiving such an argument, ARC releases the argument at the
460end of the function, subject to the usual optimizations for local
461values.</p>
462
463<div class="rationale"><p>Rationale: this formalizes direct transfers
464of ownership from a caller to a callee. The most common scenario here
465is passing the <tt>self</tt> parameter to <tt>init</tt>, but it is
466useful to generalize. Typically, local optimization will remove any
467extra retains and releases: on the caller side the retain will be
468merged with a +1 source, and on the callee side the release will be
469rolled into the initialization of the parameter.</p></div>
470
471<p>The implicit <tt>self</tt> parameter of a method may be marked as
472consumed by adding <tt>__attribute__((ns_consumes_self))</tt> to the
John McCallbe16b892011-06-18 08:15:19 +0000473method declaration. Methods in the <tt>init</tt>
474<a href="#family">family</a> are treated as if they were implicitly
475marked with this attribute.</p>
John McCall82467022011-06-15 21:21:53 +0000476
John McCallbe16b892011-06-18 08:15:19 +0000477<p>It is undefined behavior if an Objective-C message send to a method
478with <tt>ns_consumed</tt> parameters (other than self) is made with a
479null receiver. It is undefined behavior if the method to which an
480Objective-C message send statically resolves to has a different set
481of <tt>ns_consumed</tt> parameters than the method it dynamically
482resolves to. It is undefined behavior if a block or function call is
483made through a static type with a different set of <tt>ns_consumed</tt>
484parameters than the implementation of the called block or function.</p>
John McCall82467022011-06-15 21:21:53 +0000485
John McCallbe16b892011-06-18 08:15:19 +0000486<div class="rationale"><p>Rationale: consumed parameters with null
487receiver are a guaranteed leak. Mismatches with consumed parameters
488will cause over-retains or over-releases, depending on the direction.
489The rule about function calls is really just an application of the
490existing C/C++ rule about calling functions through an incompatible
491function type, but it's useful to state it explicitly.</p></div>
John McCall82467022011-06-15 21:21:53 +0000492
John McCall9da31cb2012-03-27 07:42:12 +0000493</div> <!-- objects.operands.consumed -->
John McCall82467022011-06-15 21:21:53 +0000494
John McCall9da31cb2012-03-27 07:42:12 +0000495<div id="objects.operands.retained-returns">
John McCall82467022011-06-15 21:21:53 +0000496<h1>Retained return values</h1>
497
498<p>A function or method which returns a retainable object pointer type
499may be marked as returning a retained value, signifying that the
500caller expects to take ownership of a +1 retain count. This is done
501by adding the <tt>ns_returns_retained</tt> attribute to the function or
502method declaration, like so:</p>
503
504<pre>id foo(void) __attribute((ns_returns_retained));
505- (id) foo __attribute((ns_returns_retained));</pre>
506
507<p>This attribute is part of the type of the function or method.</p>
508
509<p>When returning from such a function or method, ARC retains the
510value at the point of evaluation of the return statement, before
511leaving all local scopes.</p>
512
513<p>When receiving a return result from such a function or method, ARC
514releases the value at the end of the full-expression it is contained
515within, subject to the usual optimizations for local values.</p>
516
517<div class="rationale"><p>Rationale: this formalizes direct transfers of
518ownership from a callee to a caller. The most common scenario this
519models is the retained return from <tt>init</tt>, <tt>alloc</tt>,
520<tt>new</tt>, and <tt>copy</tt> methods, but there are other cases in
521the frameworks. After optimization there are typically no extra
522retains and releases required.</p></div>
523
524<p>Methods in
525the <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>, <tt>mutableCopy</tt>,
526and <tt>new</tt> <a href="#family">families</a> are implicitly marked
527<tt>__attribute__((ns_returns_retained))</tt>. This may be suppressed
528by explicitly marking the
529method <tt>__attribute__((ns_returns_not_retained))</tt>.</p>
John McCall82467022011-06-15 21:21:53 +0000530
John McCallbe16b892011-06-18 08:15:19 +0000531<p>It is undefined behavior if the method to which an Objective-C
532message send statically resolves has different retain semantics on its
533result from the method it dynamically resolves to. It is undefined
534behavior if a block or function call is made through a static type
535with different retain semantics on its result from the implementation
536of the called block or function.</p>
537
538<div class="rationale"><p>Rationale: Mismatches with returned results
539will cause over-retains or over-releases, depending on the direction.
540Again, the rule about function calls is really just an application of
541the existing C/C++ rule about calling functions through an
542incompatible function type.</p></div>
543
John McCall9da31cb2012-03-27 07:42:12 +0000544</div> <!-- objects.operands.retained-returns -->
John McCallbe16b892011-06-18 08:15:19 +0000545
John McCall82467022011-06-15 21:21:53 +0000546<div id="objects.operands.other-returns">
547<h1>Unretained return values</h1>
548
549<p>A method or function which returns a retainable object type but
550does not return a retained value must ensure that the object is
551still valid across the return boundary.</p>
552
553<p>When returning from such a function or method, ARC retains the
554value at the point of evaluation of the return statement, then leaves
555all local scopes, and then balances out the retain while ensuring that
556the value lives across the call boundary. In the worst case, this may
557involve an <tt>autorelease</tt>, but callers must not assume that the
558value is actually in the autorelease pool.</p>
559
560<p>ARC performs no extra mandatory work on the caller side, although
561it may elect to do something to shorten the lifetime of the returned
562value.</p>
563
564<div class="rationale"><p>Rationale: it is common in non-ARC code to not
565return an autoreleased value; therefore the convention does not force
566either path. It is convenient to not be required to do unnecessary
567retains and autoreleases; this permits optimizations such as eliding
568retain/autoreleases when it can be shown that the original pointer
569will still be valid at the point of return.</p></div>
570
571<p>A method or function may be marked
572with <tt>__attribute__((ns_returns_autoreleased))</tt> to indicate
573that it returns a pointer which is guaranteed to be valid at least as
574long as the innermost autorelease pool. There are no additional
575semantics enforced in the definition of such a method; it merely
576enables optimizations in callers.</p>
John McCall9da31cb2012-03-27 07:42:12 +0000577
578</div> <!-- objects.operands.other-returns -->
John McCall82467022011-06-15 21:21:53 +0000579
580<div id="objects.operands.casts">
581<h1>Bridged casts</h1>
582
583<p>A <span class="term">bridged cast</span> is a C-style cast
584annotated with one of three keywords:</p>
585
586<ul>
587<li><tt>(__bridge T) op</tt> casts the operand to the destination
588type <tt>T</tt>. If <tt>T</tt> is a retainable object pointer type,
589then <tt>op</tt> must have a non-retainable pointer type.
590If <tt>T</tt> is a non-retainable pointer type, then <tt>op</tt> must
591have a retainable object pointer type. Otherwise the cast is
592ill-formed. There is no transfer of ownership, and ARC inserts
593no retain operations.</li>
594
595<li><tt>(__bridge_retained T) op</tt> casts the operand, which must
596have retainable object pointer type, to the destination type, which
597must be a non-retainable pointer type. ARC retains the value, subject
598to the usual optimizations on local values, and the recipient is
599responsible for balancing that +1.</li>
600
601<li><tt>(__bridge_transfer T) op</tt> casts the operand, which must
602have non-retainable pointer type, to the destination type, which must
603be a retainable object pointer type. ARC will release the value at
604the end of the enclosing full-expression, subject to the usual
605optimizations on local values.</li>
606</ul>
607
608<p>These casts are required in order to transfer objects in and out of
609ARC control; see the rationale in the section
610on <a href="#objects.restrictions.conversion">conversion of retainable
611object pointers</a>.</p>
612
613<p>Using a <tt>__bridge_retained</tt> or <tt>__bridge_transfer</tt>
614cast purely to convince ARC to emit an unbalanced retain or release,
615respectively, is poor form.</p>
616
John McCall9da31cb2012-03-27 07:42:12 +0000617</div> <!-- objects.operands.casts -->
John McCall82467022011-06-15 21:21:53 +0000618
John McCall9da31cb2012-03-27 07:42:12 +0000619</div> <!-- objects.operands -->
John McCall82467022011-06-15 21:21:53 +0000620
621<div id="objects.restrictions">
622<h1>Restrictions</h1>
623
624<div id="objects.restrictions.conversion">
625<h1>Conversion of retainable object pointers</h1>
626
627<p>In general, a program which attempts to implicitly or explicitly
628convert a value of retainable object pointer type to any
629non-retainable type, or vice-versa, is ill-formed. For example, an
Fariborz Jahaniana26b2e52011-07-06 21:58:44 +0000630Objective-C object pointer shall not be converted to <tt>void*</tt>.
David Blaikie0ff64952011-11-24 00:37:54 +0000631As an exception, cast to <tt>intptr_t</tt> is allowed because such
Fariborz Jahaniana26b2e52011-07-06 21:58:44 +0000632casts are not transferring ownership. The <a href="#objects.operands.casts">bridged
John McCall82467022011-06-15 21:21:53 +0000633casts</a> may be used to perform these conversions where
634necessary.</p>
635
636<div class="rationale"><p>Rationale: we cannot ensure the correct
637management of the lifetime of objects if they may be freely passed
638around as unmanaged types. The bridged casts are provided so that the
639programmer may explicitly describe whether the cast transfers control
640into or out of ARC.</p></div>
John McCall82467022011-06-15 21:21:53 +0000641
John McCall9da31cb2012-03-27 07:42:12 +0000642<p>However, the following exceptions apply.</p>
John McCall82467022011-06-15 21:21:53 +0000643
John McCall9da31cb2012-03-27 07:42:12 +0000644</div> <!-- objects.restrictions.conversion -->
645
646<div id="objects.restrictions.conversion-exception-known">
647<h1>Conversion to retainable object pointer type of
648 expressions with known semantics</h1>
649
650<p><span class="revision"><span class="whenRevised">[beginning Apple
651 4.0, LLVM 3.1]</span> These exceptions have been greatly expanded;
652 they previously applied only to a much-reduced subset which is
653 difficult to categorize but which included null pointers, message
654 sends (under the given rules), and the various global constants.</span></p>
655
656<p>An unbridged conversion to a retainable object pointer type from a
657type other than a retainable object pointer type is ill-formed, as
658discussed above, unless the operand of the cast has a syntactic form
659which is known retained, known unretained, or known
660retain-agnostic.</p>
661
662<p>An expression is <span class="term">known retain-agnostic</span> if
663it is:</p>
John McCall82467022011-06-15 21:21:53 +0000664<ul>
John McCall9da31cb2012-03-27 07:42:12 +0000665<li>an Objective-C string literal,</li>
666<li>a load from a <tt>const</tt> system global variable of
667<a href="#misc.c-retainable">C retainable pointer type</a>, or</li>
668<li>a null pointer constant.</li>
John McCall82467022011-06-15 21:21:53 +0000669</ul>
670
John McCall9da31cb2012-03-27 07:42:12 +0000671<p>An expression is <span class="term">known unretained</span> if it
672is an rvalue of <a href="#misc.c-retainable">C retainable
673pointer type</a> and it is:</p>
674<ul>
675<li>a direct call to a function, and either that function has the
676 <tt>cf_returns_not_retained</tt> attribute or it is an
677 <a href="#misc.c-retainable.audit">audited</a> function that does not
678 have the <tt>cf_returns_retained</tt> attribute and does not follow
679 the create/copy naming convention,</li>
680<li>a message send, and the declared method either has
681 the <tt>cf_returns_not_retained</tt> attribute or it has neither
682 the <tt>cf_returns_retained</tt> attribute nor a
683 <a href="#family">selector family</a> that implies a retained
684 result.</li>
685</ul>
John McCall82467022011-06-15 21:21:53 +0000686
John McCall9da31cb2012-03-27 07:42:12 +0000687<p>An expression is <span class="term">known retained</span> if it is
688an rvalue of <a href="#misc.c-retainable">C retainable pointer type</a>
689and it is:</p>
690<ul>
691<li>a message send, and the declared method either has the
692 <tt>cf_returns_retained</tt> attribute, or it does not have
693 the <tt>cf_returns_not_retained</tt> attribute but it does have a
694 <a href="#family">selector family</a> that implies a retained
695 result.</li>
696</ul>
John McCall82467022011-06-15 21:21:53 +0000697
John McCall9da31cb2012-03-27 07:42:12 +0000698<p>Furthermore:</p>
699<ul>
700<li>a comma expression is classified according to its right-hand side,</li>
701<li>a statement expression is classified according to its result
702expression, if it has one,</li>
703<li>an lvalue-to-rvalue conversion applied to an Objective-C property
704lvalue is classified according to the underlying message send, and</li>
705<li>a conditional operator is classified according to its second and
706third operands, if they agree in classification, or else the other
707if one is known retain-agnostic.</li>
708</ul>
709
710<p>If the cast operand is known retained, the conversion is treated as
711a <tt>__bridge_transfer</tt> cast. If the cast operand is known
712unretained or known retain-agnostic, the conversion is treated as
713a <tt>__bridge</tt> cast.</p>
714
715<div class="rationale"><p>Rationale: Bridging casts are annoying.
716Absent the ability to completely automate the management of CF
717objects, however, we are left with relatively poor attempts to reduce
718the need for a glut of explicit bridges. Hence these rules.</p>
719
720<p>We've so far consciously refrained from implicitly turning retained
721CF results from function calls into <tt>__bridge_transfer</tt> casts.
722The worry is that some code patterns &mdash; for example, creating a
723CF value, assigning it to an ObjC-typed local, and then
724calling <tt>CFRelease</tt> when done &mdash; are a bit too likely to
725be accidentally accepted, leading to mysterious behavior.</p></div>
726
727</div> <!-- objects.restrictions.conversion-exception-known -->
728
729<div id="objects.restrictions.conversion-exception-contextual">
730<h1>Conversion from retainable object pointer type in certain contexts</h1>
731
732<p><span class="revision"><span class="whenRevised">[beginning Apple
733 4.0, LLVM 3.1]</span></span></p>
734
735<p>If an expression of retainable object pointer type is explicitly
736cast to a <a href="#misc.c-retainable">C retainable pointer type</a>,
737the program is ill-formed as discussed above unless the result is
738immediately used:</p>
739
740<ul>
741<li>to initialize a parameter in an Objective-C message send where the
742parameter is not marked with the <tt>cf_consumed</tt> attribute, or</li>
743<li>to initialize a parameter in a direct call to
744an <a href="#misc.c-retainable.audit">audited</a> function where the
745parameter is not marked with the <tt>cf_consumed</tt> attribute.</li>
746</ul>
747
748<div class="rationale"><p>Rationale: Consumed parameters are left out
749because ARC would naturally balance them with a retain, which was
750judged too treacherous. This is in part because several of the most
751common consuming functions are in the <tt>Release</tt> family, and it
752would be quite unfortunate for explicit releases to be silently
753balanced out in this way.</p></div>
754
755</div> <!-- objects.restrictions.conversion-exception-contextual -->
756
757</div> <!-- objects.restrictions -->
758
759</div> <!-- objects -->
John McCall82467022011-06-15 21:21:53 +0000760
761<div id="ownership">
762<h1>Ownership qualification</h1>
763
764<p>This section describes the behavior of <em>objects</em> of
765retainable object pointer type; that is, locations in memory which
766store retainable object pointers.</p>
767
768<p>A type is a <span class="term">retainable object owner type</span>
769if it is a retainable object pointer type or an array type whose
770element type is a retainable object owner type.</p>
771
772<p>An <span class="term">ownership qualifier</span> is a type
Douglas Gregor4020cae2011-06-17 23:16:24 +0000773qualifier which applies only to retainable object owner types. An array type is
774ownership-qualified according to its element type, and adding an ownership
775qualifier to an array type so qualifies its element type.</p>
776
777<p>A program is ill-formed if it attempts to apply an ownership qualifier
John McCall82467022011-06-15 21:21:53 +0000778to a type which is already ownership-qualified, even if it is the same
Douglas Gregor4020cae2011-06-17 23:16:24 +0000779qualifier. There is a single exception to this rule: an ownership qualifier
780may be applied to a substituted template type parameter, which overrides the
781ownership qualifier provided by the template argument.</p>
John McCall82467022011-06-15 21:21:53 +0000782
783<p>Except as described under
784the <a href="#ownership.inference">inference rules</a>, a program is
785ill-formed if it attempts to form a pointer or reference type to a
786retainable object owner type which lacks an ownership qualifier.</p>
787
788<div class="rationale"><p>Rationale: these rules, together with the
789inference rules, ensure that all objects and lvalues of retainable
Douglas Gregor4020cae2011-06-17 23:16:24 +0000790object pointer type have an ownership qualifier. The ability to override an ownership qualifier during template substitution is required to counteract the <a href="#ownership.inference.template_arguments">inference of <tt>__strong</tt> for template type arguments</a>. </p></div>
John McCall82467022011-06-15 21:21:53 +0000791
792<p>There are four ownership qualifiers:</p>
793
794<ul>
795<li><tt>__autoreleasing</tt></li>
796<li><tt>__strong</tt></li>
797<li><tt>__unsafe_unretained</tt></li>
798<li><tt>__weak</tt></li>
799</ul>
800
801<p>A type is <span class="term">nontrivially ownership-qualified</span>
802if it is qualified with <tt>__autoreleasing</tt>, <tt>__strong</tt>, or
803<tt>__weak</tt>.</p>
804
805<div id="ownership.spelling">
806<h1>Spelling</h1>
807
808<p>The names of the ownership qualifiers are reserved for the
809implementation. A program may not assume that they are or are not
810implemented with macros, or what those macros expand to.</p>
811
812<p>An ownership qualifier may be written anywhere that any other type
813qualifier may be written.</p>
814
815<p>If an ownership qualifier appears in
816the <i>declaration-specifiers</i>, the following rules apply:</p>
817
818<ul>
819<li>if the type specifier is a retainable object owner type, the
820qualifier applies to that type;</li>
821<li>if the outermost non-array part of the declarator is a pointer or
822block pointer, the qualifier applies to that type;</li>
823<li>otherwise the program is ill-formed.</li>
824</ul>
825
826<p>If an ownership qualifier appears on the declarator name, or on the
827declared object, it is applied to outermost pointer or block-pointer
828type.</p>
829
830<p>If an ownership qualifier appears anywhere else in a declarator, it
831applies to the type there.</p>
832
John McCall4f264952011-07-13 23:15:32 +0000833<div id="ownership.spelling.property">
834<h1>Property declarations</h1>
835
836<p>A property of retainable object pointer type may have ownership.
837If the property's type is ownership-qualified, then the property has
838that ownership. If the property has one of the following modifiers,
839then the property has the corresponding ownership. A property is
840ill-formed if it has conflicting sources of ownership, or if it has
841redundant ownership modifiers, or if it has <tt>__autoreleasing</tt>
842ownership.</p>
843
844<ul>
845<li><tt>assign</tt> implies <tt>__unsafe_unretained</tt> ownership.</li>
846<li><tt>copy</tt> implies <tt>__strong</tt> ownership, as well as the
847 usual behavior of copy semantics on the setter.</li>
848<li><tt>retain</tt> implies <tt>__strong</tt> ownership.</li>
849<li><tt>strong</tt> implies <tt>__strong</tt> ownership.</li>
850<li><tt>unsafe_unretained</tt> implies <tt>__unsafe_unretained</tt>
851 ownership.</li>
852<li><tt>weak</tt> implies <tt>__weak</tt> ownership.</li>
853</ul>
854
855<p>With the exception of <tt>weak</tt>, these modifiers are available
856in non-ARC modes.</p>
857
858<p>A property's specified ownership is preserved in its metadata, but
859otherwise the meaning is purely conventional unless the property is
860synthesized. If a property is synthesized, then the
861<span class="term">associated instance variable</span> is the
862instance variable which is named, possibly implicitly, by the
863<tt>@synthesize</tt> declaration. If the associated instance variable
864already exists, then its ownership qualification must equal the
865ownership of the property; otherwise, the instance variable is created
866with that ownership qualification.</p>
867
John McCall9da31cb2012-03-27 07:42:12 +0000868<p>A property of retainable object pointer type which is synthesized
869without a source of ownership has the ownership of its associated
870instance variable, if it already exists; otherwise,
871<span class="revision"><span class="whenRevised">[beginning Apple 3.1,
872LLVM 3.1]</span> its ownership is implicitly <tt>strong</tt></span>.
873Prior to this revision, it was ill-formed to synthesize such a
874property.</p>
875
876<div class="rationale"><p>Rationale: using <tt>strong</tt> by default
877is safe and consistent with the generic ARC rule about
878<a href="#ownership.inference.variables">inferring ownership</a>. It
879is, unfortunately, inconsistent with the non-ARC rule which states
880that such properties are implicitly <tt>assign</tt>. However, that
881rule is clearly untenable in ARC, since it leads to default-unsafe
882code. The main merit to banning the properties is to avoid confusion
883with non-ARC practice, which did not ultimately strike us as
884sufficient to justify requiring extra syntax and (more importantly)
885forcing novices to understand ownership rules just to declare a
886property when the default is so reasonable. Changing the rule away
887from non-ARC practice was acceptable because we had conservatively
888banned the synthesis in order to give ourselves exactly this
889leeway.</p></div>
890
John McCall4f264952011-07-13 23:15:32 +0000891</div> <!-- ownership.spelling.property -->
892
John McCall82467022011-06-15 21:21:53 +0000893</div> <!-- ownership.spelling -->
894
895<div id="ownership.semantics">
896<h1>Semantics</h1>
897
898<p>There are five <span class="term">managed operations</span> which
899may be performed on an object of retainable object pointer type. Each
900qualifier specifies different semantics for each of these operations.
901It is still undefined behavior to access an object outside of its
902lifetime.</p>
903
904<p>A load or store with <q>primitive semantics</q> has the same
905semantics as the respective operation would have on an <tt>void*</tt>
906lvalue with the same alignment and non-ownership qualification.</p>
907
908<p><span class="term">Reading</span> occurs when performing a
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000909lvalue-to-rvalue conversion on an object lvalue.</p>
John McCall82467022011-06-15 21:21:53 +0000910
911<ul>
912<li>For <tt>__weak</tt> objects, the current pointee is retained and
913then released at the end of the current full-expression. This must
914execute atomically with respect to assignments and to the final
915release of the pointee.</li>
916<li>For all other objects, the lvalue is loaded with primitive
917semantics.</li>
918</ul>
John McCall82467022011-06-15 21:21:53 +0000919
920<p><span class="term">Assignment</span> occurs when evaluating
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000921an assignment operator. The semantics vary based on the qualification:</p>
John McCall82467022011-06-15 21:21:53 +0000922<ul>
923<li>For <tt>__strong</tt> objects, the new pointee is first retained;
924second, the lvalue is loaded with primitive semantics; third, the new
925pointee is stored into the lvalue with primitive semantics; and
926finally, the old pointee is released. This is not performed
927atomically; external synchronization must be used to make this safe in
928the face of concurrent loads and stores.</li>
929<li>For <tt>__weak</tt> objects, the lvalue is updated to point to the
John McCall9da31cb2012-03-27 07:42:12 +0000930new pointee, unless the new pointee is an object currently undergoing
931deallocation, in which case the lvalue is updated to a null pointer.
932This must execute atomically with respect to other assignments to the
933object, to reads from the object, and to the final release of the new
934pointee.</li>
John McCall82467022011-06-15 21:21:53 +0000935<li>For <tt>__unsafe_unretained</tt> objects, the new pointee is
936stored into the lvalue using primitive semantics.</li>
937<li>For <tt>__autoreleasing</tt> objects, the new pointee is retained,
938autoreleased, and stored into the lvalue using primitive semantics.</li>
939</ul>
John McCall82467022011-06-15 21:21:53 +0000940
941<p><span class="term">Initialization</span> occurs when an object's
942lifetime begins, which depends on its storage duration.
Benjamin Kramer665a8dc2012-01-15 15:26:07 +0000943Initialization proceeds in two stages:</p>
John McCall82467022011-06-15 21:21:53 +0000944<ol>
945<li>First, a null pointer is stored into the lvalue using primitive
946semantics. This step is skipped if the object
947is <tt>__unsafe_unretained</tt>.</li>
948<li>Second, if the object has an initializer, that expression is
949evaluated and then assigned into the object using the usual assignment
950semantics.</li>
951</ol>
John McCall82467022011-06-15 21:21:53 +0000952
953<p><span class="term">Destruction</span> occurs when an object's
954lifetime ends. In all cases it is semantically equivalent to
955assigning a null pointer to the object, with the proviso that of
956course the object cannot be legally read after the object's lifetime
957ends.</p>
958
959<p><span class="term">Moving</span> occurs in specific situations
960where an lvalue is <q>moved from</q>, meaning that its current pointee
961will be used but the object may be left in a different (but still
962valid) state. This arises with <tt>__block</tt> variables and rvalue
963references in C++. For <tt>__strong</tt> lvalues, moving is equivalent
964to loading the lvalue with primitive semantics, writing a null pointer
965to it with primitive semantics, and then releasing the result of the
966load at the end of the current full-expression. For all other
967lvalues, moving is equivalent to reading the object.</p>
968
969</div> <!-- ownership.semantics -->
970
971<div id="ownership.restrictions">
972<h1>Restrictions</h1>
973
John McCall2fad7832011-07-07 00:03:42 +0000974<div id="ownership.restrictions.weak">
975<h1>Weak-unavailable types</h1>
976
977<p>It is explicitly permitted for Objective-C classes to not
978support <tt>__weak</tt> references. It is undefined behavior to
979perform an operation with weak assignment semantics with a pointer to
980an Objective-C object whose class does not support <tt>__weak</tt>
981references.</p>
982
983<div class="rationale"><p>Rationale: historically, it has been
984possible for a class to provide its own reference-count implementation
985by overriding <tt>retain</tt>, <tt>release</tt>, etc. However, weak
986references to an object require coordination with its class's
987reference-count implementation because, among other things, weak loads
988and stores must be atomic with respect to the final release.
989Therefore, existing custom reference-count implementations will
990generally not support weak references without additional effort. This
991is unavoidable without breaking binary compatibility.</p></div>
992
993<p>A class may indicate that it does not support weak references by
994providing the <tt>objc_arc_weak_unavailable</tt> attribute on the
995class's interface declaration. A retainable object pointer type
996is <span class="term">weak-unavailable</span> if is a pointer to an
997(optionally protocol-qualified) Objective-C class <tt>T</tt>
998where <tt>T</tt> or one of its superclasses has
999the <tt>objc_arc_weak_unavailable</tt> attribute. A program is
1000ill-formed if it applies the <tt>__weak</tt> ownership qualifier to a
1001weak-unavailable type or if the value operand of a weak assignment
1002operation has a weak-unavailable type.</p>
1003</div> <!-- ownership.restrictions.weak -->
1004
John McCall82467022011-06-15 21:21:53 +00001005<div id="ownership.restrictions.autoreleasing">
John McCall2fad7832011-07-07 00:03:42 +00001006<h1>Storage duration of <tt>__autoreleasing</tt> objects</h1>
John McCall82467022011-06-15 21:21:53 +00001007
1008<p>A program is ill-formed if it declares an <tt>__autoreleasing</tt>
1009object of non-automatic storage duration.</p>
1010
1011<div class="rationale"><p>Rationale: autorelease pools are tied to the
1012current thread and scope by their nature. While it is possible to
1013have temporary objects whose instance variables are filled with
1014autoreleased objects, there is no way that ARC can provide any sort of
1015safety guarantee there.</p></div>
1016
1017<p>It is undefined behavior if a non-null pointer is assigned to
1018an <tt>__autoreleasing</tt> object while an autorelease pool is in
1019scope and then that object is read after the autorelease pool's scope
1020is left.</p>
1021
1022</div>
1023
1024<div id="ownership.restrictions.conversion.indirect">
1025<h1>Conversion of pointers to ownership-qualified types</h1>
1026
1027<p>A program is ill-formed if an expression of type <tt>T*</tt> is
1028converted, explicitly or implicitly, to the type <tt>U*</tt>,
1029where <tt>T</tt> and <tt>U</tt> have different ownership
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001030qualification, unless:</p>
John McCall82467022011-06-15 21:21:53 +00001031<ul>
1032<li><tt>T</tt> is qualified with <tt>__strong</tt>,
1033 <tt>__autoreleasing</tt>, or <tt>__unsafe_unretained</tt>, and
1034 <tt>U</tt> is qualified with both <tt>const</tt> and
1035 <tt>__unsafe_unretained</tt>; or</li>
1036<li>either <tt>T</tt> or <tt>U</tt> is <tt>cv void</tt>, where
1037<tt>cv</tt> is an optional sequence of non-ownership qualifiers; or</li>
1038<li>the conversion is requested with a <tt>reinterpret_cast</tt> in
1039 Objective-C++; or</li>
1040<li>the conversion is a
1041well-formed <a href="#ownership.restrictions.pass_by_writeback">pass-by-writeback</a>.</li>
1042</ul>
John McCall82467022011-06-15 21:21:53 +00001043
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001044<p>The analogous rule applies to <tt>T&amp;</tt> and <tt>U&amp;</tt> in
John McCall82467022011-06-15 21:21:53 +00001045Objective-C++.</p>
1046
1047<div class="rationale"><p>Rationale: these rules provide a reasonable
1048level of type-safety for indirect pointers, as long as the underlying
1049memory is not deallocated. The conversion to <tt>const
1050__unsafe_unretained</tt> is permitted because the semantics of reads
1051are equivalent across all these ownership semantics, and that's a very
1052useful and common pattern. The interconversion with <tt>void*</tt> is
1053useful for allocating memory or otherwise escaping the type system,
1054but use it carefully. <tt>reinterpret_cast</tt> is considered to be
1055an obvious enough sign of taking responsibility for any
1056problems.</p></div>
1057
1058<p>It is undefined behavior to access an ownership-qualified object
1059through an lvalue of a differently-qualified type, except that any
1060non-<tt>__weak</tt> object may be read through
1061an <tt>__unsafe_unretained</tt> lvalue.</p>
1062
1063<p>It is undefined behavior if a managed operation is performed on
1064a <tt>__strong</tt> or <tt>__weak</tt> object without a guarantee that
1065it contains a primitive zero bit-pattern, or if the storage for such
1066an object is freed or reused without the object being first assigned a
1067null pointer.</p>
1068
1069<div class="rationale"><p>Rationale: ARC cannot differentiate between
1070an assignment operator which is intended to <q>initialize</q> dynamic
1071memory and one which is intended to potentially replace a value.
1072Therefore the object's pointer must be valid before letting ARC at it.
1073Similarly, C and Objective-C do not provide any language hooks for
1074destroying objects held in dynamic memory, so it is the programmer's
1075responsibility to avoid leaks (<tt>__strong</tt> objects) and
1076consistency errors (<tt>__weak</tt> objects).</p>
1077
1078<p>These requirements are followed automatically in Objective-C++ when
1079creating objects of retainable object owner type with <tt>new</tt>
1080or <tt>new[]</tt> and destroying them with <tt>delete</tt>,
1081<tt>delete[]</tt>, or a pseudo-destructor expression. Note that
1082arrays of nontrivially-ownership-qualified type are not ABI compatible
1083with non-ARC code because the element type is non-POD: such arrays
1084that are <tt>new[]</tt>'d in ARC translation units cannot
1085be <tt>delete[]</tt>'d in non-ARC translation units and
1086vice-versa.</p></div>
1087
1088</div>
1089
1090<div id="ownership.restrictions.pass_by_writeback">
1091<h1>Passing to an out parameter by writeback</h1>
1092
1093<p>If the argument passed to a parameter of type
1094<tt>T __autoreleasing *</tt> has type <tt>U oq *</tt>,
1095where <tt>oq</tt> is an ownership qualifier, then the argument is a
1096candidate for <span class="term">pass-by-writeback</span> if:</p>
1097
1098<ul>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001099<li><tt>oq</tt> is <tt>__strong</tt> or <tt>__weak</tt>, and</li>
John McCall82467022011-06-15 21:21:53 +00001100<li>it would be legal to initialize a <tt>T __strong *</tt> with
1101a <tt>U __strong *</tt>.</li>
1102</ul>
1103
1104<p>For purposes of overload resolution, an implicit conversion
1105sequence requiring a pass-by-writeback is always worse than an
1106implicit conversion sequence not requiring a pass-by-writeback.</p>
1107
1108<p>The pass-by-writeback is ill-formed if the argument expression does
1109not have a legal form:</p>
1110
1111<ul>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001112<li><tt>&amp;var</tt>, where <tt>var</tt> is a scalar variable of
John McCall82467022011-06-15 21:21:53 +00001113automatic storage duration with retainable object pointer type</li>
1114<li>a conditional expression where the second and third operands are
1115both legal forms</li>
1116<li>a cast whose operand is a legal form</li>
1117<li>a null pointer constant</li>
1118</ul>
1119
1120<div class="rationale"><p>Rationale: the restriction in the form of
1121the argument serves two purposes. First, it makes it impossible to
1122pass the address of an array to the argument, which serves to protect
1123against an otherwise serious risk of mis-inferring an <q>array</q>
1124argument as an out-parameter. Second, it makes it much less likely
1125that the user will see confusing aliasing problems due to the
1126implementation, below, where their store to the writeback temporary is
1127not immediately seen in the original argument variable.</p></div>
1128
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001129<p>A pass-by-writeback is evaluated as follows:</p>
John McCall82467022011-06-15 21:21:53 +00001130<ol>
1131<li>The argument is evaluated to yield a pointer <tt>p</tt> of
1132 type <tt>U oq *</tt>.</li>
1133<li>If <tt>p</tt> is a null pointer, then a null pointer is passed as
1134 the argument, and no further work is required for the pass-by-writeback.</li>
1135<li>Otherwise, a temporary of type <tt>T __autoreleasing</tt> is
1136 created and initialized to a null pointer.</li>
John McCall9da31cb2012-03-27 07:42:12 +00001137<li>If the parameter is not an Objective-C method parameter marked
John McCall82467022011-06-15 21:21:53 +00001138 <tt>out</tt>, then <tt>*p</tt> is read, and the result is written
1139 into the temporary with primitive semantics.</li>
1140<li>The address of the temporary is passed as the argument to the
1141 actual call.</li>
1142<li>After the call completes, the temporary is loaded with primitive
1143 semantics, and that value is assigned into <tt>*p</tt>.</li>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001144</ol>
John McCall82467022011-06-15 21:21:53 +00001145
1146<div class="rationale"><p>Rationale: this is all admittedly
1147convoluted. In an ideal world, we would see that a local variable is
1148being passed to an out-parameter and retroactively modify its type to
1149be <tt>__autoreleasing</tt> rather than <tt>__strong</tt>. This would
1150be remarkably difficult and not always well-founded under the C type
1151system. However, it was judged unacceptably invasive to require
1152programmers to write <tt>__autoreleasing</tt> on all the variables
1153they intend to use for out-parameters. This was the least bad
1154solution.</p></div>
1155
1156</div>
1157
1158<div id="ownership.restrictions.records">
1159<h1>Ownership-qualified fields of structs and unions</h1>
1160
1161<p>A program is ill-formed if it declares a member of a C struct or
1162union to have a nontrivially ownership-qualified type.</p>
1163
1164<div class="rationale"><p>Rationale: the resulting type would be
1165non-POD in the C++ sense, but C does not give us very good language
1166tools for managing the lifetime of aggregates, so it is more
1167convenient to simply forbid them. It is still possible to manage this
1168with a <tt>void*</tt> or an <tt>__unsafe_unretained</tt>
1169object.</p></div>
1170
1171<p>This restriction does not apply in Objective-C++. However,
David Blaikie5090e9f2011-10-18 05:49:30 +00001172nontrivally ownership-qualified types are considered non-POD: in C++11
John McCall82467022011-06-15 21:21:53 +00001173terms, they are not trivially default constructible, copy
1174constructible, move constructible, copy assignable, move assignable,
John McCall9da31cb2012-03-27 07:42:12 +00001175or destructible. It is a violation of C++'s One Definition Rule to use
1176a class outside of ARC that, under ARC, would have a nontrivially
John McCall82467022011-06-15 21:21:53 +00001177ownership-qualified member.</p>
1178
1179<div class="rationale"><p>Rationale: unlike in C, we can express all
1180the necessary ARC semantics for ownership-qualified subobjects as
1181suboperations of the (default) special member functions for the class.
1182These functions then become non-trivial. This has the non-obvious
John McCall9da31cb2012-03-27 07:42:12 +00001183result that the class will have a non-trivial copy constructor and
1184non-trivial destructor; if this would not normally be true outside of
1185ARC, objects of the type will be passed and returned in an
John McCall82467022011-06-15 21:21:53 +00001186ABI-incompatible manner.</p></div>
1187
1188</div>
1189
1190</div>
1191
1192<div id="ownership.inference">
1193<h1>Ownership inference</h1>
1194
1195<div id="ownership.inference.variables">
1196<h1>Objects</h1>
1197
1198<p>If an object is declared with retainable object owner type, but
1199without an explicit ownership qualifier, its type is implicitly
1200adjusted to have <tt>__strong</tt> qualification.</p>
1201
1202<p>As a special case, if the object's base type is <tt>Class</tt>
1203(possibly protocol-qualified), the type is adjusted to
1204have <tt>__unsafe_unretained</tt> qualification instead.</p>
1205
1206</div>
1207
1208<div id="ownership.inference.indirect_parameters">
1209<h1>Indirect parameters</h1>
1210
1211<p>If a function or method parameter has type <tt>T*</tt>, where
1212<tt>T</tt> is an ownership-unqualified retainable object pointer type,
1213then:</p>
1214
1215<ul>
1216<li>if <tt>T</tt> is <tt>const</tt>-qualified or <tt>Class</tt>, then
1217it is implicitly qualified with <tt>__unsafe_unretained</tt>;</li>
1218<li>otherwise, it is implicitly qualified
1219with <tt>__autoreleasing</tt>.</li>
1220</ul>
John McCall82467022011-06-15 21:21:53 +00001221
1222<div class="rationale"><p>Rationale: <tt>__autoreleasing</tt> exists
1223mostly for this case, the Cocoa convention for out-parameters. Since
1224a pointer to <tt>const</tt> is obviously not an out-parameter, we
1225instead use a type more useful for passing arrays. If the user
1226instead intends to pass in a <em>mutable</em> array, inferring
1227<tt>__autoreleasing</tt> is the wrong thing to do; this directs some
1228of the caution in the following rules about writeback.</p></div>
1229
1230<p>Such a type written anywhere else would be ill-formed by the
1231general rule requiring ownership qualifiers.</p>
1232
1233<p>This rule does not apply in Objective-C++ if a parameter's type is
1234dependent in a template pattern and is only <em>instantiated</em> to
1235a type which would be a pointer to an unqualified retainable object
1236pointer type. Such code is still ill-formed.</p>
1237
1238<div class="rationale"><p>Rationale: the convention is very unlikely
1239to be intentional in template code.</p></div>
1240
1241</div> <!-- ownership.inference.indirect_parameters -->
Douglas Gregore559ca12011-06-17 22:11:49 +00001242
1243<div id="ownership.inference.template_arguments">
1244<h1>Template arguments</h1>
1245
1246<p>If a template argument for a template type parameter is an
1247retainable object owner type that does not have an explicit ownership
1248qualifier, it is adjusted to have <tt>__strong</tt>
Douglas Gregor54fb28a2011-06-17 22:19:27 +00001249qualification. This adjustment occurs regardless of whether the
Douglas Gregore559ca12011-06-17 22:11:49 +00001250template argument was deduced or explicitly specified. </p>
1251
1252<div class="rationale"><p>Rationale: <tt>__strong</tt> is a useful default for containers (e.g., <tt>std::vector&lt;id&gt;</tt>), which would otherwise require explicit qualification. Moreover, unqualified retainable object pointer types are unlikely to be useful within templates, since they generally need to have a qualifier applied to the before being used.</p></div>
1253
1254</div> <!-- ownership.inference.template_arguments -->
John McCall82467022011-06-15 21:21:53 +00001255</div> <!-- ownership.inference -->
1256</div> <!-- ownership -->
1257
Douglas Gregore559ca12011-06-17 22:11:49 +00001258
John McCall82467022011-06-15 21:21:53 +00001259<div id="family">
1260<h1>Method families</h1>
1261
1262<p>An Objective-C method may fall into a <span class="term">method
1263family</span>, which is a conventional set of behaviors ascribed to it
1264by the Cocoa conventions.</p>
1265
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001266<p>A method is in a certain method family if:</p>
John McCall82467022011-06-15 21:21:53 +00001267<ul>
1268<li>it has a <tt>objc_method_family</tt> attribute placing it in that
1269 family; or if not that,</li>
1270<li>it does not have an <tt>objc_method_family</tt> attribute placing
1271 it in a different or no family, and</li>
1272<li>its selector falls into the corresponding selector family, and</li>
1273<li>its signature obeys the added restrictions of the method family.</li>
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001274</ul>
John McCall82467022011-06-15 21:21:53 +00001275
1276<p>A selector is in a certain selector family if, ignoring any leading
1277underscores, the first component of the selector either consists
1278entirely of the name of the method family or it begins with that name
1279followed by a character other than a lowercase letter. For
1280example, <tt>_perform:with:</tt> and <tt>performWith:</tt> would fall
1281into the <tt>perform</tt> family (if we recognized one),
1282but <tt>performing:with</tt> would not.</p>
1283
1284<p>The families and their added restrictions are:</p>
1285
1286<ul>
1287<li><tt>alloc</tt> methods must return a retainable object pointer type.</li>
1288<li><tt>copy</tt> methods must return a retainable object pointer type.</li>
1289<li><tt>mutableCopy</tt> methods must return a retainable object pointer type.</li>
1290<li><tt>new</tt> methods must return a retainable object pointer type.</li>
1291<li><tt>init</tt> methods must be instance methods and must return an
1292Objective-C pointer type. Additionally, a program is ill-formed if it
1293declares or contains a call to an <tt>init</tt> method whose return
1294type is neither <tt>id</tt> nor a pointer to a super-class or
John McCallbe16b892011-06-18 08:15:19 +00001295sub-class of the declaring class (if the method was declared on
1296a class) or the static receiver type of the call (if it was declared
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001297on a protocol).
John McCall82467022011-06-15 21:21:53 +00001298
1299<div class="rationale"><p>Rationale: there are a fair number of existing
1300methods with <tt>init</tt>-like selectors which nonetheless don't
1301follow the <tt>init</tt> conventions. Typically these are either
1302accidental naming collisions or helper methods called during
1303initialization. Because of the peculiar retain/release behavior
1304of <tt>init</tt> methods, it's very important not to treat these
1305methods as <tt>init</tt> methods if they aren't meant to be. It was
1306felt that implicitly defining these methods out of the family based on
1307the exact relationship between the return type and the declaring class
John McCallbe16b892011-06-18 08:15:19 +00001308would be much too subtle and fragile. Therefore we identify a small
John McCall82467022011-06-15 21:21:53 +00001309number of legitimate-seeming return types and call everything else an
1310error. This serves the secondary purpose of encouraging programmers
John McCallbe16b892011-06-18 08:15:19 +00001311not to accidentally give methods names in the <tt>init</tt> family.</p>
1312
1313<p>Note that a method with an <tt>init</tt>-family selector which
1314returns a non-Objective-C type (e.g. <tt>void</tt>) is perfectly
1315well-formed; it simply isn't in the <tt>init</tt> family.</p></div>
John McCall82467022011-06-15 21:21:53 +00001316</li>
1317</ul>
1318
1319<p>A program is ill-formed if a method's declarations,
1320implementations, and overrides do not all have the same method
1321family.</p>
1322
1323<div id="family.attribute">
1324<h1>Explicit method family control</h1>
1325
1326<p>A method may be annotated with the <tt>objc_method_family</tt>
1327attribute to precisely control which method family it belongs to. If
1328a method in an <tt>@implementation</tt> does not have this attribute,
1329but there is a method declared in the corresponding <tt>@interface</tt>
1330that does, then the attribute is copied to the declaration in the
1331<tt>@implementation</tt>. The attribute is available outside of ARC,
1332and may be tested for with the preprocessor query
1333<tt>__has_attribute(objc_method_family)</tt>.</p>
1334
1335<p>The attribute is spelled
1336<tt>__attribute__((objc_method_family(<i>family</i>)))</tt>.
1337If <i>family</i> is <tt>none</tt>, the method has no family, even if
1338it would otherwise be considered to have one based on its selector and
1339type. Otherwise, <i>family</i> must be one
1340of <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>,
1341<tt>mutableCopy</tt>, or <tt>new</tt>, in which case the method is
1342considered to belong to the corresponding family regardless of its
1343selector. It is an error if a method that is explicitly added to a
1344family in this way does not meet the requirements of the family other
1345than the selector naming convention.</p>
1346
1347<div class="rationale"><p>Rationale: the rules codified in this document
1348describe the standard conventions of Objective-C. However, as these
1349conventions have not heretofore been enforced by an unforgiving
1350mechanical system, they are only imperfectly kept, especially as they
1351haven't always even been precisely defined. While it is possible to
1352define low-level ownership semantics with attributes like
1353<tt>ns_returns_retained</tt>, this attribute allows the user to
John McCall9da31cb2012-03-27 07:42:12 +00001354communicate semantic intent, which is of use both to ARC (which, e.g.,
John McCall82467022011-06-15 21:21:53 +00001355treats calls to <tt>init</tt> specially) and the static analyzer.</p></div>
1356</div>
1357
1358<div id="family.semantics">
1359<h1>Semantics of method families</h1>
1360
1361<p>A method's membership in a method family may imply non-standard
1362semantics for its parameters and return type.</p>
1363
1364<p>Methods in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>,
1365and <tt>new</tt> families &mdash; that is, methods in all the
John McCallbe16b892011-06-18 08:15:19 +00001366currently-defined families except <tt>init</tt> &mdash; implicitly
1367<a href="#objects.operands.retained_returns">return a retained
1368object</a> as if they were annotated with
1369the <tt>ns_returns_retained</tt> attribute. This can be overridden by
1370annotating the method with either of
1371the <tt>ns_returns_autoreleased</tt> or
John McCall82467022011-06-15 21:21:53 +00001372<tt>ns_returns_not_retained</tt> attributes.</p>
1373
Fariborz Jahanianacd4aaf2011-07-06 22:47:46 +00001374<p>Properties also follow same naming rules as methods. This means that
1375those in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>,
1376and <tt>new</tt> families provide access to
1377<a href="#objects.operands.retained_returns">retained objects</a>.
1378This can be overridden by annotating the property with
1379<tt>ns_returns_not_retained</tt> attribute.</p>
1380
John McCall82467022011-06-15 21:21:53 +00001381<div id="family.semantics.init">
1382<h1>Semantics of <tt>init</tt></h1>
John McCallbe16b892011-06-18 08:15:19 +00001383<p>Methods in the <tt>init</tt> family implicitly
1384<a href="#objects.operands.consumed">consume</a> their <tt>self</tt>
1385parameter and <a href="#objects.operands.retained_returns">return a
1386retained object</a>. Neither of these properties can be altered
1387through attributes.</p>
John McCall82467022011-06-15 21:21:53 +00001388
1389<p>A call to an <tt>init</tt> method with a receiver that is either
1390<tt>self</tt> (possibly parenthesized or casted) or <tt>super</tt> is
1391called a <span class="term">delegate init call</span>. It is an error
1392for a delegate init call to be made except from an <tt>init</tt>
1393method, and excluding blocks within such methods.</p>
1394
John McCallbe16b892011-06-18 08:15:19 +00001395<p>As an exception to the <a href="misc.self">usual rule</a>, the
1396variable <tt>self</tt> is mutable in an <tt>init</tt> method and has
1397the usual semantics for a <tt>__strong</tt> variable. However, it is
1398undefined behavior and the program is ill-formed, no diagnostic
1399required, if an <tt>init</tt> method attempts to use the previous
1400value of <tt>self</tt> after the completion of a delegate init call.
1401It is conventional, but not required, for an <tt>init</tt> method to
1402return <tt>self</tt>.</p>
John McCall82467022011-06-15 21:21:53 +00001403
John McCallbe16b892011-06-18 08:15:19 +00001404<p>It is undefined behavior for a program to cause two or more calls
1405to <tt>init</tt> methods on the same object, except that
1406each <tt>init</tt> method invocation may perform at most one delegate
1407init call.</p>
John McCall82467022011-06-15 21:21:53 +00001408
John McCallf3d08a62011-06-18 07:31:30 +00001409</div> <!-- family.semantics.init -->
John McCall82467022011-06-15 21:21:53 +00001410
1411<div id="family.semantics.result_type">
1412<h1>Related result types</h1>
1413
1414<p>Certain methods are candidates to have <span class="term">related
1415result types</span>:</p>
1416<ul>
1417<li>class methods in the <tt>alloc</tt> and <tt>new</tt> method families</li>
1418<li>instance methods in the <tt>init</tt> family</li>
1419<li>the instance method <tt>self</tt></li>
1420<li>outside of ARC, the instance methods <tt>retain</tt> and <tt>autorelease</tt></li>
1421</ul>
1422
1423<p>If the formal result type of such a method is <tt>id</tt> or
1424protocol-qualified <tt>id</tt>, or a type equal to the declaring class
1425or a superclass, then it is said to have a related result type. In
1426this case, when invoked in an explicit message send, it is assumed to
1427return a type related to the type of the receiver:</p>
1428
1429<ul>
1430<li>if it is a class method, and the receiver is a class
1431name <tt>T</tt>, the message send expression has type <tt>T*</tt>;
1432otherwise</li>
1433<li>if it is an instance method, and the receiver has type <tt>T</tt>,
1434the message send expression has type <tt>T</tt>; otherwise</li>
1435<li>the message send expression has the normal result type of the
1436method.</li>
1437</ul>
1438
1439<p>This is a new rule of the Objective-C language and applies outside
1440of ARC.</p>
1441
1442<div class="rationale"><p>Rationale: ARC's automatic code emission is
1443more prone than most code to signature errors, i.e. errors where a
1444call was emitted against one method signature, but the implementing
1445method has an incompatible signature. Having more precise type
John McCall9da31cb2012-03-27 07:42:12 +00001446information helps drastically lower this risk, as well as catching
John McCall82467022011-06-15 21:21:53 +00001447a number of latent bugs.</p></div>
1448
1449</div> <!-- family.semantics.result_type -->
1450</div> <!-- family.semantics -->
1451</div> <!-- family -->
1452
1453<div id="optimization">
1454<h1>Optimization</h1>
1455
1456<p>ARC applies aggressive rules for the optimization of local
1457behavior. These rules are based around a core assumption of
1458<span class="term">local balancing</span>: that other code will
1459perform retains and releases as necessary (and only as necessary) for
1460its own safety, and so the optimizer does not need to consider global
1461properties of the retain and release sequence. For example, if a
1462retain and release immediately bracket a call, the optimizer can
1463delete the retain and release on the assumption that the called
1464function will not do a constant number of unmotivated releases
1465followed by a constant number of <q>balancing</q> retains, such that
1466the local retain/release pair is the only thing preventing the called
1467function from ending up with a dangling reference.</p>
1468
1469<p>The optimizer assumes that when a new value enters local control,
1470e.g. from a load of a non-local object or as the result of a function
1471call, it is instaneously valid. Subsequently, a retain and release of
1472a value are necessary on a computation path only if there is a use of
1473that value before the release and after any operation which might
1474cause a release of the value (including indirectly or non-locally),
1475and only if the value is not demonstrably already retained.</p>
1476
1477<p>The complete optimization rules are quite complicated, but it would
1478still be useful to document them here.</p>
1479
John McCalldc7c5ad2011-07-22 08:53:00 +00001480<div id="optimization.precise">
1481<h1>Precise lifetime semantics</h1>
1482
1483<p>In general, ARC maintains an invariant that a retainable object
1484pointer held in a <tt>__strong</tt> object will be retained for the
1485full formal lifetime of the object. Objects subject to this invariant
1486have <span class="term">precise lifetime semantics</span>.</p>
1487
1488<p>By default, local variables of automatic storage duration do not
1489have precise lifetime semantics. Such objects are simply strong
1490references which hold values of retainable object pointer type, and
1491these values are still fully subject to the optimizations on values
1492under local control.</p>
1493
1494<div class="rationale"><p>Rationale: applying these precise-lifetime
1495semantics strictly would be prohibitive. Many useful optimizations
1496that might theoretically decrease the lifetime of an object would be
1497rendered impossible. Essentially, it promises too much.</p></div>
1498
1499<p>A local variable of retainable object owner type and automatic
1500storage duration may be annotated with the <tt>objc_precise_lifetime</tt>
1501attribute to indicate that it should be considered to be an object
1502with precise lifetime semantics.</p>
1503
1504<div class="rationale"><p>Rationale: nonetheless, it is sometimes
1505useful to be able to force an object to be released at a precise time,
1506even if that object does not appear to be used. This is likely to be
1507uncommon enough that the syntactic weight of explicitly requesting
1508these semantics will not be burdensome, and may even make the code
1509clearer.</p></div>
1510
1511</div> <!-- optimization.precise -->
1512
John McCall9da31cb2012-03-27 07:42:12 +00001513</div> <!-- optimization -->
John McCall82467022011-06-15 21:21:53 +00001514
1515<div id="misc">
1516<h1>Miscellaneous</h1>
1517
John McCallf3d08a62011-06-18 07:31:30 +00001518<div id="misc.special_methods">
1519<h1>Special methods</h1>
1520
1521<div id="misc.special_methods.retain">
1522<h1>Memory management methods</h1>
1523
1524<p>A program is ill-formed if it contains a method definition, message
1525send, or <tt>@selector</tt> expression for any of the following
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001526selectors:</p>
John McCallf3d08a62011-06-18 07:31:30 +00001527<ul>
1528<li><tt>autorelease</tt></li>
1529<li><tt>release</tt></li>
1530<li><tt>retain</tt></li>
1531<li><tt>retainCount</tt></li>
1532</ul>
John McCallf3d08a62011-06-18 07:31:30 +00001533
1534<div class="rationale"><p>Rationale: <tt>retainCount</tt> is banned
1535because ARC robs it of consistent semantics. The others were banned
1536after weighing three options for how to deal with message sends:</p>
1537
1538<p><b>Honoring</b> them would work out very poorly if a programmer
1539naively or accidentally tried to incorporate code written for manual
1540retain/release code into an ARC program. At best, such code would do
1541twice as much work as necessary; quite frequently, however, ARC and
1542the explicit code would both try to balance the same retain, leading
1543to crashes. The cost is losing the ability to perform <q>unrooted</q>
1544retains, i.e. retains not logically corresponding to a strong
1545reference in the object graph.</p>
1546
1547<p><b>Ignoring</b> them would badly violate user expectations about their
1548code. While it <em>would</em> make it easier to develop code simultaneously
1549for ARC and non-ARC, there is very little reason to do so except for
1550certain library developers. ARC and non-ARC translation units share
1551an execution model and can seamlessly interoperate. Within a
1552translation unit, a developer who faithfully maintains their code in
1553non-ARC mode is suffering all the restrictions of ARC for zero
1554benefit, while a developer who isn't testing the non-ARC mode is
1555likely to be unpleasantly surprised if they try to go back to it.</p>
1556
1557<p><b>Banning</b> them has the disadvantage of making it very awkward
1558to migrate existing code to ARC. The best answer to that, given a
1559number of other changes and restrictions in ARC, is to provide a
1560specialized tool to assist users in that migration.</p>
1561
1562<p>Implementing these methods was banned because they are too integral
1563to the semantics of ARC; many tricks which worked tolerably under
1564manual reference counting will misbehave if ARC performs an ephemeral
1565extra retain or two. If absolutely required, it is still possible to
1566implement them in non-ARC code, for example in a category; the
1567implementations must obey the <a href="#objects.retains">semantics</a>
1568laid out elsewhere in this document.</p>
1569
1570</div>
1571</div> <!-- misc.special_methods.retain -->
1572
1573<div id="misc.special_methods.dealloc">
1574<h1><tt>dealloc</tt></h1>
1575
1576<p>A program is ill-formed if it contains a message send
1577or <tt>@selector</tt> expression for the selector <tt>dealloc</tt>.</p>
1578
1579<div class="rationale"><p>Rationale: there are no legitimate reasons
1580to call <tt>dealloc</tt> directly.</p></div>
1581
1582<p>A class may provide a method definition for an instance method
1583named <tt>dealloc</tt>. This method will be called after the final
1584<tt>release</tt> of the object but before it is deallocated or any of
1585its instance variables are destroyed. The superclass's implementation
1586of <tt>dealloc</tt> will be called automatically when the method
1587returns.</p>
1588
1589<div class="rationale"><p>Rationale: even though ARC destroys instance
1590variables automatically, there are still legitimate reasons to write
1591a <tt>dealloc</tt> method, such as freeing non-retainable resources.
1592Failing to call <tt>[super&nbsp;dealloc]</tt> in such a method is nearly
1593always a bug. Sometimes, the object is simply trying to prevent
1594itself from being destroyed, but <tt>dealloc</tt> is really far too
1595late for the object to be raising such objections. Somewhat more
1596legitimately, an object may have been pool-allocated and should not be
1597deallocated with <tt>free</tt>; for now, this can only be supported
1598with a <tt>dealloc</tt> implementation outside of ARC. Such an
1599implementation must be very careful to do all the other work
1600that <tt>NSObject</tt>'s <tt>dealloc</tt> would, which is outside the
1601scope of this document to describe.</p></div>
1602
1603</div>
1604
1605</div> <!-- misc.special_methods -->
1606
John McCall82467022011-06-15 21:21:53 +00001607<div id="autoreleasepool">
1608<h1><tt>@autoreleasepool</tt></h1>
1609
1610<p>To simplify the use of autorelease pools, and to bring them under
1611the control of the compiler, a new kind of statement is available in
1612Objective-C. It is written <tt>@autoreleasepool</tt> followed by
1613a <i>compound-statement</i>, i.e. by a new scope delimited by curly
1614braces. Upon entry to this block, the current state of the
1615autorelease pool is captured. When the block is exited normally,
1616whether by fallthrough or directed control flow (such
1617as <tt>return</tt> or <tt>break</tt>), the autorelease pool is
1618restored to the saved state, releasing all the objects in it. When
1619the block is exited with an exception, the pool is not drained.</p>
1620
John McCallf3d08a62011-06-18 07:31:30 +00001621<p><tt>@autoreleasepool</tt> may be used in non-ARC translation units,
1622with equivalent semantics.</p>
1623
John McCall82467022011-06-15 21:21:53 +00001624<p>A program is ill-formed if it refers to the
1625<tt>NSAutoreleasePool</tt> class.</p>
1626
1627<div class="rationale"><p>Rationale: autorelease pools are clearly
1628important for the compiler to reason about, but it is far too much to
1629expect the compiler to accurately reason about control dependencies
1630between two calls. It is also very easy to accidentally forget to
1631drain an autorelease pool when using the manual API, and this can
1632significantly inflate the process's high-water-mark. The introduction
1633of a new scope is unfortunate but basically required for sane
1634interaction with the rest of the language. Not draining the pool
1635during an unwind is apparently required by the Objective-C exceptions
1636implementation.</p></div>
1637
1638</div> <!-- autoreleasepool -->
1639
1640<div id="misc.self">
1641<h1><tt>self</tt></h1>
1642
1643<p>The <tt>self</tt> parameter variable of an Objective-C method is
1644never actually retained by the implementation. It is undefined
1645behavior, or at least dangerous, to cause an object to be deallocated
Ted Kremenek2bbcd5c2011-11-14 21:59:25 +00001646during a message send to that object.</p>
1647
1648<p>To make this safe, for Objective-C instance methods <tt>self</tt> is
1649implicitly <tt>const</tt> unless the method is in the <a
1650href="#family.semantics.init"><tt>init</tt> family</a>. Further, <tt>self</tt>
1651is <b>always</b> implicitly <tt>const</tt> within a class method.</p>
John McCall82467022011-06-15 21:21:53 +00001652
1653<div class="rationale"><p>Rationale: the cost of
1654retaining <tt>self</tt> in all methods was found to be prohibitive, as
1655it tends to be live across calls, preventing the optimizer from
1656proving that the retain and release are unnecessary &mdash; for good
1657reason, as it's quite possible in theory to cause an object to be
1658deallocated during its execution without this retain and release.
1659Since it's extremely uncommon to actually do so, even unintentionally,
1660and since there's no natural way for the programmer to remove this
1661retain/release pair otherwise (as there is for other parameters by,
1662say, making the variable <tt>__unsafe_unretained</tt>), we chose to
1663make this optimizing assumption and shift some amount of risk to the
1664user.</p></div>
1665
1666</div> <!-- misc.self -->
1667
1668<div id="misc.enumeration">
1669<h1>Fast enumeration iteration variables</h1>
1670
1671<p>If a variable is declared in the condition of an Objective-C fast
1672enumeration loop, and the variable has no explicit ownership
1673qualifier, then it is qualified with <tt>const __strong</tt> and
1674objects encountered during the enumeration are not actually
1675retained.</p>
1676
1677<div class="rationale"><p>Rationale: this is an optimization made
1678possible because fast enumeration loops promise to keep the objects
1679retained during enumeration, and the collection itself cannot be
1680synchronously modified. It can be overridden by explicitly qualifying
1681the variable with <tt>__strong</tt>, which will make the variable
1682mutable again and cause the loop to retain the objects it
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001683encounters.</p></div>
John McCall82467022011-06-15 21:21:53 +00001684
John McCall9da31cb2012-03-27 07:42:12 +00001685</div> <!-- misc.enumeration -->
John McCall82467022011-06-15 21:21:53 +00001686
1687<div id="misc.blocks">
1688<h1>Blocks</h1>
1689
1690<p>The implicit <tt>const</tt> capture variables created when
1691evaluating a block literal expression have the same ownership
1692semantics as the local variables they capture. The capture is
1693performed by reading from the captured variable and initializing the
1694capture variable with that value; the capture variable is destroyed
1695when the block literal is, i.e. at the end of the enclosing scope.</p>
1696
1697<p>The <a href="#ownership.inference">inference</a> rules apply
1698equally to <tt>__block</tt> variables, which is a shift in semantics
1699from non-ARC, where <tt>__block</tt> variables did not implicitly
1700retain during capture.</p>
1701
1702<p><tt>__block</tt> variables of retainable object owner type are
1703moved off the stack by initializing the heap copy with the result of
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001704moving from the stack copy.</p>
John McCall82467022011-06-15 21:21:53 +00001705
1706<p>With the exception of retains done as part of initializing
1707a <tt>__strong</tt> parameter variable or reading a <tt>__weak</tt>
1708variable, whenever these semantics call for retaining a value of
1709block-pointer type, it has the effect of a <tt>Block_copy</tt>. The
1710optimizer may remove such copies when it sees that the result is
1711used only as an argument to a call.</p>
1712
1713</div> <!-- misc.blocks -->
1714
1715<div id="misc.exceptions">
1716<h1>Exceptions</h1>
1717
1718<p>By default in Objective C, ARC is not exception-safe for normal
Benjamin Kramer665a8dc2012-01-15 15:26:07 +00001719releases:</p>
John McCall82467022011-06-15 21:21:53 +00001720<ul>
1721<li>It does not end the lifetime of <tt>__strong</tt> variables when
1722their scopes are abnormally terminated by an exception.</li>
1723<li>It does not perform releases which would occur at the end of
1724a full-expression if that full-expression throws an exception.</li>
1725</ul>
1726
1727<p>A program may be compiled with the option
1728<tt>-fobjc-arc-exceptions</tt> in order to enable these, or with the
1729option <tt>-fno-objc-arc-exceptions</tt> to explicitly disable them,
1730with the last such argument <q>winning</q>.</p>
1731
1732<div class="rationale"><p>Rationale: the standard Cocoa convention is
1733that exceptions signal programmer error and are not intended to be
1734recovered from. Making code exceptions-safe by default would impose
1735severe runtime and code size penalties on code that typically does not
1736actually care about exceptions safety. Therefore, ARC-generated code
1737leaks by default on exceptions, which is just fine if the process is
1738going to be immediately terminated anyway. Programs which do care
1739about recovering from exceptions should enable the option.</p></div>
1740
1741<p>In Objective-C++, <tt>-fobjc-arc-exceptions</tt> is enabled by
1742default.</p>
1743
1744<div class="rationale"><p>Rationale: C++ already introduces pervasive
1745exceptions-cleanup code of the sort that ARC introduces. C++
1746programmers who have not already disabled exceptions are much more
1747likely to actual require exception-safety.</p></div>
1748
1749<p>ARC does end the lifetimes of <tt>__weak</tt> objects when an
1750exception terminates their scope unless exceptions are disabled in the
1751compiler.</p>
1752
1753<div class="rationale"><p>Rationale: the consequence of a
1754local <tt>__weak</tt> object not being destroyed is very likely to be
1755corruption of the Objective-C runtime, so we want to be safer here.
1756Of course, potentially massive leaks are about as likely to take down
1757the process as this corruption is if the program does try to recover
1758from exceptions.</p></div>
1759
1760</div> <!-- misc.exceptions -->
1761
John McCalldc7c5ad2011-07-22 08:53:00 +00001762<div id="misc.interior">
1763<h1>Interior pointers</h1>
1764
1765<p>An Objective-C method returning a non-retainable pointer may be
1766annotated with the <tt>objc_returns_inner_pointer</tt> attribute to
1767indicate that it returns a handle to the internal data of an object,
1768and that this reference will be invalidated if the object is
1769destroyed. When such a message is sent to an object, the object's
1770lifetime will be extended until at least the earliest of:</p>
1771
1772<ul>
1773<li>the last use of the returned pointer, or any pointer derived from
1774it, in the calling function or</li>
1775<li>the autorelease pool is restored to a previous state.</li>
1776</ul>
1777
1778<div class="rationale"><p>Rationale: not all memory and resources are
1779managed with reference counts; it is common for objects to manage
1780private resources in their own, private way. Typically these
1781resources are completely encapsulated within the object, but some
1782classes offer their users direct access for efficiency. If ARC is not
1783aware of methods that return such <q>interior</q> pointers, its
1784optimizations can cause the owning object to be reclaimed too soon.
1785This attribute informs ARC that it must tread lightly.</p>
1786
1787<p>The extension rules are somewhat intentionally vague. The
1788autorelease pool limit is there to permit a simple implementation to
1789simply retain and autorelease the receiver. The other limit permits
1790some amount of optimization. The phrase <q>derived from</q> is
1791intended to encompass the results both of pointer transformations,
1792such as casts and arithmetic, and of loading from such derived
1793pointers; furthermore, it applies whether or not such derivations are
1794applied directly in the calling code or by other utility code (for
1795example, the C library routine <tt>strchr</tt>). However, the
1796implementation never need account for uses after a return from the
1797code which calls the method returning an interior pointer.</p></div>
1798
1799<p>As an exception, no extension is required if the receiver is loaded
1800directly from a <tt>__strong</tt> object
1801with <a href="#optimization.precise">precise lifetime semantics</a>.</p>
1802
1803<div class="rationale"><p>Rationale: implicit autoreleases carry the
1804risk of significantly inflating memory use, so it's important to
1805provide users a way of avoiding these autoreleases. Tying this to
1806precise lifetime semantics is ideal, as for local variables this
1807requires a very explicit annotation, which allows ARC to trust the
1808user with good cheer.</p></div>
1809
1810</div> <!-- misc.interior -->
1811
John McCall9da31cb2012-03-27 07:42:12 +00001812<div id="misc.c-retainable">
1813<h1>C retainable pointer types</h1>
1814
1815<p>A type is a <span class="term">C retainable pointer type</span>
1816if it is a pointer to (possibly qualified) <tt>void</tt> or a
1817pointer to a (possibly qualifier) <tt>struct</tt> or <tt>class</tt>
1818type.</p>
1819
1820<div class="rationale"><p>Rationale: ARC does not manage pointers of
1821CoreFoundation type (or any of the related families of retainable C
1822pointers which interoperate with Objective-C for retain/release
1823operation). In fact, ARC does not even know how to distinguish these
1824types from arbitrary C pointer types. The intent of this concept is
1825to filter out some obviously non-object types while leaving a hook for
1826later tightening if a means of exhaustively marking CF types is made
1827available.</p></div>
1828
1829<div id="misc.c-retainable.audit">
1830<h1>Auditing of C retainable pointer interfaces</h1>
1831
1832<p><span class="revision"><span class="whenRevised">[beginning Apple 4.0, LLVM 3.1]</span></span></p>
1833
1834<p>A C function may be marked with the <tt>cf_audited_transfer</tt>
1835attribute to express that, except as otherwise marked with attributes,
1836it obeys the parameter (consuming vs. non-consuming) and return
1837(retained vs. non-retained) conventions for a C function of its name,
1838namely:</p>
1839
1840<ul>
1841<li>A parameter of C retainable pointer type is assumed to not be
1842consumed unless it is marked with the <tt>cf_consumed</tt> attribute, and</li>
1843<li>A result of C retainable pointer type is assumed to not be
1844returned retained unless the function is either
1845marked <tt>cf_returns_retained</tt> or it follows
1846the create/copy naming convention and is not
1847marked <tt>cf_returns_not_retained</tt>.</li>
1848</ul>
1849
1850<p>A function obeys the <span class="term">create/copy</span> naming
1851convention if its name contains as a substring:</p>
1852<ul>
1853<li>either <q>Create</q> or <q>Copy</q> not followed by a lowercase letter, or</li>
1854<li>either <q>create</q> or <q>copy</q> not followed by a lowercase
1855letter and not preceded by any letter, whether uppercase or lowercase.</li>
1856</ul>
1857
1858<p>A second attribute, <tt>cf_unknown_transfer</tt>, signifies that a
1859function's transfer semantics cannot be accurately captured using any
1860of these annotations. A program is ill-formed if it annotates the
1861same function with both <tt>cf_audited_transfer</tt>
1862and <tt>cf_unknown_transfer</tt>.</p>
1863
1864<p>A pragma is provided to faciliate the mass annotation of interfaces:</p>
1865
1866<pre>#pragma arc_cf_code_audited begin
1867...
1868#pragma arc_cf_code_audited end</pre>
1869
1870<p>All C functions declared within the extent of this pragma are
1871treated as if annotated with the <tt>cf_audited_transfer</tt>
1872attribute unless they otherwise have the <tt>cf_unknown_transfer</tt>
1873attribute. The pragma is accepted in all language modes. A program
1874is ill-formed if it attempts to change files, whether by including a
1875file or ending the current file, within the extent of this pragma.</p>
1876
1877<p>It is possible to test for all the features in this section with
1878<tt>__has_feature(arc_cf_code_audited)</tt>.</p>
1879
1880<div class="rationale"><p>Rationale: A significant inconvenience in
1881ARC programming is the necessity of interacting with APIs based around
1882C retainable pointers. These features are designed to make it
1883relatively easy for API authors to quickly review and annotate their
1884interfaces, in turn improving the fidelity of tools such as the static
1885analyzer and ARC. The single-file restriction on the pragma is
1886designed to eliminate the risk of accidentally annotating some other
1887header's interfaces.</p></div>
1888
1889</div> <!-- misc.c-retainable.audit -->
1890
1891</div> <!-- misc.c-retainable -->
1892
John McCall82467022011-06-15 21:21:53 +00001893</div> <!-- misc -->
John McCall98a48cf2011-06-19 09:36:02 +00001894
1895<div id="runtime">
1896<h1>Runtime support</h1>
1897
John McCall085d09d2011-06-19 10:12:24 +00001898<p>This section describes the interaction between the ARC runtime and
1899the code generated by the ARC compiler. This is not part of the ARC
1900language specification; instead, it is effectively a language-specific
1901ABI supplement, akin to the <q>Itanium</q> generic ABI for C++.</p>
John McCall98a48cf2011-06-19 09:36:02 +00001902
1903<p>Ownership qualification does not alter the storage requirements for
John McCall085d09d2011-06-19 10:12:24 +00001904objects, except that it is undefined behavior if a <tt>__weak</tt>
1905object is inadequately aligned for an object of type <tt>id</tt>. The
1906other qualifiers may be used on explicitly under-aligned memory.</p>
John McCall98a48cf2011-06-19 09:36:02 +00001907
1908<p>The runtime tracks <tt>__weak</tt> objects which holds non-null
John McCall3914a302011-06-19 09:59:33 +00001909values. It is undefined behavior to direct modify a <tt>__weak</tt>
1910object which is being tracked by the runtime except through an
1911<a href="#runtime.objc_storeWeak"><tt>objc_storeWeak</tt></a>,
1912<a href="#runtime.objc_destroyWeak"><tt>objc_destroyWeak</tt></a>,
1913or <a href="#runtime.objc_moveWeak"><tt>objc_moveWeak</tt></a>
John McCall98a48cf2011-06-19 09:36:02 +00001914call.</p>
1915
John McCall3914a302011-06-19 09:59:33 +00001916<p>The runtime must provide a number of new entrypoints which the
1917compiler may emit, which are described in the remainder of this
1918section.</p>
1919
1920<div class="rationale"><p>Rationale: Several of these functions are
1921semantically equivalent to a message send; we emit calls to C
1922functions instead because:</p>
1923<ul>
1924<li>the machine code to do so is significantly smaller,</li>
1925<li>it is much easier to recognize the C functions in the ARC optimizer, and</li>
1926<li>a sufficient sophisticated runtime may be able to avoid the
1927message send in common cases.</li>
1928</ul>
1929
1930<p>Several other of these functions are <q>fused</q> operations which
1931can be described entirely in terms of other operations. We use the
1932fused operations primarily as a code-size optimization, although in
1933some cases there is also a real potential for avoiding redundant
1934operations in the runtime.</p>
1935
1936</div>
1937
John McCall98a48cf2011-06-19 09:36:02 +00001938<div id="runtime.objc_autorelease">
1939<h1><tt>id objc_autorelease(id value);</tt></h1>
1940<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1941valid object.</p>
1942<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1943adds the object to the innermost autorelease pool exactly as if the
1944object had been sent the <tt>autorelease</tt> message.</p>
1945<p>Always returns <tt>value</tt>.</p>
1946</div> <!-- runtime.objc_autorelease -->
1947
1948<div id="runtime.objc_autoreleasePoolPop">
1949<h1><tt>void objc_autoreleasePoolPop(void *pool);</tt></h1>
1950<p><i>Precondition:</i> <tt>pool</tt> is the result of a previous call to
1951<a href="runtime.objc_autoreleasePoolPush"><tt>objc_autoreleasePoolPush</tt></a>
1952on the current thread, where neither <tt>pool</tt> nor any enclosing
1953pool have previously been popped.</p>
1954<p>Releases all the objects added to the given autorelease pool and
1955any autorelease pools it encloses, then sets the current autorelease
1956pool to the pool directly enclosing <tt>pool</tt>.</p>
1957</div> <!-- runtime.objc_autoreleasePoolPop -->
1958
1959<div id="runtime.objc_autoreleasePoolPush">
1960<h1><tt>void *objc_autoreleasePoolPush(void);</tt></h1>
1961<p>Creates a new autorelease pool that is enclosed by the current
1962pool, makes that the current pool, and returns an opaque <q>handle</q>
1963to it.</p>
1964
1965<div class="rationale"><p>Rationale: while the interface is described
1966as an explicit hierarchy of pools, the rules allow the implementation
1967to just keep a stack of objects, using the stack depth as the opaque
1968pool handle.</p></div>
1969
1970</div> <!-- runtime.objc_autoreleasePoolPush -->
1971
1972<div id="runtime.objc_autoreleaseReturnValue">
1973<h1><tt>id objc_autoreleaseReturnValue(id value);</tt></h1>
1974<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
1975valid object.</p>
1976<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
1977makes a best effort to hand off ownership of a retain count on the
1978object to a call
1979to <a href="runtime.objc_retainAutoreleasedReturnValue"><tt>objc_retainAutoreleasedReturnValue</tt></a>
1980for the same object in an enclosing call frame. If this is not
1981possible, the object is autoreleased as above.</p>
1982<p>Always returns <tt>value</tt>.</p>
1983</div> <!-- runtime.objc_autoreleaseReturnValue -->
1984
1985<div id="runtime.objc_copyWeak">
1986<h1><tt>void objc_copyWeak(id *dest, id *src);</tt></h1>
1987<p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either
1988contains a null pointer or has been registered as a <tt>__weak</tt>
1989object. <tt>dest</tt> is a valid pointer which has not been
1990registered as a <tt>__weak</tt> object.</p>
1991<p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>,
1992potentially registering it with the runtime. Equivalent to the
1993following code:</p>
1994<pre>void objc_copyWeak(id *dest, id *src) {
1995 objc_release(objc_initWeak(dest, objc_loadWeakRetained(src)));
1996}</pre>
1997<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
1998on <tt>src</tt>.</p>
1999</div> <!-- runtime.objc_copyWeak -->
2000
2001<div id="runtime.objc_destroyWeak">
2002<h1><tt>void objc_destroyWeak(id *object);</tt></h1>
2003<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
2004either contains a null pointer or has been registered as
2005a <tt>__weak</tt> object.</p>
2006<p><tt>object</tt> is unregistered as a weak object, if it ever was.
2007The current value of <tt>object</tt> is left unspecified; otherwise,
2008equivalent to the following code:</p>
2009<pre>void objc_destroyWeak(id *object) {
2010 objc_storeWeak(object, nil);
2011}</pre>
2012<p>Does not need to be atomic with respect to calls
2013to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p>
2014</div> <!-- runtime.objc_destroyWeak -->
2015
2016<div id="runtime.objc_initWeak">
2017<h1><tt>id objc_initWeak(id *object, id value);</tt></h1>
2018<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which has
2019not been registered as a <tt>__weak</tt> object. <tt>value</tt> is
2020null or a pointer to a valid object.</p>
2021<p>If <tt>value</tt> is a null pointer or the object to which it
2022points has begun deallocation, <tt>object</tt> is zero-initialized.
2023Otherwise, <tt>object</tt> is registered as a <tt>__weak</tt> object
2024pointing to <tt>value</tt>. Equivalent to the following code:</p>
2025<pre>id objc_initWeak(id *object, id value) {
2026 *object = nil;
2027 return objc_storeWeak(object, value);
2028}</pre>
2029<p>Returns the value of <tt>object</tt> after the call.</p>
2030<p>Does not need to be atomic with respect to calls
2031to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p>
2032</div> <!-- runtime.objc_initWeak -->
2033
2034<div id="runtime.objc_loadWeak">
2035<h1><tt>id objc_loadWeak(id *object);</tt></h1>
2036<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
2037either contains a null pointer or has been registered as
2038a <tt>__weak</tt> object.</p>
2039<p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and
2040the last value stored into <tt>object</tt> has not yet been
2041deallocated or begun deallocation, retains and autoreleases that value
2042and returns it. Otherwise returns null. Equivalent to the following
2043code:</p>
2044<pre>id objc_loadWeak(id *object) {
2045 return objc_autorelease(objc_loadWeakRetained(object));
2046}</pre>
2047<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
2048on <tt>object</tt>.</p>
2049<div class="rationale">Rationale: loading weak references would be
2050inherently prone to race conditions without the retain.</div>
2051</div> <!-- runtime.objc_loadWeak -->
2052
2053<div id="runtime.objc_loadWeakRetained">
2054<h1><tt>id objc_loadWeakRetained(id *object);</tt></h1>
2055<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
2056either contains a null pointer or has been registered as
2057a <tt>__weak</tt> object.</p>
2058<p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and
2059the last value stored into <tt>object</tt> has not yet been
2060deallocated or begun deallocation, retains that value and returns it.
2061Otherwise returns null.</p>
2062<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
2063on <tt>object</tt>.</p>
2064</div> <!-- runtime.objc_loadWeakRetained -->
2065
2066<div id="runtime.objc_moveWeak">
2067<h1><tt>void objc_moveWeak(id *dest, id *src);</tt></h1>
2068<p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either
2069contains a null pointer or has been registered as a <tt>__weak</tt>
2070object. <tt>dest</tt> is a valid pointer which has not been
2071registered as a <tt>__weak</tt> object.</p>
2072<p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>,
2073potentially registering it with the runtime. <tt>src</tt> may then be
2074left in its original state, in which case this call is equivalent
2075to <a href="#runtime.objc_copyWeak"><tt>objc_copyWeak</tt></a>, or it
2076may be left as null.</p>
2077<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt>
2078on <tt>src</tt>.</p>
2079</div> <!-- runtime.objc_moveWeak -->
2080
John McCall085d09d2011-06-19 10:12:24 +00002081<div id="runtime.objc_release">
2082<h1><tt>void objc_release(id value);</tt></h1>
2083<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
2084valid object.</p>
2085<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
2086performs a release operation exactly as if the object had been sent
2087the <tt>release</tt> message.</p>
2088</div> <!-- runtime.objc_release -->
2089
John McCall98a48cf2011-06-19 09:36:02 +00002090<div id="runtime.objc_retain">
2091<h1><tt>id objc_retain(id value);</tt></h1>
2092<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
2093valid object.</p>
2094<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
2095performs a retain operation exactly as if the object had been sent
2096the <tt>retain</tt> message.</p>
2097<p>Always returns <tt>value</tt>.</p>
2098</div> <!-- runtime.objc_retain -->
2099
2100<div id="runtime.objc_retainAutorelease">
2101<h1><tt>id objc_retainAutorelease(id value);</tt></h1>
2102<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
2103valid object.</p>
2104<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
2105performs a retain operation followed by an autorelease operation.
2106Equivalent to the following code:</p>
2107<pre>id objc_retainAutorelease(id value) {
2108 return objc_autorelease(objc_retain(value));
2109}</pre>
2110<p>Always returns <tt>value</tt>.</p>
2111</div> <!-- runtime.objc_retainAutorelease -->
2112
2113<div id="runtime.objc_retainAutoreleaseReturnValue">
2114<h1><tt>id objc_retainAutoreleaseReturnValue(id value);</tt></h1>
2115<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
2116valid object.</p>
2117<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
2118performs a retain operation followed by the operation described in
2119<a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a>.
2120Equivalent to the following code:</p>
2121<pre>id objc_retainAutoreleaseReturnValue(id value) {
2122 return objc_autoreleaseReturnValue(objc_retain(value));
2123}</pre>
2124<p>Always returns <tt>value</tt>.</p>
2125</div> <!-- runtime.objc_retainAutoreleaseReturnValue -->
2126
2127<div id="runtime.objc_retainAutoreleasedReturnValue">
2128<h1><tt>id objc_retainAutoreleasedReturnValue(id value);</tt></h1>
2129<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
2130valid object.</p>
2131<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it
2132attempts to accept a hand off of a retain count from a call to
2133<a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a>
2134on <tt>value</tt> in a recently-called function or something it
2135calls. If that fails, it performs a retain operation exactly
2136like <a href="#runtime.objc_retain"><tt>objc_retain</tt></a>.</p>
2137<p>Always returns <tt>value</tt>.</p>
2138</div> <!-- runtime.objc_retainAutoreleasedReturnValue -->
2139
2140<div id="runtime.objc_retainBlock">
2141<h1><tt>id objc_retainBlock(id value);</tt></h1>
2142<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a
2143valid block object.</p>
2144<p>If <tt>value</tt> is null, this call has no effect. Otherwise, if
2145the block pointed to by <tt>value</tt> is still on the stack, it is
2146copied to the heap and the address of the copy is returned. Otherwise
2147a retain operation is performed on the block exactly as if it had been
2148sent the <tt>retain</tt> message.</p>
2149</div> <!-- runtime.objc_retainBlock -->
2150
John McCall98a48cf2011-06-19 09:36:02 +00002151<div id="runtime.objc_storeStrong">
2152<h1><tt>id objc_storeStrong(id *object, id value);</tt></h1>
2153<p><i>Precondition:</i> <tt>object</tt> is a valid pointer to
2154a <tt>__strong</tt> object which is adequately aligned for a
2155pointer. <tt>value</tt> is null or a pointer to a valid object.</p>
2156<p>Performs the complete sequence for assigning to a <tt>__strong</tt>
2157object of non-block type. Equivalent to the following code:</p>
2158<pre>id objc_storeStrong(id *object, id value) {
2159 value = [value retain];
2160 id oldValue = *object;
2161 *object = value;
2162 [oldValue release];
2163 return value;
2164}</pre>
2165<p>Always returns <tt>value</tt>.</p>
2166</div> <!-- runtime.objc_storeStrong -->
2167
2168<div id="runtime.objc_storeWeak">
2169<h1><tt>id objc_storeWeak(id *object, id value);</tt></h1>
2170<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which
2171either contains a null pointer or has been registered as
2172a <tt>__weak</tt> object. <tt>value</tt> is null or a pointer to a
2173valid object.</p>
2174<p>If <tt>value</tt> is a null pointer or the object to which it
2175points has begun deallocation, <tt>object</tt> is assigned null
2176and unregistered as a <tt>__weak</tt> object. Otherwise,
2177<tt>object</tt> is registered as a <tt>__weak</tt> object or has its
2178registration updated to point to <tt>value</tt>.</p>
2179<p>Returns the value of <tt>object</tt> after the call.</p>
2180</div> <!-- runtime.objc_storeWeak -->
2181
2182</div> <!-- runtime -->
John McCall82467022011-06-15 21:21:53 +00002183</div> <!-- root -->
2184</body>
2185</html>