Bug 1160485 - remove implicit conversion from RefPtr<T> to TemporaryRef<T>; r=ehsan
authorNathan Froyd <froydnj@mozilla.com>
Fri, 01 May 2015 09:14:16 -0400
changeset 245148 e9b68252df54c12015382d022f01e06c5605e27a
parent 245147 b1c86100dbce2eef1686b57b59c76ff78cfbc376
child 245149 a33ee01bca86051f053ba83251b1fe702907c1f9
push id13109
push userryanvm@gmail.com
push dateFri, 22 May 2015 18:21:40 +0000
treeherderfx-team@1a7bb3dee243 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersehsan
bugs1160485
milestone41.0a1
Bug 1160485 - remove implicit conversion from RefPtr<T> to TemporaryRef<T>; r=ehsan Having this implicit conversion means that we can silently do extra refcounting when it's completely unnecessary. It's also an obstacle to making RefPtr more nsRefPtr-like, so let's get rid of it.
dom/canvas/CanvasRenderingContext2D.cpp
dom/media/MediaDecoder.cpp
dom/media/MediaDecoderReader.cpp
dom/media/MediaFormatReader.cpp
dom/media/directshow/AudioSinkInputPin.cpp
dom/media/directshow/DirectShowUtils.cpp
dom/media/mediasource/TrackBuffer.cpp
dom/media/omx/MediaCodecReader.cpp
dom/media/omx/MediaOmxCommonDecoder.cpp
dom/media/platforms/agnostic/BlankDecoderModule.cpp
dom/media/platforms/wmf/MFTDecoder.cpp
dom/media/webaudio/MediaBufferDecoder.cpp
dom/media/webaudio/blink/HRTFDatabaseLoader.cpp
dom/svg/nsSVGPathGeometryElement.cpp
dom/system/gonk/MozMtpDatabase.cpp
dom/system/gonk/VolumeManager.cpp
gfx/2d/DrawTarget.cpp
gfx/2d/DrawTargetCG.cpp
gfx/2d/DrawTargetCairo.cpp
gfx/2d/DrawTargetD2D.cpp
gfx/2d/DrawTargetD2D1.cpp
gfx/2d/Factory.cpp
gfx/2d/FilterProcessingSIMD-inl.h
gfx/2d/SVGTurbulenceRenderer-inl.h
gfx/layers/D3D9SurfaceImage.cpp
gfx/layers/Effects.h
gfx/layers/GrallocImages.cpp
gfx/layers/IMFYCbCrImage.cpp
gfx/layers/MacIOSurfaceImage.cpp
gfx/layers/RotatedBuffer.cpp
gfx/layers/TextureDIB.cpp
gfx/layers/basic/TextureClientX11.cpp
gfx/layers/basic/TextureHostBasic.cpp
gfx/layers/client/ImageClient.cpp
gfx/layers/client/TextureClient.cpp
gfx/layers/client/TextureClient.h
gfx/layers/client/TextureClientPool.cpp
gfx/layers/composite/CompositableHost.cpp
gfx/layers/composite/TextureHost.cpp
gfx/layers/d3d11/CompositorD3D11.cpp
gfx/layers/d3d11/TextureD3D11.cpp
gfx/layers/d3d9/CompositorD3D9.cpp
gfx/layers/d3d9/DeviceManagerD3D9.cpp
gfx/layers/d3d9/TextureD3D9.cpp
gfx/layers/ipc/CompositorBench.cpp
gfx/layers/opengl/CompositorOGL.cpp
gfx/layers/opengl/GrallocTextureClient.cpp
gfx/layers/opengl/MacIOSurfaceTextureClientOGL.cpp
gfx/src/FilterSupport.cpp
gfx/tests/gtest/TestCompositor.cpp
gfx/thebes/gfxContext.cpp
gfx/thebes/gfxDWriteFonts.cpp
gfx/thebes/gfxMacFont.cpp
gfx/thebes/gfxPlatform.cpp
gfx/thebes/gfxUtils.cpp
gfx/thebes/gfxWindowsPlatform.cpp
image/ClippedImage.cpp
image/RasterImage.cpp
image/imgFrame.cpp
layout/base/nsCSSRenderingBorders.cpp
layout/svg/nsSVGMaskFrame.cpp
mfbt/RefPtr.h
mfbt/tests/TestRefPtr.cpp
mozglue/linker/BaseElf.cpp
mozglue/linker/CustomElf.cpp
mozglue/linker/ElfLoader.cpp
mozglue/linker/Zip.cpp
security/manager/ssl/src/nsNSSComponent.cpp
widget/cocoa/nsChildView.mm
widget/gonk/nativewindow/GonkBufferQueueJB.cpp
widget/gonk/nativewindow/GonkBufferQueueKK.cpp
widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.cpp
widget/gonk/nativewindow/GonkNativeWindowICS.cpp
widget/gonk/nativewindow/GonkNativeWindowJB.cpp
widget/gonk/nativewindow/GonkNativeWindowKK.cpp
widget/gonk/nativewindow/GonkNativeWindowLL.cpp
widget/gonk/nsWindow.cpp
--- a/dom/canvas/CanvasRenderingContext2D.cpp
+++ b/dom/canvas/CanvasRenderingContext2D.cpp
@@ -5631,40 +5631,44 @@ CanvasPath::GetPath(const CanvasWindingR
   FillRule fillRule = FillRule::FILL_WINDING;
   if (winding == CanvasWindingRule::Evenodd) {
     fillRule = FillRule::FILL_EVEN_ODD;
   }
 
   if (mPath &&
       (mPath->GetBackendType() == aTarget->GetBackendType()) &&
       (mPath->GetFillRule() == fillRule)) {
-    return mPath;
+    RefPtr<gfx::Path> path(mPath);
+    return path.forget();
   }
 
   if (!mPath) {
     // if there is no path, there must be a pathbuilder
     MOZ_ASSERT(mPathBuilder);
     mPath = mPathBuilder->Finish();
-    if (!mPath)
-      return mPath;
+    if (!mPath) {
+      RefPtr<gfx::Path> path(mPath);
+      return path.forget();
+    }
 
     mPathBuilder = nullptr;
   }
 
   // retarget our backend if we're used with a different backend
   if (mPath->GetBackendType() != aTarget->GetBackendType()) {
     RefPtr<PathBuilder> tmpPathBuilder = aTarget->CreatePathBuilder(fillRule);
     mPath->StreamToSink(tmpPathBuilder);
     mPath = tmpPathBuilder->Finish();
   } else if (mPath->GetFillRule() != fillRule) {
     RefPtr<PathBuilder> tmpPathBuilder = mPath->CopyToBuilder(fillRule);
     mPath = tmpPathBuilder->Finish();
   }
 
-  return mPath;
+  RefPtr<gfx::Path> path(mPath);
+  return path.forget();
 }
 
 void
 CanvasPath::EnsurePathBuilder() const
 {
   if (mPathBuilder) {
     return;
   }
--- a/dom/media/MediaDecoder.cpp
+++ b/dom/media/MediaDecoder.cpp
@@ -204,33 +204,33 @@ void MediaDecoder::UpdateDormantState(bo
   if (mIsDormant) {
     DECODER_LOG("UpdateDormantState() entering DORMANT state");
     // enter dormant state
     RefPtr<nsRunnable> event =
       NS_NewRunnableMethodWithArg<bool>(
         mDecoderStateMachine,
         &MediaDecoderStateMachine::SetDormant,
         true);
-    mDecoderStateMachine->TaskQueue()->Dispatch(event);
+    mDecoderStateMachine->TaskQueue()->Dispatch(event.forget());
 
     if (IsEnded()) {
       mWasEndedWhenEnteredDormant = true;
     }
     mNextState = mPlayState;
     ChangeState(PLAY_STATE_LOADING);
   } else {
     DECODER_LOG("UpdateDormantState() leaving DORMANT state");
     // exit dormant state
     // trigger to state machine.
     RefPtr<nsRunnable> event =
       NS_NewRunnableMethodWithArg<bool>(
         mDecoderStateMachine,
         &MediaDecoderStateMachine::SetDormant,
         false);
-    mDecoderStateMachine->TaskQueue()->Dispatch(event);
+    mDecoderStateMachine->TaskQueue()->Dispatch(event.forget());
   }
 }
 
 void MediaDecoder::DormantTimerExpired(nsITimer* aTimer, void* aClosure)
 {
   MOZ_ASSERT(aClosure);
   MediaDecoder* decoder = static_cast<MediaDecoder*>(aClosure);
   ReentrantMonitorAutoEnter mon(decoder->GetReentrantMonitor());
--- a/dom/media/MediaDecoderReader.cpp
+++ b/dom/media/MediaDecoderReader.cpp
@@ -272,17 +272,17 @@ MediaDecoderReader::RequestVideoData(boo
     if (!DecodeVideoFrame(skip, aTimeThreshold)) {
       VideoQueue().Finish();
     } else if (skip) {
       // We still need to decode more data in order to skip to the next
       // keyframe. Post another task to the decode task queue to decode
       // again. We don't just decode straight in a loop here, as that
       // would hog the decode task queue.
       RefPtr<nsIRunnable> task(new ReRequestVideoWithSkipTask(this, aTimeThreshold));
-      mTaskQueue->Dispatch(task);
+      mTaskQueue->Dispatch(task.forget());
       return p;
     }
   }
   if (VideoQueue().GetSize() > 0) {
     nsRefPtr<VideoData> v = VideoQueue().PopFront();
     if (v && mVideoDiscontinuity) {
       v->mDiscontinuity = true;
       mVideoDiscontinuity = false;
@@ -308,17 +308,17 @@ MediaDecoderReader::RequestAudioData()
       break;
     }
     // AudioQueue size is still zero, post a task to try again. Don't spin
     // waiting in this while loop since it somehow prevents audio EOS from
     // coming in gstreamer 1.x when there is still video buffer waiting to be
     // consumed. (|mVideoSinkBufferCount| > 0)
     if (AudioQueue().GetSize() == 0 && mTaskQueue) {
       RefPtr<nsIRunnable> task(new ReRequestAudioTask(this));
-      mTaskQueue->Dispatch(task);
+      mTaskQueue->Dispatch(task.forget());
       return p;
     }
   }
   if (AudioQueue().GetSize() > 0) {
     nsRefPtr<AudioData> a = AudioQueue().PopFront();
     if (mAudioDiscontinuity) {
       a->mDiscontinuity = true;
       mAudioDiscontinuity = false;
--- a/dom/media/MediaFormatReader.cpp
+++ b/dom/media/MediaFormatReader.cpp
@@ -1012,44 +1012,44 @@ MediaFormatReader::Output(TrackType aTra
     NS_WARNING("MediaFormatReader::Output() passed a null sample");
     Error(aTrack);
     return;
   }
 
   RefPtr<nsIRunnable> task =
     NS_NewRunnableMethodWithArgs<TrackType, StorensRefPtrPassByPtr<MediaData>>(
       this, &MediaFormatReader::NotifyNewOutput, aTrack, aSample);
-  GetTaskQueue()->Dispatch(task);
+  GetTaskQueue()->Dispatch(task.forget());
 }
 
 void
 MediaFormatReader::DrainComplete(TrackType aTrack)
 {
   RefPtr<nsIRunnable> task =
     NS_NewRunnableMethodWithArg<TrackType>(
       this, &MediaFormatReader::NotifyDrainComplete, aTrack);
-  GetTaskQueue()->Dispatch(task);
+  GetTaskQueue()->Dispatch(task.forget());
 }
 
 void
 MediaFormatReader::InputExhausted(TrackType aTrack)
 {
   RefPtr<nsIRunnable> task =
     NS_NewRunnableMethodWithArg<TrackType>(
       this, &MediaFormatReader::NotifyInputExhausted, aTrack);
-  GetTaskQueue()->Dispatch(task);
+  GetTaskQueue()->Dispatch(task.forget());
 }
 
 void
 MediaFormatReader::Error(TrackType aTrack)
 {
   RefPtr<nsIRunnable> task =
     NS_NewRunnableMethodWithArg<TrackType>(
       this, &MediaFormatReader::NotifyError, aTrack);
-  GetTaskQueue()->Dispatch(task);
+  GetTaskQueue()->Dispatch(task.forget());
 }
 
 void
 MediaFormatReader::Flush(TrackType aTrack)
 {
   MOZ_ASSERT(OnTaskQueue());
   LOG("Flush(%s) BEGIN", TrackTypeToStr(aTrack));
 
@@ -1357,12 +1357,12 @@ MediaFormatReader::NotifyDataArrived(con
   MOZ_ASSERT(mMainThreadDemuxer);
   mMainThreadDemuxer->NotifyDataArrived(aLength, aOffset);
 
   // Queue a task to notify our main demuxer.
   RefPtr<nsIRunnable> task =
     NS_NewRunnableMethodWithArgs<int32_t, uint64_t>(
       this, &MediaFormatReader::NotifyDemuxer,
       aLength, aOffset);
-  GetTaskQueue()->Dispatch(task);
+  GetTaskQueue()->Dispatch(task.forget());
 }
 
 } // namespace mozilla
--- a/dom/media/directshow/AudioSinkInputPin.cpp
+++ b/dom/media/directshow/AudioSinkInputPin.cpp
@@ -134,17 +134,17 @@ AudioSinkInputPin::Receive(IMediaSample*
 TemporaryRef<IMediaSeeking>
 AudioSinkInputPin::GetConnectedPinSeeking()
 {
   RefPtr<IPin> peer = GetConnected();
   if (!peer)
     return nullptr;
   RefPtr<IMediaSeeking> seeking;
   peer->QueryInterface(static_cast<IMediaSeeking**>(byRef(seeking)));
-  return seeking;
+  return seeking.forget();
 }
 
 HRESULT
 AudioSinkInputPin::BeginFlush()
 {
   HRESULT hr = media::BaseInputPin::BeginFlush();
   NS_ENSURE_TRUE(SUCCEEDED(hr), hr);
 
--- a/dom/media/directshow/DirectShowUtils.cpp
+++ b/dom/media/directshow/DirectShowUtils.cpp
@@ -293,17 +293,17 @@ GetUnconnectedPin(IBaseFilter* aFilter, 
   NS_ENSURE_TRUE(SUCCEEDED(hr), nullptr);
 
   // Test each pin to see if it matches the direction we're looking for.
   RefPtr<IPin> pin;
   while (S_OK == enumPins->Next(1, byRef(pin), nullptr)) {
     bool matches = FALSE;
     if (SUCCEEDED(MatchUnconnectedPin(pin, aPinDir, &matches)) &&
         matches) {
-      return pin;
+      return pin.forget();
     }
   }
 
   return nullptr;
 }
 
 HRESULT
 ConnectFilters(IGraphBuilder* aGraph,
--- a/dom/media/mediasource/TrackBuffer.cpp
+++ b/dom/media/mediasource/TrackBuffer.cpp
@@ -546,17 +546,17 @@ TrackBuffer::QueueInitializeDecoder(Sour
   // to aDecoder.
   static_assert(mozilla::IsBaseOf<nsISupports, SourceBufferDecoder>::value,
                 "SourceBufferDecoder must be inheriting from nsISupports");
   RefPtr<nsIRunnable> task =
     NS_NewRunnableMethodWithArg<SourceBufferDecoder*>(this,
                                                       &TrackBuffer::InitializeDecoder,
                                                       aDecoder);
   // We need to initialize the reader on its own task queue
-  aDecoder->GetReader()->GetTaskQueue()->Dispatch(task);
+  aDecoder->GetReader()->GetTaskQueue()->Dispatch(task.forget());
   return true;
 }
 
 // MetadataRecipient is a is used to pass extra values required by the
 // MetadataPromise's target methods
 class MetadataRecipient {
 public:
   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(MetadataRecipient);
@@ -1036,17 +1036,17 @@ TrackBuffer::RemoveDecoder(SourceBufferD
   {
     ReentrantMonitorAutoEnter mon(mParentDecoder->GetReentrantMonitor());
     // There should be no other references to the decoder. Assert that
     // we aren't using it in the MediaSourceReader.
     MOZ_ASSERT(!mParentDecoder->IsActiveReader(aDecoder->GetReader()));
     mInitializedDecoders.RemoveElement(aDecoder);
     mDecoders.RemoveElement(aDecoder);
   }
-  aDecoder->GetReader()->GetTaskQueue()->Dispatch(task);
+  aDecoder->GetReader()->GetTaskQueue()->Dispatch(task.forget());
 }
 
 bool
 TrackBuffer::RangeRemoval(media::TimeUnit aStart,
                           media::TimeUnit aEnd)
 {
   MOZ_ASSERT(NS_IsMainThread());
   ReentrantMonitorAutoEnter mon(mParentDecoder->GetReentrantMonitor());
--- a/dom/media/omx/MediaCodecReader.cpp
+++ b/dom/media/omx/MediaCodecReader.cpp
@@ -329,29 +329,29 @@ MediaCodecReader::Shutdown()
 
 void
 MediaCodecReader::DispatchAudioTask()
 {
   if (mAudioTrack.mTaskQueue) {
     RefPtr<nsIRunnable> task =
       NS_NewRunnableMethod(this,
                            &MediaCodecReader::DecodeAudioDataTask);
-    mAudioTrack.mTaskQueue->Dispatch(task);
+    mAudioTrack.mTaskQueue->Dispatch(task.forget());
   }
 }
 
 void
 MediaCodecReader::DispatchVideoTask(int64_t aTimeThreshold)
 {
   if (mVideoTrack.mTaskQueue) {
     RefPtr<nsIRunnable> task =
       NS_NewRunnableMethodWithArg<int64_t>(this,
                                            &MediaCodecReader::DecodeVideoFrameTask,
                                            aTimeThreshold);
-    mVideoTrack.mTaskQueue->Dispatch(task);
+    mVideoTrack.mTaskQueue->Dispatch(task.forget());
   }
 }
 
 nsRefPtr<MediaDecoderReader::AudioDataPromise>
 MediaCodecReader::RequestAudioData()
 {
   MOZ_ASSERT(GetTaskQueue()->IsCurrentThreadIn());
   MOZ_ASSERT(HasAudio());
@@ -792,17 +792,17 @@ MediaCodecReader::TextureClientRecycleCa
 
     mTextureClientIndexes.Remove(aClient);
   }
 
   if (mVideoTrack.mReleaseBufferTaskQueue->IsEmpty()) {
     RefPtr<nsIRunnable> task =
       NS_NewRunnableMethod(this,
                            &MediaCodecReader::WaitFenceAndReleaseOutputBuffer);
-    mVideoTrack.mReleaseBufferTaskQueue->Dispatch(task);
+    mVideoTrack.mReleaseBufferTaskQueue->Dispatch(task.forget());
   }
 }
 
 void
 MediaCodecReader::WaitFenceAndReleaseOutputBuffer()
 {
   nsTArray<ReleaseItem> releasingItems;
   {
@@ -1926,13 +1926,13 @@ MediaCodecReader::VideoCodecReserved()
 
 // Called on Binder thread.
 void
 MediaCodecReader::VideoCodecCanceled()
 {
   if (mVideoTrack.mTaskQueue) {
     RefPtr<nsIRunnable> task =
       NS_NewRunnableMethod(this, &MediaCodecReader::ReleaseCriticalResources);
-    mVideoTrack.mTaskQueue->Dispatch(task);
+    mVideoTrack.mTaskQueue->Dispatch(task.forget());
   }
 }
 
 } // namespace mozilla
--- a/dom/media/omx/MediaOmxCommonDecoder.cpp
+++ b/dom/media/omx/MediaOmxCommonDecoder.cpp
@@ -114,17 +114,17 @@ MediaOmxCommonDecoder::PauseStateMachine
     return;
   }
   // enter dormant state
   RefPtr<nsRunnable> event =
     NS_NewRunnableMethodWithArg<bool>(
       GetStateMachine(),
       &MediaDecoderStateMachine::SetDormant,
       true);
-  GetStateMachine()->TaskQueue()->Dispatch(event);
+  GetStateMachine()->TaskQueue()->Dispatch(event.forget());
 }
 
 void
 MediaOmxCommonDecoder::ResumeStateMachine()
 {
   MOZ_ASSERT(NS_IsMainThread());
   ReentrantMonitorAutoEnter mon(GetReentrantMonitor());
   DECODER_LOG(PR_LOG_DEBUG, ("%s current time %f", __PRETTY_FUNCTION__, mLogicalPosition));
@@ -143,27 +143,27 @@ MediaOmxCommonDecoder::ResumeStateMachin
                                  SeekTarget::Accurate,
                                  MediaDecoderEventVisibility::Suppressed);
   // Call Seek of MediaDecoderStateMachine to suppress seek events.
   RefPtr<nsRunnable> event =
     NS_NewRunnableMethodWithArg<SeekTarget>(
       GetStateMachine(),
       &MediaDecoderStateMachine::Seek,
       target);
-  GetStateMachine()->TaskQueue()->Dispatch(event);
+  GetStateMachine()->TaskQueue()->Dispatch(event.forget());
 
   mNextState = mPlayState;
   ChangeState(PLAY_STATE_LOADING);
   // exit dormant state
   event =
     NS_NewRunnableMethodWithArg<bool>(
       GetStateMachine(),
       &MediaDecoderStateMachine::SetDormant,
       false);
-  GetStateMachine()->TaskQueue()->Dispatch(event);
+  GetStateMachine()->TaskQueue()->Dispatch(event.forget());
   UpdateLogicalPosition();
 }
 
 void
 MediaOmxCommonDecoder::AudioOffloadTearDown()
 {
   MOZ_ASSERT(NS_IsMainThread());
   DECODER_LOG(PR_LOG_DEBUG, ("%s", __PRETTY_FUNCTION__));
--- a/dom/media/platforms/agnostic/BlankDecoderModule.cpp
+++ b/dom/media/platforms/agnostic/BlankDecoderModule.cpp
@@ -64,17 +64,17 @@ public:
   };
 
   virtual nsresult Input(MediaRawData* aSample) override
   {
     // The MediaDataDecoder must delete the sample when we're finished
     // with it, so the OutputEvent stores it in an nsAutoPtr and deletes
     // it once it's run.
     RefPtr<nsIRunnable> r(new OutputEvent(aSample, mCallback, mCreator));
-    mTaskQueue->Dispatch(r);
+    mTaskQueue->Dispatch(r.forget());
     return NS_OK;
   }
 
   virtual nsresult Flush() override {
     mTaskQueue->Flush();
     return NS_OK;
   }
 
--- a/dom/media/platforms/wmf/MFTDecoder.cpp
+++ b/dom/media/platforms/wmf/MFTDecoder.cpp
@@ -69,17 +69,17 @@ MFTDecoder::SetMediaTypes(IMFMediaType* 
 }
 
 TemporaryRef<IMFAttributes>
 MFTDecoder::GetAttributes()
 {
   RefPtr<IMFAttributes> attr;
   HRESULT hr = mDecoder->GetAttributes(byRef(attr));
   NS_ENSURE_TRUE(SUCCEEDED(hr), nullptr);
-  return attr;
+  return attr.forget();
 }
 
 HRESULT
 MFTDecoder::SetDecoderOutputType(ConfigureOutputCallback aCallback, void* aData)
 {
   NS_ENSURE_TRUE(mDecoder != nullptr, E_POINTER);
 
   // Iterate the enumerate the output types, until we find one compatible
--- a/dom/media/webaudio/MediaBufferDecoder.cpp
+++ b/dom/media/webaudio/MediaBufferDecoder.cpp
@@ -502,17 +502,22 @@ AsyncDecodeWebAudio(const char* aContent
     new MediaDecodeTask(aContentType, aBuffer, aLength, aDecodeJob);
   if (!task->CreateReader()) {
     nsCOMPtr<nsIRunnable> event =
       new ReportResultTask(aDecodeJob,
                            &WebAudioDecodeJob::OnFailure,
                            WebAudioDecodeJob::UnknownError);
     NS_DispatchToMainThread(event);
   } else {
-    task->Reader()->GetTaskQueue()->Dispatch(task);
+    // If we did this without a temporary:
+    //   task->Reader()->GetTaskQueue()->Dispatch(task.forget())
+    // we might evaluate the task.forget() before calling Reader(). Enforce
+    // a non-crashy order-of-operations.
+    MediaTaskQueue* taskQueue = task->Reader()->GetTaskQueue();
+    taskQueue->Dispatch(task.forget());
   }
 }
 
 WebAudioDecodeJob::WebAudioDecodeJob(const nsACString& aContentType,
                                      AudioContext* aContext,
                                      Promise* aPromise,
                                      DecodeSuccessCallback* aSuccessCallback,
                                      DecodeErrorCallback* aFailureCallback)
--- a/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp
+++ b/dom/media/webaudio/blink/HRTFDatabaseLoader.cpp
@@ -51,25 +51,25 @@ TemporaryRef<HRTFDatabaseLoader> HRTFDat
     if (!s_loaderMap) {
         s_loaderMap = new nsTHashtable<LoaderByRateEntry>();
     }
 
     LoaderByRateEntry* entry = s_loaderMap->PutEntry(sampleRate);
     loader = entry->mLoader;
     if (loader) { // existing entry
         MOZ_ASSERT(sampleRate == loader->databaseSampleRate());
-        return loader;
+        return loader.forget();
     }
 
     loader = new HRTFDatabaseLoader(sampleRate);
     entry->mLoader = loader;
 
     loader->loadAsynchronously();
 
-    return loader;
+    return loader.forget();
 }
 
 HRTFDatabaseLoader::HRTFDatabaseLoader(float sampleRate)
     : m_refCnt(0)
     , m_threadLock("HRTFDatabaseLoader")
     , m_databaseLoaderThread(nullptr)
     , m_databaseSampleRate(sampleRate)
 {
--- a/dom/svg/nsSVGPathGeometryElement.cpp
+++ b/dom/svg/nsSVGPathGeometryElement.cpp
@@ -84,17 +84,18 @@ nsSVGPathGeometryElement::GetOrBuildPath
                       gfxPlatform::GetPlatform()->GetContentBackend();
 
   // Checking for and returning mCachedPath before checking the pref means
   // that the pref is only live on page reload (or app restart for SVG in
   // chrome). The benefit is that we avoid causing a CPU memory cache miss by
   // looking at the global variable that the pref's stored in.
   if (cacheable && mCachedPath) {
     if (aDrawTarget.GetBackendType() == mCachedPath->GetBackendType()) {
-      return mCachedPath;
+      RefPtr<Path> path(mCachedPath);
+      return path.forget();
     }
   }
   RefPtr<PathBuilder> builder = aDrawTarget.CreatePathBuilder(aFillRule);
   RefPtr<Path> path = BuildPath(builder);
   if (cacheable && NS_SVGPathCachingEnabled()) {
     mCachedPath = path;
   }
   return path.forget();
--- a/dom/system/gonk/MozMtpDatabase.cpp
+++ b/dom/system/gonk/MozMtpDatabase.cpp
@@ -159,17 +159,17 @@ MozMtpDatabase::GetEntry(MtpObjectHandle
 {
   MutexAutoLock lock(mMutex);
 
   RefPtr<DbEntry> entry;
 
   if (aHandle > 0 && aHandle < mDb.Length()) {
     entry = mDb[aHandle];
   }
-  return entry;
+  return entry.forget();
 }
 
 void
 MozMtpDatabase::RemoveEntry(MtpObjectHandle aHandle)
 {
   MutexAutoLock lock(mMutex);
   if (!IsValidHandle(aHandle)) {
     return;
--- a/dom/system/gonk/VolumeManager.cpp
+++ b/dom/system/gonk/VolumeManager.cpp
@@ -70,17 +70,18 @@ VolumeManager::NumVolumes()
   return sVolumeManager->mVolumeArray.Length();
 }
 
 //static
 TemporaryRef<Volume>
 VolumeManager::GetVolume(size_t aIndex)
 {
   MOZ_ASSERT(aIndex < NumVolumes());
-  return sVolumeManager->mVolumeArray[aIndex];
+  RefPtr<Volume> vol = sVolumeManager->mVolumeArray[aIndex];
+  return vol.forget();
 }
 
 //static
 VolumeManager::STATE
 VolumeManager::State()
 {
   return mState;
 }
@@ -130,34 +131,34 @@ VolumeManager::FindVolumeByName(const ns
   if (!sVolumeManager) {
     return nullptr;
   }
   VolumeArray::size_type  numVolumes = NumVolumes();
   VolumeArray::index_type volIndex;
   for (volIndex = 0; volIndex < numVolumes; volIndex++) {
     RefPtr<Volume> vol = GetVolume(volIndex);
     if (vol->Name().Equals(aName)) {
-      return vol;
+      return vol.forget();
     }
   }
   return nullptr;
 }
 
 //static
 TemporaryRef<Volume>
 VolumeManager::FindAddVolumeByName(const nsCSubstring& aName)
 {
   RefPtr<Volume> vol = FindVolumeByName(aName);
   if (vol) {
-    return vol;
+    return vol.forget();
   }
   // No volume found, create and add a new one.
   vol = new Volume(aName);
   sVolumeManager->mVolumeArray.AppendElement(vol);
-  return vol;
+  return vol.forget();
 }
 
 //static
 void VolumeManager::InitConfig()
 {
   MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop());
 
   // This function uses /system/etc/volume.cfg to add additional volumes
--- a/gfx/2d/DrawTarget.cpp
+++ b/gfx/2d/DrawTarget.cpp
@@ -16,17 +16,17 @@ DrawTarget::CreateCaptureDT(const IntSiz
 {
   RefPtr<DrawTargetCaptureImpl> dt = new DrawTargetCaptureImpl();
 
   if (!dt->Init(aSize, this)) {
     gfxWarning() << "Failed to initialize Capture DrawTarget!";
     return nullptr;
   }
 
-  return dt;
+  return dt.forget();
 }
 
 void
 DrawTarget::DrawCapturedDT(DrawTargetCapture *aCaptureDT,
                            const Matrix& aTransform)
 {
   if (aTransform.HasNonIntegerTranslation()) {
     gfxWarning() << "Non integer translations are not supported for DrawCaptureDT at this time!";
--- a/gfx/2d/DrawTargetCG.cpp
+++ b/gfx/2d/DrawTargetCG.cpp
@@ -192,17 +192,18 @@ DrawTargetCG::Snapshot()
   if (!mSnapshot) {
     if (GetContextType(mCg) == CG_CONTEXT_TYPE_IOSURFACE) {
       return MakeAndAddRef<SourceSurfaceCGIOSurfaceContext>(this);
     }
     Flush();
     mSnapshot = new SourceSurfaceCGBitmapContext(this);
   }
 
-  return mSnapshot;
+  RefPtr<SourceSurface> snapshot(mSnapshot);
+  return snapshot.forget();
 }
 
 TemporaryRef<DrawTarget>
 DrawTargetCG::CreateSimilarDrawTarget(const IntSize &aSize, SurfaceFormat aFormat) const
 {
   // XXX: in thebes we use CGLayers to do this kind of thing. It probably makes sense
   // to add that in somehow, but at a higher level
   RefPtr<DrawTargetCG> newTarget = new DrawTargetCG();
--- a/gfx/2d/DrawTargetCairo.cpp
+++ b/gfx/2d/DrawTargetCairo.cpp
@@ -653,26 +653,28 @@ DrawTargetCairo::GetSize()
 {
   return mSize;
 }
 
 TemporaryRef<SourceSurface>
 DrawTargetCairo::Snapshot()
 {
   if (mSnapshot) {
-    return mSnapshot;
+    RefPtr<SourceSurface> snapshot(mSnapshot);
+    return snapshot.forget();
   }
 
   IntSize size = GetSize();
 
   mSnapshot = new SourceSurfaceCairo(mSurface,
                                      size,
                                      GfxFormatForCairoSurface(mSurface),
                                      this);
-  return mSnapshot;
+  RefPtr<SourceSurface> snapshot(mSnapshot);
+  return snapshot.forget();
 }
 
 bool
 DrawTargetCairo::LockBits(uint8_t** aData, IntSize* aSize,
                           int32_t* aStride, SurfaceFormat* aFormat)
 {
   if (cairo_surface_get_type(mSurface) == CAIRO_SURFACE_TYPE_IMAGE) {
     WillChange();
--- a/gfx/2d/DrawTargetD2D.cpp
+++ b/gfx/2d/DrawTargetD2D.cpp
@@ -222,17 +222,18 @@ DrawTargetD2D::~DrawTargetD2D()
 TemporaryRef<SourceSurface>
 DrawTargetD2D::Snapshot()
 {
   if (!mSnapshot) {
     mSnapshot = new SourceSurfaceD2DTarget(this, mTexture, mFormat);
     Flush();
   }
 
-  return mSnapshot;
+  RefPtr<SourceSurface> snapshot(mSnapshot);
+  return snapshot.forget();
 }
 
 void
 DrawTargetD2D::Flush()
 {
   PopAllClips();
 
   HRESULT hr = mRT->Flush();
@@ -321,28 +322,28 @@ DrawTargetD2D::GetBitmapForSurface(Sourc
 
       // subtract the integer part leaving the fractional part
       aSource.x -= (uint32_t)aSource.x;
       aSource.y -= (uint32_t)aSource.y;
     }
     break;
   }
 
-  return bitmap;
+  return bitmap.forget();
 }
 
 TemporaryRef<ID2D1Image>
 DrawTargetD2D::GetImageForSurface(SourceSurface *aSurface)
 {
   RefPtr<ID2D1Image> image;
 
   Rect r(Point(), Size(aSurface->GetSize()));
   image = GetBitmapForSurface(aSurface, r);
 
-  return image;
+  return image.forget();
 }
 
 void
 DrawTargetD2D::DrawSurface(SourceSurface *aSurface,
                            const Rect &aDest,
                            const Rect &aSource,
                            const DrawSurfaceOptions &aSurfOptions,
                            const DrawOptions &aOptions)
@@ -1863,17 +1864,18 @@ DrawTargetD2D::GetDeviceSpaceClipRect(D2
   return true;
 }
 
 TemporaryRef<ID2D1Geometry>
 DrawTargetD2D::GetClippedGeometry(IntRect *aClipBounds)
 {
   if (mCurrentClippedGeometry) {
     *aClipBounds = mCurrentClipBounds;
-    return mCurrentClippedGeometry;
+    RefPtr<ID2D1Geometry> clippedGeometry(mCurrentClippedGeometry);
+    return clippedGeometry.forget();
   }
 
   mCurrentClipBounds = IntRect(IntPoint(0, 0), mSize);
 
   // if pathGeom is null then pathRect represents the path.
   RefPtr<ID2D1Geometry> pathGeom;
   D2D1_RECT_F pathRect;
   bool pathRectIsAxisAligned = false;
@@ -1942,17 +1944,18 @@ DrawTargetD2D::GetClippedGeometry(IntRec
   // method might seem a little strange but it is just fine, if pathGeom is
   // nullptr pathRect will always still contain 1 clip unaccounted for
   // regardless of mCurrentClipBounds.
   if (!pathGeom) {
     pathGeom = ConvertRectToGeometry(pathRect);
   }
   mCurrentClippedGeometry = pathGeom.forget();
   *aClipBounds = mCurrentClipBounds;
-  return mCurrentClippedGeometry;
+  RefPtr<ID2D1Geometry> clippedGeometry(mCurrentClippedGeometry);
+  return clippedGeometry.forget();
 }
 
 TemporaryRef<ID2D1RenderTarget>
 DrawTargetD2D::CreateRTForTexture(ID3D10Texture2D *aTexture, SurfaceFormat aFormat)
 {
   HRESULT hr;
 
   RefPtr<IDXGISurface> surface;
--- a/gfx/2d/DrawTargetD2D1.cpp
+++ b/gfx/2d/DrawTargetD2D1.cpp
@@ -64,25 +64,27 @@ DrawTargetD2D1::~DrawTargetD2D1()
     (*iter)->mDependentTargets.erase(this);
   }
 }
 
 TemporaryRef<SourceSurface>
 DrawTargetD2D1::Snapshot()
 {
   if (mSnapshot) {
-    return mSnapshot;
+    RefPtr<SourceSurface> snapshot(mSnapshot);
+    return snapshot.forget();
   }
   PopAllClips();
 
   mDC->Flush();
 
   mSnapshot = new SourceSurfaceD2D1(mBitmap, mDC, mFormat, mSize, this);
 
-  return mSnapshot;
+  RefPtr<SourceSurface> snapshot(mSnapshot);
+  return snapshot.forget();
 }
 
 void
 DrawTargetD2D1::Flush()
 {
   mDC->Flush();
 
   // We no longer depend on any target.
@@ -1129,17 +1131,18 @@ DrawTargetD2D1::GetDeviceSpaceClipRect(D
   return true;
 }
 
 TemporaryRef<ID2D1Geometry>
 DrawTargetD2D1::GetClippedGeometry(IntRect *aClipBounds)
 {
   if (mCurrentClippedGeometry) {
     *aClipBounds = mCurrentClipBounds;
-    return mCurrentClippedGeometry;
+    RefPtr<ID2D1Geometry> clippedGeometry(mCurrentClippedGeometry);
+    return clippedGeometry.forget();
   }
 
   MOZ_ASSERT(mPushedClips.size());
 
   mCurrentClipBounds = IntRect(IntPoint(0, 0), mSize);
 
   // if pathGeom is null then pathRect represents the path.
   RefPtr<ID2D1Geometry> pathGeom;
@@ -1210,17 +1213,18 @@ DrawTargetD2D1::GetClippedGeometry(IntRe
   // method might seem a little strange but it is just fine, if pathGeom is
   // nullptr pathRect will always still contain 1 clip unaccounted for
   // regardless of mCurrentClipBounds.
   if (!pathGeom) {
     pathGeom = ConvertRectToGeometry(pathRect);
   }
   mCurrentClippedGeometry = pathGeom.forget();
   *aClipBounds = mCurrentClipBounds;
-  return mCurrentClippedGeometry;
+  RefPtr<ID2D1Geometry> clippedGeometry(mCurrentClippedGeometry);
+  return clippedGeometry.forget();
 }
 
 TemporaryRef<ID2D1Geometry>
 DrawTargetD2D1::GetInverseClippedGeometry()
 {
   IntRect bounds;
   RefPtr<ID2D1Geometry> geom = GetClippedGeometry(&bounds);
   RefPtr<ID2D1RectangleGeometry> rectGeom;
@@ -1228,17 +1232,17 @@ DrawTargetD2D1::GetInverseClippedGeometr
 
   factory()->CreateRectangleGeometry(D2D1::RectF(0, 0, mSize.width, mSize.height), byRef(rectGeom));
   factory()->CreatePathGeometry(byRef(inverseGeom));
   RefPtr<ID2D1GeometrySink> sink;
   inverseGeom->Open(byRef(sink));
   rectGeom->CombineWithGeometry(geom, D2D1_COMBINE_MODE_EXCLUDE, D2D1::IdentityMatrix(), sink);
   sink->Close();
 
-  return inverseGeom;
+  return inverseGeom.forget();
 }
 
 void
 DrawTargetD2D1::PopAllClips()
 {
   if (mClipsArePushed) {
     PopClipsFromDC(mDC);
   
@@ -1290,17 +1294,17 @@ DrawTargetD2D1::CreateTransparentBlackBr
   return GetSolidColorBrush(D2D1::ColorF(0, 0));
 }
 
 TemporaryRef<ID2D1SolidColorBrush>
 DrawTargetD2D1::GetSolidColorBrush(const D2D_COLOR_F& aColor)
 {
   RefPtr<ID2D1SolidColorBrush> brush = mSolidColorBrush;
   brush->SetColor(aColor);
-  return brush;
+  return brush.forget();
 }
 
 TemporaryRef<ID2D1Brush>
 DrawTargetD2D1::CreateBrushForPattern(const Pattern &aPattern, Float aAlpha)
 {
   if (!IsPatternSupportedByD2D(aPattern)) {
     return GetSolidColorBrush(D2D1::ColorF(1.0f, 1.0f, 1.0f, 1.0f));
   }
--- a/gfx/2d/Factory.cpp
+++ b/gfx/2d/Factory.cpp
@@ -647,17 +647,17 @@ Factory::CreateDrawTargetForD3D11Texture
   newTarget = new DrawTargetD2D1();
   if (newTarget->Init(aTexture, aFormat)) {
     RefPtr<DrawTarget> retVal = newTarget;
 
     if (mRecorder) {
       retVal = new DrawTargetRecording(mRecorder, retVal, true);
     }
 
-    return retVal;
+    return retVal.forget();
   }
 
   gfxWarning() << "Failed to create draw target for D3D11 texture.";
 
   // Failed
   return nullptr;
 }
 
--- a/gfx/2d/FilterProcessingSIMD-inl.h
+++ b/gfx/2d/FilterProcessingSIMD-inl.h
@@ -90,17 +90,17 @@ ConvertToB8G8R8A8_SIMD(SourceSurface* aS
           }
         }
       }
       break;
     default:
       output = nullptr;
       break;
   }
-  return output;
+  return output.forget();
 }
 
 template<typename u8x16_t>
 inline void
 ExtractAlpha_SIMD(const IntSize& size, uint8_t* sourceData, int32_t sourceStride, uint8_t* alphaData, int32_t alphaStride)
 {
   for (int32_t y = 0; y < size.height; y++) {
     for (int32_t x = 0; x < size.width; x += 16) {
@@ -329,17 +329,17 @@ ApplyBlending_SIMD(DataSourceSurface* aI
       // Throw away blendedA and overwrite it with the correct blended alpha.
       blendedA = BlendAlphaOfFourPixels<i16x8_t,i32x4_t>(s_rrrraaaa1234, d_rrrraaaa1234);
 
       u8x16_t result1234 = ShuffleAndPackComponents<i32x4_t,i16x8_t,u8x16_t>(blendedB, blendedG, blendedR, blendedA);
       simd::Store8(&targetData[targetIndex], result1234);
     }
   }
 
-  return target;
+  return target.forget();
 }
 
 template<typename i32x4_t, typename i16x8_t, typename u8x16_t>
 static TemporaryRef<DataSourceSurface>
 ApplyBlending_SIMD(DataSourceSurface* aInput1, DataSourceSurface* aInput2,
                       BlendMode aBlendMode)
 {
   switch (aBlendMode) {
@@ -603,17 +603,17 @@ ApplyColorMatrix_SIMD(DataSourceSurface*
       u8x16_t result_p1234 = simd::PackAndSaturate32To8(simd::ShiftRight32<7>(result_p1),
                                                         simd::ShiftRight32<7>(result_p2),
                                                         simd::ShiftRight32<7>(result_p3),
                                                         simd::ShiftRight32<7>(result_p4));
       simd::Store8(&targetData[targetIndex], result_p1234);
     }
   }
 
-  return target;
+  return target.forget();
 }
 
 // source / dest: bgra bgra
 // sourceAlpha / destAlpha: aaaa aaaa
 // result: bgra bgra
 template<typename i32x4_t, typename u16x8_t, uint32_t aCompositeOperator>
 static inline u16x8_t
 CompositeTwoPixels(u16x8_t source, u16x8_t sourceAlpha, u16x8_t dest, const u16x8_t& destAlpha)
@@ -1069,13 +1069,13 @@ ApplyArithmeticCombine_SIMD(DataSourceSu
       i16x8_t result_12 = ArithmeticCombineTwoPixels<i32x4_t,i16x8_t>(in1_12, in2_12, k1And4, k2And3);
       i16x8_t result_34 = ArithmeticCombineTwoPixels<i32x4_t,i16x8_t>(in1_34, in2_34, k1And4, k2And3);
 
       // Pack and store.
       simd::Store8(&targetData[targetIndex], simd::PackAndSaturate16To8(result_12, result_34));
     }
   }
 
-  return target;
+  return target.forget();
 }
 
 } // namespace mozilla
 } // namespace gfx
--- a/gfx/2d/SVGTurbulenceRenderer-inl.h
+++ b/gfx/2d/SVGTurbulenceRenderer-inl.h
@@ -348,13 +348,13 @@ SVGTurbulenceRenderer<Type,Stitch,f32x4_
       i32x4_t b = Turbulence(startOffset + Point(x + 1, y));
       i32x4_t c = Turbulence(startOffset + Point(x + 2, y));
       i32x4_t d = Turbulence(startOffset + Point(x + 3, y));
       u8x16_t result1234 = simd::PackAndSaturate32To8(a, b, c, d);
       simd::Store8(&targetData[targIndex], result1234);
     }
   }
 
-  return target;
+  return target.forget();
 }
 
 } // namespace gfx
 } // namespace mozilla
--- a/gfx/layers/D3D9SurfaceImage.cpp
+++ b/gfx/layers/D3D9SurfaceImage.cpp
@@ -264,13 +264,13 @@ D3D9SurfaceImage::GetAsSourceSurface()
     memcpy(mappedSurface.mData + mappedSurface.mStride * y,
            (unsigned char*)(src) + srcPitch * y,
            mSize.width * 4);
   }
 
   systemMemorySurface->UnlockRect();
   surface->Unmap();
 
-  return surface;
+  return surface.forget();
 }
 
 } /* layers */
 } /* mozilla */
--- a/gfx/layers/Effects.h
+++ b/gfx/layers/Effects.h
@@ -263,17 +263,17 @@ CreateTexturedEffect(gfx::SurfaceFormat 
   case gfx::SurfaceFormat::YUV:
     result = new EffectYCbCr(aSource, aFilter);
     break;
   default:
     NS_WARNING("unhandled program type");
     break;
   }
 
-  return result;
+  return result.forget();
 }
 
 /**
  * Create a textured effect based on aSource format and the presence of
  * aSourceOnWhite.
  *
  * aSourceOnWhite can be null.
  */
--- a/gfx/layers/GrallocImages.cpp
+++ b/gfx/layers/GrallocImages.cpp
@@ -402,27 +402,27 @@ GrallocImage::GetAsSourceSurface()
     NS_WARNING("Could not map DataSourceSurface");
     return nullptr;
   }
 
   int32_t rv;
   rv = ConvertOmxYUVFormatToRGB565(graphicBuffer, surface, &mappedSurface, mData);
   if (rv == OK) {
     surface->Unmap();
-    return surface;
+    return surface.forget();
   }
 
   rv = ConvertVendorYUVFormatToRGB565(graphicBuffer, surface, &mappedSurface);
   surface->Unmap();
   if (rv != OK) {
     NS_WARNING("Unknown color format");
     return nullptr;
   }
 
-  return surface;
+  return surface.forget();
 }
 
 android::sp<android::GraphicBuffer>
 GrallocImage::GetGraphicBuffer() const
 {
   if (!mTextureClient) {
     return nullptr;
   }
--- a/gfx/layers/IMFYCbCrImage.cpp
+++ b/gfx/layers/IMFYCbCrImage.cpp
@@ -90,17 +90,17 @@ InitTextures(IDirect3DDevice9* aDevice,
 
   tmpTexture->GetSurfaceLevel(0, byRef(aSurface));
   aSurface->LockRect(&aLockedRect, nullptr, 0);
   if (!aLockedRect.pBits) {
     NS_WARNING("Could not lock surface");
     return nullptr;
   }
 
-  return result;
+  return result.forget();
 }
 
 static void
 FinishTextures(IDirect3DDevice9* aDevice,
                IDirect3DTexture9* aTexture,
                IDirect3DSurface9* aSurface)
 {
   if (!aDevice) {
--- a/gfx/layers/MacIOSurfaceImage.cpp
+++ b/gfx/layers/MacIOSurfaceImage.cpp
@@ -46,10 +46,10 @@ MacIOSurfaceImage::GetAsSourceSurface()
     memcpy(mappedSurface.mData + i * mappedSurface.mStride,
            ioData + i * bytesPerRow,
            ioWidth * 4);
   }
 
   dataSurface->Unmap();
   mSurface->Unlock();
 
-  return dataSurface;
+  return dataSurface.forget();
 }
--- a/gfx/layers/RotatedBuffer.cpp
+++ b/gfx/layers/RotatedBuffer.cpp
@@ -186,17 +186,17 @@ SourceRotatedBuffer::GetSourceSurface(Co
   if (aSource == BUFFER_BLACK) {
     surf = mSource;
   } else {
     MOZ_ASSERT(aSource == BUFFER_WHITE);
     surf = mSourceOnWhite;
   }
 
   MOZ_ASSERT(surf);
-  return surf;
+  return surf.forget();
 }
 
 /* static */ bool
 RotatedContentBuffer::IsClippingCheap(DrawTarget* aTarget, const nsIntRegion& aRegion)
 {
   // Assume clipping is cheap if the draw target just has an integer
   // translation, and the visible region is simple.
   return !aTarget->GetTransform().HasNonIntegerTranslation() &&
--- a/gfx/layers/TextureDIB.cpp
+++ b/gfx/layers/TextureDIB.cpp
@@ -33,17 +33,17 @@ DIBTextureClient::CreateSimilar(TextureF
 {
   RefPtr<TextureClient> tex = new DIBTextureClient(mAllocator, mFormat,
                                                    mFlags | aFlags);
 
   if (!tex->AllocateForSurface(mSize, aAllocFlags)) {
     return nullptr;
   }
 
-  return tex;
+  return tex.forget();
 }
 
 bool
 DIBTextureClient::Lock(OpenMode)
 {
   MOZ_ASSERT(!mIsLocked);
   if (!IsValid()) {
     return false;
@@ -189,9 +189,9 @@ void
 DIBTextureHost::DeallocateDeviceData()
 {
   if (mTextureSource) {
     mTextureSource->DeallocateDeviceData();
   }
 }
 
 }
-}
\ No newline at end of file
+}
--- a/gfx/layers/basic/TextureClientX11.cpp
+++ b/gfx/layers/basic/TextureClientX11.cpp
@@ -41,17 +41,17 @@ TextureClientX11::CreateSimilar(TextureF
   RefPtr<TextureClient> tex = new TextureClientX11(mAllocator, mFormat, mFlags);
 
   // mSize is guaranteed to be non-negative
   MOZ_ASSERT(mSize.width >= 0 && mSize.height >= 0);
   if (!tex->AllocateForSurface(mSize, aAllocFlags)) {
     return nullptr;
   }
 
-  return tex;
+  return tex.forget();
 }
 
 bool
 TextureClientX11::IsAllocated() const
 {
   return !!mSurface;
 }
 
--- a/gfx/layers/basic/TextureHostBasic.cpp
+++ b/gfx/layers/basic/TextureHostBasic.cpp
@@ -18,17 +18,16 @@ TemporaryRef<TextureHost>
 CreateTextureHostBasic(const SurfaceDescriptor& aDesc,
                        ISurfaceAllocator* aDeallocator,
                        TextureFlags aFlags)
 {
 #ifdef XP_MACOSX
   if (aDesc.type() == SurfaceDescriptor::TSurfaceDescriptorMacIOSurface) {
     const SurfaceDescriptorMacIOSurface& desc =
       aDesc.get_SurfaceDescriptorMacIOSurface();
-    RefPtr<TextureHost> result = new MacIOSurfaceTextureHostBasic(aFlags, desc);
-    return result;
+    return MakeAndAddRef<MacIOSurfaceTextureHostBasic>(aFlags, desc);
   }
 #endif
   return CreateBackendIndependentTextureHost(aDesc, aDeallocator, aFlags);
 }
 
 } // namespace layers
 } // namespace gfx
--- a/gfx/layers/client/ImageClient.cpp
+++ b/gfx/layers/client/ImageClient.cpp
@@ -115,18 +115,17 @@ ImageClientSingle::ImageClientSingle(Com
 TextureInfo ImageClientSingle::GetTextureInfo() const
 {
   return TextureInfo(CompositableType::IMAGE);
 }
 
 TemporaryRef<AsyncTransactionTracker>
 ImageClientSingle::PrepareFlushAllImages()
 {
-  RefPtr<AsyncTransactionTracker> status = new RemoveTextureFromCompositableTracker();
-  return status;
+  return MakeAndAddRef<RemoveTextureFromCompositableTracker>();
 }
 
 void
 ImageClientSingle::FlushAllImages(bool aExceptFront,
                                   AsyncTransactionTracker* aAsyncTransactionTracker)
 {
   if (!aExceptFront && mFrontBuffer) {
     RemoveTextureWithTracker(mFrontBuffer, aAsyncTransactionTracker);
--- a/gfx/layers/client/TextureClient.cpp
+++ b/gfx/layers/client/TextureClient.cpp
@@ -400,17 +400,17 @@ TextureClient::CreateForDrawing(ISurface
                                            aTextureFlags);
     }
   }
 #endif
 
   MOZ_ASSERT(!texture || texture->CanExposeDrawTarget(), "texture cannot expose a DrawTarget?");
 
   if (texture && texture->AllocateForSurface(aSize, aAllocFlags)) {
-    return texture;
+    return texture.forget();
   }
 
   if (aAllocFlags & ALLOC_DISALLOW_BUFFERTEXTURECLIENT) {
     return nullptr;
   }
 
   if (texture) {
     NS_WARNING("Failed to allocate a TextureClient, falling back to BufferTextureClient.");
@@ -418,17 +418,17 @@ TextureClient::CreateForDrawing(ISurface
 
   // Can't do any better than a buffer texture client.
   texture = CreateBufferTextureClient(aAllocator, aFormat, aTextureFlags, aMoz2DBackend);
 
   if (!texture->AllocateForSurface(aSize, aAllocFlags)) {
     return nullptr;
   }
 
-  return texture;
+  return texture.forget();
 }
 
 // static
 TemporaryRef<BufferTextureClient>
 TextureClient::CreateForRawBufferAccess(ISurfaceAllocator* aAllocator,
                                         gfx::SurfaceFormat aFormat,
                                         gfx::IntSize aSize,
                                         gfx::BackendType aMoz2DBackend,
@@ -438,17 +438,17 @@ TextureClient::CreateForRawBufferAccess(
   RefPtr<BufferTextureClient> texture =
     CreateBufferTextureClient(aAllocator, aFormat,
                               aTextureFlags, aMoz2DBackend);
   if (texture) {
     if (!texture->AllocateForSurface(aSize, aAllocFlags)) {
       return nullptr;
     }
   }
-  return texture;
+  return texture.forget();
 }
 
 // static
 TemporaryRef<BufferTextureClient>
 TextureClient::CreateForYCbCr(ISurfaceAllocator* aAllocator,
                               gfx::IntSize aYSize,
                               gfx::IntSize aCbCrSize,
                               StereoMode aStereoMode,
@@ -464,17 +464,17 @@ TextureClient::CreateForYCbCr(ISurfaceAl
                                      gfx::BackendType::NONE,
                                      aTextureFlags);
   }
 
   if (!texture->AllocateForYCbCr(aYSize, aCbCrSize, aStereoMode)) {
     return nullptr;
   }
 
-  return texture;
+  return texture.forget();
 }
 
 // static
 TemporaryRef<BufferTextureClient>
 TextureClient::CreateWithBufferSize(ISurfaceAllocator* aAllocator,
                      gfx::SurfaceFormat aFormat,
                      size_t aSize,
                      TextureFlags aTextureFlags)
@@ -489,17 +489,17 @@ TextureClient::CreateWithBufferSize(ISur
                                      gfx::BackendType::NONE,
                                      aTextureFlags);
   }
 
   if (!texture->Allocate(aSize)) {
     return nullptr;
   }
 
-  return texture;
+  return texture.forget();
 }
 
 TextureClient::TextureClient(ISurfaceAllocator* aAllocator, TextureFlags aFlags)
   : mAllocator(aAllocator)
   , mFlags(aFlags)
   , mShared(false)
   , mValid(true)
   , mAddedToCompositableClient(false)
@@ -754,18 +754,17 @@ TemporaryRef<TextureClient>
 BufferTextureClient::CreateSimilar(TextureFlags aFlags,
                                    TextureAllocationFlags aAllocFlags) const
 {
   // This may return null
   RefPtr<BufferTextureClient> newBufferTex = TextureClient::CreateForRawBufferAccess(
     mAllocator, mFormat, mSize, mBackend, mFlags | aFlags, aAllocFlags
   );
 
-  RefPtr<TextureClient> newTex = newBufferTex.get();
-  return newTex;
+  return newBufferTex.forget();
 }
 
 bool
 BufferTextureClient::AllocateForSurface(gfx::IntSize aSize, TextureAllocationFlags aFlags)
 {
   MOZ_ASSERT(IsValid());
   MOZ_ASSERT(mFormat != gfx::SurfaceFormat::YUV, "This textureClient cannot use YCbCr data");
   MOZ_ASSERT(aSize.width > 0 && aSize.height > 0);
@@ -942,18 +941,17 @@ SharedSurfaceTextureClient::ToSurfaceDes
 TemporaryRef<SyncObject>
 SyncObject::CreateSyncObject(SyncHandle aHandle)
 {
   if (!aHandle) {
     return nullptr;
   }
 
 #ifdef XP_WIN
-  RefPtr<SyncObject> syncObject = new SyncObjectD3D11(aHandle);
-  return syncObject;
+  return MakeAndAddRef<SyncObjectD3D11>(aHandle);
 #else
   MOZ_ASSERT_UNREACHABLE();
   return nullptr;
 #endif
 }
 
 }
 }
--- a/gfx/layers/client/TextureClient.h
+++ b/gfx/layers/client/TextureClient.h
@@ -283,17 +283,17 @@ public:
    * This method is strictly for debugging. It causes locking and
    * needless copies.
    */
   virtual TemporaryRef<gfx::DataSourceSurface> GetAsSurface() {
     Lock(OpenMode::OPEN_READ);
     RefPtr<gfx::SourceSurface> surf = BorrowDrawTarget()->Snapshot();
     RefPtr<gfx::DataSourceSurface> data = surf->GetDataSurface();
     Unlock();
-    return data;
+    return data.forget();
   }
 
   virtual void PrintInfo(std::stringstream& aStream, const char* aPrefix);
 
   /**
    * Copies a rectangle from this texture client to a position in aTarget.
    * It is assumed that the necessary locks are in place; so this should at
    * least have a read lock and aTarget should at least have a write lock.
--- a/gfx/layers/client/TextureClientPool.cpp
+++ b/gfx/layers/client/TextureClientPool.cpp
@@ -91,17 +91,17 @@ TextureClientPool::GetTextureClient()
     textureClient = mTextureClients.top();
     mTextureClients.pop();
 #ifdef GFX_DEBUG_TRACK_CLIENTS_IN_POOL
     DebugOnly<bool> ok = TestClientPool("fetch", textureClient, this);
     MOZ_ASSERT(ok);
 #endif
     TCP_LOG("TexturePool %p giving %p from pool; size %u outstanding %u\n",
         this, textureClient.get(), mTextureClients.size(), mOutstandingClients);
-    return textureClient;
+    return textureClient.forget();
   }
 
   // We're increasing the number of outstanding TextureClients without reusing a
   // client, we may need to free a deferred-return TextureClient.
   ShrinkToMaximumSize();
 
   // No unused clients in the pool, create one
   if (gfxPrefs::ForceShmemTiles()) {
@@ -117,17 +117,17 @@ TextureClientPool::GetTextureClient()
   mOutstandingClients++;
 #ifdef GFX_DEBUG_TRACK_CLIENTS_IN_POOL
   if (textureClient) {
     textureClient->mPoolTracker = this;
   }
 #endif
   TCP_LOG("TexturePool %p giving new %p; size %u outstanding %u\n",
       this, textureClient.get(), mTextureClients.size(), mOutstandingClients);
-  return textureClient;
+  return textureClient.forget();
 }
 
 void
 TextureClientPool::ReturnTextureClient(TextureClient *aClient)
 {
   if (!aClient) {
     return;
   }
--- a/gfx/layers/composite/CompositableHost.cpp
+++ b/gfx/layers/composite/CompositableHost.cpp
@@ -201,17 +201,17 @@ CompositableHost::Create(const TextureIn
     result = new ContentHostSingleBuffered(aTextureInfo);
     break;
   case CompositableType::CONTENT_DOUBLE:
     result = new ContentHostDoubleBuffered(aTextureInfo);
     break;
   default:
     NS_ERROR("Unknown CompositableType");
   }
-  return result;
+  return result.forget();
 }
 
 void
 CompositableHost::DumpTextureHost(std::stringstream& aStream, TextureHost* aTexture)
 {
   if (!aTexture) {
     return;
   }
--- a/gfx/layers/composite/TextureHost.cpp
+++ b/gfx/layers/composite/TextureHost.cpp
@@ -195,18 +195,17 @@ TextureHost::Create(const SurfaceDescrip
         return CreateTextureHostOGL(aDesc, aDeallocator, aFlags);
       } else {
         return CreateTextureHostBasic(aDesc, aDeallocator, aFlags);
       }
 
 #ifdef MOZ_X11
     case SurfaceDescriptor::TSurfaceDescriptorX11: {
       const SurfaceDescriptorX11& desc = aDesc.get_SurfaceDescriptorX11();
-      RefPtr<TextureHost> result = new X11TextureHost(aFlags, desc);
-      return result;
+      return MakeAndAddRef<X11TextureHost>(aFlags, desc);
     }
 #endif
 
 #ifdef XP_WIN
     case SurfaceDescriptor::TSurfaceDescriptorD3D9:
       return CreateTextureHostD3D9(aDesc, aDeallocator, aFlags);
 
     case SurfaceDescriptor::TSurfaceDescriptorD3D10:
@@ -249,17 +248,17 @@ CreateBackendIndependentTextureHost(cons
       result = new DIBTextureHost(aFlags, aDesc);
       break;
     }
 #endif
     default: {
       NS_WARNING("No backend independent TextureHost for this descriptor type");
     }
   }
-  return result;
+  return result.forget();
 }
 
 void
 TextureHost::CompositorRecycle()
 {
   if (!mActor) {
     return;
   }
--- a/gfx/layers/d3d11/CompositorD3D11.cpp
+++ b/gfx/layers/d3d11/CompositorD3D11.cpp
@@ -460,17 +460,17 @@ CompositorD3D11::CreateRenderTarget(cons
   RefPtr<CompositingRenderTargetD3D11> rt = new CompositingRenderTargetD3D11(texture, aRect.TopLeft());
   rt->SetSize(IntSize(aRect.width, aRect.height));
 
   if (aInit == INIT_MODE_CLEAR) {
     FLOAT clear[] = { 0, 0, 0, 0 };
     mContext->ClearRenderTargetView(rt->mRTView, clear);
   }
 
-  return rt;
+  return rt.forget();
 }
 
 TemporaryRef<CompositingRenderTarget>
 CompositorD3D11::CreateRenderTargetFromSource(const gfx::IntRect &aRect,
                                               const CompositingRenderTarget* aSource,
                                               const gfx::IntPoint &aSourcePoint)
 {
   MOZ_ASSERT(aRect.width != 0 && aRect.height != 0);
@@ -519,17 +519,17 @@ CompositorD3D11::CreateRenderTargetFromS
       NS_WARNING("Could not copy render target - source rect out of bounds");
     }
   }
 
   RefPtr<CompositingRenderTargetD3D11> rt =
     new CompositingRenderTargetD3D11(texture, aRect.TopLeft());
   rt->SetSize(aRect.Size());
 
-  return rt;
+  return rt.forget();
 }
 
 void
 CompositorD3D11::SetRenderTarget(CompositingRenderTarget* aRenderTarget)
 {
   MOZ_ASSERT(aRenderTarget);
   CompositingRenderTargetD3D11* newRT =
     static_cast<CompositingRenderTargetD3D11*>(aRenderTarget);
--- a/gfx/layers/d3d11/TextureD3D11.cpp
+++ b/gfx/layers/d3d11/TextureD3D11.cpp
@@ -162,17 +162,17 @@ CreateTextureHostD3D11(const SurfaceDesc
       result = new DXGIYCbCrTextureHostD3D11(aFlags,
                                              aDesc.get_SurfaceDescriptorDXGIYCbCr());
       break;
     }
     default: {
       NS_WARNING("Unsupported SurfaceDescriptor type");
     }
   }
-  return result;
+  return result.forget();
 }
 
 TextureClientD3D11::TextureClientD3D11(ISurfaceAllocator* aAllocator,
                                        gfx::SurfaceFormat aFormat,
                                        TextureFlags aFlags)
   : TextureClient(aAllocator, aFlags)
   , mFormat(aFormat)
   , mIsLocked(false)
@@ -220,31 +220,31 @@ TextureClientD3D11::Create(ISurfaceAlloc
                            ID3D11Texture2D* aTexture,
                            gfx::IntSize aSize)
 {
   RefPtr<TextureClientD3D11> texture = new TextureClientD3D11(aAllocator,
                                                              aFormat,
                                                              aFlags);
   texture->mTexture = aTexture;
   texture->mSize = aSize;
-  return texture;
+  return texture.forget();
 }
 
 TemporaryRef<TextureClient>
 TextureClientD3D11::CreateSimilar(TextureFlags aFlags,
                                   TextureAllocationFlags aAllocFlags) const
 {
   RefPtr<TextureClient> tex = new TextureClientD3D11(mAllocator, mFormat,
                                                      mFlags | aFlags);
 
   if (!tex->AllocateForSurface(mSize, aAllocFlags)) {
     return nullptr;
   }
 
-  return tex;
+  return tex.forget();
 }
 
 void
 TextureClientD3D11::SyncWithObject(SyncObject* aSyncObject)
 {
   if (!aSyncObject) {
     return;
   }
@@ -570,17 +570,17 @@ DXGIYCbCrTextureClient::Create(ISurfaceA
   texture->mHandles[1] = aHandleCb;
   texture->mHandles[2] = aHandleCr;
   texture->mHoldRefs[0] = aTextureY;
   texture->mHoldRefs[1] = aTextureCb;
   texture->mHoldRefs[2] = aTextureCr;
   texture->mSize = aSize;
   texture->mSizeY = aSizeY;
   texture->mSizeCbCr = aSizeCbCr;
-  return texture;
+  return texture.forget();
 }
 
 bool
 DXGIYCbCrTextureClient::Lock(OpenMode)
 {
   MOZ_ASSERT(!mIsLocked);
   if (!IsValid()) {
     return false;
--- a/gfx/layers/d3d9/CompositorD3D9.cpp
+++ b/gfx/layers/d3d9/CompositorD3D9.cpp
@@ -120,20 +120,17 @@ CompositorD3D9::CreateRenderTarget(const
                                        D3DPOOL_DEFAULT, byRef(texture),
                                        nullptr);
   if (FAILED(hr)) {
     ReportFailure(NS_LITERAL_CSTRING("CompositorD3D9::CreateRenderTarget: Failed to create texture"),
                   hr);
     return nullptr;
   }
 
-  RefPtr<CompositingRenderTargetD3D9> rt =
-    new CompositingRenderTargetD3D9(texture, aInit, aRect);
-
-  return rt;
+  return MakeAndAddRef<CompositingRenderTargetD3D9>(texture, aInit, aRect);
 }
 
 TemporaryRef<CompositingRenderTarget>
 CompositorD3D9::CreateRenderTargetFromSource(const gfx::IntRect &aRect,
                                              const CompositingRenderTarget *aSource,
                                              const gfx::IntPoint &aSourcePoint)
 {
   MOZ_ASSERT(aRect.width != 0 && aRect.height != 0, "Trying to create a render target of invalid size");
@@ -187,22 +184,19 @@ CompositorD3D9::CreateRenderTargetFromSo
                                  D3DTEXF_NONE);
       if (FAILED(hr)) {
         ReportFailure(NS_LITERAL_CSTRING("CompositorD3D9::CreateRenderTargetFromSource: Failed to update texture"),
                       hr);
       }
     }
   }
 
-  RefPtr<CompositingRenderTargetD3D9> rt =
-    new CompositingRenderTargetD3D9(texture,
-                                    INIT_MODE_NONE,
-                                    aRect);
-
-  return rt;
+  return MakeAndAddRef<CompositingRenderTargetD3D9>(texture,
+                                                    INIT_MODE_NONE,
+                                                    aRect);
 }
 
 void
 CompositorD3D9::SetRenderTarget(CompositingRenderTarget *aRenderTarget)
 {
   MOZ_ASSERT(aRenderTarget && mDeviceManager);
   RefPtr<CompositingRenderTargetD3D9> oldRT = mCurrentRT;
   mCurrentRT = static_cast<CompositingRenderTargetD3D9*>(aRenderTarget);
--- a/gfx/layers/d3d9/DeviceManagerD3D9.cpp
+++ b/gfx/layers/d3d9/DeviceManagerD3D9.cpp
@@ -839,17 +839,17 @@ DeviceManagerD3D9::CreateTexture(const I
 
   NS_ASSERTION(aPool != D3DPOOL_MANAGED,
                "Should not be using MANAGED texture pool. We will get an error when we have to recreate the device");
   if (aPool == D3DPOOL_DEFAULT) {
     MOZ_ASSERT(aTextureHost, "We need a texture host to track so we can release the texture.");
     RegisterTextureHost(aTextureHost);
   }
 
-  return result;
+  return result.forget();
 }
 
 #ifdef DEBUG
 bool
 DeviceManagerD3D9::IsInTextureHostList(TextureSourceD3D9* aFind)
 {
   TextureSourceD3D9* cur = mTextureHostList;
   while(cur) {
--- a/gfx/layers/d3d9/TextureD3D9.cpp
+++ b/gfx/layers/d3d9/TextureD3D9.cpp
@@ -193,17 +193,17 @@ TextureSourceD3D9::InitTextures(DeviceMa
 
   tmpTexture->GetSurfaceLevel(0, byRef(aSurface));
   aSurface->LockRect(&aLockedRect, nullptr, 0);
   if (!aLockedRect.pBits) {
     NS_WARNING("Could not lock surface");
     return nullptr;
   }
 
-  return result;
+  return result.forget();
 }
 
 /**
  * Helper method for DataToTexture and SurfaceToTexture.
  */
 static void
 FinishTextures(DeviceManagerD3D9* aDeviceManager,
                IDirect3DTexture9* aTexture,
@@ -241,17 +241,17 @@ TextureSourceD3D9::DataToTexture(DeviceM
   for (int y = 0; y < aSize.height; y++) {
     memcpy((char*)lockedRect.pBits + lockedRect.Pitch * y,
             aData + aStride * y,
             width);
   }
 
   FinishTextures(aDeviceManager, texture, surface);
 
-  return texture;
+  return texture.forget();
 }
 
 TemporaryRef<IDirect3DTexture9>
 TextureSourceD3D9::TextureToTexture(DeviceManagerD3D9* aDeviceManager,
                                     IDirect3DTexture9* aTexture,
                                     const IntSize& aSize,
                                     _D3DFORMAT aFormat)
 {
@@ -265,17 +265,17 @@ TextureSourceD3D9::TextureToTexture(Devi
     return nullptr;
   }
 
   HRESULT hr = aDeviceManager->device()->UpdateTexture(aTexture, texture);
   if (FAILED(hr)) {
     return nullptr;
   }
 
-  return texture;
+  return texture.forget();
 }
 
 TemporaryRef<IDirect3DTexture9>
 TextureSourceD3D9::SurfaceToTexture(DeviceManagerD3D9* aDeviceManager,
                                     gfxWindowsSurface* aSurface,
                                     const IntSize& aSize,
                                     _D3DFORMAT aFormat)
 {
@@ -306,17 +306,17 @@ TextureSourceD3D9::SurfaceToTexture(Devi
 
         RefPtr<SourceSurface> surf = dt->CreateSourceSurfaceFromNativeSurface(nativeSurf);
         dt->CopySurface(surf, IntRect(IntPoint(), aSize), IntPoint());
     }
   }
 
   FinishTextures(aDeviceManager, texture, surface);
 
-  return texture;
+  return texture.forget();
 }
 
 DataTextureSourceD3D9::DataTextureSourceD3D9(gfx::SurfaceFormat aFormat,
                                              CompositorD3D9* aCompositor,
                                              TextureFlags aFlags,
                                              StereoMode aStereoMode)
   : mFormat(aFormat)
   , mCompositor(aCompositor)
@@ -580,17 +580,17 @@ CairoTextureClientD3D9::CreateSimilar(Te
 {
   RefPtr<TextureClient> tex = new CairoTextureClientD3D9(mAllocator, mFormat,
                                                          mFlags | aFlags);
 
   if (!tex->AllocateForSurface(mSize, aAllocFlags)) {
     return nullptr;
   }
 
-  return tex;
+  return tex.forget();
 }
 
 bool
 CairoTextureClientD3D9::Lock(OpenMode aMode)
 {
   MOZ_ASSERT(!mIsLocked);
   if (!IsValid() || !IsAllocated()) {
     return false;
@@ -777,17 +777,17 @@ SharedTextureClientD3D9::Create(ISurface
                                 aFlags);
   MOZ_ASSERT(!texture->mTexture);
   texture->mTexture = aTexture;
   texture->mHandle = aSharedHandle;
   texture->mDesc = aDesc;
   if (texture->mTexture) {
     gfxWindowsPlatform::sD3D9SharedTextureUsed += texture->mDesc.Width * texture->mDesc.Height * 4;
   }
-  return texture;
+  return texture.forget();
 }
 
 bool
 SharedTextureClientD3D9::Lock(OpenMode)
 {
   MOZ_ASSERT(!mIsLocked);
   if (!IsValid()) {
     return false;
--- a/gfx/layers/ipc/CompositorBench.cpp
+++ b/gfx/layers/ipc/CompositorBench.cpp
@@ -236,18 +236,17 @@ public:
 
   virtual void Teardown(Compositor* aCompositor) {
     mSurface = nullptr;
     mTexture = nullptr;
     free(mBuf);
   }
 
   TemporaryRef<Effect> CreateEffect(size_t i) {
-    RefPtr<TexturedEffect> effect = CreateTexturedEffect(SurfaceFormat::B8G8R8A8, mTexture, Filter::POINT, true);
-    return effect;
+    return CreateTexturedEffect(SurfaceFormat::B8G8R8A8, mTexture, Filter::POINT, true);
   }
 };
 
 class StressTexturedQuadBench : public BenchTest {
 public:
   StressTexturedQuadBench()
     : BenchTest("Stress Textured Quad (10s 256x256 quads)")
   {}
@@ -280,18 +279,17 @@ public:
 
   virtual void Teardown(Compositor* aCompositor) {
     mSurface = nullptr;
     mTexture = nullptr;
     free(mBuf);
   }
 
   virtual TemporaryRef<Effect> CreateEffect(size_t i) {
-    RefPtr<TexturedEffect> effect = CreateTexturedEffect(SurfaceFormat::B8G8R8A8, mTexture, Filter::POINT, true);
-    return effect;
+    return CreateTexturedEffect(SurfaceFormat::B8G8R8A8, mTexture, Filter::POINT, true);
   }
 };
 
 #ifdef MOZ_WIDGET_GONK
 class TrivialGrallocQuadBench : public BenchTest {
 public:
   TrivialGrallocQuadBench()
     : BenchTest("Travial Gralloc Quad (10s 256x256 quads)")
@@ -323,18 +321,17 @@ public:
 
   virtual void Teardown(Compositor* aCompositor) {
     mGralloc = nullptr;
     mTexture = nullptr;
     free(mBuf);
   }
 
   virtual TemporaryRef<Effect> CreateEffect(size_t i) {
-    RefPtr<TexturedEffect> effect = CreateTexturedEffect(SurfaceFormat::B8G8R8A8, mTexture, Filter::POINT);
-    return effect;
+    return CreateTexturedEffect(SurfaceFormat::B8G8R8A8, mTexture, Filter::POINT);
   }
 };
 
 class StressGrallocQuadBench : public BenchTest {
 public:
   StressGrallocQuadBench()
     : BenchTest("Stress Gralloc Quad (10s 256x256 quads)")
   {}
@@ -365,18 +362,17 @@ public:
 
   virtual void Teardown(Compositor* aCompositor) {
     mGralloc = nullptr;
     mTexture = nullptr;
     free(mBuf);
   }
 
   virtual TemporaryRef<Effect> CreateEffect(size_t i) {
-    RefPtr<TexturedEffect> effect = CreateTexturedEffect(SurfaceFormat::B8G8R8A8, mTexture, Filter::POINT);
-    return effect;
+    return CreateTexturedEffect(SurfaceFormat::B8G8R8A8, mTexture, Filter::POINT);
   }
 };
 #endif
 
 static void RunCompositorBench(Compositor* aCompositor, const gfx::Rect& aScreenRect)
 {
   std::vector<BenchTest*> tests;
 
--- a/gfx/layers/opengl/CompositorOGL.cpp
+++ b/gfx/layers/opengl/CompositorOGL.cpp
@@ -1419,19 +1419,17 @@ CompositorOGL::Resume()
   return gl()->RenewSurface();
 #endif
   return true;
 }
 
 TemporaryRef<DataTextureSource>
 CompositorOGL::CreateDataTextureSource(TextureFlags aFlags)
 {
-  RefPtr<DataTextureSource> result =
-    new TextureImageTextureSourceOGL(this, aFlags);
-  return result;
+  return MakeAndAddRef<TextureImageTextureSourceOGL>(this, aFlags);
 }
 
 bool
 CompositorOGL::SupportsPartialTextureUpdate()
 {
   return CanUploadSubTextures(mGLContext);
 }
 
--- a/gfx/layers/opengl/GrallocTextureClient.cpp
+++ b/gfx/layers/opengl/GrallocTextureClient.cpp
@@ -55,17 +55,17 @@ GrallocTextureClientOGL::CreateSimilar(T
   RefPtr<TextureClient> tex = new GrallocTextureClientOGL(
     mAllocator, mFormat, mBackend, mFlags | aFlags
   );
 
   if (!tex->AllocateForSurface(mSize, aAllocFlags)) {
     return nullptr;
   }
 
-  return tex;
+  return tex.forget();
 }
 
 bool
 GrallocTextureClientOGL::ToSurfaceDescriptor(SurfaceDescriptor& aOutDescriptor)
 {
   MOZ_ASSERT(IsValid());
   if (!IsAllocated()) {
     return false;
--- a/gfx/layers/opengl/MacIOSurfaceTextureClientOGL.cpp
+++ b/gfx/layers/opengl/MacIOSurfaceTextureClientOGL.cpp
@@ -28,17 +28,17 @@ MacIOSurfaceTextureClientOGL::Create(ISu
                                      TextureFlags aFlags,
                                      MacIOSurface* aSurface)
 {
   RefPtr<MacIOSurfaceTextureClientOGL> texture =
       new MacIOSurfaceTextureClientOGL(aAllocator, aFlags);
   MOZ_ASSERT(texture->IsValid());
   MOZ_ASSERT(!texture->IsAllocated());
   texture->mSurface = aSurface;
-  return texture;
+  return texture.forget();
 }
 
 bool
 MacIOSurfaceTextureClientOGL::Lock(OpenMode aMode)
 {
   MOZ_ASSERT(!mIsLocked);
   mIsLocked = true;
   return IsValid() && IsAllocated();
--- a/gfx/src/FilterSupport.cpp
+++ b/gfx/src/FilterSupport.cpp
@@ -98,130 +98,130 @@ namespace gfx {
 
 namespace FilterWrappers {
 
   static TemporaryRef<FilterNode>
   Unpremultiply(DrawTarget* aDT, FilterNode* aInput)
   {
     RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::UNPREMULTIPLY);
     filter->SetInput(IN_UNPREMULTIPLY_IN, aInput);
-    return filter;
+    return filter.forget();
   }
 
   static TemporaryRef<FilterNode>
   Premultiply(DrawTarget* aDT, FilterNode* aInput)
   {
     RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::PREMULTIPLY);
     filter->SetInput(IN_PREMULTIPLY_IN, aInput);
-    return filter;
+    return filter.forget();
   }
 
   static TemporaryRef<FilterNode>
   LinearRGBToSRGB(DrawTarget* aDT, FilterNode* aInput)
   {
     RefPtr<FilterNode> transfer = aDT->CreateFilter(FilterType::DISCRETE_TRANSFER);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_R, false);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_TABLE_R, glinearRGBTosRGBMap, 256);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_G, false);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_TABLE_G, glinearRGBTosRGBMap, 256);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_B, false);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_TABLE_B, glinearRGBTosRGBMap, 256);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_A, true);
     transfer->SetInput(IN_DISCRETE_TRANSFER_IN, aInput);
-    return transfer;
+    return transfer.forget();
   }
 
   static TemporaryRef<FilterNode>
   SRGBToLinearRGB(DrawTarget* aDT, FilterNode* aInput)
   {
     RefPtr<FilterNode> transfer = aDT->CreateFilter(FilterType::DISCRETE_TRANSFER);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_R, false);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_TABLE_R, gsRGBToLinearRGBMap, 256);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_G, false);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_TABLE_G, gsRGBToLinearRGBMap, 256);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_B, false);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_TABLE_B, gsRGBToLinearRGBMap, 256);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_A, true);
     transfer->SetInput(IN_DISCRETE_TRANSFER_IN, aInput);
-    return transfer;
+    return transfer.forget();
   }
 
   static TemporaryRef<FilterNode>
   Crop(DrawTarget* aDT, FilterNode* aInputFilter, const IntRect& aRect)
   {
     RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::CROP);
     filter->SetAttribute(ATT_CROP_RECT, Rect(aRect));
     filter->SetInput(IN_CROP_IN, aInputFilter);
-    return filter;
+    return filter.forget();
   }
 
   static TemporaryRef<FilterNode>
   Offset(DrawTarget* aDT, FilterNode* aInputFilter, const IntPoint& aOffset)
   {
     RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::TRANSFORM);
     filter->SetAttribute(ATT_TRANSFORM_MATRIX, Matrix::Translation(aOffset.x, aOffset.y));
     filter->SetInput(IN_TRANSFORM_IN, aInputFilter);
-    return filter;
+    return filter.forget();
   }
 
   static TemporaryRef<FilterNode>
   GaussianBlur(DrawTarget* aDT, FilterNode* aInputFilter, const Size& aStdDeviation)
   {
     float stdX = float(std::min(aStdDeviation.width, kMaxStdDeviation));
     float stdY = float(std::min(aStdDeviation.height, kMaxStdDeviation));
     if (stdX == stdY) {
       RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::GAUSSIAN_BLUR);
       filter->SetAttribute(ATT_GAUSSIAN_BLUR_STD_DEVIATION, stdX);
       filter->SetInput(IN_GAUSSIAN_BLUR_IN, aInputFilter);
-      return filter;
+      return filter.forget();
     }
     RefPtr<FilterNode> filterH = aDT->CreateFilter(FilterType::DIRECTIONAL_BLUR);
     RefPtr<FilterNode> filterV = aDT->CreateFilter(FilterType::DIRECTIONAL_BLUR);
     filterH->SetAttribute(ATT_DIRECTIONAL_BLUR_DIRECTION, (uint32_t)BLUR_DIRECTION_X);
     filterH->SetAttribute(ATT_DIRECTIONAL_BLUR_STD_DEVIATION, stdX);
     filterV->SetAttribute(ATT_DIRECTIONAL_BLUR_DIRECTION, (uint32_t)BLUR_DIRECTION_Y);
     filterV->SetAttribute(ATT_DIRECTIONAL_BLUR_STD_DEVIATION, stdY);
     filterH->SetInput(IN_DIRECTIONAL_BLUR_IN, aInputFilter);
     filterV->SetInput(IN_DIRECTIONAL_BLUR_IN, filterH);
-    return filterV;
+    return filterV.forget();
   }
 
   static TemporaryRef<FilterNode>
   Clear(DrawTarget* aDT)
   {
     RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::FLOOD);
     filter->SetAttribute(ATT_FLOOD_COLOR, Color(0,0,0,0));
-    return filter;
+    return filter.forget();
   }
 
   static TemporaryRef<FilterNode>
   ForSurface(DrawTarget* aDT, SourceSurface* aSurface,
              const IntPoint& aSurfacePosition)
   {
     RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::TRANSFORM);
     filter->SetAttribute(ATT_TRANSFORM_MATRIX,
       Matrix::Translation(aSurfacePosition.x, aSurfacePosition.y));
     filter->SetInput(IN_TRANSFORM_IN, aSurface);
-    return filter;
+    return filter.forget();
   }
 
   static TemporaryRef<FilterNode>
   ToAlpha(DrawTarget* aDT, FilterNode* aInput)
   {
     float zero = 0.0f;
     RefPtr<FilterNode> transfer = aDT->CreateFilter(FilterType::DISCRETE_TRANSFER);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_R, false);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_TABLE_R, &zero, 1);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_G, false);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_TABLE_G, &zero, 1);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_B, false);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_TABLE_B, &zero, 1);
     transfer->SetAttribute(ATT_DISCRETE_TRANSFER_DISABLE_A, true);
     transfer->SetInput(IN_DISCRETE_TRANSFER_IN, aInput);
-    return transfer;
+    return transfer.forget();
   }
 
 }
 
 // A class that wraps a FilterNode and handles conversion between different
 // color models. Create FilterCachedColorModels with your original filter and
 // the color model that this filter outputs in natively, and then call
 // ->ForColorModel(colorModel) in order to get a FilterNode which outputs to
@@ -275,17 +275,18 @@ FilterCachedColorModels::FilterCachedCol
 }
 
 TemporaryRef<FilterNode>
 FilterCachedColorModels::ForColorModel(ColorModel aColorModel)
 {
   if (!mFilterForColorModel[aColorModel.ToIndex()]) {
     mFilterForColorModel[aColorModel.ToIndex()] = WrapForColorModel(aColorModel);
   }
-  return mFilterForColorModel[aColorModel.ToIndex()];
+  RefPtr<FilterNode> filter(mFilterForColorModel[aColorModel.ToIndex()]);
+  return filter.forget();
 }
 
 TemporaryRef<FilterNode>
 FilterCachedColorModels::WrapForColorModel(ColorModel aColorModel)
 {
   // Convert one aspect at a time and recurse.
   // Conversions between premultiplied / unpremultiplied color channels for the
   // same color space can happen directly.
@@ -693,37 +694,38 @@ FilterNodeFromPrimitiveDescription(const
           BLEND_MODE_SATURATION,
           BLEND_MODE_COLOR,
           BLEND_MODE_LUMINOSITY
         };
         filter->SetAttribute(ATT_BLEND_BLENDMODE, (uint32_t)blendModes[mode]);
         filter->SetInput(IN_BLEND_IN, aSources[0]);
         filter->SetInput(IN_BLEND_IN2, aSources[1]);
       }
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::ColorMatrix:
     {
       float colorMatrix[20];
       uint32_t type = atts.GetUint(eColorMatrixType);
       const nsTArray<float>& values = atts.GetFloats(eColorMatrixValues);
       if (NS_FAILED(ComputeColorMatrix(type, values, colorMatrix))) {
-        return aSources[0];
+        RefPtr<FilterNode> filter(aSources[0]);
+        return filter.forget();
       }
       Matrix5x4 matrix(colorMatrix[0], colorMatrix[5], colorMatrix[10],  colorMatrix[15],
                        colorMatrix[1], colorMatrix[6], colorMatrix[11],  colorMatrix[16],
                        colorMatrix[2], colorMatrix[7], colorMatrix[12],  colorMatrix[17],
                        colorMatrix[3], colorMatrix[8], colorMatrix[13],  colorMatrix[18],
                        colorMatrix[4], colorMatrix[9], colorMatrix[14],  colorMatrix[19]);
       RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::COLOR_MATRIX);
       filter->SetAttribute(ATT_COLOR_MATRIX_MATRIX, matrix);
       filter->SetAttribute(ATT_COLOR_MATRIX_ALPHA_MODE, (uint32_t)ALPHA_MODE_STRAIGHT);
       filter->SetInput(IN_COLOR_MATRIX_IN, aSources[0]);
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::Morphology:
     {
       Size radii = atts.GetSize(eMorphologyRadii);
       int32_t rx = radii.width;
       int32_t ry = radii.height;
       if (rx < 0 || ry < 0) {
@@ -740,33 +742,33 @@ FilterNodeFromPrimitiveDescription(const
 
       MorphologyOperator op = atts.GetUint(eMorphologyOperator) == SVG_OPERATOR_ERODE ?
         MORPHOLOGY_OPERATOR_ERODE : MORPHOLOGY_OPERATOR_DILATE;
 
       RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::MORPHOLOGY);
       filter->SetAttribute(ATT_MORPHOLOGY_RADII, IntSize(rx, ry));
       filter->SetAttribute(ATT_MORPHOLOGY_OPERATOR, (uint32_t)op);
       filter->SetInput(IN_MORPHOLOGY_IN, aSources[0]);
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::Flood:
     {
       Color color = atts.GetColor(eFloodColor);
       RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::FLOOD);
       filter->SetAttribute(ATT_FLOOD_COLOR, color);
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::Tile:
     {
       RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::TILE);
       filter->SetAttribute(ATT_TILE_SOURCE_RECT, aSourceRegions[0]);
       filter->SetInput(IN_TILE_IN, aSources[0]);
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::ComponentTransfer:
     {
       RefPtr<FilterNode> filters[4]; // one for each FILTER_*_TRANSFER type
       static const AttributeName componentFunctionNames[4] = {
         eComponentTransferFunctionR,
         eComponentTransferFunctionG,
@@ -784,17 +786,17 @@ FilterNodeFromPrimitiveDescription(const
       RefPtr<FilterNode> lastFilter = aSources[0];
       for (int32_t i = 0; i < 4; i++) {
         if (filters[i]) {
           filters[i]->SetInput(0, lastFilter);
           lastFilter = filters[i];
         }
       }
 
-      return lastFilter;
+      return lastFilter.forget();
     }
 
     case PrimitiveType::ConvolveMatrix:
     {
       RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::CONVOLVE_MATRIX);
       filter->SetAttribute(ATT_CONVOLVE_MATRIX_KERNEL_SIZE, atts.GetIntSize(eConvolveMatrixKernelSize));
       const nsTArray<float>& matrix = atts.GetFloats(eConvolveMatrixKernelMatrix);
       filter->SetAttribute(ATT_CONVOLVE_MATRIX_KERNEL_MATRIX,
@@ -815,17 +817,17 @@ FilterNodeFromPrimitiveDescription(const
         EDGE_MODE_NONE       // SVG_EDGEMODE_NONE
       };
       filter->SetAttribute(ATT_CONVOLVE_MATRIX_EDGE_MODE, (uint32_t)edgeModes[edgeMode]);
       filter->SetAttribute(ATT_CONVOLVE_MATRIX_KERNEL_UNIT_LENGTH,
                            atts.GetSize(eConvolveMatrixKernelUnitLength));
       filter->SetAttribute(ATT_CONVOLVE_MATRIX_PRESERVE_ALPHA,
                            atts.GetBool(eConvolveMatrixPreserveAlpha));
       filter->SetInput(IN_CONVOLVE_MATRIX_IN, aSources[0]);
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::Offset:
     {
       return FilterWrappers::Offset(aDT, aSources[0],
                                     atts.GetIntPoint(eOffsetOffset));
     }
 
@@ -842,17 +844,17 @@ FilterNodeFromPrimitiveDescription(const
         COLOR_CHANNEL_A  // SVG_CHANNEL_A
       };
       filter->SetAttribute(ATT_DISPLACEMENT_MAP_X_CHANNEL,
                            (uint32_t)channel[atts.GetUint(eDisplacementMapXChannel)]);
       filter->SetAttribute(ATT_DISPLACEMENT_MAP_Y_CHANNEL,
                            (uint32_t)channel[atts.GetUint(eDisplacementMapYChannel)]);
       filter->SetInput(IN_DISPLACEMENT_MAP_IN, aSources[0]);
       filter->SetInput(IN_DISPLACEMENT_MAP_IN2, aSources[1]);
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::Turbulence:
     {
       RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::TURBULENCE);
       filter->SetAttribute(ATT_TURBULENCE_BASE_FREQUENCY,
                            atts.GetSize(eTurbulenceBaseFrequency));
       filter->SetAttribute(ATT_TURBULENCE_NUM_OCTAVES,
@@ -893,33 +895,34 @@ FilterNodeFromPrimitiveDescription(const
           COMPOSITE_OPERATOR_OUT,  // SVG_FECOMPOSITE_OPERATOR_OUT
           COMPOSITE_OPERATOR_ATOP, // SVG_FECOMPOSITE_OPERATOR_ATOP
           COMPOSITE_OPERATOR_XOR   // SVG_FECOMPOSITE_OPERATOR_XOR
         };
         filter->SetAttribute(ATT_COMPOSITE_OPERATOR, (uint32_t)operators[op]);
         filter->SetInput(IN_COMPOSITE_IN_START, aSources[1]);
         filter->SetInput(IN_COMPOSITE_IN_START + 1, aSources[0]);
       }
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::Merge:
     {
       if (aSources.Length() == 0) {
         return nullptr;
       }
       if (aSources.Length() == 1) {
-        return aSources[0];
+        RefPtr<FilterNode> filter(aSources[0]);
+        return filter.forget();
       }
       RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::COMPOSITE);
       filter->SetAttribute(ATT_COMPOSITE_OPERATOR, (uint32_t)COMPOSITE_OPERATOR_OVER);
       for (size_t i = 0; i < aSources.Length(); i++) {
         filter->SetInput(IN_COMPOSITE_IN_START + i, aSources[i]);
       }
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::GaussianBlur:
     {
       return FilterWrappers::GaussianBlur(aDT, aSources[0],
                                           atts.GetSize(eGaussianBlurStdDeviation));
     }
 
@@ -944,17 +947,17 @@ FilterNodeFromPrimitiveDescription(const
       composite->SetAttribute(ATT_COMPOSITE_OPERATOR, (uint32_t)COMPOSITE_OPERATOR_IN);
       composite->SetInput(IN_COMPOSITE_IN_START, offsetBlur);
       composite->SetInput(IN_COMPOSITE_IN_START + 1, flood);
 
       RefPtr<FilterNode> filter = aDT->CreateFilter(FilterType::COMPOSITE);
       filter->SetAttribute(ATT_COMPOSITE_OPERATOR, (uint32_t)COMPOSITE_OPERATOR_OVER);
       filter->SetInput(IN_COMPOSITE_IN_START, composite);
       filter->SetInput(IN_COMPOSITE_IN_START + 1, aSources[0]);
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::DiffuseLighting:
     case PrimitiveType::SpecularLighting:
     {
       bool isSpecular =
         aDescription.Type() == PrimitiveType::SpecularLighting;
 
@@ -1016,17 +1019,17 @@ FilterNodeFromPrimitiveDescription(const
                                lightAttributes.GetFloat(eDistantLightAzimuth));
           filter->SetAttribute(ATT_DISTANT_LIGHT_ELEVATION,
                                lightAttributes.GetFloat(eDistantLightElevation));
           break;
       }
 
       filter->SetInput(IN_LIGHTING_IN, aSources[0]);
 
-      return filter;
+      return filter.forget();
     }
 
     case PrimitiveType::Image:
     {
       Matrix TM = atts.GetMatrix(eImageTransform);
       if (!TM.Determinant()) {
         return nullptr;
       }
@@ -1035,17 +1038,17 @@ FilterNodeFromPrimitiveDescription(const
       // stored in the primitive description.
       RefPtr<SourceSurface> inputImage =
         aInputImages[atts.GetUint(eImageInputIndex)];
 
       RefPtr<FilterNode> transform = aDT->CreateFilter(FilterType::TRANSFORM);
       transform->SetInput(IN_TRANSFORM_IN, inputImage);
       transform->SetAttribute(ATT_TRANSFORM_MATRIX, TM);
       transform->SetAttribute(ATT_TRANSFORM_FILTER, atts.GetUint(eImageFilter));
-      return transform;
+      return transform.forget();
     }
 
     case PrimitiveType::ToAlpha:
     {
       return FilterWrappers::ToAlpha(aDT, aSources[0]);
     }
 
     default:
--- a/gfx/tests/gtest/TestCompositor.cpp
+++ b/gfx/tests/gtest/TestCompositor.cpp
@@ -120,17 +120,17 @@ static TemporaryRef<Compositor> CreateTe
 #endif
   }
 
   if (!compositor) {
     printf_stderr("Failed to construct layer manager for the requested backend\n");
     abort();
   }
 
-  return compositor;
+  return compositor.forget();
 }
 
 /**
  * Get a list of layers managers for the platform to run the test on.
  */
 static std::vector<LayerManagerData> GetLayerManagers(std::vector<LayersBackend> aBackends)
 {
   std::vector<LayerManagerData> managers;
@@ -167,20 +167,18 @@ static std::vector<LayersBackend> GetPla
 #endif
 
   // TODO Support OGL/D3D backends with unit test
   return backends;
 }
 
 static TemporaryRef<DrawTarget> CreateDT()
 {
-  RefPtr<DrawTarget> dt = gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
+  return gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
     IntSize(gCompWidth, gCompHeight), SurfaceFormat::B8G8R8A8);
-
-  return dt;
 }
 
 static bool CompositeAndCompare(nsRefPtr<LayerManagerComposite> layerManager, DrawTarget* refDT)
 {
   RefPtr<DrawTarget> drawTarget = CreateDT();
 
   layerManager->BeginTransactionWithDrawTarget(drawTarget, IntRect(0, 0, gCompWidth, gCompHeight));
   layerManager->EndEmptyTransaction();
--- a/gfx/thebes/gfxContext.cpp
+++ b/gfx/thebes/gfxContext.cpp
@@ -199,17 +199,18 @@ gfxContext::ClosePath()
 {
   EnsurePathBuilder();
   mPathBuilder->Close();
 }
 
 TemporaryRef<Path> gfxContext::GetPath()
 {
   EnsurePath();
-  return mPath;
+  RefPtr<Path> path(mPath);
+  return path.forget();
 }
 
 void gfxContext::SetPath(Path* path)
 {
   MOZ_ASSERT(path->GetBackendType() == mDT->GetBackendType() ||
              (mDT->GetBackendType() == BackendType::DIRECT2D1_1 && path->GetBackendType() == BackendType::DIRECT2D));
   mPath = path;
   mPathBuilder = nullptr;
@@ -944,17 +945,17 @@ gfxContext::PopGroupToSurface(Matrix* aT
 
   Matrix mat = mTransform;
   mat.Invert();
 
   Matrix deviceOffsetTranslation;
   deviceOffsetTranslation.PreTranslate(deviceOffset.x, deviceOffset.y);
 
   *aTransform = deviceOffsetTranslation * mat;
-  return src;
+  return src.forget();
 }
 
 void
 gfxContext::PopGroupToSource()
 {
   RefPtr<SourceSurface> src = mDT->Snapshot();
   Point deviceOffset = CurrentState().deviceOffset;
   Restore();
--- a/gfx/thebes/gfxDWriteFonts.cpp
+++ b/gfx/thebes/gfxDWriteFonts.cpp
@@ -669,17 +669,18 @@ gfxDWriteFont::AddSizeOfIncludingThis(Ma
     AddSizeOfExcludingThis(aMallocSizeOf, aSizes);
 }
 
 TemporaryRef<ScaledFont>
 gfxDWriteFont::GetScaledFont(mozilla::gfx::DrawTarget *aTarget)
 {
   bool wantCairo = aTarget->GetBackendType() == BackendType::CAIRO;
   if (mAzureScaledFont && mAzureScaledFontIsCairo == wantCairo) {
-    return mAzureScaledFont;
+    RefPtr<ScaledFont> scaledFont(mAzureScaledFont);
+    return scaledFont.forget();
   }
 
   NativeFont nativeFont;
   nativeFont.mType = NativeFontType::DWRITE_FONT_FACE;
   nativeFont.mFont = GetFontFace();
 
   if (wantCairo) {
     mAzureScaledFont = Factory::CreateScaledFontWithCairo(nativeFont,
@@ -687,10 +688,11 @@ gfxDWriteFont::GetScaledFont(mozilla::gf
                                                         GetCairoScaledFont());
   } else {
     mAzureScaledFont = Factory::CreateScaledFontForNativeFont(nativeFont,
                                                             GetAdjustedSize());
   }
 
   mAzureScaledFontIsCairo = wantCairo;
 
-  return mAzureScaledFont;
+  RefPtr<ScaledFont> scaledFont(mAzureScaledFont);
+  return scaledFont.forget();
 }
--- a/gfx/thebes/gfxMacFont.cpp
+++ b/gfx/thebes/gfxMacFont.cpp
@@ -432,17 +432,18 @@ gfxMacFont::GetScaledFont(DrawTarget *aT
 {
   if (!mAzureScaledFont) {
     NativeFont nativeFont;
     nativeFont.mType = NativeFontType::MAC_FONT_FACE;
     nativeFont.mFont = GetCGFontRef();
     mAzureScaledFont = mozilla::gfx::Factory::CreateScaledFontWithCairo(nativeFont, GetAdjustedSize(), mScaledFont);
   }
 
-  return mAzureScaledFont;
+  RefPtr<ScaledFont> scaledFont(mAzureScaledFont);
+  return scaledFont.forget();
 }
 
 TemporaryRef<mozilla::gfx::GlyphRenderingOptions>
 gfxMacFont::GetGlyphRenderingOptions(const TextRunDrawParams* aRunParams)
 {
     if (aRunParams) {
         return mozilla::gfx::Factory::CreateCGGlyphRenderingOptions(aRunParams->fontSmoothingBGColor);
     }
--- a/gfx/thebes/gfxPlatform.cpp
+++ b/gfx/thebes/gfxPlatform.cpp
@@ -853,17 +853,18 @@ gfxPlatform::GetSourceSurfaceForSurface(
   }
 
   void *userData = aSurface->GetData(&kSourceSurface);
 
   if (userData) {
     SourceSurfaceUserData *surf = static_cast<SourceSurfaceUserData*>(userData);
 
     if (surf->mSrcSurface->IsValid() && surf->mBackendType == aTarget->GetBackendType()) {
-      return surf->mSrcSurface;
+      RefPtr<SourceSurface> srcSurface(surf->mSrcSurface);
+      return srcSurface.forget();
     }
     // We can just continue here as when setting new user data the destroy
     // function will be called for the old user data.
   }
 
   SurfaceFormat format;
   if (aSurface->GetContentType() == gfxContentType::ALPHA) {
     format = SurfaceFormat::A8;
@@ -1020,20 +1021,18 @@ gfxPlatform::GetWrappedDataSourceSurface
 }
 
 TemporaryRef<ScaledFont>
 gfxPlatform::GetScaledFontForFont(DrawTarget* aTarget, gfxFont *aFont)
 {
   NativeFont nativeFont;
   nativeFont.mType = NativeFontType::CAIRO_FONT_FACE;
   nativeFont.mFont = aFont->GetCairoScaledFont();
-  RefPtr<ScaledFont> scaledFont =
-    Factory::CreateScaledFontForNativeFont(nativeFont,
-                                           aFont->GetAdjustedSize());
-  return scaledFont;
+  return Factory::CreateScaledFontForNativeFont(nativeFont,
+                                                aFont->GetAdjustedSize());
 }
 
 int
 gfxPlatform::GetTileWidth()
 {
   MOZ_ASSERT(mTileWidth != -1);
   return mTileWidth;
 }
--- a/gfx/thebes/gfxUtils.cpp
+++ b/gfx/thebes/gfxUtils.cpp
@@ -336,17 +336,17 @@ gfxUtils::CreatePremultipliedDataSurface
     }
 
     PremultiplyData(srcMap.mData, srcMap.mStride,
                     destMap.mData, destMap.mStride,
                     srcSurf->GetSize().width,
                     srcSurf->GetSize().height);
 
     UnmapSrcDest(srcSurf, destSurf);
-    return destSurf;
+    return destSurf.forget();
 }
 
 TemporaryRef<DataSourceSurface>
 gfxUtils::CreateUnpremultipliedDataSurface(DataSourceSurface* srcSurf)
 {
     RefPtr<DataSourceSurface> destSurf;
     DataSourceSurface::MappedSurface srcMap;
     DataSourceSurface::MappedSurface destMap;
@@ -357,17 +357,17 @@ gfxUtils::CreateUnpremultipliedDataSurfa
     }
 
     UnpremultiplyData(srcMap.mData, srcMap.mStride,
                       destMap.mData, destMap.mStride,
                       srcSurf->GetSize().width,
                       srcSurf->GetSize().height);
 
     UnmapSrcDest(srcSurf, destSurf);
-    return destSurf;
+    return destSurf.forget();
 }
 
 void
 gfxUtils::ConvertBGRAtoRGBA(uint8_t* aData, uint32_t aLength)
 {
     MOZ_ASSERT((aLength % 4) == 0, "Loop below will pass srcEnd!");
 
     uint8_t *src = aData;
@@ -714,18 +714,17 @@ PathFromRegionInternal(DrawTarget* aTarg
   const IntRect* r;
   while ((r = iter.Next()) != nullptr) {
     pb->MoveTo(Point(r->x, r->y));
     pb->LineTo(Point(r->XMost(), r->y));
     pb->LineTo(Point(r->XMost(), r->YMost()));
     pb->LineTo(Point(r->x, r->YMost()));
     pb->Close();
   }
-  RefPtr<Path> path = pb->Finish();
-  return path;
+  return pb->Finish();
 }
 
 static void
 ClipToRegionInternal(DrawTarget* aTarget, const nsIntRegion& aRegion)
 {
   if (!aRegion.IsComplex()) {
     IntRect rect = aRegion.GetBounds();
     aTarget->PushClipRect(Rect(rect.x, rect.y, rect.width, rect.height));
--- a/gfx/thebes/gfxWindowsPlatform.cpp
+++ b/gfx/thebes/gfxWindowsPlatform.cpp
@@ -2087,17 +2087,17 @@ gfxWindowsPlatform::CreateD3D11DecoderDe
     return nullptr;
   }
 
   nsRefPtr<ID3D10Multithread> multi;
   device->QueryInterface(__uuidof(ID3D10Multithread), getter_AddRefs(multi));
 
   multi->SetMultithreadProtected(TRUE);
 
-  return device;
+  return device.forget();
 }
 
 static bool
 DwmCompositionEnabled()
 {
   MOZ_ASSERT(WinUtils::dwmIsCompositionEnabledPtr);
   BOOL dwmEnabled = false;
   WinUtils::dwmIsCompositionEnabledPtr(&dwmEnabled);
--- a/image/ClippedImage.cpp
+++ b/image/ClippedImage.cpp
@@ -56,17 +56,18 @@ public:
   {
     return mSize == aSize &&
            mSVGContext == aSVGContext &&
            mFrame == aFrame &&
            mFlags == aFlags;
   }
 
   TemporaryRef<SourceSurface> Surface() {
-    return mSurface;
+    RefPtr<SourceSurface> surf(mSurface);
+    return surf.forget();
   }
 
 private:
   RefPtr<SourceSurface>  mSurface;
   const nsIntSize        mSize;
   Maybe<SVGImageContext> mSVGContext;
   const float            mFrame;
   const uint32_t         mFlags;
--- a/image/RasterImage.cpp
+++ b/image/RasterImage.cpp
@@ -714,17 +714,17 @@ RasterImage::CopyFrame(uint32_t aWhichFr
 
     Rect srcRect(0, 0, intFrameRect.width, intFrameRect.height);
     target->DrawSurface(srcSurf, srcRect, rect);
   }
 
   target->Flush();
   surf->Unmap();
 
-  return surf;
+  return surf.forget();
 }
 
 //******************************************************************************
 /* [noscript] SourceSurface getFrame(in uint32_t aWhichFrame,
  *                                   in uint32_t aFlags); */
 NS_IMETHODIMP_(TemporaryRef<SourceSurface>)
 RasterImage::GetFrame(uint32_t aWhichFrame,
                       uint32_t aFlags)
--- a/image/imgFrame.cpp
+++ b/image/imgFrame.cpp
@@ -61,27 +61,27 @@ CreateLockedSurface(VolatileBuffer* vbuf
   RefPtr<DataSourceSurface> surf =
     Factory::CreateWrappingDataSourceSurface(*vbufptr, stride, size, format);
   if (!surf) {
     delete vbufptr;
     return nullptr;
   }
 
   surf->AddUserData(&kVolatileBuffer, vbufptr, VolatileBufferRelease);
-  return surf;
+  return surf.forget();
 }
 
 static TemporaryRef<VolatileBuffer>
 AllocateBufferForImage(const IntSize& size, SurfaceFormat format)
 {
   int32_t stride = VolatileSurfaceStride(size, format);
   RefPtr<VolatileBuffer> buf = new VolatileBuffer();
   if (buf->Init(stride * size.height,
                 1 << gfxAlphaRecovery::GoodAlignmentLog2())) {
-    return buf;
+    return buf.forget();
   }
 
   return nullptr;
 }
 
 // Returns true if an image of aWidth x aHeight is allowed and legal.
 static bool
 AllowedImageSize(int32_t aWidth, int32_t aHeight)
@@ -1050,24 +1050,26 @@ imgFrame::GetSurface()
 
 TemporaryRef<SourceSurface>
 imgFrame::GetSurfaceInternal()
 {
   mMonitor.AssertCurrentThreadOwns();
 
   if (mOptSurface) {
     if (mOptSurface->IsValid()) {
-      return mOptSurface;
+      RefPtr<SourceSurface> surf(mOptSurface);
+      return surf.forget();
     } else {
       mOptSurface = nullptr;
     }
   }
 
   if (mImageSurface) {
-    return mImageSurface;
+    RefPtr<SourceSurface> surf(mImageSurface);
+    return surf.forget();
   }
 
   if (!mVBuf) {
     return nullptr;
   }
 
   VolatileBufferPtr<char> buf(mVBuf);
   if (buf.WasBufferPurged()) {
--- a/layout/base/nsCSSRenderingBorders.cpp
+++ b/layout/base/nsCSSRenderingBorders.cpp
@@ -1087,17 +1087,17 @@ nsCSSBorderRenderer::CreateCornerGradien
     // for certain border types. Let's optimize it!
     rawStops[0].color = secondColor;
     rawStops[1].color = firstColor;
     Point tmp = aPoint1;
     aPoint1 = aPoint2;
     aPoint2 = tmp;
     gs = gfxGradientCache::GetOrCreateGradientStops(aDT, rawStops, ExtendMode::CLAMP);
   }
-  return gs;
+  return gs.forget();
 }
 
 typedef struct { Float a, b; } twoFloats;
 
 void
 nsCSSBorderRenderer::DrawSingleWidthSolidBorder()
 {
   // Easy enough to deal with.
--- a/layout/svg/nsSVGMaskFrame.cpp
+++ b/layout/svg/nsSVGMaskFrame.cpp
@@ -327,17 +327,17 @@ nsSVGMaskFrame::GetMaskForMaskedFrame(gf
   destMaskSurface->Unmap();
 
   // Moz2D transforms in the opposite direction to Thebes
   if (!maskSurfaceMatrix.Invert()) {
     return nullptr;
   }
 
   *aMaskTransform = ToMatrix(maskSurfaceMatrix);
-  return destMaskSurface;
+  return destMaskSurface.forget();
 }
 
 nsresult
 nsSVGMaskFrame::AttributeChanged(int32_t  aNameSpaceID,
                                  nsIAtom* aAttribute,
                                  int32_t  aModType)
 {
   if (aNameSpaceID == kNameSpaceID_None &&
--- a/mfbt/RefPtr.h
+++ b/mfbt/RefPtr.h
@@ -280,18 +280,16 @@ public:
     mPtr = nullptr;
     return TemporaryRef<T>(tmp, DontRef());
   }
 
   T* get() const { return mPtr; }
   operator T*() const { return mPtr; }
   T* operator->() const MOZ_NO_ADDREF_RELEASE_ON_RETURN { return mPtr; }
   T& operator*() const { return *mPtr; }
-  template<typename U>
-  operator TemporaryRef<U>() { return TemporaryRef<U>(mPtr); }
 
 private:
   void assign(T* aVal)
   {
     unref(mPtr);
     mPtr = aVal;
   }
 
--- a/mfbt/tests/TestRefPtr.cpp
+++ b/mfbt/tests/TestRefPtr.cpp
@@ -31,17 +31,18 @@ private:
 };
 int Foo::sNumDestroyed;
 
 struct Bar : public Foo {};
 
 TemporaryRef<Foo>
 NewFoo()
 {
-  return RefPtr<Foo>(new Foo());
+  RefPtr<Foo> f(new Foo());
+  return f.forget();
 }
 
 TemporaryRef<Foo>
 NewBar()
 {
   RefPtr<Bar> bar = new Bar();
   return bar.forget();
 }
--- a/mozglue/linker/BaseElf.cpp
+++ b/mozglue/linker/BaseElf.cpp
@@ -165,17 +165,17 @@ LoadedElf::Create(const char *path, void
     elf->arm_exidx.InitSize(elf->GetPtr(arm_exidx_phdr->p_vaddr),
                             arm_exidx_phdr->p_memsz);
 #endif
 
   DEBUG_LOG("LoadedElf::Create(\"%s\", %p) = %p", path, base_addr,
     static_cast<void *>(elf));
 
   ElfLoader::Singleton.Register(elf);
-  return elf;
+  return elf.forget();
 }
 
 bool
 LoadedElf::InitDyn(const Phdr *pt_dyn)
 {
   Array<Dyn> dyns;
   dyns.InitSize(GetPtr<Dyn>(pt_dyn->p_vaddr), pt_dyn->p_filesz);
 
--- a/mozglue/linker/CustomElf.cpp
+++ b/mozglue/linker/CustomElf.cpp
@@ -258,17 +258,17 @@ CustomElf::Load(Mappable *mappable, cons
                             arm_exidx_phdr->p_memsz);
 #endif
 
   if (MOZ_UNLIKELY(Logging::isVerbose())) {
     elf->stats("oneLibLoaded");
   }
   DEBUG_LOG("CustomElf::Load(\"%s\", 0x%x) = %p", path, flags,
             static_cast<void *>(elf));
-  return elf;
+  return elf.forget();
 }
 
 CustomElf::~CustomElf()
 {
   DEBUG_LOG("CustomElf::~CustomElf(%p [\"%s\"])",
             reinterpret_cast<void *>(this), GetPath());
   CallFini();
   /* Normally, __cxa_finalize is called by the .fini function. However,
--- a/mozglue/linker/ElfLoader.cpp
+++ b/mozglue/linker/ElfLoader.cpp
@@ -341,17 +341,17 @@ ElfLoader::Load(const char *path, int fl
   if (!self_elf)
     Init();
 
   RefPtr<LibHandle> handle;
 
   /* Handle dlopen(nullptr) directly. */
   if (!path) {
     handle = SystemElf::Load(nullptr, flags);
-    return handle;
+    return handle.forget();
   }
 
   /* TODO: Handle relative paths correctly */
   const char *name = LeafName(path);
 
   /* Search the list of handles we already have for a match. When the given
    * path is not absolute, compare file names, otherwise compare full paths. */
   if (name == path) {
--- a/mozglue/linker/Zip.cpp
+++ b/mozglue/linker/Zip.cpp
@@ -49,17 +49,17 @@ Zip::Create(const char *filename, void *
   // If neither the first Local File entry nor central directory entries
   // have been found, the zip was invalid.
   if (!zip->nextFile && !zip->entries) {
     ERROR("%s - Invalid zip", filename);
     return nullptr;
   }
 
   ZipCollection::Singleton.Register(zip);
-  return zip;
+  return zip.forget();
 }
 
 Zip::Zip(const char *filename, void *mapped, size_t size)
 : name(filename ? strdup(filename) : nullptr)
 , mapped(mapped)
 , size(size)
 , nextFile(LocalFile::validate(mapped)) // first Local File entry
 , nextDir(nullptr)
--- a/security/manager/ssl/src/nsNSSComponent.cpp
+++ b/security/manager/ssl/src/nsNSSComponent.cpp
@@ -1557,17 +1557,18 @@ nsNSSComponent::IsNSSInitialized(bool* i
 
 SharedCertVerifier::~SharedCertVerifier() { }
 
 TemporaryRef<SharedCertVerifier>
 nsNSSComponent::GetDefaultCertVerifier()
 {
   MutexAutoLock lock(mutex);
   MOZ_ASSERT(mNSSInitialized);
-  return mDefaultCertVerifier;
+  RefPtr<SharedCertVerifier> certVerifier(mDefaultCertVerifier);
+  return certVerifier.forget();
 }
 
 namespace mozilla { namespace psm {
 
 TemporaryRef<SharedCertVerifier>
 GetDefaultCertVerifier()
 {
   static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID);
--- a/widget/cocoa/nsChildView.mm
+++ b/widget/cocoa/nsChildView.mm
@@ -2596,17 +2596,17 @@ nsChildView::StartRemoteDrawing()
     mBasicCompositorImage->BeginUpdate(renderSize, dirtyRegion);
 
   if (!drawTarget) {
     // Composite unchanged textures.
     DoRemoteComposition(mBounds);
     return nullptr;
   }
 
-  return drawTarget;
+  return drawTarget.forget();
 }
 
 void
 nsChildView::EndRemoteDrawing()
 {
   mBasicCompositorImage->EndUpdate(true);
   DoRemoteComposition(mBounds);
 }
@@ -2713,17 +2713,17 @@ RectTextureImage::BeginUpdate(const nsIn
       gfx::Factory::CreateDrawTarget(gfx::BackendType::COREGRAPHICS, size,
                                      gfx::SurfaceFormat::B8G8R8A8);
     mBufferSize = neededBufferSize;
   }
 
   mInUpdate = true;
 
   RefPtr<gfx::DrawTarget> drawTarget = mUpdateDrawTarget;
-  return drawTarget;
+  return drawTarget.forget();
 }
 
 #define NSFoundationVersionWithProperStrideSupportForSubtextureUpload NSFoundationVersionNumber10_6_3
 
 static bool
 CanUploadSubtextures()
 {
   return NSFoundationVersionNumber >= NSFoundationVersionWithProperStrideSupportForSubtextureUpload;
--- a/widget/gonk/nativewindow/GonkBufferQueueJB.cpp
+++ b/widget/gonk/nativewindow/GonkBufferQueueJB.cpp
@@ -1,8 +1,9 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /*
  * Copyright (C) 2012 The Android Open Source Project
  * Copyright (C) 2013 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
@@ -131,17 +132,18 @@ GonkBufferQueue::getTextureClientFromBuf
     Mutex::Autolock _l(mMutex);
     if (buffer == NULL) {
         ST_LOGE("getSlotFromBufferLocked: encountered NULL buffer");
         return nullptr;
     }
 
     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
         if (mSlots[i].mGraphicBuffer != NULL && mSlots[i].mGraphicBuffer->handle == buffer->handle) {
-            return mSlots[i].mTextureClient;
+            RefPtr<TextureClient> client(mSlots[i].mTextureClient);
+            return client.forget();
         }
     }
     ST_LOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
     return nullptr;
 }
 
 int GonkBufferQueue::getSlotFromTextureClientLocked(
         TextureClient* client) const
--- a/widget/gonk/nativewindow/GonkBufferQueueKK.cpp
+++ b/widget/gonk/nativewindow/GonkBufferQueueKK.cpp
@@ -1,8 +1,9 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /*
  * Copyright (C) 2012 The Android Open Source Project
  * Copyright (C) 2013 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
@@ -123,17 +124,18 @@ GonkBufferQueue::getTextureClientFromBuf
     Mutex::Autolock _l(mMutex);
     if (buffer == NULL) {
         ALOGE("getSlotFromBufferLocked: encountered NULL buffer");
         return nullptr;
     }
 
     for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
         if (mSlots[i].mGraphicBuffer != NULL && mSlots[i].mGraphicBuffer->handle == buffer->handle) {
-            return mSlots[i].mTextureClient;
+             RefPtr<TextureClient> client(mSlots[i].mTextureClient);
+             return client.forget();
         }
     }
     ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
     return nullptr;
 }
 
 int GonkBufferQueue::getSlotFromTextureClientLocked(
         TextureClient* client) const
--- a/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.cpp
+++ b/widget/gonk/nativewindow/GonkBufferQueueLL/GonkBufferQueueConsumer.cpp
@@ -526,17 +526,18 @@ GonkBufferQueueConsumer::getTextureClien
     Mutex::Autolock _l(mCore->mMutex);
     if (buffer == NULL) {
         ALOGE("getSlotFromBufferLocked: encountered NULL buffer");
         return nullptr;
     }
 
     for (int i = 0; i < GonkBufferQueueDefs::NUM_BUFFER_SLOTS; i++) {
         if (mSlots[i].mGraphicBuffer != NULL && mSlots[i].mGraphicBuffer->handle == buffer->handle) {
-            return mSlots[i].mTextureClient;
+            RefPtr<TextureClient> client(mSlots[i].mTextureClient);
+            return client.forget();
         }
     }
     ALOGE("getSlotFromBufferLocked: unknown buffer: %p", buffer->handle);
     return nullptr;
 }
 
 int
 GonkBufferQueueConsumer::getSlotFromTextureClientLocked(GonkBufferSlot::TextureClient* client) const
--- a/widget/gonk/nativewindow/GonkNativeWindowICS.cpp
+++ b/widget/gonk/nativewindow/GonkNativeWindowICS.cpp
@@ -1,8 +1,9 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /*
  * Copyright (C) 2010 The Android Open Source Project
  * Copyright (C) 2012-2013 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
@@ -404,17 +405,18 @@ TemporaryRef<TextureClient>
 GonkNativeWindow::getTextureClientFromBuffer(ANativeWindowBuffer* buffer)
 {
   int buf = getSlotFromBufferLocked(buffer);
   if (buf < 0 || buf >= mBufferCount ||
       mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
     return nullptr;
   }
 
-  return mSlots[buf].mTextureClient;
+  RefPtr<TextureClient> client(mSlots[buf].mTextureClient);
+  return client.forget();
 }
 
 status_t GonkNativeWindow::queueBuffer(int buf, int64_t timestamp,
         uint32_t* outWidth, uint32_t* outHeight, uint32_t* outTransform)
 {
     {
         Mutex::Autolock lock(mMutex);
         CNW_LOGD("queueBuffer: E");
@@ -482,17 +484,18 @@ GonkNativeWindow::getCurrentBuffer() {
   CNW_LOGD("getCurrentBuffer: buf=%d", buf);
 
   mSlots[buf].mBufferState = BufferSlot::RENDERING;
 
   mQueue.erase(front);
   mDequeueCondition.signal();
 
   mSlots[buf].mTextureClient->SetRecycleCallback(GonkNativeWindow::RecycleCallback, this);
-  return mSlots[buf].mTextureClient;
+  RefPtr<TextureClient> client(mSlots[buf].mTextureClient);
+  return client.forget();
 }
 
 
 /* static */ void
 GonkNativeWindow::RecycleCallback(TextureClient* client, void* closure) {
   GonkNativeWindow* nativeWindow =
     static_cast<GonkNativeWindow*>(closure);
 
--- a/widget/gonk/nativewindow/GonkNativeWindowJB.cpp
+++ b/widget/gonk/nativewindow/GonkNativeWindowJB.cpp
@@ -120,18 +120,18 @@ GonkNativeWindow::getCurrentBuffer() {
         return NULL;
     }
 
     RefPtr<TextureClient> textureClient =
       mBufferQueue->getTextureClientFromBuffer(item.mGraphicBuffer.get());
     if (!textureClient) {
         return NULL;
     }
-  textureClient->SetRecycleCallback(GonkNativeWindow::RecycleCallback, this);
-  return textureClient;
+    textureClient->SetRecycleCallback(GonkNativeWindow::RecycleCallback, this);
+    return textureClient.forget();
 }
 
 /* static */ void
 GonkNativeWindow::RecycleCallback(TextureClient* client, void* closure) {
   GonkNativeWindow* nativeWindow =
     static_cast<GonkNativeWindow*>(closure);
 
   client->ClearRecycleCallback();
--- a/widget/gonk/nativewindow/GonkNativeWindowKK.cpp
+++ b/widget/gonk/nativewindow/GonkNativeWindowKK.cpp
@@ -120,18 +120,18 @@ GonkNativeWindow::getCurrentBuffer() {
         return NULL;
     }
 
     RefPtr<TextureClient> textureClient =
       mConsumer->getTextureClientFromBuffer(item.mGraphicBuffer.get());
     if (!textureClient) {
         return NULL;
     }
-  textureClient->SetRecycleCallback(GonkNativeWindow::RecycleCallback, this);
-  return textureClient;
+    textureClient->SetRecycleCallback(GonkNativeWindow::RecycleCallback, this);
+    return textureClient.forget();
 }
 
 /* static */ void
 GonkNativeWindow::RecycleCallback(TextureClient* client, void* closure) {
   GonkNativeWindow* nativeWindow =
     static_cast<GonkNativeWindow*>(closure);
 
   client->ClearRecycleCallback();
--- a/widget/gonk/nativewindow/GonkNativeWindowLL.cpp
+++ b/widget/gonk/nativewindow/GonkNativeWindowLL.cpp
@@ -132,17 +132,17 @@ GonkNativeWindow::getCurrentBuffer() {
     }
 
     RefPtr<TextureClient> textureClient =
         mConsumer->getTextureClientFromBuffer(item.mGraphicBuffer.get());
     if (!textureClient) {
         return NULL;
     }
     textureClient->SetRecycleCallback(GonkNativeWindow::RecycleCallback, this);
-    return textureClient;
+    return textureClient.forget();
 }
 
 /* static */ void
 GonkNativeWindow::RecycleCallback(TextureClient* client, void* closure) {
     GonkNativeWindow* nativeWindow =
         static_cast<GonkNativeWindow*>(closure);
 
     client->ClearRecycleCallback();
--- a/widget/gonk/nsWindow.cpp
+++ b/widget/gonk/nsWindow.cpp
@@ -723,17 +723,18 @@ nsWindow::StartRemoteDrawing()
         MOZ_CRASH("nsWindow::StartRemoteDrawing failed in CreateDrawTargetForData");
     }
     if (!mBackBuffer ||
         mBackBuffer->GetSize() != mFramebufferTarget->GetSize() ||
         mBackBuffer->GetFormat() != mFramebufferTarget->GetFormat()) {
         mBackBuffer = mFramebufferTarget->CreateSimilarDrawTarget(
             mFramebufferTarget->GetSize(), mFramebufferTarget->GetFormat());
     }
-    return mBackBuffer;
+    RefPtr<DrawTarget> buffer(mBackBuffer);
+    return buffer.forget();
 }
 
 void
 nsWindow::EndRemoteDrawing()
 {
     if (mFramebufferTarget) {
         IntSize size = mFramebufferTarget->GetSize();
         Rect rect(0, 0, size.width, size.height);