1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 2 "http://www.w3.org/TR/html4/strict.dtd"> 3<html> 4<head> 5<title>Objective-C Automatic Reference Counting (ARC)</title> 6<link type="text/css" rel="stylesheet" href="../menu.css"> 7<link type="text/css" rel="stylesheet" href="../content.css"> 8<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 19div.rationale em { 20 font-style: normal 21} 22 23/* Revisions are also italicized. */ 24span.revision { 25 font-style: italic 26} 27 28span.whenRevised { 29 font-weight: bold; 30 font-style: normal 31} 32 33div 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 41<script type="text/javascript"> 42/// 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 222<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 254</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 261need 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> 265 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 276</div> <!-- general --> 277 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 473method 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> 476 477<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> 485 486<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> 492 493</div> <!-- objects.operands.consumed --> 494 495<div id="objects.operands.retained-returns"> 496<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> 530 531<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 544</div> <!-- objects.operands.retained-returns --> 545 546<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> 577 578</div> <!-- objects.operands.other-returns --> 579 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 617</div> <!-- objects.operands.casts --> 618 619</div> <!-- objects.operands --> 620 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 630Objective-C object pointer shall not be converted to <tt>void*</tt>. 631As an exception, cast to <tt>intptr_t</tt> is allowed because such 632casts are not transferring ownership. The <a href="#objects.operands.casts">bridged 633casts</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> 641 642<p>However, the following exceptions apply.</p> 643 644</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> 664<ul> 665<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> 669</ul> 670 671<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> 686 687<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> 697 698<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 — for example, creating a 723CF value, assigning it to an ObjC-typed local, and then 724calling <tt>CFRelease</tt> when done — 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 --> 760 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 773qualifier 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 778to a type which is already ownership-qualified, even if it is the same 779qualifier. 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> 782 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 790object 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> 791 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 833<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 868<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 891</div> <!-- ownership.spelling.property --> 892 893</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 909lvalue-to-rvalue conversion on an object lvalue.</p> 910 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> 919 920<p><span class="term">Assignment</span> occurs when evaluating 921an assignment operator. The semantics vary based on the qualification:</p> 922<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 930new 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> 935<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> 940 941<p><span class="term">Initialization</span> occurs when an object's 942lifetime begins, which depends on its storage duration. 943Initialization proceeds in two stages:</p> 944<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> 952 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 974<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 1005<div id="ownership.restrictions.autoreleasing"> 1006<h1>Storage duration of <tt>__autoreleasing</tt> objects</h1> 1007 1008<p>A program is ill-formed if it declares an <tt>__autoreleasing</tt> 1009object of non-automatic storage duration. A program is ill-formed 1010if it captures an <tt>__autoreleasing</tt> object in a block or, 1011unless by reference, in a C++11 lambda.</p> 1012 1013<div class="rationale"><p>Rationale: autorelease pools are tied to the 1014current thread and scope by their nature. While it is possible to 1015have temporary objects whose instance variables are filled with 1016autoreleased objects, there is no way that ARC can provide any sort of 1017safety guarantee there.</p></div> 1018 1019<p>It is undefined behavior if a non-null pointer is assigned to 1020an <tt>__autoreleasing</tt> object while an autorelease pool is in 1021scope and then that object is read after the autorelease pool's scope 1022is left.</p> 1023 1024</div> 1025 1026<div id="ownership.restrictions.conversion.indirect"> 1027<h1>Conversion of pointers to ownership-qualified types</h1> 1028 1029<p>A program is ill-formed if an expression of type <tt>T*</tt> is 1030converted, explicitly or implicitly, to the type <tt>U*</tt>, 1031where <tt>T</tt> and <tt>U</tt> have different ownership 1032qualification, unless:</p> 1033<ul> 1034<li><tt>T</tt> is qualified with <tt>__strong</tt>, 1035 <tt>__autoreleasing</tt>, or <tt>__unsafe_unretained</tt>, and 1036 <tt>U</tt> is qualified with both <tt>const</tt> and 1037 <tt>__unsafe_unretained</tt>; or</li> 1038<li>either <tt>T</tt> or <tt>U</tt> is <tt>cv void</tt>, where 1039<tt>cv</tt> is an optional sequence of non-ownership qualifiers; or</li> 1040<li>the conversion is requested with a <tt>reinterpret_cast</tt> in 1041 Objective-C++; or</li> 1042<li>the conversion is a 1043well-formed <a href="#ownership.restrictions.pass_by_writeback">pass-by-writeback</a>.</li> 1044</ul> 1045 1046<p>The analogous rule applies to <tt>T&</tt> and <tt>U&</tt> in 1047Objective-C++.</p> 1048 1049<div class="rationale"><p>Rationale: these rules provide a reasonable 1050level of type-safety for indirect pointers, as long as the underlying 1051memory is not deallocated. The conversion to <tt>const 1052__unsafe_unretained</tt> is permitted because the semantics of reads 1053are equivalent across all these ownership semantics, and that's a very 1054useful and common pattern. The interconversion with <tt>void*</tt> is 1055useful for allocating memory or otherwise escaping the type system, 1056but use it carefully. <tt>reinterpret_cast</tt> is considered to be 1057an obvious enough sign of taking responsibility for any 1058problems.</p></div> 1059 1060<p>It is undefined behavior to access an ownership-qualified object 1061through an lvalue of a differently-qualified type, except that any 1062non-<tt>__weak</tt> object may be read through 1063an <tt>__unsafe_unretained</tt> lvalue.</p> 1064 1065<p>It is undefined behavior if a managed operation is performed on 1066a <tt>__strong</tt> or <tt>__weak</tt> object without a guarantee that 1067it contains a primitive zero bit-pattern, or if the storage for such 1068an object is freed or reused without the object being first assigned a 1069null pointer.</p> 1070 1071<div class="rationale"><p>Rationale: ARC cannot differentiate between 1072an assignment operator which is intended to <q>initialize</q> dynamic 1073memory and one which is intended to potentially replace a value. 1074Therefore the object's pointer must be valid before letting ARC at it. 1075Similarly, C and Objective-C do not provide any language hooks for 1076destroying objects held in dynamic memory, so it is the programmer's 1077responsibility to avoid leaks (<tt>__strong</tt> objects) and 1078consistency errors (<tt>__weak</tt> objects).</p> 1079 1080<p>These requirements are followed automatically in Objective-C++ when 1081creating objects of retainable object owner type with <tt>new</tt> 1082or <tt>new[]</tt> and destroying them with <tt>delete</tt>, 1083<tt>delete[]</tt>, or a pseudo-destructor expression. Note that 1084arrays of nontrivially-ownership-qualified type are not ABI compatible 1085with non-ARC code because the element type is non-POD: such arrays 1086that are <tt>new[]</tt>'d in ARC translation units cannot 1087be <tt>delete[]</tt>'d in non-ARC translation units and 1088vice-versa.</p></div> 1089 1090</div> 1091 1092<div id="ownership.restrictions.pass_by_writeback"> 1093<h1>Passing to an out parameter by writeback</h1> 1094 1095<p>If the argument passed to a parameter of type 1096<tt>T __autoreleasing *</tt> has type <tt>U oq *</tt>, 1097where <tt>oq</tt> is an ownership qualifier, then the argument is a 1098candidate for <span class="term">pass-by-writeback</span> if:</p> 1099 1100<ul> 1101<li><tt>oq</tt> is <tt>__strong</tt> or <tt>__weak</tt>, and</li> 1102<li>it would be legal to initialize a <tt>T __strong *</tt> with 1103a <tt>U __strong *</tt>.</li> 1104</ul> 1105 1106<p>For purposes of overload resolution, an implicit conversion 1107sequence requiring a pass-by-writeback is always worse than an 1108implicit conversion sequence not requiring a pass-by-writeback.</p> 1109 1110<p>The pass-by-writeback is ill-formed if the argument expression does 1111not have a legal form:</p> 1112 1113<ul> 1114<li><tt>&var</tt>, where <tt>var</tt> is a scalar variable of 1115automatic storage duration with retainable object pointer type</li> 1116<li>a conditional expression where the second and third operands are 1117both legal forms</li> 1118<li>a cast whose operand is a legal form</li> 1119<li>a null pointer constant</li> 1120</ul> 1121 1122<div class="rationale"><p>Rationale: the restriction in the form of 1123the argument serves two purposes. First, it makes it impossible to 1124pass the address of an array to the argument, which serves to protect 1125against an otherwise serious risk of mis-inferring an <q>array</q> 1126argument as an out-parameter. Second, it makes it much less likely 1127that the user will see confusing aliasing problems due to the 1128implementation, below, where their store to the writeback temporary is 1129not immediately seen in the original argument variable.</p></div> 1130 1131<p>A pass-by-writeback is evaluated as follows:</p> 1132<ol> 1133<li>The argument is evaluated to yield a pointer <tt>p</tt> of 1134 type <tt>U oq *</tt>.</li> 1135<li>If <tt>p</tt> is a null pointer, then a null pointer is passed as 1136 the argument, and no further work is required for the pass-by-writeback.</li> 1137<li>Otherwise, a temporary of type <tt>T __autoreleasing</tt> is 1138 created and initialized to a null pointer.</li> 1139<li>If the parameter is not an Objective-C method parameter marked 1140 <tt>out</tt>, then <tt>*p</tt> is read, and the result is written 1141 into the temporary with primitive semantics.</li> 1142<li>The address of the temporary is passed as the argument to the 1143 actual call.</li> 1144<li>After the call completes, the temporary is loaded with primitive 1145 semantics, and that value is assigned into <tt>*p</tt>.</li> 1146</ol> 1147 1148<div class="rationale"><p>Rationale: this is all admittedly 1149convoluted. In an ideal world, we would see that a local variable is 1150being passed to an out-parameter and retroactively modify its type to 1151be <tt>__autoreleasing</tt> rather than <tt>__strong</tt>. This would 1152be remarkably difficult and not always well-founded under the C type 1153system. However, it was judged unacceptably invasive to require 1154programmers to write <tt>__autoreleasing</tt> on all the variables 1155they intend to use for out-parameters. This was the least bad 1156solution.</p></div> 1157 1158</div> 1159 1160<div id="ownership.restrictions.records"> 1161<h1>Ownership-qualified fields of structs and unions</h1> 1162 1163<p>A program is ill-formed if it declares a member of a C struct or 1164union to have a nontrivially ownership-qualified type.</p> 1165 1166<div class="rationale"><p>Rationale: the resulting type would be 1167non-POD in the C++ sense, but C does not give us very good language 1168tools for managing the lifetime of aggregates, so it is more 1169convenient to simply forbid them. It is still possible to manage this 1170with a <tt>void*</tt> or an <tt>__unsafe_unretained</tt> 1171object.</p></div> 1172 1173<p>This restriction does not apply in Objective-C++. However, 1174nontrivally ownership-qualified types are considered non-POD: in C++11 1175terms, they are not trivially default constructible, copy 1176constructible, move constructible, copy assignable, move assignable, 1177or destructible. It is a violation of C++'s One Definition Rule to use 1178a class outside of ARC that, under ARC, would have a nontrivially 1179ownership-qualified member.</p> 1180 1181<div class="rationale"><p>Rationale: unlike in C, we can express all 1182the necessary ARC semantics for ownership-qualified subobjects as 1183suboperations of the (default) special member functions for the class. 1184These functions then become non-trivial. This has the non-obvious 1185result that the class will have a non-trivial copy constructor and 1186non-trivial destructor; if this would not normally be true outside of 1187ARC, objects of the type will be passed and returned in an 1188ABI-incompatible manner.</p></div> 1189 1190</div> 1191 1192</div> 1193 1194<div id="ownership.inference"> 1195<h1>Ownership inference</h1> 1196 1197<div id="ownership.inference.variables"> 1198<h1>Objects</h1> 1199 1200<p>If an object is declared with retainable object owner type, but 1201without an explicit ownership qualifier, its type is implicitly 1202adjusted to have <tt>__strong</tt> qualification.</p> 1203 1204<p>As a special case, if the object's base type is <tt>Class</tt> 1205(possibly protocol-qualified), the type is adjusted to 1206have <tt>__unsafe_unretained</tt> qualification instead.</p> 1207 1208</div> 1209 1210<div id="ownership.inference.indirect_parameters"> 1211<h1>Indirect parameters</h1> 1212 1213<p>If a function or method parameter has type <tt>T*</tt>, where 1214<tt>T</tt> is an ownership-unqualified retainable object pointer type, 1215then:</p> 1216 1217<ul> 1218<li>if <tt>T</tt> is <tt>const</tt>-qualified or <tt>Class</tt>, then 1219it is implicitly qualified with <tt>__unsafe_unretained</tt>;</li> 1220<li>otherwise, it is implicitly qualified 1221with <tt>__autoreleasing</tt>.</li> 1222</ul> 1223 1224<div class="rationale"><p>Rationale: <tt>__autoreleasing</tt> exists 1225mostly for this case, the Cocoa convention for out-parameters. Since 1226a pointer to <tt>const</tt> is obviously not an out-parameter, we 1227instead use a type more useful for passing arrays. If the user 1228instead intends to pass in a <em>mutable</em> array, inferring 1229<tt>__autoreleasing</tt> is the wrong thing to do; this directs some 1230of the caution in the following rules about writeback.</p></div> 1231 1232<p>Such a type written anywhere else would be ill-formed by the 1233general rule requiring ownership qualifiers.</p> 1234 1235<p>This rule does not apply in Objective-C++ if a parameter's type is 1236dependent in a template pattern and is only <em>instantiated</em> to 1237a type which would be a pointer to an unqualified retainable object 1238pointer type. Such code is still ill-formed.</p> 1239 1240<div class="rationale"><p>Rationale: the convention is very unlikely 1241to be intentional in template code.</p></div> 1242 1243</div> <!-- ownership.inference.indirect_parameters --> 1244 1245<div id="ownership.inference.template_arguments"> 1246<h1>Template arguments</h1> 1247 1248<p>If a template argument for a template type parameter is an 1249retainable object owner type that does not have an explicit ownership 1250qualifier, it is adjusted to have <tt>__strong</tt> 1251qualification. This adjustment occurs regardless of whether the 1252template argument was deduced or explicitly specified. </p> 1253 1254<div class="rationale"><p>Rationale: <tt>__strong</tt> is a useful default for containers (e.g., <tt>std::vector<id></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> 1255 1256</div> <!-- ownership.inference.template_arguments --> 1257</div> <!-- ownership.inference --> 1258</div> <!-- ownership --> 1259 1260 1261<div id="family"> 1262<h1>Method families</h1> 1263 1264<p>An Objective-C method may fall into a <span class="term">method 1265family</span>, which is a conventional set of behaviors ascribed to it 1266by the Cocoa conventions.</p> 1267 1268<p>A method is in a certain method family if:</p> 1269<ul> 1270<li>it has a <tt>objc_method_family</tt> attribute placing it in that 1271 family; or if not that,</li> 1272<li>it does not have an <tt>objc_method_family</tt> attribute placing 1273 it in a different or no family, and</li> 1274<li>its selector falls into the corresponding selector family, and</li> 1275<li>its signature obeys the added restrictions of the method family.</li> 1276</ul> 1277 1278<p>A selector is in a certain selector family if, ignoring any leading 1279underscores, the first component of the selector either consists 1280entirely of the name of the method family or it begins with that name 1281followed by a character other than a lowercase letter. For 1282example, <tt>_perform:with:</tt> and <tt>performWith:</tt> would fall 1283into the <tt>perform</tt> family (if we recognized one), 1284but <tt>performing:with</tt> would not.</p> 1285 1286<p>The families and their added restrictions are:</p> 1287 1288<ul> 1289<li><tt>alloc</tt> methods must return a retainable object pointer type.</li> 1290<li><tt>copy</tt> methods must return a retainable object pointer type.</li> 1291<li><tt>mutableCopy</tt> methods must return a retainable object pointer type.</li> 1292<li><tt>new</tt> methods must return a retainable object pointer type.</li> 1293<li><tt>init</tt> methods must be instance methods and must return an 1294Objective-C pointer type. Additionally, a program is ill-formed if it 1295declares or contains a call to an <tt>init</tt> method whose return 1296type is neither <tt>id</tt> nor a pointer to a super-class or 1297sub-class of the declaring class (if the method was declared on 1298a class) or the static receiver type of the call (if it was declared 1299on a protocol). 1300 1301<div class="rationale"><p>Rationale: there are a fair number of existing 1302methods with <tt>init</tt>-like selectors which nonetheless don't 1303follow the <tt>init</tt> conventions. Typically these are either 1304accidental naming collisions or helper methods called during 1305initialization. Because of the peculiar retain/release behavior 1306of <tt>init</tt> methods, it's very important not to treat these 1307methods as <tt>init</tt> methods if they aren't meant to be. It was 1308felt that implicitly defining these methods out of the family based on 1309the exact relationship between the return type and the declaring class 1310would be much too subtle and fragile. Therefore we identify a small 1311number of legitimate-seeming return types and call everything else an 1312error. This serves the secondary purpose of encouraging programmers 1313not to accidentally give methods names in the <tt>init</tt> family.</p> 1314 1315<p>Note that a method with an <tt>init</tt>-family selector which 1316returns a non-Objective-C type (e.g. <tt>void</tt>) is perfectly 1317well-formed; it simply isn't in the <tt>init</tt> family.</p></div> 1318</li> 1319</ul> 1320 1321<p>A program is ill-formed if a method's declarations, 1322implementations, and overrides do not all have the same method 1323family.</p> 1324 1325<div id="family.attribute"> 1326<h1>Explicit method family control</h1> 1327 1328<p>A method may be annotated with the <tt>objc_method_family</tt> 1329attribute to precisely control which method family it belongs to. If 1330a method in an <tt>@implementation</tt> does not have this attribute, 1331but there is a method declared in the corresponding <tt>@interface</tt> 1332that does, then the attribute is copied to the declaration in the 1333<tt>@implementation</tt>. The attribute is available outside of ARC, 1334and may be tested for with the preprocessor query 1335<tt>__has_attribute(objc_method_family)</tt>.</p> 1336 1337<p>The attribute is spelled 1338<tt>__attribute__((objc_method_family(<i>family</i>)))</tt>. 1339If <i>family</i> is <tt>none</tt>, the method has no family, even if 1340it would otherwise be considered to have one based on its selector and 1341type. Otherwise, <i>family</i> must be one 1342of <tt>alloc</tt>, <tt>copy</tt>, <tt>init</tt>, 1343<tt>mutableCopy</tt>, or <tt>new</tt>, in which case the method is 1344considered to belong to the corresponding family regardless of its 1345selector. It is an error if a method that is explicitly added to a 1346family in this way does not meet the requirements of the family other 1347than the selector naming convention.</p> 1348 1349<div class="rationale"><p>Rationale: the rules codified in this document 1350describe the standard conventions of Objective-C. However, as these 1351conventions have not heretofore been enforced by an unforgiving 1352mechanical system, they are only imperfectly kept, especially as they 1353haven't always even been precisely defined. While it is possible to 1354define low-level ownership semantics with attributes like 1355<tt>ns_returns_retained</tt>, this attribute allows the user to 1356communicate semantic intent, which is of use both to ARC (which, e.g., 1357treats calls to <tt>init</tt> specially) and the static analyzer.</p></div> 1358</div> 1359 1360<div id="family.semantics"> 1361<h1>Semantics of method families</h1> 1362 1363<p>A method's membership in a method family may imply non-standard 1364semantics for its parameters and return type.</p> 1365 1366<p>Methods in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>, 1367and <tt>new</tt> families — that is, methods in all the 1368currently-defined families except <tt>init</tt> — implicitly 1369<a href="#objects.operands.retained_returns">return a retained 1370object</a> as if they were annotated with 1371the <tt>ns_returns_retained</tt> attribute. This can be overridden by 1372annotating the method with either of 1373the <tt>ns_returns_autoreleased</tt> or 1374<tt>ns_returns_not_retained</tt> attributes.</p> 1375 1376<p>Properties also follow same naming rules as methods. This means that 1377those in the <tt>alloc</tt>, <tt>copy</tt>, <tt>mutableCopy</tt>, 1378and <tt>new</tt> families provide access to 1379<a href="#objects.operands.retained_returns">retained objects</a>. 1380This can be overridden by annotating the property with 1381<tt>ns_returns_not_retained</tt> attribute.</p> 1382 1383<div id="family.semantics.init"> 1384<h1>Semantics of <tt>init</tt></h1> 1385<p>Methods in the <tt>init</tt> family implicitly 1386<a href="#objects.operands.consumed">consume</a> their <tt>self</tt> 1387parameter and <a href="#objects.operands.retained_returns">return a 1388retained object</a>. Neither of these properties can be altered 1389through attributes.</p> 1390 1391<p>A call to an <tt>init</tt> method with a receiver that is either 1392<tt>self</tt> (possibly parenthesized or casted) or <tt>super</tt> is 1393called a <span class="term">delegate init call</span>. It is an error 1394for a delegate init call to be made except from an <tt>init</tt> 1395method, and excluding blocks within such methods.</p> 1396 1397<p>As an exception to the <a href="misc.self">usual rule</a>, the 1398variable <tt>self</tt> is mutable in an <tt>init</tt> method and has 1399the usual semantics for a <tt>__strong</tt> variable. However, it is 1400undefined behavior and the program is ill-formed, no diagnostic 1401required, if an <tt>init</tt> method attempts to use the previous 1402value of <tt>self</tt> after the completion of a delegate init call. 1403It is conventional, but not required, for an <tt>init</tt> method to 1404return <tt>self</tt>.</p> 1405 1406<p>It is undefined behavior for a program to cause two or more calls 1407to <tt>init</tt> methods on the same object, except that 1408each <tt>init</tt> method invocation may perform at most one delegate 1409init call.</p> 1410 1411</div> <!-- family.semantics.init --> 1412 1413<div id="family.semantics.result_type"> 1414<h1>Related result types</h1> 1415 1416<p>Certain methods are candidates to have <span class="term">related 1417result types</span>:</p> 1418<ul> 1419<li>class methods in the <tt>alloc</tt> and <tt>new</tt> method families</li> 1420<li>instance methods in the <tt>init</tt> family</li> 1421<li>the instance method <tt>self</tt></li> 1422<li>outside of ARC, the instance methods <tt>retain</tt> and <tt>autorelease</tt></li> 1423</ul> 1424 1425<p>If the formal result type of such a method is <tt>id</tt> or 1426protocol-qualified <tt>id</tt>, or a type equal to the declaring class 1427or a superclass, then it is said to have a related result type. In 1428this case, when invoked in an explicit message send, it is assumed to 1429return a type related to the type of the receiver:</p> 1430 1431<ul> 1432<li>if it is a class method, and the receiver is a class 1433name <tt>T</tt>, the message send expression has type <tt>T*</tt>; 1434otherwise</li> 1435<li>if it is an instance method, and the receiver has type <tt>T</tt>, 1436the message send expression has type <tt>T</tt>; otherwise</li> 1437<li>the message send expression has the normal result type of the 1438method.</li> 1439</ul> 1440 1441<p>This is a new rule of the Objective-C language and applies outside 1442of ARC.</p> 1443 1444<div class="rationale"><p>Rationale: ARC's automatic code emission is 1445more prone than most code to signature errors, i.e. errors where a 1446call was emitted against one method signature, but the implementing 1447method has an incompatible signature. Having more precise type 1448information helps drastically lower this risk, as well as catching 1449a number of latent bugs.</p></div> 1450 1451</div> <!-- family.semantics.result_type --> 1452</div> <!-- family.semantics --> 1453</div> <!-- family --> 1454 1455<div id="optimization"> 1456<h1>Optimization</h1> 1457 1458<p>ARC applies aggressive rules for the optimization of local 1459behavior. These rules are based around a core assumption of 1460<span class="term">local balancing</span>: that other code will 1461perform retains and releases as necessary (and only as necessary) for 1462its own safety, and so the optimizer does not need to consider global 1463properties of the retain and release sequence. For example, if a 1464retain and release immediately bracket a call, the optimizer can 1465delete the retain and release on the assumption that the called 1466function will not do a constant number of unmotivated releases 1467followed by a constant number of <q>balancing</q> retains, such that 1468the local retain/release pair is the only thing preventing the called 1469function from ending up with a dangling reference.</p> 1470 1471<p>The optimizer assumes that when a new value enters local control, 1472e.g. from a load of a non-local object or as the result of a function 1473call, it is instaneously valid. Subsequently, a retain and release of 1474a value are necessary on a computation path only if there is a use of 1475that value before the release and after any operation which might 1476cause a release of the value (including indirectly or non-locally), 1477and only if the value is not demonstrably already retained.</p> 1478 1479<p>The complete optimization rules are quite complicated, but it would 1480still be useful to document them here.</p> 1481 1482<div id="optimization.precise"> 1483<h1>Precise lifetime semantics</h1> 1484 1485<p>In general, ARC maintains an invariant that a retainable object 1486pointer held in a <tt>__strong</tt> object will be retained for the 1487full formal lifetime of the object. Objects subject to this invariant 1488have <span class="term">precise lifetime semantics</span>.</p> 1489 1490<p>By default, local variables of automatic storage duration do not 1491have precise lifetime semantics. Such objects are simply strong 1492references which hold values of retainable object pointer type, and 1493these values are still fully subject to the optimizations on values 1494under local control.</p> 1495 1496<div class="rationale"><p>Rationale: applying these precise-lifetime 1497semantics strictly would be prohibitive. Many useful optimizations 1498that might theoretically decrease the lifetime of an object would be 1499rendered impossible. Essentially, it promises too much.</p></div> 1500 1501<p>A local variable of retainable object owner type and automatic 1502storage duration may be annotated with the <tt>objc_precise_lifetime</tt> 1503attribute to indicate that it should be considered to be an object 1504with precise lifetime semantics.</p> 1505 1506<div class="rationale"><p>Rationale: nonetheless, it is sometimes 1507useful to be able to force an object to be released at a precise time, 1508even if that object does not appear to be used. This is likely to be 1509uncommon enough that the syntactic weight of explicitly requesting 1510these semantics will not be burdensome, and may even make the code 1511clearer.</p></div> 1512 1513</div> <!-- optimization.precise --> 1514 1515</div> <!-- optimization --> 1516 1517<div id="misc"> 1518<h1>Miscellaneous</h1> 1519 1520<div id="misc.special_methods"> 1521<h1>Special methods</h1> 1522 1523<div id="misc.special_methods.retain"> 1524<h1>Memory management methods</h1> 1525 1526<p>A program is ill-formed if it contains a method definition, message 1527send, or <tt>@selector</tt> expression for any of the following 1528selectors:</p> 1529<ul> 1530<li><tt>autorelease</tt></li> 1531<li><tt>release</tt></li> 1532<li><tt>retain</tt></li> 1533<li><tt>retainCount</tt></li> 1534</ul> 1535 1536<div class="rationale"><p>Rationale: <tt>retainCount</tt> is banned 1537because ARC robs it of consistent semantics. The others were banned 1538after weighing three options for how to deal with message sends:</p> 1539 1540<p><b>Honoring</b> them would work out very poorly if a programmer 1541naively or accidentally tried to incorporate code written for manual 1542retain/release code into an ARC program. At best, such code would do 1543twice as much work as necessary; quite frequently, however, ARC and 1544the explicit code would both try to balance the same retain, leading 1545to crashes. The cost is losing the ability to perform <q>unrooted</q> 1546retains, i.e. retains not logically corresponding to a strong 1547reference in the object graph.</p> 1548 1549<p><b>Ignoring</b> them would badly violate user expectations about their 1550code. While it <em>would</em> make it easier to develop code simultaneously 1551for ARC and non-ARC, there is very little reason to do so except for 1552certain library developers. ARC and non-ARC translation units share 1553an execution model and can seamlessly interoperate. Within a 1554translation unit, a developer who faithfully maintains their code in 1555non-ARC mode is suffering all the restrictions of ARC for zero 1556benefit, while a developer who isn't testing the non-ARC mode is 1557likely to be unpleasantly surprised if they try to go back to it.</p> 1558 1559<p><b>Banning</b> them has the disadvantage of making it very awkward 1560to migrate existing code to ARC. The best answer to that, given a 1561number of other changes and restrictions in ARC, is to provide a 1562specialized tool to assist users in that migration.</p> 1563 1564<p>Implementing these methods was banned because they are too integral 1565to the semantics of ARC; many tricks which worked tolerably under 1566manual reference counting will misbehave if ARC performs an ephemeral 1567extra retain or two. If absolutely required, it is still possible to 1568implement them in non-ARC code, for example in a category; the 1569implementations must obey the <a href="#objects.retains">semantics</a> 1570laid out elsewhere in this document.</p> 1571 1572</div> 1573</div> <!-- misc.special_methods.retain --> 1574 1575<div id="misc.special_methods.dealloc"> 1576<h1><tt>dealloc</tt></h1> 1577 1578<p>A program is ill-formed if it contains a message send 1579or <tt>@selector</tt> expression for the selector <tt>dealloc</tt>.</p> 1580 1581<div class="rationale"><p>Rationale: there are no legitimate reasons 1582to call <tt>dealloc</tt> directly.</p></div> 1583 1584<p>A class may provide a method definition for an instance method 1585named <tt>dealloc</tt>. This method will be called after the final 1586<tt>release</tt> of the object but before it is deallocated or any of 1587its instance variables are destroyed. The superclass's implementation 1588of <tt>dealloc</tt> will be called automatically when the method 1589returns.</p> 1590 1591<div class="rationale"><p>Rationale: even though ARC destroys instance 1592variables automatically, there are still legitimate reasons to write 1593a <tt>dealloc</tt> method, such as freeing non-retainable resources. 1594Failing to call <tt>[super dealloc]</tt> in such a method is nearly 1595always a bug. Sometimes, the object is simply trying to prevent 1596itself from being destroyed, but <tt>dealloc</tt> is really far too 1597late for the object to be raising such objections. Somewhat more 1598legitimately, an object may have been pool-allocated and should not be 1599deallocated with <tt>free</tt>; for now, this can only be supported 1600with a <tt>dealloc</tt> implementation outside of ARC. Such an 1601implementation must be very careful to do all the other work 1602that <tt>NSObject</tt>'s <tt>dealloc</tt> would, which is outside the 1603scope of this document to describe.</p></div> 1604 1605</div> 1606 1607</div> <!-- misc.special_methods --> 1608 1609<div id="autoreleasepool"> 1610<h1><tt>@autoreleasepool</tt></h1> 1611 1612<p>To simplify the use of autorelease pools, and to bring them under 1613the control of the compiler, a new kind of statement is available in 1614Objective-C. It is written <tt>@autoreleasepool</tt> followed by 1615a <i>compound-statement</i>, i.e. by a new scope delimited by curly 1616braces. Upon entry to this block, the current state of the 1617autorelease pool is captured. When the block is exited normally, 1618whether by fallthrough or directed control flow (such 1619as <tt>return</tt> or <tt>break</tt>), the autorelease pool is 1620restored to the saved state, releasing all the objects in it. When 1621the block is exited with an exception, the pool is not drained.</p> 1622 1623<p><tt>@autoreleasepool</tt> may be used in non-ARC translation units, 1624with equivalent semantics.</p> 1625 1626<p>A program is ill-formed if it refers to the 1627<tt>NSAutoreleasePool</tt> class.</p> 1628 1629<div class="rationale"><p>Rationale: autorelease pools are clearly 1630important for the compiler to reason about, but it is far too much to 1631expect the compiler to accurately reason about control dependencies 1632between two calls. It is also very easy to accidentally forget to 1633drain an autorelease pool when using the manual API, and this can 1634significantly inflate the process's high-water-mark. The introduction 1635of a new scope is unfortunate but basically required for sane 1636interaction with the rest of the language. Not draining the pool 1637during an unwind is apparently required by the Objective-C exceptions 1638implementation.</p></div> 1639 1640</div> <!-- autoreleasepool --> 1641 1642<div id="misc.self"> 1643<h1><tt>self</tt></h1> 1644 1645<p>The <tt>self</tt> parameter variable of an Objective-C method is 1646never actually retained by the implementation. It is undefined 1647behavior, or at least dangerous, to cause an object to be deallocated 1648during a message send to that object.</p> 1649 1650<p>To make this safe, for Objective-C instance methods <tt>self</tt> is 1651implicitly <tt>const</tt> unless the method is in the <a 1652href="#family.semantics.init"><tt>init</tt> family</a>. Further, <tt>self</tt> 1653is <b>always</b> implicitly <tt>const</tt> within a class method.</p> 1654 1655<div class="rationale"><p>Rationale: the cost of 1656retaining <tt>self</tt> in all methods was found to be prohibitive, as 1657it tends to be live across calls, preventing the optimizer from 1658proving that the retain and release are unnecessary — for good 1659reason, as it's quite possible in theory to cause an object to be 1660deallocated during its execution without this retain and release. 1661Since it's extremely uncommon to actually do so, even unintentionally, 1662and since there's no natural way for the programmer to remove this 1663retain/release pair otherwise (as there is for other parameters by, 1664say, making the variable <tt>__unsafe_unretained</tt>), we chose to 1665make this optimizing assumption and shift some amount of risk to the 1666user.</p></div> 1667 1668</div> <!-- misc.self --> 1669 1670<div id="misc.enumeration"> 1671<h1>Fast enumeration iteration variables</h1> 1672 1673<p>If a variable is declared in the condition of an Objective-C fast 1674enumeration loop, and the variable has no explicit ownership 1675qualifier, then it is qualified with <tt>const __strong</tt> and 1676objects encountered during the enumeration are not actually 1677retained.</p> 1678 1679<div class="rationale"><p>Rationale: this is an optimization made 1680possible because fast enumeration loops promise to keep the objects 1681retained during enumeration, and the collection itself cannot be 1682synchronously modified. It can be overridden by explicitly qualifying 1683the variable with <tt>__strong</tt>, which will make the variable 1684mutable again and cause the loop to retain the objects it 1685encounters.</p></div> 1686 1687</div> <!-- misc.enumeration --> 1688 1689<div id="misc.blocks"> 1690<h1>Blocks</h1> 1691 1692<p>The implicit <tt>const</tt> capture variables created when 1693evaluating a block literal expression have the same ownership 1694semantics as the local variables they capture. The capture is 1695performed by reading from the captured variable and initializing the 1696capture variable with that value; the capture variable is destroyed 1697when the block literal is, i.e. at the end of the enclosing scope.</p> 1698 1699<p>The <a href="#ownership.inference">inference</a> rules apply 1700equally to <tt>__block</tt> variables, which is a shift in semantics 1701from non-ARC, where <tt>__block</tt> variables did not implicitly 1702retain during capture.</p> 1703 1704<p><tt>__block</tt> variables of retainable object owner type are 1705moved off the stack by initializing the heap copy with the result of 1706moving from the stack copy.</p> 1707 1708<p>With the exception of retains done as part of initializing 1709a <tt>__strong</tt> parameter variable or reading a <tt>__weak</tt> 1710variable, whenever these semantics call for retaining a value of 1711block-pointer type, it has the effect of a <tt>Block_copy</tt>. The 1712optimizer may remove such copies when it sees that the result is 1713used only as an argument to a call.</p> 1714 1715</div> <!-- misc.blocks --> 1716 1717<div id="misc.exceptions"> 1718<h1>Exceptions</h1> 1719 1720<p>By default in Objective C, ARC is not exception-safe for normal 1721releases:</p> 1722<ul> 1723<li>It does not end the lifetime of <tt>__strong</tt> variables when 1724their scopes are abnormally terminated by an exception.</li> 1725<li>It does not perform releases which would occur at the end of 1726a full-expression if that full-expression throws an exception.</li> 1727</ul> 1728 1729<p>A program may be compiled with the option 1730<tt>-fobjc-arc-exceptions</tt> in order to enable these, or with the 1731option <tt>-fno-objc-arc-exceptions</tt> to explicitly disable them, 1732with the last such argument <q>winning</q>.</p> 1733 1734<div class="rationale"><p>Rationale: the standard Cocoa convention is 1735that exceptions signal programmer error and are not intended to be 1736recovered from. Making code exceptions-safe by default would impose 1737severe runtime and code size penalties on code that typically does not 1738actually care about exceptions safety. Therefore, ARC-generated code 1739leaks by default on exceptions, which is just fine if the process is 1740going to be immediately terminated anyway. Programs which do care 1741about recovering from exceptions should enable the option.</p></div> 1742 1743<p>In Objective-C++, <tt>-fobjc-arc-exceptions</tt> is enabled by 1744default.</p> 1745 1746<div class="rationale"><p>Rationale: C++ already introduces pervasive 1747exceptions-cleanup code of the sort that ARC introduces. C++ 1748programmers who have not already disabled exceptions are much more 1749likely to actual require exception-safety.</p></div> 1750 1751<p>ARC does end the lifetimes of <tt>__weak</tt> objects when an 1752exception terminates their scope unless exceptions are disabled in the 1753compiler.</p> 1754 1755<div class="rationale"><p>Rationale: the consequence of a 1756local <tt>__weak</tt> object not being destroyed is very likely to be 1757corruption of the Objective-C runtime, so we want to be safer here. 1758Of course, potentially massive leaks are about as likely to take down 1759the process as this corruption is if the program does try to recover 1760from exceptions.</p></div> 1761 1762</div> <!-- misc.exceptions --> 1763 1764<div id="misc.interior"> 1765<h1>Interior pointers</h1> 1766 1767<p>An Objective-C method returning a non-retainable pointer may be 1768annotated with the <tt>objc_returns_inner_pointer</tt> attribute to 1769indicate that it returns a handle to the internal data of an object, 1770and that this reference will be invalidated if the object is 1771destroyed. When such a message is sent to an object, the object's 1772lifetime will be extended until at least the earliest of:</p> 1773 1774<ul> 1775<li>the last use of the returned pointer, or any pointer derived from 1776it, in the calling function or</li> 1777<li>the autorelease pool is restored to a previous state.</li> 1778</ul> 1779 1780<div class="rationale"><p>Rationale: not all memory and resources are 1781managed with reference counts; it is common for objects to manage 1782private resources in their own, private way. Typically these 1783resources are completely encapsulated within the object, but some 1784classes offer their users direct access for efficiency. If ARC is not 1785aware of methods that return such <q>interior</q> pointers, its 1786optimizations can cause the owning object to be reclaimed too soon. 1787This attribute informs ARC that it must tread lightly.</p> 1788 1789<p>The extension rules are somewhat intentionally vague. The 1790autorelease pool limit is there to permit a simple implementation to 1791simply retain and autorelease the receiver. The other limit permits 1792some amount of optimization. The phrase <q>derived from</q> is 1793intended to encompass the results both of pointer transformations, 1794such as casts and arithmetic, and of loading from such derived 1795pointers; furthermore, it applies whether or not such derivations are 1796applied directly in the calling code or by other utility code (for 1797example, the C library routine <tt>strchr</tt>). However, the 1798implementation never need account for uses after a return from the 1799code which calls the method returning an interior pointer.</p></div> 1800 1801<p>As an exception, no extension is required if the receiver is loaded 1802directly from a <tt>__strong</tt> object 1803with <a href="#optimization.precise">precise lifetime semantics</a>.</p> 1804 1805<div class="rationale"><p>Rationale: implicit autoreleases carry the 1806risk of significantly inflating memory use, so it's important to 1807provide users a way of avoiding these autoreleases. Tying this to 1808precise lifetime semantics is ideal, as for local variables this 1809requires a very explicit annotation, which allows ARC to trust the 1810user with good cheer.</p></div> 1811 1812</div> <!-- misc.interior --> 1813 1814<div id="misc.c-retainable"> 1815<h1>C retainable pointer types</h1> 1816 1817<p>A type is a <span class="term">C retainable pointer type</span> 1818if it is a pointer to (possibly qualified) <tt>void</tt> or a 1819pointer to a (possibly qualifier) <tt>struct</tt> or <tt>class</tt> 1820type.</p> 1821 1822<div class="rationale"><p>Rationale: ARC does not manage pointers of 1823CoreFoundation type (or any of the related families of retainable C 1824pointers which interoperate with Objective-C for retain/release 1825operation). In fact, ARC does not even know how to distinguish these 1826types from arbitrary C pointer types. The intent of this concept is 1827to filter out some obviously non-object types while leaving a hook for 1828later tightening if a means of exhaustively marking CF types is made 1829available.</p></div> 1830 1831<div id="misc.c-retainable.audit"> 1832<h1>Auditing of C retainable pointer interfaces</h1> 1833 1834<p><span class="revision"><span class="whenRevised">[beginning Apple 4.0, LLVM 3.1]</span></span></p> 1835 1836<p>A C function may be marked with the <tt>cf_audited_transfer</tt> 1837attribute to express that, except as otherwise marked with attributes, 1838it obeys the parameter (consuming vs. non-consuming) and return 1839(retained vs. non-retained) conventions for a C function of its name, 1840namely:</p> 1841 1842<ul> 1843<li>A parameter of C retainable pointer type is assumed to not be 1844consumed unless it is marked with the <tt>cf_consumed</tt> attribute, and</li> 1845<li>A result of C retainable pointer type is assumed to not be 1846returned retained unless the function is either 1847marked <tt>cf_returns_retained</tt> or it follows 1848the create/copy naming convention and is not 1849marked <tt>cf_returns_not_retained</tt>.</li> 1850</ul> 1851 1852<p>A function obeys the <span class="term">create/copy</span> naming 1853convention if its name contains as a substring:</p> 1854<ul> 1855<li>either <q>Create</q> or <q>Copy</q> not followed by a lowercase letter, or</li> 1856<li>either <q>create</q> or <q>copy</q> not followed by a lowercase 1857letter and not preceded by any letter, whether uppercase or lowercase.</li> 1858</ul> 1859 1860<p>A second attribute, <tt>cf_unknown_transfer</tt>, signifies that a 1861function's transfer semantics cannot be accurately captured using any 1862of these annotations. A program is ill-formed if it annotates the 1863same function with both <tt>cf_audited_transfer</tt> 1864and <tt>cf_unknown_transfer</tt>.</p> 1865 1866<p>A pragma is provided to faciliate the mass annotation of interfaces:</p> 1867 1868<pre>#pragma arc_cf_code_audited begin 1869... 1870#pragma arc_cf_code_audited end</pre> 1871 1872<p>All C functions declared within the extent of this pragma are 1873treated as if annotated with the <tt>cf_audited_transfer</tt> 1874attribute unless they otherwise have the <tt>cf_unknown_transfer</tt> 1875attribute. The pragma is accepted in all language modes. A program 1876is ill-formed if it attempts to change files, whether by including a 1877file or ending the current file, within the extent of this pragma.</p> 1878 1879<p>It is possible to test for all the features in this section with 1880<tt>__has_feature(arc_cf_code_audited)</tt>.</p> 1881 1882<div class="rationale"><p>Rationale: A significant inconvenience in 1883ARC programming is the necessity of interacting with APIs based around 1884C retainable pointers. These features are designed to make it 1885relatively easy for API authors to quickly review and annotate their 1886interfaces, in turn improving the fidelity of tools such as the static 1887analyzer and ARC. The single-file restriction on the pragma is 1888designed to eliminate the risk of accidentally annotating some other 1889header's interfaces.</p></div> 1890 1891</div> <!-- misc.c-retainable.audit --> 1892 1893</div> <!-- misc.c-retainable --> 1894 1895</div> <!-- misc --> 1896 1897<div id="runtime"> 1898<h1>Runtime support</h1> 1899 1900<p>This section describes the interaction between the ARC runtime and 1901the code generated by the ARC compiler. This is not part of the ARC 1902language specification; instead, it is effectively a language-specific 1903ABI supplement, akin to the <q>Itanium</q> generic ABI for C++.</p> 1904 1905<p>Ownership qualification does not alter the storage requirements for 1906objects, except that it is undefined behavior if a <tt>__weak</tt> 1907object is inadequately aligned for an object of type <tt>id</tt>. The 1908other qualifiers may be used on explicitly under-aligned memory.</p> 1909 1910<p>The runtime tracks <tt>__weak</tt> objects which holds non-null 1911values. It is undefined behavior to direct modify a <tt>__weak</tt> 1912object which is being tracked by the runtime except through an 1913<a href="#runtime.objc_storeWeak"><tt>objc_storeWeak</tt></a>, 1914<a href="#runtime.objc_destroyWeak"><tt>objc_destroyWeak</tt></a>, 1915or <a href="#runtime.objc_moveWeak"><tt>objc_moveWeak</tt></a> 1916call.</p> 1917 1918<p>The runtime must provide a number of new entrypoints which the 1919compiler may emit, which are described in the remainder of this 1920section.</p> 1921 1922<div class="rationale"><p>Rationale: Several of these functions are 1923semantically equivalent to a message send; we emit calls to C 1924functions instead because:</p> 1925<ul> 1926<li>the machine code to do so is significantly smaller,</li> 1927<li>it is much easier to recognize the C functions in the ARC optimizer, and</li> 1928<li>a sufficient sophisticated runtime may be able to avoid the 1929message send in common cases.</li> 1930</ul> 1931 1932<p>Several other of these functions are <q>fused</q> operations which 1933can be described entirely in terms of other operations. We use the 1934fused operations primarily as a code-size optimization, although in 1935some cases there is also a real potential for avoiding redundant 1936operations in the runtime.</p> 1937 1938</div> 1939 1940<div id="runtime.objc_autorelease"> 1941<h1><tt>id objc_autorelease(id value);</tt></h1> 1942<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 1943valid object.</p> 1944<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 1945adds the object to the innermost autorelease pool exactly as if the 1946object had been sent the <tt>autorelease</tt> message.</p> 1947<p>Always returns <tt>value</tt>.</p> 1948</div> <!-- runtime.objc_autorelease --> 1949 1950<div id="runtime.objc_autoreleasePoolPop"> 1951<h1><tt>void objc_autoreleasePoolPop(void *pool);</tt></h1> 1952<p><i>Precondition:</i> <tt>pool</tt> is the result of a previous call to 1953<a href="runtime.objc_autoreleasePoolPush"><tt>objc_autoreleasePoolPush</tt></a> 1954on the current thread, where neither <tt>pool</tt> nor any enclosing 1955pool have previously been popped.</p> 1956<p>Releases all the objects added to the given autorelease pool and 1957any autorelease pools it encloses, then sets the current autorelease 1958pool to the pool directly enclosing <tt>pool</tt>.</p> 1959</div> <!-- runtime.objc_autoreleasePoolPop --> 1960 1961<div id="runtime.objc_autoreleasePoolPush"> 1962<h1><tt>void *objc_autoreleasePoolPush(void);</tt></h1> 1963<p>Creates a new autorelease pool that is enclosed by the current 1964pool, makes that the current pool, and returns an opaque <q>handle</q> 1965to it.</p> 1966 1967<div class="rationale"><p>Rationale: while the interface is described 1968as an explicit hierarchy of pools, the rules allow the implementation 1969to just keep a stack of objects, using the stack depth as the opaque 1970pool handle.</p></div> 1971 1972</div> <!-- runtime.objc_autoreleasePoolPush --> 1973 1974<div id="runtime.objc_autoreleaseReturnValue"> 1975<h1><tt>id objc_autoreleaseReturnValue(id value);</tt></h1> 1976<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 1977valid object.</p> 1978<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 1979makes a best effort to hand off ownership of a retain count on the 1980object to a call 1981to <a href="runtime.objc_retainAutoreleasedReturnValue"><tt>objc_retainAutoreleasedReturnValue</tt></a> 1982for the same object in an enclosing call frame. If this is not 1983possible, the object is autoreleased as above.</p> 1984<p>Always returns <tt>value</tt>.</p> 1985</div> <!-- runtime.objc_autoreleaseReturnValue --> 1986 1987<div id="runtime.objc_copyWeak"> 1988<h1><tt>void objc_copyWeak(id *dest, id *src);</tt></h1> 1989<p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either 1990contains a null pointer or has been registered as a <tt>__weak</tt> 1991object. <tt>dest</tt> is a valid pointer which has not been 1992registered as a <tt>__weak</tt> object.</p> 1993<p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>, 1994potentially registering it with the runtime. Equivalent to the 1995following code:</p> 1996<pre>void objc_copyWeak(id *dest, id *src) { 1997 objc_release(objc_initWeak(dest, objc_loadWeakRetained(src))); 1998}</pre> 1999<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt> 2000on <tt>src</tt>.</p> 2001</div> <!-- runtime.objc_copyWeak --> 2002 2003<div id="runtime.objc_destroyWeak"> 2004<h1><tt>void objc_destroyWeak(id *object);</tt></h1> 2005<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which 2006either contains a null pointer or has been registered as 2007a <tt>__weak</tt> object.</p> 2008<p><tt>object</tt> is unregistered as a weak object, if it ever was. 2009The current value of <tt>object</tt> is left unspecified; otherwise, 2010equivalent to the following code:</p> 2011<pre>void objc_destroyWeak(id *object) { 2012 objc_storeWeak(object, nil); 2013}</pre> 2014<p>Does not need to be atomic with respect to calls 2015to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p> 2016</div> <!-- runtime.objc_destroyWeak --> 2017 2018<div id="runtime.objc_initWeak"> 2019<h1><tt>id objc_initWeak(id *object, id value);</tt></h1> 2020<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which has 2021not been registered as a <tt>__weak</tt> object. <tt>value</tt> is 2022null or a pointer to a valid object.</p> 2023<p>If <tt>value</tt> is a null pointer or the object to which it 2024points has begun deallocation, <tt>object</tt> is zero-initialized. 2025Otherwise, <tt>object</tt> is registered as a <tt>__weak</tt> object 2026pointing to <tt>value</tt>. Equivalent to the following code:</p> 2027<pre>id objc_initWeak(id *object, id value) { 2028 *object = nil; 2029 return objc_storeWeak(object, value); 2030}</pre> 2031<p>Returns the value of <tt>object</tt> after the call.</p> 2032<p>Does not need to be atomic with respect to calls 2033to <tt>objc_storeWeak</tt> on <tt>object</tt>.</p> 2034</div> <!-- runtime.objc_initWeak --> 2035 2036<div id="runtime.objc_loadWeak"> 2037<h1><tt>id objc_loadWeak(id *object);</tt></h1> 2038<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which 2039either contains a null pointer or has been registered as 2040a <tt>__weak</tt> object.</p> 2041<p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and 2042the last value stored into <tt>object</tt> has not yet been 2043deallocated or begun deallocation, retains and autoreleases that value 2044and returns it. Otherwise returns null. Equivalent to the following 2045code:</p> 2046<pre>id objc_loadWeak(id *object) { 2047 return objc_autorelease(objc_loadWeakRetained(object)); 2048}</pre> 2049<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt> 2050on <tt>object</tt>.</p> 2051<div class="rationale">Rationale: loading weak references would be 2052inherently prone to race conditions without the retain.</div> 2053</div> <!-- runtime.objc_loadWeak --> 2054 2055<div id="runtime.objc_loadWeakRetained"> 2056<h1><tt>id objc_loadWeakRetained(id *object);</tt></h1> 2057<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which 2058either contains a null pointer or has been registered as 2059a <tt>__weak</tt> object.</p> 2060<p>If <tt>object</tt> is registered as a <tt>__weak</tt> object, and 2061the last value stored into <tt>object</tt> has not yet been 2062deallocated or begun deallocation, retains that value and returns it. 2063Otherwise returns null.</p> 2064<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt> 2065on <tt>object</tt>.</p> 2066</div> <!-- runtime.objc_loadWeakRetained --> 2067 2068<div id="runtime.objc_moveWeak"> 2069<h1><tt>void objc_moveWeak(id *dest, id *src);</tt></h1> 2070<p><i>Precondition:</i> <tt>src</tt> is a valid pointer which either 2071contains a null pointer or has been registered as a <tt>__weak</tt> 2072object. <tt>dest</tt> is a valid pointer which has not been 2073registered as a <tt>__weak</tt> object.</p> 2074<p><tt>dest</tt> is initialized to be equivalent to <tt>src</tt>, 2075potentially registering it with the runtime. <tt>src</tt> may then be 2076left in its original state, in which case this call is equivalent 2077to <a href="#runtime.objc_copyWeak"><tt>objc_copyWeak</tt></a>, or it 2078may be left as null.</p> 2079<p>Must be atomic with respect to calls to <tt>objc_storeWeak</tt> 2080on <tt>src</tt>.</p> 2081</div> <!-- runtime.objc_moveWeak --> 2082 2083<div id="runtime.objc_release"> 2084<h1><tt>void objc_release(id value);</tt></h1> 2085<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2086valid object.</p> 2087<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2088performs a release operation exactly as if the object had been sent 2089the <tt>release</tt> message.</p> 2090</div> <!-- runtime.objc_release --> 2091 2092<div id="runtime.objc_retain"> 2093<h1><tt>id objc_retain(id value);</tt></h1> 2094<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2095valid object.</p> 2096<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2097performs a retain operation exactly as if the object had been sent 2098the <tt>retain</tt> message.</p> 2099<p>Always returns <tt>value</tt>.</p> 2100</div> <!-- runtime.objc_retain --> 2101 2102<div id="runtime.objc_retainAutorelease"> 2103<h1><tt>id objc_retainAutorelease(id value);</tt></h1> 2104<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2105valid object.</p> 2106<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2107performs a retain operation followed by an autorelease operation. 2108Equivalent to the following code:</p> 2109<pre>id objc_retainAutorelease(id value) { 2110 return objc_autorelease(objc_retain(value)); 2111}</pre> 2112<p>Always returns <tt>value</tt>.</p> 2113</div> <!-- runtime.objc_retainAutorelease --> 2114 2115<div id="runtime.objc_retainAutoreleaseReturnValue"> 2116<h1><tt>id objc_retainAutoreleaseReturnValue(id value);</tt></h1> 2117<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2118valid object.</p> 2119<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2120performs a retain operation followed by the operation described in 2121<a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a>. 2122Equivalent to the following code:</p> 2123<pre>id objc_retainAutoreleaseReturnValue(id value) { 2124 return objc_autoreleaseReturnValue(objc_retain(value)); 2125}</pre> 2126<p>Always returns <tt>value</tt>.</p> 2127</div> <!-- runtime.objc_retainAutoreleaseReturnValue --> 2128 2129<div id="runtime.objc_retainAutoreleasedReturnValue"> 2130<h1><tt>id objc_retainAutoreleasedReturnValue(id value);</tt></h1> 2131<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2132valid object.</p> 2133<p>If <tt>value</tt> is null, this call has no effect. Otherwise, it 2134attempts to accept a hand off of a retain count from a call to 2135<a href="#runtime.objc_autoreleaseReturnValue"><tt>objc_autoreleaseReturnValue</tt></a> 2136on <tt>value</tt> in a recently-called function or something it 2137calls. If that fails, it performs a retain operation exactly 2138like <a href="#runtime.objc_retain"><tt>objc_retain</tt></a>.</p> 2139<p>Always returns <tt>value</tt>.</p> 2140</div> <!-- runtime.objc_retainAutoreleasedReturnValue --> 2141 2142<div id="runtime.objc_retainBlock"> 2143<h1><tt>id objc_retainBlock(id value);</tt></h1> 2144<p><i>Precondition:</i> <tt>value</tt> is null or a pointer to a 2145valid block object.</p> 2146<p>If <tt>value</tt> is null, this call has no effect. Otherwise, if 2147the block pointed to by <tt>value</tt> is still on the stack, it is 2148copied to the heap and the address of the copy is returned. Otherwise 2149a retain operation is performed on the block exactly as if it had been 2150sent the <tt>retain</tt> message.</p> 2151</div> <!-- runtime.objc_retainBlock --> 2152 2153<div id="runtime.objc_storeStrong"> 2154<h1><tt>id objc_storeStrong(id *object, id value);</tt></h1> 2155<p><i>Precondition:</i> <tt>object</tt> is a valid pointer to 2156a <tt>__strong</tt> object which is adequately aligned for a 2157pointer. <tt>value</tt> is null or a pointer to a valid object.</p> 2158<p>Performs the complete sequence for assigning to a <tt>__strong</tt> 2159object of non-block type. Equivalent to the following code:</p> 2160<pre>id objc_storeStrong(id *object, id value) { 2161 value = [value retain]; 2162 id oldValue = *object; 2163 *object = value; 2164 [oldValue release]; 2165 return value; 2166}</pre> 2167<p>Always returns <tt>value</tt>.</p> 2168</div> <!-- runtime.objc_storeStrong --> 2169 2170<div id="runtime.objc_storeWeak"> 2171<h1><tt>id objc_storeWeak(id *object, id value);</tt></h1> 2172<p><i>Precondition:</i> <tt>object</tt> is a valid pointer which 2173either contains a null pointer or has been registered as 2174a <tt>__weak</tt> object. <tt>value</tt> is null or a pointer to a 2175valid object.</p> 2176<p>If <tt>value</tt> is a null pointer or the object to which it 2177points has begun deallocation, <tt>object</tt> is assigned null 2178and unregistered as a <tt>__weak</tt> object. Otherwise, 2179<tt>object</tt> is registered as a <tt>__weak</tt> object or has its 2180registration updated to point to <tt>value</tt>.</p> 2181<p>Returns the value of <tt>object</tt> after the call.</p> 2182</div> <!-- runtime.objc_storeWeak --> 2183 2184</div> <!-- runtime --> 2185</div> <!-- root --> 2186</body> 2187</html> 2188