Bug 1493737 - Fix many trivial calls to do_QueryInterface r=smaug
authorAndrew McCreight <continuation@gmail.com>
Mon, 01 Oct 2018 21:38:01 +0000
changeset 494841 93b4642d28ab55fb3ba1bc41dfe47916828abcd3
parent 494840 425d54d1ad00d4c6f13bee902311c10de82cac4f
child 494842 7764656611ce25659b5fc408ce72007623545d69
push id9984
push userffxbld-merge
push dateMon, 15 Oct 2018 21:07:35 +0000
treeherdermozilla-beta@183d27ea8570 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerssmaug
bugs1493737
milestone64.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1493737 - Fix many trivial calls to do_QueryInterface r=smaug If class A is derived from class B, then an instance of class A can be converted to B via a static cast, so a slower QI is not needed. Differential Revision: https://phabricator.services.mozilla.com/D6861
docshell/base/nsDocShell.cpp
dom/base/DocGroup.cpp
dom/base/EventSource.cpp
dom/base/ImageEncoder.cpp
dom/base/InProcessTabChildMessageManager.cpp
dom/base/ScreenOrientation.cpp
dom/base/nsContentPermissionHelper.cpp
dom/base/nsFocusManager.cpp
dom/base/nsHistory.cpp
dom/base/nsRange.cpp
dom/broadcastchannel/BroadcastChannelChild.cpp
dom/events/Event.cpp
dom/events/EventDispatcher.cpp
dom/events/EventStateManager.cpp
dom/file/FileReaderSync.cpp
dom/html/ImageDocument.cpp
dom/ipc/ContentParent.cpp
dom/ipc/TabParent.cpp
dom/media/eme/MediaKeySession.cpp
dom/payments/PaymentRequestService.cpp
dom/plugins/base/nsPluginHost.cpp
dom/plugins/base/nsPluginInstanceOwner.cpp
dom/security/FramingChecker.cpp
dom/security/SRICheck.cpp
dom/serviceworkers/ServiceWorkerPrivate.cpp
dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp
dom/vr/VRDisplay.cpp
dom/webauthn/U2FTokenManager.cpp
dom/workers/MessageEventRunnable.cpp
dom/xbl/nsXBLService.cpp
dom/xhr/XMLHttpRequestMainThread.cpp
dom/xul/XULDocument.cpp
editor/libeditor/EditorBase.cpp
editor/libeditor/HTMLEditor.cpp
editor/libeditor/TextEditorTest.cpp
editor/spellchecker/EditorSpellCheck.cpp
extensions/permissions/nsContentBlocker.cpp
image/DecodePool.cpp
image/decoders/icon/nsIconURI.cpp
image/imgRequestProxy.cpp
image/imgTools.cpp
ipc/glue/ScopedXREEmbed.cpp
layout/base/PresShell.cpp
layout/base/TouchManager.cpp
layout/base/nsDocumentViewer.cpp
layout/base/nsPresContext.cpp
layout/style/ImageLoader.cpp
netwerk/base/nsIncrementalDownload.cpp
netwerk/base/nsSecCheckWrapChannel.cpp
netwerk/cache/nsDiskCacheDevice.cpp
netwerk/cache/nsDiskCacheDeviceSQL.cpp
netwerk/protocol/http/HttpChannelParentListener.cpp
netwerk/protocol/http/nsHttpChannelAuthProvider.cpp
netwerk/protocol/http/nsHttpTransaction.cpp
netwerk/protocol/websocket/BaseWebSocketChannel.cpp
netwerk/test/gtest/TestMIMEInputStream.cpp
security/manager/ssl/nsKeygenHandler.cpp
security/manager/ssl/nsSecureBrowserUIImpl.cpp
startupcache/StartupCache.cpp
toolkit/components/places/FaviconHelpers.cpp
toolkit/components/places/nsNavHistoryResult.cpp
toolkit/components/printingui/ipc/PrintingParent.cpp
toolkit/components/satchel/nsFormFillController.cpp
toolkit/xre/nsAppRunner.cpp
toolkit/xre/nsXREDirProvider.cpp
uriloader/base/nsDocLoader.cpp
uriloader/exthandler/nsExternalHelperAppService.cpp
widget/gtk/nsPrintDialogGTK.cpp
widget/nsBaseDragService.cpp
widget/nsSoundProxy.cpp
xpcom/ds/nsStringEnumerator.cpp
xpcom/threads/SharedThreadPool.cpp
xpfe/appshell/nsWebShellWindow.cpp
xpfe/appshell/nsXULWindow.cpp
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -3827,17 +3827,17 @@ nsDocShell::AddChildSHEntryInternal(nsIS
     if (index < 0) {
       return NS_ERROR_FAILURE;
     }
 
     rv = mSessionHistory->LegacySHistory()->GetEntryAtIndex(
       index, getter_AddRefs(currentHE));
     NS_ENSURE_TRUE(currentHE, NS_ERROR_FAILURE);
 
-    nsCOMPtr<nsISHEntry> currentEntry(do_QueryInterface(currentHE));
+    nsCOMPtr<nsISHEntry> currentEntry(currentHE);
     if (currentEntry) {
       nsCOMPtr<nsISHEntry> nextEntry;
       uint32_t cloneID = aCloneRef->GetID();
       rv = nsSHistory::CloneAndReplace(currentEntry, this, cloneID,
         aNewEntry, aCloneChildren, getter_AddRefs(nextEntry));
 
       if (NS_SUCCEEDED(rv)) {
         rv = mSessionHistory->LegacySHistory()->AddEntry(nextEntry, true);
@@ -6626,21 +6626,17 @@ nsDocShell::SuspendRefreshURIs()
       }
 
       // Replace this timer object with a nsRefreshTimer object.
       nsCOMPtr<nsITimerCallback> callback;
       timer->GetCallback(getter_AddRefs(callback));
 
       timer->Cancel();
 
-      nsCOMPtr<nsITimerCallback> rt = do_QueryInterface(callback);
-      NS_ASSERTION(rt,
-                   "RefreshURIList timer callbacks should only be RefreshTimer objects");
-
-      mRefreshURIList->ReplaceElementAt(rt, i);
+      mRefreshURIList->ReplaceElementAt(callback, i);
     }
   }
 
   // Suspend refresh URIs for our child shells as well.
   nsTObserverArray<nsDocLoader*>::ForwardIterator iter(mChildList);
   while (iter.HasMore()) {
     nsCOMPtr<nsIDocShell> shell = do_QueryObject(iter.GetNext());
     if (shell) {
@@ -9496,17 +9492,17 @@ nsDocShell::InternalLoad(nsIURI* aURI,
       rv = win->OpenNoNavigate(NS_ConvertUTF8toUTF16(spec),
                                aWindowTarget,  // window name
                                EmptyString(), // Features
                                getter_AddRefs(newWin));
 
       // In some cases the Open call doesn't actually result in a new
       // window being opened.  We can detect these cases by examining the
       // document in |newWin|, if any.
-      nsCOMPtr<nsPIDOMWindowOuter> piNewWin = do_QueryInterface(newWin);
+      nsCOMPtr<nsPIDOMWindowOuter> piNewWin = newWin;
       if (piNewWin) {
         nsCOMPtr<nsIDocument> newDoc = piNewWin->GetExtantDoc();
         if (!newDoc || newDoc->IsInitialDocument()) {
           isNewWindow = true;
           aFlags |= INTERNAL_LOAD_FLAGS_FIRST_LOAD;
         }
       }
 
--- a/dom/base/DocGroup.cpp
+++ b/dom/base/DocGroup.cpp
@@ -81,17 +81,17 @@ DocGroup::ReportPerformanceInfo()
   uint64_t windowID = 0;
   uint16_t count = 0;
   uint64_t duration = 0;
   bool isTopLevel = false;
   nsCString host;
 
   // iterating on documents until we find the top window
   for (const auto& document : *this) {
-    nsCOMPtr<nsIDocument> doc = do_QueryInterface(document);
+    nsCOMPtr<nsIDocument> doc = document;
     MOZ_ASSERT(doc);
     nsCOMPtr<nsIURI> docURI = doc->GetDocumentURI();
     if (!docURI) {
       continue;
     }
     docURI->GetHost(host);
     // If the host is empty, using the url
     if (host.IsEmpty()) {
--- a/dom/base/EventSource.cpp
+++ b/dom/base/EventSource.cpp
@@ -839,17 +839,17 @@ EventSourceImpl::AsyncOnChannelRedirect(
                                         nsIChannel* aNewChannel,
                                         uint32_t aFlags,
                                         nsIAsyncVerifyRedirectCallback* aCallback)
 {
   AssertIsOnMainThread();
   if (IsClosed()) {
     return NS_ERROR_ABORT;
   }
-  nsCOMPtr<nsIRequest> aOldRequest = do_QueryInterface(aOldChannel);
+  nsCOMPtr<nsIRequest> aOldRequest = aOldChannel;
   MOZ_ASSERT(aOldRequest, "Redirect from a null request?");
 
   nsresult rv = CheckHealthOfRequestCallback(aOldRequest);
   NS_ENSURE_SUCCESS(rv, rv);
 
   MOZ_ASSERT(aNewChannel, "Redirect without a channel?");
 
   nsCOMPtr<nsIURI> newURI;
--- a/dom/base/ImageEncoder.cpp
+++ b/dom/base/ImageEncoder.cpp
@@ -452,17 +452,17 @@ ImageEncoder::ExtractDataInternal(const 
                                   aSize.height,
                                   aSize.width * 4,
                                   imgIEncoder::INPUT_FORMAT_HOSTARGB,
                                   aOptions);
       dataSurface->Unmap();
     }
 
     if (NS_SUCCEEDED(rv)) {
-      imgStream = do_QueryInterface(aEncoder);
+      imgStream = aEncoder;
     }
   } else {
     if (BufferSizeFromDimensions(aSize.width, aSize.height, 4) == 0) {
       return NS_ERROR_INVALID_ARG;
     }
 
     // no context, so we have to encode an empty image
     // note that if we didn't have a current context, the spec says we're
@@ -488,17 +488,17 @@ ImageEncoder::ExtractDataInternal(const 
                                 aSize.width * aSize.height * 4,
                                 aSize.width,
                                 aSize.height,
                                 aSize.width * 4,
                                 imgIEncoder::INPUT_FORMAT_HOSTARGB,
                                 aOptions);
     emptyCanvas->Unmap();
     if (NS_SUCCEEDED(rv)) {
-      imgStream = do_QueryInterface(aEncoder);
+      imgStream = aEncoder;
     }
   }
   NS_ENSURE_SUCCESS(rv, rv);
 
   imgStream.forget(aStream);
   return rv;
 }
 
--- a/dom/base/InProcessTabChildMessageManager.cpp
+++ b/dom/base/InProcessTabChildMessageManager.cpp
@@ -186,17 +186,17 @@ InProcessTabChildMessageManager::GetTabE
 
 uint64_t
 InProcessTabChildMessageManager::ChromeOuterWindowID()
 {
   if (!mDocShell) {
     return 0;
   }
 
-  nsCOMPtr<nsIDocShellTreeItem> item = do_QueryInterface(mDocShell);
+  nsCOMPtr<nsIDocShellTreeItem> item = mDocShell;
   nsCOMPtr<nsIDocShellTreeItem> root;
   nsresult rv = item->GetRootTreeItem(getter_AddRefs(root));
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return 0;
   }
 
   nsPIDOMWindowOuter* topWin = root->GetWindow();
   if (!topWin) {
--- a/dom/base/ScreenOrientation.cpp
+++ b/dom/base/ScreenOrientation.cpp
@@ -353,17 +353,17 @@ bool
 ScreenOrientation::LockDeviceOrientation(hal::ScreenOrientation aOrientation,
                                          bool aIsFullscreen, ErrorResult& aRv)
 {
   if (!GetOwner()) {
     aRv.Throw(NS_ERROR_UNEXPECTED);
     return false;
   }
 
-  nsCOMPtr<EventTarget> target = do_QueryInterface(GetOwner()->GetDoc());
+  nsCOMPtr<EventTarget> target = GetOwner()->GetDoc();
   // We need to register a listener so we learn when we leave fullscreen
   // and when we will have to unlock the screen.
   // This needs to be done before LockScreenOrientation call to make sure
   // the locking can be unlocked.
   if (aIsFullscreen && !target) {
     return false;
   }
 
@@ -399,17 +399,17 @@ ScreenOrientation::UnlockDeviceOrientati
   hal::UnlockScreenOrientation();
 
   if (!mFullscreenListener || !GetOwner()) {
     mFullscreenListener = nullptr;
     return;
   }
 
   // Remove event listener in case of fullscreen lock.
-  nsCOMPtr<EventTarget> target = do_QueryInterface(GetOwner()->GetDoc());
+  nsCOMPtr<EventTarget> target = GetOwner()->GetDoc();
   if (target) {
     target->RemoveSystemEventListener(NS_LITERAL_STRING("fullscreenchange"),
                                       mFullscreenListener,
                                       /* useCapture */ true);
   }
 
   mFullscreenListener = nullptr;
 }
--- a/dom/base/nsContentPermissionHelper.cpp
+++ b/dom/base/nsContentPermissionHelper.cpp
@@ -93,17 +93,17 @@ VisibilityChangeListener::HandleEvent(Ev
 void
 VisibilityChangeListener::RemoveListener()
 {
   nsCOMPtr<nsPIDOMWindowInner> window = do_QueryReferent(mWindow);
   if (!window) {
     return;
   }
 
-  nsCOMPtr<EventTarget> target = do_QueryInterface(window->GetExtantDoc());
+  nsCOMPtr<EventTarget> target = window->GetExtantDoc();
   if (target) {
     target->RemoveSystemEventListener(NS_LITERAL_STRING(kVisibilityChange),
                                       /* listener */ this,
                                       /* use capture */ true);
   }
 }
 
 void
--- a/dom/base/nsFocusManager.cpp
+++ b/dom/base/nsFocusManager.cpp
@@ -2362,21 +2362,21 @@ nsFocusManager::UpdateCaret(bool aMoveCa
   LOGFOCUS(("Update Caret: %d %d", aMoveCaretToFocus, aUpdateVisibility));
 
   if (!mFocusedWindow)
     return;
 
   // this is called when a document is focused or when the caretbrowsing
   // preference is changed
   nsCOMPtr<nsIDocShell> focusedDocShell = mFocusedWindow->GetDocShell();
-  nsCOMPtr<nsIDocShellTreeItem> dsti = do_QueryInterface(focusedDocShell);
-  if (!dsti)
+  if (!focusedDocShell) {
     return;
-
-  if (dsti->ItemType() == nsIDocShellTreeItem::typeChrome) {
+  }
+
+  if (focusedDocShell->ItemType() == nsIDocShellTreeItem::typeChrome) {
     return;  // Never browse with caret in chrome
   }
 
   bool browseWithCaret =
     Preferences::GetBool("accessibility.browsewithcaret");
 
   nsCOMPtr<nsIPresShell> presShell = focusedDocShell->GetPresShell();
   if (!presShell)
--- a/dom/base/nsHistory.cpp
+++ b/dom/base/nsHistory.cpp
@@ -121,18 +121,17 @@ nsHistory::GetState(JSContext* aCx, JS::
     return;
   }
 
   if (!win->HasActiveDocument()) {
     aRv.Throw(NS_ERROR_DOM_SECURITY_ERR);
     return;
   }
 
-  nsCOMPtr<nsIDocument> doc =
-    do_QueryInterface(win->GetExtantDoc());
+  nsCOMPtr<nsIDocument> doc = win->GetExtantDoc();
   if (!doc) {
     aRv.Throw(NS_ERROR_NOT_AVAILABLE);
     return;
   }
 
   nsCOMPtr<nsIVariant> variant;
   doc->GetStateObject(getter_AddRefs(variant));
 
--- a/dom/base/nsRange.cpp
+++ b/dom/base/nsRange.cpp
@@ -2523,17 +2523,17 @@ nsRange::CloneContents(ErrorResult& aRv)
 
       if (aRv.Failed()) {
         return nullptr;
       }
     }
 
     // Place the cloned subtree into the cloned doc frag tree!
 
-    nsCOMPtr<nsINode> cloneNode = do_QueryInterface(clone);
+    nsCOMPtr<nsINode> cloneNode = clone;
     if (closestAncestor)
     {
       // Append the subtree under closestAncestor since it is the
       // immediate parent of the subtree.
 
       closestAncestor->AppendChild(*cloneNode, aRv);
     }
     else
@@ -2647,17 +2647,17 @@ nsRange::InsertNode(nsINode& aNode, Erro
       return;
     }
 
     RefPtr<Text> secondPart = startTextNode->SplitText(tStartOffset, aRv);
     if (aRv.Failed()) {
       return;
     }
 
-    referenceNode = do_QueryInterface(secondPart);
+    referenceNode = secondPart;
   } else {
     tChildList = tStartContainer->ChildNodes();
 
     // find the insertion point in the DOM and insert the Node
     referenceNode = tChildList->Item(tStartOffset);
 
     tStartContainer->EnsurePreInsertionValidity(aNode, referenceNode, aRv);
     if (aRv.Failed()) {
--- a/dom/broadcastchannel/BroadcastChannelChild.cpp
+++ b/dom/broadcastchannel/BroadcastChannelChild.cpp
@@ -37,18 +37,17 @@ BroadcastChannelChild::~BroadcastChannel
 mozilla::ipc::IPCResult
 BroadcastChannelChild::RecvNotify(const ClonedMessageData& aData)
 {
   // Make sure to retrieve all blobs from the message before returning to avoid
   // leaking their actors.
   ipc::StructuredCloneDataNoTransfers cloneData;
   cloneData.BorrowFromClonedMessageDataForBackgroundChild(aData);
 
-  nsCOMPtr<DOMEventTargetHelper> helper = mBC;
-  nsCOMPtr<EventTarget> eventTarget = do_QueryInterface(helper);
+  nsCOMPtr<EventTarget> eventTarget = mBC;
 
   // The object is going to be deleted soon. No notify is required.
   if (!eventTarget) {
     return IPC_OK();
   }
 
   // CheckInnerWindowCorrectness can be used also without a window when
   // BroadcastChannel is running in a worker. In this case, it's a NOP.
@@ -57,17 +56,17 @@ BroadcastChannelChild::RecvNotify(const 
   }
 
   mBC->RemoveDocFromBFCache();
 
   AutoJSAPI jsapi;
   nsCOMPtr<nsIGlobalObject> globalObject;
 
   if (NS_IsMainThread()) {
-    globalObject = do_QueryInterface(mBC->GetParentObject());
+    globalObject = mBC->GetParentObject();
   } else {
     WorkerPrivate* workerPrivate = GetCurrentThreadWorkerPrivate();
     MOZ_ASSERT(workerPrivate);
     globalObject = workerPrivate->GlobalScope();
   }
 
   if (!globalObject || !jsapi.Init(globalObject)) {
     NS_WARNING("Failed to initialize AutoJSAPI object.");
--- a/dom/events/Event.cpp
+++ b/dom/events/Event.cpp
@@ -473,17 +473,17 @@ Event::EnsureWebAccessibleRelatedTarget(
 {
   nsCOMPtr<EventTarget> relatedTarget = aRelatedTarget;
   if (relatedTarget) {
     nsCOMPtr<nsIContent> content = do_QueryInterface(relatedTarget);
 
     if (content && content->ChromeOnlyAccess() &&
         !nsContentUtils::CanAccessNativeAnon()) {
       content = content->FindFirstNonChromeOnlyAccessContent();
-      relatedTarget = do_QueryInterface(content);
+      relatedTarget = content;
     }
 
     if (relatedTarget) {
       relatedTarget = relatedTarget->GetTargetForDOMEvent();
     }
   }
   return relatedTarget.forget();
 }
--- a/dom/events/EventDispatcher.cpp
+++ b/dom/events/EventDispatcher.cpp
@@ -866,17 +866,17 @@ EventDispatcher::Dispatch(nsISupports* a
   nsCOMPtr<EventTarget> target = do_QueryInterface(aTarget);
 
   bool retargeted = false;
 
   if (aEvent->mFlags.mRetargetToNonNativeAnonymous) {
     nsCOMPtr<nsIContent> content = do_QueryInterface(target);
     if (content && content->IsInNativeAnonymousSubtree()) {
       nsCOMPtr<EventTarget> newTarget =
-        do_QueryInterface(content->FindFirstNonChromeOnlyAccessContent());
+        content->FindFirstNonChromeOnlyAccessContent();
       NS_ENSURE_STATE(newTarget);
 
       aEvent->mOriginalTarget = target;
       target = newTarget;
       retargeted = true;
     }
   }
 
--- a/dom/events/EventStateManager.cpp
+++ b/dom/events/EventStateManager.cpp
@@ -493,17 +493,17 @@ EventStateManager::PreHandleEvent(nsPres
         mozilla::services::GetObserverService();
       if (obs) {
         obs->NotifyObservers(nullptr, "user-interaction-active", nullptr);
         UpdateUserActivityTimer();
       }
     }
     ++gMouseOrKeyboardEventCounter;
 
-    nsCOMPtr<nsINode> node = do_QueryInterface(aTargetContent);
+    nsCOMPtr<nsINode> node = aTargetContent;
     if (node &&
         (aEvent->mMessage == eKeyUp || aEvent->mMessage == eMouseUp ||
          aEvent->mMessage == eWheel || aEvent->mMessage == eTouchEnd ||
          aEvent->mMessage == ePointerUp)) {
       nsIDocument* doc = node->OwnerDoc();
       while (doc) {
         doc->SetUserHasInteracted();
         doc = nsContentUtils::IsChildOfSameType(doc) ?
@@ -869,17 +869,17 @@ EventStateManager::NotifyTargetUserActiv
     return;
   }
 
   WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
   if (mouseEvent && !mouseEvent->IsReal()) {
     return;
   }
 
-  nsCOMPtr<nsINode> node = do_QueryInterface(aTargetContent);
+  nsCOMPtr<nsINode> node = aTargetContent;
   if (!node) {
     return;
   }
 
   nsIDocument* doc = node->OwnerDoc();
   if (!doc || doc->HasBeenUserGestureActivated()) {
     return;
   }
@@ -4201,18 +4201,17 @@ EventStateManager::DispatchMouseOrPointe
        aMessage == eMouseOut)) {
     mCurrentTargetContent = nullptr;
     nsCOMPtr<Element> pointerLockedElement =
       do_QueryReferent(EventStateManager::sPointerLockedElement);
     if (!pointerLockedElement) {
       NS_WARNING("Should have pointer locked element, but didn't.");
       return nullptr;
     }
-    nsCOMPtr<nsIContent> content = do_QueryInterface(pointerLockedElement);
-    return mPresContext->GetPrimaryFrameFor(content);
+    return mPresContext->GetPrimaryFrameFor(pointerLockedElement);
   }
 
   mCurrentTargetContent = nullptr;
 
   if (!aTargetContent) {
     return nullptr;
   }
 
--- a/dom/file/FileReaderSync.cpp
+++ b/dom/file/FileReaderSync.cpp
@@ -305,18 +305,17 @@ FileReaderSync::ConvertStream(nsIInputSt
   nsCOMPtr<nsIConverterInputStream> converterStream =
     do_CreateInstance("@mozilla.org/intl/converter-input-stream;1");
   NS_ENSURE_TRUE(converterStream, NS_ERROR_FAILURE);
 
   nsresult rv = converterStream->Init(aStream, aCharset, 8192,
                   nsIConverterInputStream::DEFAULT_REPLACEMENT_CHARACTER);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  nsCOMPtr<nsIUnicharInputStream> unicharStream =
-    do_QueryInterface(converterStream);
+  nsCOMPtr<nsIUnicharInputStream> unicharStream = converterStream;
   NS_ENSURE_TRUE(unicharStream, NS_ERROR_FAILURE);
 
   uint32_t numChars;
   nsString result;
   while (NS_SUCCEEDED(unicharStream->ReadString(8192, result, &numChars)) &&
          numChars > 0) {
     uint32_t oldLength = aResult.Length();
     aResult.Append(result);
--- a/dom/html/ImageDocument.cpp
+++ b/dom/html/ImageDocument.cpp
@@ -235,17 +235,17 @@ ImageDocument::StartDocumentLoad(const c
   return NS_OK;
 }
 
 void
 ImageDocument::Destroy()
 {
   if (mImageContent) {
     // Remove our event listener from the image content.
-    nsCOMPtr<EventTarget> target = do_QueryInterface(mImageContent);
+    nsCOMPtr<EventTarget> target = mImageContent;
     target->RemoveEventListener(NS_LITERAL_STRING("load"), this, false);
     target->RemoveEventListener(NS_LITERAL_STRING("click"), this, false);
 
     // Break reference cycle with mImageContent, if we have one
     if (mObservingImageLoader) {
       nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mImageContent);
       if (imageLoader) {
         imageLoader->RemoveNativeObserver(this);
@@ -281,17 +281,17 @@ ImageDocument::SetScriptGlobalObject(nsI
       MOZ_ASSERT(!GetRootElement(), "Where did the root element come from?");
       // Create synthetic document
 #ifdef DEBUG
       nsresult rv =
 #endif
         CreateSyntheticDocument();
       NS_ASSERTION(NS_SUCCEEDED(rv), "failed to create synthetic document");
 
-      target = do_QueryInterface(mImageContent);
+      target = mImageContent;
       target->AddEventListener(NS_LITERAL_STRING("load"), this, false);
       target->AddEventListener(NS_LITERAL_STRING("click"), this, false);
     }
 
     target = do_QueryInterface(aScriptGlobalObject);
     target->AddEventListener(NS_LITERAL_STRING("resize"), this, false);
     target->AddEventListener(NS_LITERAL_STRING("keypress"), this, false);
 
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -4877,17 +4877,17 @@ ContentParent::CommonCreateWindow(PBrows
                             nsIWebBrowserChrome::CHROME_REMOTE_WINDOW;
   if (!!(aChromeFlags & badFlags)) {
     return IPC_FAIL(this, "Forbidden aChromeFlags passed");
   }
 
   TabParent* thisTabParent = TabParent::GetFrom(aThisTab);
   nsCOMPtr<nsIContent> frame;
   if (thisTabParent) {
-    frame = do_QueryInterface(thisTabParent->GetOwnerElement());
+    frame = thisTabParent->GetOwnerElement();
 
     if (NS_WARN_IF(thisTabParent->IsMozBrowser())) {
       return IPC_FAIL(this, "aThisTab is not a MozBrowser");
     }
   }
 
   nsCOMPtr<nsPIDOMWindowOuter> outerWin;
   if (frame) {
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -227,17 +227,17 @@ TabParent::CacheFrameLoader(nsFrameLoade
 /**
  * Will return nullptr if there is no outer window available for the
  * document hosting the owner element of this TabParent. Also will return
  * nullptr if that outer window is in the process of closing.
  */
 already_AddRefed<nsPIDOMWindowOuter>
 TabParent::GetParentWindowOuter()
 {
-  nsCOMPtr<nsIContent> frame = do_QueryInterface(GetOwnerElement());
+  nsCOMPtr<nsIContent> frame = GetOwnerElement();
   if (!frame) {
     return nullptr;
   }
 
   nsCOMPtr<nsPIDOMWindowOuter> parent = frame->OwnerDoc()->GetWindow();
   if (!parent || parent->Closed()) {
     return nullptr;
   }
@@ -580,17 +580,17 @@ TabParent::RecvDropLinks(nsTArray<nsStri
 }
 
 mozilla::ipc::IPCResult
 TabParent::RecvEvent(const RemoteDOMEvent& aEvent)
 {
   RefPtr<Event> event = aEvent.mEvent;
   NS_ENSURE_TRUE(event, IPC_OK());
 
-  nsCOMPtr<mozilla::dom::EventTarget> target = do_QueryInterface(mFrameElement);
+  nsCOMPtr<mozilla::dom::EventTarget> target = mFrameElement;
   NS_ENSURE_TRUE(target, IPC_OK());
 
   event->SetOwner(target);
 
   target->DispatchEvent(*event);
   return IPC_OK();
 }
 
@@ -1141,18 +1141,17 @@ TabParent::SendRealMouseEvent(WidgetMous
     : SendNormalPriorityRealMouseButtonEvent(aEvent, guid, blockId);
   NS_WARNING_ASSERTION(ret, "SendRealMouseButtonEvent() failed");
   MOZ_ASSERT(!ret || aEvent.HasBeenPostedToRemoteProcess());
 }
 
 LayoutDeviceToCSSScale
 TabParent::GetLayoutDeviceToCSSScale()
 {
-  nsCOMPtr<nsIContent> content = do_QueryInterface(mFrameElement);
-  nsIDocument* doc = (content ? content->OwnerDoc() : nullptr);
+  nsIDocument* doc = (mFrameElement ? mFrameElement->OwnerDoc() : nullptr);
   nsPresContext* ctx = (doc ? doc->GetPresContext() : nullptr);
   return LayoutDeviceToCSSScale(ctx
     ? (float)ctx->AppUnitsPerDevPixel() / AppUnitsPerCSSPixel()
     : 0.0f);
 }
 
 bool
 TabParent::QueryDropLinksForVerification()
@@ -2023,18 +2022,17 @@ TabParent::RecvOnWindowedPluginKeyEvent(
 mozilla::ipc::IPCResult
 TabParent::RecvRequestFocus(const bool& aCanRaise)
 {
   nsCOMPtr<nsIFocusManager> fm = nsFocusManager::GetFocusManager();
   if (!fm) {
     return IPC_OK();
   }
 
-  nsCOMPtr<nsIContent> content = do_QueryInterface(mFrameElement);
-  if (!content || !content->OwnerDoc()) {
+  if (!mFrameElement || !mFrameElement->OwnerDoc()) {
     return IPC_OK();
   }
 
   uint32_t flags = nsIFocusManager::FLAG_NOSCROLL;
   if (aCanRaise)
     flags |= nsIFocusManager::FLAG_RAISE;
 
   RefPtr<Element> element = mFrameElement;
@@ -2480,17 +2478,17 @@ TabParent::RecvSetInputContext(
 {
   IMEStateManager::SetInputContextForChildProcess(this, aContext, aAction);
   return IPC_OK();
 }
 
 already_AddRefed<nsIWidget>
 TabParent::GetTopLevelWidget()
 {
-  nsCOMPtr<nsIContent> content = do_QueryInterface(mFrameElement);
+  nsCOMPtr<nsIContent> content = mFrameElement;
   if (content) {
     nsIPresShell* shell = content->OwnerDoc()->GetShell();
     if (shell) {
       nsViewManager* vm = shell->GetViewManager();
       nsCOMPtr<nsIWidget> widget;
       vm->GetRootWidget(getter_AddRefs(widget));
       return widget.forget();
     }
@@ -2561,17 +2559,17 @@ TabParent::GetAuthPrompt(uint32_t aPromp
 {
   // we're either allowing auth, or it's a proxy request
   nsresult rv;
   nsCOMPtr<nsIPromptFactory> wwatch =
     do_GetService(NS_WINDOWWATCHER_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsCOMPtr<nsPIDOMWindowOuter> window;
-  nsCOMPtr<nsIContent> frame = do_QueryInterface(mFrameElement);
+  nsCOMPtr<nsIContent> frame = mFrameElement;
   if (frame)
     window = frame->OwnerDoc()->GetWindow();
 
   // Get an auth prompter for our window so that the parenting
   // of the dialogs works as it should when using tabs.
   nsCOMPtr<nsISupports> prompt;
   rv = wwatch->GetPrompt(window, iid, getter_AddRefs(prompt));
   NS_ENSURE_SUCCESS(rv, rv);
@@ -3075,17 +3073,17 @@ TabParent::LayerTreeUpdate(const LayersO
 {
   // Ignore updates from old epochs. They might tell us that layers are
   // available when we've already sent a message to clear them. We can't trust
   // the update in that case since layers could disappear anytime after that.
   if (aEpoch != mLayerTreeEpoch || mIsDestroyed) {
     return;
   }
 
-  nsCOMPtr<mozilla::dom::EventTarget> target = do_QueryInterface(mFrameElement);
+  nsCOMPtr<mozilla::dom::EventTarget> target = mFrameElement;
   if (!target) {
     NS_WARNING("Could not locate target for layer tree message.");
     return;
   }
 
   mHasLayers = aActive;
 
   RefPtr<Event> event = NS_NewDOMEvent(mFrameElement, nullptr, nullptr);
@@ -3108,17 +3106,17 @@ TabParent::RecvPaintWhileInterruptingJSN
   // the layers.
   LayerTreeUpdate(aEpoch, true);
   return IPC_OK();
 }
 
 mozilla::ipc::IPCResult
 TabParent::RecvRemotePaintIsReady()
 {
-  nsCOMPtr<mozilla::dom::EventTarget> target = do_QueryInterface(mFrameElement);
+  nsCOMPtr<mozilla::dom::EventTarget> target = mFrameElement;
   if (!target) {
     NS_WARNING("Could not locate target for MozAfterRemotePaint message.");
     return IPC_OK();
   }
 
   RefPtr<Event> event = NS_NewDOMEvent(mFrameElement, nullptr, nullptr);
   event->InitEvent(NS_LITERAL_STRING("MozAfterRemotePaint"), false, false);
   event->SetTrusted(true);
--- a/dom/media/eme/MediaKeySession.cpp
+++ b/dom/media/eme/MediaKeySession.cpp
@@ -617,17 +617,17 @@ uint32_t
 MediaKeySession::Token() const
 {
   return mToken;
 }
 
 already_AddRefed<DetailedPromise>
 MediaKeySession::MakePromise(ErrorResult& aRv, const nsACString& aName)
 {
-  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
+  nsCOMPtr<nsIGlobalObject> global = GetParentObject();
   if (!global) {
     NS_WARNING("Passed non-global to MediaKeys ctor!");
     aRv.Throw(NS_ERROR_UNEXPECTED);
     return nullptr;
   }
   return DetailedPromise::Create(global, aRv, aName);
 }
 
--- a/dom/payments/PaymentRequestService.cpp
+++ b/dom/payments/PaymentRequestService.cpp
@@ -56,19 +56,18 @@ PaymentRequestEnumerator::GetNext(nsISup
   if (NS_WARN_IF(!gPaymentService)) {
     return NS_ERROR_FAILURE;
   }
   RefPtr<payments::PaymentRequest> rowRequest =
     gPaymentService->GetPaymentRequestByIndex(mIndex);
   if (!rowRequest) {
     return NS_ERROR_FAILURE;
   }
-  nsCOMPtr<nsIPaymentRequest> request = do_QueryInterface(rowRequest);
   mIndex++;
-  request.forget(aItem);
+  rowRequest.forget(aItem);
   return NS_OK;
 }
 
 } // end of anonymous namespace
 
 /* PaymentRequestService */
 
 NS_IMPL_ISUPPORTS(PaymentRequestService,
@@ -109,18 +108,17 @@ PaymentRequestService::GetPaymentRequest
 {
   NS_ENSURE_ARG_POINTER(aRequest);
   *aRequest = nullptr;
   RefPtr<payments::PaymentRequest> rowRequest;
   nsresult rv = GetPaymentRequestById(aRequestId, getter_AddRefs(rowRequest));
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
-  nsCOMPtr<nsIPaymentRequest> request = do_QueryInterface(rowRequest);
-  request.forget(aRequest);
+  rowRequest.forget(aRequest);
   return NS_OK;
 }
 
 nsresult
 PaymentRequestService::GetPaymentRequestById(const nsAString& aRequestId,
                                              payments::PaymentRequest** aRequest)
 {
   NS_ENSURE_ARG_POINTER(aRequest);
--- a/dom/plugins/base/nsPluginHost.cpp
+++ b/dom/plugins/base/nsPluginHost.cpp
@@ -1861,17 +1861,17 @@ nsPluginHost::SiteHasData(nsIPluginTag* 
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   PluginLibrary* library = tag->mPlugin->GetLibrary();
 
   // Get the list of sites from the plugin
   nsCOMPtr<GetSitesClosure> closure(new GetSitesClosure(domain, this));
-  rv = library->NPP_GetSitesWithData(nsCOMPtr<nsIGetSitesWithDataCallback>(do_QueryInterface(closure)));
+  rv = library->NPP_GetSitesWithData(nsCOMPtr<nsIGetSitesWithDataCallback>(closure));
   NS_ENSURE_SUCCESS(rv, rv);
   // Spin the event loop while we wait for the async call to GetSitesWithData
   SpinEventLoopUntil([&]() { return !closure->keepWaiting; });
   *result = closure->result;
   return closure->retVal;
 }
 
 nsPluginHost::SpecialType
--- a/dom/plugins/base/nsPluginInstanceOwner.cpp
+++ b/dom/plugins/base/nsPluginInstanceOwner.cpp
@@ -459,17 +459,17 @@ NS_IMETHODIMP nsPluginInstanceOwner::Get
       return NS_ERROR_UNEXPECTED;
 
     nsCOMPtr<nsIStringInputStream> sis = do_CreateInstance("@mozilla.org/io/string-input-stream;1");
     if (!sis)
       return NS_ERROR_OUT_OF_MEMORY;
 
     rv = sis->SetData((char *)aHeadersData, aHeadersDataLen);
     NS_ENSURE_SUCCESS(rv, rv);
-    headersDataStream = do_QueryInterface(sis);
+    headersDataStream = sis;
   }
 
   int32_t blockPopups =
     Preferences::GetInt("privacy.popups.disable_from_plugins");
   nsAutoPopupStatePusher popupStatePusher((PopupControlState)blockPopups);
 
 
   // if security checks (in particular CheckLoadURIWithPrincipal) needs
--- a/dom/security/FramingChecker.cpp
+++ b/dom/security/FramingChecker.cpp
@@ -62,18 +62,17 @@ FramingChecker::CheckOneFrameOptionsPoli
   if (thisWindow == topWindow) {
     return true;
   }
 
   // Find the top docshell in our parent chain that doesn't have the system
   // principal and use it for the principal comparison.  Finding the top
   // content-type docshell doesn't work because some chrome documents are
   // loaded in content docshells (see bug 593387).
-  nsCOMPtr<nsIDocShellTreeItem> thisDocShellItem(
-    do_QueryInterface(static_cast<nsIDocShell*>(aDocShell)));
+  nsCOMPtr<nsIDocShellTreeItem> thisDocShellItem(aDocShell);
   nsCOMPtr<nsIDocShellTreeItem> parentDocShellItem;
   nsCOMPtr<nsIDocShellTreeItem> curDocShellItem = thisDocShellItem;
   nsCOMPtr<nsIDocument> topDoc;
   nsresult rv;
   nsCOMPtr<nsIScriptSecurityManager> ssm =
     do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
   if (!ssm) {
     MOZ_CRASH();
--- a/dom/security/SRICheck.cpp
+++ b/dom/security/SRICheck.cpp
@@ -328,18 +328,17 @@ SRICheckDataVerifier::Verify(const SRIMe
                              nsIChannel* aChannel,
                              const nsACString& aSourceFileURI,
                              nsIConsoleReportCollector* aReporter)
 {
   NS_ENSURE_ARG_POINTER(aReporter);
 
   if (MOZ_LOG_TEST(SRILogHelper::GetSriLog(), mozilla::LogLevel::Debug)) {
     nsAutoCString requestURL;
-    nsCOMPtr<nsIRequest> request;
-    request = do_QueryInterface(aChannel);
+    nsCOMPtr<nsIRequest> request = aChannel;
     request->GetName(requestURL);
     SRILOG(("SRICheckDataVerifier::Verify, url=%s (length=%zu)",
             requestURL.get(), mBytesHashed));
   }
 
   nsresult rv = Finish();
   NS_ENSURE_SUCCESS(rv, rv);
 
--- a/dom/serviceworkers/ServiceWorkerPrivate.cpp
+++ b/dom/serviceworkers/ServiceWorkerPrivate.cpp
@@ -2024,17 +2024,17 @@ ServiceWorkerPrivate::GetDebugger(nsIWor
   MOZ_ASSERT(aResult);
 
   if (!mDebuggerCount) {
     return NS_OK;
   }
 
   MOZ_ASSERT(mWorkerPrivate);
 
-  nsCOMPtr<nsIWorkerDebugger> debugger = do_QueryInterface(mWorkerPrivate->Debugger());
+  nsCOMPtr<nsIWorkerDebugger> debugger = mWorkerPrivate->Debugger();
   debugger.forget(aResult);
 
   return NS_OK;
 }
 
 nsresult
 ServiceWorkerPrivate::AttachDebugger()
 {
--- a/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp
+++ b/dom/serviceworkers/ServiceWorkerRegistrationInfo.cpp
@@ -237,35 +237,35 @@ ServiceWorkerRegistrationInfo::GetLastUp
   *_retval = mLastUpdateTime;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 ServiceWorkerRegistrationInfo::GetInstallingWorker(nsIServiceWorkerInfo **aResult)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  nsCOMPtr<nsIServiceWorkerInfo> info = do_QueryInterface(mInstallingWorker);
+  RefPtr<ServiceWorkerInfo> info = mInstallingWorker;
   info.forget(aResult);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 ServiceWorkerRegistrationInfo::GetWaitingWorker(nsIServiceWorkerInfo **aResult)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  nsCOMPtr<nsIServiceWorkerInfo> info = do_QueryInterface(mWaitingWorker);
+  RefPtr<ServiceWorkerInfo> info = mWaitingWorker;
   info.forget(aResult);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 ServiceWorkerRegistrationInfo::GetActiveWorker(nsIServiceWorkerInfo **aResult)
 {
   MOZ_ASSERT(NS_IsMainThread());
-  nsCOMPtr<nsIServiceWorkerInfo> info = do_QueryInterface(mActiveWorker);
+  RefPtr<ServiceWorkerInfo> info = mActiveWorker;
   info.forget(aResult);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 ServiceWorkerRegistrationInfo::GetWorkerByID(uint64_t aID, nsIServiceWorkerInfo **aResult)
 {
   MOZ_ASSERT(NS_IsMainThread());
--- a/dom/vr/VRDisplay.cpp
+++ b/dom/vr/VRDisplay.cpp
@@ -547,17 +547,17 @@ VRDisplay::OnPresentationGenerationChang
   ExitPresentInternal();
 }
 
 already_AddRefed<Promise>
 VRDisplay::RequestPresent(const nsTArray<VRLayer>& aLayers,
                           CallerType aCallerType,
                           ErrorResult& aRv)
 {
-  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
+  nsCOMPtr<nsIGlobalObject> global = GetParentObject();
   if (!global) {
     aRv.Throw(NS_ERROR_FAILURE);
     return nullptr;
   }
 
   RefPtr<Promise> promise = Promise::Create(global, aRv);
   NS_ENSURE_TRUE(!aRv.Failed(), nullptr);
 
@@ -621,17 +621,17 @@ VRDisplay::Observe(nsISupports* aSubject
 
   // This should not happen.
   return NS_ERROR_FAILURE;
 }
 
 already_AddRefed<Promise>
 VRDisplay::ExitPresent(ErrorResult& aRv)
 {
-  nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(GetParentObject());
+  nsCOMPtr<nsIGlobalObject> global = GetParentObject();
   if (!global) {
     aRv.Throw(NS_ERROR_FAILURE);
     return nullptr;
   }
 
 
   RefPtr<Promise> promise = Promise::Create(global, aRv);
   NS_ENSURE_TRUE(!aRv.Failed(), nullptr);
--- a/dom/webauthn/U2FTokenManager.cpp
+++ b/dom/webauthn/U2FTokenManager.cpp
@@ -239,17 +239,17 @@ U2FTokenManager::RunSendPromptNotificati
 {
   MOZ_ASSERT(NS_IsMainThread());
 
   nsCOMPtr<nsIObserverService> os = services::GetObserverService();
   if (NS_WARN_IF(!os)) {
     return;
   }
 
-  nsCOMPtr<nsIU2FTokenManager> self = do_QueryInterface(this);
+  nsCOMPtr<nsIU2FTokenManager> self = this;
   MOZ_ALWAYS_SUCCEEDS(os->NotifyObservers(self, "webauthn-prompt", aJSON.get()));
 }
 
 RefPtr<U2FTokenTransport>
 U2FTokenManager::GetTokenManagerImpl()
 {
   MOZ_ASSERT(U2FPrefManager::Get());
   mozilla::ipc::AssertIsOnBackgroundThread();
--- a/dom/workers/MessageEventRunnable.cpp
+++ b/dom/workers/MessageEventRunnable.cpp
@@ -26,17 +26,17 @@ MessageEventRunnable::MessageEventRunnab
 }
 
 bool
 MessageEventRunnable::DispatchDOMEvent(JSContext* aCx,
                                        WorkerPrivate* aWorkerPrivate,
                                        DOMEventTargetHelper* aTarget,
                                        bool aIsMainThread)
 {
-  nsCOMPtr<nsIGlobalObject> parent = do_QueryInterface(aTarget->GetParentObject());
+  nsCOMPtr<nsIGlobalObject> parent = aTarget->GetParentObject();
 
   // For some workers without window, parent is null and we try to find it
   // from the JS Context.
   if (!parent) {
     JS::Rooted<JSObject*> globalObject(aCx, JS::CurrentGlobalOrNull(aCx));
     if (NS_WARN_IF(!globalObject)) {
       return false;
     }
--- a/dom/xbl/nsXBLService.cpp
+++ b/dom/xbl/nsXBLService.cpp
@@ -644,17 +644,17 @@ nsXBLService::DetachGlobalKeyHandler(Eve
   nsCOMPtr<EventTarget> piTarget = aTarget;
   nsCOMPtr<nsIContent> contentNode(do_QueryInterface(aTarget));
   if (!contentNode) // detaching is only supported for content nodes
     return NS_ERROR_FAILURE;
 
   // Only attach if we're really in a document
   nsCOMPtr<nsIDocument> doc = contentNode->GetUncomposedDoc();
   if (doc)
-    piTarget = do_QueryInterface(doc);
+    piTarget = doc;
 
   if (!piTarget)
     return NS_ERROR_FAILURE;
 
   EventListenerManager* manager = piTarget->GetOrCreateListenerManager();
   if (!manager)
     return NS_ERROR_FAILURE;
 
--- a/dom/xhr/XMLHttpRequestMainThread.cpp
+++ b/dom/xhr/XMLHttpRequestMainThread.cpp
@@ -2255,17 +2255,17 @@ XMLHttpRequestMainThread::OnStopRequest(
 
     return NS_OK;
   }
 
   if (mIsHtml) {
     NS_ASSERTION(!mFlagSyncLooping,
       "We weren't supposed to support HTML parsing with XHR!");
     mParseEndListener = new nsXHRParseEndListener(this);
-    nsCOMPtr<EventTarget> eventTarget = do_QueryInterface(mResponseXML);
+    nsCOMPtr<EventTarget> eventTarget = mResponseXML;
     EventListenerManager* manager =
       eventTarget->GetOrCreateListenerManager();
     manager->AddEventListenerByType(mParseEndListener,
                                     kLiteralString_DOMContentLoaded,
                                     TrustedEventsAtSystemGroupBubble());
     return NS_OK;
   } else {
     mFlagParseBody = false;
--- a/dom/xul/XULDocument.cpp
+++ b/dom/xul/XULDocument.cpp
@@ -1817,18 +1817,17 @@ XULDocument::MaybeBroadcast()
             }
             return;
         }
         if (!mHandlingDelayedAttrChange) {
             mHandlingDelayedAttrChange = true;
             for (uint32_t i = 0; i < mDelayedAttrChangeBroadcasts.Length(); ++i) {
                 nsAtom* attrName = mDelayedAttrChangeBroadcasts[i].mAttrName;
                 if (mDelayedAttrChangeBroadcasts[i].mNeedsAttrChange) {
-                    nsCOMPtr<Element> listener =
-                        do_QueryInterface(mDelayedAttrChangeBroadcasts[i].mListener);
+                    nsCOMPtr<Element> listener = mDelayedAttrChangeBroadcasts[i].mListener;
                     const nsString& value = mDelayedAttrChangeBroadcasts[i].mAttr;
                     if (mDelayedAttrChangeBroadcasts[i].mSetAttr) {
                         listener->SetAttr(kNameSpaceID_None, attrName, value,
                                           true);
                     } else {
                         listener->UnsetAttr(kNameSpaceID_None, attrName,
                                             true);
                     }
@@ -2360,22 +2359,21 @@ XULDocument::CheckBroadcasterHookup(Elem
     ErrorResult domRv;
     AddBroadcastListenerFor(*broadcaster, *listener, attribute, domRv);
     if (domRv.Failed()) {
         return domRv.StealNSResult();
     }
 
     // Tell the world we succeeded
     if (MOZ_LOG_TEST(gXULLog, LogLevel::Debug)) {
-        nsCOMPtr<nsIContent> content =
-            do_QueryInterface(listener);
-
+        nsCOMPtr<nsIContent> content = listener;
         NS_ASSERTION(content != nullptr, "not an nsIContent");
-        if (! content)
+        if (!content) {
             return rv;
+        }
 
         nsAutoCString attributeC,broadcasteridC;
         LossyCopyUTF16toASCII(attribute, attributeC);
         LossyCopyUTF16toASCII(broadcasterID, broadcasteridC);
         MOZ_LOG(gXULLog, LogLevel::Debug,
                ("xul: broadcaster hookup <%s attribute='%s'> to %s",
                 nsAtomCString(content->NodeInfo()->NameAtom()).get(),
                 attributeC.get(),
--- a/editor/libeditor/EditorBase.cpp
+++ b/editor/libeditor/EditorBase.cpp
@@ -408,17 +408,17 @@ EditorBase::InstallEventListeners()
 {
   if (NS_WARN_IF(!IsInitialized()) || NS_WARN_IF(!mEventListener)) {
     return NS_ERROR_NOT_INITIALIZED;
   }
 
   // Initialize the event target.
   nsCOMPtr<nsIContent> rootContent = GetRoot();
   NS_ENSURE_TRUE(rootContent, NS_ERROR_NOT_AVAILABLE);
-  mEventTarget = do_QueryInterface(rootContent->GetParent());
+  mEventTarget = rootContent->GetParent();
   NS_ENSURE_TRUE(mEventTarget, NS_ERROR_NOT_AVAILABLE);
 
   nsresult rv = mEventListener->Connect(this);
   if (mComposition) {
     // Restart to handle composition with new editor contents.
     mComposition->StartHandlingComposition(this);
   }
   return rv;
--- a/editor/libeditor/HTMLEditor.cpp
+++ b/editor/libeditor/HTMLEditor.cpp
@@ -485,17 +485,17 @@ HTMLEditor::FindSelectionRoot(nsINode* a
   }
   content = aNode->AsContent();
 
   // XXX If we have readonly flag, shouldn't return the element which has
   // contenteditable="true"?  However, such case isn't there without chrome
   // permission script.
   if (IsReadonly()) {
     // We still want to allow selection in a readonly editor.
-    content = do_QueryInterface(GetRoot());
+    content = GetRoot();
     return content.forget();
   }
 
   if (!content->HasFlag(NODE_IS_EDITABLE)) {
     // If the content is in read-write state but is not editable itself,
     // return it as the selection root.
     if (content->IsElement() &&
         content->AsElement()->State().HasState(NS_EVENT_STATE_MOZ_READWRITE)) {
--- a/editor/libeditor/TextEditorTest.cpp
+++ b/editor/libeditor/TextEditorTest.cpp
@@ -37,17 +37,17 @@ TextEditorTest::~TextEditorTest()
 {
   printf("destroyed a TextEditorTest\n");
 }
 
 void TextEditorTest::Run(nsIEditor *aEditor, int32_t *outNumTests, int32_t *outNumTestsFailed)
 {
   if (!aEditor) return;
   mTextEditor = do_QueryInterface(aEditor);
-  mEditor = do_QueryInterface(aEditor);
+  mEditor = aEditor;
   RunUnitTest(outNumTests, outNumTestsFailed);
 }
 
 nsresult TextEditorTest::RunUnitTest(int32_t *outNumTests, int32_t *outNumTestsFailed)
 {
   NS_ENSURE_TRUE(outNumTests && outNumTestsFailed, NS_ERROR_NULL_POINTER);
 
   *outNumTests = 0;
--- a/editor/spellchecker/EditorSpellCheck.cpp
+++ b/editor/spellchecker/EditorSpellCheck.cpp
@@ -722,17 +722,17 @@ EditorSpellCheck::UpdateCurrentDictionar
   // Try to get topmost document's document element for embedded mail editor.
   uint32_t flags = 0;
   mEditor->GetFlags(&flags);
   if (flags & nsIPlaintextEditor::eEditorMailMask) {
     nsCOMPtr<nsIDocument> ownerDoc = rootContent->OwnerDoc();
     NS_ENSURE_TRUE(ownerDoc, NS_ERROR_FAILURE);
     nsIDocument* parentDoc = ownerDoc->GetParentDocument();
     if (parentDoc) {
-      rootContent = do_QueryInterface(parentDoc->GetDocumentElement());
+      rootContent = parentDoc->GetDocumentElement();
     }
   }
 
   if (!rootContent) {
     return NS_ERROR_FAILURE;
   }
 
   RefPtr<DictionaryFetcher> fetcher =
--- a/extensions/permissions/nsContentBlocker.cpp
+++ b/extensions/permissions/nsContentBlocker.cpp
@@ -226,17 +226,17 @@ nsContentBlocker::ShouldProcess(nsIURI  
 
   MOZ_ASSERT(contentType == nsContentUtils::InternalContentPolicyTypeToExternal(contentType),
              "We should only see external content policy types here.");
 
   // For loads where requesting context is chrome, we should just
   // accept.  Those are most likely toplevel loads in windows, and
   // chrome generally knows what it's doing anyway.
   nsCOMPtr<nsIDocShellTreeItem> item =
-    do_QueryInterface(NS_CP_GetDocShellFromContext(requestingContext));
+    NS_CP_GetDocShellFromContext(requestingContext);
 
   if (item && item->ItemType() == nsIDocShellTreeItem::typeChrome) {
     *aDecision = nsIContentPolicy::ACCEPT;
     return NS_OK;
   }
 
   // For objects, we only check policy in shouldProcess, as the final type isn't
   // determined until the channel is open -- We don't want to block images in
--- a/image/DecodePool.cpp
+++ b/image/DecodePool.cpp
@@ -481,14 +481,14 @@ DecodePool::SyncRunIfPossible(IDecodingT
 
   aTask->Run();
 }
 
 already_AddRefed<nsIEventTarget>
 DecodePool::GetIOEventTarget()
 {
   MutexAutoLock threadPoolLock(mMutex);
-  nsCOMPtr<nsIEventTarget> target = do_QueryInterface(mIOThread);
+  nsCOMPtr<nsIEventTarget> target = mIOThread;
   return target.forget();
 }
 
 } // namespace image
 } // namespace mozilla
--- a/image/decoders/icon/nsIconURI.cpp
+++ b/image/decoders/icon/nsIconURI.cpp
@@ -708,17 +708,17 @@ nsMozIconURI::Deserialize(const URIParam
   mIconState = params.iconState();
 
   return true;
 }
 
 NS_IMETHODIMP
 nsMozIconURI::GetInnerURI(nsIURI** aURI)
 {
-  nsCOMPtr<nsIURI> iconURL = do_QueryInterface(mIconURL);
+  nsCOMPtr<nsIURI> iconURL = mIconURL;
   if (!iconURL) {
     *aURI = nullptr;
     return NS_ERROR_FAILURE;
   }
 
   iconURL.forget(aURI);
   return NS_OK;
 }
--- a/image/imgRequestProxy.cpp
+++ b/image/imgRequestProxy.cpp
@@ -715,17 +715,17 @@ imgRequestProxy::GetImage(imgIContainer*
   NS_ENSURE_TRUE(aImage, NS_ERROR_NULL_POINTER);
   // It's possible that our owner has an image but hasn't notified us of it -
   // that'll happen if we get Canceled before the owner instantiates its image
   // (because Canceling unregisters us as a listener on mOwner). If we're
   // in that situation, just grab the image off of mOwner.
   RefPtr<Image> image = GetImage();
   nsCOMPtr<imgIContainer> imageToReturn;
   if (image) {
-    imageToReturn = do_QueryInterface(image);
+    imageToReturn = image;
   }
   if (!imageToReturn && GetOwner()) {
     imageToReturn = GetOwner()->GetImage();
   }
   if (!imageToReturn) {
     return NS_ERROR_FAILURE;
   }
 
--- a/image/imgTools.cpp
+++ b/image/imgTools.cpp
@@ -69,17 +69,17 @@ public:
       // Let the Image know we've sent all the data.
       mImage->OnImageDataComplete(nullptr, nullptr, mStatus, true);
 
       RefPtr<ProgressTracker> tracker = mImage->GetProgressTracker();
       tracker->SyncNotifyProgress(FLAG_LOAD_COMPLETE);
 
       nsCOMPtr<imgIContainer> container;
       if (NS_SUCCEEDED(mStatus)) {
-        container = do_QueryInterface(mImage);
+        container = mImage;
       }
 
       mCallback->OnImageReady(container, mStatus);
       return NS_OK;
     }
 
     uint64_t length;
     nsresult rv = mInputStream->Available(&length);
--- a/ipc/glue/ScopedXREEmbed.cpp
+++ b/ipc/glue/ScopedXREEmbed.cpp
@@ -51,17 +51,17 @@ ScopedXREEmbed::Start()
   if (NS_FAILED(rv))
     return;
 
   nsCOMPtr<nsIFile> parent;
   rv = localFile->GetParent(getter_AddRefs(parent));
   if (NS_FAILED(rv))
     return;
 
-  localFile = do_QueryInterface(parent);
+  localFile = parent;
   NS_ENSURE_TRUE_VOID(localFile);
 
 #ifdef OS_MACOSX
   if (XRE_IsContentProcess()) {
     // We're an XPCOM-using subprocess.  Walk out of
     // [subprocess].app/Contents/MacOS to the real GRE dir.
     rv = localFile->GetParent(getter_AddRefs(parent));
     if (NS_FAILED(rv))
--- a/layout/base/PresShell.cpp
+++ b/layout/base/PresShell.cpp
@@ -7954,19 +7954,19 @@ PresShell::DispatchEventToDOM(WidgetEven
   nsPresShellEventCB* eventCBPtr = aEventCB;
   if (!eventTarget) {
     nsCOMPtr<nsIContent> targetContent;
     if (mCurrentEventFrame) {
       rv = mCurrentEventFrame->
              GetContentForEvent(aEvent, getter_AddRefs(targetContent));
     }
     if (NS_SUCCEEDED(rv) && targetContent) {
-      eventTarget = do_QueryInterface(targetContent);
+      eventTarget = targetContent;
     } else if (mDocument) {
-      eventTarget = do_QueryInterface(mDocument);
+      eventTarget = mDocument;
       // If we don't have any content, the callback wouldn't probably
       // do nothing.
       eventCBPtr = nullptr;
     }
   }
   if (eventTarget) {
     if (aEvent->IsBlockedForFingerprintingResistance()) {
       aEvent->mFlags.mOnlySystemGroupDispatchInContent = true;
--- a/layout/base/TouchManager.cpp
+++ b/layout/base/TouchManager.cpp
@@ -302,17 +302,17 @@ TouchManager::PreHandleEvent(WidgetEvent
 
         nsCOMPtr<EventTarget> targetPtr = oldTouch->mOriginalTarget;
         if (!targetPtr) {
           touches.RemoveElementAt(i);
           continue;
         }
         nsCOMPtr<nsINode> targetNode(do_QueryInterface(targetPtr));
         if (!targetNode->IsInComposedDoc()) {
-          targetPtr = do_QueryInterface(info.mNonAnonymousTarget);
+          targetPtr = info.mNonAnonymousTarget;
         }
         touch->SetTouchTarget(targetPtr);
 
         info.mTouch = touch;
         // info.mNonAnonymousTarget is still valid from above
         sCaptureTouchList->Put(id, info);
         // if we're moving from touchstart to touchmove for this touch
         // we allow preventDefault to prevent mouse events
@@ -367,17 +367,17 @@ TouchManager::PreHandleEvent(WidgetEvent
         int32_t id = touch->Identifier();
         TouchInfo info;
         if (!sCaptureTouchList->Get(id, &info)) {
           continue;
         }
         nsCOMPtr<EventTarget> targetPtr = info.mTouch->mOriginalTarget;
         nsCOMPtr<nsINode> targetNode(do_QueryInterface(targetPtr));
         if (targetNode && !targetNode->IsInComposedDoc()) {
-          targetPtr = do_QueryInterface(info.mNonAnonymousTarget);
+          targetPtr = info.mNonAnonymousTarget;
         }
 
         aCurrentEventContent = do_QueryInterface(targetPtr);
         touch->SetTouchTarget(targetPtr);
         sCaptureTouchList->Remove(id);
         if (info.mTouch->mIsTouchEventSuppressed) {
           touches.RemoveElementAt(i);
           continue;
--- a/layout/base/nsDocumentViewer.cpp
+++ b/layout/base/nsDocumentViewer.cpp
@@ -4279,28 +4279,28 @@ nsDocumentViewer::GetIsRangeSelection(bo
 
 //----------------------------------------------------------------------------------
 // Walks the document tree and tells each DocShell whether Printing/PP is happening
 void
 nsDocumentViewer::SetIsPrintingInDocShellTree(nsIDocShellTreeItem* aParentNode,
                                                 bool                 aIsPrintingOrPP,
                                                 bool                 aStartAtTop)
 {
-  nsCOMPtr<nsIDocShellTreeItem> parentItem(do_QueryInterface(aParentNode));
+  nsCOMPtr<nsIDocShellTreeItem> parentItem(aParentNode);
 
   // find top of "same parent" tree
   if (aStartAtTop) {
     if (aIsPrintingOrPP) {
       while (parentItem) {
         nsCOMPtr<nsIDocShellTreeItem> parent;
         parentItem->GetSameTypeParent(getter_AddRefs(parent));
         if (!parent) {
           break;
         }
-        parentItem = do_QueryInterface(parent);
+        parentItem = parent;
       }
       mTopContainerWhilePrinting = do_GetWeakReference(parentItem);
     } else {
       parentItem = do_QueryReferent(mTopContainerWhilePrinting);
     }
   }
 
   // Check to see if the DocShell's ContentViewer is printing/PP
@@ -4540,17 +4540,17 @@ nsDocumentViewer::OnDonePrinting()
       mPrintJob = nullptr;
       printJob->Destroy();
     }
 
     // We are done printing, now cleanup
     if (mDeferredWindowClose) {
       mDeferredWindowClose = false;
       if (mContainer) {
-        if (nsCOMPtr<nsPIDOMWindowOuter> win = do_QueryInterface(mContainer->GetWindow())) {
+        if (nsCOMPtr<nsPIDOMWindowOuter> win = mContainer->GetWindow()) {
           win->Close();
         }
       }
     } else if (mClosingWhilePrinting) {
       if (mDocument) {
         mDocument->Destroy();
         mDocument = nullptr;
       }
--- a/layout/base/nsPresContext.cpp
+++ b/layout/base/nsPresContext.cpp
@@ -2257,17 +2257,17 @@ nsPresContext::FireDOMPaintEvent(nsTArra
 
   nsCOMPtr<EventTarget> dispatchTarget = do_QueryInterface(ourWindow);
   nsCOMPtr<EventTarget> eventTarget = dispatchTarget;
   if (!IsChrome() && !mSendAfterPaintToContent) {
     // Don't tell the window about this event, it should not know that
     // something happened in a subdocument. Tell only the chrome event handler.
     // (Events sent to the window get propagated to the chrome event handler
     // automatically.)
-    dispatchTarget = do_QueryInterface(ourWindow->GetParentTarget());
+    dispatchTarget = ourWindow->GetParentTarget();
     if (!dispatchTarget) {
       return;
     }
   }
 
   if (aTimeStamp.IsNull()) {
     aTimeStamp = mozilla::TimeStamp::Now();
   }
--- a/layout/style/ImageLoader.cpp
+++ b/layout/style/ImageLoader.cpp
@@ -314,17 +314,17 @@ ImageLoader::SetAnimationMode(uint16_t a
                aMode == imgIContainer::kLoopOnceAnimMode,
                "Wrong Animation Mode is being set!");
 
   for (auto iter = mRequestToFrameMap.ConstIter(); !iter.Done(); iter.Next()) {
     auto request = static_cast<imgIRequest*>(iter.Key());
 
 #ifdef DEBUG
     {
-      nsCOMPtr<imgIRequest> debugRequest = do_QueryInterface(request);
+      nsCOMPtr<imgIRequest> debugRequest = request;
       NS_ASSERTION(debugRequest == request, "This is bad");
     }
 #endif
 
     nsCOMPtr<imgIContainer> container;
     request->GetImage(getter_AddRefs(container));
     if (!container) {
       continue;
@@ -338,17 +338,17 @@ ImageLoader::SetAnimationMode(uint16_t a
 void
 ImageLoader::ClearFrames(nsPresContext* aPresContext)
 {
   for (auto iter = mRequestToFrameMap.ConstIter(); !iter.Done(); iter.Next()) {
     auto request = static_cast<imgIRequest*>(iter.Key());
 
 #ifdef DEBUG
     {
-      nsCOMPtr<imgIRequest> debugRequest = do_QueryInterface(request);
+      nsCOMPtr<imgIRequest> debugRequest = request;
       NS_ASSERTION(debugRequest == request, "This is bad");
     }
 #endif
 
     if (aPresContext) {
       nsLayoutUtils::DeregisterImageRequest(aPresContext,
                                             request,
                                             nullptr);
--- a/netwerk/base/nsIncrementalDownload.cpp
+++ b/netwerk/base/nsIncrementalDownload.cpp
@@ -444,17 +444,17 @@ nsIncrementalDownload::SetLoadGroup(nsIL
 
 NS_IMETHODIMP
 nsIncrementalDownload::Init(nsIURI *uri, nsIFile *dest,
                             int32_t chunkSize, int32_t interval)
 {
   // Keep it simple: only allow initialization once
   NS_ENSURE_FALSE(mURI, NS_ERROR_ALREADY_INITIALIZED);
 
-  mDest = do_QueryInterface(dest);
+  mDest = dest;
   NS_ENSURE_ARG(mDest);
 
   mURI = uri;
   mFinalURI = uri;
 
   if (chunkSize > 0)
     mChunkSize = chunkSize;
   if (interval >= 0)
--- a/netwerk/base/nsSecCheckWrapChannel.cpp
+++ b/netwerk/base/nsSecCheckWrapChannel.cpp
@@ -33,17 +33,17 @@ NS_INTERFACE_MAP_END
 //---------------------------------------------------------
 // nsSecCheckWrapChannelBase implementation
 //---------------------------------------------------------
 
 nsSecCheckWrapChannelBase::nsSecCheckWrapChannelBase(nsIChannel* aChannel)
  : mChannel(aChannel)
  , mHttpChannel(do_QueryInterface(aChannel))
  , mHttpChannelInternal(do_QueryInterface(aChannel))
- , mRequest(do_QueryInterface(aChannel))
+ , mRequest(aChannel)
  , mUploadChannel(do_QueryInterface(aChannel))
  , mUploadChannel2(do_QueryInterface(aChannel))
 {
   MOZ_ASSERT(mChannel, "can not create a channel wrapper without a channel");
 }
 
 //---------------------------------------------------------
 // nsISecCheckWrapChannel implementation
--- a/netwerk/cache/nsDiskCacheDevice.cpp
+++ b/netwerk/cache/nsDiskCacheDevice.cpp
@@ -1074,17 +1074,17 @@ nsDiskCacheDevice::SetCacheParentDirecto
     // ensure cache directory exists
     nsCOMPtr<nsIFile> directory;
 
     rv = parentDir->Clone(getter_AddRefs(directory));
     if (NS_FAILED(rv))  return;
     rv = directory->AppendNative(NS_LITERAL_CSTRING("Cache"));
     if (NS_FAILED(rv))  return;
 
-    mCacheDirectory = do_QueryInterface(directory);
+    mCacheDirectory = directory;
 }
 
 
 void
 nsDiskCacheDevice::getCacheDirectory(nsIFile ** result)
 {
     *result = mCacheDirectory;
     NS_IF_ADDREF(*result);
--- a/netwerk/cache/nsDiskCacheDeviceSQL.cpp
+++ b/netwerk/cache/nsDiskCacheDeviceSQL.cpp
@@ -2860,17 +2860,17 @@ nsOfflineCacheDevice::SetCacheParentDire
   nsCOMPtr<nsIFile> dir;
   rv = parentDir->Clone(getter_AddRefs(dir));
   if (NS_FAILED(rv))
     return;
   rv = dir->AppendNative(NS_LITERAL_CSTRING("OfflineCache"));
   if (NS_FAILED(rv))
     return;
 
-  mCacheDirectory = do_QueryInterface(dir);
+  mCacheDirectory = dir;
 }
 
 void
 nsOfflineCacheDevice::SetCapacity(uint32_t capacity)
 {
   mCacheCapacity = capacity * 1024;
 }
 
--- a/netwerk/protocol/http/HttpChannelParentListener.cpp
+++ b/netwerk/protocol/http/HttpChannelParentListener.cpp
@@ -327,17 +327,17 @@ HttpChannelParentListener::OnRedirectRes
     // if we are actually changing channels.  During a service worker
     // interception internal redirect we preserve the same HttpChannelParent.
     if (!SameCOMIdentity(redirectChannel, mNextListener)) {
       nsCOMPtr<nsIParentChannel> parent;
       parent = do_QueryInterface(mNextListener);
       MOZ_ASSERT(parent);
       parent->Delete();
       mInterceptCanceled = false;
-      mNextListener = do_QueryInterface(redirectChannel);
+      mNextListener = redirectChannel;
       MOZ_ASSERT(mNextListener);
       redirectChannel->SetParentListener(this);
     }
   } else if (redirectChannel) {
     // Delete the redirect target channel: continue using old channel
     redirectChannel->Delete();
   }
 
--- a/netwerk/protocol/http/nsHttpChannelAuthProvider.cpp
+++ b/netwerk/protocol/http/nsHttpChannelAuthProvider.cpp
@@ -101,17 +101,17 @@ nsHttpChannelAuthProvider::Init(nsIHttpA
     mAuthChannel = channel;
 
     nsresult rv = mAuthChannel->GetURI(getter_AddRefs(mURI));
     if (NS_FAILED(rv)) return rv;
 
     rv = mAuthChannel->GetIsSSL(&mUsingSSL);
     if (NS_FAILED(rv)) return rv;
 
-    nsCOMPtr<nsIProxiedChannel> proxied(do_QueryInterface(channel));
+    nsCOMPtr<nsIProxiedChannel> proxied(channel);
     if (proxied) {
         nsCOMPtr<nsIProxyInfo> pi;
         rv = proxied->GetProxyInfo(getter_AddRefs(pi));
         if (NS_FAILED(rv)) return rv;
 
         if (pi) {
             nsAutoCString proxyType;
             rv = pi->GetType(proxyType);
--- a/netwerk/protocol/http/nsHttpTransaction.cpp
+++ b/netwerk/protocol/http/nsHttpTransaction.cpp
@@ -409,17 +409,17 @@ nsHttpTransaction::Init(uint32_t caps,
             nsCOMPtr<nsIAsyncInputStream> wrappedStream;
             rv = queue->WrapStream(mRequestStream, getter_AddRefs(wrappedStream));
             // Failure to throttle isn't sufficient reason to fail
             // initialization
             if (NS_SUCCEEDED(rv)) {
                 MOZ_ASSERT(wrappedStream != nullptr);
                 LOG(("nsHttpTransaction::Init %p wrapping input stream using throttle queue %p\n",
                      this, queue));
-                mRequestStream = do_QueryInterface(wrappedStream);
+                mRequestStream = wrappedStream;
             }
         }
     }
 
     // make sure request content-length fits within js MAX_SAFE_INTEGER
     mRequestSize = InScriptableRange(requestContentLength) ? static_cast<int64_t>(requestContentLength) : -1;
 
     // create pipe for response stream
--- a/netwerk/protocol/websocket/BaseWebSocketChannel.cpp
+++ b/netwerk/protocol/websocket/BaseWebSocketChannel.cpp
@@ -350,17 +350,17 @@ BaseWebSocketChannel::AllowPort(int32_t 
 NS_IMETHODIMP
 BaseWebSocketChannel::RetargetDeliveryTo(nsIEventTarget* aTargetThread)
 {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(aTargetThread);
   MOZ_ASSERT(!mTargetThread, "Delivery target should be set once, before AsyncOpen");
   MOZ_ASSERT(!mWasOpened, "Should not be called after AsyncOpen!");
 
-  mTargetThread = do_QueryInterface(aTargetThread);
+  mTargetThread = aTargetThread;
   MOZ_ASSERT(mTargetThread);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 BaseWebSocketChannel::GetDeliveryTarget(nsIEventTarget** aTargetThread)
 {
   MOZ_ASSERT(NS_IsMainThread());
--- a/netwerk/test/gtest/TestMIMEInputStream.cpp
+++ b/netwerk/test/gtest/TestMIMEInputStream.cpp
@@ -75,17 +75,17 @@ TEST(TestNsMIMEInputStream, QIInputStrea
       nsresult rv;
       nsCOMPtr<nsIMIMEInputStream> m(
         do_CreateInstance("@mozilla.org/network/mime-input-stream;1", &rv));
       ASSERT_EQ(NS_OK, rv);
 
       rv = m->SetData(stream);
       ASSERT_EQ(NS_OK, rv);
 
-      mis = do_QueryInterface(m);
+      mis = m;
       ASSERT_TRUE(!!mis);
     }
 
     {
       nsCOMPtr<nsIInputStreamLength> qi = do_QueryInterface(mis);
       ASSERT_EQ(!!(i % 2), !!qi);
     }
 
@@ -108,17 +108,17 @@ TEST(TestNsMIMEInputStream, InputStreamL
     nsresult rv;
     nsCOMPtr<nsIMIMEInputStream> m(
       do_CreateInstance("@mozilla.org/network/mime-input-stream;1", &rv));
     ASSERT_EQ(NS_OK, rv);
 
     rv = m->SetData(stream);
     ASSERT_EQ(NS_OK, rv);
 
-    mis = do_QueryInterface(m);
+    mis = m;
     ASSERT_TRUE(!!mis);
   }
 
   nsCOMPtr<nsIInputStreamLength> qi = do_QueryInterface(mis);
   ASSERT_TRUE(!!qi);
 
   int64_t size;
   nsresult rv = qi->Length(&size);
@@ -138,17 +138,17 @@ TEST(TestNsMIMEInputStream, NegativeInpu
     nsresult rv;
     nsCOMPtr<nsIMIMEInputStream> m(
       do_CreateInstance("@mozilla.org/network/mime-input-stream;1", &rv));
     ASSERT_EQ(NS_OK, rv);
 
     rv = m->SetData(stream);
     ASSERT_EQ(NS_OK, rv);
 
-    mis = do_QueryInterface(m);
+    mis = m;
     ASSERT_TRUE(!!mis);
   }
 
   nsCOMPtr<nsIInputStreamLength> qi = do_QueryInterface(mis);
   ASSERT_TRUE(!!qi);
 
   int64_t size;
   nsresult rv = qi->Length(&size);
@@ -168,17 +168,17 @@ TEST(TestNsMIMEInputStream, AsyncInputSt
     nsresult rv;
     nsCOMPtr<nsIMIMEInputStream> m(
       do_CreateInstance("@mozilla.org/network/mime-input-stream;1", &rv));
     ASSERT_EQ(NS_OK, rv);
 
     rv = m->SetData(stream);
     ASSERT_EQ(NS_OK, rv);
 
-    mis = do_QueryInterface(m);
+    mis = m;
     ASSERT_TRUE(!!mis);
   }
 
   nsCOMPtr<nsIAsyncInputStreamLength> qi = do_QueryInterface(mis);
   ASSERT_TRUE(!!qi);
 
   RefPtr<testing::LengthCallback> callback = new testing::LengthCallback();
 
@@ -201,17 +201,17 @@ TEST(TestNsMIMEInputStream, NegativeAsyn
     nsresult rv;
     nsCOMPtr<nsIMIMEInputStream> m(
       do_CreateInstance("@mozilla.org/network/mime-input-stream;1", &rv));
     ASSERT_EQ(NS_OK, rv);
 
     rv = m->SetData(stream);
     ASSERT_EQ(NS_OK, rv);
 
-    mis = do_QueryInterface(m);
+    mis = m;
     ASSERT_TRUE(!!mis);
   }
 
   nsCOMPtr<nsIAsyncInputStreamLength> qi = do_QueryInterface(mis);
   ASSERT_TRUE(!!qi);
 
   RefPtr<testing::LengthCallback> callback = new testing::LengthCallback();
 
@@ -234,17 +234,17 @@ TEST(TestNsMIMEInputStream, AbortLengthC
     nsresult rv;
     nsCOMPtr<nsIMIMEInputStream> m(
       do_CreateInstance("@mozilla.org/network/mime-input-stream;1", &rv));
     ASSERT_EQ(NS_OK, rv);
 
     rv = m->SetData(stream);
     ASSERT_EQ(NS_OK, rv);
 
-    mis = do_QueryInterface(m);
+    mis = m;
     ASSERT_TRUE(!!mis);
   }
 
   nsCOMPtr<nsIAsyncInputStreamLength> qi = do_QueryInterface(mis);
   ASSERT_TRUE(!!qi);
 
   RefPtr<testing::LengthCallback> callback1 = new testing::LengthCallback();
   nsresult rv = qi->AsyncLengthWait(callback1, GetCurrentThreadSerialEventTarget());
--- a/security/manager/ssl/nsKeygenHandler.cpp
+++ b/security/manager/ssl/nsKeygenHandler.cpp
@@ -539,17 +539,17 @@ nsKeygenFormProcessor::GetPublicKey(cons
     if (NS_FAILED(rv) || !KeygenRunnable) {
         rv = NS_OK;
         privateKey = PK11_GenerateKeyPairWithFlags(slot, keyGenMechanism, params,
                                                    &publicKey, attrFlags, m_ctx);
     } else {
         KeygenRunnable->SetParams( slot, attrFlags, nullptr, 0,
                                    keyGenMechanism, params, m_ctx );
 
-        runnable = do_QueryInterface(KeygenRunnable);
+        runnable = KeygenRunnable;
         if (runnable) {
             rv = dialogs->DisplayGeneratingKeypairInfo(m_ctx, runnable);
             // We call join on the thread so we can be sure that no
             // simultaneous access to the passed parameters will happen.
             KeygenRunnable->Join();
 
             if (NS_SUCCEEDED(rv)) {
                 PK11SlotInfo *used_slot = nullptr;
--- a/security/manager/ssl/nsSecureBrowserUIImpl.cpp
+++ b/security/manager/ssl/nsSecureBrowserUIImpl.cpp
@@ -132,17 +132,17 @@ nsSecureBrowserUIImpl::CheckForBlockedCo
   nsCOMPtr<nsIDocShell> docShell = do_QueryReferent(mDocShell);
   if (!docShell) {
     return;
   }
 
   // For content docShells, the mixed content security state is set on the root
   // docShell.
   if (docShell->ItemType() == nsIDocShellTreeItem::typeContent) {
-    nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem(do_QueryInterface(docShell));
+    nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem(docShell);
     nsCOMPtr<nsIDocShellTreeItem> sameTypeRoot;
     Unused << docShellTreeItem->GetSameTypeRootTreeItem(
       getter_AddRefs(sameTypeRoot));
     MOZ_ASSERT(
       sameTypeRoot,
       "No document shell root tree item from document shell tree item!");
     docShell = do_QueryInterface(sameTypeRoot);
     if (!docShell) {
--- a/startupcache/StartupCache.cpp
+++ b/startupcache/StartupCache.cpp
@@ -184,17 +184,17 @@ StartupCache::Init()
     rv = file->Create(nsIFile::DIRECTORY_TYPE, 0777);
     if (NS_FAILED(rv) && rv != NS_ERROR_FILE_ALREADY_EXISTS)
       return rv;
 
     rv = file->AppendNative(NS_LITERAL_CSTRING(STARTUP_CACHE_NAME));
 
     NS_ENSURE_SUCCESS(rv, rv);
 
-    mFile = do_QueryInterface(file);
+    mFile = file;
   }
 
   NS_ENSURE_TRUE(mFile, NS_ERROR_UNEXPECTED);
 
   mObserverService = do_GetService("@mozilla.org/observer-service;1");
 
   if (!mObserverService) {
     NS_WARNING("Could not get observerService.");
--- a/toolkit/components/places/FaviconHelpers.cpp
+++ b/toolkit/components/places/FaviconHelpers.cpp
@@ -1363,17 +1363,17 @@ FetchAndConvertUnsupportedPayloads::Conv
   }
   rv = encoder->InitFromData(map.mData, map.mStride * size, size, size,
                              map.mStride, imgIEncoder::INPUT_FORMAT_HOSTARGB,
                              EmptyString());
   targetDataSurface->Unmap();
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Read the stream into a new buffer.
-  nsCOMPtr<nsIInputStream> iconStream = do_QueryInterface(encoder);
+  nsCOMPtr<nsIInputStream> iconStream = encoder;
   NS_ENSURE_STATE(iconStream);
   rv = NS_ConsumeStream(iconStream, UINT32_MAX, aPayload);
   NS_ENSURE_SUCCESS(rv, rv);
 
   return NS_OK;
 }
 
 nsresult
--- a/toolkit/components/places/nsNavHistoryResult.cpp
+++ b/toolkit/components/places/nsNavHistoryResult.cpp
@@ -1928,27 +1928,27 @@ NS_IMETHODIMP
 nsNavHistoryQueryResultNode::GetTargetFolderGuid(nsACString& aGuid) {
   aGuid = EmptyCString();
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsNavHistoryQueryResultNode::GetQuery(nsINavHistoryQuery** _query)
 {
-  nsCOMPtr<nsINavHistoryQuery> query = do_QueryInterface(mQuery);
+  RefPtr<nsNavHistoryQuery> query = mQuery;
   query.forget(_query);
   return NS_OK;
 }
 
 
 NS_IMETHODIMP
 nsNavHistoryQueryResultNode::GetQueryOptions(nsINavHistoryQueryOptions** _options)
 {
   MOZ_ASSERT(mOptions, "Options should be valid");
-  nsCOMPtr<nsINavHistoryQueryOptions> options = do_QueryInterface(mOptions);
+  RefPtr<nsNavHistoryQueryOptions> options = mOptions;
   options.forget(_options);
   return NS_OK;
 }
 
 /**
  * Safe options getter, ensures query is parsed first.
  */
 nsNavHistoryQueryOptions*
@@ -3050,17 +3050,17 @@ nsNavHistoryFolderResultNode::GetQuery(n
 /**
  * Options for the query that gives you this bookmarks folder.  This is just
  * the options for the folder with the current folder ID set.
  */
 NS_IMETHODIMP
 nsNavHistoryFolderResultNode::GetQueryOptions(nsINavHistoryQueryOptions** _options)
 {
   MOZ_ASSERT(mOptions, "Options should be valid");
-  nsCOMPtr<nsINavHistoryQueryOptions> options = do_QueryInterface(mOptions);
+  RefPtr<nsNavHistoryQueryOptions> options = mOptions;
   options.forget(_options);
   return NS_OK;
 }
 
 
 nsresult
 nsNavHistoryFolderResultNode::FillChildren()
 {
--- a/toolkit/components/printingui/ipc/PrintingParent.cpp
+++ b/toolkit/components/printingui/ipc/PrintingParent.cpp
@@ -37,17 +37,17 @@ PrintingParent::RecvShowProgress(PBrowse
 {
   bool notifyOnOpen = false;
 
   nsCOMPtr<nsPIDOMWindowOuter> parentWin = DOMWindowFromBrowserParent(parent);
   nsCOMPtr<nsIPrintingPromptService> pps(do_GetService("@mozilla.org/embedcomp/printingprompt-service;1"));
 
   PrintProgressDialogParent* dialogParent =
     static_cast<PrintProgressDialogParent*>(printProgressDialog);
-  nsCOMPtr<nsIObserver> observer = do_QueryInterface(dialogParent);
+  nsCOMPtr<nsIObserver> observer = dialogParent;
 
   nsCOMPtr<nsIWebProgressListener> printProgressListener;
   nsCOMPtr<nsIPrintProgressParams> printProgressParams;
 
   nsresult rv = NS_ERROR_INVALID_ARG;
   if (parentWin && pps) {
     rv = pps->ShowProgress(parentWin, nullptr, nullptr, observer,
                            isForPrinting,
@@ -278,17 +278,17 @@ PrintingParent::DOMWindowFromBrowserPare
     return nullptr;
   }
 
   nsCOMPtr<Element> frameElement = tabParent->GetOwnerElement();
   if (!frameElement) {
     return nullptr;
   }
 
-  nsCOMPtr<nsIContent> frame(do_QueryInterface(frameElement));
+  nsCOMPtr<nsIContent> frame(frameElement);
   if (!frame) {
     return nullptr;
   }
 
   nsCOMPtr<nsPIDOMWindowOuter> parentWin = frame->OwnerDoc()->GetWindow();
   if (!parentWin) {
     return nullptr;
   }
--- a/toolkit/components/satchel/nsFormFillController.cpp
+++ b/toolkit/components/satchel/nsFormFillController.cpp
@@ -1453,17 +1453,17 @@ nsFormFillController::GetIndexOfDocShell
   uint32_t count = mDocShells.Length();
   for (uint32_t i = 0; i < count; ++i) {
     if (mDocShells[i] == aDocShell) {
       return i;
     }
   }
 
   // Recursively check the parent docShell of this one
-  nsCOMPtr<nsIDocShellTreeItem> treeItem = do_QueryInterface(aDocShell);
+  nsCOMPtr<nsIDocShellTreeItem> treeItem = aDocShell;
   nsCOMPtr<nsIDocShellTreeItem> parentItem;
   treeItem->GetParent(getter_AddRefs(parentItem));
   if (parentItem) {
     nsCOMPtr<nsIDocShell> parentShell = do_QueryInterface(parentItem);
     return GetIndexOfDocShell(parentShell);
   }
 
   return -1;
--- a/toolkit/xre/nsAppRunner.cpp
+++ b/toolkit/xre/nsAppRunner.cpp
@@ -1112,17 +1112,17 @@ nsXULAppInfo::SetEnabled(bool aEnabled)
     }
 
     nsCOMPtr<nsIFile> greBinDir;
     NS_GetSpecialDirectory(NS_GRE_BIN_DIR, getter_AddRefs(greBinDir));
     if (!greBinDir) {
       return NS_ERROR_FAILURE;
     }
 
-    nsCOMPtr<nsIFile> xreBinDirectory = do_QueryInterface(greBinDir);
+    nsCOMPtr<nsIFile> xreBinDirectory = greBinDir;
     if (!xreBinDirectory) {
       return NS_ERROR_FAILURE;
     }
 
     return CrashReporter::SetExceptionHandler(xreBinDirectory, true);
   }
 
   if (!CrashReporter::GetEnabled()) {
--- a/toolkit/xre/nsXREDirProvider.cpp
+++ b/toolkit/xre/nsXREDirProvider.cpp
@@ -167,17 +167,17 @@ nsXREDirProvider::Initialize(nsIFile *aX
   }
 #endif
   mGREDir->Clone(getter_AddRefs(mGREBinDir));
 #ifdef XP_MACOSX
   mGREBinDir->SetNativeLeafName(NS_LITERAL_CSTRING("MacOS"));
 #endif
 
   if (!mProfileDir) {
-    nsCOMPtr<nsIDirectoryServiceProvider> app(do_QueryInterface(mAppProvider));
+    nsCOMPtr<nsIDirectoryServiceProvider> app(mAppProvider);
     if (app) {
       bool per = false;
       app->GetFile(NS_APP_USER_PROFILE_50_DIR, &per, getter_AddRefs(mProfileDir));
       NS_ASSERTION(per, "NS_APP_USER_PROFILE_50_DIR must be persistent!");
       NS_ASSERTION(mProfileDir, "NS_APP_USER_PROFILE_50_DIR not defined! This shouldn't happen!");
     }
   }
 
--- a/uriloader/base/nsDocLoader.cpp
+++ b/uriloader/base/nsDocLoader.cpp
@@ -1439,17 +1439,17 @@ NS_IMETHODIMP nsDocLoader::AsyncOnChanne
     if (loadFlags & nsIChannel::LOAD_DOCUMENT_URI)
     {
       stateFlags |= nsIWebProgressListener::STATE_IS_DOCUMENT;
 
 #if defined(DEBUG)
       // We only set mDocumentRequest in OnStartRequest(), but its possible
       // to get a redirect before that for service worker interception.
       if (mDocumentRequest) {
-        nsCOMPtr<nsIRequest> request(do_QueryInterface(aOldChannel));
+        nsCOMPtr<nsIRequest> request(aOldChannel);
         NS_ASSERTION(request == mDocumentRequest, "Wrong Document Channel");
       }
 #endif /* DEBUG */
     }
 
     OnRedirectStateChange(aOldChannel, aNewChannel, aFlags, stateFlags);
     FireOnStateChange(this, aOldChannel, stateFlags, NS_OK);
   }
--- a/uriloader/exthandler/nsExternalHelperAppService.cpp
+++ b/uriloader/exthandler/nsExternalHelperAppService.cpp
@@ -2303,18 +2303,18 @@ NS_IMETHODIMP nsExternalAppHandler::Save
 nsresult nsExternalAppHandler::ContinueSave(nsIFile * aNewFileLocation)
 {
   if (mCanceled)
     return NS_OK;
 
   MOZ_ASSERT(aNewFileLocation, "Must be called with a non-null file");
 
   nsresult rv = NS_OK;
-  nsCOMPtr<nsIFile> fileToUse = do_QueryInterface(aNewFileLocation);
-  mFinalFileDestination = do_QueryInterface(fileToUse);
+  nsCOMPtr<nsIFile> fileToUse = aNewFileLocation;
+  mFinalFileDestination = fileToUse;
 
   // Move what we have in the final directory, but append .part
   // to it, to indicate that it's unfinished.  Do not call SetTarget on the
   // saver if we are done (Finish has been called) but OnSaverComplete has not
   // been called.
   if (mFinalFileDestination && mSaver && !mStopRequestIssued)
   {
     nsCOMPtr<nsIFile> movedFile;
@@ -2409,22 +2409,22 @@ NS_IMETHODIMP nsExternalAppHandler::Laun
   if (mSuggestedFileName.IsEmpty()) {
     // Keep using the leafname of the temp file, since we're just starting a helper
     mSuggestedFileName = mTempLeafName;
   }
 
 #ifdef XP_WIN
   fileToUse->Append(mSuggestedFileName + mTempFileExtension);
 #else
-  fileToUse->Append(mSuggestedFileName);  
+  fileToUse->Append(mSuggestedFileName);
 #endif
 
   nsresult rv = fileToUse->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600);
   if(NS_SUCCEEDED(rv)) {
-    mFinalFileDestination = do_QueryInterface(fileToUse);
+    mFinalFileDestination = fileToUse;
     // launch the progress window now that the user has picked the desired action.
     rv = CreateTransfer();
     if (NS_FAILED(rv)) {
       Cancel(rv);
     }
   } else {
     // Cancel the download and report an error.  We do not want to end up in
     // a state where it appears that we have a normal download that is
--- a/widget/gtk/nsPrintDialogGTK.cpp
+++ b/widget/gtk/nsPrintDialogGTK.cpp
@@ -1019,22 +1019,21 @@ nsPrintDialogServiceGTK::Show(nsPIDOMWin
 
     // This blocks until nsFlatpakPrintPortal::FinishPrintDialog is called
     GtkPrintOperationResult printDialogResult = fpPrintPortal->GetResult();
 
     rv = NS_OK;
     switch (printDialogResult) {
       case GTK_PRINT_OPERATION_RESULT_APPLY:
         {
-          nsCOMPtr<nsIObserver> observer = do_QueryInterface(fpPrintPortal);
           nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
           NS_ENSURE_STATE(os);
           // Observer waits until notified that the file with the content
           // to print has been written.
-          rv = os->AddObserver(observer, "print-to-file-finished", false);
+          rv = os->AddObserver(fpPrintPortal, "print-to-file-finished", false);
           NS_ENSURE_SUCCESS(rv, rv);
           break;
         }
       case GTK_PRINT_OPERATION_RESULT_CANCEL:
         rv = NS_ERROR_ABORT;
         break;
       default:
         NS_WARNING("Unexpected response");
--- a/widget/nsBaseDragService.cpp
+++ b/widget/nsBaseDragService.cpp
@@ -689,22 +689,21 @@ nsBaseDragService::DrawDrag(nsINode* aDO
       mDragPopup = content;
     }
   }
 
   if (!mDragPopup) {
     // otherwise, just draw the node
     uint32_t renderFlags = mImage ? 0 : nsIPresShell::RENDER_AUTO_SCALE;
     if (renderFlags) {
-      nsCOMPtr<nsINode> dragINode = do_QueryInterface(dragNode);
       // check if the dragged node itself is an img element
-      if (dragINode->NodeName().LowerCaseEqualsLiteral("img")) {
+      if (dragNode->NodeName().LowerCaseEqualsLiteral("img")) {
         renderFlags = renderFlags | nsIPresShell::RENDER_IS_IMAGE;
       } else {
-        nsINodeList* childList = dragINode->ChildNodes();
+        nsINodeList* childList = dragNode->ChildNodes();
         uint32_t length = childList->Length();
         // check every childnode for being an img element
         // XXXbz why don't we need to check descendants recursively?
         for (uint32_t count = 0; count < length; ++count) {
           if (childList->Item(count)->NodeName().LowerCaseEqualsLiteral("img")) {
             // if the dragnode contains an image, set RENDER_IS_IMAGE flag
             renderFlags = renderFlags | nsIPresShell::RENDER_IS_IMAGE;
             break;
--- a/widget/nsSoundProxy.cpp
+++ b/widget/nsSoundProxy.cpp
@@ -13,17 +13,17 @@ using namespace mozilla::dom;
 
 NS_IMPL_ISUPPORTS(nsSoundProxy, nsISound)
 
 NS_IMETHODIMP
 nsSoundProxy::Play(nsIURL *aURL)
 {
   MOZ_ASSERT(XRE_GetProcessType() == GeckoProcessType_Content);
 
-  nsCOMPtr<nsIURI> soundURI(do_QueryInterface(aURL));
+  nsCOMPtr<nsIURI> soundURI(aURL);
   bool isChrome = false;
   // Only allow playing a chrome:// URL from the content process.
   if (!soundURI || NS_FAILED(soundURI->SchemeIs("chrome", &isChrome)) || !isChrome) {
     return NS_ERROR_FAILURE;
   }
 
   mozilla::ipc::URIParams soundParams;
   mozilla::ipc::SerializeURI(soundURI, soundParams);
--- a/xpcom/ds/nsStringEnumerator.cpp
+++ b/xpcom/ds/nsStringEnumerator.cpp
@@ -21,17 +21,17 @@ using namespace mozilla::dom;
 namespace {
 
 class JSStringEnumerator final : public nsIJSEnumerator
 {
   NS_DECL_ISUPPORTS
   NS_DECL_NSIJSENUMERATOR
 
   explicit JSStringEnumerator(nsIStringEnumerator* aEnumerator)
-    : mEnumerator(do_QueryInterface(aEnumerator))
+    : mEnumerator(aEnumerator)
   {
     MOZ_ASSERT(mEnumerator);
   }
 
 private:
   ~JSStringEnumerator() = default;
 
   nsCOMPtr<nsIStringEnumerator> mEnumerator;
--- a/xpcom/threads/SharedThreadPool.cpp
+++ b/xpcom/threads/SharedThreadPool.cpp
@@ -181,17 +181,17 @@ NS_IMETHODIMP_(MozExternalRefCountType) 
 NS_IMPL_QUERY_INTERFACE(SharedThreadPool, nsIThreadPool, nsIEventTarget)
 
 SharedThreadPool::SharedThreadPool(const nsCString& aName,
                                    nsIThreadPool* aPool)
   : mName(aName)
   , mPool(aPool)
   , mRefCnt(0)
 {
-  mEventTarget = do_QueryInterface(aPool);
+  mEventTarget = aPool;
 }
 
 SharedThreadPool::~SharedThreadPool()
 {
 }
 
 nsresult
 SharedThreadPool::EnsureThreadLimitIsAtLeast(uint32_t aLimit)
--- a/xpfe/appshell/nsWebShellWindow.cpp
+++ b/xpfe/appshell/nsWebShellWindow.cpp
@@ -181,17 +181,17 @@ nsresult nsWebShellWindow::Initialize(ns
   // Create web shell
   mDocShell = do_CreateInstance("@mozilla.org/docshell;1");
   NS_ENSURE_TRUE(mDocShell, NS_ERROR_FAILURE);
 
   mDocShell->SetOpener(aOpeningTab);
 
   // Make sure to set the item type on the docshell _before_ calling
   // Create() so it knows what type it is.
-  nsCOMPtr<nsIDocShellTreeItem> docShellAsItem(do_QueryInterface(mDocShell));
+  nsCOMPtr<nsIDocShellTreeItem> docShellAsItem(mDocShell);
   NS_ENSURE_TRUE(docShellAsItem, NS_ERROR_FAILURE);
   NS_ENSURE_SUCCESS(EnsureChromeTreeOwner(), NS_ERROR_FAILURE);
 
   docShellAsItem->SetTreeOwner(mChromeTreeOwner);
   docShellAsItem->SetItemType(nsIDocShellTreeItem::typeChrome);
 
   mDocShell->AttachBrowsingContext(nullptr);
 
--- a/xpfe/appshell/nsXULWindow.cpp
+++ b/xpfe/appshell/nsXULWindow.cpp
@@ -2042,17 +2042,17 @@ nsXULWindow::GetRootShellSize(int32_t* a
   NS_ENSURE_TRUE(shellAsWin, NS_ERROR_FAILURE);
   return shellAsWin->GetSize(aWidth, aHeight);
 }
 
 nsresult
 nsXULWindow::SetRootShellSize(int32_t aWidth,
                               int32_t aHeight)
 {
-  nsCOMPtr<nsIDocShellTreeItem> docShellAsItem = do_QueryInterface(mDocShell);
+  nsCOMPtr<nsIDocShellTreeItem> docShellAsItem = mDocShell;
   return SizeShellTo(docShellAsItem, aWidth, aHeight);
 }
 
 NS_IMETHODIMP nsXULWindow::SizeShellTo(nsIDocShellTreeItem* aShellItem,
    int32_t aCX, int32_t aCY)
 {
   // XXXTAB This is wrong, we should actually reflow based on the passed in
   // shell.  For now we are hacking and doing delta sizing.  This is bad
@@ -2546,17 +2546,17 @@ nsXULWindow::SizeShell()
     SetSpecifiedSize(specWidth, specHeight);
   }
 
   if (mIntrinsicallySized) {
     // (if LoadSizeFromXUL set the size, mIntrinsicallySized will be false)
     nsCOMPtr<nsIContentViewer> cv;
     mDocShell->GetContentViewer(getter_AddRefs(cv));
     if (cv) {
-      nsCOMPtr<nsIDocShellTreeItem> docShellAsItem = do_QueryInterface(mDocShell);
+      nsCOMPtr<nsIDocShellTreeItem> docShellAsItem = mDocShell;
       nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
       docShellAsItem->GetTreeOwner(getter_AddRefs(treeOwner));
       if (treeOwner) {
         // GetContentSize can fail, so initialise |width| and |height| to be
         // on the safe side.
         int32_t width = 0, height = 0;
         if (NS_SUCCEEDED(cv->GetContentSize(&width, &height))) {
           treeOwner->SizeShellTo(docShellAsItem, width, height);