Bug 1153267 - part 1 - use smart-pointer .forget() instead of NS_ADDREF+assign; r=ehsan
authorNathan Froyd <froydnj@mozilla.com>
Tue, 31 Mar 2015 10:03:49 -0400
changeset 238912 3fb0310f5f497d32ee6cea5b731cce32671f14ad
parent 238911 c3dd616bbb51d56eb411cee767ac0abfe71bcd74
child 238913 d7d35bcd761da47800201e9539e960ec8910d4c9
push id28577
push userryanvm@gmail.com
push dateTue, 14 Apr 2015 14:06:33 +0000
treeherdermozilla-central@388f5861dc7d [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersehsan
bugs1153267
milestone40.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1153267 - part 1 - use smart-pointer .forget() instead of NS_ADDREF+assign; r=ehsan
dom/base/nsContentPermissionHelper.cpp
dom/base/nsDOMSerializer.cpp
dom/base/nsFocusManager.cpp
dom/base/nsGlobalWindow.cpp
dom/base/nsGlobalWindowCommands.cpp
dom/base/nsRange.cpp
dom/datastore/DataStoreService.cpp
dom/devicestorage/nsDeviceStorage.cpp
dom/events/DataTransfer.cpp
dom/html/HTMLFormElement.cpp
dom/quota/QuotaManager.cpp
dom/system/gonk/nsVolumeService.cpp
dom/xul/XULDocument.cpp
dom/xul/nsXULControllers.cpp
dom/xul/nsXULPrototypeCache.cpp
dom/xul/templates/nsXULContentBuilder.cpp
dom/xul/templates/nsXULTemplateQueryProcessorRDF.cpp
dom/xul/templates/nsXULTemplateQueryProcessorStorage.cpp
dom/xul/templates/nsXULTemplateQueryProcessorXML.cpp
dom/xul/templates/nsXULTemplateResultSetRDF.cpp
layout/generic/nsFrame.cpp
layout/inspector/inDOMUtils.cpp
layout/xul/tree/nsTreeBodyFrame.cpp
netwerk/base/nsNetUtil.h
netwerk/base/nsURLHelperOSX.cpp
netwerk/base/nsURLHelperUnix.cpp
netwerk/base/nsURLHelperWin.cpp
netwerk/protocol/data/nsDataChannel.cpp
netwerk/protocol/http/nsHttpConnectionMgr.cpp
netwerk/protocol/http/nsHttpDigestAuth.cpp
netwerk/protocol/websocket/BaseWebSocketChannel.cpp
netwerk/protocol/wyciwyg/nsWyciwygProtocolHandler.cpp
netwerk/streamconv/nsStreamConverterService.cpp
toolkit/components/commandlines/nsCommandLine.cpp
toolkit/components/downloads/nsDownloadManager.cpp
toolkit/components/filepicker/nsFileView.cpp
toolkit/components/places/SQLFunctions.cpp
toolkit/components/places/nsAnnotationService.cpp
toolkit/components/places/nsNavHistoryQuery.cpp
toolkit/components/typeaheadfind/nsTypeAheadFind.cpp
toolkit/components/url-classifier/nsCheckSummedOutputStream.h
toolkit/profile/nsToolkitProfileService.cpp
toolkit/system/gnome/nsGConfService.cpp
toolkit/system/gnome/nsGIOService.cpp
toolkit/system/gnome/nsGSettingsService.cpp
toolkit/xre/nsUpdateDriver.cpp
toolkit/xre/nsXREDirProvider.cpp
--- a/dom/base/nsContentPermissionHelper.cpp
+++ b/dom/base/nsContentPermissionHelper.cpp
@@ -145,17 +145,17 @@ ContentPermissionType::GetOptions(nsIArr
 
     rv = isupportsString->SetData(mOptions[i]);
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = options->AppendElement(isupportsString, false);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  NS_ADDREF(*aOptions = options);
+  options.forget(aOptions);
   return NS_OK;
 }
 
 // nsContentPermissionUtils
 
 /* static */ uint32_t
 nsContentPermissionUtils::ConvertPermissionRequestToArray(nsTArray<PermissionRequest>& aSrcArray,
                                                           nsIMutableArray* aDesArray)
--- a/dom/base/nsDOMSerializer.cpp
+++ b/dom/base/nsDOMSerializer.cpp
@@ -78,18 +78,17 @@ SetUpEncoder(nsIDOMNode *aRoot, const ns
 
   // If we are working on the entire document we do not need to
   // specify which part to serialize
   if (!entireDocument) {
     rv = encoder->SetNode(aRoot);
   }
 
   if (NS_SUCCEEDED(rv)) {
-    *aEncoder = encoder.get();
-    NS_ADDREF(*aEncoder);
+    encoder.forget(aEncoder);
   }
 
   return rv;
 }
 
 void
 nsDOMSerializer::SerializeToString(nsINode& aRoot, nsAString& aStr,
                                    ErrorResult& rv)
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -2632,18 +2632,19 @@ nsFocusManager::DetermineElementToMoveFo
       NS_ENSURE_SUCCESS(rv, rv);
 
       // found a content node to focus.
       if (nextFocus) {
         LOGCONTENTNAVIGATION("Next Content: %s", nextFocus.get());
 
         // as long as the found node was not the same as the starting node,
         // set it as the return value.
-        if (nextFocus != originalStartContent)
-          NS_ADDREF(*aNextContent = nextFocus);
+        if (nextFocus != originalStartContent) {
+          nextFocus.forget(aNextContent);
+        }
         return NS_OK;
       }
 
       if (popupFrame) {
         // in a popup, so start again from the beginning of the popup. However,
         // if we already started at the beginning, then there isn't anything to
         // focus, so just return
         if (startContent != rootContent) {
@@ -3115,18 +3116,17 @@ nsFocusManager::GetLastDocShell(nsIDocSh
 {
   *aResult = nullptr;
 
   nsCOMPtr<nsIDocShellTreeItem> curItem = aItem;
   while (curItem) {
     int32_t childCount = 0;
     curItem->GetChildCount(&childCount);
     if (!childCount) {
-      *aResult = curItem;
-      NS_ADDREF(*aResult);
+      curItem.forget(aResult);
       return;
     }
 
     
     curItem->GetChildAt(childCount - 1, getter_AddRefs(curItem));
   }
 }
 
@@ -3194,17 +3194,17 @@ nsFocusManager::GetPreviousDocShell(nsID
     if (iterItem == aItem)
       break;
     prevItem = iterItem;
   }
 
   if (prevItem)
     GetLastDocShell(prevItem, aResult);
   else
-    NS_ADDREF(*aResult = parentItem);
+    parentItem.forget(aResult);
 }
 
 nsIContent*
 nsFocusManager::GetNextTabbablePanel(nsIDocument* aDocument, nsIFrame* aCurrentPopup, bool aForward)
 {
   nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
   if (!pm)
     return nullptr;
@@ -3412,17 +3412,17 @@ nsFocusManager::GetFocusInSelection(nsPI
   // with a variable holding the starting selectionContent
   while (testContent) {
     // Keep testing while selectionContent is equal to something,
     // eventually we'll run out of ancestors
 
     nsCOMPtr<nsIURI> uri;
     if (testContent == currentFocus ||
         testContent->IsLink(getter_AddRefs(uri))) {
-      NS_ADDREF(*aFocusedContent = testContent);
+      testContent.forget(aFocusedContent);
       return;
     }
 
     // Get the parent
     testContent = testContent->GetParent();
 
     if (!testContent) {
       // We run this loop again, checking the ancestor chain of the selection's end point
@@ -3442,17 +3442,17 @@ nsFocusManager::GetFocusInSelection(nsPI
   do {
     testContent = do_QueryInterface(selectionNode);
 
     // We're looking for any focusable link that could be part of the
     // main document's selection.
     nsCOMPtr<nsIURI> uri;
     if (testContent == currentFocus ||
         testContent->IsLink(getter_AddRefs(uri))) {
-      NS_ADDREF(*aFocusedContent = testContent);
+      testContent.forget(aFocusedContent);
       return;
     }
 
     selectionNode->GetFirstChild(getter_AddRefs(testNode));
     if (testNode) {
       selectionNode = testNode;
       continue;
     }
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -4043,17 +4043,17 @@ nsGlobalWindow::GetPrompter(nsIPrompt** 
   }
 
   if (!mDocShell)
     return NS_ERROR_FAILURE;
 
   nsCOMPtr<nsIPrompt> prompter(do_GetInterface(mDocShell));
   NS_ENSURE_TRUE(prompter, NS_ERROR_NO_INTERFACE);
 
-  NS_ADDREF(*aPrompt = prompter);
+  prompter.forget(aPrompt);
   return NS_OK;
 }
 
 BarProp*
 nsGlobalWindow::GetMenubar(ErrorResult& aError)
 {
   FORWARD_TO_INNER_OR_THROW(GetMenubar, (aError), aError, nullptr);
 
--- a/dom/base/nsGlobalWindowCommands.cpp
+++ b/dom/base/nsGlobalWindowCommands.cpp
@@ -626,18 +626,17 @@ nsSelectionCommand::GetContentViewerEdit
   nsIDocShell *docShell = window->GetDocShell();
   NS_ENSURE_TRUE(docShell, NS_ERROR_FAILURE);
 
   nsCOMPtr<nsIContentViewer> viewer;
   docShell->GetContentViewer(getter_AddRefs(viewer));
   nsCOMPtr<nsIContentViewerEdit> edit(do_QueryInterface(viewer));
   NS_ENSURE_TRUE(edit, NS_ERROR_FAILURE);
 
-  *aEditInterface = edit;
-  NS_ADDREF(*aEditInterface);
+  edit.forget(aEditInterface);
   return NS_OK;
 }
 
 #if 0
 #pragma mark -
 #endif
 
 #define NS_DECL_CLIPBOARD_COMMAND(_cmd)                                                     \
--- a/dom/base/nsRange.cpp
+++ b/dom/base/nsRange.cpp
@@ -1803,17 +1803,17 @@ nsRange::CutContents(DocumentFragment** 
   nsresult rv = iter.Init(this);
   if (NS_FAILED(rv)) return rv;
 
   if (iter.IsDone())
   {
     // There's nothing for us to delete.
     rv = CollapseRangeAfterDelete(this);
     if (NS_SUCCEEDED(rv) && aFragment) {
-      NS_ADDREF(*aFragment = retval);
+      retval.forget(aFragment);
     }
     return rv;
   }
 
   // We delete backwards to avoid iterator problems!
 
   iter.Last();
 
@@ -2010,17 +2010,17 @@ nsRange::CutContents(DocumentFragment** 
         NS_ENSURE_STATE(newCloneAncestor);
       }
       commonCloneAncestor = newCloneAncestor;
     }
   }
 
   rv = CollapseRangeAfterDelete(this);
   if (NS_SUCCEEDED(rv) && aFragment) {
-    NS_ADDREF(*aFragment = retval);
+    retval.forget(aFragment);
   }
   return rv;
 }
 
 NS_IMETHODIMP
 nsRange::DeleteContents()
 {
   return CutContents(nullptr);
--- a/dom/datastore/DataStoreService.cpp
+++ b/dom/datastore/DataStoreService.cpp
@@ -1099,18 +1099,17 @@ DataStoreService::GetAppManifestURLsForD
   HashApp* apps = nullptr;
   if (mStores.Get(aName, &apps)) {
     apps->EnumerateRead(GetAppManifestURLsEnumerator, manifestURLs.get());
   }
   if (mAccessStores.Get(aName, &apps)) {
     apps->EnumerateRead(GetAppManifestURLsEnumerator, manifestURLs.get());
   }
 
-  *aManifestURLs = manifestURLs;
-  NS_ADDREF(*aManifestURLs);
+  manifestURLs.forget(aManifestURLs);
   return NS_OK;
 }
 
 bool
 DataStoreService::CheckPermission(nsIPrincipal* aPrincipal)
 {
   // First of all, the general pref has to be turned on.
   bool enabled = false;
--- a/dom/devicestorage/nsDeviceStorage.cpp
+++ b/dom/devicestorage/nsDeviceStorage.cpp
@@ -3510,17 +3510,17 @@ nsDOMDeviceStorage::CreateDeviceStorageF
     GetDefaultStorageName(aType, storageName);
   }
 
   nsRefPtr<nsDOMDeviceStorage> ds = new nsDOMDeviceStorage(aWin);
   if (NS_FAILED(ds->Init(aWin, aType, storageName))) {
     *aStore = nullptr;
     return;
   }
-  NS_ADDREF(*aStore = ds.get());
+  ds.forget(aStore);
 }
 
 // static
 void
 nsDOMDeviceStorage::CreateDeviceStoragesFor(
   nsPIDOMWindow* aWin,
   const nsAString &aType,
   nsTArray<nsRefPtr<nsDOMDeviceStorage> > &aStores)
--- a/dom/events/DataTransfer.cpp
+++ b/dom/events/DataTransfer.cpp
@@ -977,28 +977,28 @@ DataTransfer::ConvertFromVariant(nsIVari
     nsCOMPtr<nsISupports> data;
     if (NS_FAILED(aVariant->GetAsISupports(getter_AddRefs(data))))
        return false;
  
     nsCOMPtr<nsIFlavorDataProvider> fdp = do_QueryInterface(data);
     if (fdp) {
       // for flavour data providers, use kFlavorHasDataProvider (which has the
       // value 0) as the length.
-      NS_ADDREF(*aSupports = fdp);
+      fdp.forget(aSupports);
       *aLength = nsITransferable::kFlavorHasDataProvider;
     }
     else {
       // wrap the item in an nsISupportsInterfacePointer
       nsCOMPtr<nsISupportsInterfacePointer> ptrSupports =
         do_CreateInstance(NS_SUPPORTS_INTERFACE_POINTER_CONTRACTID);
       if (!ptrSupports)
         return false;
 
       ptrSupports->SetData(data);
-      NS_ADDREF(*aSupports = ptrSupports);
+      ptrSupports.forget(aSupports);
 
       *aLength = sizeof(nsISupportsInterfacePointer *);
     }
 
     return true;
   }
 
   char16_t* chrs;
@@ -1012,18 +1012,17 @@ DataTransfer::ConvertFromVariant(nsIVari
 
   nsCOMPtr<nsISupportsString>
     strSupports(do_CreateInstance(NS_SUPPORTS_STRING_CONTRACTID));
   if (!strSupports)
     return false;
 
   strSupports->SetData(str);
 
-  *aSupports = strSupports;
-  NS_ADDREF(*aSupports);
+  strSupports.forget(aSupports);
 
   // each character is two bytes
   *aLength = str.Length() << 1;
 
   return true;
 }
 
 void
--- a/dom/html/HTMLFormElement.cpp
+++ b/dom/html/HTMLFormElement.cpp
@@ -1738,18 +1738,17 @@ HTMLFormElement::GetActionURL(nsIURI** a
     if (!permitsFormAction) {
       rv = NS_ERROR_CSP_FORM_ACTION_VIOLATION;
     }
   }
 
   //
   // Assign to the output
   //
-  *aActionURL = actionURL;
-  NS_ADDREF(*aActionURL);
+  actionURL.forget(aActionURL);
 
   return rv;
 }
 
 NS_IMETHODIMP_(nsIFormControl*)
 HTMLFormElement::GetDefaultSubmitElement() const
 {
   NS_PRECONDITION(mDefaultSubmitElement == mFirstSubmitInElements ||
--- a/dom/quota/QuotaManager.cpp
+++ b/dom/quota/QuotaManager.cpp
@@ -2242,17 +2242,17 @@ QuotaManager::EnsureOriginIsInitialized(
   // Get directory for this origin and persistence type.
   nsCOMPtr<nsIFile> directory;
   rv = GetDirectoryForOrigin(aPersistenceType, aOrigin,
                              getter_AddRefs(directory));
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (IsTreatedAsPersistent(aPersistenceType, aIsApp)) {
     if (mInitializedOrigins.Contains(OriginKey(aPersistenceType, aOrigin))) {
-      NS_ADDREF(*aDirectory = directory);
+      directory.forget(aDirectory);
       return NS_OK;
     }
   } else if (!mTemporaryStorageInitialized) {
     rv = InitializeRepository(aPersistenceType);
     if (NS_WARN_IF(NS_FAILED(rv))) {
       // We have to cleanup partially initialized quota.
       RemoveQuota();
 
--- a/dom/system/gonk/nsVolumeService.cpp
+++ b/dom/system/gonk/nsVolumeService.cpp
@@ -234,17 +234,17 @@ nsVolumeService::GetVolumeNames(nsIArray
 
     rv = isupportsString->SetData(vol->Name());
     NS_ENSURE_SUCCESS(rv, rv);
 
     rv = volNames->AppendElement(isupportsString, false);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
-  NS_ADDREF(*aVolNames = volNames);
+  volNames.forget(aVolNames);
   return NS_OK;
 }
 
 void
 nsVolumeService::GetVolumesForIPC(nsTArray<VolumeInfo>* aResult)
 {
   MOZ_ASSERT(XRE_GetProcessType() == GeckoProcessType_Default);
   MOZ_ASSERT(NS_IsMainThread());
--- a/dom/xul/XULDocument.cpp
+++ b/dom/xul/XULDocument.cpp
@@ -2036,18 +2036,17 @@ XULDocument::PrepareToLoadPrototype(nsIU
 
     parser->SetCommand(nsCRT::strcmp(aCommand, "view-source") ? eViewNormal :
                        eViewSource);
 
     parser->SetDocumentCharset(NS_LITERAL_CSTRING("UTF-8"),
                                kCharsetFromDocTypeDefault);
     parser->SetContentSink(sink); // grabs a reference to the parser
 
-    *aResult = parser;
-    NS_ADDREF(*aResult);
+    parser.forget(aResult);
     return NS_OK;
 }
 
 
 nsresult
 XULDocument::ApplyPersistentAttributes()
 {
     // For non-chrome documents, persistance is simply broken
@@ -3656,17 +3655,17 @@ XULDocument::CreateOverlayElement(nsXULP
         new OverlayForwardReference(this, element);
     if (! fwdref)
         return NS_ERROR_OUT_OF_MEMORY;
 
     // transferring ownership to ya...
     rv = AddForwardReference(fwdref);
     if (NS_FAILED(rv)) return rv;
 
-    NS_ADDREF(*aResult = element);
+    element.forget(aResult);
     return NS_OK;
 }
 
 nsresult
 XULDocument::AddAttributes(nsXULPrototypeElement* aPrototype,
                            nsIContent* aElement)
 {
     nsresult rv;
--- a/dom/xul/nsXULControllers.cpp
+++ b/dom/xul/nsXULControllers.cpp
@@ -102,18 +102,17 @@ nsXULControllers::GetControllerForComman
     {
       nsCOMPtr<nsIController> controller;
       controllerData->GetController(getter_AddRefs(controller));
       if (controller)
       {
         bool supportsCommand;
         controller->SupportsCommand(aCommand, &supportsCommand);
         if (supportsCommand) {
-          *_retval = controller;
-          NS_ADDREF(*_retval);
+          controller.forget(_retval);
           return NS_OK;
         }
       }
     }
   }
   
   return NS_OK;
 }
--- a/dom/xul/nsXULPrototypeCache.cpp
+++ b/dom/xul/nsXULPrototypeCache.cpp
@@ -367,17 +367,17 @@ nsXULPrototypeCache::GetInputStream(nsIU
         return NS_ERROR_NOT_AVAILABLE;
 
     rv = NewObjectInputStreamFromBuffer(buf, len, getter_AddRefs(ois));
     NS_ENSURE_SUCCESS(rv, rv);
     buf.forget();
 
     mInputStreamTable.Put(uri, ois);
     
-    NS_ADDREF(*stream = ois);
+    ois.forget(stream);
     return NS_OK;
 }
 
 nsresult
 nsXULPrototypeCache::FinishInputStream(nsIURI* uri) {
     mInputStreamTable.Remove(uri);
     return NS_OK;
 }
@@ -397,17 +397,17 @@ nsXULPrototypeCache::GetOutputStream(nsI
         objectOutput->SetOutputStream(outputStream);
     } else {
         rv = NewObjectOutputWrappedStorageStream(getter_AddRefs(objectOutput), 
                                                  getter_AddRefs(storageStream),
                                                  false);
         NS_ENSURE_SUCCESS(rv, rv);
         mOutputStreamTable.Put(uri, storageStream);
     }
-    NS_ADDREF(*stream = objectOutput);
+    objectOutput.forget(stream);
     return NS_OK;
 }
 
 nsresult
 nsXULPrototypeCache::FinishOutputStream(nsIURI* uri) 
 {
     nsresult rv;
     StartupCache* sc = StartupCache::GetSingleton();
--- a/dom/xul/templates/nsXULContentBuilder.cpp
+++ b/dom/xul/templates/nsXULContentBuilder.cpp
@@ -1245,18 +1245,17 @@ nsXULContentBuilder::EnsureElementHasGen
         if (NS_FAILED(rv))
             return rv;
 
         // XXX Note that the notification ensures we won't batch insertions! This could be bad! - Dave
         rv = parent->AppendChildTo(element, aNotify);
         if (NS_FAILED(rv))
             return rv;
 
-        *result = element;
-        NS_ADDREF(*result);
+        element.forget(result);
         return NS_ELEMENT_GOT_CREATED;
     }
     else {
         return NS_ELEMENT_WAS_THERE;
     }
 }
 
 bool
--- a/dom/xul/templates/nsXULTemplateQueryProcessorRDF.cpp
+++ b/dom/xul/templates/nsXULTemplateQueryProcessorRDF.cpp
@@ -420,18 +420,17 @@ nsXULTemplateQueryProcessorRDF::CompileQ
     }
 
     rv = lastnode->AddChild(instnode);
     if (NS_FAILED(rv))
         return rv;
 
     mQueries.AppendElement(query);
 
-    *_retval = query;
-    NS_ADDREF(*_retval);
+    query.forget(_retval);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULTemplateQueryProcessorRDF::GenerateResults(nsISupports* aDatasource,
                                                 nsIXULTemplateResult* aRef,
                                                 nsISupports* aQuery,
--- a/dom/xul/templates/nsXULTemplateQueryProcessorStorage.cpp
+++ b/dom/xul/templates/nsXULTemplateQueryProcessorStorage.cpp
@@ -235,17 +235,17 @@ nsXULTemplateQueryProcessorStorage::GetD
     // ok now we have an URI of a sqlite file
     nsCOMPtr<mozIStorageConnection> connection;
     rv = storage->OpenDatabase(databaseFile, getter_AddRefs(connection));
     if (NS_FAILED(rv)) {
         nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_STORAGE_CANNOT_OPEN_DATABASE);
         return rv;
     }
 
-    NS_ADDREF(*aReturn = connection);
+    connection.forget(aReturn);
     return NS_OK;
 }
 
 
 
 NS_IMETHODIMP
 nsXULTemplateQueryProcessorStorage::InitializeForBuilding(nsISupports* aDatasource,
                                                           nsIXULTemplateBuilder* aBuilder,
--- a/dom/xul/templates/nsXULTemplateQueryProcessorXML.cpp
+++ b/dom/xul/templates/nsXULTemplateQueryProcessorXML.cpp
@@ -280,18 +280,17 @@ nsXULTemplateQueryProcessorXML::CompileQ
 
                 nsCOMPtr<nsIAtom> varatom = do_GetAtom(var);
 
                 query->AddBinding(varatom, Move(compiledexpr));
             }
         }
     }
 
-    *_retval = query;
-    NS_ADDREF(*_retval);
+    query.forget(_retval);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULTemplateQueryProcessorXML::GenerateResults(nsISupports* aDatasource,
                                                 nsIXULTemplateResult* aRef,
                                                 nsISupports* aQuery,
--- a/dom/xul/templates/nsXULTemplateResultSetRDF.cpp
+++ b/dom/xul/templates/nsXULTemplateResultSetRDF.cpp
@@ -71,13 +71,12 @@ nsXULTemplateResultSetRDF::GetNext(nsISu
         return NS_ERROR_OUT_OF_MEMORY;
 
     // add the supporting memory elements to the processor's map. These are
     // used to remove the results when an assertion is removed from the graph
     mProcessor->AddMemoryElements(mCurrent->mInstantiation, nextresult);
 
     mCheckedNext = false;
 
-    *aResult = nextresult;
-    NS_ADDREF(*aResult);
+    nextresult.forget(aResult);
 
     return NS_OK;
 }
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -2667,18 +2667,17 @@ nsFrame::GetDataForTableSelection(const 
   nsCOMPtr<nsIContent> parentContent = tableOrCellContent->GetParent();
   if (!parentContent) return NS_ERROR_FAILURE;
 
   int32_t offset = parentContent->IndexOf(tableOrCellContent);
   // Not likely?
   if (offset < 0) return NS_ERROR_FAILURE;
 
   // Everything is OK -- set the return values
-  *aParentContent = parentContent;
-  NS_ADDREF(*aParentContent);
+  parentContent.forget(aParentContent);
 
   *aContentOffset = offset;
 
 #if 0
   if (selectRow)
     *aTarget = nsISelectionPrivate::TABLESELECTION_ROW;
   else if (selectColumn)
     *aTarget = nsISelectionPrivate::TABLESELECTION_COLUMN;
--- a/layout/inspector/inDOMUtils.cpp
+++ b/layout/inspector/inDOMUtils.cpp
@@ -229,18 +229,17 @@ inDOMUtils::GetCSSStyleRules(nsIDOMEleme
     cssRule = do_QueryObject(ruleNode->GetRule());
     if (cssRule) {
       nsCOMPtr<nsIDOMCSSRule> domRule = cssRule->GetDOMRule();
       if (domRule)
         rules->InsertElementAt(domRule, 0);
     }
   }
 
-  *_retval = rules;
-  NS_ADDREF(*_retval);
+  rules.forget(_retval);
 
   return NS_OK;
 }
 
 static already_AddRefed<StyleRule>
 GetRuleFromDOMRule(nsIDOMCSSStyleRule *aRule, ErrorResult& rv)
 {
   nsCOMPtr<nsICSSStyleRuleDOMWrapper> rule = do_QueryInterface(aRule);
@@ -897,17 +896,17 @@ inDOMUtils::GetBindingURLs(nsIDOMElement
 
   nsXBLBinding *binding = content->GetXBLBinding();
 
   while (binding) {
     urls->AppendElement(binding->PrototypeBinding()->BindingURI(), false);
     binding = binding->GetBaseBinding();
   }
 
-  NS_ADDREF(*_retval = urls);
+  urls.forget(_retval);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 inDOMUtils::SetContentState(nsIDOMElement* aElement,
                             EventStates::InternalType aState)
 {
   NS_ENSURE_ARG_POINTER(aElement);
--- a/layout/xul/tree/nsTreeBodyFrame.cpp
+++ b/layout/xul/tree/nsTreeBodyFrame.cpp
@@ -616,17 +616,17 @@ nsTreeBodyFrame::GetSelectionRegion(nsIS
     if (isSelected)
       region->UnionRect(x, y, rect.width, rowHeight);
     y += rowHeight;
   }
 
   // clip to the tree boundary in case one row extends past it
   region->IntersectRect(x, top, rect.width, rect.height);
 
-  NS_ADDREF(*aRegion = region);
+  region.forget(aRegion);
   return NS_OK;
 }
 
 nsresult
 nsTreeBodyFrame::Invalidate()
 {
   if (mUpdateBatchNest)
     return NS_OK;
--- a/netwerk/base/nsNetUtil.h
+++ b/netwerk/base/nsNetUtil.h
@@ -845,18 +845,19 @@ NS_NewDownloader(nsIStreamListener   **r
                  nsIDownloadObserver  *observer,
                  nsIFile              *downloadLocation = nullptr)
 {
     nsresult rv;
     nsCOMPtr<nsIDownloader> downloader =
         do_CreateInstance(NS_DOWNLOADER_CONTRACTID, &rv);
     if (NS_SUCCEEDED(rv)) {
         rv = downloader->Init(observer, downloadLocation);
-        if (NS_SUCCEEDED(rv))
-            NS_ADDREF(*result = downloader);
+        if (NS_SUCCEEDED(rv)) {
+            downloader.forget(result);
+        }
     }
     return rv;
 }
 
 inline nsresult
 NS_NewStreamLoader(nsIStreamLoader        **result,
                    nsIStreamLoaderObserver *observer)
 {
@@ -986,18 +987,19 @@ inline nsresult
 NS_NewSyncStreamListener(nsIStreamListener **result,
                          nsIInputStream    **stream)
 {
     nsresult rv;
     nsCOMPtr<nsISyncStreamListener> listener =
         do_CreateInstance(NS_SYNCSTREAMLISTENER_CONTRACTID, &rv);
     if (NS_SUCCEEDED(rv)) {
         rv = listener->GetInputStream(stream);
-        if (NS_SUCCEEDED(rv))
-            NS_ADDREF(*result = listener);  // cannot use nsCOMPtr::swap
+        if (NS_SUCCEEDED(rv)) {
+            listener.forget(result);
+        }
     }
     return rv;
 }
 
 /**
  * Implement the nsIChannel::Open(nsIInputStream**) method using the channel's
  * AsyncOpen method.
  *
@@ -1032,34 +1034,36 @@ NS_NewRequestObserverProxy(nsIRequestObs
                            nsIRequestObserver  *observer,
                            nsISupports         *context)
 {
     nsresult rv;
     nsCOMPtr<nsIRequestObserverProxy> proxy =
         do_CreateInstance(NS_REQUESTOBSERVERPROXY_CONTRACTID, &rv);
     if (NS_SUCCEEDED(rv)) {
         rv = proxy->Init(observer, context);
-        if (NS_SUCCEEDED(rv))
-            NS_ADDREF(*result = proxy);  // cannot use nsCOMPtr::swap
+        if (NS_SUCCEEDED(rv)) {
+            proxy.forget(result);
+        }
     }
     return rv;
 }
 
 inline nsresult
 NS_NewSimpleStreamListener(nsIStreamListener **result,
                            nsIOutputStream    *sink,
                            nsIRequestObserver *observer = nullptr)
 {
     nsresult rv;
     nsCOMPtr<nsISimpleStreamListener> listener = 
         do_CreateInstance(NS_SIMPLESTREAMLISTENER_CONTRACTID, &rv);
     if (NS_SUCCEEDED(rv)) {
         rv = listener->Init(sink, observer);
-        if (NS_SUCCEEDED(rv))
-            NS_ADDREF(*result = listener);  // cannot use nsCOMPtr::swap
+        if (NS_SUCCEEDED(rv)) {
+            listener.forget(result);
+        }
     }
     return rv;
 }
 
 inline nsresult
 NS_CheckPortSafety(int32_t       port,
                    const char   *scheme,
                    nsIIOService *ioService = nullptr)
@@ -1429,36 +1433,38 @@ NS_NewBufferedInputStream(nsIInputStream
                           nsIInputStream  *str,
                           uint32_t         bufferSize)
 {
     nsresult rv;
     nsCOMPtr<nsIBufferedInputStream> in =
         do_CreateInstance(NS_BUFFEREDINPUTSTREAM_CONTRACTID, &rv);
     if (NS_SUCCEEDED(rv)) {
         rv = in->Init(str, bufferSize);
-        if (NS_SUCCEEDED(rv))
-            NS_ADDREF(*result = in);  // cannot use nsCOMPtr::swap
+        if (NS_SUCCEEDED(rv)) {
+            in.forget(result);
+        }
     }
     return rv;
 }
 
 // note: the resulting stream can be QI'ed to nsISafeOutputStream iff the
 // provided stream supports it.
 inline nsresult
 NS_NewBufferedOutputStream(nsIOutputStream **result,
                            nsIOutputStream  *str,
                            uint32_t          bufferSize)
 {
     nsresult rv;
     nsCOMPtr<nsIBufferedOutputStream> out =
         do_CreateInstance(NS_BUFFEREDOUTPUTSTREAM_CONTRACTID, &rv);
     if (NS_SUCCEEDED(rv)) {
         rv = out->Init(str, bufferSize);
-        if (NS_SUCCEEDED(rv))
-            NS_ADDREF(*result = out);  // cannot use nsCOMPtr::swap
+        if (NS_SUCCEEDED(rv)) {
+            out.forget(result);
+        }
     }
     return rv;
 }
 
 /**
  * Attempts to buffer a given output stream.  If this fails, it returns the
  * passed-in output stream.
  *
@@ -1513,17 +1519,17 @@ NS_NewPostDataStream(nsIInputStream  **r
         (do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv));
     if (NS_FAILED(rv))
         return rv;
 
     rv = stream->SetData(data.BeginReading(), data.Length());
     if (NS_FAILED(rv))
         return rv;
 
-    NS_ADDREF(*result = stream);
+    stream.forget(result);
     return NS_OK;
 }
 
 inline nsresult
 NS_ReadInputStreamToBuffer(nsIInputStream *aInputStream, 
                            void** aDest,
                            uint32_t aCount)
 {
--- a/netwerk/base/nsURLHelperOSX.cpp
+++ b/netwerk/base/nsURLHelperOSX.cpp
@@ -206,11 +206,11 @@ net_GetFileFromURLSpec(const nsACString 
   if (bHFSPath)
     convertHFSPathtoPOSIX(path, path);
 
   // assuming path is encoded in the native charset
   rv = localFile->InitWithNativePath(path);
   if (NS_FAILED(rv))
     return rv;
 
-  NS_ADDREF(*result = localFile);
+  localFile.forget(result);
   return NS_OK;
 }
--- a/netwerk/base/nsURLHelperUnix.cpp
+++ b/netwerk/base/nsURLHelperUnix.cpp
@@ -91,11 +91,11 @@ net_GetFileFromURLSpec(const nsACString 
             // encoding is valid as UTF-8.
     }
     else 
         // if path is not in UTF-8, assume it is encoded in the native charset
         rv = localFile->InitWithNativePath(path);
 
     if (NS_FAILED(rv)) return rv;
 
-    NS_ADDREF(*result = localFile);
+    localFile.forget(result);
     return NS_OK;
 }
--- a/netwerk/base/nsURLHelperWin.cpp
+++ b/netwerk/base/nsURLHelperWin.cpp
@@ -107,11 +107,11 @@ net_GetFileFromURLSpec(const nsACString 
         // However, the chance is very low that a meaningful word in a legacy
         // encoding is valid as UTF-8.
     else 
         // if path is not in UTF-8, assume it is encoded in the native charset
         rv = localFile->InitWithNativePath(path);
 
     if (NS_FAILED(rv)) return rv;
 
-    NS_ADDREF(*result = localFile);
+    localFile.forget(result);
     return NS_OK;
 }
--- a/netwerk/protocol/data/nsDataChannel.cpp
+++ b/netwerk/protocol/data/nsDataChannel.cpp
@@ -78,12 +78,12 @@ nsDataChannel::OpenContentStream(bool as
     }
     if (NS_FAILED(rv))
         return rv;
 
     SetContentType(contentType);
     SetContentCharset(contentCharset);
     mContentLength = contentLen;
 
-    NS_ADDREF(*result = bufInStream);
+    bufInStream.forget(result);
 
     return NS_OK;
 }
--- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp
+++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp
@@ -2063,17 +2063,17 @@ nsHttpConnectionMgr::BuildPipeline(nsCon
     /* form a pipeline here even if nothing is pending so that we
        can stream-feed it as new transactions arrive */
 
     /* the first transaction can go in unconditionally - 1 transaction
        on a nsHttpPipeline object is not a real HTTP pipeline */
 
     nsRefPtr<nsHttpPipeline> pipeline = new nsHttpPipeline();
     pipeline->AddTransaction(firstTrans);
-    NS_ADDREF(*result = pipeline);
+    pipeline.forget(result);
     return NS_OK;
 }
 
 void
 nsHttpConnectionMgr::ReportProxyTelemetry(nsConnectionEntry *ent)
 {
     enum { PROXY_NONE = 1, PROXY_HTTP = 2, PROXY_SOCKS = 3, PROXY_HTTPS = 4 };
 
--- a/netwerk/protocol/http/nsHttpDigestAuth.cpp
+++ b/netwerk/protocol/http/nsHttpDigestAuth.cpp
@@ -266,17 +266,17 @@ nsHttpDigestAuth::GenerateCredentials(ns
       v->SetData(nc);
     }
   }
   else {
     nsCOMPtr<nsISupportsPRUint32> v(
             do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID));
     if (v) {
       v->SetData(1);
-      NS_ADDREF(*sessionState = v);
+      v.forget(sessionState);
     }
   }
   LOG(("   nonce_count=%s\n", nonce_count));
 
   //
   // this lets the client verify the server response (via a server
   // returned Authentication-Info header). also used for session info.
   //
--- a/netwerk/protocol/websocket/BaseWebSocketChannel.cpp
+++ b/netwerk/protocol/websocket/BaseWebSocketChannel.cpp
@@ -245,17 +245,17 @@ BaseWebSocketChannel::NewURI(const nsACS
   if (NS_FAILED(rv))
     return rv;
 
   nsRefPtr<nsStandardURL> url = new nsStandardURL();
   rv = url->Init(nsIStandardURL::URLTYPE_AUTHORITY, port, aSpec,
                 aOriginCharset, aBaseURI);
   if (NS_FAILED(rv))
     return rv;
-  NS_ADDREF(*_retval = url);
+  url.forget(_retval);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 BaseWebSocketChannel::NewChannel2(nsIURI* aURI,
                                   nsILoadInfo* aLoadInfo,
                                   nsIChannel** outChannel)
 {
--- a/netwerk/protocol/wyciwyg/nsWyciwygProtocolHandler.cpp
+++ b/netwerk/protocol/wyciwyg/nsWyciwygProtocolHandler.cpp
@@ -73,18 +73,17 @@ nsWyciwygProtocolHandler::NewURI(const n
   nsresult rv;
 
   nsCOMPtr<nsIURI> url = do_CreateInstance(NS_SIMPLEURI_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = url->SetSpec(aSpec);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  *result = url;
-  NS_ADDREF(*result);
+  url.forget(result);
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsWyciwygProtocolHandler::NewChannel2(nsIURI* url,
                                       nsILoadInfo* aLoadInfo,
                                       nsIChannel** result)
--- a/netwerk/streamconv/nsStreamConverterService.cpp
+++ b/netwerk/streamconv/nsStreamConverterService.cpp
@@ -449,19 +449,17 @@ nsStreamConverterService::Convert(nsIInp
             dataToConvert = convertedData;
             if (NS_FAILED(rv)) {
                 delete converterChain;
                 return rv;
             }
         }
 
         delete converterChain;
-        *_retval = convertedData;
-        NS_ADDREF(*_retval);
-
+        convertedData.forget(_retval);
     } else {
         // we're going direct.
         rv = converter->Convert(aFromStream, aFromType, aToType, aContext, _retval);
     }
 
     return rv;
 }
 
@@ -541,25 +539,21 @@ nsStreamConverterService::AsyncConvertDa
             // pointing to the converter that "starts" the conversion chain.
             // this converter's "from" type is the original "from" type. Prior
             // to the last iteration, finalListener will continuously be wedged
             // into the next listener in the chain, then be updated.
             finalListener = chainListener;
         }
         delete converterChain;
         // return the first listener in the chain.
-        *_retval = finalListener;
-        NS_ADDREF(*_retval);
-
+        finalListener.forget(_retval);
     } else {
         // we're going direct.
-        *_retval = listener;
-        NS_ADDREF(*_retval);
-
         rv = listener->AsyncConvertData(aFromType, aToType, aListener, aContext);
+        listener.forget(_retval);
     }
 
     return rv;
 
 }
 
 nsresult
 NS_NewStreamConv(nsStreamConverterService** aStreamConv)
--- a/toolkit/components/commandlines/nsCommandLine.cpp
+++ b/toolkit/components/commandlines/nsCommandLine.cpp
@@ -270,17 +270,17 @@ nsCommandLine::ResolveFile(const nsAStri
                                                           true, baseurl);
 
   CFRelease(baseurl);
 
   rv = newfile->InitWithCFURL(newurl);
   CFRelease(newurl);
   if (NS_FAILED(rv)) return rv;
 
-  NS_ADDREF(*aResult = newfile);
+  newfile.forget(aResult);
   return NS_OK;
 
 #elif defined(XP_UNIX)
   nsCOMPtr<nsIFile> lf (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID));
   NS_ENSURE_TRUE(lf, NS_ERROR_OUT_OF_MEMORY);
 
   if (aArgument.First() == '/') {
     // absolute path
@@ -301,17 +301,17 @@ nsCommandLine::ResolveFile(const nsAStri
   newpath.Append(nativeArg);
 
   rv = lf->InitWithNativePath(newpath);
   if (NS_FAILED(rv)) return rv;
 
   rv = lf->Normalize();
   if (NS_FAILED(rv)) return rv;
 
-  NS_ADDREF(*aResult = lf);
+  lf.forget(aResult);
   return NS_OK;
 
 #elif defined(XP_WIN32)
   nsCOMPtr<nsIFile> lf (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID));
   NS_ENSURE_TRUE(lf, NS_ERROR_OUT_OF_MEMORY);
 
   rv = lf->InitWithPath(aArgument);
   if (NS_FAILED(rv)) {
@@ -328,17 +328,17 @@ nsCommandLine::ResolveFile(const nsAStri
 
     WCHAR pathBuf[MAX_PATH];
     if (!_wfullpath(pathBuf, fullPath.get(), MAX_PATH))
       return NS_ERROR_FAILURE;
 
     rv = lf->InitWithPath(nsDependentString(pathBuf));
     if (NS_FAILED(rv)) return rv;
   }
-  NS_ADDREF(*aResult = lf);
+  lf.forget(aResult);
   return NS_OK;
 
 #else
 #error Need platform-specific logic here.
 #endif
 }
 
 NS_IMETHODIMP
--- a/toolkit/components/downloads/nsDownloadManager.cpp
+++ b/toolkit/components/downloads/nsDownloadManager.cpp
@@ -1275,17 +1275,17 @@ nsDownloadManager::GetDownloadFromDB(moz
     NS_ENSURE_SUCCESS(rv, rv);
     rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("id"), dl->mID);
     NS_ENSURE_SUCCESS(rv, rv);
     rv = stmt->Execute();
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Addrefing and returning
-  NS_ADDREF(*retVal = dl);
+  dl.forget(retVal);
   return NS_OK;
 }
 
 nsresult
 nsDownloadManager::AddToCurrentDownloads(nsDownload *aDl)
 {
   nsCOMArray<nsDownload>& currentDownloads =
     aDl->mPrivate ? mCurrentPrivateDownloads : mCurrentDownloads;
@@ -1670,17 +1670,17 @@ nsDownloadManager::AddDownload(DownloadT
     if (logEnabled) {
       (void)pc->Log(nsIParentalControlsService::ePCLog_FileDownload,
                     enabled,
                     aSource,
                     nullptr);
     }
   }
 
-  NS_ADDREF(*aDownload = dl);
+  dl.forget(aDownload);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsDownloadManager::GetDownload(uint32_t aID, nsIDownload **aDownloadItem)
 {
   NS_ENSURE_STATE(!mUseJSTransfer);
--- a/toolkit/components/filepicker/nsFileView.cpp
+++ b/toolkit/components/filepicker/nsFileView.cpp
@@ -557,17 +557,17 @@ nsFileView::GetSelectedFiles(nsIArray** 
           curFile = mFilteredFiles[itemIndex - dirCount];
       }
 
       if (curFile)
         fileArray->AppendElement(curFile, false);
     }
   }
 
-  NS_ADDREF(*aFiles = fileArray);
+  fileArray.forget(aFiles);
   return NS_OK;
 }
 
 
 // nsITreeView implementation
 
 NS_IMETHODIMP
 nsFileView::GetRowCount(int32_t* aRowCount)
--- a/toolkit/components/places/SQLFunctions.cpp
+++ b/toolkit/components/places/SQLFunctions.cpp
@@ -711,17 +711,17 @@ namespace places {
       src.Truncate(src.Length() - 1);
       nsAutoString dest;
       ReverseString(src, dest);
       result->SetAsAString(dest);
     }
     else {
       result->SetAsAString(EmptyString());
     }
-    NS_ADDREF(*_result = result);
+    result.forget(_result);
     return NS_OK;
   }
 
 ////////////////////////////////////////////////////////////////////////////////
 //// Fixup URL Function
 
   FixupURLFunction::~FixupURLFunction()
   {
@@ -766,17 +766,17 @@ namespace places {
     NS_ENSURE_STATE(result);
 
     // Remove common URL hostname prefixes
     if (StringBeginsWith(src, NS_LITERAL_STRING("www."))) {
       src.Cut(0, 4);
     }
 
     result->SetAsAString(src);
-    NS_ADDREF(*_result = result);
+    result.forget(_result);
     return NS_OK;
   }
 
 ////////////////////////////////////////////////////////////////////////////////
 //// Frecency Changed Notification Function
 
   FrecencyNotificationFunction::~FrecencyNotificationFunction()
   {
@@ -828,14 +828,14 @@ namespace places {
     navHistory->DispatchFrecencyChangedNotification(spec, newFrecency, guid,
                                                     hidden, lastVisitDate);
 
     nsCOMPtr<nsIWritableVariant> result =
       do_CreateInstance("@mozilla.org/variant;1");
     NS_ENSURE_STATE(result);
     rv = result->SetAsInt32(newFrecency);
     NS_ENSURE_SUCCESS(rv, rv);
-    NS_ADDREF(*_result = result);
+    result.forget(_result);
     return NS_OK;
   }
 
 } // namespace places
 } // namespace mozilla
--- a/toolkit/components/places/nsAnnotationService.cpp
+++ b/toolkit/components/places/nsAnnotationService.cpp
@@ -662,18 +662,19 @@ nsAnnotationService::GetPageAnnotation(n
       break;
     }
     default: {
       rv = NS_ERROR_UNEXPECTED;
       break;
     }
   }
 
-  if (NS_SUCCEEDED(rv))
-    NS_ADDREF(*_retval = value);
+  if (NS_SUCCEEDED(rv)) {
+    value.forget(_retval);
+  }
 
   return rv;
 }
 
 
 NS_IMETHODIMP
 nsAnnotationService::GetItemAnnotation(int64_t aItemId,
                                        const nsACString& aName,
@@ -706,18 +707,19 @@ nsAnnotationService::GetItemAnnotation(i
       break;
     }
     default: {
       rv = NS_ERROR_UNEXPECTED;
       break;
     }
   }
 
-  if (NS_SUCCEEDED(rv))
-    NS_ADDREF(*_retval = value);
+  if (NS_SUCCEEDED(rv)) {
+    value.forget(_retval);
+  }
 
   return rv;
 }
 
 
 NS_IMETHODIMP
 nsAnnotationService::GetPageAnnotationInt32(nsIURI* aURI,
                                         const nsACString& aName,
--- a/toolkit/components/places/nsNavHistoryQuery.cpp
+++ b/toolkit/components/places/nsNavHistoryQuery.cpp
@@ -277,17 +277,17 @@ nsNavHistory::QueryStringToQueries(const
     *aQueries = static_cast<nsINavHistoryQuery**>
                            (moz_xmalloc(sizeof(nsINavHistoryQuery*) * queries.Count()));
     NS_ENSURE_TRUE(*aQueries, NS_ERROR_OUT_OF_MEMORY);
     for (int32_t i = 0; i < queries.Count(); i ++) {
       (*aQueries)[i] = queries[i];
       NS_ADDREF((*aQueries)[i]);
     }
   }
-  NS_ADDREF(*aOptions = options);
+  options.forget(aOptions);
   return NS_OK;
 }
 
 
 // nsNavHistory::QueryStringToQueryArray
 //
 //    An internal version of QueryStringToQueries that fills a COM array for
 //    ease-of-use.
@@ -311,17 +311,17 @@ nsNavHistory::QueryStringToQueryArray(co
 
   rv = TokensToQueries(tokens, aQueries, options);
   if (NS_FAILED(rv)) {
     NS_WARNING("Unable to parse the query string: ");
     NS_WARNING(PromiseFlatCString(aQueryString).get());
     return rv;
   }
 
-  NS_ADDREF(*aOptions = options);
+  options.forget(aOptions);
   return NS_OK;
 }
 
 
 // nsNavHistory::QueriesToQueryString
 
 NS_IMETHODIMP
 nsNavHistory::QueriesToQueryString(nsINavHistoryQuery **aQueries,
@@ -1158,17 +1158,17 @@ NS_IMETHODIMP nsNavHistoryQuery::GetTags
     rv = out->SetAsArray(nsIDataType::VTYPE_WCHAR_STR,
                          nullptr,
                          arrayLen,
                          reinterpret_cast<void *>(array));
     NS_Free(array);
   }
   NS_ENSURE_SUCCESS(rv, rv);
 
-  NS_ADDREF(*aTags = out);
+  out.forget(aTags);
   return NS_OK;
 }
 
 NS_IMETHODIMP nsNavHistoryQuery::SetTags(nsIVariant *aTags)
 {
   NS_ENSURE_ARG(aTags);
 
   uint16_t dataType;
--- a/toolkit/components/typeaheadfind/nsTypeAheadFind.cpp
+++ b/toolkit/components/typeaheadfind/nsTypeAheadFind.cpp
@@ -814,21 +814,18 @@ nsTypeAheadFind::GetSearchContainers(nsI
 
     // We need to set the start point this way, other methods haven't worked
     mStartPointRange->SelectNode(startNode);
     mStartPointRange->SetStart(startNode, startOffset);
   }
 
   mStartPointRange->Collapse(true); // collapse to start
 
-  *aPresShell = presShell;
-  NS_ADDREF(*aPresShell);
-
-  *aPresContext = presContext;
-  NS_ADDREF(*aPresContext);
+  presShell.forget(aPresShell);
+  presContext.forget(aPresContext);
 
   return NS_OK;
 }
 
 void
 nsTypeAheadFind::RangeStartsInsideLink(nsIDOMRange *aRange,
                                        nsIPresShell *aPresShell,
                                        bool *aIsInsideLink,
--- a/toolkit/components/url-classifier/nsCheckSummedOutputStream.h
+++ b/toolkit/components/url-classifier/nsCheckSummedOutputStream.h
@@ -41,14 +41,15 @@ inline nsresult
 NS_NewCheckSummedOutputStream(nsIOutputStream **result,
                               nsIFile         *file,
                               int32_t         ioFlags       = -1,
                               int32_t         perm          = -1,
                               int32_t         behaviorFlags =  0)
 {
     nsCOMPtr<nsIFileOutputStream> out = new nsCheckSummedOutputStream();
     nsresult rv = out->Init(file, ioFlags, perm, behaviorFlags);
-    if (NS_SUCCEEDED(rv))
-      NS_ADDREF(*result = out);  // cannot use nsCOMPtr::swap
+    if (NS_SUCCEEDED(rv)) {
+      out.forget(result);
+    }
     return rv;
 }
 
 #endif
--- a/toolkit/profile/nsToolkitProfileService.cpp
+++ b/toolkit/profile/nsToolkitProfileService.cpp
@@ -671,17 +671,17 @@ NS_LockProfilePath(nsIFile* aPath, nsIFi
                    nsIProfileUnlocker* *aUnlocker, nsIProfileLock* *aResult)
 {
     nsRefPtr<nsToolkitProfileLock> lock = new nsToolkitProfileLock();
     if (!lock) return NS_ERROR_OUT_OF_MEMORY;
 
     nsresult rv = lock->Init(aPath, aTempPath, aUnlocker);
     if (NS_FAILED(rv)) return rv;
 
-    NS_ADDREF(*aResult = lock);
+    lock.forget(aResult);
     return NS_OK;
 }
 
 static const char kTable[] =
     { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
       'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
       '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
 
@@ -899,17 +899,17 @@ nsToolkitProfileService::CreateProfileIn
         while (last->mNext)
             last = last->mNext;
     }
 
     nsCOMPtr<nsIToolkitProfile> profile =
         new nsToolkitProfile(aName, rootDir, localDir, last, aForExternalApp);
     if (!profile) return NS_ERROR_OUT_OF_MEMORY;
 
-    NS_ADDREF(*aResult = profile);
+    profile.forget(aResult);
     return NS_OK;
 }
 
 nsresult
 nsToolkitProfileService::CreateTimesInternal(nsIFile* aProfileDir)
 {
     nsresult rv = NS_ERROR_FAILURE;
     nsCOMPtr<nsIFile> creationLog;
@@ -1103,18 +1103,19 @@ XRE_GetFileFromPath(const char *aPath, n
 
     nsCOMPtr<nsIFile> lf;
     nsresult rv = NS_NewNativeLocalFile(EmptyCString(), true,
                                         getter_AddRefs(lf));
     if (NS_SUCCEEDED(rv)) {
         nsCOMPtr<nsILocalFileMac> lfMac = do_QueryInterface(lf, &rv);
         if (NS_SUCCEEDED(rv)) {
             rv = lfMac->InitWithCFURL(fullPath);
-            if (NS_SUCCEEDED(rv))
-                NS_ADDREF(*aResult = lf);
+            if (NS_SUCCEEDED(rv)) {
+                lf.forget(aResult);
+            }
         }
     }
     CFRelease(fullPath);
     return rv;
 
 #elif defined(XP_UNIX)
     char fullPath[MAXPATHLEN];
 
--- a/toolkit/system/gnome/nsGConfService.cpp
+++ b/toolkit/system/gnome/nsGConfService.cpp
@@ -185,17 +185,17 @@ nsGConfService::GetStringList(const nsAC
       return NS_ERROR_OUT_OF_MEMORY;
     }
     obj->SetData(NS_ConvertUTF8toUTF16((const char*)l->data));
     items->AppendElement(obj, false);
     g_free(l->data);
   }
   
   g_slist_free(list);
-  NS_ADDREF(*aResult = items);
+  items.forget(aResult);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGConfService::SetBool(const nsACString &aKey, bool aValue)
 {
   bool res = gconf_client_set_bool(mClient, PromiseFlatCString(aKey).get(),
                                      aValue, nullptr);
--- a/toolkit/system/gnome/nsGIOService.cpp
+++ b/toolkit/system/gnome/nsGIOService.cpp
@@ -137,17 +137,17 @@ nsGIOMimeApp::GetSupportedURISchemes(nsI
 
   while (*uri_schemes != nullptr) {
     if (!array->mStrings.AppendElement(*uri_schemes)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
     uri_schemes++;
   }
 
-  NS_ADDREF(*aSchemes = array);
+  array.forget(aSchemes);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsGIOMimeApp::SetAsDefaultForMimeType(nsACString const& aMimeType)
 {
   char *content_type =
     g_content_type_from_mime_type(PromiseFlatCString(aMimeType).get());
--- a/toolkit/system/gnome/nsGSettingsService.cpp
+++ b/toolkit/system/gnome/nsGSettingsService.cpp
@@ -267,33 +267,33 @@ nsGSettingsCollection::GetStringList(con
   if (!g_variant_is_of_type(value, G_VARIANT_TYPE_STRING_ARRAY)) {
     g_variant_unref(value);
     return NS_ERROR_FAILURE;
   }
 
   const gchar ** gs_strings = g_variant_get_strv(value, nullptr);
   if (!gs_strings) {
     // empty array
-    NS_ADDREF(*aResult = items);
+    items.forget(aResult);
     g_variant_unref(value);
     return NS_OK;
   }
 
   const gchar** p_gs_strings = gs_strings;
   while (*p_gs_strings != nullptr)
   {
     nsCOMPtr<nsISupportsCString> obj(do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID));
     if (obj) {
       obj->SetData(nsDependentCString(*p_gs_strings));
       items->AppendElement(obj, false);
     }
     p_gs_strings++;
   }
   g_free(gs_strings);
-  NS_ADDREF(*aResult = items);
+  items.forget(aResult);
   g_variant_unref(value);
   return NS_OK;
 }
 
 nsresult
 nsGSettingsService::Init()
 {
 #define FUNC(name, type, params) { #name, (nsGSettingsFunc *)&_##name },
--- a/toolkit/xre/nsUpdateDriver.cpp
+++ b/toolkit/xre/nsUpdateDriver.cpp
@@ -189,17 +189,17 @@ GetXULRunnerStubPath(const char* argv0, 
   nsCOMPtr<nsILocalFileMac> lfm;
   nsresult rv = NS_NewLocalFileWithCFURL(bundleURL, true, getter_AddRefs(lfm));
 
   ::CFRelease(bundleURL);
 
   if (NS_FAILED(rv))
     return rv;
 
-  NS_ADDREF(*aResult = static_cast<nsIFile*>(lfm.get()));
+  lfm.forget(aResult);
   return NS_OK;
 }
 #endif /* XP_MACOSX */
 
 static bool
 GetFile(nsIFile *dir, const nsCSubstring &name, nsCOMPtr<nsIFile> &result)
 {
   nsresult rv;
--- a/toolkit/xre/nsXREDirProvider.cpp
+++ b/toolkit/xre/nsXREDirProvider.cpp
@@ -388,17 +388,17 @@ nsXREDirProvider::GetFile(const char* aP
     // We need to allow component, xpt, and chrome registration to
     // occur prior to the profile-after-change notification.
     if (!strcmp(aProperty, NS_APP_USER_CHROME_DIR)) {
       rv = file->AppendNative(NS_LITERAL_CSTRING("chrome"));
     }
   }
 
   if (NS_SUCCEEDED(rv) && file) {
-    NS_ADDREF(*aFile = file);
+    file.forget(aFile);
     return NS_OK;
   }
 
   bool ensureFilePermissions = false;
 
   if (NS_SUCCEEDED(GetProfileDir(getter_AddRefs(file)))) {
     if (!strcmp(aProperty, NS_APP_PREFS_50_DIR)) {
       rv = NS_OK;
@@ -454,17 +454,17 @@ nsXREDirProvider::GetFile(const char* aP
       uint32_t permissions;
       if (NS_SUCCEEDED(file->GetPermissions(&permissions))) {
         rv = file->SetPermissions(permissions | 0600);
         NS_ASSERTION(NS_SUCCEEDED(rv), "failed to ensure file permissions");
       }
     }
   }
 
-  NS_ADDREF(*aFile = file);
+  file.forget(aFile);
   return NS_OK;
 }
 
 static void
 LoadDirIntoArray(nsIFile* dir,
                  const char *const *aAppendList,
                  nsCOMArray<nsIFile>& aDirectories)
 {
@@ -520,26 +520,26 @@ nsXREDirProvider::GetFiles(const char* a
   nsCOMPtr<nsIDirectoryServiceProvider2>
     appP2(do_QueryInterface(mAppProvider));
   if (appP2) {
     rv = appP2->GetFiles(aProperty, getter_AddRefs(appEnum));
     if (NS_FAILED(rv)) {
       appEnum = nullptr;
     }
     else if (rv != NS_SUCCESS_AGGREGATE_RESULT) {
-      NS_ADDREF(*aResult = appEnum);
+      appEnum.forget(aResult);
       return NS_OK;
     }
   }
 
   nsCOMPtr<nsISimpleEnumerator> xreEnum;
   rv = GetFilesInternal(aProperty, getter_AddRefs(xreEnum));
   if (NS_FAILED(rv)) {
     if (appEnum) {
-      NS_ADDREF(*aResult = appEnum);
+      appEnum.forget(aResult);
       return NS_SUCCESS_AGGREGATE_RESULT;
     }
 
     return rv;
   }
 
   rv = NS_NewUnionEnumerator(aResult, appEnum, xreEnum);
   if (NS_FAILED(rv))
@@ -1063,17 +1063,17 @@ nsXREDirProvider::GetUpdateRootDir(nsIFi
     return NS_ERROR_FAILURE;
   }
 
   if (NS_FAILED(localDir->Append(NS_LITERAL_STRING("updates"))) ||
       NS_FAILED(localDir->AppendRelativePath(appDirPath))) {
     return NS_ERROR_FAILURE;
   }
 
-  NS_ADDREF(*aResult = localDir);
+  NS_localDir.forget(aResult);
   return NS_OK;
 
 #elif XP_WIN
   nsAutoString pathHash;
   bool pathHashResult = false;
   bool hasVendor = gAppData->vendor && strlen(gAppData->vendor) != 0;
 
   nsAutoString appDirPath;
@@ -1104,17 +1104,17 @@ nsXREDirProvider::GetUpdateRootDir(nsIFi
   // Metro & Desktop).
   nsCOMPtr<nsIFile> localDir;
   if (pathHashResult && (hasVendor || gAppData->name) &&
       NS_SUCCEEDED(GetUserDataDirectoryHome(getter_AddRefs(localDir), true)) &&
       NS_SUCCEEDED(localDir->AppendNative(nsDependentCString(hasVendor ?
                                           gAppData->vendor : gAppData->name))) &&
       NS_SUCCEEDED(localDir->Append(NS_LITERAL_STRING("updates"))) &&
       NS_SUCCEEDED(localDir->Append(pathHash))) {
-    NS_ADDREF(*aResult = localDir);
+    localDir.forget(aResult);
     return NS_OK;
   }
 
   nsAutoString appPath;
   rv = updRoot->GetPath(appPath);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // AppDir may be a short path. Convert to long path to make sure
@@ -1157,17 +1157,17 @@ nsXREDirProvider::GetUpdateRootDir(nsIFi
   rv = GetUserLocalDataDirectory(getter_AddRefs(updRoot));
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = updRoot->AppendRelativePath(programName);
   NS_ENSURE_SUCCESS(rv, rv);
 
 #endif // XP_WIN
 #endif
-  NS_ADDREF(*aResult = updRoot);
+  updRoot.forget(aResult);
   return NS_OK;
 }
 
 nsresult
 nsXREDirProvider::GetProfileStartupDir(nsIFile* *aResult)
 {
   if (mProfileDir)
     return mProfileDir->Clone(aResult);
@@ -1301,17 +1301,17 @@ nsXREDirProvider::GetSysUserExtensionsDi
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = AppendSysUserExtensionPath(localDir);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = EnsureDirectoryExists(localDir);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  NS_ADDREF(*aFile = localDir);
+  localDir.forget(aFile);
   return NS_OK;
 }
 
 #if defined(XP_UNIX) || defined(XP_MACOSX)
 nsresult
 nsXREDirProvider::GetSystemExtensionsDirectory(nsIFile** aFile)
 {
   nsresult rv;
@@ -1349,17 +1349,17 @@ nsXREDirProvider::GetSystemExtensionsDir
     "/usr/lib/mozilla/extensions";
 #endif
 
   rv = NS_NewNativeLocalFile(nsDependentCString(sysSExtDir), false,
                              getter_AddRefs(localDir));
   NS_ENSURE_SUCCESS(rv, rv);
 #endif
 
-  NS_ADDREF(*aFile = localDir);
+  localDir.forget(aFile);
   return NS_OK;
 }
 #endif
 
 nsresult
 nsXREDirProvider::GetUserDataDirectory(nsIFile** aFile, bool aLocal,
                                        const nsACString* aProfileName,
                                        const nsACString* aAppName,
@@ -1375,17 +1375,17 @@ nsXREDirProvider::GetUserDataDirectory(n
 #ifdef DEBUG_jungshik
   nsAutoCString cwd;
   localDir->GetNativePath(cwd);
   printf("nsXREDirProvider::GetUserDataDirectory: %s\n", cwd.get());
 #endif
   rv = EnsureDirectoryExists(localDir);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  NS_ADDREF(*aFile = localDir);
+  localDir.forget(aFile);
   return NS_OK;
 }
 
 nsresult
 nsXREDirProvider::EnsureDirectoryExists(nsIFile* aDirectory)
 {
   bool exists;
   nsresult rv = aDirectory->Exists(&exists);
@@ -1443,17 +1443,17 @@ nsXREDirProvider::GetProfileDefaultsDir(
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = defaultsDir->AppendNative(NS_LITERAL_CSTRING("defaults"));
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = defaultsDir->AppendNative(NS_LITERAL_CSTRING("profile"));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  NS_ADDREF(*aResult = defaultsDir);
+  defaultsDir.forget(aResult);
   return NS_OK;
 }
 
 nsresult
 nsXREDirProvider::AppendSysUserExtensionPath(nsIFile* aFile)
 {
   NS_ASSERTION(aFile, "Null pointer!");