blob: d094d74125fc0907124a7fb70cd1d1733e169e85 [file] [log] [blame]
John McCall82467022011-06-15 21:21:53 +00001<html>
2<head>
3<title>Objective-C Automatic Reference Counting (ARC)</title>
4<link type="text/css" rel="stylesheet" href="../menu.css" />
5<link type="text/css" rel="stylesheet" href="../content.css" />
6<style type="text/css">
7/* Collapse the items in the ToC to the left. */
8div#toc ul {
9 padding-left: 0
10}
11
12/* Rationales appear in italic. */
13div.rationale {
14 font-style: italic
15}
16
17div h1 { font-size: 2em; margin: .67em 0 }
18div div h1 { font-size: 1.5em; margin: .75em 0 }
19div div div h1 { font-size: 1.17em; margin: .83em 0 }
20div div div div h1 { margin: 1.12em 0 }
21
22span.term { font-style: italic; font-weight: bold }
23</style>
24
25<script lang="javascript">
26/// A little script to recursively build a table of contents.
27function buildTOC(div, toc, ancestry) {
28 var children = div.childNodes;
29 var len = children.length;
30
31 var childNumber = 0;
32
33 var list = null;
34 for (var i = 0; i < len; ++i) {
35 var child = children[i];
36 if (child.nodeName != "DIV") continue;
37 if (child.getAttribute("class") == "rationale") continue;
38 if (child.id == "toc") continue;
39
40 // Okay, we're actually going to build a list node.
41 if (list === null) list = document.createElement("ul");
42
43 var childAncestry = ancestry + ++childNumber + ".";
44
45 var headerNode = child.childNodes[1];
46 var title = headerNode.innerHTML;
47 headerNode.insertBefore(document.createTextNode(childAncestry + " "),
48 headerNode.firstChild);
49
50 var item = document.createElement("li");
51 item.appendChild(document.createTextNode(childAncestry + " "));
52
53 var anchor = document.createElement("a");
54 anchor.href = "#" + child.id;
55 anchor.innerHTML = title;
56 item.appendChild(anchor);
57
58 buildTOC(child, item, childAncestry);
59
60 list.appendChild(item);
61 }
62 if (list) toc.appendChild(list);
63}
64
65function onLoad() {
66 var toc = document.getElementById("toc");
67 var content = document.getElementById("content");
68 buildTOC(content, toc, "");
69}
70window.onload = onLoad;
71
72</script>
73</head>
74<body>
75
76<!--#include virtual="../menu.html.incl"-->
77
78<div id="content">
79<h1>Automatic Reference Counting</h1>
80
81<div id="toc">
82</div>
83
84<div id="meta">
85<h1>About this document</h1>
86
87<div id="meta.purpose">
88<h1>Purpose</h1>
89
90<p>The first and primary purpose of this document is to serve as a
91complete technical specification of Automatic Reference Counting.
92Given a core Objective-C compiler and runtime, it should be possible
93to write a compiler and runtime which implements these new
94semantics.</p>
95
96<p>The secondary purpose is to act as a rationale for why ARC was
97designed in this way. This should remain tightly focused on the
98technical design and should not stray into marketing speculation.</p>
99
100</div> <!-- meta.purpose -->
101
102<div id="meta.background">
103<h1>Background</h1>
104
105<p>This document assumes a basic familiarity with C.</p>
106
107<p><span class="term">Blocks</span> are a C language extension for
108creating anonymous functions. Users interact with and transfer block
109objects using <span class="term">block pointers</span>, which are
110represented like a normal pointer. A block may capture values from
111local variables; when this occurs, memory must be dynamically
112allocated. The initial allocation is done on the stack, but the
113runtime provides a <tt>Block_copy</tt> function which, given a block
114pointer, either copies the underlying block object to the heap,
115setting its reference count to 1 and returning the new block pointer,
116or (if the block object is already on the heap) increases its
117reference count by 1. The paired function is <tt>Block_release</tt>,
118which decreases the reference count by 1 and destroys the object if
119the count reaches zero and is on the heap.</p>
120
121<p>Objective-C is a set of language extensions, significant enough to
122be considered a different language. It is a strict superset of C.
123The extensions can also be imposed on C++, producing a language called
124Objective-C++. The primary feature is a single-inheritance object
125system; we briefly describe the modern dialect.</p>
126
127<p>Objective-C defines a new type kind, collectively called
128the <span class="term">object pointer types</span>. This kind has two
129notable builtin members, <tt>id</tt> and <tt>Class</tt>; <tt>id</tt>
130is the final supertype of all object pointers. The validity of
131conversions between object pointer types is not checked at runtime.
132Users may define <span class="term">classes</span>; each class is a
133type, and the pointer to that type is an object pointer type. A class
134may have a superclass; its pointer type is a subtype of its
135superclass's pointer type. A class has a set
136of <span class="term">ivars</span>, fields which appear on all
137instances of that class. For every class <i>T</i> there's an
138associated metaclass; it has no fields, its superclass is the
139metaclass of <i>T</i>'s superclass, and its metaclass is a global
140class. Every class has a global object whose class is the
141class's metaclass; metaclasses have no associated type, so pointers to
142this object have type <tt>Class</tt>.</p>
143
144<p>A class declaration (<tt>@interface</tt>) declares a set
145of <span class="term">methods</span>. A method has a return type, a
146list of argument types, and a <span class="term">selector</span>: a
147name like <tt>foo:bar:baz:</tt>, where the number of colons
148corresponds to the number of formal arguments. A method may be an
149instance method, in which case it can be invoked on objects of the
150class, or a class method, in which case it can be invoked on objects
151of the metaclass. A method may be invoked by providing an object
152(called the <span class="term">receiver</span>) and a list of formal
153arguments interspersed with the selector, like so:</p>
154
155<pre>[receiver foo: fooArg bar: barArg baz: bazArg]</pre>
156
157<p>This looks in the dynamic class of the receiver for a method with
158this name, then in that class's superclass, etc., until it finds
159something it can execute. The receiver <q>expression</q> may also be
160the name of a class, in which case the actual receiver is the class
161object for that class, or (within method definitions) it may
162be <tt>super</tt>, in which case the lookup algorithm starts with the
163static superclass instead of the dynamic class. The actual methods
164dynamically found in a class are not those declared in the
165<tt>@interface</tt>, but those defined in a separate
166<tt>@implementation</tt> declaration; however, when compiling a
167call, typechecking is done based on the methods declared in the
168<tt>@interface</tt>.</p>
169
170<p>Method declarations may also be grouped into
171<span class="term">protocols</span>, which are not inherently
172associated with any class, but which classes may claim to follow.
173Object pointer types may be qualified with additional protocols that
174the object is known to support.</p>
175
176<p><span class="term">Class extensions</span> are collections of ivars
177and methods, designed to allow a class's <tt>@interface</tt> to be
178split across multiple files; however, there is still a primary
179implementation file which must see the <tt>@interface</tt>s of all
180class extensions.
181<span class="term">Categories</span> allow methods (but not ivars) to
182be declared <i>post hoc</i> on an arbitrary class; the methods in the
183category's <tt>@implementation</tt> will be dynamically added to that
184class's method tables which the category is loaded at runtime,
185replacing those methods in case of a collision.</p>
186
187<p>In the standard environment, objects are allocated on the heap, and
188their lifetime is manually managed using a reference count. This is
189done using two instance methods which all classes are expected to
190implement: <tt>retain</tt> increases the object's reference count by
1911, whereas <tt>release</tt> decreases it by 1 and calls the instance
192method <tt>dealloc</tt> if the count reaches 0. To simplify certain
193operations, there is also an <span class="term">autorelease
194pool</span>, a thread-local list of objects to call <tt>release</tt>
195on later; an object can be added to this pool by
196calling <tt>autorelease</tt> on it.</p>
197
198<p>Block pointers may be converted to type <tt>id</tt>; block objects
199are laid out in a way that makes them compatible with Objective-C
200objects. There is a builtin class that all block objects are
201considered to be objects of; this class implements <tt>retain</tt> by
202adjusting the reference count, not by calling <tt>Block_copy</tt>.</p>
203
204</div> <!-- meta.background -->
205
206</div> <!-- meta -->
207
208<div id="general">
209<h1>General</h1>
210
211<p>Automatic Reference Counting implements automatic memory management
212for Objective-C objects and blocks, freeing the programmer from the
213need explicitly insert retains and releases. It does not provide a
214cycle collector; users must explicitly manage lifetime instead.</p>
215
216<p>ARC may be explicitly enabled with the compiler
217flag <tt>-fobjc-arc</tt>. It may also be explicitly disabled with the
218compiler flag <tt>-fno-objc-arc</tt>. The last of these two flags
219appearing on the compile line <q>wins</q>.</p>
220
221<p>If ARC is enabled, <tt>__has_feature(objc_arc)</tt> will expand to
2221 in the preprocessor. For more information about <tt>__has_feature</tt>,
223see the <a href="LanguageExtensions.html#__has_feature_extension">language
224extensions</a> document.</p>
225
226</div>
227
228<div id="objects">
229<h1>Retainable object pointers</h1>
230
231<p>This section describes retainable object pointers, their basic
232operations, and the restrictions imposed on their use under ARC. Note
233in particular that it covers the rules for pointer <em>values</em>
234(patterns of bits indicating the location of a pointed-to object), not
235pointer
236<em>objects</em> (locations in memory which store pointer values).
237The rules for objects are covered in the next section.</p>
238
239<p>A <span class="term">retainable object pointer</span>
240(or <q>retainable pointer</q>) is a value of
241a <span class="term">retainable object pointer type</span>
242(<q>retainable type</q>). There are three kinds of retainable object
243pointer types:</p>
244<ul>
245<li>block pointers (formed by applying the caret (<tt>^</tt>)
246declarator sigil to a function type)</li>
247<li>Objective-C object pointers (<tt>id</tt>, <tt>Class</tt>, <tt>NSFoo*</tt>, etc.)</li>
248<li>typedefs marked with <tt>__attribute__((NSObject))</tt></li>
249</ul>
250
251<p>Other pointer types, such as <tt>int*</tt> and <tt>CFStringRef</tt>,
252are not subject to ARC's semantics and restrictions.</p>
253
254<div class="rationale">
255
256<p>Rationale: We are not at liberty to require
257all code to be recompiled with ARC; therefore, ARC must interoperate
258with Objective-C code which manages retains and releases manually. In
259general, there are three requirements in order for a
260compiler-supported reference-count system to provide reliable
261interoperation:</p>
262
263<ul>
264<li>The type system must reliably identify which objects are to be
265managed. An <tt>int*</tt> might be a pointer to a <tt>malloc</tt>'ed
266array, or it might be a interior pointer to such an array, or it might
267point to some field or local variable. In contrast, values of the
268retainable object pointer types are never interior.</li>
269<li>The type system must reliably indicate how to
270manage objects of a type. This usually means that the type must imply
271a procedure for incrementing and decrementing retain counts.
272Supporting single-ownership objects requires a lot more explicit
273mediation in the language.</li>
274<li>There must be reliable conventions for whether and
275when <q>ownership</q> is passed between caller and callee, for both
276arguments and return values. Objective-C methods follow such a
277convention very reliably, at least for system libraries on Mac OS X,
278and functions always pass objects at +0. The C-based APIs for Core
279Foundation objects, on the other hand, have much more varied transfer
280semantics.</li>
281</ul>
282</div> <!-- rationale -->
283
284<p>The use of <tt>__attribute__((NSObject))</tt> typedefs is not
285recommended. If it's absolutely necessary to use this attribute, be
286very explicit about using the typedef, and do not assume that it will
287be preserved by language features like <tt>__typeof</tt> and C++
288template argument substitution.</p>
289
290<div class="rationale"><p>Rationale: any compiler operation which
291incidentally strips type <q>sugar</q> from a type will yield a type
292without the attribute, which may result in unexpected
293behavior.</p></div>
294
295<div id="objects.retains">
296<h1>Retain count semantics</h1>
297
298<p>A retainable object pointer is either a <span class="term">null
299pointer</span> or a pointer to a valid object. Furthermore, if it has
300block pointer type and is not <tt>null</tt> then it must actually be a
301pointer to a block object, and if it has <tt>Class</tt> type (possibly
302protocol-qualified) then it must actually be a pointer to a class
303object. Otherwise ARC does not enforce the Objective-C type system as
304long as the implementing methods follow the signature of the static
305type. It is undefined behavior if ARC is exposed to an invalid
306pointer.</p>
307
308<p>For ARC's purposes, a valid object is one with <q>well-behaved</q>
309retaining operations. Specifically, the object must be laid out such
310that the Objective-C message send machinery can successfully send it
311the following messages:</p>
312
313<ul>
314<li><tt>retain</tt>, taking no arguments and returning a pointer to
315the object.</li>
316<li><tt>release</tt>, taking no arguments and returning <tt>void</tt>.</li>
317<li><tt>autorelease</tt>, taking no arguments and returning a pointer
318to the object.</li>
319</ul>
320
321<p>The behavior of these methods is constrained in the following ways.
322The term <span class="term">high-level semantics</span> is an
323intentionally vague term; the intent is that programmers must
324implement these methods in a way such that the compiler, modifying
325code in ways it deems safe according to these constraints, will not
326violate their requirements. For example, if the user puts logging
327statements in <tt>retain</tt>, they should not be surprised if those
328statements are executed more or less often depending on optimization
329settings. These constraints are not exhaustive of the optimization
330opportunities: values held in local variables are subject to
331additional restrictions, described later in this document.</p>
332
333<p>It is undefined behavior if a computation history featuring a send
334of <tt>retain</tt> followed by a send of <tt>release</tt> to the same
335object, with no intervening <tt>release</tt> on that object, is not
336equivalent under the high-level semantics to a computation
337history in which these sends are removed. Note that this implies that
338these methods may not raise exceptions.</p>
339
340<p>It is undefined behavior if a computation history features any use
341whatsoever of an object following the completion of a send
342of <tt>release</tt> that is not preceded by a send of <tt>retain</tt>
343to the same object.</p>
344
345<p>The behavior of <tt>autorelease</tt> must be equivalent to sending
346<tt>release</tt> when one of the autorelease pools currently in scope
347is popped. It may not throw an exception.</p>
348
349<p>When the semantics call for performing one of these operations on a
350retainable object pointer, if that pointer is <tt>null</tt> then the
351effect is a no-op.</p>
352
353<p>All of the semantics described in this document are subject to
354additional <a href="#optimization">optimization rules</a> which permit
355the removal or optimization of operations based on local knowledge of
356data flow. The semantics describe the high-level behaviors that the
357compiler implements, not an exact sequence of operations that a
358program will be compiled into.</p>
359
360</div> <!-- objects.retains -->
361
362<div id="objects.operands">
363<h1>Retainable object pointers as operands and arguments</h1>
364
365<p>In general, ARC does not perform retain or release operations when
366simply using a retainable object pointer as an operand within an
367expression. This includes:</p>
368<ul>
369<li>loading a retainable pointer from an object with non-weak
370<a href="#ownership">ownership</a>,</li>
371<li>passing a retainable pointer as an argument to a function or
372method, and</li>
373<li>receiving a retainable pointer as the result of a function or
374method call.</li>
375</ul>
376
377<div class="rationale"><p>Rationale: while this might seem
378uncontroversial, it is actually unsafe when multiple expressions are
379evaluated in <q>parallel</q>, as with binary operators and calls,
380because (for example) one expression might load from an object while
381another writes to it. However, C and C++ already call this undefined
382behavior because the evaluations are unsequenced, and ARC simply
383exploits that here to avoid needing to retain arguments across a large
384number of calls.</p></div>
385
386<p>The remainder of this section describes exceptions to these rules,
387how those exceptions are detected, and what those exceptions imply
388semantically.</p>
389
390<div id="objects.operands.consumed">
391<h1>Consumed parameters</h1>
392
393<p>A function or method parameter of retainable object pointer type
394may be marked as <span class="term">consumed</span>, signifying that
395the callee expects to take ownership of a +1 retain count. This is
396done by adding the <tt>ns_consumed</tt> attribute to the parameter
397declaration, like so:</p>
398
399<pre>void foo(__attribute((ns_consumed)) id x);
400- (void) foo: (id) __attribute((ns_consumed)) x;</pre>
401
402<p>This attribute is part of the type of the function or method, not
403the type of the parameter. It controls only how the argument is
404passed and received.</p>
405
406<p>When passing such an argument, ARC retains the argument prior to
407making the call.</p>
408
409<p>When receiving such an argument, ARC releases the argument at the
410end of the function, subject to the usual optimizations for local
411values.</p>
412
413<div class="rationale"><p>Rationale: this formalizes direct transfers
414of ownership from a caller to a callee. The most common scenario here
415is passing the <tt>self</tt> parameter to <tt>init</tt>, but it is
416useful to generalize. Typically, local optimization will remove any
417extra retains and releases: on the caller side the retain will be
418merged with a +1 source, and on the callee side the release will be
419rolled into the initialization of the parameter.</p></div>
420
421<p>The implicit <tt>self</tt> parameter of a method may be marked as
422consumed by adding <tt>__attribute__((ns_consumes_self))</tt> to the
423method declaration. Methods in
424the <tt>init</tt> <a href="#family">family</a> are implicitly
425marked <tt>__attribute__((ns_consumes_self))</tt>.</p>
426
427<p>It is undefined behavior if an Objective-C message send of a method
428with <tt>ns_consumed</tt> parameters (other than self) is made to a
429null pointer.</p>
430
431<div class="rationale"><p>Rationale: in fact, it's probably a
432guaranteed leak.</p></div>
433
434</div>
435
436<div id="objects.operands.retained-returns">
437<h1>Retained return values</h1>
438
439<p>A function or method which returns a retainable object pointer type
440may be marked as returning a retained value, signifying that the
441caller expects to take ownership of a +1 retain count. This is done
442by adding the <tt>ns_returns_retained</tt> attribute to the function or
443method declaration, like so:</p>
444
445<pre>id foo(void) __attribute((ns_returns_retained));
446- (id) foo __attribute((ns_returns_retained));</pre>
447
448<p>This attribute is part of the type of the function or method.</p>
449
450<p>When returning from such a function or method, ARC retains the
451value at the point of evaluation of the return statement, before
452leaving all local scopes.</p>
453
454<p>When receiving a return result from such a function or method, ARC
455releases the value at the end of the full-expression it is contained
456within, subject to the usual optimizations for local values.</p>
457
458<div class="rationale"><p>Rationale: this formalizes direct transfers of
459ownership from a callee to a caller. The most common scenario this
460models is the retained return from <tt>init</tt>, <tt>alloc</tt>,
461<tt>new</tt>, and <tt>copy</tt> methods, but there are other cases in
462the frameworks. After optimization there are typically no extra
463retains and releases required.</p></div>
464
465<p>Methods in
466the <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>, <tt>mutableCopy</tt>,
467and <tt>new</tt> <a href="#family">families</a> are implicitly marked
468<tt>__attribute__((ns_returns_retained))</tt>. This may be suppressed
469by explicitly marking the
470method <tt>__attribute__((ns_returns_not_retained))</tt>.</p>
471</div>
472
473<div id="objects.operands.other-returns">
474<h1>Unretained return values</h1>
475
476<p>A method or function which returns a retainable object type but
477does not return a retained value must ensure that the object is
478still valid across the return boundary.</p>
479
480<p>When returning from such a function or method, ARC retains the
481value at the point of evaluation of the return statement, then leaves
482all local scopes, and then balances out the retain while ensuring that
483the value lives across the call boundary. In the worst case, this may
484involve an <tt>autorelease</tt>, but callers must not assume that the
485value is actually in the autorelease pool.</p>
486
487<p>ARC performs no extra mandatory work on the caller side, although
488it may elect to do something to shorten the lifetime of the returned
489value.</p>
490
491<div class="rationale"><p>Rationale: it is common in non-ARC code to not
492return an autoreleased value; therefore the convention does not force
493either path. It is convenient to not be required to do unnecessary
494retains and autoreleases; this permits optimizations such as eliding
495retain/autoreleases when it can be shown that the original pointer
496will still be valid at the point of return.</p></div>
497
498<p>A method or function may be marked
499with <tt>__attribute__((ns_returns_autoreleased))</tt> to indicate
500that it returns a pointer which is guaranteed to be valid at least as
501long as the innermost autorelease pool. There are no additional
502semantics enforced in the definition of such a method; it merely
503enables optimizations in callers.</p>
504</div>
505
506<div id="objects.operands.casts">
507<h1>Bridged casts</h1>
508
509<p>A <span class="term">bridged cast</span> is a C-style cast
510annotated with one of three keywords:</p>
511
512<ul>
513<li><tt>(__bridge T) op</tt> casts the operand to the destination
514type <tt>T</tt>. If <tt>T</tt> is a retainable object pointer type,
515then <tt>op</tt> must have a non-retainable pointer type.
516If <tt>T</tt> is a non-retainable pointer type, then <tt>op</tt> must
517have a retainable object pointer type. Otherwise the cast is
518ill-formed. There is no transfer of ownership, and ARC inserts
519no retain operations.</li>
520
521<li><tt>(__bridge_retained T) op</tt> casts the operand, which must
522have retainable object pointer type, to the destination type, which
523must be a non-retainable pointer type. ARC retains the value, subject
524to the usual optimizations on local values, and the recipient is
525responsible for balancing that +1.</li>
526
527<li><tt>(__bridge_transfer T) op</tt> casts the operand, which must
528have non-retainable pointer type, to the destination type, which must
529be a retainable object pointer type. ARC will release the value at
530the end of the enclosing full-expression, subject to the usual
531optimizations on local values.</li>
532</ul>
533
534<p>These casts are required in order to transfer objects in and out of
535ARC control; see the rationale in the section
536on <a href="#objects.restrictions.conversion">conversion of retainable
537object pointers</a>.</p>
538
539<p>Using a <tt>__bridge_retained</tt> or <tt>__bridge_transfer</tt>
540cast purely to convince ARC to emit an unbalanced retain or release,
541respectively, is poor form.</p>
542
543</div>
544
545</div>
546
547<div id="objects.restrictions">
548<h1>Restrictions</h1>
549
550<div id="objects.restrictions.conversion">
551<h1>Conversion of retainable object pointers</h1>
552
553<p>In general, a program which attempts to implicitly or explicitly
554convert a value of retainable object pointer type to any
555non-retainable type, or vice-versa, is ill-formed. For example, an
556Objective-C object pointer shall not be converted to <tt>intptr_t</tt>
557or <tt>void*</tt>. The <a href="#objects.operands.casts">bridged
558casts</a> may be used to perform these conversions where
559necessary.</p>
560
561<div class="rationale"><p>Rationale: we cannot ensure the correct
562management of the lifetime of objects if they may be freely passed
563around as unmanaged types. The bridged casts are provided so that the
564programmer may explicitly describe whether the cast transfers control
565into or out of ARC.</p></div>
566</div>
567
568<p>An unbridged cast to a retainable object pointer type of the return
569value of a Objective-C message send which yields a non-retainable
570pointer is treated as a <tt>__bridge_transfer</tt> cast
571if:</p>
572
573<ul>
574<li>the method has the <tt>cf_returns_retained</tt> attribute, or if
575not that,</li>
576<li>the method does not have the <tt>cf_returns_not_retained</tt>
577attribute and</li>
578<li>the method's <a href="#family">selector family</a> would imply
579the <tt>ns_returns_retained</tt> attribute on a method which returned
580a retainable object pointer type.</li>
581</ul>
582
583<p>Otherwise the cast is treated as a <tt>__bridge</tt> cast.</p>
584
585</div>
586
587</div>
588
589<div id="ownership">
590<h1>Ownership qualification</h1>
591
592<p>This section describes the behavior of <em>objects</em> of
593retainable object pointer type; that is, locations in memory which
594store retainable object pointers.</p>
595
596<p>A type is a <span class="term">retainable object owner type</span>
597if it is a retainable object pointer type or an array type whose
598element type is a retainable object owner type.</p>
599
600<p>An <span class="term">ownership qualifier</span> is a type
Douglas Gregor4020cae2011-06-17 23:16:24 +0000601qualifier which applies only to retainable object owner types. An array type is
602ownership-qualified according to its element type, and adding an ownership
603qualifier to an array type so qualifies its element type.</p>
604
605<p>A program is ill-formed if it attempts to apply an ownership qualifier
John McCall82467022011-06-15 21:21:53 +0000606to a type which is already ownership-qualified, even if it is the same
Douglas Gregor4020cae2011-06-17 23:16:24 +0000607qualifier. There is a single exception to this rule: an ownership qualifier
608may be applied to a substituted template type parameter, which overrides the
609ownership qualifier provided by the template argument.</p>
John McCall82467022011-06-15 21:21:53 +0000610
611<p>Except as described under
612the <a href="#ownership.inference">inference rules</a>, a program is
613ill-formed if it attempts to form a pointer or reference type to a
614retainable object owner type which lacks an ownership qualifier.</p>
615
616<div class="rationale"><p>Rationale: these rules, together with the
617inference rules, ensure that all objects and lvalues of retainable
Douglas Gregor4020cae2011-06-17 23:16:24 +0000618object 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 +0000619
620<p>There are four ownership qualifiers:</p>
621
622<ul>
623<li><tt>__autoreleasing</tt></li>
624<li><tt>__strong</tt></li>
625<li><tt>__unsafe_unretained</tt></li>
626<li><tt>__weak</tt></li>
627</ul>
628
629<p>A type is <span class="term">nontrivially ownership-qualified</span>
630if it is qualified with <tt>__autoreleasing</tt>, <tt>__strong</tt>, or
631<tt>__weak</tt>.</p>
632
633<div id="ownership.spelling">
634<h1>Spelling</h1>
635
636<p>The names of the ownership qualifiers are reserved for the
637implementation. A program may not assume that they are or are not
638implemented with macros, or what those macros expand to.</p>
639
640<p>An ownership qualifier may be written anywhere that any other type
641qualifier may be written.</p>
642
643<p>If an ownership qualifier appears in
644the <i>declaration-specifiers</i>, the following rules apply:</p>
645
646<ul>
647<li>if the type specifier is a retainable object owner type, the
648qualifier applies to that type;</li>
649<li>if the outermost non-array part of the declarator is a pointer or
650block pointer, the qualifier applies to that type;</li>
651<li>otherwise the program is ill-formed.</li>
652</ul>
653
654<p>If an ownership qualifier appears on the declarator name, or on the
655declared object, it is applied to outermost pointer or block-pointer
656type.</p>
657
658<p>If an ownership qualifier appears anywhere else in a declarator, it
659applies to the type there.</p>
660
661</div> <!-- ownership.spelling -->
662
663<div id="ownership.semantics">
664<h1>Semantics</h1>
665
666<p>There are five <span class="term">managed operations</span> which
667may be performed on an object of retainable object pointer type. Each
668qualifier specifies different semantics for each of these operations.
669It is still undefined behavior to access an object outside of its
670lifetime.</p>
671
672<p>A load or store with <q>primitive semantics</q> has the same
673semantics as the respective operation would have on an <tt>void*</tt>
674lvalue with the same alignment and non-ownership qualification.</p>
675
676<p><span class="term">Reading</span> occurs when performing a
677lvalue-to-rvalue conversion on an object lvalue.
678
679<ul>
680<li>For <tt>__weak</tt> objects, the current pointee is retained and
681then released at the end of the current full-expression. This must
682execute atomically with respect to assignments and to the final
683release of the pointee.</li>
684<li>For all other objects, the lvalue is loaded with primitive
685semantics.</li>
686</ul>
687</p>
688
689<p><span class="term">Assignment</span> occurs when evaluating
690an assignment operator. The semantics vary based on the qualification:
691<ul>
692<li>For <tt>__strong</tt> objects, the new pointee is first retained;
693second, the lvalue is loaded with primitive semantics; third, the new
694pointee is stored into the lvalue with primitive semantics; and
695finally, the old pointee is released. This is not performed
696atomically; external synchronization must be used to make this safe in
697the face of concurrent loads and stores.</li>
698<li>For <tt>__weak</tt> objects, the lvalue is updated to point to the
699new pointee, unless that object is currently undergoing deallocation,
700in which case it the lvalue is updated to a null pointer. This must
701execute atomically with respect to other assignments to the object, to
702reads from the object, and to the final release of the new pointed-to
703value.</li>
704<li>For <tt>__unsafe_unretained</tt> objects, the new pointee is
705stored into the lvalue using primitive semantics.</li>
706<li>For <tt>__autoreleasing</tt> objects, the new pointee is retained,
707autoreleased, and stored into the lvalue using primitive semantics.</li>
708</ul>
709</p>
710
711<p><span class="term">Initialization</span> occurs when an object's
712lifetime begins, which depends on its storage duration.
713Initialization proceeds in two stages:
714<ol>
715<li>First, a null pointer is stored into the lvalue using primitive
716semantics. This step is skipped if the object
717is <tt>__unsafe_unretained</tt>.</li>
718<li>Second, if the object has an initializer, that expression is
719evaluated and then assigned into the object using the usual assignment
720semantics.</li>
721</ol>
722</p>
723
724<p><span class="term">Destruction</span> occurs when an object's
725lifetime ends. In all cases it is semantically equivalent to
726assigning a null pointer to the object, with the proviso that of
727course the object cannot be legally read after the object's lifetime
728ends.</p>
729
730<p><span class="term">Moving</span> occurs in specific situations
731where an lvalue is <q>moved from</q>, meaning that its current pointee
732will be used but the object may be left in a different (but still
733valid) state. This arises with <tt>__block</tt> variables and rvalue
734references in C++. For <tt>__strong</tt> lvalues, moving is equivalent
735to loading the lvalue with primitive semantics, writing a null pointer
736to it with primitive semantics, and then releasing the result of the
737load at the end of the current full-expression. For all other
738lvalues, moving is equivalent to reading the object.</p>
739
740</div> <!-- ownership.semantics -->
741
742<div id="ownership.restrictions">
743<h1>Restrictions</h1>
744
745<div id="ownership.restrictions.autoreleasing">
746<h1>Storage duration of<tt> __autoreleasing</tt> objects</h1>
747
748<p>A program is ill-formed if it declares an <tt>__autoreleasing</tt>
749object of non-automatic storage duration.</p>
750
751<div class="rationale"><p>Rationale: autorelease pools are tied to the
752current thread and scope by their nature. While it is possible to
753have temporary objects whose instance variables are filled with
754autoreleased objects, there is no way that ARC can provide any sort of
755safety guarantee there.</p></div>
756
757<p>It is undefined behavior if a non-null pointer is assigned to
758an <tt>__autoreleasing</tt> object while an autorelease pool is in
759scope and then that object is read after the autorelease pool's scope
760is left.</p>
761
762</div>
763
764<div id="ownership.restrictions.conversion.indirect">
765<h1>Conversion of pointers to ownership-qualified types</h1>
766
767<p>A program is ill-formed if an expression of type <tt>T*</tt> is
768converted, explicitly or implicitly, to the type <tt>U*</tt>,
769where <tt>T</tt> and <tt>U</tt> have different ownership
770qualification, unless:
771<ul>
772<li><tt>T</tt> is qualified with <tt>__strong</tt>,
773 <tt>__autoreleasing</tt>, or <tt>__unsafe_unretained</tt>, and
774 <tt>U</tt> is qualified with both <tt>const</tt> and
775 <tt>__unsafe_unretained</tt>; or</li>
776<li>either <tt>T</tt> or <tt>U</tt> is <tt>cv void</tt>, where
777<tt>cv</tt> is an optional sequence of non-ownership qualifiers; or</li>
778<li>the conversion is requested with a <tt>reinterpret_cast</tt> in
779 Objective-C++; or</li>
780<li>the conversion is a
781well-formed <a href="#ownership.restrictions.pass_by_writeback">pass-by-writeback</a>.</li>
782</ul>
783</p>
784
785<p>The analogous rule applies to <tt>T&</tt> and <tt>U&</tt> in
786Objective-C++.</p>
787
788<div class="rationale"><p>Rationale: these rules provide a reasonable
789level of type-safety for indirect pointers, as long as the underlying
790memory is not deallocated. The conversion to <tt>const
791__unsafe_unretained</tt> is permitted because the semantics of reads
792are equivalent across all these ownership semantics, and that's a very
793useful and common pattern. The interconversion with <tt>void*</tt> is
794useful for allocating memory or otherwise escaping the type system,
795but use it carefully. <tt>reinterpret_cast</tt> is considered to be
796an obvious enough sign of taking responsibility for any
797problems.</p></div>
798
799<p>It is undefined behavior to access an ownership-qualified object
800through an lvalue of a differently-qualified type, except that any
801non-<tt>__weak</tt> object may be read through
802an <tt>__unsafe_unretained</tt> lvalue.</p>
803
804<p>It is undefined behavior if a managed operation is performed on
805a <tt>__strong</tt> or <tt>__weak</tt> object without a guarantee that
806it contains a primitive zero bit-pattern, or if the storage for such
807an object is freed or reused without the object being first assigned a
808null pointer.</p>
809
810<div class="rationale"><p>Rationale: ARC cannot differentiate between
811an assignment operator which is intended to <q>initialize</q> dynamic
812memory and one which is intended to potentially replace a value.
813Therefore the object's pointer must be valid before letting ARC at it.
814Similarly, C and Objective-C do not provide any language hooks for
815destroying objects held in dynamic memory, so it is the programmer's
816responsibility to avoid leaks (<tt>__strong</tt> objects) and
817consistency errors (<tt>__weak</tt> objects).</p>
818
819<p>These requirements are followed automatically in Objective-C++ when
820creating objects of retainable object owner type with <tt>new</tt>
821or <tt>new[]</tt> and destroying them with <tt>delete</tt>,
822<tt>delete[]</tt>, or a pseudo-destructor expression. Note that
823arrays of nontrivially-ownership-qualified type are not ABI compatible
824with non-ARC code because the element type is non-POD: such arrays
825that are <tt>new[]</tt>'d in ARC translation units cannot
826be <tt>delete[]</tt>'d in non-ARC translation units and
827vice-versa.</p></div>
828
829</div>
830
831<div id="ownership.restrictions.pass_by_writeback">
832<h1>Passing to an out parameter by writeback</h1>
833
834<p>If the argument passed to a parameter of type
835<tt>T __autoreleasing *</tt> has type <tt>U oq *</tt>,
836where <tt>oq</tt> is an ownership qualifier, then the argument is a
837candidate for <span class="term">pass-by-writeback</span> if:</p>
838
839<ul>
840<li><tt>oq</tt> is <tt>__strong</tt> or <tt>__weak</tt>, and
841<li>it would be legal to initialize a <tt>T __strong *</tt> with
842a <tt>U __strong *</tt>.</li>
843</ul>
844
845<p>For purposes of overload resolution, an implicit conversion
846sequence requiring a pass-by-writeback is always worse than an
847implicit conversion sequence not requiring a pass-by-writeback.</p>
848
849<p>The pass-by-writeback is ill-formed if the argument expression does
850not have a legal form:</p>
851
852<ul>
853<li><tt>&var</tt>, where <tt>var</tt> is a scalar variable of
854automatic storage duration with retainable object pointer type</li>
855<li>a conditional expression where the second and third operands are
856both legal forms</li>
857<li>a cast whose operand is a legal form</li>
858<li>a null pointer constant</li>
859</ul>
860
861<div class="rationale"><p>Rationale: the restriction in the form of
862the argument serves two purposes. First, it makes it impossible to
863pass the address of an array to the argument, which serves to protect
864against an otherwise serious risk of mis-inferring an <q>array</q>
865argument as an out-parameter. Second, it makes it much less likely
866that the user will see confusing aliasing problems due to the
867implementation, below, where their store to the writeback temporary is
868not immediately seen in the original argument variable.</p></div>
869
870<p>A pass-by-writeback is evaluated as follows:
871<ol>
872<li>The argument is evaluated to yield a pointer <tt>p</tt> of
873 type <tt>U oq *</tt>.</li>
874<li>If <tt>p</tt> is a null pointer, then a null pointer is passed as
875 the argument, and no further work is required for the pass-by-writeback.</li>
876<li>Otherwise, a temporary of type <tt>T __autoreleasing</tt> is
877 created and initialized to a null pointer.</li>
878<li>If the argument is not an Objective-C method parameter marked
879 <tt>out</tt>, then <tt>*p</tt> is read, and the result is written
880 into the temporary with primitive semantics.</li>
881<li>The address of the temporary is passed as the argument to the
882 actual call.</li>
883<li>After the call completes, the temporary is loaded with primitive
884 semantics, and that value is assigned into <tt>*p</tt>.</li>
885</ol></p>
886
887<div class="rationale"><p>Rationale: this is all admittedly
888convoluted. In an ideal world, we would see that a local variable is
889being passed to an out-parameter and retroactively modify its type to
890be <tt>__autoreleasing</tt> rather than <tt>__strong</tt>. This would
891be remarkably difficult and not always well-founded under the C type
892system. However, it was judged unacceptably invasive to require
893programmers to write <tt>__autoreleasing</tt> on all the variables
894they intend to use for out-parameters. This was the least bad
895solution.</p></div>
896
897</div>
898
899<div id="ownership.restrictions.records">
900<h1>Ownership-qualified fields of structs and unions</h1>
901
902<p>A program is ill-formed if it declares a member of a C struct or
903union to have a nontrivially ownership-qualified type.</p>
904
905<div class="rationale"><p>Rationale: the resulting type would be
906non-POD in the C++ sense, but C does not give us very good language
907tools for managing the lifetime of aggregates, so it is more
908convenient to simply forbid them. It is still possible to manage this
909with a <tt>void*</tt> or an <tt>__unsafe_unretained</tt>
910object.</p></div>
911
912<p>This restriction does not apply in Objective-C++. However,
913nontrivally ownership-qualified types are considered non-POD: in C++0x
914terms, they are not trivially default constructible, copy
915constructible, move constructible, copy assignable, move assignable,
916or destructible. It is a violation of C++ One Definition Rule to use
917a class outside of ARC that, under ARC, would have an
918ownership-qualified member.</p>
919
920<div class="rationale"><p>Rationale: unlike in C, we can express all
921the necessary ARC semantics for ownership-qualified subobjects as
922suboperations of the (default) special member functions for the class.
923These functions then become non-trivial. This has the non-obvious
924repercussion that the class will have a non-trivial copy constructor
925and non-trivial destructor; if it wouldn't outside of ARC, this means
926that objects of the type will be passed and returned in an
927ABI-incompatible manner.</p></div>
928
929</div>
930
931</div>
932
933<div id="ownership.inference">
934<h1>Ownership inference</h1>
935
936<div id="ownership.inference.variables">
937<h1>Objects</h1>
938
939<p>If an object is declared with retainable object owner type, but
940without an explicit ownership qualifier, its type is implicitly
941adjusted to have <tt>__strong</tt> qualification.</p>
942
943<p>As a special case, if the object's base type is <tt>Class</tt>
944(possibly protocol-qualified), the type is adjusted to
945have <tt>__unsafe_unretained</tt> qualification instead.</p>
946
947</div>
948
949<div id="ownership.inference.indirect_parameters">
950<h1>Indirect parameters</h1>
951
952<p>If a function or method parameter has type <tt>T*</tt>, where
953<tt>T</tt> is an ownership-unqualified retainable object pointer type,
954then:</p>
955
956<ul>
957<li>if <tt>T</tt> is <tt>const</tt>-qualified or <tt>Class</tt>, then
958it is implicitly qualified with <tt>__unsafe_unretained</tt>;</li>
959<li>otherwise, it is implicitly qualified
960with <tt>__autoreleasing</tt>.</li>
961</ul>
962</p>
963
964<div class="rationale"><p>Rationale: <tt>__autoreleasing</tt> exists
965mostly for this case, the Cocoa convention for out-parameters. Since
966a pointer to <tt>const</tt> is obviously not an out-parameter, we
967instead use a type more useful for passing arrays. If the user
968instead intends to pass in a <em>mutable</em> array, inferring
969<tt>__autoreleasing</tt> is the wrong thing to do; this directs some
970of the caution in the following rules about writeback.</p></div>
971
972<p>Such a type written anywhere else would be ill-formed by the
973general rule requiring ownership qualifiers.</p>
974
975<p>This rule does not apply in Objective-C++ if a parameter's type is
976dependent in a template pattern and is only <em>instantiated</em> to
977a type which would be a pointer to an unqualified retainable object
978pointer type. Such code is still ill-formed.</p>
979
980<div class="rationale"><p>Rationale: the convention is very unlikely
981to be intentional in template code.</p></div>
982
983</div> <!-- ownership.inference.indirect_parameters -->
Douglas Gregore559ca12011-06-17 22:11:49 +0000984
985<div id="ownership.inference.template_arguments">
986<h1>Template arguments</h1>
987
988<p>If a template argument for a template type parameter is an
989retainable object owner type that does not have an explicit ownership
990qualifier, it is adjusted to have <tt>__strong</tt>
Douglas Gregor54fb28a2011-06-17 22:19:27 +0000991qualification. This adjustment occurs regardless of whether the
Douglas Gregore559ca12011-06-17 22:11:49 +0000992template argument was deduced or explicitly specified. </p>
993
994<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>
995
996</div> <!-- ownership.inference.template_arguments -->
John McCall82467022011-06-15 21:21:53 +0000997</div> <!-- ownership.inference -->
998</div> <!-- ownership -->
999
Douglas Gregore559ca12011-06-17 22:11:49 +00001000
John McCall82467022011-06-15 21:21:53 +00001001<div id="family">
1002<h1>Method families</h1>
1003
1004<p>An Objective-C method may fall into a <span class="term">method
1005family</span>, which is a conventional set of behaviors ascribed to it
1006by the Cocoa conventions.</p>
1007
1008<p>A method is in a certain method family if:
1009<ul>
1010<li>it has a <tt>objc_method_family</tt> attribute placing it in that
1011 family; or if not that,</li>
1012<li>it does not have an <tt>objc_method_family</tt> attribute placing
1013 it in a different or no family, and</li>
1014<li>its selector falls into the corresponding selector family, and</li>
1015<li>its signature obeys the added restrictions of the method family.</li>
1016</ul></p>
1017
1018<p>A selector is in a certain selector family if, ignoring any leading
1019underscores, the first component of the selector either consists
1020entirely of the name of the method family or it begins with that name
1021followed by a character other than a lowercase letter. For
1022example, <tt>_perform:with:</tt> and <tt>performWith:</tt> would fall
1023into the <tt>perform</tt> family (if we recognized one),
1024but <tt>performing:with</tt> would not.</p>
1025
1026<p>The families and their added restrictions are:</p>
1027
1028<ul>
1029<li><tt>alloc</tt> methods must return a retainable object pointer type.</li>
1030<li><tt>copy</tt> methods must return a retainable object pointer type.</li>
1031<li><tt>mutableCopy</tt> methods must return a retainable object pointer type.</li>
1032<li><tt>new</tt> methods must return a retainable object pointer type.</li>
1033<li><tt>init</tt> methods must be instance methods and must return an
1034Objective-C pointer type. Additionally, a program is ill-formed if it
1035declares or contains a call to an <tt>init</tt> method whose return
1036type is neither <tt>id</tt> nor a pointer to a super-class or
1037sub-class of either the declaring class, if the method was declared on
1038a class, or the static receiver type of the call, if it was declared
1039on a protocol.</p>
1040
1041<div class="rationale"><p>Rationale: there are a fair number of existing
1042methods with <tt>init</tt>-like selectors which nonetheless don't
1043follow the <tt>init</tt> conventions. Typically these are either
1044accidental naming collisions or helper methods called during
1045initialization. Because of the peculiar retain/release behavior
1046of <tt>init</tt> methods, it's very important not to treat these
1047methods as <tt>init</tt> methods if they aren't meant to be. It was
1048felt that implicitly defining these methods out of the family based on
1049the exact relationship between the return type and the declaring class
1050would much too subtle and fragile. Therefore we identify a small
1051number of legitimate-seeming return types and call everything else an
1052error. This serves the secondary purpose of encouraging programmers
1053not to accidentally give methods names in the <tt>init</tt> family.</p></div>
1054</li>
1055</ul>
1056
1057<p>A program is ill-formed if a method's declarations,
1058implementations, and overrides do not all have the same method
1059family.</p>
1060
1061<div id="family.attribute">
1062<h1>Explicit method family control</h1>
1063
1064<p>A method may be annotated with the <tt>objc_method_family</tt>
1065attribute to precisely control which method family it belongs to. If
1066a method in an <tt>@implementation</tt> does not have this attribute,
1067but there is a method declared in the corresponding <tt>@interface</tt>
1068that does, then the attribute is copied to the declaration in the
1069<tt>@implementation</tt>. The attribute is available outside of ARC,
1070and may be tested for with the preprocessor query
1071<tt>__has_attribute(objc_method_family)</tt>.</p>
1072
1073<p>The attribute is spelled
1074<tt>__attribute__((objc_method_family(<i>family</i>)))</tt>.
1075If <i>family</i> is <tt>none</tt>, the method has no family, even if
1076it would otherwise be considered to have one based on its selector and
1077type. Otherwise, <i>family</i> must be one
1078of <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>,
1079<tt>mutableCopy</tt>, or <tt>new</tt>, in which case the method is
1080considered to belong to the corresponding family regardless of its
1081selector. It is an error if a method that is explicitly added to a
1082family in this way does not meet the requirements of the family other
1083than the selector naming convention.</p>
1084
1085<div class="rationale"><p>Rationale: the rules codified in this document
1086describe the standard conventions of Objective-C. However, as these
1087conventions have not heretofore been enforced by an unforgiving
1088mechanical system, they are only imperfectly kept, especially as they
1089haven't always even been precisely defined. While it is possible to
1090define low-level ownership semantics with attributes like
1091<tt>ns_returns_retained</tt>, this attribute allows the user to
1092communicate semantic intent, which of use both to ARC (which, e.g.,
1093treats calls to <tt>init</tt> specially) and the static analyzer.</p></div>
1094</div>
1095
1096<div id="family.semantics">
1097<h1>Semantics of method families</h1>
1098
1099<p>A method's membership in a method family may imply non-standard
1100semantics for its parameters and return type.</p>
1101
1102<p>Methods in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>,
1103and <tt>new</tt> families &mdash; that is, methods in all the
1104currently-defined families except <tt>init</tt> &mdash; transfer
1105ownership of a +1 retain count on their return value to the calling
1106function, as if they were implicitly annotated with
1107the <tt>ns_returns_retained</tt> attribute. However, this is not true
1108if the method has either of the <tt>ns_returns_autoreleased</tt> or
1109<tt>ns_returns_not_retained</tt> attributes.</p>
1110
1111<div id="family.semantics.init">
1112<h1>Semantics of <tt>init</tt></h1>
1113
1114<p>Methods in the <tt>init</tt> family must be transferred ownership
1115of a +1 retain count on their <tt>self</tt> parameter, exactly as if
1116the method had the <tt>ns_consumes_self</tt> attribute, and must
1117transfer ownership of a +1 retain count on their return value, exactly
1118as if they method had the <tt>ns_returns_retained</tt> attribute.
1119Neither of these may be altered through attributes.</p>
1120
1121<p>A call to an <tt>init</tt> method with a receiver that is either
1122<tt>self</tt> (possibly parenthesized or casted) or <tt>super</tt> is
1123called a <span class="term">delegate init call</span>. It is an error
1124for a delegate init call to be made except from an <tt>init</tt>
1125method, and excluding blocks within such methods.</p>
1126
1127<p>The variable <tt>self</tt> is mutable in an <tt>init</tt> method
1128and is implicitly qualified as <tt>__strong</tt>. However, a program
1129is ill-formed, no diagnostic required, if it alters <tt>self</tt>
1130except to assign it the immediate result of a delegate init call. It
1131is an error to use the previous value of <tt>self</tt> after the
1132completion of a delegate init call.</p>
1133
1134<p>A program is ill-formed, no diagnostic required, if it causes two
1135or more calls to <tt>init</tt> methods on the same object, except that
1136each <tt>init</tt> method invocation may perform at most one
1137delegate init call.</p>
1138
1139</div> <!-- family.semantics.delegate-init -->
1140
1141<div id="family.semantics.result_type">
1142<h1>Related result types</h1>
1143
1144<p>Certain methods are candidates to have <span class="term">related
1145result types</span>:</p>
1146<ul>
1147<li>class methods in the <tt>alloc</tt> and <tt>new</tt> method families</li>
1148<li>instance methods in the <tt>init</tt> family</li>
1149<li>the instance method <tt>self</tt></li>
1150<li>outside of ARC, the instance methods <tt>retain</tt> and <tt>autorelease</tt></li>
1151</ul>
1152
1153<p>If the formal result type of such a method is <tt>id</tt> or
1154protocol-qualified <tt>id</tt>, or a type equal to the declaring class
1155or a superclass, then it is said to have a related result type. In
1156this case, when invoked in an explicit message send, it is assumed to
1157return a type related to the type of the receiver:</p>
1158
1159<ul>
1160<li>if it is a class method, and the receiver is a class
1161name <tt>T</tt>, the message send expression has type <tt>T*</tt>;
1162otherwise</li>
1163<li>if it is an instance method, and the receiver has type <tt>T</tt>,
1164the message send expression has type <tt>T</tt>; otherwise</li>
1165<li>the message send expression has the normal result type of the
1166method.</li>
1167</ul>
1168
1169<p>This is a new rule of the Objective-C language and applies outside
1170of ARC.</p>
1171
1172<div class="rationale"><p>Rationale: ARC's automatic code emission is
1173more prone than most code to signature errors, i.e. errors where a
1174call was emitted against one method signature, but the implementing
1175method has an incompatible signature. Having more precise type
1176information helps drastically lower this risks, as well as catching
1177a number of latent bugs.</p></div>
1178
1179</div> <!-- family.semantics.result_type -->
1180</div> <!-- family.semantics -->
1181</div> <!-- family -->
1182
1183<div id="optimization">
1184<h1>Optimization</h1>
1185
1186<p>ARC applies aggressive rules for the optimization of local
1187behavior. These rules are based around a core assumption of
1188<span class="term">local balancing</span>: that other code will
1189perform retains and releases as necessary (and only as necessary) for
1190its own safety, and so the optimizer does not need to consider global
1191properties of the retain and release sequence. For example, if a
1192retain and release immediately bracket a call, the optimizer can
1193delete the retain and release on the assumption that the called
1194function will not do a constant number of unmotivated releases
1195followed by a constant number of <q>balancing</q> retains, such that
1196the local retain/release pair is the only thing preventing the called
1197function from ending up with a dangling reference.</p>
1198
1199<p>The optimizer assumes that when a new value enters local control,
1200e.g. from a load of a non-local object or as the result of a function
1201call, it is instaneously valid. Subsequently, a retain and release of
1202a value are necessary on a computation path only if there is a use of
1203that value before the release and after any operation which might
1204cause a release of the value (including indirectly or non-locally),
1205and only if the value is not demonstrably already retained.</p>
1206
1207<p>The complete optimization rules are quite complicated, but it would
1208still be useful to document them here.</p>
1209
1210</div>
1211
1212<div id="misc">
1213<h1>Miscellaneous</h1>
1214
1215<div id="autoreleasepool">
1216<h1><tt>@autoreleasepool</tt></h1>
1217
1218<p>To simplify the use of autorelease pools, and to bring them under
1219the control of the compiler, a new kind of statement is available in
1220Objective-C. It is written <tt>@autoreleasepool</tt> followed by
1221a <i>compound-statement</i>, i.e. by a new scope delimited by curly
1222braces. Upon entry to this block, the current state of the
1223autorelease pool is captured. When the block is exited normally,
1224whether by fallthrough or directed control flow (such
1225as <tt>return</tt> or <tt>break</tt>), the autorelease pool is
1226restored to the saved state, releasing all the objects in it. When
1227the block is exited with an exception, the pool is not drained.</p>
1228
1229<p>A program is ill-formed if it refers to the
1230<tt>NSAutoreleasePool</tt> class.</p>
1231
1232<div class="rationale"><p>Rationale: autorelease pools are clearly
1233important for the compiler to reason about, but it is far too much to
1234expect the compiler to accurately reason about control dependencies
1235between two calls. It is also very easy to accidentally forget to
1236drain an autorelease pool when using the manual API, and this can
1237significantly inflate the process's high-water-mark. The introduction
1238of a new scope is unfortunate but basically required for sane
1239interaction with the rest of the language. Not draining the pool
1240during an unwind is apparently required by the Objective-C exceptions
1241implementation.</p></div>
1242
1243</div> <!-- autoreleasepool -->
1244
1245<div id="misc.self">
1246<h1><tt>self</tt></h1>
1247
1248<p>The <tt>self</tt> parameter variable of an Objective-C method is
1249never actually retained by the implementation. It is undefined
1250behavior, or at least dangerous, to cause an object to be deallocated
1251during a message send to that object. To make this
1252safe, <tt>self</tt> is implicitly <tt>const</tt> unless the method is
1253in the <a href="#family.semantics.init"><tt>init</tt> family</a>.</p>
1254
1255<div class="rationale"><p>Rationale: the cost of
1256retaining <tt>self</tt> in all methods was found to be prohibitive, as
1257it tends to be live across calls, preventing the optimizer from
1258proving that the retain and release are unnecessary &mdash; for good
1259reason, as it's quite possible in theory to cause an object to be
1260deallocated during its execution without this retain and release.
1261Since it's extremely uncommon to actually do so, even unintentionally,
1262and since there's no natural way for the programmer to remove this
1263retain/release pair otherwise (as there is for other parameters by,
1264say, making the variable <tt>__unsafe_unretained</tt>), we chose to
1265make this optimizing assumption and shift some amount of risk to the
1266user.</p></div>
1267
1268</div> <!-- misc.self -->
1269
1270<div id="misc.enumeration">
1271<h1>Fast enumeration iteration variables</h1>
1272
1273<p>If a variable is declared in the condition of an Objective-C fast
1274enumeration loop, and the variable has no explicit ownership
1275qualifier, then it is qualified with <tt>const __strong</tt> and
1276objects encountered during the enumeration are not actually
1277retained.</p>
1278
1279<div class="rationale"><p>Rationale: this is an optimization made
1280possible because fast enumeration loops promise to keep the objects
1281retained during enumeration, and the collection itself cannot be
1282synchronously modified. It can be overridden by explicitly qualifying
1283the variable with <tt>__strong</tt>, which will make the variable
1284mutable again and cause the loop to retain the objects it
1285encounters.</div>
1286
1287</div>
1288
1289<div id="misc.blocks">
1290<h1>Blocks</h1>
1291
1292<p>The implicit <tt>const</tt> capture variables created when
1293evaluating a block literal expression have the same ownership
1294semantics as the local variables they capture. The capture is
1295performed by reading from the captured variable and initializing the
1296capture variable with that value; the capture variable is destroyed
1297when the block literal is, i.e. at the end of the enclosing scope.</p>
1298
1299<p>The <a href="#ownership.inference">inference</a> rules apply
1300equally to <tt>__block</tt> variables, which is a shift in semantics
1301from non-ARC, where <tt>__block</tt> variables did not implicitly
1302retain during capture.</p>
1303
1304<p><tt>__block</tt> variables of retainable object owner type are
1305moved off the stack by initializing the heap copy with the result of
1306moving from the stack copy.</tt></p>
1307
1308<p>With the exception of retains done as part of initializing
1309a <tt>__strong</tt> parameter variable or reading a <tt>__weak</tt>
1310variable, whenever these semantics call for retaining a value of
1311block-pointer type, it has the effect of a <tt>Block_copy</tt>. The
1312optimizer may remove such copies when it sees that the result is
1313used only as an argument to a call.</p>
1314
1315</div> <!-- misc.blocks -->
1316
1317<div id="misc.exceptions">
1318<h1>Exceptions</h1>
1319
1320<p>By default in Objective C, ARC is not exception-safe for normal
1321releases:
1322<ul>
1323<li>It does not end the lifetime of <tt>__strong</tt> variables when
1324their scopes are abnormally terminated by an exception.</li>
1325<li>It does not perform releases which would occur at the end of
1326a full-expression if that full-expression throws an exception.</li>
1327</ul>
1328
1329<p>A program may be compiled with the option
1330<tt>-fobjc-arc-exceptions</tt> in order to enable these, or with the
1331option <tt>-fno-objc-arc-exceptions</tt> to explicitly disable them,
1332with the last such argument <q>winning</q>.</p>
1333
1334<div class="rationale"><p>Rationale: the standard Cocoa convention is
1335that exceptions signal programmer error and are not intended to be
1336recovered from. Making code exceptions-safe by default would impose
1337severe runtime and code size penalties on code that typically does not
1338actually care about exceptions safety. Therefore, ARC-generated code
1339leaks by default on exceptions, which is just fine if the process is
1340going to be immediately terminated anyway. Programs which do care
1341about recovering from exceptions should enable the option.</p></div>
1342
1343<p>In Objective-C++, <tt>-fobjc-arc-exceptions</tt> is enabled by
1344default.</p>
1345
1346<div class="rationale"><p>Rationale: C++ already introduces pervasive
1347exceptions-cleanup code of the sort that ARC introduces. C++
1348programmers who have not already disabled exceptions are much more
1349likely to actual require exception-safety.</p></div>
1350
1351<p>ARC does end the lifetimes of <tt>__weak</tt> objects when an
1352exception terminates their scope unless exceptions are disabled in the
1353compiler.</p>
1354
1355<div class="rationale"><p>Rationale: the consequence of a
1356local <tt>__weak</tt> object not being destroyed is very likely to be
1357corruption of the Objective-C runtime, so we want to be safer here.
1358Of course, potentially massive leaks are about as likely to take down
1359the process as this corruption is if the program does try to recover
1360from exceptions.</p></div>
1361
1362</div> <!-- misc.exceptions -->
1363
1364</div> <!-- misc -->
1365</div> <!-- root -->
1366</body>
1367</html>