Bug 1660378 - part 9: Avoid QI for getting `nsStyledElement` pointer r=smaug
authorMasayuki Nakano <masayuki@d-toybox.com>
Wed, 26 Aug 2020 05:29:06 +0000
changeset 546240 d1a42f86dd6125fe9dd6a3e56e5b13972821391c
parent 546239 ee4715363f7004e72ea5f12a8d95f1fd81e2d21d
child 546241 331c529201854224d437d87427526e2b44419466
push id37732
push usermalexandru@mozilla.com
push dateWed, 26 Aug 2020 15:40:57 +0000
treeherdermozilla-central@7cea08d78f8b [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewerssmaug
bugs1660378
milestone82.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 1660378 - part 9: Avoid QI for getting `nsStyledElement` pointer r=smaug The editor modules does QI too many times when it sets or removes some style with `execCommand` or XPCOM API. Therefore, there should be an API to retrieve `nsStyledElement` pointer from `nsINode*`. Differential Revision: https://phabricator.services.mozilla.com/D87990
dom/animation/Animation.cpp
dom/base/nsINode.h
dom/base/nsStyledElement.h
editor/libeditor/EditorDOMPoint.h
editor/libeditor/HTMLAbsPositionEditor.cpp
editor/libeditor/HTMLEditSubActionHandler.cpp
editor/libeditor/HTMLEditUtils.cpp
editor/libeditor/HTMLEditor.cpp
editor/libeditor/HTMLEditorObjectResizer.cpp
editor/libeditor/HTMLInlineTableEditor.cpp
editor/libeditor/HTMLStyleEditor.cpp
layout/generic/ScrollbarActivity.cpp
layout/xul/nsResizerFrame.cpp
--- a/dom/animation/Animation.cpp
+++ b/dom/animation/Animation.cpp
@@ -697,17 +697,18 @@ void Animation::CommitStyles(ErrorResult
   }
 
   if (target.mPseudoType != PseudoStyleType::NotPseudo) {
     return aRv.ThrowNoModificationAllowedError(
         "Can't commit styles of a pseudo-element");
   }
 
   // Check it is an element with a style attribute
-  nsCOMPtr<nsStyledElement> styledElement = do_QueryInterface(target.mElement);
+  RefPtr<nsStyledElement> styledElement =
+      nsStyledElement::FromNodeOrNull(target.mElement);
   if (!styledElement) {
     return aRv.ThrowNoModificationAllowedError(
         "Target is not capable of having a style attribute");
   }
 
   // Hold onto a strong reference to the doc in case the flush destroys it.
   RefPtr<Document> doc = target.mElement->GetComposedDoc();
 
--- a/dom/base/nsINode.h
+++ b/dom/base/nsINode.h
@@ -518,16 +518,21 @@ class nsINode : public mozilla::dom::Eve
   /**
    * Return this node as an Element.  Should only be used for nodes
    * for which IsElement() is true.  This is defined inline in Element.h.
    */
   inline mozilla::dom::Element* AsElement();
   inline const mozilla::dom::Element* AsElement() const;
 
   /**
+   * Return whether the node is an nsStyledElement instance or not.
+   */
+  virtual bool IsStyledElement() const { return false; }
+
+  /**
    * Return this node as nsIContent.  Should only be used for nodes for which
    * IsContent() is true.
    *
    * The assertion in nsIContent's constructor makes this safe.
    */
   nsIContent* AsContent() {
     MOZ_ASSERT(IsContent());
     return reinterpret_cast<nsIContent*>(this);
--- a/dom/base/nsStyledElement.h
+++ b/dom/base/nsStyledElement.h
@@ -48,16 +48,19 @@ class nsStyledElement : public nsStyledE
       mozilla::MutationClosureData& aData) override;
   virtual nsresult SetInlineStyleDeclaration(
       mozilla::DeclarationBlock& aDeclaration,
       mozilla::MutationClosureData& aData) override;
 
   nsICSSDeclaration* Style();
 
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_STYLED_ELEMENT_IID)
+  NS_IMPL_FROMNODE_HELPER(nsStyledElement, IsStyledElement());
+
+  bool IsStyledElement() const final { return true; }
 
  protected:
   nsICSSDeclaration* GetExistingStyle();
 
   /**
    * Parse a style attr value into a CSS rulestruct (or, if there is no
    * document, leave it as a string) and return as nsAttrValue.
    *
--- a/editor/libeditor/EditorDOMPoint.h
+++ b/editor/libeditor/EditorDOMPoint.h
@@ -174,19 +174,18 @@ class EditorDOMPointBase final {
   }
 
   MOZ_NEVER_INLINE_DEBUG dom::Element* ContainerAsElement() const {
     MOZ_ASSERT(mParent);
     MOZ_ASSERT(mParent->IsElement());
     return mParent->AsElement();
   }
 
-  already_AddRefed<nsStyledElement> GetContainerAsStyledElement() const {
-    nsCOMPtr<nsStyledElement> styledElement = do_QueryInterface(mParent);
-    return styledElement.forget();
+  nsStyledElement* GetContainerAsStyledElement() const {
+    return nsStyledElement::FromNodeOrNull(mParent);
   }
 
   dom::Text* GetContainerAsText() const {
     return dom::Text::FromNodeOrNull(mParent);
   }
 
   MOZ_NEVER_INLINE_DEBUG dom::Text* ContainerAsText() const {
     MOZ_ASSERT(mParent);
--- a/editor/libeditor/HTMLAbsPositionEditor.cpp
+++ b/editor/libeditor/HTMLAbsPositionEditor.cpp
@@ -310,18 +310,18 @@ nsresult HTMLEditor::RefreshGrabberInter
   if (NS_FAILED(rv)) {
     NS_WARNING("HTMLEditor::GetPositionAndDimensions() failed");
     return rv;
   }
   if (NS_WARN_IF(absolutelyPositionedObject != mAbsolutelyPositionedObject)) {
     return NS_ERROR_FAILURE;
   }
 
-  nsCOMPtr<nsStyledElement> grabberStyledElement =
-      do_QueryInterface(mGrabber.get());
+  RefPtr<nsStyledElement> grabberStyledElement =
+      nsStyledElement::FromNodeOrNull(mGrabber.get());
   if (!grabberStyledElement) {
     return NS_OK;
   }
   rv = SetAnonymousElementPositionWithTransaction(
       *grabberStyledElement, mPositionedObjectX + 12, mPositionedObjectY - 14);
   if (NS_FAILED(rv)) {
     NS_WARNING(
         "HTMLEditor::SetAnonymousElementPositionWithTransaction() failed");
@@ -441,18 +441,18 @@ nsresult HTMLEditor::StartMoving() {
   // make the shadow appear
   DebugOnly<nsresult> rvIgnored =
       mPositioningShadow->UnsetAttr(kNameSpaceID_None, nsGkAtoms::_class, true);
   NS_WARNING_ASSERTION(
       NS_SUCCEEDED(rvIgnored),
       "Element::UnsetAttr(nsGkAtoms::_class) failed, but ignored");
 
   // position it
-  if (nsCOMPtr<nsStyledElement> positioningShadowStyledElement =
-          do_QueryInterface(mPositioningShadow.get())) {
+  if (RefPtr<nsStyledElement> positioningShadowStyledElement =
+          nsStyledElement::FromNode(mPositioningShadow.get())) {
     nsresult rv;
     rv = mCSSEditUtils->SetCSSPropertyPixelsWithTransaction(
         *positioningShadowStyledElement, *nsGkAtoms::width,
         mPositionedObjectWidth);
     if (rv == NS_ERROR_EDITOR_DESTROYED) {
       NS_WARNING(
           "CSSEditUtils::SetCSSPropertyPixelsWithTransaction(nsGkAtoms::width) "
           "destroyed the editor");
@@ -556,18 +556,18 @@ nsresult HTMLEditor::SetFinalPosition(in
 
   // we want one transaction only from a user's point of view
   AutoPlaceholderBatch treatAsOneTransaction(*this,
                                              ScrollSelectionIntoView::Yes);
 
   if (NS_WARN_IF(!mAbsolutelyPositionedObject)) {
     return NS_ERROR_FAILURE;
   }
-  if (nsCOMPtr<nsStyledElement> styledAbsolutelyPositionedElement =
-          do_QueryInterface(mAbsolutelyPositionedObject)) {
+  if (RefPtr<nsStyledElement> styledAbsolutelyPositionedElement =
+          nsStyledElement::FromNode(mAbsolutelyPositionedObject)) {
     nsresult rv;
     rv = mCSSEditUtils->SetCSSPropertyPixelsWithTransaction(
         *styledAbsolutelyPositionedElement, *nsGkAtoms::top, newY);
     if (rv == NS_ERROR_EDITOR_DESTROYED) {
       NS_WARNING(
           "CSSEditUtils::SetCSSPropertyPixelsWithTransaction(nsGkAtoms::top) "
           "destroyed the editor");
       return NS_ERROR_EDITOR_DESTROYED;
@@ -640,36 +640,41 @@ nsresult HTMLEditor::SetPositionToAbsolu
   AutoPlaceholderBatch treatAsOneTransaction(*this,
                                              ScrollSelectionIntoView::Yes);
 
   int32_t x, y;
   DebugOnly<nsresult> rvIgnored = GetElementOrigin(aElement, x, y);
   NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
                        "HTMLEditor::GetElementOrigin() failed, but ignored");
 
-  nsCOMPtr<nsStyledElement> styledElement = do_QueryInterface(&aElement);
+  nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement);
   if (styledElement) {
+    // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+    // by the caller because of MOZ_CAN_RUN_SCRIPT method.
     nsresult rv = mCSSEditUtils->SetCSSPropertyWithTransaction(
-        *styledElement, *nsGkAtoms::position, u"absolute"_ns);
+        MOZ_KnownLive(*styledElement), *nsGkAtoms::position, u"absolute"_ns);
     if (rv == NS_ERROR_EDITOR_DESTROYED) {
       NS_WARNING(
           "CSSEditUtils::SetCSSProperyWithTransaction(nsGkAtoms::Position) "
           "destroyed the editor");
       return NS_ERROR_EDITOR_DESTROYED;
     }
     NS_WARNING_ASSERTION(
         NS_SUCCEEDED(rvIgnored),
         "CSSEditUtils::SetCSSPropertyWithTransaction(nsGkAtoms::position, "
         "absolute) failed, but ignored");
   }
 
   AddPositioningOffset(x, y);
   SnapToGrid(x, y);
   if (styledElement) {
-    nsresult rv = SetTopAndLeftWithTransaction(*styledElement, x, y);
+    // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+    // by the caller because of MOZ_CAN_RUN_SCRIPT method.
+    nsresult rv =
+        SetTopAndLeftWithTransaction(MOZ_KnownLive(*styledElement), x, y);
     if (NS_FAILED(rv)) {
       NS_WARNING("HTMLEditor::SetTopAndLeftWithTransaction() failed");
       return rv;
     }
   }
 
   // we may need to create a br if the positioned element is alone in its
   // container
@@ -680,89 +685,101 @@ nsresult HTMLEditor::SetPositionToAbsolu
   RefPtr<Element> newBRElement =
       InsertBRElementWithTransaction(EditorDOMPoint(parentNode, 0));
   NS_WARNING_ASSERTION(newBRElement,
                        "HTMLEditor::InsertBRElementWithTransaction() failed");
   return newBRElement ? NS_OK : NS_ERROR_FAILURE;
 }
 
 nsresult HTMLEditor::SetPositionToStatic(Element& aElement) {
-  nsCOMPtr<nsStyledElement> styledElement = do_QueryInterface(&aElement);
+  nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement);
   if (NS_WARN_IF(!styledElement)) {
     return NS_ERROR_INVALID_ARG;
   }
 
   AutoPlaceholderBatch treatAsOneTransaction(*this,
                                              ScrollSelectionIntoView::Yes);
 
   nsresult rv;
+  // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+  // by the caller because of MOZ_CAN_RUN_SCRIPT method.
   rv = mCSSEditUtils->RemoveCSSPropertyWithTransaction(
-      *styledElement, *nsGkAtoms::position, EmptyString());
+      MOZ_KnownLive(*styledElement), *nsGkAtoms::position, EmptyString());
   if (rv == NS_ERROR_EDITOR_DESTROYED) {
     NS_WARNING(
         "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::position) "
         "destroyed the editor");
     return NS_ERROR_EDITOR_DESTROYED;
   }
   NS_WARNING_ASSERTION(
       NS_SUCCEEDED(rv),
       "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::position) "
       "failed, but ignored");
+  // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+  // by the caller because of MOZ_CAN_RUN_SCRIPT method.
   rv = mCSSEditUtils->RemoveCSSPropertyWithTransaction(
-      *styledElement, *nsGkAtoms::top, EmptyString());
+      MOZ_KnownLive(*styledElement), *nsGkAtoms::top, EmptyString());
   if (rv == NS_ERROR_EDITOR_DESTROYED) {
     NS_WARNING(
         "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::top) "
         "destroyed the editor");
     return NS_ERROR_EDITOR_DESTROYED;
   }
   NS_WARNING_ASSERTION(
       NS_SUCCEEDED(rv),
       "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::top) "
       "failed, but ignored");
+  // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+  // by the caller because of MOZ_CAN_RUN_SCRIPT method.
   rv = mCSSEditUtils->RemoveCSSPropertyWithTransaction(
-      *styledElement, *nsGkAtoms::left, EmptyString());
+      MOZ_KnownLive(*styledElement), *nsGkAtoms::left, EmptyString());
   if (rv == NS_ERROR_EDITOR_DESTROYED) {
     NS_WARNING(
         "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::left) "
         "destroyed the editor");
     return NS_ERROR_EDITOR_DESTROYED;
   }
   NS_WARNING_ASSERTION(
       NS_SUCCEEDED(rv),
       "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::left) "
       "failed, but ignored");
+  // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+  // by the caller because of MOZ_CAN_RUN_SCRIPT method.
   rv = mCSSEditUtils->RemoveCSSPropertyWithTransaction(
-      *styledElement, *nsGkAtoms::z_index, EmptyString());
+      MOZ_KnownLive(*styledElement), *nsGkAtoms::z_index, EmptyString());
   if (rv == NS_ERROR_EDITOR_DESTROYED) {
     NS_WARNING(
         "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::z_index) "
         "destroyed the editor");
     return NS_ERROR_EDITOR_DESTROYED;
   }
   NS_WARNING_ASSERTION(
       NS_SUCCEEDED(rv),
       "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::z_index) "
       "failed, but ignored");
 
   if (!HTMLEditUtils::IsImage(styledElement)) {
+    // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+    // by the caller because of MOZ_CAN_RUN_SCRIPT method.
     rv = mCSSEditUtils->RemoveCSSPropertyWithTransaction(
-        *styledElement, *nsGkAtoms::width, EmptyString());
+        MOZ_KnownLive(*styledElement), *nsGkAtoms::width, EmptyString());
     if (rv == NS_ERROR_EDITOR_DESTROYED) {
       NS_WARNING(
           "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::width) "
           "destroyed the editor");
       return NS_ERROR_EDITOR_DESTROYED;
     }
     NS_WARNING_ASSERTION(
         NS_SUCCEEDED(rv),
         "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::width) "
         "failed, but ignored");
+    // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+    // by the caller because of MOZ_CAN_RUN_SCRIPT method.
     rv = mCSSEditUtils->RemoveCSSPropertyWithTransaction(
-        *styledElement, *nsGkAtoms::height, EmptyString());
+        MOZ_KnownLive(*styledElement), *nsGkAtoms::height, EmptyString());
     if (rv == NS_ERROR_EDITOR_DESTROYED) {
       NS_WARNING(
           "CSSEditUtils::RemoveCSSPropertyWithTransaction(nsGkAtoms::height) "
           "destroyed the editor");
       return NS_ERROR_EDITOR_DESTROYED;
     }
     NS_WARNING_ASSERTION(
         NS_SUCCEEDED(rv),
@@ -772,27 +789,33 @@ nsresult HTMLEditor::SetPositionToStatic
 
   if (!styledElement->IsHTMLElement(nsGkAtoms::div) ||
       HTMLEditor::HasStyleOrIdOrClassAttribute(*styledElement)) {
     return NS_OK;
   }
 
   // Make sure the first fild and last child of aElement starts/ends hard
   // line(s) even after removing `aElement`.
-  rv = EnsureHardLineBeginsWithFirstChildOf(*styledElement);
+  // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+  // by the caller because of MOZ_CAN_RUN_SCRIPT method.
+  rv = EnsureHardLineBeginsWithFirstChildOf(MOZ_KnownLive(*styledElement));
   if (NS_FAILED(rv)) {
     NS_WARNING("HTMLEditor::EnsureHardLineBeginsWithFirstChildOf() failed");
     return rv;
   }
-  rv = EnsureHardLineEndsWithLastChildOf(*styledElement);
+  // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+  // by the caller because of MOZ_CAN_RUN_SCRIPT method.
+  rv = EnsureHardLineEndsWithLastChildOf(MOZ_KnownLive(*styledElement));
   if (NS_FAILED(rv)) {
     NS_WARNING("HTMLEditor::EnsureHardLineEndsWithLastChildOf() failed");
     return rv;
   }
-  rv = RemoveContainerWithTransaction(*styledElement);
+  // MOZ_KnownLive(*styledElement): aElement's lifetime must be guarantted
+  // by the caller because of MOZ_CAN_RUN_SCRIPT method.
+  rv = RemoveContainerWithTransaction(MOZ_KnownLive(*styledElement));
   if (NS_WARN_IF(Destroyed())) {
     return NS_ERROR_EDITOR_DESTROYED;
   }
   NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                        "HTMLEditor::RemoveContainerWithTransaction() failed");
   return rv;
 }
 
--- a/editor/libeditor/HTMLEditSubActionHandler.cpp
+++ b/editor/libeditor/HTMLEditSubActionHandler.cpp
@@ -8658,33 +8658,37 @@ nsresult HTMLEditor::AlignNodesAndDescen
     }
 
     // If it's a list item, or a list inside a list, forget any "current" div,
     // and instead put divs inside the appropriate block (td, li, etc.)
     if (HTMLEditUtils::IsListItem(content) ||
         HTMLEditUtils::IsAnyListElement(content)) {
       Element* listOrListItemElement = content->AsElement();
       AutoEditorDOMPointOffsetInvalidator lockChild(atContent);
+      // MOZ_KnownLive(*listOrListItemElement): An element of aArrayOfContents
+      // which is array of OwningNonNull.
       nsresult rv = RemoveAlignFromDescendants(
           MOZ_KnownLive(*listOrListItemElement), aAlignType,
           EditTarget::OnlyDescendantsExceptTable);
       if (NS_FAILED(rv)) {
         NS_WARNING(
             "HTMLEditor::RemoveAlignFromDescendants(EditTarget::"
             "OnlyDescendantsExceptTable) failed");
         return rv;
       }
 
       if (useCSS) {
-        if (nsCOMPtr<nsStyledElement> styledListOrListItemElement =
-                do_QueryInterface(listOrListItemElement)) {
+        if (nsStyledElement* styledListOrListItemElement =
+                nsStyledElement::FromNode(listOrListItemElement)) {
+          // MOZ_KnownLive(*styledListOrListItemElement): An element of
+          // aArrayOfContents which is array of OwningNonNull.
           Result<int32_t, nsresult> result =
               mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithTransaction(
-                  *styledListOrListItemElement, nullptr, nsGkAtoms::align,
-                  &aAlignType);
+                  MOZ_KnownLive(*styledListOrListItemElement), nullptr,
+                  nsGkAtoms::align, &aAlignType);
           if (result.isErr()) {
             if (result.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
               NS_WARNING(
                   "CSSEditUtils::SetCSSEquivalentToHTMLStyleWithTransaction("
                   "nsGkAtoms::align) destroyed the editor");
               return NS_ERROR_EDITOR_DESTROYED;
             }
             NS_WARNING(
@@ -8697,16 +8701,18 @@ nsresult HTMLEditor::AlignNodesAndDescen
       }
 
       if (HTMLEditUtils::IsAnyListElement(atContent.GetContainer())) {
         // If we don't use CSS, add a content to list element: they have to
         // be inside another list, i.e., >= second level of nesting.
         // XXX AlignContentsInAllTableCellsAndListItems() handles only list
         //     item elements and table cells.  Is it intentional?  Why don't
         //     we need to align contents in other type blocks?
+        // MOZ_KnownLive(*listOrListItemElement): An element of aArrayOfContents
+        // which is array of OwningNonNull.
         nsresult rv = AlignContentsInAllTableCellsAndListItems(
             MOZ_KnownLive(*listOrListItemElement), aAlignType);
         if (NS_FAILED(rv)) {
           NS_WARNING(
               "HTMLEditor::AlignContentsInAllTableCellsAndListItems() failed");
           return rv;
         }
         createdDivElement = nullptr;
@@ -12741,24 +12747,27 @@ nsresult HTMLEditor::RemoveAlignFromDesc
           return NS_ERROR_EDITOR_DESTROYED;
         }
         if (NS_FAILED(rv)) {
           NS_WARNING(
               "EditorBase::SetAttributeOrEquivalent(nsGkAtoms::align) failed");
           return rv;
         }
       } else {
-        nsCOMPtr<nsStyledElement> styledBlockOrHRElement =
-            do_QueryInterface(blockOrHRElement);
+        nsStyledElement* styledBlockOrHRElement =
+            nsStyledElement::FromNode(blockOrHRElement);
         if (NS_WARN_IF(!styledBlockOrHRElement)) {
           return NS_ERROR_FAILURE;
         }
+        // MOZ_KnownLive(*styledBlockOrHRElement): It's `blockOrHRElement
+        // which is OwningNonNull.
         nsAutoString dummyCssValue;
         nsresult rv = mCSSEditUtils->RemoveCSSInlineStyleWithTransaction(
-            *styledBlockOrHRElement, nsGkAtoms::textAlign, dummyCssValue);
+            MOZ_KnownLive(*styledBlockOrHRElement), nsGkAtoms::textAlign,
+            dummyCssValue);
         if (NS_FAILED(rv)) {
           NS_WARNING(
               "CSSEditUtils::RemoveCSSInlineStyleWithTransaction(nsGkAtoms::"
               "textAlign) failed");
           return rv;
         }
       }
     }
@@ -12919,39 +12928,45 @@ nsresult HTMLEditor::ChangeMarginStart(E
     f += NS_EDITOR_INDENT_INCREMENT_EX * multiplier;
   } else if (nsGkAtoms::px == unit) {
     f += NS_EDITOR_INDENT_INCREMENT_PX * multiplier;
   } else if (nsGkAtoms::percentage == unit) {
     f += NS_EDITOR_INDENT_INCREMENT_PERCENT * multiplier;
   }
 
   if (0 < f) {
-    if (nsCOMPtr<nsStyledElement> styledElement =
-            do_QueryInterface(&aElement)) {
+    if (nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement)) {
       nsAutoString newValue;
       newValue.AppendFloat(f);
       newValue.Append(nsDependentAtomString(unit));
+      // MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
+      // be guaranteed by caller because of MOZ_CAN_RUN_SCRIPT method.
+      // MOZ_KnownLive(merginProperty): It's nsStaticAtom.
       nsresult rv = mCSSEditUtils->SetCSSPropertyWithTransaction(
-          *styledElement, MOZ_KnownLive(marginProperty), newValue);
+          MOZ_KnownLive(*styledElement), MOZ_KnownLive(marginProperty),
+          newValue);
       if (rv == NS_ERROR_EDITOR_DESTROYED) {
         NS_WARNING(
             "CSSEditUtils::SetCSSPropertyWithTransaction() destroyed the "
             "editor");
         return NS_ERROR_EDITOR_DESTROYED;
       }
       NS_WARNING_ASSERTION(
           NS_SUCCEEDED(rv),
           "CSSEditUtils::SetCSSPropertyWithTransaction() failed, but ignored");
     }
     return NS_OK;
   }
 
-  if (nsCOMPtr<nsStyledElement> styledElement = do_QueryInterface(&aElement)) {
+  if (nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement)) {
+    // MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
+    // be guaranteed by caller because of MOZ_CAN_RUN_SCRIPT method.
+    // MOZ_KnownLive(merginProperty): It's nsStaticAtom.
     nsresult rv = mCSSEditUtils->RemoveCSSPropertyWithTransaction(
-        *styledElement, MOZ_KnownLive(marginProperty), value);
+        MOZ_KnownLive(*styledElement), MOZ_KnownLive(marginProperty), value);
     if (rv == NS_ERROR_EDITOR_DESTROYED) {
       NS_WARNING(
           "CSSEditUtils::RemoveCSSPropertyWithTransaction() destroyed the "
           "editor");
       return NS_ERROR_EDITOR_DESTROYED;
     }
     NS_WARNING_ASSERTION(
         NS_SUCCEEDED(rv),
@@ -13503,27 +13518,29 @@ EditActionResult HTMLEditor::AddZIndexAs
       return EditActionHandled(NS_ERROR_EDITOR_DESTROYED);
     }
     NS_WARNING(
         "HTMLEditor::GetAbsolutelyPositionedSelectionContainer() returned "
         "nullptr");
     return EditActionHandled(NS_ERROR_FAILURE);
   }
 
-  nsCOMPtr<nsStyledElement> absolutelyPositionedStyledElement =
-      do_QueryInterface(absolutelyPositionedElement);
+  nsStyledElement* absolutelyPositionedStyledElement =
+      nsStyledElement::FromNode(absolutelyPositionedElement);
   if (NS_WARN_IF(!absolutelyPositionedStyledElement)) {
     return EditActionHandled(NS_ERROR_FAILURE);
   }
 
   {
     AutoSelectionRestorer restoreSelectionLater(*this);
 
-    Result<int32_t, nsresult> result =
-        AddZIndexWithTransaction(*absolutelyPositionedStyledElement, aChange);
+    // MOZ_KnownLive(*absolutelyPositionedStyledElement): It's
+    // absolutelyPositionedElement whose type is RefPtr.
+    Result<int32_t, nsresult> result = AddZIndexWithTransaction(
+        MOZ_KnownLive(*absolutelyPositionedStyledElement), aChange);
     if (result.isErr()) {
       NS_WARNING("HTMLEditor::AddZIndexWithTransaction() failed");
       return EditActionHandled(result.unwrapErr());
     }
   }
 
   // Restoring Selection might cause destroying the HTML editor.
   return NS_WARN_IF(Destroyed()) ? EditActionHandled(NS_ERROR_EDITOR_DESTROYED)
--- a/editor/libeditor/HTMLEditUtils.cpp
+++ b/editor/libeditor/HTMLEditUtils.cpp
@@ -44,23 +44,23 @@ bool HTMLEditUtils::CanContentsBeJoined(
   }
   if (aStyleDifference == StyleDifference::CompareIfSpanElements &&
       !aLeftContent.IsHTMLElement(nsGkAtoms::span)) {
     return true;
   }
   if (!aLeftContent.IsElement() || !aRightContent.IsElement()) {
     return false;
   }
-  nsCOMPtr<nsStyledElement> leftStyledElement =
-      do_QueryInterface(const_cast<nsIContent*>(&aLeftContent));
+  nsStyledElement* leftStyledElement =
+      nsStyledElement::FromNode(const_cast<nsIContent*>(&aLeftContent));
   if (!leftStyledElement) {
     return false;
   }
-  nsCOMPtr<nsStyledElement> rightStyledElement =
-      do_QueryInterface(const_cast<nsIContent*>(&aRightContent));
+  nsStyledElement* rightStyledElement =
+      nsStyledElement::FromNode(const_cast<nsIContent*>(&aRightContent));
   if (!rightStyledElement) {
     return false;
   }
   return CSSEditUtils::DoStyledElementsHaveSameStyle(*leftStyledElement,
                                                      *rightStyledElement);
 }
 
 bool HTMLEditUtils::IsBlockElement(const nsIContent& aContent) {
--- a/editor/libeditor/HTMLEditor.cpp
+++ b/editor/libeditor/HTMLEditor.cpp
@@ -5171,26 +5171,29 @@ bool HTMLEditor::IsEmptyNodeImpl(nsINode
 nsresult HTMLEditor::SetAttributeOrEquivalent(Element* aElement,
                                               nsAtom* aAttribute,
                                               const nsAString& aValue,
                                               bool aSuppressTransaction) {
   MOZ_ASSERT(aElement);
   MOZ_ASSERT(aAttribute);
 
   nsAutoScriptBlocker scriptBlocker;
-  nsCOMPtr<nsStyledElement> styledElement = do_QueryInterface(aElement);
+  nsStyledElement* styledElement = nsStyledElement::FromNodeOrNull(aElement);
   if (!IsCSSEnabled() || !mCSSEditUtils) {
     // we are not in an HTML+CSS editor; let's set the attribute the HTML way
     if (mCSSEditUtils && styledElement) {
+      // MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
+      // be guaranteed by the caller because of MOZ_CAN_RUN_SCRIPT method.
       nsresult rv =
           aSuppressTransaction
               ? mCSSEditUtils->RemoveCSSEquivalentToHTMLStyleWithoutTransaction(
-                    *styledElement, nullptr, aAttribute, nullptr)
+                    MOZ_KnownLive(*styledElement), nullptr, aAttribute, nullptr)
               : mCSSEditUtils->RemoveCSSEquivalentToHTMLStyleWithTransaction(
-                    *styledElement, nullptr, aAttribute, nullptr);
+                    MOZ_KnownLive(*styledElement), nullptr, aAttribute,
+                    nullptr);
       if (rv == NS_ERROR_EDITOR_DESTROYED) {
         NS_WARNING(
             "CSSEditUtils::RemoveCSSEquivalentToHTMLStyle*Transaction() "
             "destroyed the editor");
         return NS_ERROR_EDITOR_DESTROYED;
       }
       NS_WARNING_ASSERTION(
           NS_SUCCEEDED(rv),
@@ -5205,22 +5208,24 @@ nsresult HTMLEditor::SetAttributeOrEquiv
     }
     nsresult rv = SetAttributeWithTransaction(*aElement, *aAttribute, aValue);
     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
                          "EditorBase::SetAttributeWithTransaction() failed");
     return rv;
   }
 
   if (styledElement) {
+    // MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
+    // be guaranteed by the caller because of MOZ_CAN_RUN_SCRIPT method.
     Result<int32_t, nsresult> count =
         aSuppressTransaction
             ? mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithoutTransaction(
-                  *styledElement, nullptr, aAttribute, &aValue)
+                  MOZ_KnownLive(*styledElement), nullptr, aAttribute, &aValue)
             : mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithTransaction(
-                  *styledElement, nullptr, aAttribute, &aValue);
+                  MOZ_KnownLive(*styledElement), nullptr, aAttribute, &aValue);
     if (count.isErr()) {
       if (count.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
         return NS_ERROR_EDITOR_DESTROYED;
       }
       NS_WARNING(
           "CSSEditUtils::SetCSSEquivalentToHTMLStyle*Transaction() failed, but "
           "ignored");
     }
@@ -5289,26 +5294,28 @@ nsresult HTMLEditor::RemoveAttributeOrEq
                                                  bool aSuppressTransaction) {
   MOZ_ASSERT(aElement);
   MOZ_ASSERT(aAttribute);
 
   if (IsCSSEnabled() && mCSSEditUtils &&
       CSSEditUtils::IsCSSEditableProperty(aElement, nullptr, aAttribute)) {
     // XXX It might be keep handling attribute even if aElement is not
     //     an nsStyledElement instance.
-    nsCOMPtr<nsStyledElement> styledElement = do_QueryInterface(aElement);
+    nsStyledElement* styledElement = nsStyledElement::FromNodeOrNull(aElement);
     if (NS_WARN_IF(!styledElement)) {
       return NS_ERROR_INVALID_ARG;
     }
+    // MOZ_KnownLive(*styledElement): It's aElement and its lifetime must
+    // be guaranteed by the caller because of MOZ_CAN_RUN_SCRIPT method.
     nsresult rv =
         aSuppressTransaction
             ? mCSSEditUtils->RemoveCSSEquivalentToHTMLStyleWithoutTransaction(
-                  *styledElement, nullptr, aAttribute, nullptr)
+                  MOZ_KnownLive(*styledElement), nullptr, aAttribute, nullptr)
             : mCSSEditUtils->RemoveCSSEquivalentToHTMLStyleWithTransaction(
-                  *styledElement, nullptr, aAttribute, nullptr);
+                  MOZ_KnownLive(*styledElement), nullptr, aAttribute, nullptr);
     if (NS_FAILED(rv)) {
       NS_WARNING(
           "CSSEditUtils::RemoveCSSEquivalentToHTMLStyle*Transaction() failed");
       return rv;
     }
   }
 
   if (!aElement->HasAttr(kNameSpaceID_None, aAttribute)) {
@@ -5412,19 +5419,20 @@ nsresult HTMLEditor::SetCSSBackgroundCol
           NS_WARN_IF(!endOfRange.IsSet())) {
         continue;
       }
 
       if (startOfRange.GetContainer() == endOfRange.GetContainer()) {
         // If the range is in a text node, set background color of its parent
         // block.
         if (startOfRange.IsInTextNode()) {
-          if (nsCOMPtr<nsStyledElement> blockStyledElement =
-                  do_QueryInterface(HTMLEditUtils::GetAncestorBlockElement(
-                      *startOfRange.ContainerAsText()))) {
+          if (RefPtr<nsStyledElement> blockStyledElement =
+                  nsStyledElement::FromNodeOrNull(
+                      HTMLEditUtils::GetAncestorBlockElement(
+                          *startOfRange.ContainerAsText()))) {
             Result<int32_t, nsresult> result =
                 mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithTransaction(
                     *blockStyledElement, nullptr, nsGkAtoms::bgcolor, &aColor);
             if (result.isErr()) {
               if (result.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
                 NS_WARNING(
                     "CSSEditUtils::SetCSSEquivalentToHTMLStyleWithTransaction("
                     "nsGkAtoms::bgcolor) destroyed the editor");
@@ -5439,17 +5447,17 @@ nsresult HTMLEditor::SetCSSBackgroundCol
         }
 
         // If `Selection` is collapsed in a `<body>` element, set background
         // color of the `<body>` element.
         // XXX Why do we refer whether the `Selection` is collapsed rather
         //     than the `nsRange` is collapsed?
         if (startOfRange.GetContainer()->IsHTMLElement(nsGkAtoms::body) &&
             selectionIsCollapsed) {
-          if (nsCOMPtr<nsStyledElement> styledElement =
+          if (RefPtr<nsStyledElement> styledElement =
                   startOfRange.GetContainerAsStyledElement()) {
             Result<int32_t, nsresult> result =
                 mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithTransaction(
                     *styledElement, nullptr, nsGkAtoms::bgcolor, &aColor);
             if (result.isErr()) {
               if (result.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
                 NS_WARNING(
                     "CSSEditUtils::SetCSSEquivalentToHTMLStyleWithTransaction("
@@ -5466,19 +5474,20 @@ nsresult HTMLEditor::SetCSSBackgroundCol
         // If one node is selected, set background color of it if it's a
         // block, or of its parent block otherwise.
         if ((startOfRange.IsStartOfContainer() &&
              endOfRange.IsStartOfContainer()) ||
             startOfRange.Offset() + 1 == endOfRange.Offset()) {
           if (NS_WARN_IF(startOfRange.IsInDataNode())) {
             continue;
           }
-          if (nsCOMPtr<nsStyledElement> blockStyledElement = do_QueryInterface(
-                  HTMLEditUtils::GetInclusiveAncestorBlockElement(
-                      *startOfRange.GetChild()))) {
+          if (RefPtr<nsStyledElement> blockStyledElement =
+                  nsStyledElement::FromNodeOrNull(
+                      HTMLEditUtils::GetInclusiveAncestorBlockElement(
+                          *startOfRange.GetChild()))) {
             Result<int32_t, nsresult> result =
                 mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithTransaction(
                     *blockStyledElement, nullptr, nsGkAtoms::bgcolor, &aColor);
             if (result.isErr()) {
               if (result.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
                 NS_WARNING(
                     "CSSEditUtils::SetCSSEquivalentToHTMLStyleWithTransaction("
                     "nsGkAtoms::bgcolor) destroyed the editor");
@@ -5523,21 +5532,24 @@ nsresult HTMLEditor::SetCSSBackgroundCol
       // block.
       if (startOfRange.IsInTextNode() &&
           EditorUtils::IsEditableContent(*startOfRange.ContainerAsText(),
                                          EditorType::HTML)) {
         RefPtr<Element> blockElement = HTMLEditUtils::GetAncestorBlockElement(
             *startOfRange.ContainerAsText());
         if (blockElement && handledBlockParent != blockElement) {
           handledBlockParent = blockElement;
-          if (nsCOMPtr<nsStyledElement> blockStyledElement =
-                  do_QueryInterface(blockElement)) {
+          if (nsStyledElement* blockStyledElement =
+                  nsStyledElement::FromNode(blockElement)) {
+            // MOZ_KnownLive(*blockStyledElement): It's blockElement whose
+            // type is RefPtr.
             Result<int32_t, nsresult> result =
                 mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithTransaction(
-                    *blockStyledElement, nullptr, nsGkAtoms::bgcolor, &aColor);
+                    MOZ_KnownLive(*blockStyledElement), nullptr,
+                    nsGkAtoms::bgcolor, &aColor);
             if (result.isErr()) {
               if (result.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
                 NS_WARNING(
                     "CSSEditUtils::SetCSSEquivalentToHTMLStyleWithTransaction("
                     "nsGkAtoms::bgcolor) destroyed the editor");
                 return NS_ERROR_EDITOR_DESTROYED;
               }
               NS_WARNING(
@@ -5550,21 +5562,24 @@ nsresult HTMLEditor::SetCSSBackgroundCol
 
       // Then, set background color of each block or block parent of all nodes
       // in the range entirely.
       for (OwningNonNull<nsIContent>& content : arrayOfContents) {
         RefPtr<Element> blockElement =
             HTMLEditUtils::GetInclusiveAncestorBlockElement(content);
         if (blockElement && handledBlockParent != blockElement) {
           handledBlockParent = blockElement;
-          if (nsCOMPtr<nsStyledElement> blockStyledElement =
-                  do_QueryInterface(blockElement)) {
+          if (nsStyledElement* blockStyledElement =
+                  nsStyledElement::FromNode(blockElement)) {
+            // MOZ_KnownLive(*blockStyledElement): It's blockElement whose
+            // type is RefPtr.
             Result<int32_t, nsresult> result =
                 mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithTransaction(
-                    *blockStyledElement, nullptr, nsGkAtoms::bgcolor, &aColor);
+                    MOZ_KnownLive(*blockStyledElement), nullptr,
+                    nsGkAtoms::bgcolor, &aColor);
             if (result.isErr()) {
               if (result.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
                 NS_WARNING(
                     "CSSEditUtils::SetCSSEquivalentToHTMLStyleWithTransaction("
                     "nsGkAtoms::bgcolor) destroyed the editor");
                 return NS_ERROR_EDITOR_DESTROYED;
               }
               NS_WARNING(
@@ -5578,21 +5593,24 @@ nsresult HTMLEditor::SetCSSBackgroundCol
       // Finally, if end node is a text node, set background color of its
       // parent block.
       if (endOfRange.IsInTextNode() &&
           EditorUtils::IsEditableContent(*endOfRange.ContainerAsText(),
                                          EditorType::HTML)) {
         RefPtr<Element> blockElement = HTMLEditUtils::GetAncestorBlockElement(
             *endOfRange.ContainerAsText());
         if (blockElement && handledBlockParent != blockElement) {
-          if (nsCOMPtr<nsStyledElement> blockStyledElement =
-                  do_QueryInterface(blockElement)) {
+          if (nsStyledElement* blockStyledElement =
+                  nsStyledElement::FromNode(blockElement)) {
+            // MOZ_KnownLive(*blockStyledElement): It's blockElement whose
+            // type is RefPtr.
             Result<int32_t, nsresult> result =
                 mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithTransaction(
-                    *blockStyledElement, nullptr, nsGkAtoms::bgcolor, &aColor);
+                    MOZ_KnownLive(*blockStyledElement), nullptr,
+                    nsGkAtoms::bgcolor, &aColor);
             if (result.isErr()) {
               if (result.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
                 NS_WARNING(
                     "CSSEditUtils::SetCSSEquivalentToHTMLStyleWithTransaction("
                     "nsGkAtoms::bgcolor) destroyed the editor");
                 return NS_ERROR_EDITOR_DESTROYED;
               }
               NS_WARNING(
--- a/editor/libeditor/HTMLEditorObjectResizer.cpp
+++ b/editor/libeditor/HTMLEditorObjectResizer.cpp
@@ -179,18 +179,18 @@ nsresult HTMLEditor::SetAllResizersPosit
   // all resizers here, and then, if we detect a resizer is removed or replaced,
   // we should do nothing anymore.
   // FYI: Note that only checking if mTopLeftHandle is replaced is enough.
   //      We're may be in hot path if user resizes an element a lot.  So,
   //      we should just add-ref mTopLeftHandle.
   auto setHandlePosition =
       [this](ManualNACPtr& aHandleElement, int32_t aNewX, int32_t aNewY)
           MOZ_CAN_RUN_SCRIPT_FOR_DEFINITION -> nsresult {
-    nsCOMPtr<nsStyledElement> handleStyledElement =
-        do_QueryInterface(aHandleElement.get());
+    RefPtr<nsStyledElement> handleStyledElement =
+        nsStyledElement::FromNodeOrNull(aHandleElement.get());
     if (!handleStyledElement) {
       return NS_OK;
     }
     nsresult rv = SetAnonymousElementPositionWithTransaction(
         *handleStyledElement, aNewX, aNewY);
     if (NS_FAILED(rv)) {
       NS_WARNING(
           "HTMLEditor::SetAnonymousElementPositionWithTransaction() failed");
@@ -696,18 +696,18 @@ nsresult HTMLEditor::StartResizing(Eleme
       mResizingShadow->UnsetAttr(kNameSpaceID_None, nsGkAtoms::_class, true);
   if (NS_WARN_IF(Destroyed())) {
     return NS_ERROR_EDITOR_DESTROYED;
   }
   NS_WARNING_ASSERTION(NS_SUCCEEDED(rvIgnored),
                        "Element::UnsetAttr(nsGkAtoms::_class) failed");
 
   // position it
-  if (nsCOMPtr<nsStyledElement> resizingShadowStyledElement =
-          do_QueryInterface(mResizingShadow.get())) {
+  if (RefPtr<nsStyledElement> resizingShadowStyledElement =
+          nsStyledElement::FromNodeOrNull(mResizingShadow.get())) {
     nsresult rv;
     rv = mCSSEditUtils->SetCSSPropertyPixelsWithTransaction(
         *resizingShadowStyledElement, *nsGkAtoms::width, mResizedObjectWidth);
     if (rv == NS_ERROR_EDITOR_DESTROYED) {
       NS_WARNING(
           "CSSEditUtils::SetCSSPropertyPixelsWithTransaction(nsGkAtoms::width) "
           "destroyed the editor");
       return NS_ERROR_EDITOR_DESTROYED;
@@ -887,18 +887,18 @@ nsresult HTMLEditor::SetResizingInfoPosi
   } else {
     // should only occur when mActivatedHandle is one of the 3 bottom-side
     // handles, but this is a reasonable default if it isn't any of them (?)
     infoYPosition = aY + aH;
   }
 
   // Offset info box by 20 so it's not directly under the mouse cursor.
   const int mouseCursorOffset = 20;
-  if (nsCOMPtr<nsStyledElement> resizingInfoStyledElement =
-          do_QueryInterface(mResizingInfo.get())) {
+  if (RefPtr<nsStyledElement> resizingInfoStyledElement =
+          nsStyledElement::FromNodeOrNull(mResizingInfo.get())) {
     nsresult rv;
     rv = mCSSEditUtils->SetCSSPropertyPixelsWithTransaction(
         *resizingInfoStyledElement, *nsGkAtoms::left,
         infoXPosition + mouseCursorOffset);
     if (rv == NS_ERROR_EDITOR_DESTROYED) {
       NS_WARNING(
           "CSSEditUtils::SetCSSPropertyPixelsWithTransaction(nsGkAtoms::left) "
           "destroyed the editor");
@@ -974,20 +974,22 @@ nsresult HTMLEditor::SetShadowPosition(E
                                        Element& aElement, int32_t aElementX,
                                        int32_t aElementY) {
   MOZ_ASSERT(&aShadowElement == mResizingShadow ||
              &aShadowElement == mPositioningShadow);
   RefPtr<Element> handlingShadowElement = &aShadowElement == mResizingShadow
                                               ? mResizingShadow.get()
                                               : mPositioningShadow.get();
 
-  if (nsCOMPtr<nsStyledElement> styledShadowElement =
-          do_QueryInterface(&aShadowElement)) {
+  if (nsStyledElement* styledShadowElement =
+          nsStyledElement::FromNode(&aShadowElement)) {
+    // MOZ_KnownLive(*styledShadowElement): It's aShadowElement whose lifetime
+    // must be guaranteed by caller because of MOZ_CAN_RUN_SCRIPT method.
     nsresult rv = SetAnonymousElementPositionWithTransaction(
-        *styledShadowElement, aElementX, aElementY);
+        MOZ_KnownLive(*styledShadowElement), aElementX, aElementY);
     if (NS_FAILED(rv)) {
       NS_WARNING(
           "HTMLEditor::SetAnonymousElementPositionWithTransaction() failed");
       return rv;
     }
   }
 
   if (!HTMLEditUtils::IsImage(&aElement)) {
@@ -1093,18 +1095,18 @@ nsresult HTMLEditor::OnMouseMove(MouseEv
     int32_t clientX = aMouseEvent->ClientX();
     int32_t clientY = aMouseEvent->ClientY();
 
     int32_t newX = GetNewResizingX(clientX, clientY);
     int32_t newY = GetNewResizingY(clientX, clientY);
     int32_t newWidth = GetNewResizingWidth(clientX, clientY);
     int32_t newHeight = GetNewResizingHeight(clientX, clientY);
 
-    if (nsCOMPtr<nsStyledElement> resizingShadowStyledElement =
-            do_QueryInterface(mResizingShadow.get())) {
+    if (RefPtr<nsStyledElement> resizingShadowStyledElement =
+            nsStyledElement::FromNodeOrNull(mResizingShadow.get())) {
       nsresult rv;
       rv = mCSSEditUtils->SetCSSPropertyPixelsWithTransaction(
           *resizingShadowStyledElement, *nsGkAtoms::left, newX);
       if (rv == NS_ERROR_EDITOR_DESTROYED) {
         NS_WARNING(
             "CSSEditUtils::SetCSSPropertyPixelsWithTransaction(nsGkAtoms::left)"
             " destroyed the editor");
         return NS_ERROR_EDITOR_DESTROYED;
@@ -1183,18 +1185,18 @@ nsresult HTMLEditor::OnMouseMove(MouseEv
     int32_t clientX = aMouseEvent->ClientX();
     int32_t clientY = aMouseEvent->ClientY();
 
     int32_t newX = mPositionedObjectX + clientX - mOriginalX;
     int32_t newY = mPositionedObjectY + clientY - mOriginalY;
 
     SnapToGrid(newX, newY);
 
-    if (nsCOMPtr<nsStyledElement> positioningShadowStyledElement =
-            do_QueryInterface(mPositioningShadow.get())) {
+    if (RefPtr<nsStyledElement> positioningShadowStyledElement =
+            nsStyledElement::FromNodeOrNull(mPositioningShadow.get())) {
       nsresult rv;
       rv = mCSSEditUtils->SetCSSPropertyPixelsWithTransaction(
           *positioningShadowStyledElement, *nsGkAtoms::left, newX);
       if (rv == NS_ERROR_EDITOR_DESTROYED) {
         NS_WARNING(
             "CSSEditUtils::SetCSSPropertyPixelsWithTransaction(nsGkAtoms::left)"
             " destroyed the editor");
         return NS_ERROR_EDITOR_DESTROYED;
@@ -1254,18 +1256,18 @@ nsresult HTMLEditor::SetFinalSizeWithTra
   y = top - ((mResizedObjectIsAbsolutelyPositioned)
                  ? mResizedObjectBorderTop + mResizedObjectMarginTop
                  : 0);
 
   // we want one transaction only from a user's point of view
   AutoPlaceholderBatch treatAsOneTransaction(*this,
                                              ScrollSelectionIntoView::Yes);
   RefPtr<Element> resizedElement(mResizedObject);
-  nsCOMPtr<nsStyledElement> resizedStyleElement =
-      do_QueryInterface(mResizedObject);
+  RefPtr<nsStyledElement> resizedStyleElement =
+      nsStyledElement::FromNodeOrNull(mResizedObject);
 
   if (mResizedObjectIsAbsolutelyPositioned && resizedStyleElement) {
     if (setHeight) {
       nsresult rv = mCSSEditUtils->SetCSSPropertyPixelsWithTransaction(
           *resizedStyleElement, *nsGkAtoms::top, y);
       if (rv == NS_ERROR_EDITOR_DESTROYED) {
         NS_WARNING(
             "CSSEditUtils::SetCSSPropertyPixelsWithTransaction(nsGkAtoms::"
--- a/editor/libeditor/HTMLInlineTableEditor.cpp
+++ b/editor/libeditor/HTMLInlineTableEditor.cpp
@@ -417,18 +417,18 @@ nsresult HTMLEditor::RefreshInlineTableE
   if (NS_FAILED(rv)) {
     NS_WARNING("HTMLEditor::GetTableSize() failed");
     return rv;
   }
 
   auto setInlineTableEditButtonPosition =
       [this](ManualNACPtr& aButtonElement, int32_t aNewX, int32_t aNewY)
           MOZ_CAN_RUN_SCRIPT_FOR_DEFINITION -> nsresult {
-    nsCOMPtr<nsStyledElement> buttonStyledElement =
-        do_QueryInterface(aButtonElement.get());
+    RefPtr<nsStyledElement> buttonStyledElement =
+        nsStyledElement::FromNodeOrNull(aButtonElement.get());
     if (!buttonStyledElement) {
       return NS_OK;
     }
     nsresult rv = SetAnonymousElementPositionWithTransaction(
         *buttonStyledElement, aNewX, aNewY);
     if (NS_FAILED(rv)) {
       NS_WARNING(
           "HTMLEditor::SetAnonymousElementPositionWithTransaction() failed");
--- a/editor/libeditor/HTMLStyleEditor.cpp
+++ b/editor/libeditor/HTMLStyleEditor.cpp
@@ -395,34 +395,36 @@ Result<bool, nsresult> HTMLEditor::Eleme
   // "text-decoration: underline", which decomposes into four different text-*
   // properties.  So for now, we just create a span, add the desired style, and
   // see if it matches.
   RefPtr<Element> newSpanElement = CreateHTMLContent(nsGkAtoms::span);
   if (!newSpanElement) {
     NS_WARNING("EditorBase::CreateHTMLContent(nsGkAtoms::span) failed");
     return false;
   }
-  nsCOMPtr<nsStyledElement> styledNewSpanElement =
-      do_QueryInterface(newSpanElement);
+  nsStyledElement* styledNewSpanElement =
+      nsStyledElement::FromNode(newSpanElement);
   if (!styledNewSpanElement) {
     return false;
   }
+  // MOZ_KnownLive(*styledNewSpanElement): It's newSpanElement whose type is
+  // RefPtr.
   Result<int32_t, nsresult> result =
       mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithoutTransaction(
-          *styledNewSpanElement, aProperty, aAttribute, aValue);
+          MOZ_KnownLive(*styledNewSpanElement), aProperty, aAttribute, aValue);
   if (result.isErr()) {
     // The call shouldn't return destroyed error because it must be
     // impossible to run script with modifying the new orphan node.
     MOZ_ASSERT_UNREACHABLE("How did you destroy this editor?");
     if (NS_WARN_IF(result.inspectErr() == NS_ERROR_EDITOR_DESTROYED)) {
       return Err(NS_ERROR_EDITOR_DESTROYED);
     }
     return false;
   }
-  nsCOMPtr<nsStyledElement> styledElement = do_QueryInterface(&aElement);
+  nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement);
   if (!styledElement) {
     return false;
   }
   return CSSEditUtils::DoStyledElementsHaveSameStyle(*styledNewSpanElement,
                                                      *styledElement);
 }
 
 nsresult HTMLEditor::SetInlinePropertyOnTextNode(
@@ -670,21 +672,24 @@ nsresult HTMLEditor::SetInlinePropertyOn
         NS_WARNING(
             "HTMLEditor::InsertContainerWithTransaction(nsGkAtoms::span) "
             "failed");
         return NS_ERROR_FAILURE;
       }
     }
 
     // Add the CSS styles corresponding to the HTML style request
-    if (nsCOMPtr<nsStyledElement> spanStyledElement =
-            do_QueryInterface(spanElement)) {
+    if (nsStyledElement* spanStyledElement =
+            nsStyledElement::FromNode(spanElement)) {
+      // MOZ_KnownLive(*spanStyledElement): It's spanElement whose type is
+      // RefPtr.
       Result<int32_t, nsresult> result =
           mCSSEditUtils->SetCSSEquivalentToHTMLStyleWithTransaction(
-              *spanStyledElement, &aProperty, aAttribute, &aValue);
+              MOZ_KnownLive(*spanStyledElement), &aProperty, aAttribute,
+              &aValue);
       if (result.isErr()) {
         if (result.inspectErr() == NS_ERROR_EDITOR_DESTROYED) {
           NS_WARNING(
               "CSSEditUtils::SetCSSEquivalentToHTMLStyleWithTransaction() "
               "destroyed the editor");
           return NS_ERROR_EDITOR_DESTROYED;
         }
         NS_WARNING(
@@ -1210,22 +1215,23 @@ nsresult HTMLEditor::RemoveStyleInside(E
   }
 
   // Then, remove CSS style if specified.
   // XXX aElement may have already been removed from the DOM tree.  Why
   //     do we keep handling aElement here??
   if (CSSEditUtils::IsCSSEditableProperty(&aElement, aProperty, aAttribute) &&
       CSSEditUtils::HaveSpecifiedCSSEquivalentStyles(aElement, aProperty,
                                                      aAttribute)) {
-    if (nsCOMPtr<nsStyledElement> styledElement =
-            do_QueryInterface(&aElement)) {
+    if (nsStyledElement* styledElement = nsStyledElement::FromNode(&aElement)) {
       // If aElement has CSS declaration of the given style, remove it.
+      // MOZ_KnownLive(*styledElement): It's aElement and its lifetime must be
+      // guaranteed by the caller because of MOZ_CAN_RUN_SCRIPT method.
       nsresult rv =
           mCSSEditUtils->RemoveCSSEquivalentToHTMLStyleWithTransaction(
-              *styledElement, aProperty, aAttribute, nullptr);
+              MOZ_KnownLive(*styledElement), aProperty, aAttribute, nullptr);
       if (rv == NS_ERROR_EDITOR_DESTROYED) {
         NS_WARNING(
             "CSSEditUtils::RemoveCSSEquivalentToHTMLStyleWithTransaction() "
             "destroyed the editor");
         return NS_ERROR_EDITOR_DESTROYED;
       }
       NS_WARNING_ASSERTION(
           NS_SUCCEEDED(rv),
--- a/layout/generic/ScrollbarActivity.cpp
+++ b/layout/generic/ScrollbarActivity.cpp
@@ -287,18 +287,18 @@ void ScrollbarActivity::SetIsActive(bool
     HoveredScrollbar(nullptr);
   }
 
   SetBooleanAttribute(GetHorizontalScrollbar(), nsGkAtoms::active, mIsActive);
   SetBooleanAttribute(GetVerticalScrollbar(), nsGkAtoms::active, mIsActive);
 }
 
 static void SetOpacityOnElement(nsIContent* aContent, double aOpacity) {
-  nsCOMPtr<nsStyledElement> inlineStyleContent = do_QueryInterface(aContent);
-  if (inlineStyleContent) {
+  if (RefPtr<nsStyledElement> inlineStyleContent =
+          nsStyledElement::FromNodeOrNull(aContent)) {
     nsICSSDeclaration* decl = inlineStyleContent->Style();
     nsAutoCString str;
     str.AppendFloat(aOpacity);
     decl->SetProperty("opacity"_ns, str, EmptyString(), IgnoreErrors());
   }
 }
 
 bool ScrollbarActivity::UpdateOpacity(TimeStamp aTime) {
@@ -318,18 +318,18 @@ bool ScrollbarActivity::UpdateOpacity(Ti
   SetOpacityOnElement(GetVerticalScrollbar(), opacity);
   if (!weakFrame.IsAlive()) {
     return false;
   }
   return true;
 }
 
 static void UnsetOpacityOnElement(nsIContent* aContent) {
-  nsCOMPtr<nsStyledElement> inlineStyleContent = do_QueryInterface(aContent);
-  if (inlineStyleContent) {
+  if (RefPtr<nsStyledElement> inlineStyleContent =
+          nsStyledElement::FromNodeOrNull(aContent)) {
     nsICSSDeclaration* decl = inlineStyleContent->Style();
     nsAutoString dummy;
     decl->RemoveProperty("opacity"_ns, dummy, IgnoreErrors());
   }
 }
 
 bool ScrollbarActivity::SetIsFading(bool aNewFading) {
   if (mIsFading == aNewFading) return true;
--- a/layout/xul/nsResizerFrame.cpp
+++ b/layout/xul/nsResizerFrame.cpp
@@ -418,44 +418,40 @@ void nsResizerFrame::ResizeContent(nsICo
     if (aDirection.mHorizontal) {
       aContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::width,
                                      aSizeInfo.width, true);
     }
     if (aDirection.mVertical) {
       aContent->AsElement()->SetAttr(kNameSpaceID_None, nsGkAtoms::height,
                                      aSizeInfo.height, true);
     }
-  } else {
-    nsCOMPtr<nsStyledElement> inlineStyleContent = do_QueryInterface(aContent);
-    if (inlineStyleContent) {
-      nsICSSDeclaration* decl = inlineStyleContent->Style();
+  } else if (RefPtr<nsStyledElement> inlineStyleContent =
+                 nsStyledElement::FromNode(aContent)) {
+    nsICSSDeclaration* decl = inlineStyleContent->Style();
 
-      if (aOriginalSizeInfo) {
-        decl->GetPropertyValue("width"_ns, aOriginalSizeInfo->width);
-        decl->GetPropertyValue("height"_ns, aOriginalSizeInfo->height);
-      }
+    if (aOriginalSizeInfo) {
+      decl->GetPropertyValue("width"_ns, aOriginalSizeInfo->width);
+      decl->GetPropertyValue("height"_ns, aOriginalSizeInfo->height);
+    }
 
-      // only set the property if the element could have changed in that
-      // direction
-      if (aDirection.mHorizontal) {
-        NS_ConvertUTF16toUTF8 widthstr(aSizeInfo.width);
-        if (!widthstr.IsEmpty() &&
-            !Substring(widthstr, widthstr.Length() - 2, 2).EqualsLiteral("px"))
-          widthstr.AppendLiteral("px");
-        decl->SetProperty("width"_ns, widthstr, EmptyString(), IgnoreErrors());
-      }
-      if (aDirection.mVertical) {
-        NS_ConvertUTF16toUTF8 heightstr(aSizeInfo.height);
-        if (!heightstr.IsEmpty() &&
-            !Substring(heightstr, heightstr.Length() - 2, 2)
-                 .EqualsLiteral("px"))
-          heightstr.AppendLiteral("px");
-        decl->SetProperty("height"_ns, heightstr, EmptyString(),
-                          IgnoreErrors());
-      }
+    // only set the property if the element could have changed in that
+    // direction
+    if (aDirection.mHorizontal) {
+      NS_ConvertUTF16toUTF8 widthstr(aSizeInfo.width);
+      if (!widthstr.IsEmpty() &&
+          !Substring(widthstr, widthstr.Length() - 2, 2).EqualsLiteral("px"))
+        widthstr.AppendLiteral("px");
+      decl->SetProperty("width"_ns, widthstr, EmptyString(), IgnoreErrors());
+    }
+    if (aDirection.mVertical) {
+      NS_ConvertUTF16toUTF8 heightstr(aSizeInfo.height);
+      if (!heightstr.IsEmpty() &&
+          !Substring(heightstr, heightstr.Length() - 2, 2).EqualsLiteral("px"))
+        heightstr.AppendLiteral("px");
+      decl->SetProperty("height"_ns, heightstr, EmptyString(), IgnoreErrors());
     }
   }
 }
 
 /* static */
 void nsResizerFrame::MaybePersistOriginalSize(nsIContent* aContent,
                                               const SizeInfo& aSizeInfo) {
   nsresult rv;