Merge mozilla-central to inbound. a=merge CLOSED TREE
authorMargareta Eliza Balazs <ebalazs@mozilla.com>
Wed, 05 Sep 2018 15:43:59 +0300
changeset 490577 e841c95ba671adc63c814de4e37f2413d6201cbf
parent 490576 e9287b5dfb52ee72c1d97dd546cf4b3f15c55dfb (current diff)
parent 490502 26990836dc5cc3cd1b8027392b79210e71094dc3 (diff)
child 490578 3d23c2f43b8a5ccd1dd21f1240689cea1566deed
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)
reviewersmerge
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
Merge mozilla-central to inbound. a=merge CLOSED TREE
dom/base/SelectionChangeListener.cpp
dom/base/SelectionChangeListener.h
--- a/accessible/base/FocusManager.h
+++ b/accessible/base/FocusManager.h
@@ -39,16 +39,21 @@ public:
   /**
    * Return true if the given accessible is an active item, i.e. an item that
    * is current within the active widget.
    */
   inline bool IsActiveItem(const Accessible* aAccessible)
     { return aAccessible == mActiveItem; }
 
   /**
+   * Return DOM node having DOM focus.
+   */
+  nsINode* FocusedDOMNode() const;
+
+  /**
    * Return true if given DOM node has DOM focus.
    */
   inline bool HasDOMFocus(const nsINode* aNode) const
     { return aNode == FocusedDOMNode(); }
 
   /**
    * Return true if focused accessible is within the given container.
    */
@@ -109,21 +114,16 @@ public:
 protected:
   FocusManager();
 
 private:
   FocusManager(const FocusManager&);
   FocusManager& operator =(const FocusManager&);
 
   /**
-   * Return DOM node having DOM focus.
-   */
-  nsINode* FocusedDOMNode() const;
-
-  /**
    * Return DOM document having DOM focus.
    */
   nsIDocument* FocusedDOMDocument() const;
 
 private:
   RefPtr<Accessible> mActiveItem;
   RefPtr<Accessible> mActiveARIAMenubar;
 };
--- a/accessible/generic/DocAccessible.cpp
+++ b/accessible/generic/DocAccessible.cpp
@@ -916,16 +916,17 @@ DocAccessible::AttributeChangedImpl(Acce
     RefPtr<AccEvent> event =
       new AccStateChangeEvent(aAccessible, states::BUSY, isOn);
     FireDelayedEvent(event);
     return;
   }
 
   if (aAttribute == nsGkAtoms::id) {
     RelocateARIAOwnedIfNeeded(elm);
+    ARIAActiveDescendantIDMaybeMoved(elm);
   }
 
   // ARIA or XUL selection
   if ((aAccessible->GetContent()->IsXULElement() &&
        aAttribute == nsGkAtoms::selected) ||
       aAttribute == nsGkAtoms::aria_selected) {
     Accessible* widget =
       nsAccUtils::GetSelectableContainer(aAccessible, aAccessible->State());
@@ -2473,8 +2474,51 @@ DocAccessible::DispatchScrollingEvent(ui
 
   RefPtr<AccEvent> event = new AccScrollingEvent(aEventType, this,
                                                  scrollPoint.x, scrollPoint.y,
                                                  scrollRange.width,
                                                  scrollRange.height);
 
   nsEventShell::FireEvent(event);
 }
+
+void
+DocAccessible::ARIAActiveDescendantIDMaybeMoved(dom::Element* aElm)
+{
+  nsINode* focusNode = FocusMgr()->FocusedDOMNode();
+  // The focused element must be within this document.
+  if (!focusNode || focusNode->OwnerDoc() != mDocumentNode) {
+    return;
+  }
+
+  dom::Element* focusElm = nullptr;
+  if (focusNode == mDocumentNode) {
+    // The document is focused, so look for aria-activedescendant on the
+    // body/root.
+    focusElm = Elm();
+    if (!focusElm) {
+      return;
+    }
+  } else {
+    MOZ_ASSERT(focusNode->IsElement());
+    focusElm = focusNode->AsElement();
+  }
+
+  // Check if the focus has aria-activedescendant and whether
+  // it refers to the id just set on aElm.
+  nsAutoString id;
+  aElm->GetAttr(kNameSpaceID_None, nsGkAtoms::id, id);
+  if (!focusElm->AttrValueIs(kNameSpaceID_None,
+      nsGkAtoms::aria_activedescendant, id, eCaseMatters)) {
+    return;
+  }
+
+  // The aria-activedescendant target has probably changed.
+  Accessible* acc = GetAccessibleEvenIfNotInMapOrContainer(focusNode);
+  if (!acc) {
+    return;
+  }
+  
+  // The active descendant might have just been inserted and may not be in the
+  // tree yet. Therefore, schedule this async to ensure the tree is up to date.
+  mNotificationController->ScheduleNotification<DocAccessible, Accessible>
+    (this, &DocAccessible::ARIAActiveDescendantChanged, acc);
+}
--- a/accessible/generic/DocAccessible.h
+++ b/accessible/generic/DocAccessible.h
@@ -579,16 +579,26 @@ protected:
    *
    * @param aTimer    [in] the timer object
    * @param aClosure  [in] the document accessible where scrolling happens
    */
   static void ScrollTimerCallback(nsITimer* aTimer, void* aClosure);
 
   void DispatchScrollingEvent(uint32_t aEventType);
 
+  /**
+   * Check if an id attribute change affects aria-activedescendant and handle
+   * the aria-activedescendant change if appropriate.
+   * If the currently focused element has aria-activedescendant and an
+   * element's id changes to match this, the id was probably moved from the
+   * previous active descendant, thus making this element the new active
+   * descendant. In that case, accessible focus must be changed accordingly.
+   */
+  void ARIAActiveDescendantIDMaybeMoved(dom::Element* aElm);
+
 protected:
 
   /**
    * State and property flags, kept by mDocFlags.
    */
   enum {
     // Whether scroll listeners were added.
     eScrollInitialized = 1 << 0,
--- a/accessible/tests/mochitest/events/test_focus_aria_activedescendant.html
+++ b/accessible/tests/mochitest/events/test_focus_aria_activedescendant.html
@@ -45,23 +45,31 @@ https://bugzilla.mozilla.org/show_bug.cg
         getNode(aID).removeAttribute("aria-activedescendant");
       };
 
       this.getID = function clearARIAActiveDescendant_getID() {
         return "clear aria-activedescendant on container " + aID;
       };
     }
 
-    function changeARIAActiveDescendantInvalid(aID) {
+    /**
+     * Change aria-activedescendant to an invalid (non-existent) id.
+     * Ensure that focus is fired on the element itself.
+     */
+    function changeARIAActiveDescendantInvalid(aID, aInvalidID) {
+      if (!aInvalidID) {
+        aInvalidID = "invalid";
+      }
+
       this.eventSeq = [
         new focusChecker(aID)
       ];
 
       this.invoke = function changeARIAActiveDescendant_invoke() {
-        getNode(aID).setAttribute("aria-activedescendant", "invalid");
+        getNode(aID).setAttribute("aria-activedescendant", aInvalidID);
       };
 
       this.getID = function changeARIAActiveDescendant_getID() {
         return "change aria-activedescendant to invalid id";
       };
     }
     
     function insertItemNFocus(aID, aNewItemID) {
@@ -82,34 +90,66 @@ https://bugzilla.mozilla.org/show_bug.cg
         container.setAttribute("aria-activedescendant", aNewItemID);
       };
 
       this.getID = function insertItemNFocus_getID() {
         return "insert new node and focus it with ID: " + aNewItemID;
       };
     }
 
+    /**
+     * Change the id of an element to another id which is the target of
+     * aria-activedescendant.
+     * If another element already has the desired id, remove it from that
+     * element first.
+     * Ensure that focus is fired on the target element which was given the
+     * desired id.
+     * @param aFromID The existing id of the target element.
+     * @param aToID The desired id to be given to the target element.
+    */
+    function moveARIAActiveDescendantID(aFromID, aToID) {
+      this.eventSeq = [
+        new focusChecker(aToID)
+      ];
+
+      this.invoke = function moveARIAActiveDescendantID_invoke() {
+        let orig = document.getElementById(aToID);
+        if (orig) {
+          orig.id = "";
+        }
+        document.getElementById(aFromID).id = aToID;
+      };
+
+      this.getID = function moveARIAActiveDescendantID_getID() {
+        return "move aria-activedescendant id " + aToID;
+      };
+    }
+
     var gQueue = null;
     function doTest() {
       gQueue = new eventQueue();
 
       gQueue.push(new synthFocus("listbox", new focusChecker("item1")));
       gQueue.push(new changeARIAActiveDescendant("listbox", "item2"));
       gQueue.push(new changeARIAActiveDescendant("listbox", "item3"));
 
       gQueue.push(new synthFocus("combobox_entry", new focusChecker("combobox_entry")));
       gQueue.push(new changeARIAActiveDescendant("combobox", "combobox_option2"));
 
       gQueue.push(new synthFocus("listbox", new focusChecker("item3")));
       gQueue.push(new insertItemNFocus("listbox", "item4"));
 
       gQueue.push(new clearARIAActiveDescendant("listbox"));
       gQueue.push(new changeARIAActiveDescendant("listbox", "item1"));
-      gQueue.push(new changeARIAActiveDescendantInvalid("listbox"));
-      gQueue.push(new changeARIAActiveDescendant("listbox", "item1"));
+      gQueue.push(new changeARIAActiveDescendantInvalid("listbox", "invalid"));
+
+      gQueue.push(new changeARIAActiveDescendant("listbox", "roaming"));
+      gQueue.push(new moveARIAActiveDescendantID("roaming2", "roaming"));
+      gQueue.push(new changeARIAActiveDescendantInvalid("listbox", "roaming3"));
+      gQueue.push(new moveARIAActiveDescendantID("roaming", "roaming3"));
 
       gQueue.invoke(); // Will call SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
 </head>
@@ -129,16 +169,18 @@ https://bugzilla.mozilla.org/show_bug.cg
   <div id="content" style="display: none"></div>
   <pre id="test">
   </pre>
 
   <div role="listbox" aria-activedescendant="item1" id="listbox" tabindex="1"
        aria-owns="item3">
     <div role="listitem" id="item1">item1</div>
     <div role="listitem" id="item2">item2</div>
+    <div role="listitem" id="roaming">roaming</div>
+    <div role="listitem" id="roaming2">roaming2</div>
   </div>
   <div role="listitem" id="item3">item3</div>
 
   <div role="combobox" id="combobox">
     <input id="combobox_entry">
     <ul>
       <li role="option" id="combobox_option1">option1</li>
       <li role="option" id="combobox_option2">option2</li>
--- a/accessible/windows/msaa/AccessibleWrap.h
+++ b/accessible/windows/msaa/AccessibleWrap.h
@@ -15,17 +15,17 @@
 #include "ia2AccessibleHyperlink.h"
 #include "ia2AccessibleValue.h"
 #include "mozilla/a11y/AccessibleHandler.h"
 #include "mozilla/a11y/MsaaIdGenerator.h"
 #include "mozilla/a11y/ProxyAccessible.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/mscom/Utils.h"
 
-#ifdef __GNUC__
+#if defined(__GNUC__) || defined(__clang__)
 // Inheriting from both XPCOM and MSCOM interfaces causes a lot of warnings
 // about virtual functions being hidden by each other. This is done by
 // design, so silence the warning.
 #pragma GCC diagnostic ignored "-Woverloaded-virtual"
 #endif
 
 namespace mozilla {
 namespace a11y {
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -1410,17 +1410,17 @@ pref("identity.mobilepromo.ios", "https:
 // Developer Edition profile.
 #ifdef MOZ_DEV_EDITION
 pref("identity.fxaccounts.migrateToDevEdition", true);
 #else
 pref("identity.fxaccounts.migrateToDevEdition", false);
 #endif
 
 // If activated, send tab will use the new FxA commands backend.
-pref("identity.fxaccounts.commands.enabled", false);
+pref("identity.fxaccounts.commands.enabled", true);
 
 // On GTK, we now default to showing the menubar only when alt is pressed:
 #ifdef MOZ_WIDGET_GTK
 pref("ui.key.menuAccessKeyFocuses", true);
 #endif
 
 #ifdef NIGHTLY_BUILD
 pref("media.eme.vp9-in-mp4.enabled", true);
--- a/browser/base/content/tabbrowser.js
+++ b/browser/base/content/tabbrowser.js
@@ -1089,17 +1089,19 @@ window._gBrowser = {
     } else if (gMultiProcessBrowser && activeEl != newBrowser && activeEl != newTab) {
       // In e10s, if focus isn't already in the tabstrip or on the new browser,
       // and the new browser's previous focus wasn't in the url bar but focus is
       // there now, we need to adjust focus further.
       let keepFocusOnUrlBar = newBrowser &&
         newBrowser._urlbarFocused &&
         gURLBar &&
         gURLBar.focused;
-      if (!keepFocusOnUrlBar) {
+      // In an HTML document (built with MOZ_BROWSER_XHTML), the activeElement
+      // can be null, so check before attempting to blur it (Bug 1485157).
+      if (!keepFocusOnUrlBar && document.activeElement) {
         // Clear focus so that _adjustFocusAfterTabSwitch can detect if
         // some element has been focused and respect that.
         document.activeElement.blur();
       }
     }
   },
 
   _adjustFocusAfterTabSwitch(newTab) {
--- a/browser/components/extensions/parent/ext-browser.js
+++ b/browser/components/extensions/parent/ext-browser.js
@@ -272,17 +272,17 @@ class TabTracker extends TabTrackerBase 
   }
 
   init() {
     if (this.initialized) {
       return;
     }
     this.initialized = true;
 
-    this.adoptedTabs = new WeakMap();
+    this.adoptedTabs = new WeakSet();
 
     this._handleWindowOpen = this._handleWindowOpen.bind(this);
     this._handleWindowClose = this._handleWindowClose.bind(this);
 
     windowTracker.addListener("TabClose", this);
     windowTracker.addListener("TabOpen", this);
     windowTracker.addListener("TabSelect", this);
     windowTracker.addListener("TabMultiSelect", this);
@@ -330,29 +330,45 @@ class TabTracker extends TabTrackerBase 
     if (nativeTab.linkedBrowser) {
       this._browsers.set(nativeTab.linkedBrowser, id);
     }
     this._tabIds.set(id, nativeTab);
   }
 
   /**
    * Handles tab adoption when a tab is moved between windows.
-   * Ensures the new tab will have the same ID as the old one,
-   * and emits a "tab-adopted" event.
+   * Ensures the new tab will have the same ID as the old one, and
+   * emits "tab-adopted", "tab-detached" and "tab-attached" events.
    *
    * @param {NativeTab} adoptingTab
    *        The tab which is being opened and adopting `adoptedTab`.
    * @param {NativeTab} adoptedTab
    *        The tab which is being closed and adopted by `adoptingTab`.
    */
   adopt(adoptingTab, adoptedTab) {
-    if (!this.adoptedTabs.has(adoptedTab)) {
-      this.adoptedTabs.set(adoptedTab, adoptingTab);
-      this.setId(adoptingTab, this.getId(adoptedTab));
-      this.emit("tab-adopted", adoptingTab, adoptedTab);
+    if (this.adoptedTabs.has(adoptedTab)) {
+      // The adoption has already been handled.
+      return;
+    }
+    this.adoptedTabs.add(adoptedTab);
+    let tabId = this.getId(adoptedTab);
+    this.setId(adoptingTab, tabId);
+    this.emit("tab-adopted", adoptingTab, adoptedTab);
+    if (this.has("tab-detached")) {
+      let nativeTab = adoptedTab;
+      let adoptedBy = adoptingTab;
+      let oldWindowId = windowTracker.getId(nativeTab.ownerGlobal);
+      let oldPosition = nativeTab._tPos;
+      this.emit("tab-detached", {nativeTab, adoptedBy, tabId, oldWindowId, oldPosition});
+    }
+    if (this.has("tab-attached")) {
+      let nativeTab = adoptingTab;
+      let newWindowId = windowTracker.getId(nativeTab.ownerGlobal);
+      let newPosition = nativeTab._tPos;
+      this.emit("tab-attached", {nativeTab, tabId, newWindowId, newPosition});
     }
   }
 
   _handleTabDestroyed(event, {nativeTab}) {
     let id = this._tabs.get(nativeTab);
     if (id) {
       this._tabs.delete(nativeTab);
       if (this._tabIds.get(id) === nativeTab) {
@@ -412,44 +428,39 @@ class TabTracker extends TabTrackerBase 
         if (adoptedTab) {
           // This tab is being created to adopt a tab from a different window.
           // Handle the adoption.
           this.adopt(nativeTab, adoptedTab);
 
           adoptedTab.linkedBrowser.messageManager.sendAsyncMessage("Extension:SetFrameData", {
             windowId: windowTracker.getId(nativeTab.ownerGlobal),
           });
-        }
-
-        // Save the current tab, since the newly-created tab will likely be
-        // active by the time the promise below resolves and the event is
-        // dispatched.
-        let currentTab = nativeTab.ownerGlobal.gBrowser.selectedTab;
+        } else {
+          // Save the current tab, since the newly-created tab will likely be
+          // active by the time the promise below resolves and the event is
+          // dispatched.
+          let currentTab = nativeTab.ownerGlobal.gBrowser.selectedTab;
 
-        // We need to delay sending this event until the next tick, since the
-        // tab does not have its final index when the TabOpen event is dispatched.
-        Promise.resolve().then(() => {
-          if (event.detail.adoptedTab) {
-            this.emitAttached(event.originalTarget);
-          } else {
+          // We need to delay sending this event until the next tick, since the
+          // tab could have been created with a lazy browser but still not have
+          // been assigned a SessionStore tab state with the URL and title.
+          Promise.resolve().then(() => {
             this.emitCreated(event.originalTarget, currentTab);
-          }
-        });
+          });
+        }
         break;
 
       case "TabClose":
         let {adoptedBy} = event.detail;
         if (adoptedBy) {
           // This tab is being closed because it was adopted by a new window.
           // Handle the adoption in case it was created as the first tab of a
           // new window, and did not have an `adoptedTab` detail when it was
           // opened.
           this.adopt(adoptedBy, nativeTab);
-
-          this.emitDetached(nativeTab, adoptedBy);
         } else {
           this.emitRemoved(nativeTab, false);
         }
         break;
 
       case "TabSelect":
         // Because we are delaying calling emitCreated above, we also need to
         // delay sending this event because it shouldn't fire before onCreated.
@@ -496,33 +507,18 @@ class TabTracker extends TabTrackerBase 
   _handleWindowOpen(window) {
     const tabToAdopt = window.gBrowserInit.getTabToAdopt();
     if (tabToAdopt) {
       // Note that this event handler depends on running before the
       // delayed startup code in browser.js, which is currently triggered
       // by the first MozAfterPaint event. That code handles finally
       // adopting the tab, and clears it from the arguments list in the
       // process, so if we run later than it, we're too late.
-      let nativeTab = tabToAdopt;
       let adoptedBy = window.gBrowser.tabs[0];
-      this.adopt(adoptedBy, nativeTab);
-
-      // We need to be sure to fire this event after the onDetached event
-      // for the original tab.
-      let listener = (event, details) => {
-        if (details.nativeTab === nativeTab) {
-          this.off("tab-detached", listener);
-
-          Promise.resolve().then(() => {
-            this.emitAttached(details.adoptedBy);
-          });
-        }
-      };
-
-      this.on("tab-detached", listener);
+      this.adopt(adoptedBy, tabToAdopt);
     } else {
       for (let nativeTab of window.gBrowser.tabs) {
         this.emitCreated(nativeTab);
       }
 
       // emitActivated to trigger tab.onActivated/tab.onHighlighted for a newly opened window.
       this.emitActivated(window.gBrowser.tabs[0]);
       if (this.has("tabs-highlighted")) {
@@ -536,19 +532,17 @@ class TabTracker extends TabTrackerBase 
    * and dispatches the necessary events for it.
    *
    * @param {DOMWindow} window
    *        The window being closed.
    * @private
    */
   _handleWindowClose(window) {
     for (let nativeTab of window.gBrowser.tabs) {
-      if (this.adoptedTabs.has(nativeTab)) {
-        this.emitDetached(nativeTab, this.adoptedTabs.get(nativeTab));
-      } else {
+      if (!this.adoptedTabs.has(nativeTab)) {
         this.emitRemoved(nativeTab, true);
       }
     }
   }
 
   /**
    * Emits a "tab-activated" event for the given tab element.
    *
@@ -571,47 +565,16 @@ class TabTracker extends TabTrackerBase 
    */
   emitHighlighted(window) {
     let tabIds = window.gBrowser.selectedTabs.map(tab => this.getId(tab));
     let windowId = windowTracker.getId(window);
     this.emit("tabs-highlighted", {tabIds, windowId});
   }
 
   /**
-   * Emits a "tab-attached" event for the given tab element.
-   *
-   * @param {NativeTab} nativeTab
-   *        The tab element in the window to which the tab is being attached.
-   * @private
-   */
-  emitAttached(nativeTab) {
-    let newWindowId = windowTracker.getId(nativeTab.ownerGlobal);
-    let tabId = this.getId(nativeTab);
-
-    this.emit("tab-attached", {nativeTab, tabId, newWindowId, newPosition: nativeTab._tPos});
-  }
-
-  /**
-   * Emits a "tab-detached" event for the given tab element.
-   *
-   * @param {NativeTab} nativeTab
-   *        The tab element in the window from which the tab is being detached.
-   * @param {NativeTab} adoptedBy
-   *        The tab element in the window to which detached tab is being moved,
-   *        and will adopt this tab's contents.
-   * @private
-   */
-  emitDetached(nativeTab, adoptedBy) {
-    let oldWindowId = windowTracker.getId(nativeTab.ownerGlobal);
-    let tabId = this.getId(nativeTab);
-
-    this.emit("tab-detached", {nativeTab, adoptedBy, tabId, oldWindowId, oldPosition: nativeTab._tPos});
-  }
-
-  /**
    * Emits a "tab-created" event for the given tab element.
    *
    * @param {NativeTab} nativeTab
    *        The tab element which is being created.
    * @param {NativeTab} [currentTab]
    *        The tab element for the currently active tab.
    * @private
    */
--- a/browser/components/extensions/test/browser/browser_ext_tabs_events.js
+++ b/browser/components/extensions/test/browser/browser_ext_tabs_events.js
@@ -77,19 +77,21 @@ add_task(async function testTabEvents() 
       browser.test.assertEq(tab.id, created.tab.id, "Got expected tab ID");
       browser.test.assertEq(oldIndex, created.tab.index, "Got expected tab index");
 
 
       browser.test.log("Move tab to window 2");
       await browser.tabs.move([tab.id], {windowId: otherWindowId, index: 0});
 
       let [detached, attached] = await expectEvents(["onDetached", "onAttached"]);
+      browser.test.assertEq(tab.id, detached.tabId, "Expected onDetached tab ID");
       browser.test.assertEq(oldIndex, detached.oldPosition, "Expected old index");
       browser.test.assertEq(windowId, detached.oldWindowId, "Expected old window ID");
 
+      browser.test.assertEq(tab.id, attached.tabId, "Expected onAttached tab ID");
       browser.test.assertEq(0, attached.newPosition, "Expected new index");
       browser.test.assertEq(otherWindowId, attached.newWindowId, "Expected new window ID");
 
 
       browser.test.log("Move tab within the same window");
       let [moved] = await browser.tabs.move([tab.id], {index: 1});
       browser.test.assertEq(1, moved.index, "Expected new index");
 
@@ -136,24 +138,39 @@ add_task(async function testTabEvents() 
       let [window] = await Promise.all([
         browser.windows.create({tabId: tab.id}),
         promiseAttached,
       ]);
 
       [detached, attached] = await expectEvents(["onDetached", "onAttached"]);
 
       browser.test.assertEq(tab.id, detached.tabId, "Expected onDetached tab ID");
+      browser.test.assertEq(1, detached.oldPosition, "Expected onDetached old index");
+      browser.test.assertEq(windowId, detached.oldWindowId, "Expected onDetached old window ID");
 
       browser.test.assertEq(tab.id, attached.tabId, "Expected onAttached tab ID");
       browser.test.assertEq(0, attached.newPosition, "Expected onAttached new index");
       browser.test.assertEq(window.id, attached.newWindowId,
                             "Expected onAttached new window id");
 
-      browser.test.log("Close the new window");
-      await browser.windows.remove(window.id);
+      browser.test.log("Close the new window by moving the tab into former window");
+      await browser.tabs.move(tab.id, {index: 1, windowId});
+      [detached, attached] = await expectEvents(["onDetached", "onAttached"]);
+
+      browser.test.assertEq(tab.id, detached.tabId, "Expected onDetached tab ID");
+      browser.test.assertEq(0, detached.oldPosition, "Expected onDetached old index");
+      browser.test.assertEq(window.id, detached.oldWindowId, "Expected onDetached old window ID");
+
+      browser.test.assertEq(tab.id, attached.tabId, "Expected onAttached tab ID");
+      browser.test.assertEq(1, attached.newPosition, "Expected onAttached new index");
+      browser.test.assertEq(windowId, attached.newWindowId,
+                            "Expected onAttached new window id");
+
+      browser.test.log("Remove the tab");
+      await browser.tabs.remove(tab.id);
 
       browser.test.notifyPass("tabs-events");
     } catch (e) {
       browser.test.fail(`${e} :: ${e.stack}`);
       browser.test.notifyFail("tabs-events");
     }
   }
 
--- a/browser/modules/ThemeVariableMap.jsm
+++ b/browser/modules/ThemeVariableMap.jsm
@@ -92,16 +92,20 @@ const ThemeVariableMap = [
       // Drop alpha channel
       return `rgb(${r}, ${g}, ${b})`;
     },
   }],
   ["--sidebar-text-color", {
     lwtProperty: "sidebar_text",
     optionalElementID: "sidebar-box",
   }],
+  ["--sidebar-border-color", {
+    lwtProperty: "sidebar_border",
+    optionalElementID: "browser",
+  }],
 ];
 
 const ThemeContentPropertyList = [
   "ntp_background",
   "ntp_text",
   "sidebar",
   "sidebar_highlight",
   "sidebar_highlight_text",
--- a/build/autoconf/expandlibs.m4
+++ b/build/autoconf/expandlibs.m4
@@ -9,29 +9,38 @@ dnl =
 dnl = Check what kind of list files are supported by the
 dnl = linker
 dnl =
 dnl ========================================================
 
 AC_CACHE_CHECK(what kind of list files are supported by the linker,
     EXPAND_LIBS_LIST_STYLE,
     [echo "int main() {return 0;}" > conftest.${ac_ext}
-     if AC_TRY_COMMAND(${CC-cc} -o conftest.${OBJ_SUFFIX} -c $CFLAGS $CPPFLAGS conftest.${ac_ext} 1>&5) && test -s conftest.${OBJ_SUFFIX}; then
+     dnl Because BFD ld doesn't work with LTO + linker scripts, we
+     dnl must pass the LTO CFLAGS to the compile command, and the LTO
+     dnl LDFLAGS to all subsequent link commands.
+     dnl https://sourceware.org/bugzilla/show_bug.cgi?id=23600
+     if AC_TRY_COMMAND(${CC-cc} -o conftest.${OBJ_SUFFIX} -c $MOZ_LTO_CFLAGS $CFLAGS $CPPFLAGS conftest.${ac_ext} 1>&5) && test -s conftest.${OBJ_SUFFIX}; then
          echo "INPUT(conftest.${OBJ_SUFFIX})" > conftest.list
-         if AC_TRY_COMMAND(${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS conftest.list $LIBS 1>&5) && test -s conftest${ac_exeext}; then
+         if test "$OS_TARGET" = WINNT; then
+             link="$LINKER -OUT:conftest${ac_exeext}"
+         else
+             link="${CC-cc} -o conftest${ac_exeext}"
+         fi
+         if AC_TRY_COMMAND($link $MOZ_LTO_LDFLAGS $LDFLAGS conftest.list $LIBS 1>&5) && test -s conftest${ac_exeext}; then
              EXPAND_LIBS_LIST_STYLE=linkerscript
          else
              echo "conftest.${OBJ_SUFFIX}" > conftest.list
              dnl -filelist is for the OS X linker.  We need to try -filelist
              dnl first because clang understands @file, but may pass an
              dnl oversized argument list to the linker depending on the
              dnl contents of @file.
-             if AC_TRY_COMMAND(${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS [-Wl,-filelist,conftest.list] $LIBS 1>&5) && test -s conftest${ac_exeext}; then
+             if AC_TRY_COMMAND($link $MOZ_LTO_LDFLAGS $LDFLAGS [-Wl,-filelist,conftest.list] $LIBS 1>&5) && test -s conftest${ac_exeext}; then
                  EXPAND_LIBS_LIST_STYLE=filelist
-             elif AC_TRY_COMMAND(${CC-cc} -o conftest${ac_exeext} $CFLAGS $CPPFLAGS $LDFLAGS @conftest.list $LIBS 1>&5) && test -s conftest${ac_exeext}; then
+             elif AC_TRY_COMMAND($link $MOZ_LTO_LDFLAGS $LDFLAGS @conftest.list $LIBS 1>&5) && test -s conftest${ac_exeext}; then
                  EXPAND_LIBS_LIST_STYLE=list
              else
                  AC_ERROR([Couldn't find one that works])
              fi
          fi
      else
          dnl We really don't expect to get here, but just in case
          AC_ERROR([couldn't compile a simple C file])
--- a/build/moz.configure/toolchain.configure
+++ b/build/moz.configure/toolchain.configure
@@ -1402,16 +1402,18 @@ def lto(value, pgo, c_compiler):
     )
 
 
 add_old_configure_assignment('MOZ_LTO', lto.enabled)
 set_config('MOZ_LTO', lto.enabled)
 set_define('MOZ_LTO', lto.enabled)
 set_config('MOZ_LTO_CFLAGS', lto.cflags)
 set_config('MOZ_LTO_LDFLAGS', lto.ldflags)
+add_old_configure_assignment('MOZ_LTO_CFLAGS', lto.cflags)
+add_old_configure_assignment('MOZ_LTO_LDFLAGS', lto.ldflags)
 
 # ASAN
 # ==============================================================
 
 js_option('--enable-address-sanitizer', help='Enable Address Sanitizer')
 
 
 @depends_if('--enable-address-sanitizer')
--- a/caps/BasePrincipal.cpp
+++ b/caps/BasePrincipal.cpp
@@ -54,16 +54,23 @@ BasePrincipal::GetOrigin(nsACString& aOr
 NS_IMETHODIMP
 BasePrincipal::GetOriginNoSuffix(nsACString& aOrigin)
 {
   MOZ_ASSERT(mInitialized);
   mOriginNoSuffix->ToUTF8String(aOrigin);
   return NS_OK;
 }
 
+NS_IMETHODIMP
+BasePrincipal::GetSiteOrigin(nsACString& aSiteOrigin)
+{
+  MOZ_ASSERT(mInitialized);
+  return GetOrigin(aSiteOrigin);
+}
+
 bool
 BasePrincipal::Subsumes(nsIPrincipal* aOther, DocumentDomainConsideration aConsideration)
 {
   MOZ_ASSERT(aOther);
   MOZ_ASSERT_IF(Kind() == eCodebasePrincipal, mOriginSuffix);
 
   // Expanded principals handle origin attributes for each of their
   // sub-principals individually, null principals do only simple checks for
--- a/caps/BasePrincipal.h
+++ b/caps/BasePrincipal.h
@@ -81,16 +81,17 @@ public:
   NS_IMETHOD GetIsSystemPrincipal(bool* aResult) override;
   NS_IMETHOD GetIsAddonOrExpandedAddonPrincipal(bool* aResult) override;
   NS_IMETHOD GetOriginAttributes(JSContext* aCx, JS::MutableHandle<JS::Value> aVal) final;
   NS_IMETHOD GetOriginSuffix(nsACString& aOriginSuffix) final;
   NS_IMETHOD GetAppId(uint32_t* aAppId) final;
   NS_IMETHOD GetIsInIsolatedMozBrowserElement(bool* aIsInIsolatedMozBrowserElement) final;
   NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
   NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
+  NS_IMETHOD GetSiteOrigin(nsACString& aOrigin) override;
 
   virtual bool AddonHasPermission(const nsAtom* aPerm);
 
   virtual bool IsCodebasePrincipal() const { return false; };
 
   static BasePrincipal* Cast(nsIPrincipal* aPrin) { return static_cast<BasePrincipal*>(aPrin); }
 
   static already_AddRefed<BasePrincipal>
--- a/caps/ContentPrincipal.cpp
+++ b/caps/ContentPrincipal.cpp
@@ -12,16 +12,17 @@
 #include "nsScriptSecurityManager.h"
 #include "nsString.h"
 #include "nsReadableUtils.h"
 #include "pratom.h"
 #include "nsIURI.h"
 #include "nsIURL.h"
 #include "nsIStandardURL.h"
 #include "nsIURIWithSpecialOrigin.h"
+#include "nsIURIMutator.h"
 #include "nsJSPrincipals.h"
 #include "nsIEffectiveTLDService.h"
 #include "nsIClassInfoImpl.h"
 #include "nsIObjectInputStream.h"
 #include "nsIObjectOutputStream.h"
 #include "nsIProtocolHandler.h"
 #include "nsError.h"
 #include "nsIContentSecurityPolicy.h"
@@ -242,17 +243,28 @@ ContentPrincipal::SubsumesInternal(nsIPr
     // Get .domain on each principal.
     nsCOMPtr<nsIURI> thisDomain, otherDomain;
     GetDomain(getter_AddRefs(thisDomain));
     aOther->GetDomain(getter_AddRefs(otherDomain));
 
     // If either has .domain set, we have equality i.f.f. the domains match.
     // Otherwise, we fall through to the non-document-domain-considering case.
     if (thisDomain || otherDomain) {
-      return nsScriptSecurityManager::SecurityCompareURIs(thisDomain, otherDomain);
+      bool isMatch =
+        nsScriptSecurityManager::SecurityCompareURIs(thisDomain, otherDomain);
+#ifdef DEBUG
+      if (isMatch) {
+        nsAutoCString thisSiteOrigin, otherSiteOrigin;
+        MOZ_ALWAYS_SUCCEEDS(GetSiteOrigin(thisSiteOrigin));
+        MOZ_ALWAYS_SUCCEEDS(aOther->GetSiteOrigin(otherSiteOrigin));
+        MOZ_ASSERT(thisSiteOrigin == otherSiteOrigin,
+          "SubsumesConsideringDomain passed with mismatched siteOrigin!");
+      }
+#endif
+      return isMatch;
     }
   }
 
   nsCOMPtr<nsIURI> otherURI;
   rv = aOther->GetURI(getter_AddRefs(otherURI));
   NS_ENSURE_SUCCESS(rv, false);
 
   // Compare codebases.
@@ -386,16 +398,63 @@ ContentPrincipal::GetBaseDomain(nsACStri
     do_GetService(THIRDPARTYUTIL_CONTRACTID);
   if (thirdPartyUtil) {
     return thirdPartyUtil->GetBaseDomain(mCodebase, aBaseDomain);
   }
 
   return NS_OK;
 }
 
+NS_IMETHODIMP
+ContentPrincipal::GetSiteOrigin(nsACString& aSiteOrigin)
+{
+  // Get the eTLDService & determine our base domain. If we don't have a valid
+  // BaseDomain, we can fall-back to GetOrigin.
+  nsCOMPtr<nsIEffectiveTLDService> tldService =
+    do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
+  if (NS_WARN_IF(!tldService)) {
+    return GetOrigin(aSiteOrigin);
+  }
+
+  nsAutoCString baseDomain;
+  nsresult rv = tldService->GetBaseDomain(mCodebase, 0, baseDomain);
+  if (NS_FAILED(rv)) {
+    return GetOrigin(aSiteOrigin);
+  }
+
+  // NOTE: Calling `SetHostPort` with a portless domain is insufficient to clear
+  // the port, so an extra `SetPort` call has to be made.
+  nsCOMPtr<nsIURI> siteUri;
+  rv = NS_MutateURI(mCodebase)
+    .SetUserPass(EmptyCString())
+    .SetPort(-1)
+    .SetHostPort(baseDomain)
+    .Finalize(siteUri);
+  MOZ_ASSERT(NS_SUCCEEDED(rv), "failed to create siteUri");
+  if (NS_FAILED(rv)) {
+    return GetOrigin(aSiteOrigin);
+  }
+
+  rv = GenerateOriginNoSuffixFromURI(siteUri, aSiteOrigin);
+  MOZ_ASSERT(NS_SUCCEEDED(rv), "failed to create siteOriginNoSuffix");
+  if (NS_FAILED(rv)) {
+    return GetOrigin(aSiteOrigin);
+  }
+
+  nsAutoCString suffix;
+  rv = GetOriginSuffix(suffix);
+  MOZ_ASSERT(NS_SUCCEEDED(rv), "failed to create suffix");
+  if (NS_FAILED(rv)) {
+    return GetOrigin(aSiteOrigin);
+  }
+
+  aSiteOrigin.Append(suffix);
+  return NS_OK;
+}
+
 WebExtensionPolicy*
 ContentPrincipal::AddonPolicy()
 {
   if (!mAddon.isSome()) {
     NS_ENSURE_TRUE(mCodebase, nullptr);
 
     bool isMozExt;
     if (NS_SUCCEEDED(mCodebase->SchemeIs("moz-extension", &isMozExt)) && isMozExt) {
--- a/caps/ContentPrincipal.h
+++ b/caps/ContentPrincipal.h
@@ -24,16 +24,17 @@ public:
   NS_DECL_NSISERIALIZABLE
   NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr) override;
   NS_IMETHOD GetHashValue(uint32_t* aHashValue) override;
   NS_IMETHOD GetURI(nsIURI** aURI) override;
   NS_IMETHOD GetDomain(nsIURI** aDomain) override;
   NS_IMETHOD SetDomain(nsIURI* aDomain) override;
   NS_IMETHOD GetBaseDomain(nsACString& aBaseDomain) override;
   NS_IMETHOD GetAddonId(nsAString& aAddonId) override;
+  NS_IMETHOD GetSiteOrigin(nsACString& aSiteOrigin) override;
   bool IsCodebasePrincipal() const override { return true; }
 
   ContentPrincipal();
 
   static PrincipalKind Kind() { return eCodebasePrincipal; }
 
   // Init() must be called before the principal is in a usable state.
   nsresult Init(nsIURI* aCodebase,
--- a/caps/nsIPrincipal.idl
+++ b/caps/nsIPrincipal.idl
@@ -241,16 +241,30 @@ interface nsIPrincipal : nsISerializable
      *
      * The value of .originSuffix is automatically serialized into .origin, so any
      * consumers using that are automatically origin-attribute-aware. Consumers with
      * special requirements must inspect and compare .originSuffix manually.
      */
     readonly attribute AUTF8String originSuffix;
 
     /**
+     * A canonical representation of the site-origin for this principal.
+     * This string has the same format as |origin| (see above). Two principals
+     * with differing |siteOrigin| values will never compare equal, even when
+     * considering domain mutations.
+     *
+     * For most principals, |siteOrigin| matches |origin| precisely. Only
+     * principals which allow mutating |domain|, such as ContentPrincipal,
+     * override the default implementation in BasePrincipal.
+     *
+     * TODO(nika): Use this in DocGroup.
+     */
+    readonly attribute ACString siteOrigin;
+
+    /**
      * The base domain of the codebase URI to which this principal pertains
      * (generally the document URI), handling null principals and
      * non-hierarchical schemes correctly.
      */
     readonly attribute ACString baseDomain;
 
     /**
      * Gets the id of the app this principal is inside.  If this principal is
--- a/dom/base/Selection.cpp
+++ b/dom/base/Selection.cpp
@@ -732,34 +732,34 @@ Selection::GetDocGroup() const
 NS_IMPL_CYCLE_COLLECTION_CLASS(Selection)
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Selection)
   // Unlink the selection listeners *before* we do RemoveAllRanges since
   // we don't want to notify the listeners during JS GC (they could be
   // in JS!).
   tmp->mNotifyAutoCopy = false;
   tmp->StopNotifyingAccessibleCaretEventHub();
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelectionChangeListener)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelectionChangeEventDispatcher)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mSelectionListeners)
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mCachedRange)
   tmp->RemoveAllRanges(IgnoreErrors());
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mFrameSelection)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Selection)
   {
     uint32_t i, count = tmp->mRanges.Length();
     for (i = 0; i < count; ++i) {
       NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mRanges[i].mRange)
     }
   }
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAnchorFocusRange)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCachedRange)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mFrameSelection)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelectionChangeListener)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelectionChangeEventDispatcher)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelectionListeners)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(Selection)
 
 // QueryInterface implementation for Selection
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Selection)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
@@ -3500,19 +3500,20 @@ Selection::NotifySelectionListeners()
     AutoCopyListener::OnSelectionChange(doc, *this, reason);
   }
 
   if (mAccessibleCaretEventHub) {
     RefPtr<AccessibleCaretEventHub> hub(mAccessibleCaretEventHub);
     hub->OnSelectionChange(doc, this, reason);
   }
 
-  if (mSelectionChangeListener) {
-    RefPtr<SelectionChangeListener> listener(mSelectionChangeListener);
-    listener->OnSelectionChange(doc, this, reason);
+  if (mSelectionChangeEventDispatcher) {
+    RefPtr<SelectionChangeEventDispatcher> dispatcher(
+                                             mSelectionChangeEventDispatcher);
+    dispatcher->OnSelectionChange(doc, this, reason);
   }
   for (auto& listener : selectionListeners) {
     listener->NotifySelectionChanged(doc, this, reason);
   }
   return NS_OK;
 }
 
 void
--- a/dom/base/Selection.h
+++ b/dom/base/Selection.h
@@ -7,17 +7,17 @@
 #ifndef mozilla_Selection_h__
 #define mozilla_Selection_h__
 
 #include "nsIWeakReference.h"
 
 #include "mozilla/AccessibleCaretEventHub.h"
 #include "mozilla/AutoRestore.h"
 #include "mozilla/RangeBoundary.h"
-#include "mozilla/SelectionChangeListener.h"
+#include "mozilla/SelectionChangeEventDispatcher.h"
 #include "mozilla/TextRange.h"
 #include "mozilla/UniquePtr.h"
 #include "mozilla/WeakPtr.h"
 #include "nsDirection.h"
 #include "nsIPresShell.h"  // For ScrollAxis
 #include "nsISelectionController.h"
 #include "nsISelectionListener.h"
 #include "nsRange.h"
@@ -112,24 +112,24 @@ public:
    * AccessibleCaretEventHub of selection change.
    */
   void StopNotifyingAccessibleCaretEventHub()
   {
     mAccessibleCaretEventHub = nullptr;
   }
 
   /**
-   * EnableSelectionChangeEvent() starts to notify SelectionChangeListener of
-   * selection change to dispatch a selectionchange event at every selection
-   * change.
+   * EnableSelectionChangeEvent() starts to notify
+   * SelectionChangeEventDispatcher of selection change to dispatch a
+   * selectionchange event at every selection change.
    */
   void EnableSelectionChangeEvent()
   {
-    if (!mSelectionChangeListener) {
-      mSelectionChangeListener = new SelectionChangeListener();
+    if (!mSelectionChangeEventDispatcher) {
+      mSelectionChangeEventDispatcher = new SelectionChangeEventDispatcher();
     }
   }
 
   nsIDocument* GetParentObject() const;
   DocGroup* GetDocGroup() const;
 
   // utility methods for scrolling the selection into view
   nsPresContext* GetPresContext() const;
@@ -726,17 +726,17 @@ private:
   // a mutation observer because it is not so cheap to register the range
   // as a mutation observer again.  On the other hand, we make it not
   // positioned because it is not so cheap to keep valid DOM point against
   // mutations.  This does not cause any problems because we will set new
   // DOM point when we treat it as a range of Selection again.
   RefPtr<nsRange> mCachedRange;
   RefPtr<nsFrameSelection> mFrameSelection;
   RefPtr<AccessibleCaretEventHub> mAccessibleCaretEventHub;
-  RefPtr<SelectionChangeListener> mSelectionChangeListener;
+  RefPtr<SelectionChangeEventDispatcher> mSelectionChangeEventDispatcher;
   RefPtr<nsAutoScrollTimer> mAutoScrollTimer;
   nsTArray<nsCOMPtr<nsISelectionListener>> mSelectionListeners;
   nsRevocableEventPtr<ScrollSelectionIntoViewEvent> mScrollEvent;
   CachedOffsetForFrame* mCachedOffsetForFrame;
   nsDirection mDirection;
   SelectionType mSelectionType;
   UniquePtr<SelectionCustomColors> mCustomColors;
 
rename from dom/base/SelectionChangeListener.cpp
rename to dom/base/SelectionChangeEventDispatcher.cpp
--- a/dom/base/SelectionChangeListener.cpp
+++ b/dom/base/SelectionChangeEventDispatcher.cpp
@@ -1,88 +1,91 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 /*
- * Implementation of mozilla::dom::SelectionChangeListener
+ * Implementation of mozilla::SelectionChangeEventDispatcher
  */
 
-#include "SelectionChangeListener.h"
+#include "SelectionChangeEventDispatcher.h"
 
 #include "mozilla/AsyncEventDispatcher.h"
 #include "nsCOMPtr.h"
 #include "nsContentUtils.h"
 #include "nsIDocument.h"
 #include "nsFrameSelection.h"
 #include "nsRange.h"
 #include "mozilla/dom/Selection.h"
 
-using namespace mozilla;
-using namespace mozilla::dom;
+namespace mozilla {
 
-SelectionChangeListener::RawRangeData::RawRangeData(const nsRange* aRange)
+using namespace dom;
+
+SelectionChangeEventDispatcher::RawRangeData::RawRangeData(
+                                                const nsRange* aRange)
 {
   mozilla::ErrorResult rv;
   mStartContainer = aRange->GetStartContainer(rv);
   rv.SuppressException();
   mEndContainer = aRange->GetEndContainer(rv);
   rv.SuppressException();
   mStartOffset = aRange->GetStartOffset(rv);
   rv.SuppressException();
   mEndOffset = aRange->GetEndOffset(rv);
   rv.SuppressException();
 }
 
 bool
-SelectionChangeListener::RawRangeData::Equals(const nsRange* aRange)
+SelectionChangeEventDispatcher::RawRangeData::Equals(const nsRange* aRange)
 {
   mozilla::ErrorResult rv;
   bool eq = mStartContainer == aRange->GetStartContainer(rv);
   rv.SuppressException();
   eq = eq && mEndContainer == aRange->GetEndContainer(rv);
   rv.SuppressException();
   eq = eq && mStartOffset == aRange->GetStartOffset(rv);
   rv.SuppressException();
   eq = eq && mEndOffset == aRange->GetEndOffset(rv);
   rv.SuppressException();
   return eq;
 }
 
 inline void
-ImplCycleCollectionTraverse(nsCycleCollectionTraversalCallback& aCallback,
-                            SelectionChangeListener::RawRangeData& aField,
-                            const char* aName,
-                            uint32_t aFlags = 0)
+ImplCycleCollectionTraverse(
+  nsCycleCollectionTraversalCallback& aCallback,
+  SelectionChangeEventDispatcher::RawRangeData& aField,
+  const char* aName,
+  uint32_t aFlags = 0)
 {
   ImplCycleCollectionTraverse(aCallback, aField.mStartContainer,
                               "mStartContainer", aFlags);
   ImplCycleCollectionTraverse(aCallback, aField.mEndContainer,
                               "mEndContainer", aFlags);
 }
 
-NS_IMPL_CYCLE_COLLECTION_CLASS(SelectionChangeListener)
+NS_IMPL_CYCLE_COLLECTION_CLASS(SelectionChangeEventDispatcher)
 
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(SelectionChangeListener)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(SelectionChangeEventDispatcher)
   tmp->mOldRanges.Clear();
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(SelectionChangeListener)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(SelectionChangeEventDispatcher)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOldRanges);
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
-NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(SelectionChangeListener, AddRef)
-NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(SelectionChangeListener, Release)
+NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(SelectionChangeEventDispatcher, AddRef)
+NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(SelectionChangeEventDispatcher, Release)
 
 void
-SelectionChangeListener::OnSelectionChange(nsIDocument* aDoc,
-                                           Selection* aSel,
-                                           int16_t aReason)
+SelectionChangeEventDispatcher::OnSelectionChange(nsIDocument* aDoc,
+                                                  Selection* aSel,
+                                                  int16_t aReason)
 {
   nsIDocument* doc = aSel->GetParentObject();
   if (!(doc && nsContentUtils::IsSystemPrincipal(doc->NodePrincipal())) &&
       !nsFrameSelection::sSelectionEventsEnabled) {
     return;
   }
 
   // Check if the ranges have actually changed
@@ -166,8 +169,10 @@ SelectionChangeListener::OnSelectionChan
 
     if (aDoc) {
       RefPtr<AsyncEventDispatcher> asyncDispatcher =
         new AsyncEventDispatcher(aDoc, eSelectionChange, CanBubble::eNo);
       asyncDispatcher->PostDOMEvent();
     }
   }
 }
+
+} // namespace mozilla
rename from dom/base/SelectionChangeListener.h
rename to dom/base/SelectionChangeEventDispatcher.h
--- a/dom/base/SelectionChangeListener.h
+++ b/dom/base/SelectionChangeEventDispatcher.h
@@ -1,42 +1,44 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#ifndef mozilla_SelectionChangeListener_h_
-#define mozilla_SelectionChangeListener_h_
+#ifndef mozilla_SelectionChangeEventDispatcher_h
+#define mozilla_SelectionChangeEventDispatcher_h
 
 #include "mozilla/Attributes.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsTArray.h"
 #include "nsCOMPtr.h"
 
+class nsIDocument;
+class nsINode;
 class nsRange;
-class nsINode;
 
 namespace mozilla {
-namespace dom {
 
-// XXX This class name is too generic.  Perhaps, SelectionChangeEventDispatcher?
-//     And also it's odd that this is in |dom| namespace since this is not
-//     an implementation of any DOM object.
-class SelectionChangeListener final
+namespace dom {
+class Selection;
+}
+
+class SelectionChangeEventDispatcher final
 {
 public:
-  // SelectionChangeListener has to participate in cycle collection because
-  // it holds strong references to nsINodes in its mOldRanges array.
-  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(SelectionChangeListener)
-  NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(SelectionChangeListener)
+  // SelectionChangeEventDispatcher has to participate in cycle collection
+  // because it holds strong references to nsINodes in its mOldRanges array.
+  NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(
+    SelectionChangeEventDispatcher)
+  NS_DECL_CYCLE_COLLECTION_NATIVE_CLASS(SelectionChangeEventDispatcher)
 
   MOZ_CAN_RUN_SCRIPT
   void OnSelectionChange(nsIDocument* aDocument,
-                         Selection* aSelection,
+                         dom::Selection* aSelection,
                          int16_t aReason);
 
   // This field is used to keep track of the ranges which were present in the
   // selection when the selectionchange event was previously fired. This allows
   // for the selectionchange event to only be fired when a selection is actually
   // changed.
   struct RawRangeData
   {
@@ -55,15 +57,14 @@ public:
 
     explicit RawRangeData(const nsRange* aRange);
     bool Equals(const nsRange* aRange);
   };
 
 private:
   nsTArray<RawRangeData> mOldRanges;
 
-  ~SelectionChangeListener() {}
+  ~SelectionChangeEventDispatcher() {}
 };
 
-} // namespace dom
 } // namespace mozilla
 
-#endif // mozilla_SelectionChangeListener_h_
+#endif // mozilla_SelectionChangeEventDispatcher_h
--- a/dom/base/moz.build
+++ b/dom/base/moz.build
@@ -127,17 +127,17 @@ if CONFIG['MOZ_WEBRTC']:
         'nsDOMDataChannelDeclarations.h',
     ]
 
 EXPORTS.mozilla += [
     'CORSMode.h',
     'FeedWriterEnabled.h',
     'FlushType.h',
     'RangeBoundary.h',
-    'SelectionChangeListener.h',
+    'SelectionChangeEventDispatcher.h',
     'TextInputProcessor.h',
     'UseCounter.h',
 ]
 
 EXPORTS.mozilla.dom += [
     '!UseCounterList.h',
     'AnonymousContent.h',
     'Attr.h',
@@ -364,17 +364,17 @@ UNIFIED_SOURCES += [
     'Pose.cpp',
     'PostMessageEvent.cpp',
     'ProcessMessageManager.cpp',
     'ResponsiveImageSelector.cpp',
     'SameProcessMessageQueue.cpp',
     'ScreenLuminance.cpp',
     'ScreenOrientation.cpp',
     'Selection.cpp',
-    'SelectionChangeListener.cpp',
+    'SelectionChangeEventDispatcher.cpp',
     'ShadowRoot.cpp',
     'StructuredCloneBlob.cpp',
     'StructuredCloneHolder.cpp',
     'StyleSheetList.cpp',
     'SubtleCrypto.cpp',
     'TabGroup.cpp',
     'Text.cpp',
     'TextInputProcessor.cpp',
--- a/ipc/glue/URIUtils.h
+++ b/ipc/glue/URIUtils.h
@@ -34,17 +34,17 @@ struct IPDLParamTraits<nsIURI>
 {
   static void Write(IPC::Message* aMsg, IProtocol* aActor, nsIURI* aParam)
   {
     OptionalURIParams params;
     SerializeURI(aParam, params);
     WriteIPDLParam(aMsg, aActor, params);
   }
 
-  static bool Read(IPC::Message* aMsg, PickleIterator* aIter,
+  static bool Read(const IPC::Message* aMsg, PickleIterator* aIter,
                    IProtocol* aActor, RefPtr<nsIURI>* aResult)
   {
     OptionalURIParams params;
     if (!ReadIPDLParam(aMsg, aIter, aActor, &params)) {
       return false;
     }
     *aResult = DeserializeURI(params);
     return true;
--- a/layout/base/nsLayoutUtils.cpp
+++ b/layout/base/nsLayoutUtils.cpp
@@ -2875,27 +2875,27 @@ TransformGfxPointFromAncestor(nsIFrame *
 }
 
 static Rect
 TransformGfxRectToAncestor(const nsIFrame *aFrame,
                            const Rect &aRect,
                            const nsIFrame *aAncestor,
                            bool* aPreservesAxisAlignedRectangles = nullptr,
                            Maybe<Matrix4x4Flagged>* aMatrixCache = nullptr,
-                           bool aStopAtStackingContextAndDisplayPort = false,
+                           bool aStopAtStackingContextAndDisplayPortAndOOFFrame = false,
                            nsIFrame** aOutAncestor = nullptr)
 {
   Matrix4x4Flagged ctm;
   if (aMatrixCache && *aMatrixCache) {
     // We are given a matrix to use, so use it
     ctm = aMatrixCache->value();
   } else {
     // Else, compute it
     uint32_t flags = 0;
-    if (aStopAtStackingContextAndDisplayPort) {
+    if (aStopAtStackingContextAndDisplayPortAndOOFFrame) {
       flags |= nsIFrame::STOP_AT_STACKING_CONTEXT_AND_DISPLAY_PORT;
     }
     ctm = nsLayoutUtils::GetTransformToAncestor(aFrame, aAncestor, flags, aOutAncestor);
     if (aMatrixCache) {
       // and put it in the cache, if provided
       *aMatrixCache = Some(ctm);
     }
   }
@@ -2952,41 +2952,41 @@ nsLayoutUtils::TransformAncestorPointToF
 }
 
 nsRect
 nsLayoutUtils::TransformFrameRectToAncestor(const nsIFrame* aFrame,
                                             const nsRect& aRect,
                                             const nsIFrame* aAncestor,
                                             bool* aPreservesAxisAlignedRectangles /* = nullptr */,
                                             Maybe<Matrix4x4Flagged>* aMatrixCache /* = nullptr */,
-                                            bool aStopAtStackingContextAndDisplayPort /* = false */,
+                                            bool aStopAtStackingContextAndDisplayPortAndOOFFrame /* = false */,
                                             nsIFrame** aOutAncestor /* = nullptr */)
 {
   SVGTextFrame* text = GetContainingSVGTextFrame(aFrame);
 
   float srcAppUnitsPerDevPixel = aFrame->PresContext()->AppUnitsPerDevPixel();
   Rect result;
 
   if (text) {
     result = ToRect(text->TransformFrameRectFromTextChild(aRect, aFrame));
     result = TransformGfxRectToAncestor(text, result, aAncestor,
                                         nullptr, aMatrixCache,
-                                        aStopAtStackingContextAndDisplayPort, aOutAncestor);
+                                        aStopAtStackingContextAndDisplayPortAndOOFFrame, aOutAncestor);
     // TransformFrameRectFromTextChild could involve any kind of transform, we
     // could drill down into it to get an answer out of it but we don't yet.
     if (aPreservesAxisAlignedRectangles)
       *aPreservesAxisAlignedRectangles = false;
   } else {
     result = Rect(NSAppUnitsToFloatPixels(aRect.x, srcAppUnitsPerDevPixel),
                   NSAppUnitsToFloatPixels(aRect.y, srcAppUnitsPerDevPixel),
                   NSAppUnitsToFloatPixels(aRect.width, srcAppUnitsPerDevPixel),
                   NSAppUnitsToFloatPixels(aRect.height, srcAppUnitsPerDevPixel));
     result = TransformGfxRectToAncestor(aFrame, result, aAncestor,
                                         aPreservesAxisAlignedRectangles, aMatrixCache,
-                                        aStopAtStackingContextAndDisplayPort, aOutAncestor);
+                                        aStopAtStackingContextAndDisplayPortAndOOFFrame, aOutAncestor);
   }
 
   float destAppUnitsPerDevPixel = aAncestor->PresContext()->AppUnitsPerDevPixel();
   return nsRect(NSFloatPixelsToAppUnits(float(result.x), destAppUnitsPerDevPixel),
                 NSFloatPixelsToAppUnits(float(result.y), destAppUnitsPerDevPixel),
                 NSFloatPixelsToAppUnits(float(result.width), destAppUnitsPerDevPixel),
                 NSFloatPixelsToAppUnits(float(result.height), destAppUnitsPerDevPixel));
 }
--- a/layout/base/nsLayoutUtils.h
+++ b/layout/base/nsLayoutUtils.h
@@ -865,17 +865,17 @@ public:
    * non-null pointer to a non-empty Matrix4x4 - The provided matrix will be used
    *   as the transform matrix and applied to the rect.
    */
   static nsRect TransformFrameRectToAncestor(const nsIFrame* aFrame,
                                              const nsRect& aRect,
                                              const nsIFrame* aAncestor,
                                              bool* aPreservesAxisAlignedRectangles = nullptr,
                                              mozilla::Maybe<Matrix4x4Flagged>* aMatrixCache = nullptr,
-                                             bool aStopAtStackingContextAndDisplayPort = false,
+                                             bool aStopAtStackingContextAndDisplayPortAndOOFFrame = false,
                                              nsIFrame** aOutAncestor = nullptr);
 
 
   /**
    * Gets the transform for aFrame relative to aAncestor. Pass null for
    * aAncestor to go up to the root frame. aInCSSUnits set to true will
    * return CSS units, set to false (the default) will return App units.
    */
--- a/layout/base/nsPresContext.cpp
+++ b/layout/base/nsPresContext.cpp
@@ -1752,17 +1752,17 @@ nsPresContext::RefreshSystemMetrics()
   nsMediaFeatures::FreeSystemMetrics();
 
   // Changes to system metrics can change media queries on them.
   //
   // Changes in theme can change system colors (whose changes are
   // properly reflected in computed style data), system fonts (whose
   // changes are not), and -moz-appearance (whose changes likewise are
   // not), so we need to recascade for the first, and reflow for the rest.
-  MediaFeatureValuesChanged({
+  MediaFeatureValuesChangedAllDocuments({
     eRestyle_ForceDescendants,
     NS_STYLE_HINT_REFLOW,
     MediaFeatureChangeReason::SystemMetricsChange,
   });
 }
 
 void
 nsPresContext::UIResolutionChanged()
new file mode 100644
--- /dev/null
+++ b/layout/forms/crashtests/1488219.html
@@ -0,0 +1,26 @@
+<!DOCTYPE HTML>
+<html class="reftest-wait">
+<script>
+function doTest(){
+  document.getElementById('c').appendChild(document.getElementById('b').cloneNode(true));
+  window.frames[0].document.body.appendChild(document.getElementById('a'));
+  document.documentElement.removeAttribute('class');
+}
+document.addEventListener("MozReftestInvalidate", doTest);
+</script>
+
+<iframe hidden></iframe>
+<style>
+:last-of-type {
+  -moz-column-count:71;
+  float:left;
+}
+</style>
+<bdo id='a'>A</bdo>
+<address>
+<blockquote>
+</address>
+<footer id='b'>
+</footer>
+<input id='c' type='time'>
+</html>
--- a/layout/forms/crashtests/crashtests.list
+++ b/layout/forms/crashtests/crashtests.list
@@ -70,8 +70,9 @@ load 1279354.html
 load 1388230-1.html
 load 1388230-2.html
 load 1405830.html
 load 1418477.html
 load 1432853.html
 asserts(2-4) load 1460787-1.html
 load 1464165-1.html
 load 1471157.html
+load 1488219.html
--- a/layout/generic/nsFrameIdList.h
+++ b/layout/generic/nsFrameIdList.h
@@ -15,17 +15,17 @@ FRAME_ID(nsBulletFrame, Bullet, Leaf)
 FRAME_ID(nsButtonBoxFrame, Box, NotLeaf)
 FRAME_ID(nsCanvasFrame, Canvas, NotLeaf)
 FRAME_ID(nsCheckboxRadioFrame, CheckboxRadio, Leaf)
 FRAME_ID(nsColorControlFrame, ColorControl, Leaf)
 FRAME_ID(nsColumnSetFrame, ColumnSet, NotLeaf)
 FRAME_ID(nsComboboxControlFrame, ComboboxControl, NotLeaf)
 FRAME_ID(nsComboboxDisplayFrame, ComboboxDisplay, NotLeaf)
 FRAME_ID(nsContinuingTextFrame, Text, Leaf)
-FRAME_ID(nsDateTimeControlFrame, DateTimeControl, NotLeaf)
+FRAME_ID(nsDateTimeControlFrame, DateTimeControl, Leaf)
 FRAME_ID(nsDeckFrame, Deck, NotLeaf)
 FRAME_ID(nsDocElementBoxFrame, Box, NotLeaf)
 FRAME_ID(nsFieldSetFrame, FieldSet, NotLeaf)
 FRAME_ID(nsFileControlFrame, Block, Leaf)
 FRAME_ID(nsFirstLetterFrame, Letter, NotLeaf)
 FRAME_ID(nsFirstLineFrame, Line, NotLeaf)
 FRAME_ID(nsFlexContainerFrame, FlexContainer, NotLeaf)
 FRAME_ID(nsFrame, None, NotLeaf)
--- a/layout/generic/nsFrameSelection.h
+++ b/layout/generic/nsFrameSelection.h
@@ -176,19 +176,19 @@ struct nsPrevNextBidiLevels
   }
   nsIFrame* mFrameBefore;
   nsIFrame* mFrameAfter;
   nsBidiLevel mLevelBefore;
   nsBidiLevel mLevelAfter;
 };
 
 namespace mozilla {
+class SelectionChangeEventDispatcher;
 namespace dom {
 class Selection;
-class SelectionChangeListener;
 } // namespace dom
 
 /**
  * Constants for places that want to handle table selections.  These
  * indicate what part of a table is being selected.
  */
 enum class TableSelection : uint32_t {
   None, /* Nothing being selected; not valid in all cases. */
@@ -686,17 +686,17 @@ private:
             (nsISelectionListener::DRAG_REASON |
              nsISelectionListener::MOUSEDOWN_REASON |
              nsISelectionListener::MOUSEUP_REASON |
              nsISelectionListener::KEYPRESS_REASON)) !=
            nsISelectionListener::NO_REASON;
   }
 
   friend class mozilla::dom::Selection;
-  friend class mozilla::dom::SelectionChangeListener;
+  friend class mozilla::SelectionChangeEventDispatcher;
   friend struct mozilla::AutoPrepareFocusRange;
 #ifdef DEBUG
   void printSelection();       // for debugging
 #endif /* DEBUG */
 
   void ResizeBuffer(uint32_t aNewBufSize);
 
 /*HELPER METHODS*/
--- a/layout/painting/ActiveLayerTracker.cpp
+++ b/layout/painting/ActiveLayerTracker.cpp
@@ -33,19 +33,21 @@ using namespace gfx;
  * ongoing content changes or style changes that indicate animation.
  *
  * When no changes of *any* kind are detected after 75-100ms we remove this
  * object. Because we only track all kinds of activity with a single
  * nsExpirationTracker, it's possible a frame might remain active somewhat
  * spuriously if different kinds of changes kept happening, but that almost
  * certainly doesn't matter.
  */
-class LayerActivity {
+class LayerActivity
+{
 public:
-  enum ActivityIndex {
+  enum ActivityIndex
+  {
     ACTIVITY_OPACITY,
     ACTIVITY_TRANSFORM,
     ACTIVITY_LEFT,
     ACTIVITY_TOP,
     ACTIVITY_RIGHT,
     ACTIVITY_BOTTOM,
     ACTIVITY_BACKGROUND_POSITION,
 
@@ -68,26 +70,37 @@ public:
   uint8_t& RestyleCountForProperty(nsCSSPropertyID aProperty)
   {
     return mRestyleCounts[GetActivityIndexForProperty(aProperty)];
   }
 
   static ActivityIndex GetActivityIndexForProperty(nsCSSPropertyID aProperty)
   {
     switch (aProperty) {
-    case eCSSProperty_opacity: return ACTIVITY_OPACITY;
-    case eCSSProperty_transform: return ACTIVITY_TRANSFORM;
-    case eCSSProperty_left: return ACTIVITY_LEFT;
-    case eCSSProperty_top: return ACTIVITY_TOP;
-    case eCSSProperty_right: return ACTIVITY_RIGHT;
-    case eCSSProperty_bottom: return ACTIVITY_BOTTOM;
-    case eCSSProperty_background_position: return ACTIVITY_BACKGROUND_POSITION;
-    case eCSSProperty_background_position_x: return ACTIVITY_BACKGROUND_POSITION;
-    case eCSSProperty_background_position_y: return ACTIVITY_BACKGROUND_POSITION;
-    default: MOZ_ASSERT(false); return ACTIVITY_OPACITY;
+      case eCSSProperty_opacity:
+        return ACTIVITY_OPACITY;
+      case eCSSProperty_transform:
+        return ACTIVITY_TRANSFORM;
+      case eCSSProperty_left:
+        return ACTIVITY_LEFT;
+      case eCSSProperty_top:
+        return ACTIVITY_TOP;
+      case eCSSProperty_right:
+        return ACTIVITY_RIGHT;
+      case eCSSProperty_bottom:
+        return ACTIVITY_BOTTOM;
+      case eCSSProperty_background_position:
+        return ACTIVITY_BACKGROUND_POSITION;
+      case eCSSProperty_background_position_x:
+        return ACTIVITY_BACKGROUND_POSITION;
+      case eCSSProperty_background_position_y:
+        return ACTIVITY_BACKGROUND_POSITION;
+      default:
+        MOZ_ASSERT(false);
+        return ACTIVITY_OPACITY;
     }
   }
 
   // While tracked, exactly one of mFrame or mContent is non-null, depending
   // on whether this property is stored on a frame or on a content node.
   // When this property is expired by the layer activity tracker, both mFrame
   // and mContent are nulled-out and the property is deleted.
   nsIFrame* mFrame;
@@ -105,32 +118,39 @@ public:
   // mAnimatingScrollHandlerFrame's scroll event handler.
   EnumSet<ActivityIndex> mScrollHandlerInducedActivity;
 
   // Number of restyle operations detected
   uint8_t mRestyleCounts[ACTIVITY_COUNT];
   bool mContentActive;
 };
 
-class LayerActivityTracker final : public nsExpirationTracker<LayerActivity,4> {
+class LayerActivityTracker final : public nsExpirationTracker<LayerActivity, 4>
+{
 public:
   // 75-100ms is a good timeout period. We use 4 generations of 25ms each.
-  enum { GENERATION_MS = 100 };
+  enum
+  {
+    GENERATION_MS = 100
+  };
+
   explicit LayerActivityTracker(nsIEventTarget* aEventTarget)
-    : nsExpirationTracker<LayerActivity,4>(GENERATION_MS,
-                                           "LayerActivityTracker",
-                                           aEventTarget)
+    : nsExpirationTracker<LayerActivity, 4>(GENERATION_MS,
+                                            "LayerActivityTracker",
+                                            aEventTarget)
     , mDestroying(false)
-  {}
-  ~LayerActivityTracker() {
+  {
+  }
+  ~LayerActivityTracker() override
+  {
     mDestroying = true;
     AgeAllGenerations();
   }
 
-  virtual void NotifyExpired(LayerActivity* aObject) override;
+  void NotifyExpired(LayerActivity* aObject) override;
 
 public:
   WeakFrame mCurrentScrollHandlerFrame;
 
 private:
   bool mDestroying;
 };
 
@@ -160,17 +180,18 @@ LayerActivityTracker::NotifyExpired(Laye
   RemoveObject(aObject);
 
   nsIFrame* f = aObject->mFrame;
   nsIContent* c = aObject->mContent;
   aObject->mFrame = nullptr;
   aObject->mContent = nullptr;
 
   MOZ_ASSERT((f == nullptr) != (c == nullptr),
-             "A LayerActivity object should always have a reference to either its frame or its content");
+             "A LayerActivity object should always have a reference to either "
+             "its frame or its content");
 
   if (f) {
     // The pres context might have been detached during the delay -
     // that's fine, just skip the paint.
     if (f->PresContext()->GetContainerWeak()) {
       f->SchedulePaint();
     }
     f->RemoveStateBits(NS_FRAME_HAS_LAYER_ACTIVITY_PROPERTY);
@@ -210,89 +231,93 @@ GetLayerActivityForUpdate(nsIFrame* aFra
 
 static void
 IncrementMutationCount(uint8_t* aCount)
 {
   *aCount = uint8_t(std::min(0xFF, *aCount + 1));
 }
 
 /* static */ void
-ActiveLayerTracker::TransferActivityToContent(nsIFrame* aFrame, nsIContent* aContent)
+ActiveLayerTracker::TransferActivityToContent(nsIFrame* aFrame,
+                                              nsIContent* aContent)
 {
   if (!aFrame->HasAnyStateBits(NS_FRAME_HAS_LAYER_ACTIVITY_PROPERTY)) {
     return;
   }
-  LayerActivity* layerActivity = aFrame->RemoveProperty(LayerActivityProperty());
+  LayerActivity* layerActivity =
+    aFrame->RemoveProperty(LayerActivityProperty());
   aFrame->RemoveStateBits(NS_FRAME_HAS_LAYER_ACTIVITY_PROPERTY);
   if (!layerActivity) {
     return;
   }
   layerActivity->mFrame = nullptr;
   layerActivity->mContent = aContent;
-  aContent->SetProperty(nsGkAtoms::LayerActivity, layerActivity,
-                        nsINode::DeleteProperty<LayerActivity>, true);
+  aContent->SetProperty(nsGkAtoms::LayerActivity,
+                        layerActivity,
+                        nsINode::DeleteProperty<LayerActivity>,
+                        true);
 }
 
 /* static */ void
-ActiveLayerTracker::TransferActivityToFrame(nsIContent* aContent, nsIFrame* aFrame)
+ActiveLayerTracker::TransferActivityToFrame(nsIContent* aContent,
+                                            nsIFrame* aFrame)
 {
   LayerActivity* layerActivity = static_cast<LayerActivity*>(
     aContent->UnsetProperty(nsGkAtoms::LayerActivity));
   if (!layerActivity) {
     return;
   }
   layerActivity->mContent = nullptr;
   layerActivity->mFrame = aFrame;
   aFrame->AddStateBits(NS_FRAME_HAS_LAYER_ACTIVITY_PROPERTY);
   aFrame->SetProperty(LayerActivityProperty(), layerActivity);
 }
 
 static void
 IncrementScaleRestyleCountIfNeeded(nsIFrame* aFrame, LayerActivity* aActivity)
 {
   const nsStyleDisplay* display = aFrame->StyleDisplay();
-  if (!display->mSpecifiedTransform &&
-      !display->HasIndividualTransform() &&
+  if (!display->mSpecifiedTransform && !display->HasIndividualTransform() &&
       !(display->mMotion && display->mMotion->HasPath())) {
     // The transform was removed.
     aActivity->mPreviousTransformScale = Nothing();
     IncrementMutationCount(
       &aActivity->mRestyleCounts[LayerActivity::ACTIVITY_SCALE]);
     return;
   }
 
   // Compute the new scale due to the CSS transform property.
   bool dummyBool;
   nsStyleTransformMatrix::TransformReferenceBox refBox(aFrame);
   Matrix4x4 transform = nsStyleTransformMatrix::ReadTransforms(
-      display->mIndividualTransform
-        ? display->mIndividualTransform->mHead
-        : nullptr,
-      nsLayoutUtils::ResolveMotionPath(aFrame),
-      display->mSpecifiedTransform
-        ? display->mSpecifiedTransform->mHead
-        : nullptr,
-      refBox,
-      AppUnitsPerCSSPixel(),
-      &dummyBool);
+    display->mIndividualTransform ? display->mIndividualTransform->mHead
+                                  : nullptr,
+    nsLayoutUtils::ResolveMotionPath(aFrame),
+    display->mSpecifiedTransform ? display->mSpecifiedTransform->mHead
+                                 : nullptr,
+    refBox,
+    AppUnitsPerCSSPixel(),
+    &dummyBool);
   Matrix transform2D;
   if (!transform.Is2D(&transform2D)) {
     // We don't attempt to handle 3D transforms; just assume the scale changed.
     aActivity->mPreviousTransformScale = Nothing();
-    IncrementMutationCount(&aActivity->mRestyleCounts[LayerActivity::ACTIVITY_SCALE]);
+    IncrementMutationCount(
+      &aActivity->mRestyleCounts[LayerActivity::ACTIVITY_SCALE]);
     return;
   }
 
   Size scale = transform2D.ScaleFactors(true);
   if (aActivity->mPreviousTransformScale == Some(scale)) {
-    return;  // Nothing changed.
+    return; // Nothing changed.
   }
 
   aActivity->mPreviousTransformScale = Some(scale);
-  IncrementMutationCount(&aActivity->mRestyleCounts[LayerActivity::ACTIVITY_SCALE]);
+  IncrementMutationCount(
+    &aActivity->mRestyleCounts[LayerActivity::ACTIVITY_SCALE]);
 }
 
 /* static */ void
 ActiveLayerTracker::NotifyRestyle(nsIFrame* aFrame, nsCSSPropertyID aProperty)
 {
   LayerActivity* layerActivity = GetLayerActivityForUpdate(aFrame);
   uint8_t& mutationCount = layerActivity->RestyleCountForProperty(aProperty);
   IncrementMutationCount(&mutationCount);
@@ -301,20 +326,24 @@ ActiveLayerTracker::NotifyRestyle(nsIFra
     IncrementScaleRestyleCountIfNeeded(aFrame, layerActivity);
   }
 }
 
 /* static */ void
 ActiveLayerTracker::NotifyOffsetRestyle(nsIFrame* aFrame)
 {
   LayerActivity* layerActivity = GetLayerActivityForUpdate(aFrame);
-  IncrementMutationCount(&layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_LEFT]);
-  IncrementMutationCount(&layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_TOP]);
-  IncrementMutationCount(&layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_RIGHT]);
-  IncrementMutationCount(&layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_BOTTOM]);
+  IncrementMutationCount(
+    &layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_LEFT]);
+  IncrementMutationCount(
+    &layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_TOP]);
+  IncrementMutationCount(
+    &layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_RIGHT]);
+  IncrementMutationCount(
+    &layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_BOTTOM]);
 }
 
 /* static */ void
 ActiveLayerTracker::NotifyAnimated(nsIFrame* aFrame,
                                    nsCSSPropertyID aProperty,
                                    const nsAString& aNewValue,
                                    nsDOMCSSDeclaration* aDOMCSSDecl)
 {
@@ -326,25 +355,27 @@ ActiveLayerTracker::NotifyAnimated(nsIFr
     if (aNewValue != oldValue) {
       // We know this is animated, so just hack the mutation count.
       mutationCount = 0xFF;
     }
   }
 }
 
 /* static */ void
-ActiveLayerTracker::NotifyAnimatedFromScrollHandler(nsIFrame* aFrame, nsCSSPropertyID aProperty,
+ActiveLayerTracker::NotifyAnimatedFromScrollHandler(nsIFrame* aFrame,
+                                                    nsCSSPropertyID aProperty,
                                                     nsIFrame* aScrollFrame)
 {
   if (aFrame->PresContext() != aScrollFrame->PresContext()) {
     // Don't allow cross-document dependencies.
     return;
   }
   LayerActivity* layerActivity = GetLayerActivityForUpdate(aFrame);
-  LayerActivity::ActivityIndex activityIndex = LayerActivity::GetActivityIndexForProperty(aProperty);
+  LayerActivity::ActivityIndex activityIndex =
+    LayerActivity::GetActivityIndexForProperty(aProperty);
 
   if (layerActivity->mAnimatingScrollHandlerFrame.GetFrame() != aScrollFrame) {
     // Discard any activity of a different scroll frame. We only track the
     // most recent scroll handler induced activity.
     layerActivity->mScrollHandlerInducedActivity.clear();
     layerActivity->mAnimatingScrollHandlerFrame = aScrollFrame;
   }
 
@@ -359,55 +390,63 @@ IsPresContextInScriptAnimationCallback(n
   }
   // Treat timeouts/setintervals as scripted animation callbacks for our
   // purposes.
   nsPIDOMWindowInner* win = aPresContext->Document()->GetInnerWindow();
   return win && win->IsRunningTimeout();
 }
 
 /* static */ void
-ActiveLayerTracker::NotifyInlineStyleRuleModified(nsIFrame* aFrame,
-                                                  nsCSSPropertyID aProperty,
-                                                  const nsAString& aNewValue,
-                                                  nsDOMCSSDeclaration* aDOMCSSDecl)
+ActiveLayerTracker::NotifyInlineStyleRuleModified(
+  nsIFrame* aFrame,
+  nsCSSPropertyID aProperty,
+  const nsAString& aNewValue,
+  nsDOMCSSDeclaration* aDOMCSSDecl)
 {
   if (IsPresContextInScriptAnimationCallback(aFrame->PresContext())) {
     NotifyAnimated(aFrame, aProperty, aNewValue, aDOMCSSDecl);
   }
   if (gLayerActivityTracker &&
       gLayerActivityTracker->mCurrentScrollHandlerFrame.IsAlive()) {
-    NotifyAnimatedFromScrollHandler(aFrame, aProperty,
+    NotifyAnimatedFromScrollHandler(
+      aFrame,
+      aProperty,
       gLayerActivityTracker->mCurrentScrollHandlerFrame.GetFrame());
   }
 }
 
 /* static */ void
 ActiveLayerTracker::NotifyNeedsRepaint(nsIFrame* aFrame)
 {
   LayerActivity* layerActivity = GetLayerActivityForUpdate(aFrame);
   if (IsPresContextInScriptAnimationCallback(aFrame->PresContext())) {
-    // This is mirroring NotifyInlineStyleRuleModified's NotifyAnimated logic. Just max out
-    // the restyle count if we're in an animation callback.
-    layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_TRIGGERED_REPAINT] = 0xFF;
+    // This is mirroring NotifyInlineStyleRuleModified's NotifyAnimated logic.
+    // Just max out the restyle count if we're in an animation callback.
+    layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_TRIGGERED_REPAINT] =
+      0xFF;
   } else {
-    IncrementMutationCount(&layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_TRIGGERED_REPAINT]);
+    IncrementMutationCount(
+      &layerActivity
+         ->mRestyleCounts[LayerActivity::ACTIVITY_TRIGGERED_REPAINT]);
   }
 }
 
 /* static */ bool
-ActiveLayerTracker::IsStyleMaybeAnimated(nsIFrame* aFrame, nsCSSPropertyID aProperty)
+ActiveLayerTracker::IsStyleMaybeAnimated(nsIFrame* aFrame,
+                                         nsCSSPropertyID aProperty)
 {
   return IsStyleAnimated(nullptr, aFrame, aProperty);
 }
 
 /* static */ bool
 ActiveLayerTracker::IsBackgroundPositionAnimated(nsDisplayListBuilder* aBuilder,
                                                  nsIFrame* aFrame)
 {
-  return IsStyleAnimated(aBuilder, aFrame, eCSSProperty_background_position_x) ||
+  return IsStyleAnimated(
+           aBuilder, aFrame, eCSSProperty_background_position_x) ||
          IsStyleAnimated(aBuilder, aFrame, eCSSProperty_background_position_y);
 }
 
 static bool
 CheckScrollInducedActivity(LayerActivity* aLayerActivity,
                            LayerActivity::ActivityIndex aActivityIndex,
                            nsDisplayListBuilder* aBuilder)
 {
@@ -426,49 +465,58 @@ CheckScrollInducedActivity(LayerActivity
   // the layer activity so that it can expire.
   aLayerActivity->mAnimatingScrollHandlerFrame = nullptr;
   aLayerActivity->mScrollHandlerInducedActivity.clear();
   return false;
 }
 
 /* static */ bool
 ActiveLayerTracker::IsStyleAnimated(nsDisplayListBuilder* aBuilder,
-                                    nsIFrame* aFrame, nsCSSPropertyID aProperty)
+                                    nsIFrame* aFrame,
+                                    nsCSSPropertyID aProperty)
 {
   // TODO: Add some abuse restrictions
-  if ((aFrame->StyleDisplay()->mWillChangeBitField & NS_STYLE_WILL_CHANGE_TRANSFORM) &&
+  if ((aFrame->StyleDisplay()->mWillChangeBitField &
+       NS_STYLE_WILL_CHANGE_TRANSFORM) &&
       aProperty == eCSSProperty_transform &&
-      (!aBuilder || aBuilder->IsInWillChangeBudget(aFrame, aFrame->GetSize()))) {
+      (!aBuilder ||
+       aBuilder->IsInWillChangeBudget(aFrame, aFrame->GetSize()))) {
     return true;
   }
-  if ((aFrame->StyleDisplay()->mWillChangeBitField & NS_STYLE_WILL_CHANGE_OPACITY) &&
+  if ((aFrame->StyleDisplay()->mWillChangeBitField &
+       NS_STYLE_WILL_CHANGE_OPACITY) &&
       aProperty == eCSSProperty_opacity &&
-      (!aBuilder || aBuilder->IsInWillChangeBudget(aFrame, aFrame->GetSize()))) {
+      (!aBuilder ||
+       aBuilder->IsInWillChangeBudget(aFrame, aFrame->GetSize()))) {
     return true;
   }
 
   LayerActivity* layerActivity = GetLayerActivity(aFrame);
   if (layerActivity) {
-    LayerActivity::ActivityIndex activityIndex = LayerActivity::GetActivityIndexForProperty(aProperty);
+    LayerActivity::ActivityIndex activityIndex =
+      LayerActivity::GetActivityIndexForProperty(aProperty);
     if (layerActivity->mRestyleCounts[activityIndex] >= 2) {
       // If the frame needs to be repainted frequently, we probably don't get
       // much from treating the property as animated, *unless* this frame's
       // 'scale' (which includes the bounds changes of a rotation) is changing.
       // Marking a scaling transform as animating allows us to avoid resizing
       // the texture, even if we have to repaint the contents of that texture.
-      if (layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_TRIGGERED_REPAINT] < 2 ||
-          (aProperty == eCSSProperty_transform && IsScaleSubjectToAnimation(aFrame))) {
+      if (layerActivity
+              ->mRestyleCounts[LayerActivity::ACTIVITY_TRIGGERED_REPAINT] < 2 ||
+          (aProperty == eCSSProperty_transform &&
+           IsScaleSubjectToAnimation(aFrame))) {
         return true;
       }
     }
     if (CheckScrollInducedActivity(layerActivity, activityIndex, aBuilder)) {
       return true;
     }
   }
-  if (aProperty == eCSSProperty_transform && aFrame->Combines3DTransformWithAncestors()) {
+  if (aProperty == eCSSProperty_transform &&
+      aFrame->Combines3DTransformWithAncestors()) {
     return IsStyleAnimated(aBuilder, aFrame->GetParent(), aProperty);
   }
   return nsLayoutUtils::HasEffectiveAnimation(aFrame, aProperty);
 }
 
 /* static */ bool
 ActiveLayerTracker::IsOffsetStyleAnimated(nsIFrame* aFrame)
 {
@@ -489,17 +537,18 @@ ActiveLayerTracker::IsOffsetStyleAnimate
   return false;
 }
 
 /* static */ bool
 ActiveLayerTracker::IsScaleSubjectToAnimation(nsIFrame* aFrame)
 {
   // Check whether JavaScript is animating this frame's scale.
   LayerActivity* layerActivity = GetLayerActivity(aFrame);
-  if (layerActivity && layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_SCALE] >= 2) {
+  if (layerActivity &&
+      layerActivity->mRestyleCounts[LayerActivity::ACTIVITY_SCALE] >= 2) {
     return true;
   }
 
   // Check if any animations, transitions, etc. associated with this frame may
   // animate its scale.
   EffectSet* effects = EffectSet::GetEffectSet(aFrame);
   if (effects &&
       AnimationUtils::EffectSetContainsAnimatedScale(*effects, aFrame)) {
--- a/layout/painting/ActiveLayerTracker.h
+++ b/layout/painting/ActiveLayerTracker.h
@@ -17,25 +17,27 @@ class nsDOMCSSDeclaration;
 namespace mozilla {
 
 /**
  * This class receives various notifications about style changes and content
  * changes that affect layerization decisions, and implements the heuristics
  * that drive those decisions. It manages per-frame state to support those
  * heuristics.
  */
-class ActiveLayerTracker {
+class ActiveLayerTracker
+{
 public:
   static void Shutdown();
 
   /*
    * We track style changes to selected styles:
    *   eCSSProperty_transform
    *   eCSSProperty_opacity
-   *   eCSSProperty_left, eCSSProperty_top, eCSSProperty_right, eCSSProperty_bottom
+   *   eCSSProperty_left, eCSSProperty_top,
+   *   eCSSProperty_right, eCSSProperty_bottom
    * and use that information to guess whether style changes are animated.
    */
 
   /**
    * Notify aFrame's style property as having changed due to a restyle,
    * and therefore possibly wanting an active layer to render that style.
    * Any such marking will time out after a short period.
    * @param aProperty the property that has changed
@@ -48,53 +50,57 @@ public:
    */
   static void NotifyOffsetRestyle(nsIFrame* aFrame);
   /**
    * Mark aFrame as being known to have an animation of aProperty.
    * Any such marking will time out after a short period.
    * aNewValue and aDOMCSSDecl are used to determine whether the property's
    * value has changed.
    */
-  static void NotifyAnimated(nsIFrame* aFrame, nsCSSPropertyID aProperty,
+  static void NotifyAnimated(nsIFrame* aFrame,
+                             nsCSSPropertyID aProperty,
                              const nsAString& aNewValue,
                              nsDOMCSSDeclaration* aDOMCSSDecl);
   /**
    * Notify aFrame as being known to have an animation of aProperty through an
    * inline style modification during aScrollFrame's scroll event handler.
    */
-  static void NotifyAnimatedFromScrollHandler(nsIFrame* aFrame, nsCSSPropertyID aProperty,
+  static void NotifyAnimatedFromScrollHandler(nsIFrame* aFrame,
+                                              nsCSSPropertyID aProperty,
                                               nsIFrame* aScrollFrame);
   /**
    * Notify that a property in the inline style rule of aFrame's element
    * has been modified.
    * This notification is incomplete --- not all modifications to inline
    * style will trigger this.
    * aNewValue and aDOMCSSDecl are used to determine whether the property's
    * value has changed.
    */
-  static void NotifyInlineStyleRuleModified(nsIFrame* aFrame, nsCSSPropertyID aProperty,
+  static void NotifyInlineStyleRuleModified(nsIFrame* aFrame,
+                                            nsCSSPropertyID aProperty,
                                             const nsAString& aNewValue,
                                             nsDOMCSSDeclaration* aDOMCSSDecl);
   /**
    * Notify that a frame needs to be repainted. This is important for layering
    * decisions where, say, aFrame's transform is updated from JS, but we need
    * to repaint aFrame anyway, so we get no benefit from giving it its own
    * layer.
    */
   static void NotifyNeedsRepaint(nsIFrame* aFrame);
   /**
-   * Return true if aFrame's aProperty style should be considered as being animated
-   * for pre-rendering.
+   * Return true if aFrame's aProperty style should be considered as being
+   * animated for pre-rendering.
    */
   static bool IsStyleMaybeAnimated(nsIFrame* aFrame, nsCSSPropertyID aProperty);
   /**
-   * Return true if aFrame's aProperty style should be considered as being animated
-   * for constructing active layers.
+   * Return true if aFrame's aProperty style should be considered as being
+   * animated for constructing active layers.
    */
-  static bool IsStyleAnimated(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame,
+  static bool IsStyleAnimated(nsDisplayListBuilder* aBuilder,
+                              nsIFrame* aFrame,
                               nsCSSPropertyID aProperty);
   /**
    * Return true if any of aFrame's offset property styles should be considered
    * as being animated for constructing active layers.
    */
   static bool IsOffsetStyleAnimated(nsIFrame* aFrame);
   /**
    * Return true if aFrame's background-position-x or background-position-y
@@ -118,18 +124,18 @@ public:
   static void TransferActivityToContent(nsIFrame* aFrame, nsIContent* aContent);
   /**
    * Transfer the LayerActivity property back to the content node's primary
    * frame after the frame has been created.
    */
   static void TransferActivityToFrame(nsIContent* aContent, nsIFrame* aFrame);
 
   /*
-   * We track modifications to the content of certain frames (i.e. canvas frames)
-   * and use that to make layering decisions.
+   * We track modifications to the content of certain frames (i.e. canvas
+   * frames) and use that to make layering decisions.
    */
 
   /**
    * Mark aFrame's content as being active. This marking will time out after
    * a short period.
    */
   static void NotifyContentChange(nsIFrame* aFrame);
   /**
--- a/layout/painting/BorderCache.h
+++ b/layout/painting/BorderCache.h
@@ -32,45 +32,51 @@ struct FourFloats
   FourFloats(Float a, Float b, Float c, Float d)
   {
     n[0] = a;
     n[1] = b;
     n[2] = c;
     n[3] = d;
   }
 
-  bool
-  operator==(const FourFloats& aOther) const
+  bool operator==(const FourFloats& aOther) const
   {
-    return n[0] == aOther.n[0] &&
-           n[1] == aOther.n[1] &&
-           n[2] == aOther.n[2] &&
+    return n[0] == aOther.n[0] && n[1] == aOther.n[1] && n[2] == aOther.n[2] &&
            n[3] == aOther.n[3];
   }
 };
 
 class FourFloatsHashKey : public PLDHashEntryHdr
 {
 public:
   typedef const FourFloats& KeyType;
   typedef const FourFloats* KeyTypePointer;
 
-  explicit FourFloatsHashKey(KeyTypePointer aKey) : mValue(*aKey) {}
-  FourFloatsHashKey(const FourFloatsHashKey& aToCopy) : mValue(aToCopy.mValue) {}
-  ~FourFloatsHashKey() {}
+  explicit FourFloatsHashKey(KeyTypePointer aKey)
+    : mValue(*aKey)
+  {
+  }
+  FourFloatsHashKey(const FourFloatsHashKey& aToCopy)
+    : mValue(aToCopy.mValue)
+  {
+  }
+  ~FourFloatsHashKey() = default;
 
   KeyType GetKey() const { return mValue; }
   bool KeyEquals(KeyTypePointer aKey) const { return *aKey == mValue; }
 
   static KeyTypePointer KeyToPointer(KeyType aKey) { return &aKey; }
   static PLDHashNumber HashKey(KeyTypePointer aKey)
   {
     return HashBytes(aKey->n, sizeof(mozilla::gfx::Float) * 4);
   }
-  enum { ALLOW_MEMMOVE = true };
+  enum
+  {
+    ALLOW_MEMMOVE = true
+  };
 
 private:
   const FourFloats mValue;
 };
 
 } // namespace mozilla
 
 #endif /* mozilla_BorderCache_h_ */
--- a/layout/painting/BorderConsts.h
+++ b/layout/painting/BorderConsts.h
@@ -3,18 +3,18 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_BorderConsts_h_
 #define mozilla_BorderConsts_h_
 
 // thickness of dashed line relative to dotted line
-#define DOT_LENGTH  1           // square
-#define DASH_LENGTH 3           // 3 times longer than dot
+#define DOT_LENGTH 1  // square
+#define DASH_LENGTH 3 // 3 times longer than dot
 
 #define C_TL mozilla::eCornerTopLeft
 #define C_TR mozilla::eCornerTopRight
 #define C_BR mozilla::eCornerBottomRight
 #define C_BL mozilla::eCornerBottomLeft
 
 #define BORDER_SEGMENT_COUNT_MAX 100
 #define BORDER_DOTTED_CORNER_MAX_RADIUS 100000
--- a/layout/painting/DashedCornerFinder.cpp
+++ b/layout/painting/DashedCornerFinder.cpp
@@ -17,40 +17,49 @@ using namespace gfx;
 struct BestDashLength
 {
   typedef mozilla::gfx::Float Float;
 
   Float dashLength;
   size_t count;
 
   BestDashLength()
-   : dashLength(0.0f), count(0)
-  {}
+    : dashLength(0.0f)
+    , count(0)
+  {
+  }
 
   BestDashLength(Float aDashLength, size_t aCount)
-   : dashLength(aDashLength), count(aCount)
-  {}
+    : dashLength(aDashLength)
+    , count(aCount)
+  {
+  }
 };
 
 static const size_t DashedCornerCacheSize = 256;
 nsDataHashtable<FourFloatsHashKey, BestDashLength> DashedCornerCache;
 
 DashedCornerFinder::DashedCornerFinder(const Bezier& aOuterBezier,
                                        const Bezier& aInnerBezier,
-                                       Float aBorderWidthH, Float aBorderWidthV,
+                                       Float aBorderWidthH,
+                                       Float aBorderWidthV,
                                        const Size& aCornerDim)
- : mOuterBezier(aOuterBezier),
-   mInnerBezier(aInnerBezier),
-   mLastOuterP(aOuterBezier.mPoints[0]), mLastInnerP(aInnerBezier.mPoints[0]),
-   mLastOuterT(0.0f), mLastInnerT(0.0f),
-   mBestDashLength(DOT_LENGTH * DASH_LENGTH),
-   mHasZeroBorderWidth(false), mHasMore(true),
-   mMaxCount(aCornerDim.width + aCornerDim.height),
-   mType(OTHER),
-   mI(0), mCount(0)
+  : mOuterBezier(aOuterBezier)
+  , mInnerBezier(aInnerBezier)
+  , mLastOuterP(aOuterBezier.mPoints[0])
+  , mLastInnerP(aInnerBezier.mPoints[0])
+  , mLastOuterT(0.0f)
+  , mLastInnerT(0.0f)
+  , mBestDashLength(DOT_LENGTH * DASH_LENGTH)
+  , mHasZeroBorderWidth(false)
+  , mHasMore(true)
+  , mMaxCount(aCornerDim.width + aCornerDim.height)
+  , mType(OTHER)
+  , mI(0)
+  , mCount(0)
 {
   NS_ASSERTION(aBorderWidthH > 0.0f || aBorderWidthV > 0.0f,
                "At least one side should have non-zero width.");
 
   DetermineType(aBorderWidthH, aBorderWidthV);
 
   Reset();
 }
@@ -65,22 +74,21 @@ DashedCornerFinder::DetermineType(Float 
     Swap(mOuterBezier.mPoints[0], mOuterBezier.mPoints[3]);
     Swap(mOuterBezier.mPoints[1], mOuterBezier.mPoints[2]);
     mLastOuterP = mOuterBezier.mPoints[0];
     mLastInnerP = mInnerBezier.mPoints[0];
   }
 
   // See the comment at mType declaration for each condition.
 
-  Float borderRadiusA = fabs(mOuterBezier.mPoints[0].x -
-                             mOuterBezier.mPoints[3].x);
-  Float borderRadiusB = fabs(mOuterBezier.mPoints[0].y -
-                             mOuterBezier.mPoints[3].y);
-  if (aBorderWidthH == aBorderWidthV &&
-      borderRadiusA == borderRadiusB &&
+  Float borderRadiusA =
+    fabs(mOuterBezier.mPoints[0].x - mOuterBezier.mPoints[3].x);
+  Float borderRadiusB =
+    fabs(mOuterBezier.mPoints[0].y - mOuterBezier.mPoints[3].y);
+  if (aBorderWidthH == aBorderWidthV && borderRadiusA == borderRadiusB &&
       borderRadiusA > aBorderWidthH * 2.0f) {
     Float curveHeight = borderRadiusA - aBorderWidthH / 2.0;
 
     mType = PERFECT;
     Float borderLength = M_PI * curveHeight / 2.0f;
 
     Float dashWidth = aBorderWidthH * DOT_LENGTH * DASH_LENGTH;
     size_t count = ceil(borderLength / dashWidth);
@@ -96,18 +104,18 @@ DashedCornerFinder::DetermineType(Float 
     mHasZeroBorderWidth = true;
   }
 
   if (mType == OTHER && !mHasZeroBorderWidth) {
     Float minBorderRadius = std::min(borderRadiusA, borderRadiusB);
     Float maxBorderRadius = std::max(borderRadiusA, borderRadiusB);
     Float maxBorderWidth = std::max(aBorderWidthH, aBorderWidthV);
 
-    FindBestDashLength(minBorderWidth, maxBorderWidth,
-                       minBorderRadius, maxBorderRadius);
+    FindBestDashLength(
+      minBorderWidth, maxBorderWidth, minBorderRadius, maxBorderRadius);
   }
 }
 
 bool
 DashedCornerFinder::HasMore(void) const
 {
   if (mHasZeroBorderWidth) {
     return mI < mMaxCount && mHasMore;
@@ -293,18 +301,18 @@ DashedCornerFinder::FindBestDashLength(F
                                        Float aMaxBorderWidth,
                                        Float aMinBorderRadius,
                                        Float aMaxBorderRadius)
 {
   // If dashLength is not calculateable, find it with binary search,
   // such that there exists i that OuterP_i == OuterP_n and
   // InnerP_i == InnerP_n with given dashLength.
 
-  FourFloats key(aMinBorderWidth, aMaxBorderWidth,
-                 aMinBorderRadius, aMaxBorderRadius);
+  FourFloats key(
+    aMinBorderWidth, aMaxBorderWidth, aMinBorderRadius, aMaxBorderRadius);
   BestDashLength best;
   if (DashedCornerCache.Get(key, &best)) {
     mCount = best.count;
     mBestDashLength = best.dashLength;
     return;
   }
 
   Float lower = 1.0f;
--- a/layout/painting/DashedCornerFinder.h
+++ b/layout/painting/DashedCornerFinder.h
@@ -106,21 +106,21 @@ public:
     //         |#####____+ 3
     //        0 +----
     //              ^
     //              |
     //   innerSectionBezier
     Bezier outerSectionBezier;
     Bezier innerSectionBezier;
 
-    Result(const Bezier& aOuterSectionBezier,
-           const Bezier& aInnerSectionBezier)
-     : outerSectionBezier(aOuterSectionBezier),
-       innerSectionBezier(aInnerSectionBezier)
-    {}
+    Result(const Bezier& aOuterSectionBezier, const Bezier& aInnerSectionBezier)
+      : outerSectionBezier(aOuterSectionBezier)
+      , innerSectionBezier(aInnerSectionBezier)
+    {
+    }
   };
 
   //                       aCornerDim.width
   //                     |<----------------->|
   //                     |                   |
   //                   --+-------------___---+--
   //                   ^ |         __--      | ^
   //                   | |       _-          | |
@@ -135,18 +135,20 @@ public:
   //                   | |          |
   //                   | |         |
   //                   | |         |
   //                   v |         |
   //                   --+---------+
   //                     |         |
   //                     |<------->|
   //                     aBorderWidthV
-  DashedCornerFinder(const Bezier& aOuterBezier, const Bezier& aInnerBezier,
-                     Float aBorderWidthH, Float aBorderWidthV,
+  DashedCornerFinder(const Bezier& aOuterBezier,
+                     const Bezier& aInnerBezier,
+                     Float aBorderWidthH,
+                     Float aBorderWidthV,
                      const Size& aCornerDim);
 
   bool HasMore(void) const;
   Result Next(void);
 
 private:
   static const size_t MAX_LOOP = 32;
 
@@ -182,17 +184,18 @@ private:
   // If one of border-widths is 0, do not calculate mBestDashLength, and draw
   // segments until it reaches the other side or exceeds mMaxCount.
   bool mHasZeroBorderWidth;
   bool mHasMore;
 
   // The maximum number of segments.
   size_t mMaxCount;
 
-  enum {
+  enum
+  {
     //                      radius.width
     //                 |<----------------->|
     //                 |                   |
     //               --+-------------___---+--
     //               ^ |         __--      | ^
     //               | |       _-          | |
     //               | |     /             + | top-width
     //               | |   /               | |
@@ -259,20 +262,23 @@ private:
 
   // Reset calculation.
   void Reset(void);
 
   // Find next segment.
   Float FindNext(Float dashLength);
 
   // Find mBestDashLength for parameters.
-  void FindBestDashLength(Float aMinBorderWidth, Float aMaxBorderWidth,
-                          Float aMinBorderRadius, Float aMaxBorderRadius);
+  void FindBestDashLength(Float aMinBorderWidth,
+                          Float aMaxBorderWidth,
+                          Float aMinBorderRadius,
+                          Float aMaxBorderRadius);
 
   // Fill corner with dashes with given dash length, and return the number of
   // segments and last segment's dash length.
   bool GetCountAndLastDashLength(Float aDashLength,
-                                 size_t* aCount, Float* aActualDashLength);
+                                 size_t* aCount,
+                                 Float* aActualDashLength);
 };
 
 } // namespace mozilla
 
 #endif /* mozilla_DashedCornerFinder_h_ */
--- a/layout/painting/DisplayItemClip.cpp
+++ b/layout/painting/DisplayItemClip.cpp
@@ -30,32 +30,32 @@ DisplayItemClip::SetTo(const nsRect& aRe
 void
 DisplayItemClip::SetTo(const nsRect& aRect, const nscoord* aRadii)
 {
   mHaveClipRect = true;
   mClipRect = aRect;
   if (aRadii) {
     mRoundedClipRects.SetLength(1);
     mRoundedClipRects[0].mRect = aRect;
-    memcpy(mRoundedClipRects[0].mRadii, aRadii, sizeof(nscoord)*8);
+    memcpy(mRoundedClipRects[0].mRadii, aRadii, sizeof(nscoord) * 8);
   } else {
     mRoundedClipRects.Clear();
   }
 }
 
 void
 DisplayItemClip::SetTo(const nsRect& aRect,
                        const nsRect& aRoundedRect,
                        const nscoord* aRadii)
 {
   mHaveClipRect = true;
   mClipRect = aRect;
   mRoundedClipRects.SetLength(1);
   mRoundedClipRects[0].mRect = aRoundedRect;
-  memcpy(mRoundedClipRects[0].mRadii, aRadii, sizeof(nscoord)*8);
+  memcpy(mRoundedClipRects[0].mRadii, aRadii, sizeof(nscoord) * 8);
 }
 
 bool
 DisplayItemClip::MayIntersect(const nsRect& aRect) const
 {
   if (!mHaveClipRect) {
     return !aRect.IsEmpty();
   }
@@ -85,18 +85,17 @@ DisplayItemClip::IntersectWith(const Dis
   if (!mClipRect.IntersectRect(mClipRect, aOther.mClipRect)) {
     mRoundedClipRects.Clear();
     return;
   }
   mRoundedClipRects.AppendElements(aOther.mRoundedClipRects);
 }
 
 void
-DisplayItemClip::ApplyTo(gfxContext* aContext,
-                         int32_t A2D) const
+DisplayItemClip::ApplyTo(gfxContext* aContext, int32_t A2D) const
 {
   ApplyRectTo(aContext, A2D);
   ApplyRoundedRectClipsTo(aContext, A2D, 0, mRoundedClipRects.Length());
 }
 
 void
 DisplayItemClip::ApplyRectTo(gfxContext* aContext, int32_t A2D) const
 {
@@ -104,108 +103,112 @@ DisplayItemClip::ApplyRectTo(gfxContext*
   gfxRect clip = nsLayoutUtils::RectToGfxRect(mClipRect, A2D);
   aContext->Rectangle(clip, true);
   aContext->Clip();
 }
 
 void
 DisplayItemClip::ApplyRoundedRectClipsTo(gfxContext* aContext,
                                          int32_t A2D,
-                                         uint32_t aBegin, uint32_t aEnd) const
+                                         uint32_t aBegin,
+                                         uint32_t aEnd) const
 {
   DrawTarget& aDrawTarget = *aContext->GetDrawTarget();
 
   aEnd = std::min<uint32_t>(aEnd, mRoundedClipRects.Length());
 
   for (uint32_t i = aBegin; i < aEnd; ++i) {
     RefPtr<Path> roundedRect =
       MakeRoundedRectPath(aDrawTarget, A2D, mRoundedClipRects[i]);
     aContext->Clip(roundedRect);
   }
 }
 
 void
-DisplayItemClip::FillIntersectionOfRoundedRectClips(gfxContext* aContext,
-                                                    const Color& aColor,
-                                                    int32_t aAppUnitsPerDevPixel) const
+DisplayItemClip::FillIntersectionOfRoundedRectClips(
+  gfxContext* aContext,
+  const Color& aColor,
+  int32_t aAppUnitsPerDevPixel) const
 {
   DrawTarget& aDrawTarget = *aContext->GetDrawTarget();
 
   uint32_t end = mRoundedClipRects.Length();
   if (!end) {
     return;
   }
 
   // Push clips for any rects that come BEFORE the rect at |aEnd - 1|, if any:
   ApplyRoundedRectClipsTo(aContext, aAppUnitsPerDevPixel, 0, end - 1);
 
   // Now fill the rect at |aEnd - 1|:
-  RefPtr<Path> roundedRect = MakeRoundedRectPath(aDrawTarget,
-                                                 aAppUnitsPerDevPixel,
-                                                 mRoundedClipRects[end - 1]);
+  RefPtr<Path> roundedRect = MakeRoundedRectPath(
+    aDrawTarget, aAppUnitsPerDevPixel, mRoundedClipRects[end - 1]);
   ColorPattern color(ToDeviceColor(aColor));
   aDrawTarget.Fill(roundedRect, color);
 
   // Finally, pop any clips that we may have pushed:
   for (uint32_t i = 0; i < end - 1; ++i) {
     aContext->PopClip();
   }
 }
 
 already_AddRefed<Path>
 DisplayItemClip::MakeRoundedRectPath(DrawTarget& aDrawTarget,
                                      int32_t A2D,
-                                     const RoundedRect &aRoundRect) const
+                                     const RoundedRect& aRoundRect) const
 {
   RectCornerRadii pixelRadii;
   nsCSSRendering::ComputePixelRadii(aRoundRect.mRadii, A2D, &pixelRadii);
 
   Rect rect = NSRectToSnappedRect(aRoundRect.mRect, A2D, aDrawTarget);
 
   return MakePathForRoundedRect(aDrawTarget, rect, pixelRadii);
 }
 
 nsRect
 DisplayItemClip::ApproximateIntersectInward(const nsRect& aRect) const
 {
   nsRect r = aRect;
   if (mHaveClipRect) {
     r.IntersectRect(r, mClipRect);
   }
-  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length();
-       i < iEnd; ++i) {
-    const RoundedRect &rr = mRoundedClipRects[i];
-    nsRegion rgn = nsLayoutUtils::RoundedRectIntersectRect(rr.mRect, rr.mRadii, r);
+  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length(); i < iEnd; ++i) {
+    const RoundedRect& rr = mRoundedClipRects[i];
+    nsRegion rgn =
+      nsLayoutUtils::RoundedRectIntersectRect(rr.mRect, rr.mRadii, r);
     r = rgn.GetLargestRectangle();
   }
   return r;
 }
 
 // Test if (aXPoint, aYPoint) is in the ellipse with center (aXCenter, aYCenter)
 // and radii aXRadius, aYRadius.
 static bool
-IsInsideEllipse(nscoord aXRadius, nscoord aXCenter, nscoord aXPoint,
-                nscoord aYRadius, nscoord aYCenter, nscoord aYPoint)
+IsInsideEllipse(nscoord aXRadius,
+                nscoord aXCenter,
+                nscoord aXPoint,
+                nscoord aYRadius,
+                nscoord aYCenter,
+                nscoord aYPoint)
 {
   float scaledX = float(aXPoint - aXCenter) / float(aXRadius);
   float scaledY = float(aYPoint - aYCenter) / float(aYRadius);
   return scaledX * scaledX + scaledY * scaledY < 1.0f;
 }
 
 bool
 DisplayItemClip::IsRectClippedByRoundedCorner(const nsRect& aRect) const
 {
   if (mRoundedClipRects.IsEmpty())
     return false;
 
   nsRect rect;
   rect.IntersectRect(aRect, NonRoundedIntersection());
-  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length();
-       i < iEnd; ++i) {
-    const RoundedRect &rr = mRoundedClipRects[i];
+  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length(); i < iEnd; ++i) {
+    const RoundedRect& rr = mRoundedClipRects[i];
     // top left
     if (rect.x < rr.mRect.x + rr.mRadii[eCornerTopLeftX] &&
         rect.y < rr.mRect.y + rr.mRadii[eCornerTopLeftY]) {
       if (!IsInsideEllipse(rr.mRadii[eCornerTopLeftX],
                            rr.mRect.x + rr.mRadii[eCornerTopLeftX],
                            rect.x,
                            rr.mRadii[eCornerTopLeftY],
                            rr.mRect.y + rr.mRadii[eCornerTopLeftY],
@@ -253,84 +256,83 @@ DisplayItemClip::IsRectClippedByRoundedC
   return false;
 }
 
 nsRect
 DisplayItemClip::NonRoundedIntersection() const
 {
   NS_ASSERTION(mHaveClipRect, "Must have a clip rect!");
   nsRect result = mClipRect;
-  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length();
-       i < iEnd; ++i) {
+  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length(); i < iEnd; ++i) {
     result.IntersectRect(result, mRoundedClipRects[i].mRect);
   }
   return result;
 }
 
 bool
 DisplayItemClip::IsRectAffectedByClip(const nsRect& aRect) const
 {
   if (mHaveClipRect && !mClipRect.Contains(aRect)) {
     return true;
   }
-  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length();
-       i < iEnd; ++i) {
-    const RoundedRect &rr = mRoundedClipRects[i];
-    nsRegion rgn = nsLayoutUtils::RoundedRectIntersectRect(rr.mRect, rr.mRadii, aRect);
+  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length(); i < iEnd; ++i) {
+    const RoundedRect& rr = mRoundedClipRects[i];
+    nsRegion rgn =
+      nsLayoutUtils::RoundedRectIntersectRect(rr.mRect, rr.mRadii, aRect);
     if (!rgn.Contains(aRect)) {
       return true;
     }
   }
   return false;
 }
 
 bool
 DisplayItemClip::IsRectAffectedByClip(const nsIntRect& aRect,
                                       float aXScale,
                                       float aYScale,
                                       int32_t A2D) const
 {
   if (mHaveClipRect) {
-    nsIntRect pixelClipRect = mClipRect.ScaleToNearestPixels(aXScale, aYScale, A2D);
+    nsIntRect pixelClipRect =
+      mClipRect.ScaleToNearestPixels(aXScale, aYScale, A2D);
     if (!pixelClipRect.Contains(aRect)) {
       return true;
     }
   }
 
   // Rounded rect clipping only snaps to user-space pixels, not device space.
   nsIntRect unscaled = aRect;
-  unscaled.Scale(1/aXScale, 1/aYScale);
+  unscaled.Scale(1 / aXScale, 1 / aYScale);
 
-  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length();
-       i < iEnd; ++i) {
-    const RoundedRect &rr = mRoundedClipRects[i];
+  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length(); i < iEnd; ++i) {
+    const RoundedRect& rr = mRoundedClipRects[i];
 
     nsIntRect pixelRect = rr.mRect.ToNearestPixels(A2D);
 
     RectCornerRadii pixelRadii;
     nsCSSRendering::ComputePixelRadii(rr.mRadii, A2D, &pixelRadii);
 
-    nsIntRegion rgn = nsLayoutUtils::RoundedRectIntersectIntRect(pixelRect, pixelRadii, unscaled);
+    nsIntRegion rgn = nsLayoutUtils::RoundedRectIntersectIntRect(
+      pixelRect, pixelRadii, unscaled);
     if (!rgn.Contains(unscaled)) {
       return true;
     }
   }
   return false;
 }
 
 nsRect
 DisplayItemClip::ApplyNonRoundedIntersection(const nsRect& aRect) const
 {
   if (!mHaveClipRect) {
     return aRect;
   }
 
   nsRect result = aRect.Intersect(mClipRect);
-  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length();
-       i < iEnd; ++i) {
+  for (uint32_t i = 0, iEnd = mRoundedClipRects.Length(); i < iEnd; ++i) {
     result = result.Intersect(mRoundedClipRects[i].mRect);
   }
   return result;
 }
 
 void
 DisplayItemClip::RemoveRoundedCorners()
 {
@@ -338,17 +340,20 @@ DisplayItemClip::RemoveRoundedCorners()
     return;
 
   mClipRect = NonRoundedIntersection();
   mRoundedClipRects.Clear();
 }
 
 // Computes the difference between aR1 and aR2, limited to aBounds.
 static void
-AccumulateRectDifference(const nsRect& aR1, const nsRect& aR2, const nsRect& aBounds, nsRegion* aOut)
+AccumulateRectDifference(const nsRect& aR1,
+                         const nsRect& aR2,
+                         const nsRect& aBounds,
+                         nsRegion* aOut)
 {
   if (aR1.IsEqualInterior(aR2))
     return;
   nsRegion r;
   r.Xor(aR1, aR2);
   r.And(r, aBounds);
   aOut->Or(*aOut, r);
 }
@@ -358,19 +363,20 @@ AccumulateRoundedRectDifference(const Di
                                 const DisplayItemClip::RoundedRect& aR2,
                                 const nsRect& aBounds,
                                 const nsRect& aOtherBounds,
                                 nsRegion* aOut)
 {
   const nsRect& rect1 = aR1.mRect;
   const nsRect& rect2 = aR2.mRect;
 
-  // If the two rectangles are totally disjoint, just add them both - otherwise we'd
-  // end up adding one big enclosing rect
-  if (!rect1.Intersects(rect2) || memcmp(aR1.mRadii, aR2.mRadii, sizeof(aR1.mRadii))) {
+  // If the two rectangles are totally disjoint, just add them both - otherwise
+  // we'd end up adding one big enclosing rect
+  if (!rect1.Intersects(rect2) ||
+      memcmp(aR1.mRadii, aR2.mRadii, sizeof(aR1.mRadii))) {
     aOut->Or(*aOut, rect1.Intersect(aBounds));
     aOut->Or(*aOut, rect2.Intersect(aOtherBounds));
     return;
   }
 
   nscoord lowestBottom = std::max(rect1.YMost(), rect2.YMost());
   nscoord highestTop = std::min(rect1.Y(), rect2.Y());
   nscoord maxRight = std::max(rect1.XMost(), rect2.XMost());
@@ -393,59 +399,72 @@ AccumulateRoundedRectDifference(const Di
   // |       |--------------          --|------------         |
   // |       |-----aR1---|--          --|-----aR2---|         |
   // |       |--------------          --|------------         |
   // |       -\ __________\-__________-/ _ _ _ _ _ /-          |
   // |                                                        |
   // The logic below just implements this idea, but generalized to both the
   // X and Y dimensions. The "(...)Adjusted(...)" values represent the lopped
   // off sides.
-  nscoord highestAdjustedBottom =
-    std::min(rect1.YMost() - aR1.mRadii[eCornerBottomLeftY],
-             std::min(rect1.YMost() - aR1.mRadii[eCornerBottomRightY],
-                      std::min(rect2.YMost() - aR2.mRadii[eCornerBottomLeftY],
-                               rect2.YMost() - aR2.mRadii[eCornerBottomRightY])));
+  nscoord highestAdjustedBottom = std::min(
+    rect1.YMost() - aR1.mRadii[eCornerBottomLeftY],
+    std::min(rect1.YMost() - aR1.mRadii[eCornerBottomRightY],
+             std::min(rect2.YMost() - aR2.mRadii[eCornerBottomLeftY],
+                      rect2.YMost() - aR2.mRadii[eCornerBottomRightY])));
   nscoord lowestAdjustedTop =
     std::max(rect1.Y() + aR1.mRadii[eCornerTopLeftY],
              std::max(rect1.Y() + aR1.mRadii[eCornerTopRightY],
                       std::max(rect2.Y() + aR2.mRadii[eCornerTopLeftY],
                                rect2.Y() + aR2.mRadii[eCornerTopRightY])));
 
-  nscoord minAdjustedRight =
-    std::min(rect1.XMost() - aR1.mRadii[eCornerTopRightX],
-             std::min(rect1.XMost() - aR1.mRadii[eCornerBottomRightX],
-                      std::min(rect2.XMost() - aR2.mRadii[eCornerTopRightX],
-                               rect2.XMost() - aR2.mRadii[eCornerBottomRightX])));
+  nscoord minAdjustedRight = std::min(
+    rect1.XMost() - aR1.mRadii[eCornerTopRightX],
+    std::min(rect1.XMost() - aR1.mRadii[eCornerBottomRightX],
+             std::min(rect2.XMost() - aR2.mRadii[eCornerTopRightX],
+                      rect2.XMost() - aR2.mRadii[eCornerBottomRightX])));
   nscoord maxAdjustedLeft =
     std::max(rect1.X() + aR1.mRadii[eCornerTopLeftX],
              std::max(rect1.X() + aR1.mRadii[eCornerBottomLeftX],
                       std::max(rect2.X() + aR2.mRadii[eCornerTopLeftX],
                                rect2.X() + aR2.mRadii[eCornerBottomLeftX])));
 
-  // We only want to add an invalidation rect if the bounds have changed. If we always
-  // added all of the 4 rects below, we would always be invalidating a border around the
-  // rects, even in cases where we just translated along the X or Y axis.
+  // We only want to add an invalidation rect if the bounds have changed. If we
+  // always added all of the 4 rects below, we would always be invalidating a
+  // border around the rects, even in cases where we just translated along the X
+  // or Y axis.
   nsRegion r;
   // First, or with the Y delta rects, wide along the X axis
   if (rect1.Y() != rect2.Y()) {
-    r.Or(r, nsRect(minLeft, highestTop,
-                   maxRight - minLeft, lowestAdjustedTop - highestTop));
+    r.Or(r,
+         nsRect(minLeft,
+                highestTop,
+                maxRight - minLeft,
+                lowestAdjustedTop - highestTop));
   }
   if (rect1.YMost() != rect2.YMost()) {
-    r.Or(r, nsRect(minLeft, highestAdjustedBottom,
-                   maxRight - minLeft, lowestBottom - highestAdjustedBottom));
+    r.Or(r,
+         nsRect(minLeft,
+                highestAdjustedBottom,
+                maxRight - minLeft,
+                lowestBottom - highestAdjustedBottom));
   }
   // Then, or with the X delta rects, narrow along the Y axis
   if (rect1.X() != rect2.X()) {
-    r.Or(r, nsRect(minLeft, lowestAdjustedTop,
-                   maxAdjustedLeft - minLeft, highestAdjustedBottom - lowestAdjustedTop));
+    r.Or(r,
+         nsRect(minLeft,
+                lowestAdjustedTop,
+                maxAdjustedLeft - minLeft,
+                highestAdjustedBottom - lowestAdjustedTop));
   }
   if (rect1.XMost() != rect2.XMost()) {
-    r.Or(r, nsRect(minAdjustedRight, lowestAdjustedTop,
-                   maxRight - minAdjustedRight, highestAdjustedBottom - lowestAdjustedTop));
+    r.Or(r,
+         nsRect(minAdjustedRight,
+                lowestAdjustedTop,
+                maxRight - minAdjustedRight,
+                highestAdjustedBottom - lowestAdjustedTop));
   }
 
   r.And(r, aBounds.Union(aOtherBounds));
   aOut->Or(*aOut, r);
 }
 
 void
 DisplayItemClip::AddOffsetAndComputeDifference(const nsPoint& aOffset,
@@ -456,17 +475,18 @@ DisplayItemClip::AddOffsetAndComputeDiff
 {
   if (mHaveClipRect != aOther.mHaveClipRect ||
       mRoundedClipRects.Length() != aOther.mRoundedClipRects.Length()) {
     aDifference->Or(*aDifference, aBounds);
     aDifference->Or(*aDifference, aOtherBounds);
     return;
   }
   if (mHaveClipRect) {
-    AccumulateRectDifference(mClipRect + aOffset, aOther.mClipRect,
+    AccumulateRectDifference(mClipRect + aOffset,
+                             aOther.mClipRect,
                              aBounds.Union(aOtherBounds),
                              aDifference);
   }
   for (uint32_t i = 0; i < mRoundedClipRects.Length(); ++i) {
     if (mRoundedClipRects[i] + aOffset != aOther.mRoundedClipRects[i]) {
       AccumulateRoundedRectDifference(mRoundedClipRects[i] + aOffset,
                                       aOther.mRoundedClipRects[i],
                                       aBounds,
@@ -474,17 +494,18 @@ DisplayItemClip::AddOffsetAndComputeDiff
                                       aDifference);
     }
   }
 }
 
 void
 DisplayItemClip::AppendRoundedRects(nsTArray<RoundedRect>* aArray) const
 {
-  aArray->AppendElements(mRoundedClipRects.Elements(), mRoundedClipRects.Length());
+  aArray->AppendElements(mRoundedClipRects.Elements(),
+                         mRoundedClipRects.Length());
 }
 
 bool
 DisplayItemClip::ComputeRegionInClips(const DisplayItemClip* aOldClip,
                                       const nsPoint& aShift,
                                       nsRegion* aCombined) const
 {
   if (!mHaveClipRect || (aOldClip && !aOldClip->mHaveClipRect)) {
@@ -530,41 +551,62 @@ DisplayItemClip::Shutdown()
   gNoClip = nullptr;
 }
 
 nsCString
 DisplayItemClip::ToString() const
 {
   nsAutoCString str;
   if (mHaveClipRect) {
-    str.AppendPrintf("%d,%d,%d,%d", mClipRect.x, mClipRect.y,
-                     mClipRect.width, mClipRect.height);
+    str.AppendPrintf("%d,%d,%d,%d",
+                     mClipRect.x,
+                     mClipRect.y,
+                     mClipRect.width,
+                     mClipRect.height);
     for (uint32_t i = 0; i < mRoundedClipRects.Length(); ++i) {
       const RoundedRect& r = mRoundedClipRects[i];
       str.AppendPrintf(" [%d,%d,%d,%d corners %d,%d,%d,%d,%d,%d,%d,%d]",
-                       r.mRect.x, r.mRect.y, r.mRect.width, r.mRect.height,
-                       r.mRadii[0], r.mRadii[1], r.mRadii[2], r.mRadii[3],
-                       r.mRadii[4], r.mRadii[5], r.mRadii[6], r.mRadii[7]);
+                       r.mRect.x,
+                       r.mRect.y,
+                       r.mRect.width,
+                       r.mRect.height,
+                       r.mRadii[0],
+                       r.mRadii[1],
+                       r.mRadii[2],
+                       r.mRadii[3],
+                       r.mRadii[4],
+                       r.mRadii[5],
+                       r.mRadii[6],
+                       r.mRadii[7]);
     }
   }
   return str;
 }
 
 void
-DisplayItemClip::ToComplexClipRegions(int32_t aAppUnitsPerDevPixel,
-                                      const layers::StackingContextHelper& aSc,
-                                      nsTArray<wr::ComplexClipRegion>& aOutArray) const
+DisplayItemClip::ToComplexClipRegions(
+  int32_t aAppUnitsPerDevPixel,
+  const layers::StackingContextHelper& aSc,
+  nsTArray<wr::ComplexClipRegion>& aOutArray) const
 {
   for (uint32_t i = 0; i < mRoundedClipRects.Length(); i++) {
     wr::ComplexClipRegion* region = aOutArray.AppendElement();
     region->rect = wr::ToRoundedLayoutRect(LayoutDeviceRect::FromAppUnits(
-        mRoundedClipRects[i].mRect, aAppUnitsPerDevPixel));
+      mRoundedClipRects[i].mRect, aAppUnitsPerDevPixel));
     const nscoord* radii = mRoundedClipRects[i].mRadii;
     region->radii = wr::ToBorderRadius(
-        LayoutDeviceSize::FromAppUnits(nsSize(radii[eCornerTopLeftX], radii[eCornerTopLeftY]), aAppUnitsPerDevPixel),
-        LayoutDeviceSize::FromAppUnits(nsSize(radii[eCornerTopRightX], radii[eCornerTopRightY]), aAppUnitsPerDevPixel),
-        LayoutDeviceSize::FromAppUnits(nsSize(radii[eCornerBottomLeftX], radii[eCornerBottomLeftY]), aAppUnitsPerDevPixel),
-        LayoutDeviceSize::FromAppUnits(nsSize(radii[eCornerBottomRightX], radii[eCornerBottomRightY]), aAppUnitsPerDevPixel));
+      LayoutDeviceSize::FromAppUnits(
+        nsSize(radii[eCornerTopLeftX], radii[eCornerTopLeftY]),
+        aAppUnitsPerDevPixel),
+      LayoutDeviceSize::FromAppUnits(
+        nsSize(radii[eCornerTopRightX], radii[eCornerTopRightY]),
+        aAppUnitsPerDevPixel),
+      LayoutDeviceSize::FromAppUnits(
+        nsSize(radii[eCornerBottomLeftX], radii[eCornerBottomLeftY]),
+        aAppUnitsPerDevPixel),
+      LayoutDeviceSize::FromAppUnits(
+        nsSize(radii[eCornerBottomRightX], radii[eCornerBottomRightY]),
+        aAppUnitsPerDevPixel));
     region->mode = wr::ClipMode::Clip;
   }
 }
 
 } // namespace mozilla
--- a/layout/painting/DisplayItemClip.h
+++ b/layout/painting/DisplayItemClip.h
@@ -32,77 +32,91 @@ struct ComplexClipRegion;
 namespace mozilla {
 
 /**
  * An DisplayItemClip represents the intersection of an optional rectangle
  * with a list of rounded rectangles (which is often empty), all in appunits.
  * It can represent everything CSS clipping can do to an element (except for
  * SVG clip-path), including no clipping at all.
  */
-class DisplayItemClip {
+class DisplayItemClip
+{
   typedef mozilla::gfx::Color Color;
   typedef mozilla::gfx::DrawTarget DrawTarget;
   typedef mozilla::gfx::Path Path;
 
 public:
-  struct RoundedRect {
+  struct RoundedRect
+  {
     nsRect mRect;
     // Indices into mRadii are the HalfCorner values in gfx/2d/Types.h
     nscoord mRadii[8];
 
-    RoundedRect operator+(const nsPoint& aOffset) const {
+    RoundedRect operator+(const nsPoint& aOffset) const
+    {
       RoundedRect r = *this;
       r.mRect += aOffset;
       return r;
     }
-    bool operator==(const RoundedRect& aOther) const {
+    bool operator==(const RoundedRect& aOther) const
+    {
       if (!mRect.IsEqualInterior(aOther.mRect)) {
         return false;
       }
 
-      NS_FOR_CSS_HALF_CORNERS(corner) {
+      NS_FOR_CSS_HALF_CORNERS(corner)
+      {
         if (mRadii[corner] != aOther.mRadii[corner]) {
           return false;
         }
       }
       return true;
     }
-    bool operator!=(const RoundedRect& aOther) const {
+    bool operator!=(const RoundedRect& aOther) const
+    {
       return !(*this == aOther);
     }
   };
 
   // Constructs a DisplayItemClip that does no clipping at all.
-  DisplayItemClip() : mHaveClipRect(false) {}
+  DisplayItemClip()
+    : mHaveClipRect(false)
+  {
+  }
 
   void SetTo(const nsRect& aRect);
   void SetTo(const nsRect& aRect, const nscoord* aRadii);
-  void SetTo(const nsRect& aRect, const nsRect& aRoundedRect, const nscoord* aRadii);
+  void SetTo(const nsRect& aRect,
+             const nsRect& aRoundedRect,
+             const nscoord* aRadii);
   void IntersectWith(const DisplayItemClip& aOther);
 
   // Apply this |DisplayItemClip| to the given gfxContext.  Any saving of state
   // or clearing of other clips must be done by the caller.
   // See aBegin/aEnd note on ApplyRoundedRectsTo.
   void ApplyTo(gfxContext* aContext, int32_t A2D) const;
 
   void ApplyRectTo(gfxContext* aContext, int32_t A2D) const;
   // Applies the rounded rects in this Clip to aContext
   // Will only apply rounded rects from aBegin (inclusive) to aEnd
   // (exclusive) or the number of rounded rects, whichever is smaller.
-  void ApplyRoundedRectClipsTo(gfxContext* aContext, int32_t A2DPRInt32,
-                               uint32_t aBegin, uint32_t aEnd) const;
+  void ApplyRoundedRectClipsTo(gfxContext* aContext,
+                               int32_t A2DPRInt32,
+                               uint32_t aBegin,
+                               uint32_t aEnd) const;
 
   // Draw (fill) the rounded rects in this clip to aContext
   void FillIntersectionOfRoundedRectClips(gfxContext* aContext,
                                           const Color& aColor,
                                           int32_t aAppUnitsPerDevPixel) const;
   // 'Draw' (create as a path, does not stroke or fill) aRoundRect to aContext
-  already_AddRefed<Path> MakeRoundedRectPath(DrawTarget& aDrawTarget,
-                                                  int32_t A2D,
-                                                  const RoundedRect &aRoundRect) const;
+  already_AddRefed<Path> MakeRoundedRectPath(
+    DrawTarget& aDrawTarget,
+    int32_t A2D,
+    const RoundedRect& aRoundRect) const;
 
   // Returns true if the intersection of aRect and this clip region is
   // non-empty. This is precise for DisplayItemClips with at most one
   // rounded rectangle. When multiple rounded rectangles are present, we just
   // check that the rectangle intersects all of them (but possibly in different
   // places). So it may return true when the correct answer is false.
   bool MayIntersect(const nsRect& aRect) const;
 
@@ -126,40 +140,47 @@ public:
   // this clip. Returns true if aRect is clipped by a rounded corner in this
   // clip or it can not be quickly determined that it is not clipped by a
   // rounded corner in this clip.
   bool IsRectClippedByRoundedCorner(const nsRect& aRect) const;
 
   // Returns false if aRect is definitely not clipped by anything in this clip.
   // Fast but not necessarily accurate.
   bool IsRectAffectedByClip(const nsRect& aRect) const;
-  bool IsRectAffectedByClip(const nsIntRect& aRect, float aXScale, float aYScale, int32_t A2D) const;
+  bool IsRectAffectedByClip(const nsIntRect& aRect,
+                            float aXScale,
+                            float aYScale,
+                            int32_t A2D) const;
 
   // Intersection of all rects in this clip ignoring any rounded corners.
   nsRect NonRoundedIntersection() const;
 
   // Intersect the given rects with all rects in this clip, ignoring any
   // rounded corners.
   nsRect ApplyNonRoundedIntersection(const nsRect& aRect) const;
 
   // Gets rid of any rounded corners in this clip.
   void RemoveRoundedCorners();
 
   // Adds the difference between Intersect(*this + aPoint, aBounds) and
   // Intersect(aOther, aOtherBounds) to aDifference (or a bounding-box thereof).
-  void AddOffsetAndComputeDifference(const nsPoint& aPoint, const nsRect& aBounds,
-                                     const DisplayItemClip& aOther, const nsRect& aOtherBounds,
+  void AddOffsetAndComputeDifference(const nsPoint& aPoint,
+                                     const nsRect& aBounds,
+                                     const DisplayItemClip& aOther,
+                                     const nsRect& aOtherBounds,
                                      nsRegion* aDifference);
 
-  bool operator==(const DisplayItemClip& aOther) const {
+  bool operator==(const DisplayItemClip& aOther) const
+  {
     return mHaveClipRect == aOther.mHaveClipRect &&
            (!mHaveClipRect || mClipRect.IsEqualInterior(aOther.mClipRect)) &&
            mRoundedClipRects == aOther.mRoundedClipRects;
   }
-  bool operator!=(const DisplayItemClip& aOther) const {
+  bool operator!=(const DisplayItemClip& aOther) const
+  {
     return !(*this == aOther);
   }
 
   bool HasClip() const { return mHaveClipRect; }
   const nsRect& GetClipRect() const
   {
     NS_ASSERTION(HasClip(), "No clip rect!");
     return mClipRect;
@@ -168,18 +189,18 @@ public:
   void MoveBy(const nsPoint& aPoint);
 
   nsCString ToString() const;
 
   uint32_t GetRoundedRectCount() const { return mRoundedClipRects.Length(); }
   void AppendRoundedRects(nsTArray<RoundedRect>* aArray) const;
 
   void ToComplexClipRegions(int32_t aAppUnitsPerDevPixel,
-                              const layers::StackingContextHelper& aSc,
-                              nsTArray<wr::ComplexClipRegion>& aOutArray) const;
+                            const layers::StackingContextHelper& aSc,
+                            nsTArray<wr::ComplexClipRegion>& aOutArray) const;
 
   static const DisplayItemClip& NoClip();
 
   static void Shutdown();
 
 private:
   nsRect mClipRect;
   nsTArray<RoundedRect> mRoundedClipRects;
--- a/layout/painting/DisplayItemClipChain.cpp
+++ b/layout/painting/DisplayItemClipChain.cpp
@@ -6,38 +6,41 @@
 
 #include "DisplayItemClipChain.h"
 
 #include "nsDisplayList.h"
 
 namespace mozilla {
 
 /* static */ const DisplayItemClip*
-DisplayItemClipChain::ClipForASR(const DisplayItemClipChain* aClipChain, const ActiveScrolledRoot* aASR)
+DisplayItemClipChain::ClipForASR(const DisplayItemClipChain* aClipChain,
+                                 const ActiveScrolledRoot* aASR)
 {
-  while (aClipChain && !ActiveScrolledRoot::IsAncestor(aClipChain->mASR, aASR)) {
+  while (aClipChain &&
+         !ActiveScrolledRoot::IsAncestor(aClipChain->mASR, aASR)) {
     aClipChain = aClipChain->mParent;
   }
-  return (aClipChain && aClipChain->mASR == aASR) ? &aClipChain->mClip : nullptr;
+  return (aClipChain && aClipChain->mASR == aASR) ? &aClipChain->mClip
+                                                  : nullptr;
 }
 
 bool
-DisplayItemClipChain::Equal(const DisplayItemClipChain* aClip1, const DisplayItemClipChain* aClip2)
+DisplayItemClipChain::Equal(const DisplayItemClipChain* aClip1,
+                            const DisplayItemClipChain* aClip2)
 {
   if (aClip1 == aClip2) {
     return true;
   }
 
   if (!aClip1 || !aClip2) {
     return false;
   }
 
-  bool ret = aClip1->mASR == aClip2->mASR &&
-         aClip1->mClip == aClip2->mClip &&
-         Equal(aClip1->mParent, aClip2->mParent);
+  bool ret = aClip1->mASR == aClip2->mASR && aClip1->mClip == aClip2->mClip &&
+             Equal(aClip1->mParent, aClip2->mParent);
   // Sanity check: if two clip chains are equal they must hash to the same
   // thing too, or Bad Things (TM) will happen.
   MOZ_ASSERT(!ret || (Hash(aClip1) == Hash(aClip2)));
   return ret;
 }
 
 uint32_t
 DisplayItemClipChain::Hash(const DisplayItemClipChain* aClip)
@@ -66,26 +69,30 @@ DisplayItemClipChain::Hash(const Display
 }
 
 /* static */ nsCString
 DisplayItemClipChain::ToString(const DisplayItemClipChain* aClipChain)
 {
   nsAutoCString str;
   for (auto* sc = aClipChain; sc; sc = sc->mParent) {
     if (sc->mASR) {
-      str.AppendPrintf("0x%p <%s> [0x%p]", sc, sc->mClip.ToString().get(), sc->mASR->mScrollableFrame);
+      str.AppendPrintf("0x%p <%s> [0x%p]",
+                       sc,
+                       sc->mClip.ToString().get(),
+                       sc->mASR->mScrollableFrame);
     } else {
       str.AppendPrintf("0x%p <%s> [root asr]", sc, sc->mClip.ToString().get());
     }
     if (sc->mParent) {
       str.AppendLiteral(", ");
     }
   }
   return str;
 }
 
 bool
 DisplayItemClipChain::HasRoundedCorners() const
 {
-  return mClip.GetRoundedRectCount() > 0 || (mParent && mParent->HasRoundedCorners());
+  return mClip.GetRoundedRectCount() > 0 ||
+         (mParent && mParent->HasRoundedCorners());
 }
 
 } // namespace mozilla
--- a/layout/painting/DisplayItemClipChain.h
+++ b/layout/painting/DisplayItemClipChain.h
@@ -25,63 +25,70 @@ struct ActiveScrolledRoot;
  * A clip that moves along with a display item can be fused to the item's
  * contents when drawing the layer contents, but all other clips in the chain
  * need to be kept separate so that they can be applied at composition time,
  * after any async scroll offsets have been applied.
  * The clip chain is created during display list construction by the builder's
  * DisplayListClipState.
  * The clip chain order is determined by the active scrolled root order.
  * For every DisplayItemClipChain object |clipChain|, the following holds:
- * !clipChain->mParent || ActiveScrolledRoot::IsAncestor(clipChain->mParent->mASR, clipChain->mASR).
+ * !clipChain->mParent ||
+ * ActiveScrolledRoot::IsAncestor(clipChain->mParent->mASR, clipChain->mASR).
  * The clip chain can skip over active scrolled roots. That just means that
  * there is no clip that moves with the skipped ASR in this chain.
  */
-struct DisplayItemClipChain {
+struct DisplayItemClipChain
+{
 
   /**
    * Get the display item clip in this chain that moves with aASR, or nullptr
    * if no such clip exists. aClipChain can be null.
    */
-  static const DisplayItemClip* ClipForASR(const DisplayItemClipChain* aClipChain,
-                                           const ActiveScrolledRoot* aASR);
+  static const DisplayItemClip* ClipForASR(
+    const DisplayItemClipChain* aClipChain,
+    const ActiveScrolledRoot* aASR);
 
-  static bool Equal(const DisplayItemClipChain* aClip1, const DisplayItemClipChain* aClip2);
+  static bool Equal(const DisplayItemClipChain* aClip1,
+                    const DisplayItemClipChain* aClip2);
   /**
    * Hash function that returns the same value for any two clips A and B
    * where Equal(A, B) is true.
    */
   static uint32_t Hash(const DisplayItemClipChain* aClip);
 
   static nsCString ToString(const DisplayItemClipChain* aClipChain);
 
   bool HasRoundedCorners() const;
 
-  void AddRef() {
-    mRefCount++;
-  }
-  void Release() {
+  void AddRef() { mRefCount++; }
+  void Release()
+  {
     MOZ_ASSERT(mRefCount > 0);
     mRefCount--;
   }
 
-  DisplayItemClipChain(const DisplayItemClip& aClip, const ActiveScrolledRoot* aASR, const DisplayItemClipChain* aParent)
+  DisplayItemClipChain(const DisplayItemClip& aClip,
+                       const ActiveScrolledRoot* aASR,
+                       const DisplayItemClipChain* aParent)
     : mClip(aClip)
     , mASR(aASR)
     , mParent(aParent)
 #ifdef DEBUG
     , mOnStack(true)
 #endif
-  {}
+  {
+  }
 
   DisplayItemClipChain()
     : mASR(nullptr)
 #ifdef DEBUG
     , mOnStack(true)
 #endif
-  {}
+  {
+  }
 
   DisplayItemClip mClip;
   const ActiveScrolledRoot* mASR;
   RefPtr<const DisplayItemClipChain> mParent;
   uint32_t mRefCount = 0;
 #ifdef DEBUG
   bool mOnStack;
 #endif
--- a/layout/painting/DisplayListClipState.cpp
+++ b/layout/painting/DisplayListClipState.cpp
@@ -6,31 +6,32 @@
 
 #include "DisplayListClipState.h"
 
 #include "nsDisplayList.h"
 
 namespace mozilla {
 
 const DisplayItemClipChain*
-DisplayListClipState::GetCurrentCombinedClipChain(nsDisplayListBuilder* aBuilder)
+DisplayListClipState::GetCurrentCombinedClipChain(
+  nsDisplayListBuilder* aBuilder)
 {
   if (mCurrentCombinedClipChainIsValid) {
     return mCurrentCombinedClipChain;
   }
   if (!mClipChainContentDescendants && !mClipChainContainingBlockDescendants) {
     mCurrentCombinedClipChain = nullptr;
     mCurrentCombinedClipChainIsValid = true;
     return nullptr;
   }
 
   mCurrentCombinedClipChain =
     aBuilder->CreateClipChainIntersection(mCurrentCombinedClipChain,
-                                             mClipChainContentDescendants,
-                                             mClipChainContainingBlockDescendants);
+                                          mClipChainContentDescendants,
+                                          mClipChainContainingBlockDescendants);
   mCurrentCombinedClipChainIsValid = true;
   return mCurrentCombinedClipChain;
 }
 
 static void
 ApplyClip(nsDisplayListBuilder* aBuilder,
           const DisplayItemClipChain*& aClipToModify,
           const ActiveScrolledRoot* aASR,
@@ -45,115 +46,125 @@ ApplyClip(nsDisplayListBuilder* aBuilder
   } else if (!aClipToModify ||
              ActiveScrolledRoot::IsAncestor(aClipToModify->mASR, aASR)) {
     // Add a new clip chain item at the bottom.
     aClipChainOnStack.mParent = aClipToModify;
     aClipToModify = &aClipChainOnStack;
   } else {
     // We need to insert / intersect a DisplayItemClipChain in the middle of the
     // aClipToModify chain. This is a very rare case.
-    // Find the common ancestor and have the builder create the DisplayItemClipChain
-    // intersection. This will create new DisplayItemClipChain objects for all
-    // descendants of ancestorSC and we will not hold on to a pointer to
-    // aClipChainOnStack.
+    // Find the common ancestor and have the builder create the
+    // DisplayItemClipChain intersection. This will create new
+    // DisplayItemClipChain objects for all descendants of ancestorSC and we
+    // will not hold on to a pointer to aClipChainOnStack.
     const DisplayItemClipChain* ancestorSC = aClipToModify;
-    while (ancestorSC && ActiveScrolledRoot::IsAncestor(aASR, ancestorSC->mASR)) {
+    while (ancestorSC &&
+           ActiveScrolledRoot::IsAncestor(aASR, ancestorSC->mASR)) {
       ancestorSC = ancestorSC->mParent;
     }
     ancestorSC = aBuilder->CopyWholeChain(ancestorSC);
     aClipChainOnStack.mParent = nullptr;
-    aClipToModify =
-      aBuilder->CreateClipChainIntersection(ancestorSC, aClipToModify, &aClipChainOnStack);
+    aClipToModify = aBuilder->CreateClipChainIntersection(
+      ancestorSC, aClipToModify, &aClipChainOnStack);
   }
 }
 
 void
-DisplayListClipState::ClipContainingBlockDescendants(nsDisplayListBuilder* aBuilder,
-                                                     const nsRect& aRect,
-                                                     const nscoord* aRadii,
-                                                     DisplayItemClipChain& aClipChainOnStack)
+DisplayListClipState::ClipContainingBlockDescendants(
+  nsDisplayListBuilder* aBuilder,
+  const nsRect& aRect,
+  const nscoord* aRadii,
+  DisplayItemClipChain& aClipChainOnStack)
 {
   if (aRadii) {
     aClipChainOnStack.mClip.SetTo(aRect, aRadii);
   } else {
     aClipChainOnStack.mClip.SetTo(aRect);
   }
   const ActiveScrolledRoot* asr = aBuilder->CurrentActiveScrolledRoot();
-  ApplyClip(aBuilder, mClipChainContainingBlockDescendants, asr, aClipChainOnStack);
+  ApplyClip(
+    aBuilder, mClipChainContainingBlockDescendants, asr, aClipChainOnStack);
   InvalidateCurrentCombinedClipChain(asr);
 }
 
 void
-DisplayListClipState::ClipContentDescendants(nsDisplayListBuilder* aBuilder,
-                                             const nsRect& aRect,
-                                             const nscoord* aRadii,
-                                             DisplayItemClipChain& aClipChainOnStack)
+DisplayListClipState::ClipContentDescendants(
+  nsDisplayListBuilder* aBuilder,
+  const nsRect& aRect,
+  const nscoord* aRadii,
+  DisplayItemClipChain& aClipChainOnStack)
 {
   if (aRadii) {
     aClipChainOnStack.mClip.SetTo(aRect, aRadii);
   } else {
     aClipChainOnStack.mClip.SetTo(aRect);
   }
   const ActiveScrolledRoot* asr = aBuilder->CurrentActiveScrolledRoot();
   ApplyClip(aBuilder, mClipChainContentDescendants, asr, aClipChainOnStack);
   InvalidateCurrentCombinedClipChain(asr);
 }
 
 void
-DisplayListClipState::ClipContentDescendants(nsDisplayListBuilder* aBuilder,
-                                             const nsRect& aRect,
-                                             const nsRect& aRoundedRect,
-                                             const nscoord* aRadii,
-                                             DisplayItemClipChain& aClipChainOnStack)
+DisplayListClipState::ClipContentDescendants(
+  nsDisplayListBuilder* aBuilder,
+  const nsRect& aRect,
+  const nsRect& aRoundedRect,
+  const nscoord* aRadii,
+  DisplayItemClipChain& aClipChainOnStack)
 {
   if (aRadii) {
     aClipChainOnStack.mClip.SetTo(aRect, aRoundedRect, aRadii);
   } else {
     nsRect intersect = aRect.Intersect(aRoundedRect);
     aClipChainOnStack.mClip.SetTo(intersect);
   }
   const ActiveScrolledRoot* asr = aBuilder->CurrentActiveScrolledRoot();
   ApplyClip(aBuilder, mClipChainContentDescendants, asr, aClipChainOnStack);
   InvalidateCurrentCombinedClipChain(asr);
 }
 
-
 void
-DisplayListClipState::InvalidateCurrentCombinedClipChain(const ActiveScrolledRoot* aInvalidateUpTo)
+DisplayListClipState::InvalidateCurrentCombinedClipChain(
+  const ActiveScrolledRoot* aInvalidateUpTo)
 {
   mCurrentCombinedClipChainIsValid = false;
   while (mCurrentCombinedClipChain &&
-         ActiveScrolledRoot::IsAncestor(aInvalidateUpTo, mCurrentCombinedClipChain->mASR)) {
+         ActiveScrolledRoot::IsAncestor(aInvalidateUpTo,
+                                        mCurrentCombinedClipChain->mASR)) {
     mCurrentCombinedClipChain = mCurrentCombinedClipChain->mParent;
   }
 }
 
 void
-DisplayListClipState::ClipContainingBlockDescendantsToContentBox(nsDisplayListBuilder* aBuilder,
-                                                                 nsIFrame* aFrame,
-                                                                 DisplayItemClipChain& aClipChainOnStack,
-                                                                 uint32_t aFlags)
+DisplayListClipState::ClipContainingBlockDescendantsToContentBox(
+  nsDisplayListBuilder* aBuilder,
+  nsIFrame* aFrame,
+  DisplayItemClipChain& aClipChainOnStack,
+  uint32_t aFlags)
 {
   nscoord radii[8];
   bool hasBorderRadius = aFrame->GetContentBoxBorderRadii(radii);
-  if (!hasBorderRadius && (aFlags & ASSUME_DRAWING_RESTRICTED_TO_CONTENT_RECT)) {
+  if (!hasBorderRadius &&
+      (aFlags & ASSUME_DRAWING_RESTRICTED_TO_CONTENT_RECT)) {
     return;
   }
 
-  nsRect clipRect = aFrame->GetContentRectRelativeToSelf() +
-    aBuilder->ToReferenceFrame(aFrame);
+  nsRect clipRect =
+    aFrame->GetContentRectRelativeToSelf() + aBuilder->ToReferenceFrame(aFrame);
   // If we have a border-radius, we have to clip our content to that
   // radius.
-  ClipContainingBlockDescendants(aBuilder, clipRect, hasBorderRadius ? radii : nullptr,
-                                 aClipChainOnStack);
+  ClipContainingBlockDescendants(
+    aBuilder, clipRect, hasBorderRadius ? radii : nullptr, aClipChainOnStack);
 }
 
-DisplayListClipState::AutoSaveRestore::AutoSaveRestore(nsDisplayListBuilder* aBuilder)
+DisplayListClipState::AutoSaveRestore::AutoSaveRestore(
+  nsDisplayListBuilder* aBuilder)
   : mBuilder(aBuilder)
   , mState(aBuilder->ClipState())
   , mSavedState(aBuilder->ClipState())
 #ifdef DEBUG
   , mClipUsed(false)
   , mRestored(false)
 #endif
-{}
+{
+}
 
 } // namespace mozilla
--- a/layout/painting/DisplayListClipState.h
+++ b/layout/painting/DisplayListClipState.h
@@ -17,66 +17,71 @@ class nsIScrollableFrame;
 class nsDisplayListBuilder;
 
 namespace mozilla {
 
 /**
  * All clip coordinates are in appunits relative to the reference frame
  * for the display item we're building.
  */
-class DisplayListClipState {
+class DisplayListClipState
+{
 public:
   DisplayListClipState()
     : mClipChainContentDescendants(nullptr)
     , mClipChainContainingBlockDescendants(nullptr)
     , mCurrentCombinedClipChain(nullptr)
     , mCurrentCombinedClipChainIsValid(false)
-  {}
+  {
+  }
 
   /**
    * Returns intersection of mClipChainContainingBlockDescendants and
    * mClipChainContentDescendants, allocated on aBuilder's arena.
    */
-  const DisplayItemClipChain* GetCurrentCombinedClipChain(nsDisplayListBuilder* aBuilder);
+  const DisplayItemClipChain* GetCurrentCombinedClipChain(
+    nsDisplayListBuilder* aBuilder);
 
   const DisplayItemClipChain* GetClipChainForContainingBlockDescendants() const
   {
     return mClipChainContainingBlockDescendants;
   }
   const DisplayItemClipChain* GetClipChainForContentDescendants() const
   {
     return mClipChainContentDescendants;
   }
 
   const ActiveScrolledRoot* GetContentClipASR() const
   {
-    return mClipChainContentDescendants ? mClipChainContentDescendants->mASR : nullptr;
+    return mClipChainContentDescendants ? mClipChainContentDescendants->mASR
+                                        : nullptr;
   }
 
   class AutoSaveRestore;
 
   class AutoClipContainingBlockDescendantsToContentBox;
 
   class AutoClipMultiple;
 
-  enum {
+  enum
+  {
     ASSUME_DRAWING_RESTRICTED_TO_CONTENT_RECT = 0x01
   };
 
 private:
-
   void Clear()
   {
     mClipChainContentDescendants = nullptr;
     mClipChainContainingBlockDescendants = nullptr;
     mCurrentCombinedClipChain = nullptr;
     mCurrentCombinedClipChainIsValid = false;
   }
 
-  void SetClipChainForContainingBlockDescendants(const DisplayItemClipChain* aClipChain)
+  void SetClipChainForContainingBlockDescendants(
+    const DisplayItemClipChain* aClipChain)
   {
     mClipChainContainingBlockDescendants = aClipChain;
     InvalidateCurrentCombinedClipChain(aClipChain ? aClipChain->mASR : nullptr);
   }
 
   /**
    * Intersects the given clip rect (with optional aRadii) with the current
    * mClipContainingBlockDescendants and sets mClipContainingBlockDescendants to
@@ -92,87 +97,88 @@ private:
                               const nscoord* aRadii,
                               DisplayItemClipChain& aClipChainOnStack);
   void ClipContentDescendants(nsDisplayListBuilder* aBuilder,
                               const nsRect& aRect,
                               const nsRect& aRoundedRect,
                               const nscoord* aRadii,
                               DisplayItemClipChain& aClipChainOnStack);
 
-  void InvalidateCurrentCombinedClipChain(const ActiveScrolledRoot* aInvalidateUpTo);
+  void InvalidateCurrentCombinedClipChain(
+    const ActiveScrolledRoot* aInvalidateUpTo);
 
   /**
    * Clips containing-block descendants to the frame's content-box,
    * taking border-radius into account.
    * If aFlags contains ASSUME_DRAWING_RESTRICTED_TO_CONTENT_RECT then
    * we assume display items will not draw outside the content rect, so
    * clipping is only required if there is a border-radius. This is an
    * optimization to reduce the amount of clipping required.
    */
-  void ClipContainingBlockDescendantsToContentBox(nsDisplayListBuilder* aBuilder,
-                                                  nsIFrame* aFrame,
-                                                  DisplayItemClipChain& aClipChainOnStack,
-                                                  uint32_t aFlags);
+  void ClipContainingBlockDescendantsToContentBox(
+    nsDisplayListBuilder* aBuilder,
+    nsIFrame* aFrame,
+    DisplayItemClipChain& aClipChainOnStack,
+    uint32_t aFlags);
 
   /**
    * All content descendants (i.e. following placeholder frames to their
-   * out-of-flows if necessary) should be clipped by mClipChainContentDescendants.
-   * Null if no clipping applies.
+   * out-of-flows if necessary) should be clipped by
+   * mClipChainContentDescendants. Null if no clipping applies.
    */
   const DisplayItemClipChain* mClipChainContentDescendants;
   /**
    * All containing-block descendants (i.e. frame descendants), including
    * display items for the current frame, should be clipped by
    * mClipChainContainingBlockDescendants.
    * Null if no clipping applies.
    */
   const DisplayItemClipChain* mClipChainContainingBlockDescendants;
   /**
    * The intersection of mClipChainContentDescendants and
    * mClipChainContainingBlockDescendants.
    * Allocated in the nsDisplayListBuilder arena. Null if none has been
-   * allocated or both mClipChainContentDescendants and mClipChainContainingBlockDescendants
-   * are null.
+   * allocated or both mClipChainContentDescendants and
+   * mClipChainContainingBlockDescendants are null.
    */
   const DisplayItemClipChain* mCurrentCombinedClipChain;
   bool mCurrentCombinedClipChainIsValid;
 };
 
 /**
  * A class to automatically save and restore the current clip state. Also
  * offers methods for modifying the clip state. Only one modification is allowed
  * to be in scope at a time using one of these objects; multiple modifications
  * require nested objects. The interface is written this way to prevent
  * dangling pointers to DisplayItemClips.
  */
-class DisplayListClipState::AutoSaveRestore {
+class DisplayListClipState::AutoSaveRestore
+{
 public:
   explicit AutoSaveRestore(nsDisplayListBuilder* aBuilder);
   void Restore()
   {
     mState = mSavedState;
 #ifdef DEBUG
     mRestored = true;
 #endif
   }
-  ~AutoSaveRestore()
-  {
-    Restore();
-  }
+  ~AutoSaveRestore() { Restore(); }
 
   void Clear()
   {
     NS_ASSERTION(!mRestored, "Already restored!");
     mState.Clear();
 #ifdef DEBUG
     mClipUsed = false;
 #endif
   }
 
-  void SetClipChainForContainingBlockDescendants(const DisplayItemClipChain* aClipChain)
+  void SetClipChainForContainingBlockDescendants(
+    const DisplayItemClipChain* aClipChain)
   {
     mState.SetClipChainForContainingBlockDescendants(aClipChain);
   }
 
   /**
    * Intersects the given clip rect (with optional aRadii) with the current
    * mClipContainingBlockDescendants and sets mClipContainingBlockDescendants to
    * the result, stored in aClipOnStack.
@@ -203,92 +209,101 @@ public:
                               const nsRect& aRoundedRect,
                               const nscoord* aRadii = nullptr)
   {
     NS_ASSERTION(!mRestored, "Already restored!");
     NS_ASSERTION(!mClipUsed, "mClip already used");
 #ifdef DEBUG
     mClipUsed = true;
 #endif
-    mState.ClipContentDescendants(mBuilder, aRect, aRoundedRect, aRadii, mClipChain);
+    mState.ClipContentDescendants(
+      mBuilder, aRect, aRoundedRect, aRadii, mClipChain);
   }
 
   /**
    * Clips containing-block descendants to the frame's content-box,
    * taking border-radius into account.
    * If aFlags contains ASSUME_DRAWING_RESTRICTED_TO_CONTENT_RECT then
    * we assume display items will not draw outside the content rect, so
    * clipping is only required if there is a border-radius. This is an
    * optimization to reduce the amount of clipping required.
    */
-  void ClipContainingBlockDescendantsToContentBox(nsDisplayListBuilder* aBuilder,
-                                                  nsIFrame* aFrame,
-                                                  uint32_t aFlags = 0)
+  void ClipContainingBlockDescendantsToContentBox(
+    nsDisplayListBuilder* aBuilder,
+    nsIFrame* aFrame,
+    uint32_t aFlags = 0)
   {
     NS_ASSERTION(!mRestored, "Already restored!");
     NS_ASSERTION(!mClipUsed, "mClip already used");
 #ifdef DEBUG
     mClipUsed = true;
 #endif
-    mState.ClipContainingBlockDescendantsToContentBox(aBuilder, aFrame, mClipChain, aFlags);
+    mState.ClipContainingBlockDescendantsToContentBox(
+      aBuilder, aFrame, mClipChain, aFlags);
   }
 
 protected:
   nsDisplayListBuilder* mBuilder;
   DisplayListClipState& mState;
   DisplayListClipState mSavedState;
   DisplayItemClipChain mClipChain;
 #ifdef DEBUG
   bool mClipUsed;
   bool mRestored;
 #endif
 };
 
-class DisplayListClipState::AutoClipContainingBlockDescendantsToContentBox : public AutoSaveRestore {
+class DisplayListClipState::AutoClipContainingBlockDescendantsToContentBox
+  : public AutoSaveRestore
+{
 public:
   AutoClipContainingBlockDescendantsToContentBox(nsDisplayListBuilder* aBuilder,
                                                  nsIFrame* aFrame,
                                                  uint32_t aFlags = 0)
     : AutoSaveRestore(aBuilder)
   {
 #ifdef DEBUG
     mClipUsed = true;
 #endif
-    mState.ClipContainingBlockDescendantsToContentBox(aBuilder, aFrame, mClipChain, aFlags);
+    mState.ClipContainingBlockDescendantsToContentBox(
+      aBuilder, aFrame, mClipChain, aFlags);
   }
 };
 
 /**
  * Do not use this outside of nsFrame::BuildDisplayListForChild, use
  * multiple AutoSaveRestores instead. We provide this class just to ensure
  * BuildDisplayListForChild is as efficient as possible.
  */
-class DisplayListClipState::AutoClipMultiple : public AutoSaveRestore {
+class DisplayListClipState::AutoClipMultiple : public AutoSaveRestore
+{
 public:
   explicit AutoClipMultiple(nsDisplayListBuilder* aBuilder)
     : AutoSaveRestore(aBuilder)
 #ifdef DEBUG
     , mExtraClipUsed(false)
 #endif
-  {}
+  {
+  }
 
   /**
    * Intersects the given clip rect (with optional aRadii) with the current
    * mClipContainingBlockDescendants and sets mClipContainingBlockDescendants to
    * the result, stored in aClipOnStack.
    */
   void ClipContainingBlockDescendantsExtra(const nsRect& aRect,
                                            const nscoord* aRadii)
   {
     NS_ASSERTION(!mRestored, "Already restored!");
     NS_ASSERTION(!mExtraClipUsed, "mExtraClip already used");
 #ifdef DEBUG
     mExtraClipUsed = true;
 #endif
-    mState.ClipContainingBlockDescendants(mBuilder, aRect, aRadii, mExtraClipChain);
+    mState.ClipContainingBlockDescendants(
+      mBuilder, aRect, aRadii, mExtraClipChain);
   }
 
 protected:
   DisplayItemClipChain mExtraClipChain;
 #ifdef DEBUG
   bool mExtraClipUsed;
 #endif
 };
--- a/layout/painting/DottedCornerFinder.cpp
+++ b/layout/painting/DottedCornerFinder.cpp
@@ -27,66 +27,79 @@ PointRotateCCW90(const Point& aP)
 }
 
 struct BestOverlap
 {
   Float overlap;
   size_t count;
 
   BestOverlap()
-   : overlap(0.0f), count(0)
-  {}
+    : overlap(0.0f)
+    , count(0)
+  {
+  }
 
   BestOverlap(Float aOverlap, size_t aCount)
-   : overlap(aOverlap), count(aCount)
-  {}
+    : overlap(aOverlap)
+    , count(aCount)
+  {
+  }
 };
 
 static const size_t DottedCornerCacheSize = 256;
 nsDataHashtable<FourFloatsHashKey, BestOverlap> DottedCornerCache;
 
 DottedCornerFinder::DottedCornerFinder(const Bezier& aOuterBezier,
                                        const Bezier& aInnerBezier,
                                        Corner aCorner,
                                        Float aBorderRadiusX,
                                        Float aBorderRadiusY,
-                                       const Point& aC0, Float aR0,
-                                       const Point& aCn, Float aRn,
+                                       const Point& aC0,
+                                       Float aR0,
+                                       const Point& aCn,
+                                       Float aRn,
                                        const Size& aCornerDim)
- : mOuterBezier(aOuterBezier),
-   mInnerBezier(aInnerBezier),
-   mCorner(aCorner),
-   mNormalSign((aCorner == C_TL || aCorner == C_BR) ? -1.0f : 1.0f),
-   mC0(aC0), mCn(aCn),
-   mR0(aR0), mRn(aRn), mMaxR(std::max(aR0, aRn)),
-   mCenterCurveOrigin(mC0.x, mCn.y), mCenterCurveR(0.0),
-   mInnerCurveOrigin(mInnerBezier.mPoints[0].x, mInnerBezier.mPoints[3].y),
-   mBestOverlap(0.0f),
-   mHasZeroBorderWidth(false), mHasMore(true),
-   mMaxCount(aCornerDim.width + aCornerDim.height),
-   mType(OTHER),
-   mI(0), mCount(0)
+  : mOuterBezier(aOuterBezier)
+  , mInnerBezier(aInnerBezier)
+  , mCorner(aCorner)
+  , mNormalSign((aCorner == C_TL || aCorner == C_BR) ? -1.0f : 1.0f)
+  , mC0(aC0)
+  , mCn(aCn)
+  , mR0(aR0)
+  , mRn(aRn)
+  , mMaxR(std::max(aR0, aRn))
+  , mCenterCurveOrigin(mC0.x, mCn.y)
+  , mCenterCurveR(0.0)
+  , mInnerCurveOrigin(mInnerBezier.mPoints[0].x, mInnerBezier.mPoints[3].y)
+  , mBestOverlap(0.0f)
+  , mHasZeroBorderWidth(false)
+  , mHasMore(true)
+  , mMaxCount(aCornerDim.width + aCornerDim.height)
+  , mType(OTHER)
+  , mI(0)
+  , mCount(0)
 {
   NS_ASSERTION(mR0 > 0.0f || mRn > 0.0f,
                "At least one side should have non-zero radius.");
 
   mInnerWidth = fabs(mInnerBezier.mPoints[0].x - mInnerBezier.mPoints[3].x);
   mInnerHeight = fabs(mInnerBezier.mPoints[0].y - mInnerBezier.mPoints[3].y);
 
   DetermineType(aBorderRadiusX, aBorderRadiusY);
 
   Reset();
 }
 
 static bool
-IsSingleCurve(Float aMinR, Float aMaxR,
-              Float aMinBorderRadius, Float aMaxBorderRadius)
+IsSingleCurve(Float aMinR,
+              Float aMaxR,
+              Float aMinBorderRadius,
+              Float aMaxBorderRadius)
 {
-  return aMinR > 0.0f &&
-         aMinBorderRadius > aMaxR * 4.0f &&
+  return aMinR > 0.0f && aMinBorderRadius > aMaxR * 4.0f &&
          aMinBorderRadius / aMaxBorderRadius > 0.5f;
 }
 
 void
 DottedCornerFinder::DetermineType(Float aBorderRadiusX, Float aBorderRadiusY)
 {
   // Calculate parameters for the center curve before swap.
   Float centerCurveWidth = fabs(mC0.x - mCn.x);
@@ -116,18 +129,18 @@ DottedCornerFinder::DetermineType(Float 
       Float borderLength;
       if (minBorderRadius == maxBorderRadius) {
         mType = PERFECT;
         borderLength = M_PI * centerCurveHeight / 2.0f;
 
         mCenterCurveR = centerCurveWidth;
       } else {
         mType = SINGLE_CURVE_AND_RADIUS;
-        borderLength = GetQuarterEllipticArcLength(centerCurveWidth,
-                                                   centerCurveHeight);
+        borderLength =
+          GetQuarterEllipticArcLength(centerCurveWidth, centerCurveHeight);
       }
 
       Float diameter = mR0 * 2.0f;
       size_t count = round(borderLength / diameter);
       if (count % 2) {
         count++;
       }
       mCount = count / 2 - 1;
@@ -136,34 +149,32 @@ DottedCornerFinder::DetermineType(Float 
       }
     } else {
       mType = SINGLE_CURVE;
     }
   }
 
   if (mType == SINGLE_CURVE_AND_RADIUS || mType == SINGLE_CURVE) {
     Size cornerSize(centerCurveWidth, centerCurveHeight);
-    GetBezierPointsForCorner(&mCenterBezier, mCorner,
-                             cornerPoint, cornerSize);
+    GetBezierPointsForCorner(&mCenterBezier, mCorner, cornerPoint, cornerSize);
     if (swapped) {
       Swap(mCenterBezier.mPoints[0], mCenterBezier.mPoints[3]);
       Swap(mCenterBezier.mPoints[1], mCenterBezier.mPoints[2]);
     }
   }
 
   if (minR == 0.0f) {
     mHasZeroBorderWidth = true;
   }
 
   if ((mType == SINGLE_CURVE || mType == OTHER) && !mHasZeroBorderWidth) {
     FindBestOverlap(minR, minBorderRadius, maxBorderRadius);
   }
 }
 
-
 bool
 DottedCornerFinder::HasMore(void) const
 {
   if (mHasZeroBorderWidth) {
     return mI < mMaxCount && mHasMore;
   }
 
   return mI < mCount;
@@ -205,19 +216,21 @@ DottedCornerFinder::Reset(void)
 {
   mLastC = mC0;
   mLastR = mR0;
   mLastT = 0.0f;
   mHasMore = true;
 }
 
 void
-DottedCornerFinder::FindPointAndRadius(Point& C, Float& r,
+DottedCornerFinder::FindPointAndRadius(Point& C,
+                                       Float& r,
                                        const Point& innerTangent,
-                                       const Point& normal, Float t)
+                                       const Point& normal,
+                                       Float t)
 {
   // Find radius for the given tangent point on the inner curve such that the
   // circle is also tangent to the outer curve.
 
   NS_ASSERTION(mType == OTHER, "Wrong mType");
 
   Float lower = 0.0f;
   Float upper = mMaxR;
@@ -287,18 +300,18 @@ DottedCornerFinder::FindNext(Float overl
         // Basically this shouldn't happen.
         // If differential is 0, we cannot calculate tangent circle,
         // skip this point.
         t = (t + upper) / 2.0f;
         continue;
       }
 
       Point normal = PointRotateCCW90(Diff / DiffLength) * (-mNormalSign);
-      r = CalculateDistanceToEllipticArc(C, normal, mInnerCurveOrigin,
-                                         mInnerWidth, mInnerHeight);
+      r = CalculateDistanceToEllipticArc(
+        C, normal, mInnerCurveOrigin, mInnerWidth, mInnerHeight);
 
       // Check overlap along arc.
       circlesDist = GetBezierLength(mCenterBezier, mLastT, t);
       expectedDist = (r + mLastR) * factor;
       if (circlesDist < expectedDist - DIST_MARGIN) {
         lower = t;
       } else if (circlesDist > expectedDist + DIST_MARGIN) {
         upper = t;
@@ -374,24 +387,24 @@ DottedCornerFinder::FindNext(Float overl
   if (expectedDist == 0.0f) {
     return 0.0f;
   }
 
   return 1.0f - circlesDist * factor / expectedDist;
 }
 
 void
-DottedCornerFinder::FindBestOverlap(Float aMinR, Float aMinBorderRadius,
+DottedCornerFinder::FindBestOverlap(Float aMinR,
+                                    Float aMinBorderRadius,
                                     Float aMaxBorderRadius)
 {
   // If overlap is not calculateable, find it with binary search,
   // such that there exists i that C_i == C_n with the given overlap.
 
-  FourFloats key(aMinR, mMaxR,
-                 aMinBorderRadius, aMaxBorderRadius);
+  FourFloats key(aMinR, mMaxR, aMinBorderRadius, aMaxBorderRadius);
   BestOverlap best;
   if (DottedCornerCache.Get(key, &best)) {
     mCount = best.count;
     mBestOverlap = best.overlap;
     return;
   }
 
   Float lower = 0.0f;
--- a/layout/painting/DottedCornerFinder.h
+++ b/layout/painting/DottedCornerFinder.h
@@ -52,17 +52,18 @@ class DottedCornerFinder
 public:
   struct Result
   {
     // Center point of dot and its radius.
     Point C;
     Float r;
 
     Result(const Point& aC, Float aR)
-     : C(aC), r(aR)
+      : C(aC)
+      , r(aR)
     {
       MOZ_ASSERT(aR >= 0);
     }
   };
 
   //                        aBorderRadiusX
   //                       aCornerDim.width
   //                     |<----------------->|
@@ -111,20 +112,25 @@ public:
   //                   |                  |                   |
   //                   |                  |                   |
   //                   |                  |                   |
   //                   v                  |        aCn        |
   //                   -------------------+---------+---------+
   //                                      |         |
   //                                      |<------->|
   //                                          aRn
-  DottedCornerFinder(const Bezier& aOuterBezier, const Bezier& aInnerBezier,
+  DottedCornerFinder(const Bezier& aOuterBezier,
+                     const Bezier& aInnerBezier,
                      mozilla::Corner aCorner,
-                     Float aBorderRadiusX, Float aBorderRadiusY,
-                     const Point& aC0, Float aR0, const Point& aCn, Float aRn,
+                     Float aBorderRadiusX,
+                     Float aBorderRadiusY,
+                     const Point& aC0,
+                     Float aR0,
+                     const Point& aCn,
+                     Float aRn,
                      const Size& aCornerDim);
 
   bool HasMore(void) const;
   Result Next(void);
 
 private:
   static const size_t MAX_LOOP = 32;
 
@@ -255,17 +261,18 @@ private:
   // If one of border-widths is 0, do not calculate overlap, and draw circles
   // until it reaches the other side or exceeds mMaxCount.
   bool mHasZeroBorderWidth;
   bool mHasMore;
 
   // The maximum number of filled/unfilled circles.
   size_t mMaxCount;
 
-  enum {
+  enum
+  {
     //                      radius.width
     //                 |<----------------->|
     //                 |                   |
     //               --+-------------___---+----
     //               ^ |         __--     #|#  ^
     //               | |       _-        ##|## |
     //               | |     /           ##+## | top-width
     //               | |   /             ##|## |
@@ -413,27 +420,32 @@ private:
   // Determine mType from parameters.
   void DetermineType(Float aBorderRadiusX, Float aBorderRadiusY);
 
   // Reset calculation.
   void Reset(void);
 
   // Find radius for the given tangent point on the inner curve such that the
   // circle is also tangent to the outer curve.
-  void FindPointAndRadius(Point& C, Float& r, const Point& innerTangent,
-                          const Point& normal, Float t);
+  void FindPointAndRadius(Point& C,
+                          Float& r,
+                          const Point& innerTangent,
+                          const Point& normal,
+                          Float t);
 
   // Find next dot.
   Float FindNext(Float overlap);
 
   // Find mBestOverlap for parameters.
   void FindBestOverlap(Float aMinR,
-                       Float aMinBorderRadius, Float aMaxBorderRadius);
+                       Float aMinBorderRadius,
+                       Float aMaxBorderRadius);
 
   // Fill corner with dots with given overlap, and return the number of dots
   // and last two dots's overlap.
   bool GetCountAndLastOverlap(Float aOverlap,
-                              size_t* aCount, Float* aActualOverlap);
+                              size_t* aCount,
+                              Float* aActualOverlap);
 };
 
 } // namespace mozilla
 
 #endif /* mozilla_DottedCornerFinder_h_ */
--- a/layout/painting/FrameLayerBuilder.cpp
+++ b/layout/painting/FrameLayerBuilder.cpp
@@ -56,17 +56,18 @@
 
 #include <algorithm>
 #include <functional>
 #include <deque>
 
 using namespace mozilla::layers;
 using namespace mozilla::gfx;
 
-// PaintedLayerData::mAssignedDisplayItems is a std::vector, which is non-memmovable
+// PaintedLayerData::mAssignedDisplayItems is a std::vector, which is
+// non-memmovable
 DECLARE_USE_COPY_CONSTRUCTORS(mozilla::PaintedLayerData);
 
 namespace mozilla {
 
 class PaintedDisplayItemLayerUserData;
 
 static nsTHashtable<nsPtrHashKey<DisplayItemData>>* sAliveDisplayItemDatas;
 
@@ -109,31 +110,33 @@ uint8_t gMaskLayerUserData;
  * data key for mask layers of css masking managed by FrameLayerBuilder.
  * The user data is a CSSMaskLayerUserData.
  */
 uint8_t gCSSMaskLayerUserData;
 
 // a global cache of image containers used for mask layers
 static MaskLayerImageCache* gMaskLayerImageCache = nullptr;
 
-static inline MaskLayerImageCache* GetMaskLayerImageCache()
+static inline MaskLayerImageCache*
+GetMaskLayerImageCache()
 {
   if (!gMaskLayerImageCache) {
     gMaskLayerImageCache = new MaskLayerImageCache();
   }
 
   return gMaskLayerImageCache;
 }
 
-struct DisplayItemEntry {
-  DisplayItemEntry(nsDisplayItem* aItem,
-                   DisplayItemEntryType aType)
+struct DisplayItemEntry
+{
+  DisplayItemEntry(nsDisplayItem* aItem, DisplayItemEntryType aType)
     : mItem(aItem)
     , mType(aType)
-  {}
+  {
+  }
 
   nsDisplayItem* mItem;
   DisplayItemEntryType mType;
 };
 
 /**
  * Returns true if the given |aType| is an effect start marker.
  */
@@ -150,45 +153,45 @@ IsEffectStartMarker(DisplayItemEntryType
  */
 static bool
 IsEffectEndMarker(DisplayItemEntryType aType)
 {
   return aType == DisplayItemEntryType::POP_OPACITY ||
          aType == DisplayItemEntryType::POP_TRANSFORM;
 }
 
-enum class MarkerType {
+enum class MarkerType
+{
   StartMarker,
   EndMarker
 };
 
 /**
  * Adds the effect marker to |aMarkers| based on the type of |aItem| and whether
  * |markerType| is a start or end marker.
  */
 template<MarkerType markerType>
 static bool
-AddMarkerIfNeeded(nsDisplayItem* aItem,
-                  std::deque<DisplayItemEntry>& aMarkers)
+AddMarkerIfNeeded(nsDisplayItem* aItem, std::deque<DisplayItemEntry>& aMarkers)
 {
   const DisplayItemType type = aItem->GetType();
   if (type != DisplayItemType::TYPE_OPACITY &&
       type != DisplayItemType::TYPE_TRANSFORM) {
     return false;
   }
 
   DisplayItemEntryType marker;
 
 // Just a fancy way to avoid writing two separate functions to select between
 // PUSH and POP markers. This is done during compile time based on |markerType|.
-#define GET_MARKER(start_marker, end_marker)\
-std::conditional<markerType == MarkerType::StartMarker,\
-                 std::integral_constant<DisplayItemEntryType, start_marker>,\
-                 std::integral_constant<DisplayItemEntryType, end_marker>\
-                >::type::value;
+#define GET_MARKER(start_marker, end_marker)                                   \
+  std::conditional<                                                            \
+    markerType == MarkerType::StartMarker,                                     \
+    std::integral_constant<DisplayItemEntryType, start_marker>,                \
+    std::integral_constant<DisplayItemEntryType, end_marker>>::type::value;
 
   switch (type) {
     case DisplayItemType::TYPE_OPACITY:
       marker = GET_MARKER(DisplayItemEntryType::PUSH_OPACITY,
                           DisplayItemEntryType::POP_OPACITY);
       break;
     case DisplayItemType::TYPE_TRANSFORM:
       marker = GET_MARKER(DisplayItemEntryType::PUSH_TRANSFORM,
@@ -221,30 +224,27 @@ public:
   {
     if (!mMarkers.empty()) {
       DisplayItemEntry entry = mMarkers.front();
       mMarkers.pop_front();
       return entry;
     }
 
     nsDisplayItem* next = GetNext();
-    return DisplayItemEntry { next, DisplayItemEntryType::ITEM };
+    return DisplayItemEntry{ next, DisplayItemEntryType::ITEM };
   }
 
   nsDisplayItem* GetNext();
 
   bool HasNext() const
   {
     return FlattenedDisplayItemIterator::HasNext() || !mMarkers.empty();
   }
 
-  nsDisplayItem* PeekNext()
-  {
-    return mNext;
-  }
+  nsDisplayItem* PeekNext() { return mNext; }
 
 private:
   bool ShouldFlattenNextItem() override;
 
   void StartNested(nsDisplayItem* aItem) override
   {
     if (!mStoreMarker) {
       return;
@@ -272,18 +272,20 @@ private:
   bool NextItemWantsInactiveLayer();
 
   std::deque<DisplayItemEntry> mMarkers;
   AutoTArray<nsDisplayItem*, 4> mActiveMarkers;
   ContainerState* mState;
   bool mStoreMarker;
 };
 
-DisplayItemData::DisplayItemData(LayerManagerData* aParent, uint32_t aKey,
-                                 Layer* aLayer, nsIFrame* aFrame)
+DisplayItemData::DisplayItemData(LayerManagerData* aParent,
+                                 uint32_t aKey,
+                                 Layer* aLayer,
+                                 nsIFrame* aFrame)
 
   : mRefCnt(0)
   , mParent(aParent)
   , mLayer(aLayer)
   , mDisplayItemKey(aKey)
   , mItem(nullptr)
   , mUsed(true)
   , mIsInvalid(false)
@@ -347,28 +349,33 @@ DisplayItemData::EndUpdate(nsAutoPtr<nsD
   }
   mClip = mItem->GetClip();
   mChangedFrameInvalidations.SetEmpty();
 
   EndUpdate();
 }
 
 void
-DisplayItemData::BeginUpdate(Layer* aLayer, LayerState aState,
+DisplayItemData::BeginUpdate(Layer* aLayer,
+                             LayerState aState,
                              bool aFirstUpdate,
                              nsDisplayItem* aItem /* = nullptr */)
 {
-  BeginUpdate(aLayer, aState, aItem,
+  BeginUpdate(aLayer,
+              aState,
+              aItem,
               (aItem && !aFirstUpdate) ? aItem->IsReused() : false,
               aItem ? aItem->HasMergedFrames() : false);
 }
 
 void
-DisplayItemData::BeginUpdate(Layer* aLayer, LayerState aState,
-                             nsDisplayItem* aItem, bool aIsReused,
+DisplayItemData::BeginUpdate(Layer* aLayer,
+                             LayerState aState,
+                             nsDisplayItem* aItem,
+                             bool aIsReused,
                              bool aIsMerged)
 {
   MOZ_RELEASE_ASSERT(mLayer);
   MOZ_RELEASE_ASSERT(aLayer);
   mLayer = aLayer;
   mOptLayer = nullptr;
   mInactiveManager = nullptr;
   mLayerState = aState;
@@ -396,17 +403,17 @@ DisplayItemData::BeginUpdate(Layer* aLay
   // since we have to modify userdata each time
   AutoTArray<nsIFrame*, 4> copy(mFrameList);
   if (!copy.RemoveElement(aItem->Frame())) {
     AddFrame(aItem->Frame());
     mChangedFrameInvalidations.Or(mChangedFrameInvalidations,
                                   aItem->Frame()->GetVisualOverflowRect());
   }
 
-  AutoTArray<nsIFrame*,4> mergedFrames;
+  AutoTArray<nsIFrame*, 4> mergedFrames;
   aItem->GetMergedFrames(&mergedFrames);
   for (uint32_t i = 0; i < mergedFrames.Length(); ++i) {
     if (!copy.RemoveElement(mergedFrames[i])) {
       AddFrame(mergedFrames[i]);
       mChangedFrameInvalidations.Or(mChangedFrameInvalidations,
                                     mergedFrames[i]->GetVisualOverflowRect());
     }
   }
@@ -434,137 +441,149 @@ DisplayItemData::~DisplayItemData()
       continue;
     }
 
     SmallPointerArray<DisplayItemData>& array = frame->DisplayItemData();
     array.RemoveElement(this);
   }
 
   MOZ_RELEASE_ASSERT(sAliveDisplayItemDatas);
-  nsPtrHashKey<mozilla::DisplayItemData>* entry
-    = sAliveDisplayItemDatas->GetEntry(this);
+  nsPtrHashKey<mozilla::DisplayItemData>* entry =
+    sAliveDisplayItemDatas->GetEntry(this);
   MOZ_RELEASE_ASSERT(entry);
 
   sAliveDisplayItemDatas->RemoveEntry(entry);
 
   if (sAliveDisplayItemDatas->Count() == 0) {
     delete sAliveDisplayItemDatas;
     sAliveDisplayItemDatas = nullptr;
   }
 }
 
 void
 DisplayItemData::ClearAnimationCompositorState()
 {
-  if (mDisplayItemKey != static_cast<uint32_t>(DisplayItemType::TYPE_TRANSFORM) &&
+  if (mDisplayItemKey !=
+        static_cast<uint32_t>(DisplayItemType::TYPE_TRANSFORM) &&
       mDisplayItemKey != static_cast<uint32_t>(DisplayItemType::TYPE_OPACITY)) {
     return;
   }
 
   for (nsIFrame* frame : mFrameList) {
-    nsCSSPropertyID prop = mDisplayItemKey == static_cast<uint32_t>(DisplayItemType::TYPE_TRANSFORM) ?
-      eCSSProperty_transform : eCSSProperty_opacity;
+    nsCSSPropertyID prop =
+      mDisplayItemKey == static_cast<uint32_t>(DisplayItemType::TYPE_TRANSFORM)
+        ? eCSSProperty_transform
+        : eCSSProperty_opacity;
     EffectCompositor::ClearIsRunningOnCompositor(frame, prop);
   }
 }
 
 const nsRegion&
 DisplayItemData::GetChangedFrameInvalidations()
 {
   return mChangedFrameInvalidations;
 }
 
 DisplayItemData*
 DisplayItemData::AssertDisplayItemData(DisplayItemData* aData)
 {
   MOZ_RELEASE_ASSERT(aData);
-  MOZ_RELEASE_ASSERT(sAliveDisplayItemDatas && sAliveDisplayItemDatas->Contains(aData));
+  MOZ_RELEASE_ASSERT(sAliveDisplayItemDatas &&
+                     sAliveDisplayItemDatas->Contains(aData));
   MOZ_RELEASE_ASSERT(aData->mLayer);
   return aData;
 }
 
 /**
  * This is the userdata we associate with a layer manager.
  */
-class LayerManagerData : public LayerUserData {
+class LayerManagerData : public LayerUserData
+{
 public:
-  explicit LayerManagerData(LayerManager *aManager)
+  explicit LayerManagerData(LayerManager* aManager)
     : mLayerManager(aManager)
 #ifdef DEBUG_DISPLAY_ITEM_DATA
     , mParent(nullptr)
 #endif
     , mInvalidateAllLayers(false)
   {
     MOZ_COUNT_CTOR(LayerManagerData);
   }
-  ~LayerManagerData() {
-    MOZ_COUNT_DTOR(LayerManagerData);
-  }
+  ~LayerManagerData() override { MOZ_COUNT_DTOR(LayerManagerData); }
 
 #ifdef DEBUG_DISPLAY_ITEM_DATA
-  void Dump(const char *aPrefix = "") {
+  void Dump(const char* aPrefix = "")
+  {
     printf_stderr("%sLayerManagerData %p\n", aPrefix, this);
 
     for (auto& data : mDisplayItems) {
       nsAutoCString prefix;
       prefix += aPrefix;
       prefix += "  ";
 
       const char* layerState;
       switch (data->mLayerState) {
-      case LAYER_NONE:
-        layerState = "LAYER_NONE"; break;
-      case LAYER_INACTIVE:
-        layerState = "LAYER_INACTIVE"; break;
-      case LAYER_ACTIVE:
-        layerState = "LAYER_ACTIVE"; break;
-      case LAYER_ACTIVE_FORCE:
-        layerState = "LAYER_ACTIVE_FORCE"; break;
-      case LAYER_ACTIVE_EMPTY:
-        layerState = "LAYER_ACTIVE_EMPTY"; break;
-      case LAYER_SVG_EFFECTS:
-        layerState = "LAYER_SVG_EFFECTS"; break;
+        case LAYER_NONE:
+          layerState = "LAYER_NONE";
+          break;
+        case LAYER_INACTIVE:
+          layerState = "LAYER_INACTIVE";
+          break;
+        case LAYER_ACTIVE:
+          layerState = "LAYER_ACTIVE";
+          break;
+        case LAYER_ACTIVE_FORCE:
+          layerState = "LAYER_ACTIVE_FORCE";
+          break;
+        case LAYER_ACTIVE_EMPTY:
+          layerState = "LAYER_ACTIVE_EMPTY";
+          break;
+        case LAYER_SVG_EFFECTS:
+          layerState = "LAYER_SVG_EFFECTS";
+          break;
       }
       uint32_t mask = (1 << TYPE_BITS) - 1;
 
       nsAutoCString str;
       str += prefix;
       str += nsPrintfCString("Frame %p ", data->mFrameList[0]);
-      str += nsDisplayItem::DisplayItemTypeName(static_cast<nsDisplayItem::Type>(data->mDisplayItemKey & mask));
+      str += nsDisplayItem::DisplayItemTypeName(
+        static_cast<nsDisplayItem::Type>(data->mDisplayItemKey & mask));
       if ((data->mDisplayItemKey >> TYPE_BITS)) {
         str += nsPrintfCString("(%i)", data->mDisplayItemKey >> TYPE_BITS);
       }
       str += nsPrintfCString(", %s, Layer %p", layerState, data->mLayer.get());
       if (data->mOptLayer) {
         str += nsPrintfCString(", OptLayer %p", data->mOptLayer.get());
       }
       if (data->mInactiveManager) {
-        str += nsPrintfCString(", InactiveLayerManager %p", data->mInactiveManager.get());
+        str += nsPrintfCString(", InactiveLayerManager %p",
+                               data->mInactiveManager.get());
       }
       str += "\n";
 
       printf_stderr("%s", str.get());
 
       if (data->mInactiveManager) {
         prefix += "  ";
         printf_stderr("%sDumping inactive layer info:\n", prefix.get());
-        LayerManagerData* lmd = static_cast<LayerManagerData*>
-          (data->mInactiveManager->GetUserData(&gLayerManagerUserData));
+        LayerManagerData* lmd = static_cast<LayerManagerData*>(
+          data->mInactiveManager->GetUserData(&gLayerManagerUserData));
         lmd->Dump(prefix.get());
       }
     }
   }
 #endif
 
   /**
    * Tracks which frames have layers associated with them.
    */
-  LayerManager *mLayerManager;
+  LayerManager* mLayerManager;
 #ifdef DEBUG_DISPLAY_ITEM_DATA
-  LayerManagerData *mParent;
+  LayerManagerData* mParent;
 #endif
   std::vector<RefPtr<DisplayItemData>> mDisplayItems;
   bool mInvalidateAllLayers;
 };
 
 /* static */ void
 FrameLayerBuilder::DestroyDisplayItemDataFor(nsIFrame* aFrame)
 {
@@ -577,17 +596,18 @@ FrameLayerBuilder::DestroyDisplayItemDat
  * We keep a stack of these to represent the PaintedLayers that are
  * currently available to have display items added to.
  * We use a stack here because as much as possible we want to
  * assign display items to existing PaintedLayers, and to the lowest
  * PaintedLayer in z-order. This reduces the number of layers and
  * makes it more likely a display item will be rendered to an opaque
  * layer, giving us the best chance of getting subpixel AA.
  */
-class PaintedLayerData {
+class PaintedLayerData
+{
 public:
   PaintedLayerData()
     : mAnimatedGeometryRoot(nullptr)
     , mASR(nullptr)
     , mClipChain(nullptr)
     , mReferenceFrame(nullptr)
     , mLayer(nullptr)
     , mSolidColor(NS_RGBA(0, 0, 0, 0))
@@ -601,63 +621,64 @@ public:
     , mShouldPaintOnContentSide(false)
     , mDTCRequiresTargetConfirmation(false)
     , mImage(nullptr)
     , mItemClip(nullptr)
     , mNewChildLayersIndex(-1)
 #ifdef DEBUG
     , mTransformLevel(0)
 #endif
-  {}
-
-  ~PaintedLayerData()
   {
-    MOZ_ASSERT(mTransformLevel == 0);
-  }
+  }
+
+  ~PaintedLayerData() { MOZ_ASSERT(mTransformLevel == 0); }
 
 #ifdef MOZ_DUMP_PAINTING
   /**
    * Keep track of important decisions for debugging.
    */
   nsCString mLog;
 
-  #define FLB_LOG_PAINTED_LAYER_DECISION(pld, ...) \
-          if (gfxPrefs::LayersDumpDecision()) { \
-            pld->mLog.AppendPrintf("\t\t\t\t"); \
-            pld->mLog.AppendPrintf(__VA_ARGS__); \
-          }
+#define FLB_LOG_PAINTED_LAYER_DECISION(pld, ...)                               \
+  if (gfxPrefs::LayersDumpDecision()) {                                        \
+    pld->mLog.AppendPrintf("\t\t\t\t");                                        \
+    pld->mLog.AppendPrintf(__VA_ARGS__);                                       \
+  }
 #else
-  #define FLB_LOG_PAINTED_LAYER_DECISION(...)
+#define FLB_LOG_PAINTED_LAYER_DECISION(...)
 #endif
 
   /**
    * Record that an item has been added to the PaintedLayer, so we
    * need to update our regions.
    * @param aVisibleRect the area of the item that's visible
    * @param aSolidColor if non-null, the visible area of the item is
    * a constant color given by *aSolidColor
    */
   void Accumulate(ContainerState* aState,
                   nsDisplayItem* aItem,
                   const nsIntRect& aVisibleRect,
                   const nsRect& aContentRect,
                   const DisplayItemClip& aClip,
                   LayerState aLayerState,
-                  nsDisplayList *aList,
+                  nsDisplayList* aList,
                   DisplayItemEntryType aType,
                   nsTArray<size_t>& aOpacityIndices,
                   const RefPtr<TransformClipNode>& aTransform);
 
   /**
    * Updates the status of |mTransform| and |aOpacityIndices|, based on |aType|.
    */
   void UpdateEffectStatus(DisplayItemEntryType aType,
                           nsTArray<size_t>& aOpacityIndices);
 
-  AnimatedGeometryRoot* GetAnimatedGeometryRoot() { return mAnimatedGeometryRoot; }
+  AnimatedGeometryRoot* GetAnimatedGeometryRoot()
+  {
+    return mAnimatedGeometryRoot;
+  }
 
   /**
    * A region including the horizontal pan, vertical pan, and no action regions.
    */
   nsRegion CombinedTouchActionRegion();
 
   /**
    * Add the given hit test info to the hit regions for this PaintedLayer.
@@ -672,46 +693,51 @@ public:
    */
   bool CanOptimizeToImageLayer(nsDisplayListBuilder* aBuilder);
 
   /**
    * If this represents only a nsDisplayImage, and the image type supports being
    * optimized to an ImageLayer, returns an ImageContainer for the underlying
    * image if one is available.
    */
-  already_AddRefed<ImageContainer> GetContainerForImageLayer(nsDisplayListBuilder* aBuilder);
+  already_AddRefed<ImageContainer> GetContainerForImageLayer(
+    nsDisplayListBuilder* aBuilder);
 
   bool VisibleAboveRegionIntersects(const nsIntRegion& aRegion) const
-  { return !mVisibleAboveRegion.Intersect(aRegion).IsEmpty(); }
+  {
+    return !mVisibleAboveRegion.Intersect(aRegion).IsEmpty();
+  }
   bool VisibleRegionIntersects(const nsIntRegion& aRegion) const
-  { return !mVisibleRegion.Intersect(aRegion).IsEmpty(); }
+  {
+    return !mVisibleRegion.Intersect(aRegion).IsEmpty();
+  }
 
   /**
    * The region of visible content in the layer, relative to the
    * container layer (which is at the snapped top-left of the display
    * list reference frame).
    */
-  nsIntRegion  mVisibleRegion;
+  nsIntRegion mVisibleRegion;
   /**
    * The region of visible content in the layer that is opaque.
    * Same coordinate system as mVisibleRegion.
    */
-  nsIntRegion  mOpaqueRegion;
+  nsIntRegion mOpaqueRegion;
   /**
    * The definitely-hit region for this PaintedLayer.
    */
-  nsRegion  mHitRegion;
+  nsRegion mHitRegion;
   /**
    * The maybe-hit region for this PaintedLayer.
    */
-  nsRegion  mMaybeHitRegion;
+  nsRegion mMaybeHitRegion;
   /**
    * The dispatch-to-content hit region for this PaintedLayer.
    */
-  nsRegion  mDispatchToContentHitRegion;
+  nsRegion mDispatchToContentHitRegion;
   /**
    * The region for this PaintedLayer that is sensitive to events
    * but disallows panning and zooming. This is an approximation
    * and any deviation from the true region will be part of the
    * mDispatchToContentHitRegion.
    */
   nsRegion mNoActionRegion;
   /**
@@ -759,17 +785,17 @@ public:
    * frame; the latter case is used for background-attachment:fixed content.
    */
   const nsIFrame* mReferenceFrame;
   PaintedLayer* mLayer;
   /**
    * If mIsSolidColorInVisibleRegion is true, this is the color of the visible
    * region.
    */
-  nscolor      mSolidColor;
+  nscolor mSolidColor;
   /**
    * True if every pixel in mVisibleRegion will have color mSolidColor.
    */
   bool mIsSolidColorInVisibleRegion;
   /**
    * True if there is any text visible in the layer that's over
    * transparent pixels in the layer.
    */
@@ -819,18 +845,18 @@ public:
    * convert this to an ImageLayer.
    */
   nsDisplayImageContainer* mImage;
   /**
    * Stores the clip that we need to apply to the image or, if there is no
    * image, a clip for SOME item in the layer. There is no guarantee which
    * item's clip will be stored here and mItemClip should not be used to clip
    * the whole layer - only some part of the clip should be used, as determined
-   * by PaintedDisplayItemLayerUserData::GetCommonClipCount() - which may even be
-   * no part at all.
+   * by PaintedDisplayItemLayerUserData::GetCommonClipCount() - which may even
+   * be no part at all.
    */
   const DisplayItemClip* mItemClip;
   /**
    * Index of this layer in mNewChildLayers.
    */
   int32_t mNewChildLayersIndex;
   /**
    * The region of visible content above the layer and below the
@@ -847,30 +873,32 @@ public:
 #ifdef DEBUG
   /**
    * Tracks the level of transform to ensure balanced PUSH/POP markers.
    */
   int mTransformLevel;
 #endif
 };
 
-struct NewLayerEntry {
+struct NewLayerEntry
+{
   NewLayerEntry()
     : mAnimatedGeometryRoot(nullptr)
     , mASR(nullptr)
     , mClipChain(nullptr)
     , mScrollMetadataASR(nullptr)
     , mLayerContentsVisibleRect(0, 0, -1, -1)
     , mLayerState(LAYER_INACTIVE)
     , mHideAllLayersBelow(false)
     , mOpaqueForAnimatedGeometryRootParent(false)
     , mPropagateComponentAlphaFlattening(true)
     , mUntransformedVisibleRegion(false)
     , mIsFixedToRootScrollFrame(false)
-  {}
+  {
+  }
   // mLayer is null if the previous entry is for a PaintedLayer that hasn't
   // been optimized to some other form (yet).
   RefPtr<Layer> mLayer;
   AnimatedGeometryRoot* mAnimatedGeometryRoot;
   const ActiveScrolledRoot* mASR;
   const DisplayItemClipChain* mClipChain;
   const ActiveScrolledRoot* mScrollMetadataASR;
   // If non-null, this ScrollMetadata is set to the be the first ScrollMetadata
@@ -923,59 +951,70 @@ class PaintedLayerDataTree;
  * (sync or async), and during async animations everything is guaranteed to
  * look correct.
  * The contents of a node's PaintedLayerData stack all share the node's
  * animated geometry root. The child nodes are on top of the PaintedLayerData
  * stack, in z-order, and the clip rects of the child nodes are allowed to
  * intersect with the visible region or visible above region of their parent
  * node's PaintedLayerDatas.
  */
-class PaintedLayerDataNode {
+class PaintedLayerDataNode
+{
 public:
   PaintedLayerDataNode(PaintedLayerDataTree& aTree,
                        PaintedLayerDataNode* aParent,
                        AnimatedGeometryRoot* aAnimatedGeometryRoot);
   ~PaintedLayerDataNode();
 
-  AnimatedGeometryRoot* GetAnimatedGeometryRoot() const { return mAnimatedGeometryRoot; }
+  AnimatedGeometryRoot* GetAnimatedGeometryRoot() const
+  {
+    return mAnimatedGeometryRoot;
+  }
 
   /**
    * Whether this node's contents can potentially intersect aRect.
    * aRect is in our tree's ContainerState's coordinate space.
    */
   bool Intersects(const nsIntRect& aRect) const
-    { return !mHasClip || mClipRect.Intersects(aRect); }
+  {
+    return !mHasClip || mClipRect.Intersects(aRect);
+  }
 
   /**
    * Create a PaintedLayerDataNode for aAnimatedGeometryRoot, add it to our
    * children, and return it.
    */
-  PaintedLayerDataNode* AddChildNodeFor(AnimatedGeometryRoot* aAnimatedGeometryRoot);
+  PaintedLayerDataNode* AddChildNodeFor(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot);
 
   /**
    * Find a PaintedLayerData in our mPaintedLayerDataStack that aItem can be
    * added to. Creates a new PaintedLayerData by calling
    * aNewPaintedLayerCallback if necessary.
    */
   template<typename NewPaintedLayerCallbackType>
-  PaintedLayerData* FindPaintedLayerFor(const nsIntRect& aVisibleRect,
-                                        bool aBackfaceHidden,
-                                        const ActiveScrolledRoot* aASR,
-                                        const DisplayItemClipChain* aClipChain,
-                                        NewPaintedLayerCallbackType aNewPaintedLayerCallback);
+  PaintedLayerData* FindPaintedLayerFor(
+    const nsIntRect& aVisibleRect,
+    bool aBackfaceHidden,
+    const ActiveScrolledRoot* aASR,
+    const DisplayItemClipChain* aClipChain,
+    NewPaintedLayerCallbackType aNewPaintedLayerCallback);
 
   /**
    * Find an opaque background color for aRegion. Pulls a color from the parent
    * geometry root if appropriate, but only if that color is present underneath
    * the whole clip of this node, so that this node's contents can animate or
    * move (possibly async) without having to change the background color.
    * @param aUnderIndex Searching will start in mPaintedLayerDataStack right
    *                    below aUnderIndex.
    */
-  enum { ABOVE_TOP = -1 };
+  enum
+  {
+    ABOVE_TOP = -1
+  };
   nscolor FindOpaqueBackgroundColor(const nsIntRegion& aRegion,
                                     int32_t aUnderIndex = ABOVE_TOP) const;
   /**
    * Same as FindOpaqueBackgroundColor, but only returns a color if absolutely
    * nothing is in between, so that it can be used for a layer that can move
    * anywhere inside our clip.
    */
   nscolor FindOpaqueBackgroundColorCoveringEverything() const;
@@ -1089,24 +1128,26 @@ class ContainerState;
  * finished.
  * The tree's root node is always the root reference frame of the builder. We
  * don't stop at the container state's mContainerAnimatedGeometryRoot because
  * some of our contents can have animated geometry roots that are not
  * descendants of the container's animated geometry root. Every animated
  * geometry root we encounter for our contents needs to have a defined place in
  * the tree.
  */
-class PaintedLayerDataTree {
+class PaintedLayerDataTree
+{
 public:
   PaintedLayerDataTree(ContainerState& aContainerState,
                        nscolor& aBackgroundColor)
     : mContainerState(aContainerState)
     , mContainerUniformBackgroundColor(aBackgroundColor)
     , mForInactiveLayer(false)
-  {}
+  {
+  }
 
   ~PaintedLayerDataTree()
   {
     MOZ_ASSERT(!mRoot);
     MOZ_ASSERT(mNodes.Count() == 0);
   }
 
   void InitializeForInactiveLayer(AnimatedGeometryRoot* aAnimatedGeometryRoot);
@@ -1125,249 +1166,268 @@ public:
                       nscolor* aOutUniformBackgroundColor);
 
   /**
    * Find a PaintedLayerData for aItem. This can either be an existing
    * PaintedLayerData from inside a node in our tree, or a new one that gets
    * created by a call out to aNewPaintedLayerCallback.
    */
   template<typename NewPaintedLayerCallbackType>
-  PaintedLayerData* FindPaintedLayerFor(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                        const ActiveScrolledRoot* aASR,
-                                        const DisplayItemClipChain* aClipChain,
-                                        const nsIntRect& aVisibleRect,
-                                        const bool aBackfaceHidden,
-                                        NewPaintedLayerCallbackType aNewPaintedLayerCallback);
+  PaintedLayerData* FindPaintedLayerFor(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot,
+    const ActiveScrolledRoot* aASR,
+    const DisplayItemClipChain* aClipChain,
+    const nsIntRect& aVisibleRect,
+    const bool aBackfaceHidden,
+    NewPaintedLayerCallbackType aNewPaintedLayerCallback);
 
   /**
    * Finish everything.
    */
   void Finish();
 
   /**
    * Get the parent animated geometry root of aAnimatedGeometryRoot.
    * That's either aAnimatedGeometryRoot's animated geometry root, or, if
    * that's aAnimatedGeometryRoot itself, then it's the animated geometry
    * root for aAnimatedGeometryRoot's cross-doc parent frame.
    */
-  AnimatedGeometryRoot* GetParentAnimatedGeometryRoot(AnimatedGeometryRoot* aAnimatedGeometryRoot);
+  AnimatedGeometryRoot* GetParentAnimatedGeometryRoot(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot);
 
   /**
    * Whether aAnimatedGeometryRoot has an intrinsic clip that doesn't move with
    * respect to aAnimatedGeometryRoot's parent animated geometry root.
    * If aAnimatedGeometryRoot is a scroll frame, this will be the scroll frame's
    * scroll port, otherwise there is no clip.
    * This method doesn't have much to do with PaintedLayerDataTree, but this is
    * where we have easy access to a display list builder, which we use to get
    * the clip rect result into the right coordinate space.
    */
-  bool IsClippedWithRespectToParentAnimatedGeometryRoot(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                                        nsIntRect* aOutClip);
+  bool IsClippedWithRespectToParentAnimatedGeometryRoot(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot,
+    nsIntRect* aOutClip);
 
   /**
    * Called by PaintedLayerDataNode when it is finished, so that we can drop
    * our pointers to it.
    */
   void NodeWasFinished(AnimatedGeometryRoot* aAnimatedGeometryRoot);
 
   nsDisplayListBuilder* Builder() const;
   ContainerState& ContState() const { return mContainerState; }
-  nscolor UniformBackgroundColor() const { return mContainerUniformBackgroundColor; }
+  nscolor UniformBackgroundColor() const
+  {
+    return mContainerUniformBackgroundColor;
+  }
 
 protected:
   /**
    * Finish all nodes that potentially intersect *aRect, where *aRect is a rect
    * that doesn't move with respect to aAnimatedGeometryRoot.
    * If aRect is null, *aRect will be considered infinite.
    */
-  void FinishPotentiallyIntersectingNodes(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                          const nsIntRect* aRect);
+  void FinishPotentiallyIntersectingNodes(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot,
+    const nsIntRect* aRect);
 
   /**
    * Make sure that there is a node for aAnimatedGeometryRoot and all of its
    * ancestor geometry roots. Return the node for aAnimatedGeometryRoot.
    */
-  PaintedLayerDataNode* EnsureNodeFor(AnimatedGeometryRoot* aAnimatedGeometryRoot);
+  PaintedLayerDataNode* EnsureNodeFor(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot);
 
   /**
    * Find an existing node in the tree for an ancestor of aAnimatedGeometryRoot.
    * *aOutAncestorChild will be set to the last ancestor that was encountered
    * in the search up from aAnimatedGeometryRoot; it will be a child animated
    * geometry root of the result, if neither are null.
    */
-  PaintedLayerDataNode*
-    FindNodeForAncestorAnimatedGeometryRoot(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                            AnimatedGeometryRoot** aOutAncestorChild);
+  PaintedLayerDataNode* FindNodeForAncestorAnimatedGeometryRoot(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot,
+    AnimatedGeometryRoot** aOutAncestorChild);
 
   ContainerState& mContainerState;
   Maybe<PaintedLayerDataNode> mRoot;
 
   /**
    * The uniform opaque color from behind this container layer, or
    * NS_RGBA(0,0,0,0) if the background behind this container layer is not
    * uniform and opaque. This color can be pulled into PaintedLayers that are
    * directly above the background.
    */
   nscolor mContainerUniformBackgroundColor;
 
   /**
    * A hash map for quick access the node belonging to a particular animated
    * geometry root.
    */
-  nsDataHashtable<nsPtrHashKey<AnimatedGeometryRoot>, PaintedLayerDataNode*> mNodes;
+  nsDataHashtable<nsPtrHashKey<AnimatedGeometryRoot>, PaintedLayerDataNode*>
+    mNodes;
 
   bool mForInactiveLayer;
 };
 
 /**
  * This is a helper object used to build up the layer children for
  * a ContainerLayer.
  */
-class ContainerState {
+class ContainerState
+{
 public:
   ContainerState(nsDisplayListBuilder* aBuilder,
                  LayerManager* aManager,
                  FrameLayerBuilder* aLayerBuilder,
                  nsIFrame* aContainerFrame,
                  nsDisplayItem* aContainerItem,
                  const nsRect& aContainerBounds,
                  ContainerLayer* aContainerLayer,
                  const ContainerLayerParameters& aParameters,
                  nscolor aBackgroundColor,
                  const ActiveScrolledRoot* aContainerASR,
                  const ActiveScrolledRoot* aContainerScrollMetadataASR,
-                 const ActiveScrolledRoot* aContainerCompositorASR) :
-    mBuilder(aBuilder), mManager(aManager),
-    mLayerBuilder(aLayerBuilder),
-    mContainerFrame(aContainerFrame),
-    mContainerLayer(aContainerLayer),
-    mContainerBounds(aContainerBounds),
-    mContainerASR(aContainerASR),
-    mContainerScrollMetadataASR(aContainerScrollMetadataASR),
-    mContainerCompositorASR(aContainerCompositorASR),
-    mParameters(aParameters),
-    mPaintedLayerDataTree(*this, aBackgroundColor),
-    mLastDisplayPortAGR(nullptr)
+                 const ActiveScrolledRoot* aContainerCompositorASR)
+    : mBuilder(aBuilder)
+    , mManager(aManager)
+    , mLayerBuilder(aLayerBuilder)
+    , mContainerFrame(aContainerFrame)
+    , mContainerLayer(aContainerLayer)
+    , mContainerBounds(aContainerBounds)
+    , mContainerASR(aContainerASR)
+    , mContainerScrollMetadataASR(aContainerScrollMetadataASR)
+    , mContainerCompositorASR(aContainerCompositorASR)
+    , mParameters(aParameters)
+    , mPaintedLayerDataTree(*this, aBackgroundColor)
+    , mLastDisplayPortAGR(nullptr)
   {
     nsPresContext* presContext = aContainerFrame->PresContext();
     mAppUnitsPerDevPixel = presContext->AppUnitsPerDevPixel();
-    mContainerReferenceFrame =
-      const_cast<nsIFrame*>(aContainerItem ? aContainerItem->ReferenceFrameForChildren() :
-                                             mBuilder->FindReferenceFrameFor(mContainerFrame));
-    bool isAtRoot = !aContainerItem || (aContainerItem->Frame() == mBuilder->RootReferenceFrame());
-    MOZ_ASSERT(!isAtRoot || mContainerReferenceFrame == mBuilder->RootReferenceFrame());
-    mContainerAnimatedGeometryRoot = isAtRoot
-      ? aBuilder->GetRootAnimatedGeometryRoot()
-      : aContainerItem->GetAnimatedGeometryRoot();
-    MOZ_ASSERT(!mBuilder->IsPaintingToWindow() ||
+    mContainerReferenceFrame = const_cast<nsIFrame*>(
+      aContainerItem ? aContainerItem->ReferenceFrameForChildren()
+                     : mBuilder->FindReferenceFrameFor(mContainerFrame));
+    bool isAtRoot = !aContainerItem ||
+                    (aContainerItem->Frame() == mBuilder->RootReferenceFrame());
+    MOZ_ASSERT(!isAtRoot ||
+               mContainerReferenceFrame == mBuilder->RootReferenceFrame());
+    mContainerAnimatedGeometryRoot =
+      isAtRoot ? aBuilder->GetRootAnimatedGeometryRoot()
+               : aContainerItem->GetAnimatedGeometryRoot();
+    MOZ_ASSERT(
+      !mBuilder->IsPaintingToWindow() ||
       nsLayoutUtils::IsAncestorFrameCrossDoc(mBuilder->RootReferenceFrame(),
                                              *mContainerAnimatedGeometryRoot));
     // When AllowResidualTranslation is false, display items will be drawn
     // scaled with a translation by integer pixels, so we know how the snapping
     // will work.
     mSnappingEnabled = aManager->IsSnappingEffectiveTransforms() &&
-      !mParameters.AllowResidualTranslation();
+                       !mParameters.AllowResidualTranslation();
     CollectOldLayers();
   }
 
   /**
    * This is the method that actually walks a display list and builds
    * the child layers.
    */
   void ProcessDisplayItems(nsDisplayList* aList);
   /**
    * This finalizes all the open PaintedLayers by popping every element off
    * mPaintedLayerDataStack, then sets the children of the container layer
    * to be all the layers in mNewChildLayers in that order and removes any
    * layers as children of the container that aren't in mNewChildLayers.
    * @param aTextContentFlags if any child layer has CONTENT_COMPONENT_ALPHA,
    * set *aTextContentFlags to CONTENT_COMPONENT_ALPHA
    */
-  void Finish(uint32_t *aTextContentFlags,
+  void Finish(uint32_t* aTextContentFlags,
               const nsIntRect& aContainerPixelBounds,
               nsDisplayList* aChildItems);
 
   nscoord GetAppUnitsPerDevPixel() { return mAppUnitsPerDevPixel; }
 
   nsIntRect ScaleToNearestPixels(const nsRect& aRect) const
   {
-    return aRect.ScaleToNearestPixels(mParameters.mXScale, mParameters.mYScale,
-                                      mAppUnitsPerDevPixel);
+    return aRect.ScaleToNearestPixels(
+      mParameters.mXScale, mParameters.mYScale, mAppUnitsPerDevPixel);
   }
   nsIntRegion ScaleRegionToNearestPixels(const nsRegion& aRegion) const
   {
-    return aRegion.ScaleToNearestPixels(mParameters.mXScale, mParameters.mYScale,
-                                        mAppUnitsPerDevPixel);
+    return aRegion.ScaleToNearestPixels(
+      mParameters.mXScale, mParameters.mYScale, mAppUnitsPerDevPixel);
   }
   nsIntRect ScaleToOutsidePixels(const nsRect& aRect, bool aSnap = false) const
   {
     if (aSnap && mSnappingEnabled) {
       return ScaleToNearestPixels(aRect);
     }
-    return aRect.ScaleToOutsidePixels(mParameters.mXScale, mParameters.mYScale,
-                                      mAppUnitsPerDevPixel);
-  }
-  nsIntRegion ScaleToOutsidePixels(const nsRegion& aRegion, bool aSnap = false) const
+    return aRect.ScaleToOutsidePixels(
+      mParameters.mXScale, mParameters.mYScale, mAppUnitsPerDevPixel);
+  }
+  nsIntRegion ScaleToOutsidePixels(const nsRegion& aRegion,
+                                   bool aSnap = false) const
   {
     if (aSnap && mSnappingEnabled) {
       return ScaleRegionToNearestPixels(aRegion);
     }
-    return aRegion.ScaleToOutsidePixels(mParameters.mXScale, mParameters.mYScale,
-                                        mAppUnitsPerDevPixel);
+    return aRegion.ScaleToOutsidePixels(
+      mParameters.mXScale, mParameters.mYScale, mAppUnitsPerDevPixel);
   }
   nsIntRect ScaleToInsidePixels(const nsRect& aRect, bool aSnap = false) const
   {
     if (aSnap && mSnappingEnabled) {
       return ScaleToNearestPixels(aRect);
     }
-    return aRect.ScaleToInsidePixels(mParameters.mXScale, mParameters.mYScale,
-                                     mAppUnitsPerDevPixel);
-  }
-
-  nsIntRegion ScaleRegionToInsidePixels(const nsRegion& aRegion, bool aSnap = false) const
+    return aRect.ScaleToInsidePixels(
+      mParameters.mXScale, mParameters.mYScale, mAppUnitsPerDevPixel);
+  }
+
+  nsIntRegion ScaleRegionToInsidePixels(const nsRegion& aRegion,
+                                        bool aSnap = false) const
   {
     if (aSnap && mSnappingEnabled) {
       return ScaleRegionToNearestPixels(aRegion);
     }
-    return aRegion.ScaleToInsidePixels(mParameters.mXScale, mParameters.mYScale,
-                                        mAppUnitsPerDevPixel);
-  }
-
-  nsIntRegion ScaleRegionToOutsidePixels(const nsRegion& aRegion, bool aSnap = false) const
+    return aRegion.ScaleToInsidePixels(
+      mParameters.mXScale, mParameters.mYScale, mAppUnitsPerDevPixel);
+  }
+
+  nsIntRegion ScaleRegionToOutsidePixels(const nsRegion& aRegion,
+                                         bool aSnap = false) const
   {
     if (aSnap && mSnappingEnabled) {
       return ScaleRegionToNearestPixels(aRegion);
     }
-    return aRegion.ScaleToOutsidePixels(mParameters.mXScale, mParameters.mYScale,
-                                        mAppUnitsPerDevPixel);
+    return aRegion.ScaleToOutsidePixels(
+      mParameters.mXScale, mParameters.mYScale, mAppUnitsPerDevPixel);
   }
 
   nsIFrame* GetContainerFrame() const { return mContainerFrame; }
   nsDisplayListBuilder* Builder() const { return mBuilder; }
 
   /**
    * Check if we are currently inside an inactive layer.
    */
-  bool IsInInactiveLayer() const {
+  bool IsInInactiveLayer() const
+  {
     return mLayerBuilder->GetContainingPaintedLayerData();
   }
 
   /**
    * Sets aOuterVisibleRegion as aLayer's visible region.
    * @param aOuterVisibleRegion
    *   is in the coordinate space of the container reference frame.
    * @param aLayerContentsVisibleRect, if non-null, is in the layer's own
    *   coordinate system.
    * @param aOuterUntransformed is true if the given aOuterVisibleRegion
    *   is already untransformed with the matrix of the layer.
    */
-  void SetOuterVisibleRegionForLayer(Layer* aLayer,
-                                     const nsIntRegion& aOuterVisibleRegion,
-                                     const nsIntRect* aLayerContentsVisibleRect = nullptr,
-                                     bool aOuterUntransformed = false) const;
+  void SetOuterVisibleRegionForLayer(
+    Layer* aLayer,
+    const nsIntRegion& aOuterVisibleRegion,
+    const nsIntRect* aLayerContentsVisibleRect = nullptr,
+    bool aOuterUntransformed = false) const;
 
   /**
    * Try to determine whether the PaintedLayer aData has a single opaque color
    * covering aRect. If successful, return that color, otherwise return
    * NS_RGBA(0,0,0,0).
    * If aRect turns out not to intersect any content in the layer,
    * *aOutIntersectsLayer will be set to false.
    */
@@ -1376,57 +1436,62 @@ public:
                                            bool* aOutIntersectsLayer) const;
 
   /**
    * Indicate that we are done adding items to the PaintedLayer represented by
    * aData. Make sure that a real PaintedLayer exists for it, and set the final
    * visible region and opaque-content.
    */
   template<typename FindOpaqueBackgroundColorCallbackType>
-  void FinishPaintedLayerData(PaintedLayerData& aData, FindOpaqueBackgroundColorCallbackType aFindOpaqueBackgroundColor);
+  void FinishPaintedLayerData(
+    PaintedLayerData& aData,
+    FindOpaqueBackgroundColorCallbackType aFindOpaqueBackgroundColor);
 
 protected:
   friend class PaintedLayerData;
   friend class FLBDisplayItemIterator;
 
-  LayerManager::PaintedLayerCreationHint
-    GetLayerCreationHint(AnimatedGeometryRoot* aAnimatedGeometryRoot);
+  LayerManager::PaintedLayerCreationHint GetLayerCreationHint(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot);
 
   /**
    * Creates a new PaintedLayer and sets up the transform on the PaintedLayer
    * to account for scrolling.
    */
   already_AddRefed<PaintedLayer> CreatePaintedLayer(PaintedLayerData* aData);
 
   /**
    * Find a PaintedLayer for recycling, recycle it and prepare it for use, or
    * return null if no suitable layer was found.
    */
-  already_AddRefed<PaintedLayer> AttemptToRecyclePaintedLayer(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                                              nsDisplayItem* aItem,
-                                                              const nsPoint& aTopLeft,
-                                                              const nsIFrame* aReferenceFrame);
+  already_AddRefed<PaintedLayer> AttemptToRecyclePaintedLayer(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot,
+    nsDisplayItem* aItem,
+    const nsPoint& aTopLeft,
+    const nsIFrame* aReferenceFrame);
   /**
    * Recycle aLayer and do any necessary invalidation.
    */
-  PaintedDisplayItemLayerUserData* RecyclePaintedLayer(PaintedLayer* aLayer,
-                                                       AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                                       bool& didResetScrollPositionForLayerPixelAlignment);
+  PaintedDisplayItemLayerUserData* RecyclePaintedLayer(
+    PaintedLayer* aLayer,
+    AnimatedGeometryRoot* aAnimatedGeometryRoot,
+    bool& didResetScrollPositionForLayerPixelAlignment);
 
   /**
    * Perform the last step of CreatePaintedLayer / AttemptToRecyclePaintedLayer:
    * Initialize aData, set up the layer's transform for scrolling, and
    * invalidate the layer for layer pixel alignment changes if necessary.
    */
-  void PreparePaintedLayerForUse(PaintedLayer* aLayer,
-                                 PaintedDisplayItemLayerUserData* aData,
-                                 AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                 const nsIFrame* aReferenceFrame,
-                                 const nsPoint& aTopLeft,
-                                 bool aDidResetScrollPositionForLayerPixelAlignment);
+  void PreparePaintedLayerForUse(
+    PaintedLayer* aLayer,
+    PaintedDisplayItemLayerUserData* aData,
+    AnimatedGeometryRoot* aAnimatedGeometryRoot,
+    const nsIFrame* aReferenceFrame,
+    const nsPoint& aTopLeft,
+    bool aDidResetScrollPositionForLayerPixelAlignment);
 
   /**
    * Attempt to prepare an ImageLayer based upon the provided PaintedLayerData.
    * Returns nullptr on failure.
    */
   already_AddRefed<Layer> PrepareImageLayer(PaintedLayerData* aData);
 
   /**
@@ -1434,47 +1499,49 @@ protected:
    * Returns nullptr on failure.
    */
   already_AddRefed<Layer> PrepareColorLayer(PaintedLayerData* aData);
 
   /**
    * Grab the next recyclable ColorLayer, or create one if there are no
    * more recyclable ColorLayers.
    */
-  already_AddRefed<ColorLayer> CreateOrRecycleColorLayer(PaintedLayer* aPainted);
+  already_AddRefed<ColorLayer> CreateOrRecycleColorLayer(
+    PaintedLayer* aPainted);
   /**
    * Grab the next recyclable ImageLayer, or create one if there are no
    * more recyclable ImageLayers.
    */
-  already_AddRefed<ImageLayer> CreateOrRecycleImageLayer(PaintedLayer* aPainted);
+  already_AddRefed<ImageLayer> CreateOrRecycleImageLayer(
+    PaintedLayer* aPainted);
   /**
    * Grab a recyclable ImageLayer for use as a mask layer for aLayer (that is a
    * mask layer which has been used for aLayer before), or create one if such
    * a layer doesn't exist.
    *
    * Since mask layers can exist either on the layer directly, or as a side-
    * attachment to FrameMetrics (for ancestor scrollframe clips), we key the
    * recycle operation on both the originating layer and the mask layer's
    * index in the layer, if any.
    */
   struct MaskLayerKey;
   template<typename UserData>
   already_AddRefed<ImageLayer> CreateOrRecycleMaskImageLayerFor(
-      const MaskLayerKey& aKey,
-      UserData* (*aGetUserData)(Layer* aLayer),
-      void (*aSetDefaultUserData)(Layer* aLayer));
+    const MaskLayerKey& aKey,
+    UserData* (*aGetUserData)(Layer* aLayer),
+    void (*aSetDefaultUserData)(Layer* aLayer));
   /**
-   * Grabs all PaintedLayers and ColorLayers from the ContainerLayer and makes them
-   * available for recycling.
+   * Grabs all PaintedLayers and ColorLayers from the ContainerLayer and makes
+   * them available for recycling.
    */
   void CollectOldLayers();
   /**
    * If aItem used to belong to a PaintedLayer, invalidates the area of
-   * aItem in that layer. If aNewLayer is a PaintedLayer, invalidates the area of
-   * aItem in that layer.
+   * aItem in that layer. If aNewLayer is a PaintedLayer, invalidates the area
+   * of aItem in that layer.
    */
   void InvalidateForLayerChange(nsDisplayItem* aItem,
                                 PaintedLayer* aNewLayer,
                                 DisplayItemData* aData);
   /**
    * Returns true if aItem's opaque area (in aOpaque) covers the entire
    * scrollable area of its presshell.
    */
@@ -1513,22 +1580,23 @@ protected:
                                 bool* aOpaqueForAnimatedGeometryRootParent);
 
   /**
    * Fills a PaintedLayerData object that is initialized for a layer that the
    * current item will be assigned to. Also creates mNewChildLayers entries.
    * @param  aData                 The PaintedLayerData that will be filled.
    * @param  aVisibleRect          The visible rect of the item.
    * @param  aAnimatedGeometryRoot The item's animated geometry root.
-   * @param  aASR                  The active scrolled root that moves this PaintedLayer.
+   * @param  aASR                  The active scrolled root that moves this
+   * PaintedLayer.
    * @param  aClipChain            The clip chain that the compositor needs to
    *                               apply to this layer.
-   * @param  aScrollMetadataASR    The leaf ASR for which scroll metadata needs to be
-   *                               set on the layer, because either the layer itself
-   *                               or its scrolled clip need to move with that ASR.
+   * @param  aScrollMetadataASR    The leaf ASR for which scroll metadata needs
+   * to be set on the layer, because either the layer itself or its scrolled
+   * clip need to move with that ASR.
    * @param  aTopLeft              The offset between aAnimatedGeometryRoot and
    *                               the reference frame.
    * @param  aReferenceFrame       The reference frame for the item.
    * @param  aBackfaceHidden       The backface visibility for the item frame.
    */
   void NewPaintedLayerData(PaintedLayerData* aData,
                            AnimatedGeometryRoot* aAnimatedGeometryRoot,
                            const ActiveScrolledRoot* aASR,
@@ -1541,17 +1609,17 @@ protected:
   /* Build a mask layer to represent the clipping region. Will return null if
    * there is no clipping specified or a mask layer cannot be built.
    * Builds an ImageLayer for the appropriate backend; the mask is relative to
    * aLayer's visible region.
    * aLayer is the layer to be clipped.
    * relative to the container reference frame
    * aRoundedRectClipCount is used when building mask layers for PaintedLayers,
    */
-  void SetupMaskLayer(Layer *aLayer, const DisplayItemClip& aClip);
+  void SetupMaskLayer(Layer* aLayer, const DisplayItemClip& aClip);
 
   /**
    * If |aClip| has rounded corners, create a mask layer for them, and
    * add it to |aLayer|'s ancestor mask layers, returning an index into
    * the array of ancestor mask layers. Returns an empty Maybe if
    * |aClip| does not have rounded corners, or if no mask layer could
    * be created.
    */
@@ -1560,109 +1628,121 @@ protected:
 
   /*
    * Create/find a mask layer with suitable size for aMaskItem to paint
    * css-positioned-masking onto.
    */
   void SetupMaskLayerForCSSMask(Layer* aLayer, nsDisplayMask* aMaskItem);
 
   already_AddRefed<Layer> CreateMaskLayer(
-    Layer *aLayer, const DisplayItemClip& aClip,
+    Layer* aLayer,
+    const DisplayItemClip& aClip,
     const Maybe<size_t>& aForAncestorMaskLayer);
 
   /**
    * Get the display port for an AGR.
    * The result would be cached for later reusing.
    */
-  nsRect GetDisplayPortForAnimatedGeometryRoot(AnimatedGeometryRoot* aAnimatedGeometryRoot);
-
-  nsDisplayListBuilder*            mBuilder;
-  LayerManager*                    mManager;
-  FrameLayerBuilder*               mLayerBuilder;
-  nsIFrame*                        mContainerFrame;
-  nsIFrame*                        mContainerReferenceFrame;
-  AnimatedGeometryRoot*            mContainerAnimatedGeometryRoot;
-  ContainerLayer*                  mContainerLayer;
-  nsRect                           mContainerBounds;
+  nsRect GetDisplayPortForAnimatedGeometryRoot(
+    AnimatedGeometryRoot* aAnimatedGeometryRoot);
+
+  nsDisplayListBuilder* mBuilder;
+  LayerManager* mManager;
+  FrameLayerBuilder* mLayerBuilder;
+  nsIFrame* mContainerFrame;
+  nsIFrame* mContainerReferenceFrame;
+  AnimatedGeometryRoot* mContainerAnimatedGeometryRoot;
+  ContainerLayer* mContainerLayer;
+  nsRect mContainerBounds;
 
   // Due to the way we store scroll annotations in the layer tree, we need to
   // keep track of three (possibly different) ASRs here.
   // mContainerASR is the ASR of the container display item that this
   // ContainerState was created for.
   // mContainerScrollMetadataASR is the ASR of the leafmost scroll metadata
   // that's in effect on mContainerLayer.
   // mContainerCompositorASR is the ASR that mContainerLayer moves with on
   // the compositor / APZ side, taking into account both the scroll meta data
   // and the fixed position annotation on itself and its ancestors.
-  const ActiveScrolledRoot*        mContainerASR;
-  const ActiveScrolledRoot*        mContainerScrollMetadataASR;
-  const ActiveScrolledRoot*        mContainerCompositorASR;
+  const ActiveScrolledRoot* mContainerASR;
+  const ActiveScrolledRoot* mContainerScrollMetadataASR;
+  const ActiveScrolledRoot* mContainerCompositorASR;
 #ifdef DEBUG
-  nsRect                           mAccumulatedChildBounds;
+  nsRect mAccumulatedChildBounds;
 #endif
-  ContainerLayerParameters         mParameters;
+  ContainerLayerParameters mParameters;
   /**
    * The region of PaintedLayers that should be invalidated every time
    * we recycle one.
    */
-  nsIntRegion                      mInvalidPaintedContent;
-  PaintedLayerDataTree             mPaintedLayerDataTree;
+  nsIntRegion mInvalidPaintedContent;
+  PaintedLayerDataTree mPaintedLayerDataTree;
   /**
    * We collect the list of children in here. During ProcessDisplayItems,
    * the layers in this array either have mContainerLayer as their parent,
    * or no parent.
-   * PaintedLayers have two entries in this array: the second one is used only if
-   * the PaintedLayer is optimized away to a ColorLayer or ImageLayer.
-   * It's essential that this array is only appended to, since PaintedLayerData
+   * PaintedLayers have two entries in this array: the second one is used only
+   * if the PaintedLayer is optimized away to a ColorLayer or ImageLayer. It's
+   * essential that this array is only appended to, since PaintedLayerData
    * records the index of its PaintedLayer in this array.
    */
-  typedef AutoTArray<NewLayerEntry,1> AutoLayersArray;
-  AutoLayersArray                  mNewChildLayers;
-  nsTHashtable<nsRefPtrHashKey<PaintedLayer>> mPaintedLayersAvailableForRecycling;
-  nscoord                          mAppUnitsPerDevPixel;
-  bool                             mSnappingEnabled;
-
-  struct MaskLayerKey {
-    MaskLayerKey() : mLayer(nullptr) {}
+  typedef AutoTArray<NewLayerEntry, 1> AutoLayersArray;
+  AutoLayersArray mNewChildLayers;
+  nsTHashtable<nsRefPtrHashKey<PaintedLayer>>
+    mPaintedLayersAvailableForRecycling;
+  nscoord mAppUnitsPerDevPixel;
+  bool mSnappingEnabled;
+
+  struct MaskLayerKey
+  {
+    MaskLayerKey()
+      : mLayer(nullptr)
+    {
+    }
     MaskLayerKey(Layer* aLayer, const Maybe<size_t>& aAncestorIndex)
-      : mLayer(aLayer),
-        mAncestorIndex(aAncestorIndex)
-    {}
-
-    PLDHashNumber Hash() const {
+      : mLayer(aLayer)
+      , mAncestorIndex(aAncestorIndex)
+    {
+    }
+
+    PLDHashNumber Hash() const
+    {
       // Hash the layer and add the layer index to the hash.
-      return (NS_PTR_TO_UINT32(mLayer) >> 2)
-             + (mAncestorIndex ? (*mAncestorIndex + 1) : 0);
-    }
-    bool operator ==(const MaskLayerKey& aOther) const {
-      return mLayer == aOther.mLayer &&
-             mAncestorIndex == aOther.mAncestorIndex;
+      return (NS_PTR_TO_UINT32(mLayer) >> 2) +
+             (mAncestorIndex ? (*mAncestorIndex + 1) : 0);
+    }
+    bool operator==(const MaskLayerKey& aOther) const
+    {
+      return mLayer == aOther.mLayer && mAncestorIndex == aOther.mAncestorIndex;
     }
 
     Layer* mLayer;
     Maybe<size_t> mAncestorIndex;
   };
 
   nsDataHashtable<nsGenericHashKey<MaskLayerKey>, RefPtr<ImageLayer>>
     mRecycledMaskImageLayers;
   // Keep display port of AGR to avoid wasting time on doing the same
   // thing repeatly.
   AnimatedGeometryRoot* mLastDisplayPortAGR;
   nsRect mLastDisplayPortRect;
 
-  // Cache ScrollMetadata so it doesn't need recomputed if the ASR and clip are unchanged.
-  // If mASR == nullptr then mMetadata is not valid.
-  struct CachedScrollMetadata {
+  // Cache ScrollMetadata so it doesn't need recomputed if the ASR and clip are
+  // unchanged. If mASR == nullptr then mMetadata is not valid.
+  struct CachedScrollMetadata
+  {
     const ActiveScrolledRoot* mASR;
     const DisplayItemClip* mClip;
     Maybe<ScrollMetadata> mMetadata;
 
     CachedScrollMetadata()
-      : mASR(nullptr), mClip(nullptr)
-    {}
+      : mASR(nullptr)
+      , mClip(nullptr)
+    {
+    }
   };
   CachedScrollMetadata mCachedScrollMetadata;
 };
 
 nsDisplayItem*
 FLBDisplayItemIterator::GetNext()
 {
   // This function is only supposed to be called if there are no markers set.
@@ -1675,17 +1755,17 @@ FLBDisplayItemIterator::GetNext()
   // Advance mNext to the following item
   if (next) {
     nsDisplayItem* peek = next->GetAbove();
 
     // Peek ahead to the next item and see if it can be merged with the
     // current item.
     if (peek && next->CanMerge(peek)) {
       // Create a list of consecutive items that can be merged together.
-      AutoTArray<nsDisplayItem*, 2> mergedItems { next, peek };
+      AutoTArray<nsDisplayItem*, 2> mergedItems{ next, peek };
       while ((peek = peek->GetAbove())) {
         if (!next->CanMerge(peek)) {
           break;
         }
 
         mergedItems.AppendElement(peek);
       }
 
@@ -1703,19 +1783,18 @@ FLBDisplayItemIterator::GetNext()
   }
 
   return next;
 }
 
 bool
 FLBDisplayItemIterator::NextItemWantsInactiveLayer()
 {
-  LayerState layerState = mNext->GetLayerState(mState->mBuilder,
-                                               mState->mManager,
-                                               mState->mParameters);
+  LayerState layerState = mNext->GetLayerState(
+    mState->mBuilder, mState->mManager, mState->mParameters);
 
   return layerState == LayerState::LAYER_INACTIVE;
 }
 
 bool
 FLBDisplayItemIterator::ShouldFlattenNextItem()
 {
   if (!mNext) {
@@ -1751,26 +1830,29 @@ FLBDisplayItemIterator::ShouldFlattenNex
   // Flatten inactive nsDisplayOpacity and nsDisplayTransform.
   mStoreMarker = true;
   return true;
 }
 
 class PaintedDisplayItemLayerUserData : public LayerUserData
 {
 public:
-  PaintedDisplayItemLayerUserData() :
-    mForcedBackgroundColor(NS_RGBA(0,0,0,0)),
-    mXScale(1.f), mYScale(1.f),
-    mAppUnitsPerDevPixel(0),
-    mTranslation(0, 0),
-    mAnimatedGeometryRootPosition(0, 0),
-    mLastItemCount(0),
-    mContainerLayerFrame(nullptr),
-    mHasExplicitLastPaintOffset(false),
-    mDisabledAlpha(false) {}
+  PaintedDisplayItemLayerUserData()
+    : mForcedBackgroundColor(NS_RGBA(0, 0, 0, 0))
+    , mXScale(1.f)
+    , mYScale(1.f)
+    , mAppUnitsPerDevPixel(0)
+    , mTranslation(0, 0)
+    , mAnimatedGeometryRootPosition(0, 0)
+    , mLastItemCount(0)
+    , mContainerLayerFrame(nullptr)
+    , mHasExplicitLastPaintOffset(false)
+    , mDisabledAlpha(false)
+  {
+  }
 
   NS_INLINE_DECL_REFCOUNTING(PaintedDisplayItemLayerUserData);
 
   /**
    * A color that should be painted over the bounds of the layer's visible
    * region before any other content is painted.
    */
   nscolor mForcedBackgroundColor;
@@ -1792,19 +1874,19 @@ public:
    * offset specified by the parent ContainerLayer/
    */
   nsIntPoint mTranslation;
 
   /**
    * We try to make 0,0 of the PaintedLayer be the top-left of the
    * border-box of the "active scrolled root" frame (i.e. the nearest ancestor
    * frame for the display items that is being actively scrolled). But
-   * we force the PaintedLayer transform to be an integer translation, and we may
-   * have a resolution scale, so we have to snap the PaintedLayer transform, so
-   * 0,0 may not be exactly the top-left of the active scrolled root. Here we
+   * we force the PaintedLayer transform to be an integer translation, and we
+   * may have a resolution scale, so we have to snap the PaintedLayer transform,
+   * so 0,0 may not be exactly the top-left of the active scrolled root. Here we
    * store the coordinates in PaintedLayer space of the top-left of the
    * active scrolled root.
    */
   gfxPoint mAnimatedGeometryRootPosition;
 
   nsIntRegion mRegionToInvalidate;
 
   // The offset between the active scrolled root of this layer
@@ -1843,17 +1925,17 @@ public:
   bool mHasExplicitLastPaintOffset;
 
   /**
    * This is set when the painted layer has no component alpha.
    */
   bool mDisabledAlpha;
 
 protected:
-  ~PaintedDisplayItemLayerUserData() = default;
+  ~PaintedDisplayItemLayerUserData() override = default;
 };
 
 FrameLayerBuilder::FrameLayerBuilder()
   : mRetainingManager(nullptr)
   , mDisplayListBuilder(nullptr)
   , mContainingPaintedLayer(nullptr)
   , mInactiveLayerClip(nullptr)
   , mInvalidateAllLayers(false)
@@ -1869,31 +1951,33 @@ FrameLayerBuilder::~FrameLayerBuilder()
   for (PaintedDisplayItemLayerUserData* userData : mPaintedLayerItems) {
     userData->mItems.clear();
     userData->mContainerLayerFrame = nullptr;
   }
   MOZ_COUNT_DTOR(FrameLayerBuilder);
 }
 
 void
-FrameLayerBuilder::AddPaintedLayerItemsEntry(PaintedDisplayItemLayerUserData* aData)
+FrameLayerBuilder::AddPaintedLayerItemsEntry(
+  PaintedDisplayItemLayerUserData* aData)
 {
   mPaintedLayerItems.AppendElement(aData);
 }
 
 /*
  * User data for layers which will be used as masks.
  */
 struct MaskLayerUserData : public LayerUserData
 {
   MaskLayerUserData()
     : mScaleX(-1.0f)
     , mScaleY(-1.0f)
     , mAppUnitsPerDevPixel(-1)
-  { }
+  {
+  }
   MaskLayerUserData(const DisplayItemClip& aClip,
                     int32_t aAppUnitsPerDevPixel,
                     const ContainerLayerParameters& aParams)
     : mScaleX(aParams.mXScale)
     , mScaleY(aParams.mYScale)
     , mOffset(aParams.mOffset)
     , mAppUnitsPerDevPixel(aAppUnitsPerDevPixel)
   {
@@ -1904,64 +1988,64 @@ struct MaskLayerUserData : public LayerU
   {
     mScaleX = aOther.mScaleX;
     mScaleY = aOther.mScaleY;
     mOffset = aOther.mOffset;
     mAppUnitsPerDevPixel = aOther.mAppUnitsPerDevPixel;
     mRoundedClipRects.SwapElements(aOther.mRoundedClipRects);
   }
 
-  bool
-  operator== (const MaskLayerUserData& aOther) const
+  bool operator==(const MaskLayerUserData& aOther) const
   {
     return mRoundedClipRects == aOther.mRoundedClipRects &&
-           mScaleX == aOther.mScaleX &&
-           mScaleY == aOther.mScaleY &&
+           mScaleX == aOther.mScaleX && mScaleY == aOther.mScaleY &&
            mOffset == aOther.mOffset &&
            mAppUnitsPerDevPixel == aOther.mAppUnitsPerDevPixel;
   }
 
   // Keeps a MaskLayerImageKey alive by managing its mLayerCount member-var
   MaskLayerImageCache::MaskLayerImageKeyRef mImageKey;
   // properties of the mask layer; the mask layer may be re-used if these
   // remain unchanged.
   nsTArray<DisplayItemClip::RoundedRect> mRoundedClipRects;
   // scale from the masked layer which is applied to the mask
   float mScaleX, mScaleY;
-  // The ContainerLayerParameters offset which is applied to the mask's transform.
+  // The ContainerLayerParameters offset which is applied to the mask's
+  // transform.
   nsIntPoint mOffset;
   int32_t mAppUnitsPerDevPixel;
 };
 
 /*
  * User data for layers which will be used as masks for css positioned mask.
  */
 struct CSSMaskLayerUserData : public LayerUserData
 {
   CSSMaskLayerUserData()
     : mMaskStyle(nsStyleImageLayers::LayerType::Mask)
-  { }
-
-  CSSMaskLayerUserData(nsIFrame* aFrame, const nsIntRect& aMaskBounds,
+  {
+  }
+
+  CSSMaskLayerUserData(nsIFrame* aFrame,
+                       const nsIntRect& aMaskBounds,
                        const nsPoint& aMaskLayerOffset)
-    : mMaskBounds(aMaskBounds),
-      mMaskStyle(aFrame->StyleSVGReset()->mMask),
-      mMaskLayerOffset(aMaskLayerOffset)
+    : mMaskBounds(aMaskBounds)
+    , mMaskStyle(aFrame->StyleSVGReset()->mMask)
+    , mMaskLayerOffset(aMaskLayerOffset)
   {
   }
 
   void operator=(CSSMaskLayerUserData&& aOther)
   {
     mMaskBounds = aOther.mMaskBounds;
     mMaskStyle = std::move(aOther.mMaskStyle);
     mMaskLayerOffset = aOther.mMaskLayerOffset;
   }
 
-  bool
-  operator==(const CSSMaskLayerUserData& aOther) const
+  bool operator==(const CSSMaskLayerUserData& aOther) const
   {
     if (!mMaskBounds.IsEqualInterior(aOther.mMaskBounds)) {
       return false;
     }
 
     // Make sure we draw the same portion of the mask onto mask layer.
     if (mMaskLayerOffset != aOther.mMaskLayerOffset) {
       return false;
@@ -2010,30 +2094,31 @@ public:
       return mDrawTarget;
     }
 
     if (mLayerManager->GetBackendType() == LayersBackend::LAYERS_BASIC) {
       mDrawTarget = mLayerManager->CreateOptimalMaskDrawTarget(mSize);
       return mDrawTarget;
     }
 
-    MOZ_ASSERT(mLayerManager->GetBackendType() == LayersBackend::LAYERS_CLIENT ||
+    MOZ_ASSERT(mLayerManager->GetBackendType() ==
+                 LayersBackend::LAYERS_CLIENT ||
                mLayerManager->GetBackendType() == LayersBackend::LAYERS_WR);
 
     KnowsCompositor* knowsCompositor = mLayerManager->AsKnowsCompositor();
     if (!knowsCompositor) {
       return nullptr;
     }
-    mTextureClient =
-      TextureClient::CreateForDrawing(knowsCompositor,
-                                      SurfaceFormat::A8,
-                                      mSize,
-                                      BackendSelector::Content,
-                                      TextureFlags::DISALLOW_BIGIMAGE,
-                                      TextureAllocationFlags::ALLOC_CLEAR_BUFFER);
+    mTextureClient = TextureClient::CreateForDrawing(
+      knowsCompositor,
+      SurfaceFormat::A8,
+      mSize,
+      BackendSelector::Content,
+      TextureFlags::DISALLOW_BIGIMAGE,
+      TextureAllocationFlags::ALLOC_CLEAR_BUFFER);
     if (!mTextureClient) {
       return nullptr;
     }
 
     mTextureClientLocked = mTextureClient->Lock(OpenMode::OPEN_READ_WRITE);
     if (!mTextureClientLocked) {
       return nullptr;
     }
@@ -2065,20 +2150,19 @@ private:
       // Disallow BIGIMAGE (splitting into multiple textures) for mask
       // layer images
       image->SetTextureFlags(TextureFlags::DISALLOW_BIGIMAGE);
       return image.forget();
     }
 
     if ((mLayerManager->GetBackendType() == LayersBackend::LAYERS_CLIENT ||
          mLayerManager->GetBackendType() == LayersBackend::LAYERS_WR) &&
-        mTextureClient &&
-        mDrawTarget) {
-      RefPtr<TextureWrapperImage> image =
-          new TextureWrapperImage(mTextureClient, gfx::IntRect(gfx::IntPoint(0, 0), mSize));
+        mTextureClient && mDrawTarget) {
+      RefPtr<TextureWrapperImage> image = new TextureWrapperImage(
+        mTextureClient, gfx::IntRect(gfx::IntPoint(0, 0), mSize));
       return image.forget();
     }
 
     return nullptr;
   }
 
   bool mTextureClientLocked;
   gfx::IntSize mSize;
@@ -2099,68 +2183,73 @@ FrameLayerBuilder::Shutdown()
 {
   if (gMaskLayerImageCache) {
     delete gMaskLayerImageCache;
     gMaskLayerImageCache = nullptr;
   }
 }
 
 void
-FrameLayerBuilder::Init(nsDisplayListBuilder* aBuilder, LayerManager* aManager,
+FrameLayerBuilder::Init(nsDisplayListBuilder* aBuilder,
+                        LayerManager* aManager,
                         PaintedLayerData* aLayerData,
                         bool aIsInactiveLayerManager,
                         const DisplayItemClip* aInactiveLayerClip)
 {
   mDisplayListBuilder = aBuilder;
-  mRootPresContext = aBuilder->RootReferenceFrame()->PresContext()->GetRootPresContext();
+  mRootPresContext =
+    aBuilder->RootReferenceFrame()->PresContext()->GetRootPresContext();
   mContainingPaintedLayer = aLayerData;
   mIsInactiveLayerManager = aIsInactiveLayerManager;
   mInactiveLayerClip = aInactiveLayerClip;
   aManager->SetUserData(&gLayerManagerLayerBuilder, this);
 }
 
 void
-FrameLayerBuilder::FlashPaint(gfxContext *aContext)
+FrameLayerBuilder::FlashPaint(gfxContext* aContext)
 {
   float r = float(rand()) / RAND_MAX;
   float g = float(rand()) / RAND_MAX;
   float b = float(rand()) / RAND_MAX;
   aContext->SetColor(Color(r, g, b, 0.4f));
   aContext->Paint();
 }
 
 DisplayItemData*
 FrameLayerBuilder::GetDisplayItemData(nsIFrame* aFrame, uint32_t aKey)
 {
   const SmallPointerArray<DisplayItemData>& array = aFrame->DisplayItemData();
   for (uint32_t i = 0; i < array.Length(); i++) {
-    DisplayItemData* item = DisplayItemData::AssertDisplayItemData(array.ElementAt(i));
+    DisplayItemData* item =
+      DisplayItemData::AssertDisplayItemData(array.ElementAt(i));
     if (item->mDisplayItemKey == aKey &&
         item->mLayer->Manager() == mRetainingManager) {
       return item;
     }
   }
   return nullptr;
 }
 
 #ifdef MOZ_DUMP_PAINTING
 static nsACString&
-AppendToString(nsACString& s, const nsIntRect& r,
-               const char* pfx="", const char* sfx="")
+AppendToString(nsACString& s,
+               const nsIntRect& r,
+               const char* pfx = "",
+               const char* sfx = "")
 {
   s += pfx;
-  s += nsPrintfCString(
-    "(x=%d, y=%d, w=%d, h=%d)",
-    r.x, r.y, r.width, r.height);
+  s += nsPrintfCString("(x=%d, y=%d, w=%d, h=%d)", r.x, r.y, r.width, r.height);
   return s += sfx;
 }
 
 static nsACString&
-AppendToString(nsACString& s, const nsIntRegion& r,
-               const char* pfx="", const char* sfx="")
+AppendToString(nsACString& s,
+               const nsIntRegion& r,
+               const char* pfx = "",
+               const char* sfx = "")
 {
   s += pfx;
 
   s += "< ";
   for (auto iter = r.RectIter(); !iter.Done(); iter.Next()) {
     AppendToString(s, iter.Get()) += "; ";
   }
   s += ">";
@@ -2198,38 +2287,38 @@ InvalidatePostTransformRegion(PaintedLay
 static void
 InvalidatePreTransformRect(PaintedLayer* aLayer,
                            const nsRect& aRect,
                            const DisplayItemClip& aClip,
                            const nsIntPoint& aTranslation,
                            TransformClipNode* aTransform)
 {
   PaintedDisplayItemLayerUserData* data =
-      static_cast<PaintedDisplayItemLayerUserData*>(aLayer->GetUserData(&gPaintedDisplayItemLayerUserData));
+    static_cast<PaintedDisplayItemLayerUserData*>(
+      aLayer->GetUserData(&gPaintedDisplayItemLayerUserData));
 
   nsRect rect = aClip.ApplyNonRoundedIntersection(aRect);
 
-  nsIntRect pixelRect = rect.ScaleToOutsidePixels(data->mXScale, data->mYScale,
-                                                  data->mAppUnitsPerDevPixel);
+  nsIntRect pixelRect = rect.ScaleToOutsidePixels(
+    data->mXScale, data->mYScale, data->mAppUnitsPerDevPixel);
 
   if (aTransform) {
     pixelRect =
       aTransform->TransformRect(pixelRect, data->mAppUnitsPerDevPixel);
   }
 
   InvalidatePostTransformRegion(aLayer, pixelRect, aTranslation);
 }
 
-
 static nsIntPoint
 GetTranslationForPaintedLayer(PaintedLayer* aLayer)
 {
   PaintedDisplayItemLayerUserData* data =
-    static_cast<PaintedDisplayItemLayerUserData*>
-      (aLayer->GetUserData(&gPaintedDisplayItemLayerUserData));
+    static_cast<PaintedDisplayItemLayerUserData*>(
+      aLayer->GetUserData(&gPaintedDisplayItemLayerUserData));
   NS_ASSERTION(data, "Must be a tracked painted layer!");
 
   return data->mTranslation;
 }
 
 /**
  * Some frames can have multiple, nested, retaining layer managers
  * associated with them (normal manager, inactive managers, SVG effects).
@@ -2242,59 +2331,61 @@ GetTranslationForPaintedLayer(PaintedLay
  * the DisplayItemData destructor. If the inner layer manager had any
  * items with the same frame, then we attempt to retrieve properties
  * from the deleted frame.
  *
  * Cache the destroyed frame pointer here so we can avoid crashing in this case.
  */
 
 /* static */ void
-FrameLayerBuilder::RemoveFrameFromLayerManager(const nsIFrame* aFrame,
-                                               SmallPointerArray<DisplayItemData>& aArray)
+FrameLayerBuilder::RemoveFrameFromLayerManager(
+  const nsIFrame* aFrame,
+  SmallPointerArray<DisplayItemData>& aArray)
 {
   MOZ_RELEASE_ASSERT(!sDestroyedFrame);
   sDestroyedFrame = aFrame;
 
   // Hold a reference to all the items so that they don't get
   // deleted from under us.
-  nsTArray<RefPtr<DisplayItemData> > arrayCopy;
+  nsTArray<RefPtr<DisplayItemData>> arrayCopy;
   for (DisplayItemData* data : aArray) {
     arrayCopy.AppendElement(data);
   }
 
 #ifdef DEBUG_DISPLAY_ITEM_DATA
   if (aArray->Length()) {
-    LayerManagerData *rootData = aArray->ElementAt(0)->mParent;
+    LayerManagerData* rootData = aArray->ElementAt(0)->mParent;
     while (rootData->mParent) {
       rootData = rootData->mParent;
     }
     printf_stderr("Removing frame %p - dumping display data\n", aFrame);
     rootData->Dump();
   }
 #endif
 
   for (DisplayItemData* data : aArray) {
     PaintedLayer* t = data->mLayer ? data->mLayer->AsPaintedLayer() : nullptr;
     if (t) {
       PaintedDisplayItemLayerUserData* paintedData =
-          static_cast<PaintedDisplayItemLayerUserData*>(t->GetUserData(&gPaintedDisplayItemLayerUserData));
+        static_cast<PaintedDisplayItemLayerUserData*>(
+          t->GetUserData(&gPaintedDisplayItemLayerUserData));
       if (paintedData && data->mGeometry) {
         const int32_t appUnitsPerDevPixel = paintedData->mAppUnitsPerDevPixel;
         nsRegion old = data->mGeometry->ComputeInvalidationRegion();
-        nsIntRegion rgn = old.ScaleToOutsidePixels(paintedData->mXScale,
-                                                   paintedData->mYScale,
-                                                   appUnitsPerDevPixel);
+        nsIntRegion rgn = old.ScaleToOutsidePixels(
+          paintedData->mXScale, paintedData->mYScale, appUnitsPerDevPixel);
 
         if (data->mTransform) {
           rgn = data->mTransform->TransformRegion(rgn, appUnitsPerDevPixel);
         }
 
         rgn.MoveBy(-GetTranslationForPaintedLayer(t));
 
-        paintedData->mRegionToInvalidate.Or(paintedData->mRegionToInvalidate, rgn);
+        paintedData->mRegionToInvalidate.Or(paintedData->mRegionToInvalidate,
+                                            rgn);
         paintedData->mRegionToInvalidate.SimplifyOutward(8);
       }
     }
 
     auto it = std::find(data->mParent->mDisplayItems.begin(),
                         data->mParent->mDisplayItems.end(),
                         data);
     MOZ_ASSERT(it != data->mParent->mDisplayItems.end());
@@ -2305,18 +2396,18 @@ FrameLayerBuilder::RemoveFrameFromLayerM
   arrayCopy.Clear();
   sDestroyedFrame = nullptr;
 }
 
 void
 FrameLayerBuilder::DidBeginRetainedLayerTransaction(LayerManager* aManager)
 {
   mRetainingManager = aManager;
-  LayerManagerData* data = static_cast<LayerManagerData*>
-    (aManager->GetUserData(&gLayerManagerUserData));
+  LayerManagerData* data = static_cast<LayerManagerData*>(
+    aManager->GetUserData(&gLayerManagerUserData));
   if (data) {
     mInvalidateAllLayers = data->mInvalidateAllLayers;
   } else {
     data = new LayerManagerData(aManager);
     aManager->SetUserData(&gLayerManagerUserData, data);
   }
 }
 
@@ -2329,31 +2420,35 @@ FrameLayerBuilder::DidEndTransaction()
 void
 FrameLayerBuilder::WillEndTransaction()
 {
   if (!mRetainingManager) {
     return;
   }
 
   // We need to save the data we'll need to support retaining.
-  LayerManagerData* data = static_cast<LayerManagerData*>
-    (mRetainingManager->GetUserData(&gLayerManagerUserData));
+  LayerManagerData* data = static_cast<LayerManagerData*>(
+    mRetainingManager->GetUserData(&gLayerManagerUserData));
   NS_ASSERTION(data, "Must have data!");
 
   // Update all the frames that used to have layers.
   auto iter = data->mDisplayItems.begin();
   while (iter != data->mDisplayItems.end()) {
     DisplayItemData* did = iter->get();
     if (!did->mUsed) {
       // This item was visible, but isn't anymore.
       PaintedLayer* t = did->mLayer->AsPaintedLayer();
       if (t && did->mGeometry) {
 #ifdef MOZ_DUMP_PAINTING
         if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
-          printf_stderr("Invalidating unused display item (%i) belonging to frame %p from layer %p\n", did->mDisplayItemKey, did->mFrameList[0], t);
+          printf_stderr("Invalidating unused display item (%i) belonging to "
+                        "frame %p from layer %p\n",
+                        did->mDisplayItemKey,
+                        did->mFrameList[0],
+                        t);
         }
 #endif
         InvalidatePreTransformRect(t,
                                    did->mGeometry->ComputeInvalidationRegion(),
                                    did->mClip,
                                    GetLastPaintOffset(t),
                                    did->mTransform);
       }
@@ -2365,17 +2460,18 @@ FrameLayerBuilder::WillEndTransaction()
       if (iter != data->mDisplayItems.end() - 1) {
         std::iter_swap(iter, data->mDisplayItems.end() - 1);
         data->mDisplayItems.pop_back();
       } else {
         data->mDisplayItems.pop_back();
         break;
       }
 
-      // Don't increment iter because we still need to process the item which was moved.
+      // Don't increment iter because we still need to process the item which
+      // was moved.
 
     } else {
       ComputeGeometryChangeForItem(did);
       iter++;
     }
   }
 
   data->mInvalidateAllLayers = false;
@@ -2383,46 +2479,50 @@ FrameLayerBuilder::WillEndTransaction()
 
 /* static */ DisplayItemData*
 FrameLayerBuilder::GetDisplayItemDataForManager(nsDisplayItem* aItem,
                                                 LayerManager* aManager)
 {
   const SmallPointerArray<DisplayItemData>& array =
     aItem->Frame()->DisplayItemData();
   for (uint32_t i = 0; i < array.Length(); i++) {
-    DisplayItemData* item = DisplayItemData::AssertDisplayItemData(array.ElementAt(i));
+    DisplayItemData* item =
+      DisplayItemData::AssertDisplayItemData(array.ElementAt(i));
     if (item->mDisplayItemKey == aItem->GetPerFrameKey() &&
         item->mLayer->Manager() == aManager) {
       return item;
     }
   }
   return nullptr;
 }
 
 bool
-FrameLayerBuilder::HasRetainedDataFor(nsIFrame* aFrame, uint32_t aDisplayItemKey)
-{
-  const SmallPointerArray<DisplayItemData>& array =
-    aFrame->DisplayItemData();
+FrameLayerBuilder::HasRetainedDataFor(nsIFrame* aFrame,
+                                      uint32_t aDisplayItemKey)
+{
+  const SmallPointerArray<DisplayItemData>& array = aFrame->DisplayItemData();
   for (uint32_t i = 0; i < array.Length(); i++) {
-    if (DisplayItemData::AssertDisplayItemData(array.ElementAt(i))->mDisplayItemKey == aDisplayItemKey) {
+    if (DisplayItemData::AssertDisplayItemData(array.ElementAt(i))
+          ->mDisplayItemKey == aDisplayItemKey) {
       return true;
     }
   }
-  if (RefPtr<WebRenderUserData> data = GetWebRenderUserData<WebRenderFallbackData>(aFrame, aDisplayItemKey)) {
+  if (RefPtr<WebRenderUserData> data =
+        GetWebRenderUserData<WebRenderFallbackData>(aFrame, aDisplayItemKey)) {
     return true;
   }
   return false;
 }
 
 DisplayItemData*
-FrameLayerBuilder::GetOldLayerForFrame(nsIFrame* aFrame,
-                                       uint32_t aDisplayItemKey,
-                                       DisplayItemData* aOldData, /* = nullptr */
-                                       LayerManager* aOldLayerManager /* = nullptr */)
+FrameLayerBuilder::GetOldLayerForFrame(
+  nsIFrame* aFrame,
+  uint32_t aDisplayItemKey,
+  DisplayItemData* aOldData, /* = nullptr */
+  LayerManager* aOldLayerManager /* = nullptr */)
 {
   // If we need to build a new layer tree, then just refuse to recycle
   // anything.
   if (!mRetainingManager || mInvalidateAllLayers)
     return nullptr;
 
   MOZ_ASSERT(!aOldData || aOldLayerManager,
              "You must provide aOldLayerManager to check aOldData's validity.");
@@ -2458,42 +2558,46 @@ FrameLayerBuilder::GetOldLayerFor(nsDisp
   }
 
   return nullptr;
 }
 
 /* static */ DisplayItemData*
 FrameLayerBuilder::GetOldDataFor(nsDisplayItem* aItem)
 {
-  const SmallPointerArray<DisplayItemData>& array = aItem->Frame()->DisplayItemData();
+  const SmallPointerArray<DisplayItemData>& array =
+    aItem->Frame()->DisplayItemData();
 
   for (uint32_t i = 0; i < array.Length(); i++) {
-    DisplayItemData *data = DisplayItemData::AssertDisplayItemData(array.ElementAt(i));
+    DisplayItemData* data =
+      DisplayItemData::AssertDisplayItemData(array.ElementAt(i));
 
     if (data->mDisplayItemKey == aItem->GetPerFrameKey()) {
       return data;
     }
   }
   return nullptr;
 }
 
 // Reset state that should not persist when a layer is recycled.
 static void
-ResetLayerStateForRecycling(Layer* aLayer) {
+ResetLayerStateForRecycling(Layer* aLayer)
+{
   // Currently, this clears the mask layer and ancestor mask layers.
   // Other cleanup may be added here.
   aLayer->SetMaskLayer(nullptr);
   aLayer->SetAncestorMaskLayers({});
 }
 
 already_AddRefed<ColorLayer>
-ContainerState::CreateOrRecycleColorLayer(PaintedLayer *aPainted)
+ContainerState::CreateOrRecycleColorLayer(PaintedLayer* aPainted)
 {
   PaintedDisplayItemLayerUserData* data =
-      static_cast<PaintedDisplayItemLayerUserData*>(aPainted->GetUserData(&gPaintedDisplayItemLayerUserData));
+    static_cast<PaintedDisplayItemLayerUserData*>(
+      aPainted->GetUserData(&gPaintedDisplayItemLayerUserData));
   RefPtr<ColorLayer> layer = data->mColorLayer;
   if (layer) {
     ResetLayerStateForRecycling(layer);
     layer->ClearExtraDumpInfo();
   } else {
     // Create a new layer
     layer = mManager->CreateColorLayer();
     if (!layer)
@@ -2504,20 +2608,21 @@ ContainerState::CreateOrRecycleColorLaye
 
     // Remove other layer types we might have stored for this PaintedLayer
     data->mImageLayer = nullptr;
   }
   return layer.forget();
 }
 
 already_AddRefed<ImageLayer>
-ContainerState::CreateOrRecycleImageLayer(PaintedLayer *aPainted)
+ContainerState::CreateOrRecycleImageLayer(PaintedLayer* aPainted)
 {
   PaintedDisplayItemLayerUserData* data =
-      static_cast<PaintedDisplayItemLayerUserData*>(aPainted->GetUserData(&gPaintedDisplayItemLayerUserData));
+    static_cast<PaintedDisplayItemLayerUserData*>(
+      aPainted->GetUserData(&gPaintedDisplayItemLayerUserData));
   RefPtr<ImageLayer> layer = data->mImageLayer;
   if (layer) {
     ResetLayerStateForRecycling(layer);
     layer->ClearExtraDumpInfo();
   } else {
     // Create a new layer
     layer = mManager->CreateImageLayer();
     if (!layer)
@@ -2530,19 +2635,19 @@ ContainerState::CreateOrRecycleImageLaye
     data->mColorLayer = nullptr;
   }
   return layer.forget();
 }
 
 template<typename UserData>
 already_AddRefed<ImageLayer>
 ContainerState::CreateOrRecycleMaskImageLayerFor(
-    const MaskLayerKey& aKey,
-    UserData* (*aGetUserData)(Layer* aLayer),
-    void (*aSetDefaultUserData)(Layer* aLayer))
+  const MaskLayerKey& aKey,
+  UserData* (*aGetUserData)(Layer* aLayer),
+  void (*aSetDefaultUserData)(Layer* aLayer))
 {
   RefPtr<ImageLayer> result = mRecycledMaskImageLayers.Get(aKey);
 
   if (result && aGetUserData(result.get())) {
     mRecycledMaskImageLayers.Remove(aKey);
     aKey.mLayer->ClearExtraDumpInfo();
     // XXX if we use clip on mask layers, null it out here
   } else {
@@ -2567,53 +2672,60 @@ static const double SUBPIXEL_OFFSET_EPSI
  * is close to aOldResidual.
  */
 static int32_t
 RoundToMatchResidual(double aValue, double aOldResidual)
 {
   int32_t v = NSToIntRoundUp(aValue);
   double residual = aValue - v;
   if (aOldResidual < 0) {
-    if (residual > 0 && fabs(residual - 1.0 - aOldResidual) < SUBPIXEL_OFFSET_EPSILON) {
+    if (residual > 0 &&
+        fabs(residual - 1.0 - aOldResidual) < SUBPIXEL_OFFSET_EPSILON) {
       // Round up instead
       return int32_t(ceil(aValue));
     }
   } else if (aOldResidual > 0) {
-    if (residual < 0 && fabs(residual + 1.0 - aOldResidual) < SUBPIXEL_OFFSET_EPSILON) {
+    if (residual < 0 &&
+        fabs(residual + 1.0 - aOldResidual) < SUBPIXEL_OFFSET_EPSILON) {
       // Round down instead
       return int32_t(floor(aValue));
     }
   }
   return v;
 }
 
 static void
-ResetScrollPositionForLayerPixelAlignment(AnimatedGeometryRoot* aAnimatedGeometryRoot)
-{
-  nsIScrollableFrame* sf = nsLayoutUtils::GetScrollableFrameFor(*aAnimatedGeometryRoot);
+ResetScrollPositionForLayerPixelAlignment(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot)
+{
+  nsIScrollableFrame* sf =
+    nsLayoutUtils::GetScrollableFrameFor(*aAnimatedGeometryRoot);
   if (sf) {
     sf->ResetScrollPositionForLayerPixelAlignment();
   }
 }
 
 static void
-InvalidateEntirePaintedLayer(PaintedLayer* aLayer, AnimatedGeometryRoot* aAnimatedGeometryRoot, const char *aReason)
+InvalidateEntirePaintedLayer(PaintedLayer* aLayer,
+                             AnimatedGeometryRoot* aAnimatedGeometryRoot,
+                             const char* aReason)
 {
 #ifdef MOZ_DUMP_PAINTING
   if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
     printf_stderr("Invalidating entire layer %p: %s\n", aLayer, aReason);
   }
 #endif
   aLayer->InvalidateWholeLayer();
   aLayer->SetInvalidRectToVisibleRegion();
   ResetScrollPositionForLayerPixelAlignment(aAnimatedGeometryRoot);
 }
 
 LayerManager::PaintedLayerCreationHint
-ContainerState::GetLayerCreationHint(AnimatedGeometryRoot* aAnimatedGeometryRoot)
+ContainerState::GetLayerCreationHint(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot)
 {
   // Check whether the layer will be scrollable. This is used as a hint to
   // influence whether tiled layers are used or not.
 
   // Check creation hint inherited from our parent.
   if (mParameters.mLayerCreationHint == LayerManager::SCROLLABLE) {
     return LayerManager::SCROLLABLE;
   }
@@ -2631,89 +2743,101 @@ ContainerState::GetLayerCreationHint(Ani
     if (scrollable) {
       return LayerManager::SCROLLABLE;
     }
   }
   return LayerManager::NONE;
 }
 
 already_AddRefed<PaintedLayer>
-ContainerState::AttemptToRecyclePaintedLayer(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                             nsDisplayItem* aItem,
-                                             const nsPoint& aTopLeft,
-                                             const nsIFrame* aReferenceFrame)
+ContainerState::AttemptToRecyclePaintedLayer(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot,
+  nsDisplayItem* aItem,
+  const nsPoint& aTopLeft,
+  const nsIFrame* aReferenceFrame)
 {
   Layer* oldLayer = mLayerBuilder->GetOldLayerFor(aItem);
   if (!oldLayer || !oldLayer->AsPaintedLayer()) {
     return nullptr;
   }
 
-  if (!mPaintedLayersAvailableForRecycling.EnsureRemoved(oldLayer->AsPaintedLayer())) {
+  if (!mPaintedLayersAvailableForRecycling.EnsureRemoved(
+        oldLayer->AsPaintedLayer())) {
     // Not found.
     return nullptr;
   }
 
   // Try to recycle the layer.
   RefPtr<PaintedLayer> layer = oldLayer->AsPaintedLayer();
 
   // Check if the layer hint has changed and whether or not the layer should
   // be recreated because of it.
   if (!layer->IsOptimizedFor(GetLayerCreationHint(aAnimatedGeometryRoot))) {
     return nullptr;
   }
 
   bool didResetScrollPositionForLayerPixelAlignment = false;
-  PaintedDisplayItemLayerUserData* data =
-    RecyclePaintedLayer(layer, aAnimatedGeometryRoot,
-                        didResetScrollPositionForLayerPixelAlignment);
-  PreparePaintedLayerForUse(layer, data, aAnimatedGeometryRoot,
-                            aReferenceFrame, aTopLeft,
+  PaintedDisplayItemLayerUserData* data = RecyclePaintedLayer(
+    layer, aAnimatedGeometryRoot, didResetScrollPositionForLayerPixelAlignment);
+  PreparePaintedLayerForUse(layer,
+                            data,
+                            aAnimatedGeometryRoot,
+                            aReferenceFrame,
+                            aTopLeft,
                             didResetScrollPositionForLayerPixelAlignment);
 
   return layer.forget();
 }
 
-void ReleaseLayerUserData(void* aData)
+void
+ReleaseLayerUserData(void* aData)
 {
   PaintedDisplayItemLayerUserData* userData =
     static_cast<PaintedDisplayItemLayerUserData*>(aData);
   userData->Release();
 }
 
 already_AddRefed<PaintedLayer>
 ContainerState::CreatePaintedLayer(PaintedLayerData* aData)
 {
   LayerManager::PaintedLayerCreationHint creationHint =
     GetLayerCreationHint(aData->mAnimatedGeometryRoot);
 
   // Create a new painted layer
-  RefPtr<PaintedLayer> layer = mManager->CreatePaintedLayerWithHint(creationHint);
+  RefPtr<PaintedLayer> layer =
+    mManager->CreatePaintedLayerWithHint(creationHint);
   if (!layer) {
     return nullptr;
   }
 
   // Mark this layer as being used for painting display items
-  RefPtr<PaintedDisplayItemLayerUserData> userData = new PaintedDisplayItemLayerUserData();
+  RefPtr<PaintedDisplayItemLayerUserData> userData =
+    new PaintedDisplayItemLayerUserData();
   userData->mDisabledAlpha =
     mParameters.mDisableSubpixelAntialiasingInDescendants;
   userData.get()->AddRef();
-  layer->SetUserData(&gPaintedDisplayItemLayerUserData, userData, ReleaseLayerUserData);
+  layer->SetUserData(
+    &gPaintedDisplayItemLayerUserData, userData, ReleaseLayerUserData);
   ResetScrollPositionForLayerPixelAlignment(aData->mAnimatedGeometryRoot);
 
-  PreparePaintedLayerForUse(layer, userData, aData->mAnimatedGeometryRoot,
+  PreparePaintedLayerForUse(layer,
+                            userData,
+                            aData->mAnimatedGeometryRoot,
                             aData->mReferenceFrame,
-                            aData->mAnimatedGeometryRootOffset, true);
+                            aData->mAnimatedGeometryRootOffset,
+                            true);
 
   return layer.forget();
 }
 
 PaintedDisplayItemLayerUserData*
-ContainerState::RecyclePaintedLayer(PaintedLayer* aLayer,
-                                    AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                    bool& didResetScrollPositionForLayerPixelAlignment)
+ContainerState::RecyclePaintedLayer(
+  PaintedLayer* aLayer,
+  AnimatedGeometryRoot* aAnimatedGeometryRoot,
+  bool& didResetScrollPositionForLayerPixelAlignment)
 {
   // Clear clip rect and mask layer so we don't accidentally stay clipped.
   // We will reapply any necessary clipping.
   ResetLayerStateForRecycling(aLayer);
   aLayer->ClearExtraDumpInfo();
 
   PaintedDisplayItemLayerUserData* data =
     static_cast<PaintedDisplayItemLayerUserData*>(
@@ -2727,98 +2851,112 @@ ContainerState::RecyclePaintedLayer(Pain
   // This needs to be done before we update the PaintedLayer to its new
   // transform. See nsGfxScrollFrame::InvalidateInternal, where
   // we ensure that mInvalidPaintedContent is updated according to the
   // scroll position as of the most recent paint.
   if (!FuzzyEqual(data->mXScale, mParameters.mXScale, 0.00001f) ||
       !FuzzyEqual(data->mYScale, mParameters.mYScale, 0.00001f) ||
       data->mAppUnitsPerDevPixel != mAppUnitsPerDevPixel) {
 #ifdef MOZ_DUMP_PAINTING
-  if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
-    printf_stderr("Recycled layer %p changed scale\n", aLayer);
-  }
+    if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
+      printf_stderr("Recycled layer %p changed scale\n", aLayer);
+    }
 #endif
-    InvalidateEntirePaintedLayer(aLayer, aAnimatedGeometryRoot, "recycled layer changed state");
+    InvalidateEntirePaintedLayer(
+      aLayer, aAnimatedGeometryRoot, "recycled layer changed state");
     didResetScrollPositionForLayerPixelAlignment = true;
   }
   if (!data->mRegionToInvalidate.IsEmpty()) {
 #ifdef MOZ_DUMP_PAINTING
     if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
-      printf_stderr("Invalidating deleted frame content from layer %p\n", aLayer);
+      printf_stderr("Invalidating deleted frame content from layer %p\n",
+                    aLayer);
     }
 #endif
     aLayer->InvalidateRegion(data->mRegionToInvalidate);
 #ifdef MOZ_DUMP_PAINTING
     if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
       nsAutoCString str;
       AppendToString(str, data->mRegionToInvalidate);
       printf_stderr("Invalidating layer %p: %s\n", aLayer, str.get());
     }
 #endif
     data->mRegionToInvalidate.SetEmpty();
   }
   return data;
 }
 
 void
-ContainerState::PreparePaintedLayerForUse(PaintedLayer* aLayer,
-                                          PaintedDisplayItemLayerUserData* aData,
-                                          AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                          const nsIFrame* aReferenceFrame,
-                                          const nsPoint& aTopLeft,
-                                          bool didResetScrollPositionForLayerPixelAlignment)
+ContainerState::PreparePaintedLayerForUse(
+  PaintedLayer* aLayer,
+  PaintedDisplayItemLayerUserData* aData,
+  AnimatedGeometryRoot* aAnimatedGeometryRoot,
+  const nsIFrame* aReferenceFrame,
+  const nsPoint& aTopLeft,
+  bool didResetScrollPositionForLayerPixelAlignment)
 {
   aData->mXScale = mParameters.mXScale;
   aData->mYScale = mParameters.mYScale;
   aData->mLastAnimatedGeometryRootOrigin = aData->mAnimatedGeometryRootOrigin;
   aData->mAnimatedGeometryRootOrigin = aTopLeft;
   aData->mAppUnitsPerDevPixel = mAppUnitsPerDevPixel;
   aLayer->SetAllowResidualTranslation(mParameters.AllowResidualTranslation());
 
   aData->mLastPaintOffset = GetTranslationForPaintedLayer(aLayer);
   aData->mHasExplicitLastPaintOffset = true;
 
   // Set up transform so that 0,0 in the PaintedLayer corresponds to the
   // (pixel-snapped) top-left of the aAnimatedGeometryRoot.
-  nsPoint offset = (*aAnimatedGeometryRoot)->GetOffsetToCrossDoc(aReferenceFrame);
-  nscoord appUnitsPerDevPixel = (*aAnimatedGeometryRoot)->PresContext()->AppUnitsPerDevPixel();
+  nsPoint offset =
+    (*aAnimatedGeometryRoot)->GetOffsetToCrossDoc(aReferenceFrame);
+  nscoord appUnitsPerDevPixel =
+    (*aAnimatedGeometryRoot)->PresContext()->AppUnitsPerDevPixel();
   gfxPoint scaledOffset(
-      NSAppUnitsToDoublePixels(offset.x, appUnitsPerDevPixel)*mParameters.mXScale,
-      NSAppUnitsToDoublePixels(offset.y, appUnitsPerDevPixel)*mParameters.mYScale);
+    NSAppUnitsToDoublePixels(offset.x, appUnitsPerDevPixel) *
+      mParameters.mXScale,
+    NSAppUnitsToDoublePixels(offset.y, appUnitsPerDevPixel) *
+      mParameters.mYScale);
   // We call RoundToMatchResidual here so that the residual after rounding
   // is close to aData->mAnimatedGeometryRootPosition if possible.
-  nsIntPoint pixOffset(RoundToMatchResidual(scaledOffset.x, aData->mAnimatedGeometryRootPosition.x),
-                       RoundToMatchResidual(scaledOffset.y, aData->mAnimatedGeometryRootPosition.y));
+  nsIntPoint pixOffset(
+    RoundToMatchResidual(scaledOffset.x,
+                         aData->mAnimatedGeometryRootPosition.x),
+    RoundToMatchResidual(scaledOffset.y,
+                         aData->mAnimatedGeometryRootPosition.y));
   aData->mTranslation = pixOffset;
   pixOffset += mParameters.mOffset;
   Matrix matrix = Matrix::Translation(pixOffset.x, pixOffset.y);
   aLayer->SetBaseTransform(Matrix4x4::From2D(matrix));
 
   aData->mVisibilityComputedRegion.SetEmpty();
 
   // Calculate exact position of the top-left of the active scrolled root.
   // This might not be 0,0 due to the snapping in ScaleToNearestPixels.
-  gfxPoint animatedGeometryRootTopLeft = scaledOffset - ThebesPoint(matrix.GetTranslation()) + mParameters.mOffset;
+  gfxPoint animatedGeometryRootTopLeft =
+    scaledOffset - ThebesPoint(matrix.GetTranslation()) + mParameters.mOffset;
   const bool disableAlpha =
     mParameters.mDisableSubpixelAntialiasingInDescendants;
   if (aData->mDisabledAlpha != disableAlpha) {
     aData->mAnimatedGeometryRootPosition = animatedGeometryRootTopLeft;
-    InvalidateEntirePaintedLayer(aLayer, aAnimatedGeometryRoot, "change of subpixel-AA");
+    InvalidateEntirePaintedLayer(
+      aLayer, aAnimatedGeometryRoot, "change of subpixel-AA");
     aData->mDisabledAlpha = disableAlpha;
     return;
   }
 
-  // FIXME: Temporary workaround for bug 681192 and bug 724786.
+    // FIXME: Temporary workaround for bug 681192 and bug 724786.
 #ifndef MOZ_WIDGET_ANDROID
   // If it has changed, then we need to invalidate the entire layer since the
   // pixels in the layer buffer have the content at a (subpixel) offset
   // from what we need.
-  if (!animatedGeometryRootTopLeft.WithinEpsilonOf(aData->mAnimatedGeometryRootPosition, SUBPIXEL_OFFSET_EPSILON)) {
+  if (!animatedGeometryRootTopLeft.WithinEpsilonOf(
+        aData->mAnimatedGeometryRootPosition, SUBPIXEL_OFFSET_EPSILON)) {
     aData->mAnimatedGeometryRootPosition = animatedGeometryRootTopLeft;
-    InvalidateEntirePaintedLayer(aLayer, aAnimatedGeometryRoot, "subpixel offset");
+    InvalidateEntirePaintedLayer(
+      aLayer, aAnimatedGeometryRoot, "subpixel offset");
   } else if (didResetScrollPositionForLayerPixelAlignment) {
     aData->mAnimatedGeometryRootPosition = animatedGeometryRootTopLeft;
   }
 #else
   Unused << didResetScrollPositionForLayerPixelAlignment;
 #endif
 }
 
@@ -2843,88 +2981,95 @@ AppUnitsPerDevPixel(nsDisplayItem* aItem
 /**
  * Set the visible region for aLayer.
  * aOuterVisibleRegion is the visible region relative to the parent layer.
  * aLayerContentsVisibleRect, if non-null, is a rectangle in the layer's
  * own coordinate system to which the layer's visible region is restricted.
  * Consumes *aOuterVisibleRegion.
  */
 static void
-SetOuterVisibleRegion(Layer* aLayer, nsIntRegion* aOuterVisibleRegion,
+SetOuterVisibleRegion(Layer* aLayer,
+                      nsIntRegion* aOuterVisibleRegion,
                       const nsIntRect* aLayerContentsVisibleRect = nullptr,
                       bool aOuterUntransformed = false)
 {
   Matrix4x4 transform = aLayer->GetTransform();
   Matrix transform2D;
   if (aOuterUntransformed) {
     if (aLayerContentsVisibleRect) {
       aOuterVisibleRegion->And(*aOuterVisibleRegion,
                                *aLayerContentsVisibleRect);
     }
-  } else if (transform.Is2D(&transform2D) && !transform2D.HasNonIntegerTranslation()) {
+  } else if (transform.Is2D(&transform2D) &&
+             !transform2D.HasNonIntegerTranslation()) {
     aOuterVisibleRegion->MoveBy(-int(transform2D._31), -int(transform2D._32));
     if (aLayerContentsVisibleRect) {
-      aOuterVisibleRegion->And(*aOuterVisibleRegion, *aLayerContentsVisibleRect);
+      aOuterVisibleRegion->And(*aOuterVisibleRegion,
+                               *aLayerContentsVisibleRect);
     }
   } else {
     nsIntRect outerRect = aOuterVisibleRegion->GetBounds();
     // if 'transform' is not invertible, then nothing will be displayed
     // for the layer, so it doesn't really matter what we do here
-    Rect outerVisible(outerRect.x, outerRect.y,
-                      outerRect.width, outerRect.height);
+    Rect outerVisible(
+      outerRect.x, outerRect.y, outerRect.width, outerRect.height);
     transform.Invert();
 
     Rect layerContentsVisible = Rect::MaxIntRect();
 
     if (aLayerContentsVisibleRect) {
       NS_ASSERTION(aLayerContentsVisibleRect->width >= 0 &&
-                   aLayerContentsVisibleRect->height >= 0,
+                     aLayerContentsVisibleRect->height >= 0,
                    "Bad layer contents rectangle");
       // restrict to aLayerContentsVisibleRect before call GfxRectToIntRect,
       // in case layerVisible is extremely large (as it can be when
       // projecting through the inverse of a 3D transform)
-      layerContentsVisible = Rect(
-          aLayerContentsVisibleRect->x, aLayerContentsVisibleRect->y,
-          aLayerContentsVisibleRect->width, aLayerContentsVisibleRect->height);
+      layerContentsVisible = Rect(aLayerContentsVisibleRect->x,
+                                  aLayerContentsVisibleRect->y,
+                                  aLayerContentsVisibleRect->width,
+                                  aLayerContentsVisibleRect->height);
     }
 
     Rect layerVisible =
       transform.ProjectRectBounds(outerVisible, layerContentsVisible);
 
     layerVisible.RoundOut();
 
     IntRect intRect;
     if (!layerVisible.ToIntRect(&intRect)) {
       intRect = IntRect::MaxIntRect();
     }
 
     *aOuterVisibleRegion = intRect;
   }
 
-  aLayer->SetVisibleRegion(LayerIntRegion::FromUnknownRegion(*aOuterVisibleRegion));
+  aLayer->SetVisibleRegion(
+    LayerIntRegion::FromUnknownRegion(*aOuterVisibleRegion));
 }
 
 void
-ContainerState::SetOuterVisibleRegionForLayer(Layer* aLayer,
-                                              const nsIntRegion& aOuterVisibleRegion,
-                                              const nsIntRect* aLayerContentsVisibleRect,
-                                              bool aOuterUntransformed) const
+ContainerState::SetOuterVisibleRegionForLayer(
+  Layer* aLayer,
+  const nsIntRegion& aOuterVisibleRegion,
+  const nsIntRect* aLayerContentsVisibleRect,
+  bool aOuterUntransformed) const
 {
   nsIntRegion visRegion = aOuterVisibleRegion;
   if (!aOuterUntransformed) {
     visRegion.MoveBy(mParameters.mOffset);
   }
-  SetOuterVisibleRegion(aLayer, &visRegion, aLayerContentsVisibleRect,
-                        aOuterUntransformed);
+  SetOuterVisibleRegion(
+    aLayer, &visRegion, aLayerContentsVisibleRect, aOuterUntransformed);
 }
 
 nscolor
-ContainerState::FindOpaqueBackgroundColorInLayer(const PaintedLayerData* aData,
-                                                 const nsIntRect& aRect,
-                                                 bool* aOutIntersectsLayer) const
+ContainerState::FindOpaqueBackgroundColorInLayer(
+  const PaintedLayerData* aData,
+  const nsIntRect& aRect,
+  bool* aOutIntersectsLayer) const
 {
   *aOutIntersectsLayer = true;
 
   // Scan the candidate's display items.
   nsIntRect deviceRect = aRect;
   nsRect appUnitRect = ToAppUnits(deviceRect, mAppUnitsPerDevPixel);
   appUnitRect.ScaleInverseRoundOut(mParameters.mXScale, mParameters.mYScale);
 
@@ -2945,97 +3090,99 @@ ContainerState::FindOpaqueBackgroundColo
     bool snap;
     nsRect bounds = item->GetBounds(mBuilder, &snap);
     if (snap && mSnappingEnabled) {
       nsIntRect snappedBounds = ScaleToNearestPixels(bounds);
       if (!snappedBounds.Intersects(deviceRect))
         continue;
 
       if (!snappedBounds.Contains(deviceRect))
-        return NS_RGBA(0,0,0,0);
+        return NS_RGBA(0, 0, 0, 0);
 
     } else {
       // The layer's visible rect is already (close enough to) pixel
       // aligned, so no need to round out and in here.
       if (!bounds.Intersects(appUnitRect))
         continue;
 
       if (!bounds.Contains(appUnitRect))
-        return NS_RGBA(0,0,0,0);
+        return NS_RGBA(0, 0, 0, 0);
     }
 
     if (item->IsInvisibleInRect(appUnitRect)) {
       continue;
     }
 
     if (item->GetClip().IsRectAffectedByClip(deviceRect,
                                              mParameters.mXScale,
                                              mParameters.mYScale,
                                              mAppUnitsPerDevPixel)) {
-      return NS_RGBA(0,0,0,0);
+      return NS_RGBA(0, 0, 0, 0);
     }
 
     MOZ_ASSERT(!assignedItem.mHasOpacity && !assignedItem.mHasTransform);
     Maybe<nscolor> color = item->IsUniform(mBuilder);
 
     if (color && NS_GET_A(*color) == 255) {
       return *color;
     }
 
-    return NS_RGBA(0,0,0,0);
+    return NS_RGBA(0, 0, 0, 0);
   }
 
   *aOutIntersectsLayer = false;
-  return NS_RGBA(0,0,0,0);
+  return NS_RGBA(0, 0, 0, 0);
 }
 
 nscolor
-PaintedLayerDataNode::FindOpaqueBackgroundColor(const nsIntRegion& aTargetVisibleRegion,
-                                                int32_t aUnderIndex) const
+PaintedLayerDataNode::FindOpaqueBackgroundColor(
+  const nsIntRegion& aTargetVisibleRegion,
+  int32_t aUnderIndex) const
 {
   if (aUnderIndex == ABOVE_TOP) {
     aUnderIndex = mPaintedLayerDataStack.Length();
   }
   for (int32_t i = aUnderIndex - 1; i >= 0; --i) {
     const PaintedLayerData* candidate = &mPaintedLayerDataStack[i];
     if (candidate->VisibleAboveRegionIntersects(aTargetVisibleRegion)) {
       // Some non-PaintedLayer content between target and candidate; this is
       // hopeless
-      return NS_RGBA(0,0,0,0);
+      return NS_RGBA(0, 0, 0, 0);
     }
 
     if (!candidate->VisibleRegionIntersects(aTargetVisibleRegion)) {
       // The layer doesn't intersect our target, ignore it and move on
       continue;
     }
 
     bool intersectsLayer = true;
     nsIntRect rect = aTargetVisibleRegion.GetBounds();
     nscolor color = mTree.ContState().FindOpaqueBackgroundColorInLayer(
-                                        candidate, rect, &intersectsLayer);
+      candidate, rect, &intersectsLayer);
     if (!intersectsLayer) {
       continue;
     }
     return color;
   }
   if (mAllDrawingAboveBackground ||
-      !mVisibleAboveBackgroundRegion.Intersect(aTargetVisibleRegion).IsEmpty()) {
-    // Some non-PaintedLayer content is between this node's background and target.
-    return NS_RGBA(0,0,0,0);
+      !mVisibleAboveBackgroundRegion.Intersect(aTargetVisibleRegion)
+         .IsEmpty()) {
+    // Some non-PaintedLayer content is between this node's background and
+    // target.
+    return NS_RGBA(0, 0, 0, 0);
   }
   return FindOpaqueBackgroundColorInParentNode();
 }
 
 nscolor
 PaintedLayerDataNode::FindOpaqueBackgroundColorCoveringEverything() const
 {
-  if (!mPaintedLayerDataStack.IsEmpty() ||
-      mAllDrawingAboveBackground ||
+  if (!mPaintedLayerDataStack.IsEmpty() || mAllDrawingAboveBackground ||
       !mVisibleAboveBackgroundRegion.IsEmpty()) {
-    return NS_RGBA(0,0,0,0);
+    return NS_RGBA(0, 0, 0, 0);
   }
   return FindOpaqueBackgroundColorInParentNode();
 }
 
 nscolor
 PaintedLayerDataNode::FindOpaqueBackgroundColorInParentNode() const
 {
   if (mParent) {
@@ -3072,60 +3219,64 @@ PaintedLayerData::GetContainerForImageLa
 {
   if (!mImage) {
     return nullptr;
   }
 
   return mImage->GetContainer(mLayer->Manager(), aBuilder);
 }
 
-PaintedLayerDataNode::PaintedLayerDataNode(PaintedLayerDataTree& aTree,
-                                           PaintedLayerDataNode* aParent,
-                                           AnimatedGeometryRoot* aAnimatedGeometryRoot)
+PaintedLayerDataNode::PaintedLayerDataNode(
+  PaintedLayerDataTree& aTree,
+  PaintedLayerDataNode* aParent,
+  AnimatedGeometryRoot* aAnimatedGeometryRoot)
   : mTree(aTree)
   , mParent(aParent)
   , mAnimatedGeometryRoot(aAnimatedGeometryRoot)
   , mAllDrawingAboveBackground(false)
 {
-  MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDoc(mTree.Builder()->RootReferenceFrame(), *mAnimatedGeometryRoot));
-  mHasClip = mTree.IsClippedWithRespectToParentAnimatedGeometryRoot(mAnimatedGeometryRoot, &mClipRect);
+  MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDoc(
+    mTree.Builder()->RootReferenceFrame(), *mAnimatedGeometryRoot));
+  mHasClip = mTree.IsClippedWithRespectToParentAnimatedGeometryRoot(
+    mAnimatedGeometryRoot, &mClipRect);
 }
 
 PaintedLayerDataNode::~PaintedLayerDataNode()
 {
   MOZ_ASSERT(mPaintedLayerDataStack.IsEmpty());
   MOZ_ASSERT(mChildren.IsEmpty());
 }
 
 PaintedLayerDataNode*
-PaintedLayerDataNode::AddChildNodeFor(AnimatedGeometryRoot* aAnimatedGeometryRoot)
+PaintedLayerDataNode::AddChildNodeFor(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot)
 {
   MOZ_ASSERT(aAnimatedGeometryRoot->mParentAGR == mAnimatedGeometryRoot);
   UniquePtr<PaintedLayerDataNode> child =
     MakeUnique<PaintedLayerDataNode>(mTree, this, aAnimatedGeometryRoot);
   mChildren.AppendElement(std::move(child));
   return mChildren.LastElement().get();
 }
 
 template<typename NewPaintedLayerCallbackType>
 PaintedLayerData*
-PaintedLayerDataNode::FindPaintedLayerFor(const nsIntRect& aVisibleRect,
-                                          const bool aBackfaceHidden,
-                                          const ActiveScrolledRoot* aASR,
-                                          const DisplayItemClipChain* aClipChain,
-                                          NewPaintedLayerCallbackType aNewPaintedLayerCallback)
+PaintedLayerDataNode::FindPaintedLayerFor(
+  const nsIntRect& aVisibleRect,
+  const bool aBackfaceHidden,
+  const ActiveScrolledRoot* aASR,
+  const DisplayItemClipChain* aClipChain,
+  NewPaintedLayerCallbackType aNewPaintedLayerCallback)
 {
   if (!mPaintedLayerDataStack.IsEmpty()) {
     PaintedLayerData* lowestUsableLayer = nullptr;
     for (auto& data : Reversed(mPaintedLayerDataStack)) {
       if (data.mVisibleAboveRegion.Intersects(aVisibleRect)) {
         break;
       }
-      if (data.mBackfaceHidden == aBackfaceHidden &&
-          data.mASR == aASR &&
+      if (data.mBackfaceHidden == aBackfaceHidden && data.mASR == aASR &&
           data.mClipChain == aClipChain) {
         lowestUsableLayer = &data;
       }
       // Also check whether the event-regions intersect the visible rect,
       // unless we're in an inactive layer, in which case the event-regions
       // will be hoisted out into their own layer.
       // For performance reasons, we check the intersection with the bounds
       // of the event-regions.
@@ -3138,17 +3289,19 @@ PaintedLayerDataNode::FindPaintedLayerFo
       // can't possibly use any of the layers below it, so stop the search
       // now.
       //
       // If we're trying to minimize painted layer size and we don't
       // intersect the current visible region, then make sure we don't
       // use this painted layer.
       if (data.mVisibleRegion.Intersects(aVisibleRect)) {
         break;
-      } else if (gfxPrefs::LayoutSmallerPaintedLayers()) {
+      }
+
+      if (gfxPrefs::LayoutSmallerPaintedLayers()) {
         lowestUsableLayer = nullptr;
       }
     }
     if (lowestUsableLayer) {
       return lowestUsableLayer;
     }
   }
   PaintedLayerData* data = mPaintedLayerDataStack.AppendElement();
@@ -3164,17 +3317,18 @@ PaintedLayerDataNode::FinishChildrenInte
     if (mChildren[i]->Intersects(aRect)) {
       mChildren[i]->Finish(true);
       mChildren.RemoveElementAt(i);
     }
   }
 }
 
 void
-PaintedLayerDataNode::FinishAllChildren(bool aThisNodeNeedsAccurateVisibleAboveRegion)
+PaintedLayerDataNode::FinishAllChildren(
+  bool aThisNodeNeedsAccurateVisibleAboveRegion)
 {
   for (int32_t i = mChildren.Length() - 1; i >= 0; i--) {
     mChildren[i]->Finish(aThisNodeNeedsAccurateVisibleAboveRegion);
   }
   mChildren.Clear();
 }
 
 void
@@ -3193,49 +3347,51 @@ PaintedLayerDataNode::Finish(bool aParen
     }
   }
   mTree.NodeWasFinished(mAnimatedGeometryRoot);
 }
 
 void
 PaintedLayerDataNode::AddToVisibleAboveRegion(const nsIntRect& aRect)
 {
-  nsIntRegion& visibleAboveRegion = mPaintedLayerDataStack.IsEmpty()
-    ? mVisibleAboveBackgroundRegion
-    : mPaintedLayerDataStack.LastElement().mVisibleAboveRegion;
+  nsIntRegion& visibleAboveRegion =
+    mPaintedLayerDataStack.IsEmpty()
+      ? mVisibleAboveBackgroundRegion
+      : mPaintedLayerDataStack.LastElement().mVisibleAboveRegion;
   visibleAboveRegion.Or(visibleAboveRegion, aRect);
   visibleAboveRegion.SimplifyOutward(8);
 }
 
 void
 PaintedLayerDataNode::SetAllDrawingAbove()
 {
   PopAllPaintedLayerData();
   mAllDrawingAboveBackground = true;
   mVisibleAboveBackgroundRegion.SetEmpty();
 }
 
 void
 PaintedLayerDataNode::PopAllPaintedLayerData()
 {
-  for (int32_t index = mPaintedLayerDataStack.Length() - 1; index >= 0; index--) {
+  for (int32_t index = mPaintedLayerDataStack.Length() - 1; index >= 0;
+       index--) {
     PaintedLayerData& data = mPaintedLayerDataStack[index];
     mTree.ContState().FinishPaintedLayerData(data, [this, &data, index]() {
       return this->FindOpaqueBackgroundColor(data.mVisibleRegion, index);
     });
   }
   mPaintedLayerDataStack.Clear();
 }
 
 void
-PaintedLayerDataTree::InitializeForInactiveLayer(AnimatedGeometryRoot* aAnimatedGeometryRoot)
+PaintedLayerDataTree::InitializeForInactiveLayer(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot)
 {
   mForInactiveLayer = true;
   mRoot.emplace(*this, nullptr, aAnimatedGeometryRoot);
-
 }
 
 nsDisplayListBuilder*
 PaintedLayerDataTree::Builder() const
 {
   return mContainerState.Builder();
 }
 
@@ -3245,78 +3401,81 @@ PaintedLayerDataTree::Finish()
   if (mRoot) {
     mRoot->Finish(false);
   }
   MOZ_ASSERT(mNodes.Count() == 0);
   mRoot.reset();
 }
 
 void
-PaintedLayerDataTree::NodeWasFinished(AnimatedGeometryRoot* aAnimatedGeometryRoot)
+PaintedLayerDataTree::NodeWasFinished(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot)
 {
   mNodes.Remove(aAnimatedGeometryRoot);
 }
 
 void
-PaintedLayerDataTree::AddingOwnLayer(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                     const nsIntRect* aRect,
-                                     nscolor* aOutUniformBackgroundColor)
+PaintedLayerDataTree::AddingOwnLayer(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot,
+  const nsIntRect* aRect,
+  nscolor* aOutUniformBackgroundColor)
 {
   PaintedLayerDataNode* node = nullptr;
   if (mForInactiveLayer) {
     node = mRoot.ptr();
   } else {
     FinishPotentiallyIntersectingNodes(aAnimatedGeometryRoot, aRect);
     node = EnsureNodeFor(aAnimatedGeometryRoot);
   }
   if (aRect) {
     if (aOutUniformBackgroundColor) {
       *aOutUniformBackgroundColor = node->FindOpaqueBackgroundColor(*aRect);
     }
     node->AddToVisibleAboveRegion(*aRect);
   } else {
     if (aOutUniformBackgroundColor) {
-      *aOutUniformBackgroundColor = node->FindOpaqueBackgroundColorCoveringEverything();
+      *aOutUniformBackgroundColor =
+        node->FindOpaqueBackgroundColorCoveringEverything();
     }
     node->SetAllDrawingAbove();
   }
 }
 
 template<typename NewPaintedLayerCallbackType>
 PaintedLayerData*
-PaintedLayerDataTree::FindPaintedLayerFor(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                          const ActiveScrolledRoot* aASR,
-                                          const DisplayItemClipChain* aClipChain,
-                                          const nsIntRect& aVisibleRect,
-                                          const bool aBackfaceHidden,
-                                          NewPaintedLayerCallbackType aNewPaintedLayerCallback)
+PaintedLayerDataTree::FindPaintedLayerFor(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot,
+  const ActiveScrolledRoot* aASR,
+  const DisplayItemClipChain* aClipChain,
+  const nsIntRect& aVisibleRect,
+  const bool aBackfaceHidden,
+  NewPaintedLayerCallbackType aNewPaintedLayerCallback)
 {
   const nsIntRect* bounds = &aVisibleRect;
   PaintedLayerDataNode* node = nullptr;
   if (mForInactiveLayer) {
     node = mRoot.ptr();
   } else {
     FinishPotentiallyIntersectingNodes(aAnimatedGeometryRoot, bounds);
     node = EnsureNodeFor(aAnimatedGeometryRoot);
   }
 
-  PaintedLayerData* data =
-    node->FindPaintedLayerFor(aVisibleRect, aBackfaceHidden, aASR, aClipChain,
-                              aNewPaintedLayerCallback);
+  PaintedLayerData* data = node->FindPaintedLayerFor(
+    aVisibleRect, aBackfaceHidden, aASR, aClipChain, aNewPaintedLayerCallback);
   return data;
 }
 
 void
-PaintedLayerDataTree::FinishPotentiallyIntersectingNodes(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                                         const nsIntRect* aRect)
+PaintedLayerDataTree::FinishPotentiallyIntersectingNodes(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot,
+  const nsIntRect* aRect)
 {
   AnimatedGeometryRoot* ancestorThatIsChildOfCommonAncestor = nullptr;
-  PaintedLayerDataNode* ancestorNode =
-    FindNodeForAncestorAnimatedGeometryRoot(aAnimatedGeometryRoot,
-                                            &ancestorThatIsChildOfCommonAncestor);
+  PaintedLayerDataNode* ancestorNode = FindNodeForAncestorAnimatedGeometryRoot(
+    aAnimatedGeometryRoot, &ancestorThatIsChildOfCommonAncestor);
   if (!ancestorNode) {
     // None of our ancestors are in the tree. This should only happen if this
     // is the very first item we're looking at.
     MOZ_ASSERT(!mRoot);
     return;
   }
 
   if (ancestorNode->GetAnimatedGeometryRoot() == aAnimatedGeometryRoot) {
@@ -3331,92 +3490,102 @@ PaintedLayerDataTree::FinishPotentiallyI
     return;
   }
 
   // We have found an existing ancestor, but it's a proper ancestor of our
   // animated geometry root.
   // ancestorThatIsChildOfCommonAncestor is the last animated geometry root
   // encountered on the way up from aAnimatedGeometryRoot to ancestorNode.
   MOZ_ASSERT(ancestorThatIsChildOfCommonAncestor);
-  MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDoc(*ancestorThatIsChildOfCommonAncestor, *aAnimatedGeometryRoot));
-  MOZ_ASSERT(ancestorThatIsChildOfCommonAncestor->mParentAGR == ancestorNode->GetAnimatedGeometryRoot());
+  MOZ_ASSERT(nsLayoutUtils::IsAncestorFrameCrossDoc(
+    *ancestorThatIsChildOfCommonAncestor, *aAnimatedGeometryRoot));
+  MOZ_ASSERT(ancestorThatIsChildOfCommonAncestor->mParentAGR ==
+             ancestorNode->GetAnimatedGeometryRoot());
 
   // ancestorThatIsChildOfCommonAncestor is not in the tree yet!
   MOZ_ASSERT(!mNodes.Get(ancestorThatIsChildOfCommonAncestor));
 
   // We're about to add a node for ancestorThatIsChildOfCommonAncestor, so we
   // finish all intersecting siblings.
   nsIntRect clip;
-  if (IsClippedWithRespectToParentAnimatedGeometryRoot(ancestorThatIsChildOfCommonAncestor, &clip)) {
+  if (IsClippedWithRespectToParentAnimatedGeometryRoot(
+        ancestorThatIsChildOfCommonAncestor, &clip)) {
     ancestorNode->FinishChildrenIntersecting(clip);
   } else {
     ancestorNode->FinishAllChildren();
   }
 }
 
 PaintedLayerDataNode*
 PaintedLayerDataTree::EnsureNodeFor(AnimatedGeometryRoot* aAnimatedGeometryRoot)
 {
   MOZ_ASSERT(aAnimatedGeometryRoot);
   PaintedLayerDataNode* node = mNodes.Get(aAnimatedGeometryRoot);
   if (node) {
     return node;
   }
 
-  AnimatedGeometryRoot* parentAnimatedGeometryRoot = aAnimatedGeometryRoot->mParentAGR;
+  AnimatedGeometryRoot* parentAnimatedGeometryRoot =
+    aAnimatedGeometryRoot->mParentAGR;
   if (!parentAnimatedGeometryRoot) {
     MOZ_ASSERT(!mRoot);
     MOZ_ASSERT(*aAnimatedGeometryRoot == Builder()->RootReferenceFrame());
     mRoot.emplace(*this, nullptr, aAnimatedGeometryRoot);
     node = mRoot.ptr();
   } else {
-    PaintedLayerDataNode* parentNode = EnsureNodeFor(parentAnimatedGeometryRoot);
+    PaintedLayerDataNode* parentNode =
+      EnsureNodeFor(parentAnimatedGeometryRoot);
     MOZ_ASSERT(parentNode);
     node = parentNode->AddChildNodeFor(aAnimatedGeometryRoot);
   }
   MOZ_ASSERT(node);
   mNodes.Put(aAnimatedGeometryRoot, node);
   return node;
 }
 
 bool
-PaintedLayerDataTree::IsClippedWithRespectToParentAnimatedGeometryRoot(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                                                       nsIntRect* aOutClip)
+PaintedLayerDataTree::IsClippedWithRespectToParentAnimatedGeometryRoot(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot,
+  nsIntRect* aOutClip)
 {
   if (mForInactiveLayer) {
     return false;
   }
-  nsIScrollableFrame* scrollableFrame = nsLayoutUtils::GetScrollableFrameFor(*aAnimatedGeometryRoot);
+  nsIScrollableFrame* scrollableFrame =
+    nsLayoutUtils::GetScrollableFrameFor(*aAnimatedGeometryRoot);
   if (!scrollableFrame) {
     return false;
   }
   nsIFrame* scrollFrame = do_QueryFrame(scrollableFrame);
-  nsRect scrollPort = scrollableFrame->GetScrollPortRect() + Builder()->ToReferenceFrame(scrollFrame);
+  nsRect scrollPort = scrollableFrame->GetScrollPortRect() +
+                      Builder()->ToReferenceFrame(scrollFrame);
   *aOutClip = mContainerState.ScaleToNearestPixels(scrollPort);
   return true;
 }
 
 PaintedLayerDataNode*
-PaintedLayerDataTree::FindNodeForAncestorAnimatedGeometryRoot(AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                                              AnimatedGeometryRoot** aOutAncestorChild)
+PaintedLayerDataTree::FindNodeForAncestorAnimatedGeometryRoot(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot,
+  AnimatedGeometryRoot** aOutAncestorChild)
 {
   if (!aAnimatedGeometryRoot) {
     return nullptr;
   }
   PaintedLayerDataNode* node = mNodes.Get(aAnimatedGeometryRoot);
   if (node) {
     return node;
   }
   *aOutAncestorChild = aAnimatedGeometryRoot;
-  return FindNodeForAncestorAnimatedGeometryRoot(aAnimatedGeometryRoot->mParentAGR, aOutAncestorChild);
+  return FindNodeForAncestorAnimatedGeometryRoot(
+    aAnimatedGeometryRoot->mParentAGR, aOutAncestorChild);
 }
 
 static bool
 CanOptimizeAwayPaintedLayer(PaintedLayerData* aData,
-                           FrameLayerBuilder* aLayerBuilder)
+                            FrameLayerBuilder* aLayerBuilder)
 {
   if (!aLayerBuilder->IsBuildingRetainedLayers()) {
     return false;
   }
 
   // If there's no painted layer with valid content in it that we can reuse,
   // always create a color or image layer (and potentially throw away an
   // existing completely invalid painted layer).
@@ -3427,18 +3596,18 @@ CanOptimizeAwayPaintedLayer(PaintedLayer
   // There is an existing painted layer we can reuse. Throwing it away can make
   // compositing cheaper (see bug 946952), but it might cause us to re-allocate
   // the painted layer frequently due to an animation. So we only discard it if
   // we're in tree compression mode, which is triggered at a low frequency.
   return aLayerBuilder->CheckInLayerTreeCompressionMode();
 }
 
 #ifdef DEBUG
-static int32_t FindIndexOfLayerIn(nsTArray<NewLayerEntry>& aArray,
-                                  Layer* aLayer)
+static int32_t
+FindIndexOfLayerIn(nsTArray<NewLayerEntry>& aArray, Layer* aLayer)
 {
   for (uint32_t i = 0; i < aArray.Length(); ++i) {
     if (aArray[i].mLayer == aLayer) {
       return i;
     }
   }
   return -1;
 }
@@ -3451,30 +3620,29 @@ ContainerState::PrepareImageLayer(Painte
     aData->GetContainerForImageLayer(mBuilder);
   if (!imageContainer) {
     return nullptr;
   }
 
   RefPtr<ImageLayer> imageLayer = CreateOrRecycleImageLayer(aData->mLayer);
   imageLayer->SetContainer(imageContainer);
   aData->mImage->ConfigureLayer(imageLayer, mParameters);
-  imageLayer->SetPostScale(mParameters.mXScale,
-                           mParameters.mYScale);
+  imageLayer->SetPostScale(mParameters.mXScale, mParameters.mYScale);
 
   if (aData->mItemClip->HasClip()) {
-    ParentLayerIntRect clip =
-      ViewAs<ParentLayerPixel>(ScaleToNearestPixels(aData->mItemClip->GetClipRect()));
+    ParentLayerIntRect clip = ViewAs<ParentLayerPixel>(
+      ScaleToNearestPixels(aData->mItemClip->GetClipRect()));
     clip.MoveBy(ViewAs<ParentLayerPixel>(mParameters.mOffset));
     imageLayer->SetClipRect(Some(clip));
   } else {
     imageLayer->SetClipRect(Nothing());
   }
 
-  FLB_LOG_PAINTED_LAYER_DECISION(aData,
-                                 "  Selected image layer=%p\n", imageLayer.get());
+  FLB_LOG_PAINTED_LAYER_DECISION(
+    aData, "  Selected image layer=%p\n", imageLayer.get());
 
   return imageLayer.forget();
 }
 
 already_AddRefed<Layer>
 ContainerState::PrepareColorLayer(PaintedLayerData* aData)
 {
   RefPtr<ColorLayer> colorLayer = CreateOrRecycleColorLayer(aData->mLayer);
@@ -3485,18 +3653,18 @@ ContainerState::PrepareColorLayer(Painte
   colorLayer->SetPostScale(aData->mLayer->GetPostXScale(),
                            aData->mLayer->GetPostYScale());
 
   nsIntRect visibleRect = aData->mVisibleRegion.GetBounds();
   visibleRect.MoveBy(-GetTranslationForPaintedLayer(aData->mLayer));
   colorLayer->SetBounds(visibleRect);
   colorLayer->SetClipRect(Nothing());
 
-  FLB_LOG_PAINTED_LAYER_DECISION(aData,
-                                 "  Selected color layer=%p\n", colorLayer.get());
+  FLB_LOG_PAINTED_LAYER_DECISION(
+    aData, "  Selected color layer=%p\n", colorLayer.get());
 
   return colorLayer.forget();
 }
 
 static void
 SetBackfaceHiddenForLayer(bool aBackfaceHidden, Layer* aLayer)
 {
   if (aBackfaceHidden) {
@@ -3504,48 +3672,56 @@ SetBackfaceHiddenForLayer(bool aBackface
                             Layer::CONTENT_BACKFACE_HIDDEN);
   } else {
     aLayer->SetContentFlags(aLayer->GetContentFlags() &
                             ~Layer::CONTENT_BACKFACE_HIDDEN);
   }
 }
 
 template<typename FindOpaqueBackgroundColorCallbackType>
-void ContainerState::FinishPaintedLayerData(PaintedLayerData& aData, FindOpaqueBackgroundColorCallbackType aFindOpaqueBackgroundColor)
+void
+ContainerState::FinishPaintedLayerData(
+  PaintedLayerData& aData,
+  FindOpaqueBackgroundColorCallbackType aFindOpaqueBackgroundColor)
 {
   PaintedLayerData* data = &aData;
 
   if (!data->mLayer) {
     // No layer was recycled, so we create a new one.
     RefPtr<PaintedLayer> paintedLayer = CreatePaintedLayer(data);
     data->mLayer = paintedLayer;
 
     NS_ASSERTION(FindIndexOfLayerIn(mNewChildLayers, paintedLayer) < 0,
                  "Layer already in list???");
     mNewChildLayers[data->mNewChildLayersIndex].mLayer = paintedLayer.forget();
   }
 
-  PaintedDisplayItemLayerUserData* userData = GetPaintedDisplayItemLayerUserData(data->mLayer);
+  PaintedDisplayItemLayerUserData* userData =
+    GetPaintedDisplayItemLayerUserData(data->mLayer);
   NS_ASSERTION(userData, "where did our user data go?");
   userData->mLastItemCount = data->mAssignedDisplayItems.size();
 
   NewLayerEntry* newLayerEntry = &mNewChildLayers[data->mNewChildLayersIndex];
 
   RefPtr<Layer> layer;
   bool canOptimizeToImageLayer = data->CanOptimizeToImageLayer(mBuilder);
 
   FLB_LOG_PAINTED_LAYER_DECISION(data, "Selecting layer for pld=%p\n", data);
-  FLB_LOG_PAINTED_LAYER_DECISION(data, "  Solid=%i, hasImage=%c, canOptimizeAwayPaintedLayer=%i\n",
-          data->mIsSolidColorInVisibleRegion, canOptimizeToImageLayer ? 'y' : 'n',
-          CanOptimizeAwayPaintedLayer(data, mLayerBuilder));
+  FLB_LOG_PAINTED_LAYER_DECISION(
+    data,
+    "  Solid=%i, hasImage=%c, canOptimizeAwayPaintedLayer=%i\n",
+    data->mIsSolidColorInVisibleRegion,
+    canOptimizeToImageLayer ? 'y' : 'n',
+    CanOptimizeAwayPaintedLayer(data, mLayerBuilder));
 
   if ((data->mIsSolidColorInVisibleRegion || canOptimizeToImageLayer) &&
       CanOptimizeAwayPaintedLayer(data, mLayerBuilder)) {
-    NS_ASSERTION(!(data->mIsSolidColorInVisibleRegion && canOptimizeToImageLayer),
-                 "Can't be a solid color as well as an image!");
+    NS_ASSERTION(
+      !(data->mIsSolidColorInVisibleRegion && canOptimizeToImageLayer),
+      "Can't be a solid color as well as an image!");
 
     layer = canOptimizeToImageLayer ? PrepareImageLayer(data)
                                     : PrepareColorLayer(data);
 
     if (layer) {
       NS_ASSERTION(FindIndexOfLayerIn(mNewChildLayers, layer) < 0,
                    "Layer already in list???");
       NS_ASSERTION(newLayerEntry->mLayer == data->mLayer,
@@ -3569,76 +3745,83 @@ void ContainerState::FinishPaintedLayerD
       data->mLayer->SetEventRegions(EventRegions());
     }
   }
 
   if (!layer) {
     // We couldn't optimize to an image layer or a color layer above.
     layer = data->mLayer;
     layer->SetClipRect(Nothing());
-    FLB_LOG_PAINTED_LAYER_DECISION(data, "  Selected painted layer=%p\n", layer.get());
+    FLB_LOG_PAINTED_LAYER_DECISION(
+      data, "  Selected painted layer=%p\n", layer.get());
   }
 
   for (auto& item : data->mAssignedDisplayItems) {
-    MOZ_ASSERT(item.mItem->GetType() != DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO);
+    MOZ_ASSERT(item.mItem->GetType() !=
+               DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO);
 
     if (IsEffectEndMarker(item.mType)) {
       // Do not invalidate for end markers.
       continue;
     }
 
     InvalidateForLayerChange(item.mItem, data->mLayer, item.mDisplayItemData);
     mLayerBuilder->AddPaintedDisplayItem(data, item, *this, layer);
     item.mDisplayItemData = nullptr;
   }
 
   if (mLayerBuilder->IsBuildingRetainedLayers()) {
     newLayerEntry->mVisibleRegion = data->mVisibleRegion;
     newLayerEntry->mOpaqueRegion = data->mOpaqueRegion;
     newLayerEntry->mHideAllLayersBelow = data->mHideAllLayersBelow;
-    newLayerEntry->mOpaqueForAnimatedGeometryRootParent = data->mOpaqueForAnimatedGeometryRootParent;
+    newLayerEntry->mOpaqueForAnimatedGeometryRootParent =
+      data->mOpaqueForAnimatedGeometryRootParent;
   } else {
     SetOuterVisibleRegionForLayer(layer, data->mVisibleRegion);
   }
 
 #ifdef MOZ_DUMP_PAINTING
   if (!data->mLog.IsEmpty()) {
-    if (PaintedLayerData* containingPld = mLayerBuilder->GetContainingPaintedLayerData()) {
+    if (PaintedLayerData* containingPld =
+          mLayerBuilder->GetContainingPaintedLayerData()) {
       containingPld->mLayer->AddExtraDumpInfo(nsCString(data->mLog));
     } else {
       layer->AddExtraDumpInfo(nsCString(data->mLog));
     }
   }
 #endif
 
   mLayerBuilder->AddPaintedLayerItemsEntry(userData);
 
   nsIntRegion transparentRegion;
   transparentRegion.Sub(data->mVisibleRegion, data->mOpaqueRegion);
   bool isOpaque = transparentRegion.IsEmpty();
   // For translucent PaintedLayers, try to find an opaque background
   // color that covers the entire area beneath it so we can pull that
   // color into this layer to make it opaque.
   if (layer == data->mLayer) {
-    nscolor backgroundColor = NS_RGBA(0,0,0,0);
+    nscolor backgroundColor = NS_RGBA(0, 0, 0, 0);
     if (!isOpaque) {
       backgroundColor = aFindOpaqueBackgroundColor();
       if (NS_GET_A(backgroundColor) == 255) {
         isOpaque = true;
       }
     }
 
     // Store the background color
     if (userData->mForcedBackgroundColor != backgroundColor) {
-      // Invalidate the entire target PaintedLayer since we're changing
-      // the background color
+    // Invalidate the entire target PaintedLayer since we're changing
+    // the background color
 #ifdef MOZ_DUMP_PAINTING
       if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
-        printf_stderr("Forced background color has changed from #%08X to #%08X on layer %p\n",
-                      userData->mForcedBackgroundColor, backgroundColor, data->mLayer);
+        printf_stderr("Forced background color has changed from #%08X to #%08X "
+                      "on layer %p\n",
+                      userData->mForcedBackgroundColor,
+                      backgroundColor,
+                      data->mLayer);
         nsAutoCString str;
         AppendToString(str, data->mLayer->GetValidRegion());
         printf_stderr("Invalidating layer %p: %s\n", data->mLayer, str.get());
       }
 #endif
       data->mLayer->InvalidateWholeLayer();
     }
     userData->mForcedBackgroundColor = backgroundColor;
@@ -3663,38 +3846,40 @@ void ContainerState::FinishPaintedLayerD
     flags |= Layer::CONTENT_DISABLE_FLATTENING;
   }
   layer->SetContentFlags(flags);
 
   userData->mItems = std::move(data->mAssignedDisplayItems);
   userData->mContainerLayerFrame = GetContainerFrame();
 
   PaintedLayerData* containingPaintedLayerData =
-     mLayerBuilder->GetContainingPaintedLayerData();
+    mLayerBuilder->GetContainingPaintedLayerData();
   // If we're building layers for an inactive layer, the event regions are
   // clipped to the inactive layer's clip prior to being combined into the
   // event regions of the containing PLD.
   // For the dispatch-to-content and maybe-hit regions, rounded corners on
   // the clip are ignored, since these are approximate regions. For the
   // remaining regions, rounded corners in the clip cause the region to
   // be combined into the corresponding "imprecise" region of the
   // containing's PLD (e.g. the maybe-hit region instead of the hit region).
-  const DisplayItemClip* inactiveLayerClip = mLayerBuilder->GetInactiveLayerClip();
+  const DisplayItemClip* inactiveLayerClip =
+    mLayerBuilder->GetInactiveLayerClip();
   if (containingPaintedLayerData) {
     if (!data->mDispatchToContentHitRegion.GetBounds().IsEmpty()) {
       nsRect rect = nsLayoutUtils::TransformFrameRectToAncestor(
         mContainerReferenceFrame,
         data->mDispatchToContentHitRegion.GetBounds(),
         containingPaintedLayerData->mReferenceFrame);
       if (inactiveLayerClip) {
         rect = inactiveLayerClip->ApplyNonRoundedIntersection(rect);
       }
       containingPaintedLayerData->mDispatchToContentHitRegion.Or(
         containingPaintedLayerData->mDispatchToContentHitRegion, rect);
-      containingPaintedLayerData->mDispatchToContentHitRegion.SimplifyOutward(8);
+      containingPaintedLayerData->mDispatchToContentHitRegion.SimplifyOutward(
+        8);
       if (data->mDTCRequiresTargetConfirmation) {
         containingPaintedLayerData->mDTCRequiresTargetConfirmation = true;
       }
     }
     if (!data->mMaybeHitRegion.GetBounds().IsEmpty()) {
       nsRect rect = nsLayoutUtils::TransformFrameRectToAncestor(
         mContainerReferenceFrame,
         data->mMaybeHitRegion.GetBounds(),
@@ -3710,22 +3895,22 @@ void ContainerState::FinishPaintedLayerD
     nsLayoutUtils::TransformToAncestorAndCombineRegions(
       data->mHitRegion,
       mContainerReferenceFrame,
       containingPaintedLayerData->mReferenceFrame,
       &containingPaintedLayerData->mHitRegion,
       &containingPaintedLayerData->mMaybeHitRegion,
       &matrixCache,
       inactiveLayerClip);
-    // See the comment in nsDisplayList::AddFrame, where the touch action regions
-    // are handled. The same thing applies here.
+    // See the comment in nsDisplayList::AddFrame, where the touch action
+    // regions are handled. The same thing applies here.
     bool alreadyHadRegions =
-        !containingPaintedLayerData->mNoActionRegion.IsEmpty() ||
-        !containingPaintedLayerData->mHorizontalPanRegion.IsEmpty() ||
-        !containingPaintedLayerData->mVerticalPanRegion.IsEmpty();
+      !containingPaintedLayerData->mNoActionRegion.IsEmpty() ||
+      !containingPaintedLayerData->mHorizontalPanRegion.IsEmpty() ||
+      !containingPaintedLayerData->mVerticalPanRegion.IsEmpty();
     nsLayoutUtils::TransformToAncestorAndCombineRegions(
       data->mNoActionRegion,
       mContainerReferenceFrame,
       containingPaintedLayerData->mReferenceFrame,
       &containingPaintedLayerData->mNoActionRegion,
       &containingPaintedLayerData->mDispatchToContentHitRegion,
       &matrixCache,
       inactiveLayerClip);
@@ -3746,23 +3931,23 @@ void ContainerState::FinishPaintedLayerD
       &matrixCache,
       inactiveLayerClip);
     if (alreadyHadRegions) {
       containingPaintedLayerData->mDispatchToContentHitRegion.OrWith(
         containingPaintedLayerData->CombinedTouchActionRegion());
     }
   } else {
     EventRegions regions(
-        ScaleRegionToOutsidePixels(data->mHitRegion),
-        ScaleRegionToOutsidePixels(data->mMaybeHitRegion),
-        ScaleRegionToOutsidePixels(data->mDispatchToContentHitRegion),
-        ScaleRegionToOutsidePixels(data->mNoActionRegion),
-        ScaleRegionToOutsidePixels(data->mHorizontalPanRegion),
-        ScaleRegionToOutsidePixels(data->mVerticalPanRegion),
-        data->mDTCRequiresTargetConfirmation);
+      ScaleRegionToOutsidePixels(data->mHitRegion),
+      ScaleRegionToOutsidePixels(data->mMaybeHitRegion),
+      ScaleRegionToOutsidePixels(data->mDispatchToContentHitRegion),
+      ScaleRegionToOutsidePixels(data->mNoActionRegion),
+      ScaleRegionToOutsidePixels(data->mHorizontalPanRegion),
+      ScaleRegionToOutsidePixels(data->mVerticalPanRegion),
+      data->mDTCRequiresTargetConfirmation);
 
     Matrix mat = layer->GetTransform().As2D();
     mat.Invert();
     regions.ApplyTranslationAndScale(mat._31, mat._32, mat._11, mat._22);
 
     layer->SetEventRegions(regions);
   }
 
@@ -3826,47 +4011,51 @@ PaintedLayerData::Accumulate(ContainerSt
                              const nsRect& aContentRect,
                              const DisplayItemClip& aClip,
                              LayerState aLayerState,
                              nsDisplayList* aList,
                              DisplayItemEntryType aType,
                              nsTArray<size_t>& aOpacityIndices,
                              const RefPtr<TransformClipNode>& aTransform)
 {
-  FLB_LOG_PAINTED_LAYER_DECISION(this, "Accumulating dp=%s(%p), f=%p against pld=%p\n", aItem->Name(), aItem, aItem->Frame(), this);
+  FLB_LOG_PAINTED_LAYER_DECISION(
+    this,
+    "Accumulating dp=%s(%p), f=%p against pld=%p\n",
+    aItem->Name(),
+    aItem,
+    aItem->Frame(),
+    this);
 
   const bool hasOpacity = aOpacityIndices.Length() > 0;
 
   const DisplayItemClip* oldClip = mItemClip;
   mItemClip = &aClip;
 
   UpdateEffectStatus(aType, aOpacityIndices);
 
   if (IsEffectEndMarker(aType)) {
-    mAssignedDisplayItems.emplace_back(aItem, aLayerState, nullptr,
-                                       aContentRect, aType, hasOpacity,
-                                       aTransform);
+    mAssignedDisplayItems.emplace_back(
+      aItem, aLayerState, nullptr, aContentRect, aType, hasOpacity, aTransform);
     return;
   }
 
   bool clipMatches =
     (oldClip == mItemClip) || (oldClip && *oldClip == *mItemClip);
 
   DisplayItemData* currentData =
     aItem->HasMergedFrames() ? nullptr : aItem->GetDisplayItemData();
 
-  DisplayItemData* oldData =
-    aState->mLayerBuilder->GetOldLayerForFrame(aItem->Frame(),
-                                               aItem->GetPerFrameKey(),
-                                               currentData,
-                                               aItem->GetDisplayItemDataLayerManager());
-
-  mAssignedDisplayItems.emplace_back(aItem, aLayerState, oldData,
-                                     aContentRect, aType, hasOpacity,
-                                     aTransform);
+  DisplayItemData* oldData = aState->mLayerBuilder->GetOldLayerForFrame(
+    aItem->Frame(),
+    aItem->GetPerFrameKey(),
+    currentData,
+    aItem->GetDisplayItemDataLayerManager());
+
+  mAssignedDisplayItems.emplace_back(
+    aItem, aLayerState, oldData, aContentRect, aType, hasOpacity, aTransform);
 
   if (aState->mBuilder->NeedToForceTransparentSurfaceForItem(aItem)) {
     mForceTransparentSurface = true;
   }
 
   nsRect componentAlphaBounds;
   if (aState->mParameters.mDisableSubpixelAntialiasingInDescendants) {
     // Disable component alpha.
@@ -3883,56 +4072,62 @@ PaintedLayerData::Accumulate(ContainerSt
         MOZ_ASSERT(item.mType == DisplayItemEntryType::PUSH_OPACITY ||
                    item.mType == DisplayItemEntryType::PUSH_OPACITY_WITH_BG);
         item.mType = DisplayItemEntryType::PUSH_OPACITY_WITH_BG;
       }
     }
   }
 
   if (aItem->MustPaintOnContentSide()) {
-     mShouldPaintOnContentSide = true;
+    mShouldPaintOnContentSide = true;
   }
 
   if (aTransform && aType == DisplayItemEntryType::ITEM) {
     // Bounds transformed with axis-aligned transforms could be included in the
     // opaque region calculations. For simplicity, this is currently not done.
     return;
   }
 
   if (!mIsSolidColorInVisibleRegion && mOpaqueRegion.Contains(aVisibleRect) &&
       mVisibleRegion.Contains(aVisibleRect) && !mImage) {
     // A very common case! Most pages have a PaintedLayer with the page
     // background (opaque) visible and most or all of the page content over the
     // top of that background.
-    // The rest of this method won't do anything. mVisibleRegion and mOpaqueRegion
-    // don't need updating. mVisibleRegion contains aVisibleRect already,
-    // mOpaqueRegion contains aVisibleRect and therefore whatever the opaque
-    // region of the item is. mVisibleRegion must contain mOpaqueRegion
+    // The rest of this method won't do anything. mVisibleRegion and
+    // mOpaqueRegion don't need updating. mVisibleRegion contains aVisibleRect
+    // already, mOpaqueRegion contains aVisibleRect and therefore whatever the
+    // opaque region of the item is. mVisibleRegion must contain mOpaqueRegion
     // and therefore aVisibleRect.
     return;
   }
 
   nsIntRegion opaquePixels;
 
   // Active opacity means no opaque pixels.
   if (!hasOpacity) {
-    opaquePixels = aState->ComputeOpaqueRect(aItem, mAnimatedGeometryRoot, mASR,
-                                             aClip, aList, &mHideAllLayersBelow,
-                                             &mOpaqueForAnimatedGeometryRootParent);
+    opaquePixels =
+      aState->ComputeOpaqueRect(aItem,
+                                mAnimatedGeometryRoot,
+                                mASR,
+                                aClip,
+                                aList,
+                                &mHideAllLayersBelow,
+                                &mOpaqueForAnimatedGeometryRootParent);
     opaquePixels.AndWith(aVisibleRect);
   }
 
-  /* Mark as available for conversion to image layer if this is a nsDisplayImage and
-   * it's the only thing visible in this layer.
+  /* Mark as available for conversion to image layer if this is a nsDisplayImage
+   * and it's the only thing visible in this layer.
    */
   if (nsIntRegion(aVisibleRect).Contains(mVisibleRegion) &&
       opaquePixels.Contains(mVisibleRegion) &&
       aItem->SupportsOptimizingToImage()) {
     mImage = static_cast<nsDisplayImageContainer*>(aItem);
-    FLB_LOG_PAINTED_LAYER_DECISION(this, "  Tracking image: nsDisplayImageContainer covers the layer\n");
+    FLB_LOG_PAINTED_LAYER_DECISION(
+      this, "  Tracking image: nsDisplayImageContainer covers the layer\n");
   } else if (mImage) {
     FLB_LOG_PAINTED_LAYER_DECISION(this, "  No longer tracking image\n");
     mImage = nullptr;
   }
 
   bool isFirstVisibleItem = mVisibleRegion.IsEmpty();
 
   Maybe<nscolor> uniformColor;
@@ -3947,81 +4142,89 @@ PaintedLayerData::Accumulate(ContainerSt
     // Make sure that the visible area is covered by uniform pixels. In
     // particular this excludes cases where the edges of the item are not
     // pixel-aligned (thus the item will not be truly uniform).
     if (uniformColor) {
       bool snap;
       nsRect bounds = aItem->GetBounds(aState->mBuilder, &snap);
       if (!aState->ScaleToInsidePixels(bounds, snap).Contains(aVisibleRect)) {
         uniformColor = Nothing();
-        FLB_LOG_PAINTED_LAYER_DECISION(this, "  Display item does not cover the visible rect\n");
+        FLB_LOG_PAINTED_LAYER_DECISION(
+          this, "  Display item does not cover the visible rect\n");
       }
     }
     if (uniformColor) {
       if (isFirstVisibleItem) {
         // This color is all we have
         mSolidColor = *uniformColor;
         mIsSolidColorInVisibleRegion = true;
       } else if (mIsSolidColorInVisibleRegion &&
                  mVisibleRegion.IsEqual(nsIntRegion(aVisibleRect)) &&
                  clipMatches) {
         // we can just blend the colors together
         mSolidColor = NS_ComposeColors(mSolidColor, *uniformColor);
       } else {
-        FLB_LOG_PAINTED_LAYER_DECISION(this, "  Layer not a solid color: Can't blend colors togethers\n");
+        FLB_LOG_PAINTED_LAYER_DECISION(
+          this, "  Layer not a solid color: Can't blend colors togethers\n");
         mIsSolidColorInVisibleRegion = false;
       }
     } else {
-      FLB_LOG_PAINTED_LAYER_DECISION(this, "  Layer is not a solid color: Display item is not uniform over the visible bound\n");
+      FLB_LOG_PAINTED_LAYER_DECISION(this,
+                                     "  Layer is not a solid color: Display "
+                                     "item is not uniform over the visible "
+                                     "bound\n");
       mIsSolidColorInVisibleRegion = false;
     }
 
     mVisibleRegion.Or(mVisibleRegion, aVisibleRect);
     mVisibleRegion.SimplifyOutward(4);
   }
 
   if (!opaquePixels.IsEmpty()) {
     for (auto iter = opaquePixels.RectIter(); !iter.Done(); iter.Next()) {
       // We don't use SimplifyInward here since it's not defined exactly
       // what it will discard. For our purposes the most important case
       // is a large opaque background at the bottom of z-order (e.g.,
       // a canvas background), so we need to make sure that the first rect
       // we see doesn't get discarded.
       nsIntRegion tmp;
       tmp.Or(mOpaqueRegion, iter.Get());
-       // Opaque display items in chrome documents whose window is partially
-       // transparent are always added to the opaque region. This helps ensure
-       // that we get as much subpixel-AA as possible in the chrome.
-       if (tmp.GetNumRects() <= 4 || aItem->Frame()->PresContext()->IsChrome()) {
+      // Opaque display items in chrome documents whose window is partially
+      // transparent are always added to the opaque region. This helps ensure
+      // that we get as much subpixel-AA as possible in the chrome.
+      if (tmp.GetNumRects() <= 4 || aItem->Frame()->PresContext()->IsChrome()) {
         mOpaqueRegion = std::move(tmp);
       }
     }
   }
 
   if (!aState->mParameters.mDisableSubpixelAntialiasingInDescendants &&
       !componentAlphaBounds.IsEmpty()) {
     nsIntRect componentAlphaRect =
-      aState->ScaleToOutsidePixels(componentAlphaBounds, false).Intersect(aVisibleRect);
+      aState->ScaleToOutsidePixels(componentAlphaBounds, false)
+        .Intersect(aVisibleRect);
 
     if (!mOpaqueRegion.Contains(componentAlphaRect)) {
-      if (IsItemAreaInWindowOpaqueRegion(aState->mBuilder, aItem,
+      if (IsItemAreaInWindowOpaqueRegion(
+            aState->mBuilder,
+            aItem,
             componentAlphaBounds.Intersect(aItem->GetBuildingRect()))) {
         mNeedComponentAlpha = true;
       } else {
         aItem->DisableComponentAlpha();
       }
     }
   }
 
   // Ensure animated text does not get flattened, even if it forces other
   // content in the container to be layerized. The content backend might
   // not support subpixel positioning of text that animated transforms can
   // generate. bug 633097
   if (aState->mParameters.mInActiveTransformedSubtree &&
-       (mNeedComponentAlpha || !componentAlphaBounds.IsEmpty())) {
+      (mNeedComponentAlpha || !componentAlphaBounds.IsEmpty())) {
     mDisableFlattening = true;
   }
 }
 
 nsRegion
 PaintedLayerData::CombinedTouchActionRegion()
 {
   nsRegion result;
@@ -4030,18 +4233,18 @@ PaintedLayerData::CombinedTouchActionReg
   return result;
 }
 
 void
 PaintedLayerData::AccumulateHitTestInfo(ContainerState* aState,
                                         nsDisplayCompositorHitTestInfo* aItem,
                                         TransformClipNode* aTransform)
 {
-  FLB_LOG_PAINTED_LAYER_DECISION(this,
-    "Accumulating hit test info %p against pld=%p\n", aItem, this);
+  FLB_LOG_PAINTED_LAYER_DECISION(
+    this, "Accumulating hit test info %p against pld=%p\n", aItem, this);
 
   const mozilla::DisplayItemClip& clip = aItem->GetClip();
   nsRect area = clip.ApplyNonRoundedIntersection(aItem->Area());
   if (aTransform) {
     area = aTransform->TransformRect(area, aState->mAppUnitsPerDevPixel);
   }
   const mozilla::gfx::CompositorHitTestInfo hitTestInfo = aItem->HitTestInfo();
 
@@ -4065,28 +4268,29 @@ PaintedLayerData::AccumulateHitTestInfo(
     mMaybeHitRegion.OrWith(area);
   } else {
     mHitRegion.OrWith(area);
   }
 
   if (aItem->HitTestInfo() & CompositorHitTestInfo::eDispatchToContent) {
     mDispatchToContentHitRegion.OrWith(area);
 
-    if (aItem->HitTestInfo() & CompositorHitTestInfo::eRequiresTargetConfirmation) {
+    if (aItem->HitTestInfo() &
+        CompositorHitTestInfo::eRequiresTargetConfirmation) {
       mDTCRequiresTargetConfirmation = true;
     }
   }
 
   auto touchFlags = hitTestInfo & CompositorHitTestInfo::eTouchActionMask;
   if (touchFlags) {
-    // If there are multiple touch-action areas, there are multiple elements with
-    // touch-action properties. We don't know what the relationship is between
-    // those elements in terms of DOM ancestry, and so we don't know how to
-    // combine the regions properly. Instead, we just add all the areas to the
-    // dispatch-to-content region, so that the APZ knows to check with the
+    // If there are multiple touch-action areas, there are multiple elements
+    // with touch-action properties. We don't know what the relationship is
+    // between those elements in terms of DOM ancestry, and so we don't know how
+    // to combine the regions properly. Instead, we just add all the areas to
+    // the dispatch-to-content region, so that the APZ knows to check with the
     // main thread. See bug 1286957.
     if (mCollapsedTouchActions) {
       mDispatchToContentHitRegion.OrWith(area);
     } else if (touchFlags == CompositorHitTestInfo::eTouchActionMask) {
       // everything was disabled, so touch-action:none
       mNoActionRegion.OrWith(area);
     } else {
       // The event regions code does not store enough information to actually
@@ -4099,17 +4303,18 @@ PaintedLayerData::AccumulateHitTestInfo(
       // mVerticalPanRegion} were modified, and so the fact that case (2) should
       // have prevented double-tap-zooming was getting lost.
       // With CompositorHitTestInfo we can now represent that case correctly,
       // but only if we use CompositorHitTestInfo all the way to the compositor
       // (i.e. in the WebRender-enabled case). In the non-WebRender case where
       // we still use the event regions, we must collapse these two cases back
       // together. Or add another region to the event regions to fix this
       // properly.
-      if (touchFlags != CompositorHitTestInfo::eTouchActionDoubleTapZoomDisabled) {
+      if (touchFlags !=
+          CompositorHitTestInfo::eTouchActionDoubleTapZoomDisabled) {
         if (!(hitTestInfo & CompositorHitTestInfo::eTouchActionPanXDisabled)) {
           // pan-x is allowed
           mHorizontalPanRegion.OrWith(area);
         }
         if (!(hitTestInfo & CompositorHitTestInfo::eTouchActionPanYDisabled)) {
           // pan-y is allowed
           mVerticalPanRegion.OrWith(area);
         }
@@ -4117,25 +4322,25 @@ PaintedLayerData::AccumulateHitTestInfo(
         // the touch-action: manipulation case described above. To preserve the
         // existing behaviour, don't touch either mHorizontalPanRegion or
         // mVerticalPanRegion
       }
     }
   }
 
   if (!mCollapsedTouchActions) {
-    // If there are multiple touch-action areas, there are multiple elements with
-    // touch-action properties. We don't know what the relationship is between
-    // those elements in terms of DOM ancestry, and so we don't know how to
-    // combine the regions properly. Instead, we just add all the areas to the
-    // dispatch-to-content region, so that the APZ knows to check with the
+    // If there are multiple touch-action areas, there are multiple elements
+    // with touch-action properties. We don't know what the relationship is
+    // between those elements in terms of DOM ancestry, and so we don't know how
+    // to combine the regions properly. Instead, we just add all the areas to
+    // the dispatch-to-content region, so that the APZ knows to check with the
     // main thread. See bug 1286957.
     const int alreadyHadRegions = mNoActionRegion.GetNumRects() +
-      mHorizontalPanRegion.GetNumRects() +
-      mVerticalPanRegion.GetNumRects();
+                                  mHorizontalPanRegion.GetNumRects() +
+                                  mVerticalPanRegion.GetNumRects();
 
     if (alreadyHadRegions > 1) {
       mDispatchToContentHitRegion.OrWith(CombinedTouchActionRegion());
       mNoActionRegion.SetEmpty();
       mHorizontalPanRegion.SetEmpty();
       mVerticalPanRegion.SetEmpty();
       mCollapsedTouchActions = true;
     }
@@ -4143,31 +4348,31 @@ PaintedLayerData::AccumulateHitTestInfo(
 
   // Avoid quadratic performance as a result of the region growing to include
   // and arbitrarily large number of rects, which can happen on some pages.
   mMaybeHitRegion.SimplifyOutward(8);
   mDispatchToContentHitRegion.SimplifyOutward(8);
 
   // Calculate scaled versions of the bounds of mHitRegion and mMaybeHitRegion
   // for quick access in FindPaintedLayerFor().
-  mScaledHitRegionBounds =
-    aState->ScaleToOutsidePixels(mHitRegion.GetBounds());
+  mScaledHitRegionBounds = aState->ScaleToOutsidePixels(mHitRegion.GetBounds());
   mScaledMaybeHitRegionBounds =
     aState->ScaleToOutsidePixels(mMaybeHitRegion.GetBounds());
 }
 
 void
-ContainerState::NewPaintedLayerData(PaintedLayerData* aData,
-                                    AnimatedGeometryRoot* aAnimatedGeometryRoot,
-                                    const ActiveScrolledRoot* aASR,
-                                    const DisplayItemClipChain* aClipChain,
-                                    const ActiveScrolledRoot* aScrollMetadataASR,
-                                    const nsPoint& aTopLeft,
-                                    const nsIFrame* aReferenceFrame,
-                                    const bool aBackfaceHidden)
+ContainerState::NewPaintedLayerData(
+  PaintedLayerData* aData,
+  AnimatedGeometryRoot* aAnimatedGeometryRoot,
+  const ActiveScrolledRoot* aASR,
+  const DisplayItemClipChain* aClipChain,
+  const ActiveScrolledRoot* aScrollMetadataASR,
+  const nsPoint& aTopLeft,
+  const nsIFrame* aReferenceFrame,
+  const bool aBackfaceHidden)
 {
   aData->mAnimatedGeometryRoot = aAnimatedGeometryRoot;
   aData->mASR = aASR;
   aData->mClipChain = aClipChain;
   aData->mAnimatedGeometryRootOffset = aTopLeft;
   aData->mReferenceFrame = aReferenceFrame;
   aData->mBackfaceHidden = aBackfaceHidden;
 
@@ -4175,28 +4380,31 @@ ContainerState::NewPaintedLayerData(Pain
   NewLayerEntry* newLayerEntry = mNewChildLayers.AppendElement();
   newLayerEntry->mAnimatedGeometryRoot = aAnimatedGeometryRoot;
   newLayerEntry->mASR = aASR;
   newLayerEntry->mScrollMetadataASR = aScrollMetadataASR;
   newLayerEntry->mClipChain = aClipChain;
   // newLayerEntry->mOpaqueRegion is filled in later from
   // paintedLayerData->mOpaqueRegion, if necessary.
 
-  // Allocate another entry for this layer's optimization to ColorLayer/ImageLayer
+  // Allocate another entry for this layer's optimization to
+  // ColorLayer/ImageLayer
   mNewChildLayers.AppendElement();
 }
 
 #ifdef MOZ_DUMP_PAINTING
 static void
 DumpPaintedImage(nsDisplayItem* aItem, SourceSurface* aSurface)
 {
   nsCString string(aItem->Name());
   string.Append('-');
   string.AppendInt((uint64_t)aItem);
-  fprintf_stderr(gfxUtils::sDumpPaintFile, "<script>array[\"%s\"]=\"", string.BeginReading());
+  fprintf_stderr(gfxUtils::sDumpPaintFile,
+                 "<script>array[\"%s\"]=\"",
+                 string.BeginReading());
   gfxUtils::DumpAsDataURI(aSurface, gfxUtils::sDumpPaintFile);
   fprintf_stderr(gfxUtils::sDumpPaintFile, "\";</script>\n");
 }
 #endif
 
 static void
 PaintInactiveLayer(nsDisplayListBuilder* aBuilder,
                    LayerManager* aManager,
@@ -4211,93 +4419,101 @@ PaintInactiveLayer(nsDisplayListBuilder*
 #ifdef MOZ_DUMP_PAINTING
   int32_t appUnitsPerDevPixel = AppUnitsPerDevPixel(aItem);
   nsIntRect itemVisibleRect =
     aItem->GetPaintRect().ToOutsidePixels(appUnitsPerDevPixel);
 
   RefPtr<DrawTarget> tempDT;
   if (gfxEnv::DumpPaint()) {
     tempDT = gfxPlatform::GetPlatform()->CreateOffscreenContentDrawTarget(
-                                      itemVisibleRect.Size(),
-                                      SurfaceFormat::B8G8R8A8);
+      itemVisibleRect.Size(), SurfaceFormat::B8G8R8A8);
     if (tempDT) {
       context = gfxContext::CreateOrNull(tempDT);
       if (!context) {
         // Leave this as crash, it's in the debugging code, we want to know
-        gfxDevCrash(LogReason::InvalidContext) << "PaintInactive context problem " << gfx::hexa(tempDT);
+        gfxDevCrash(LogReason::InvalidContext)
+          << "PaintInactive context problem " << gfx::hexa(tempDT);
         return;
       }
-      context->SetMatrix(Matrix::Translation(-itemVisibleRect.x,
-                                             -itemVisibleRect.y));
+      context->SetMatrix(
+        Matrix::Translation(-itemVisibleRect.x, -itemVisibleRect.y));
     }
   }
 #endif
   basic->BeginTransaction();
   basic->SetTarget(context);
 
   if (aItem->GetType() == DisplayItemType::TYPE_MASK) {
     static_cast<nsDisplayMask*>(aItem)->PaintAsLayer(aBuilder, aCtx, basic);
     if (basic->InTransaction()) {
       basic->AbortTransaction();
     }
-  } else if (aItem->GetType() == DisplayItemType::TYPE_FILTER){
+  } else if (aItem->GetType() == DisplayItemType::TYPE_FILTER) {
     static_cast<nsDisplayFilter*>(aItem)->PaintAsLayer(aBuilder, aCtx, basic);
     if (basic->InTransaction()) {
       basic->AbortTransaction();
     }
   } else {
     basic->EndTransaction(FrameLayerBuilder::DrawPaintedLayer, aBuilder);
   }
-  FrameLayerBuilder *builder = static_cast<FrameLayerBuilder*>(basic->GetUserData(&gLayerManagerLayerBuilder));
+  FrameLayerBuilder* builder = static_cast<FrameLayerBuilder*>(
+    basic->GetUserData(&gLayerManagerLayerBuilder));
   if (builder) {
     builder->DidEndTransaction();
   }
 
   basic->SetTarget(nullptr);
 
 #ifdef MOZ_DUMP_PAINTING
   if (gfxEnv::DumpPaint() && tempDT) {
     RefPtr<SourceSurface> surface = tempDT->Snapshot();
     DumpPaintedImage(aItem, surface);
 
     DrawTarget* drawTarget = aContext->GetDrawTarget();
-    Rect rect(itemVisibleRect.x, itemVisibleRect.y,
-              itemVisibleRect.width, itemVisibleRect.height);
-    drawTarget->DrawSurface(surface, rect, Rect(Point(0,0), rect.Size()));
+    Rect rect(itemVisibleRect.x,
+              itemVisibleRect.y,
+              itemVisibleRect.width,
+              itemVisibleRect.height);
+    drawTarget->DrawSurface(surface, rect, Rect(Point(0, 0), rect.Size()));
 
     aItem->SetPainted();
   }
 #endif
 }
 
 nsRect
-ContainerState::GetDisplayPortForAnimatedGeometryRoot(AnimatedGeometryRoot* aAnimatedGeometryRoot)
+ContainerState::GetDisplayPortForAnimatedGeometryRoot(
+  AnimatedGeometryRoot* aAnimatedGeometryRoot)
 {
   if (mLastDisplayPortAGR == aAnimatedGeometryRoot) {
     return mLastDisplayPortRect;
   }
 
   mLastDisplayPortAGR = aAnimatedGeometryRoot;
 
-  nsIScrollableFrame* sf = nsLayoutUtils::GetScrollableFrameFor(*aAnimatedGeometryRoot);
-  if (sf == nullptr || nsLayoutUtils::UsesAsyncScrolling(*aAnimatedGeometryRoot)) {
+  nsIScrollableFrame* sf =
+    nsLayoutUtils::GetScrollableFrameFor(*aAnimatedGeometryRoot);
+  if (sf == nullptr ||
+      nsLayoutUtils::UsesAsyncScrolling(*aAnimatedGeometryRoot)) {
     mLastDisplayPortRect = nsRect();
     return mLastDisplayPortRect;
   }
 
   bool usingDisplayport =
-    nsLayoutUtils::GetDisplayPort((*aAnimatedGeometryRoot)->GetContent(), &mLastDisplayPortRect,
+    nsLayoutUtils::GetDisplayPort((*aAnimatedGeometryRoot)->GetContent(),
+                                  &mLastDisplayPortRect,
                                   RelativeTo::ScrollFrame);
   if (!usingDisplayport) {
     // No async scrolling, so all that matters is that the layer contents
     // cover the scrollport.
     mLastDisplayPortRect = sf->GetScrollPortRect();
   }
   nsIFrame* scrollFrame = do_QueryFrame(sf);
-  mLastDisplayPortRect += scrollFrame->GetOffsetToCrossDoc(mContainerReferenceFrame);
+  mLastDisplayPortRect +=
+    scrollFrame->GetOffsetToCrossDoc(mContainerReferenceFrame);
   return mLastDisplayPortRect;
 }
 
 nsIntRegion
 ContainerState::ComputeOpaqueRect(nsDisplayItem* aItem,
                                   AnimatedGeometryRoot* aAnimatedGeometryRoot,
                                   const ActiveScrolledRoot* aASR,
                                   const DisplayItemClip& aClip,
@@ -4313,18 +4529,17 @@ ContainerState::ComputeOpaqueRect(nsDisp
 
   nsIntRegion opaquePixels;
   nsRegion opaqueClipped;
   for (auto iter = opaque.RectIter(); !iter.Done(); iter.Next()) {
     opaqueClipped.Or(opaqueClipped,
                      aClip.ApproximateIntersectInward(iter.Get()));
   }
   if (aAnimatedGeometryRoot == mContainerAnimatedGeometryRoot &&
-      aASR == mContainerASR &&
-      opaqueClipped.Contains(mContainerBounds)) {
+      aASR == mContainerASR && opaqueClipped.Contains(mContainerBounds)) {
     *aHideAllLayersBelow = true;
     aList->SetIsOpaque();
   }
   // Add opaque areas to the "exclude glass" region. Only do this when our
   // container layer is going to be the rootmost layer, otherwise transforms
   // etc will mess us up (and opaque contributions from other containers are
   // not needed).
   if (!nsLayoutUtils::GetCrossDocParentFrame(mContainerFrame)) {
@@ -4346,54 +4561,57 @@ ContainerState::ComputeOpaqueRect(nsDisp
 }
 
 Maybe<size_t>
 ContainerState::SetupMaskLayerForScrolledClip(Layer* aLayer,
                                               const DisplayItemClip& aClip)
 {
   if (aClip.GetRoundedRectCount() > 0) {
     Maybe<size_t> maskLayerIndex = Some(aLayer->GetAncestorMaskLayerCount());
-    if (RefPtr<Layer> maskLayer = CreateMaskLayer(aLayer, aClip, maskLayerIndex)) {
+    if (RefPtr<Layer> maskLayer =
+          CreateMaskLayer(aLayer, aClip, maskLayerIndex)) {
       aLayer->AddAncestorMaskLayer(maskLayer);
       return maskLayerIndex;
     }
     // Fall through to |return Nothing()|.
   }
   return Nothing();
 }
 
 static const ActiveScrolledRoot*
-GetASRForPerspective(const ActiveScrolledRoot* aASR, nsIFrame* aPerspectiveFrame)
+GetASRForPerspective(const ActiveScrolledRoot* aASR,
+                     nsIFrame* aPerspectiveFrame)
 {
   for (const ActiveScrolledRoot* asr = aASR; asr; asr = asr->mParent) {
     nsIFrame* scrolledFrame = asr->mScrollableFrame->GetScrolledFrame();
-    if (nsLayoutUtils::IsAncestorFrameCrossDoc(scrolledFrame, aPerspectiveFrame)) {
+    if (nsLayoutUtils::IsAncestorFrameCrossDoc(scrolledFrame,
+                                               aPerspectiveFrame)) {
       return asr;
     }
   }
   return nullptr;
 }
 
 static CSSMaskLayerUserData*
 GetCSSMaskLayerUserData(Layer* aMaskLayer)
 {
   if (!aMaskLayer) {
     return nullptr;
   }
 
-  return static_cast<CSSMaskLayerUserData*>(aMaskLayer->GetUserData(&gCSSMaskLayerUserData));
+  return static_cast<CSSMaskLayerUserData*>(
+    aMaskLayer->GetUserData(&gCSSMaskLayerUserData));
 }
 
 static void
 SetCSSMaskLayerUserData(Layer* aMaskLayer)
 {
   MOZ_ASSERT(aMaskLayer);
 
-  aMaskLayer->SetUserData(&gCSSMaskLayerUserData,
-                          new CSSMaskLayerUserData());
+  aMaskLayer->SetUserData(&gCSSMaskLayerUserData, new CSSMaskLayerUserData());
 }
 
 void
 ContainerState::SetupMaskLayerForCSSMask(Layer* aLayer,
                                          nsDisplayMask* aMaskItem)
 {
   RefPtr<ImageLayer> maskLayer =
     CreateOrRecycleMaskImageLayerFor(MaskLayerKey(aLayer, Nothing()),
@@ -4411,17 +4629,18 @@ ContainerState::SetupMaskLayerForCSSMask
   // each time is required.
   Matrix4x4 matrix;
   matrix.PreTranslate(itemRect.x, itemRect.y, 0);
   matrix.PreTranslate(mParameters.mOffset.x, mParameters.mOffset.y, 0);
   maskLayer->SetBaseTransform(matrix);
 
   nsPoint maskLayerOffset = aMaskItem->ToReferenceFrame() - bounds.TopLeft();
 
-  CSSMaskLayerUserData newUserData(aMaskItem->Frame(), itemRect, maskLayerOffset);
+  CSSMaskLayerUserData newUserData(
+    aMaskItem->Frame(), itemRect, maskLayerOffset);
   nsRect dirtyRect;
   if (!aMaskItem->IsInvalid(dirtyRect) && *oldUserData == newUserData) {
     aLayer->SetMaskLayer(maskLayer);
     return;
   }
 
   int32_t maxSize = mManager->GetMaxTextureSize();
   IntSize surfaceSize(std::min(itemRect.width, maxSize),
@@ -4436,17 +4655,18 @@ ContainerState::SetupMaskLayerForCSSMask
   RefPtr<DrawTarget> dt = imageData.CreateDrawTarget();
   if (!dt || !dt->IsValid()) {
     NS_WARNING("Could not create DrawTarget for mask layer.");
     return;
   }
 
   RefPtr<gfxContext> maskCtx = gfxContext::CreateOrNull(dt);
   maskCtx->SetMatrix(Matrix::Translation(-itemRect.TopLeft()));
-  maskCtx->Multiply(gfxMatrix::Scaling(mParameters.mXScale, mParameters.mYScale));
+  maskCtx->Multiply(
+    gfxMatrix::Scaling(mParameters.mXScale, mParameters.mYScale));
 
   bool isPaintFinished = aMaskItem->PaintMask(mBuilder, maskCtx);
 
   RefPtr<ImageContainer> imgContainer =
     imageData.CreateImageAndImageContainer();
   if (!imgContainer) {
     return;
   }
@@ -4498,40 +4718,39 @@ ProcessDisplayItemMarker(DisplayItemEntr
  * of visible rects for some PaintedLayers is deferred until the calling
  * of ContainerState::Finish.
  */
 void
 ContainerState::ProcessDisplayItems(nsDisplayList* aList)
 {
   AUTO_PROFILER_LABEL("ContainerState::ProcessDisplayItems", GRAPHICS);
 
-  nsPoint topLeft(0,0);
+  nsPoint topLeft(0, 0);
 
   int32_t maxLayers = gfxPrefs::MaxActiveLayers();
   int layerCount = 0;
 
   if (!mManager->IsWidgetLayerManager()) {
-    mPaintedLayerDataTree.InitializeForInactiveLayer(mContainerAnimatedGeometryRoot);
+    mPaintedLayerDataTree.InitializeForInactiveLayer(
+      mContainerAnimatedGeometryRoot);
   }
 
   AnimatedGeometryRoot* lastAnimatedGeometryRoot = nullptr;
   nsPoint lastTopLeft;
 
   // Tracks the PaintedLayerData that the item will be accumulated in, if it is
   // non-null.
   PaintedLayerData* selectedLayer = nullptr;
   AutoTArray<size_t, 2> opacityIndices;
 
   AnimatedGeometryRoot* containerAGR = nullptr;
   const ActiveScrolledRoot* containerASR = nullptr;
   RefPtr<TransformClipNode> transformNode = nullptr;
 
-  const auto InTransform = [&]() {
-    return transformNode;
-  };
+  const auto InTransform = [&]() { return transformNode; };
 
   const auto InOpacity = [&]() {
     return selectedLayer && opacityIndices.Length() > 0;
   };
 
   FLBDisplayItemIterator iter(mBuilder, aList, this);
   while (iter.HasNext()) {
     DisplayItemEntry e = iter.GetNextEntry();
@@ -4557,17 +4776,18 @@ ContainerState::ProcessDisplayItems(nsDi
         selectedLayer->AccumulateHitTestInfo(this, hitTestInfo, transformNode);
         continue;
       }
     }
 
     MOZ_ASSERT(item->GetType() != DisplayItemType::TYPE_WRAP_LIST);
 
     NS_ASSERTION(mAppUnitsPerDevPixel == AppUnitsPerDevPixel(item),
-      "items in a container layer should all have the same app units per dev pixel");
+                 "items in a container layer should all have the same app "
+                 "units per dev pixel");
 
     if (mBuilder->NeedToForceTransparentSurfaceForItem(item)) {
       aList->SetNeedsTransparentSurface();
     }
 
     if (mParameters.mForEventsAndPluginsOnly && !item->GetChildren() &&
         (itemType != DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO &&
          itemType != DisplayItemType::TYPE_PLUGIN)) {
@@ -4611,31 +4831,41 @@ ContainerState::ProcessDisplayItems(nsDi
       itemASR = mContainerASR;
       item->FuseClipChainUpTo(mBuilder, mContainerASR);
     }
 
     const DisplayItemClip& itemClip = item->GetClip();
 
     if (inEffect && marker == DisplayItemEntryType::ITEM) {
       MOZ_ASSERT(selectedLayer);
-      selectedLayer->Accumulate(this, item, nsIntRect(), nsRect(),
-                                itemClip, layerState, aList, marker,
-                                opacityIndices, transformNode);
+      selectedLayer->Accumulate(this,
+                                item,
+                                nsIntRect(),
+                                nsRect(),
+                                itemClip,
+                                layerState,
+                                aList,
+                                marker,
+                                opacityIndices,
+                                transformNode);
       continue;
     }
 
     if (animatedGeometryRoot == lastAnimatedGeometryRoot) {
       topLeft = lastTopLeft;
     } else {
-      lastTopLeft = topLeft = (*animatedGeometryRoot)->GetOffsetToCrossDoc(mContainerReferenceFrame);
+      lastTopLeft = topLeft =
+        (*animatedGeometryRoot)->GetOffsetToCrossDoc(mContainerReferenceFrame);
       lastAnimatedGeometryRoot = animatedGeometryRoot;
     }
 
     const ActiveScrolledRoot* scrollMetadataASR =
-        layerClipChain ? ActiveScrolledRoot::PickDescendant(itemASR, layerClipChain->mASR) : itemASR;
+      layerClipChain
+        ? ActiveScrolledRoot::PickDescendant(itemASR, layerClipChain->mASR)
+        : itemASR;
 
     const bool prerenderedTransform =
       itemType == DisplayItemType::TYPE_TRANSFORM &&
       static_cast<nsDisplayTransform*>(item)->MayBeAnimated(mBuilder);
 
     bool snap;
     nsRect itemContent = item->GetBounds(mBuilder, &snap);
 
@@ -4659,45 +4889,43 @@ ContainerState::ProcessDisplayItems(nsDi
       clipRect.MoveBy(ViewAs<ParentLayerPixel>(mParameters.mOffset));
     }
 
     if (marker == DisplayItemEntryType::POP_TRANSFORM) {
       MOZ_ASSERT(transformNode);
       transformNode = transformNode->Parent();
     }
 
-
     if (transformNode) {
       // If we are within transform, transform itemContent and itemDrawRect.
       MOZ_ASSERT(transformNode);
 
       itemContent =
-        transformNode->TransformRect(itemContent,mAppUnitsPerDevPixel);
+        transformNode->TransformRect(itemContent, mAppUnitsPerDevPixel);
 
       itemDrawRect =
         transformNode->TransformRect(itemDrawRect, mAppUnitsPerDevPixel);
     }
 
 #ifdef DEBUG
     nsRect bounds = itemContent;
 
     if (itemType == DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO || inEffect) {
       bounds.SetEmpty();
     }
 
-
     if (!bounds.IsEmpty() && itemASR != mContainerASR) {
       if (Maybe<nsRect> clip =
             item->GetClipWithRespectToASR(mBuilder, mContainerASR)) {
         bounds = clip.ref();
       }
     }
 
-    ((nsRect&)mAccumulatedChildBounds).UnionRect(mAccumulatedChildBounds,
-                                                 bounds);
+    ((nsRect&)mAccumulatedChildBounds)
+      .UnionRect(mAccumulatedChildBounds, bounds);
 #endif
 
     nsIntRect itemVisibleRect = itemDrawRect;
 
     // We intersect the building rect with the clipped item bounds to get a
     // tighter visible rect.
     if (!prerenderedTransform) {
       nsRect itemBuildingRect = item->GetBuildingRect();
@@ -4711,157 +4939,162 @@ ContainerState::ProcessDisplayItems(nsDi
         ScaleToOutsidePixels(itemBuildingRect, false));
     }
 
     if (maxLayers != -1 && layerCount >= maxLayers) {
       forceInactive = true;
     }
 
     // Assign the item to a layer
-    bool treatInactiveItemAsActive = (layerState == LAYER_INACTIVE && mLayerBuilder->GetContainingPaintedLayerData());
-    if (layerState == LAYER_ACTIVE_FORCE ||
-        treatInactiveItemAsActive ||
+    bool treatInactiveItemAsActive =
+      (layerState == LAYER_INACTIVE &&
+       mLayerBuilder->GetContainingPaintedLayerData());
+    if (layerState == LAYER_ACTIVE_FORCE || treatInactiveItemAsActive ||
         (!forceInactive &&
-         (layerState == LAYER_ACTIVE_EMPTY ||
-          layerState == LAYER_ACTIVE))) {
+         (layerState == LAYER_ACTIVE_EMPTY || layerState == LAYER_ACTIVE))) {
 
       layerCount++;
 
       // Currently we do not support flattening effects within nested inactive
       // layer trees.
       MOZ_ASSERT(selectedLayer == nullptr);
       MOZ_ASSERT(marker == DisplayItemEntryType::ITEM);
 
       // LAYER_ACTIVE_EMPTY means the layer is created just for its metadata.
       // We should never see an empty layer with any visible content!
       NS_ASSERTION(layerState != LAYER_ACTIVE_EMPTY ||
-                   itemVisibleRect.IsEmpty(),
+                     itemVisibleRect.IsEmpty(),
                    "State is LAYER_ACTIVE_EMPTY but visible rect is not.");
 
       // As long as the new layer isn't going to be a PaintedLayer,
       // InvalidateForLayerChange doesn't need the new layer pointer.
       // We also need to check the old data now, because BuildLayer
       // can overwrite it.
-      DisplayItemData* oldData =
-        mLayerBuilder->GetOldLayerForFrame(item->Frame(), item->GetPerFrameKey());
+      DisplayItemData* oldData = mLayerBuilder->GetOldLayerForFrame(
+        item->Frame(), item->GetPerFrameKey());
       InvalidateForLayerChange(item, nullptr, oldData);
 
       // If the item would have its own layer but is invisible, just hide it.
       // Note that items without their own layers can't be skipped this
       // way, since their PaintedLayer may decide it wants to draw them
       // into its buffer even if they're currently covered.
       if (itemVisibleRect.IsEmpty() &&
           !item->ShouldBuildLayerEvenIfInvisible(mBuilder)) {
         continue;
       }
 
       // 3D-transformed layers don't necessarily draw in the order in which
       // they're added to their parent container layer.
-      bool mayDrawOutOfOrder = itemType == DisplayItemType::TYPE_TRANSFORM &&
+      bool mayDrawOutOfOrder =
+        itemType == DisplayItemType::TYPE_TRANSFORM &&
         (item->Frame()->Combines3DTransformWithAncestors() ||
          item->Frame()->Extend3DContext());
 
       // Let mPaintedLayerDataTree know about this item, so that
       // FindPaintedLayerFor and FindOpaqueBackgroundColor are aware of this
       // item, even though it's not in any PaintedLayerDataStack.
       // Ideally we'd only need the "else" case here and have
       // mPaintedLayerDataTree figure out the right clip from the animated
       // geometry root that we give it, but it can't easily figure about
       // overflow:hidden clips on ancestors just by looking at the frame.
       // So we'll do a little hand holding and pass the clip instead of the
       // visible rect for the two important cases.
-      nscolor uniformColor = NS_RGBA(0,0,0,0);
-      nscolor* uniformColorPtr = (mayDrawOutOfOrder || IsInInactiveLayer()) ? nullptr :
-                                                                              &uniformColor;
+      nscolor uniformColor = NS_RGBA(0, 0, 0, 0);
+      nscolor* uniformColorPtr =
+        (mayDrawOutOfOrder || IsInInactiveLayer()) ? nullptr : &uniformColor;
       nsIntRect clipRectUntyped;
       nsIntRect* clipPtr = nullptr;
       if (itemClip.HasClip()) {
         clipRectUntyped = clipRect.ToUnknownRect();
         clipPtr = &clipRectUntyped;
       }
 
-      bool hasScrolledClip = layerClipChain && layerClipChain->mClip.HasClip() &&
+      bool hasScrolledClip =
+        layerClipChain && layerClipChain->mClip.HasClip() &&
         (!ActiveScrolledRoot::IsAncestor(layerClipChain->mASR, itemASR) ||
          itemType == DisplayItemType::TYPE_STICKY_POSITION);
 
       if (hasScrolledClip) {
         // If the clip is scrolled, reserve just the area of the clip for
         // layerization, so that elements outside the clip can still merge
         // into the same layer.
         const ActiveScrolledRoot* clipASR = layerClipChain->mASR;
-        AnimatedGeometryRoot* clipAGR = mBuilder->AnimatedGeometryRootForASR(clipASR);
+        AnimatedGeometryRoot* clipAGR =
+          mBuilder->AnimatedGeometryRootForASR(clipASR);
         nsIntRect scrolledClipRect =
-          ScaleToNearestPixels(layerClipChain->mClip.GetClipRect()) + mParameters.mOffset;
-        mPaintedLayerDataTree.AddingOwnLayer(clipAGR,
-                                             &scrolledClipRect,
-                                             uniformColorPtr);
+          ScaleToNearestPixels(layerClipChain->mClip.GetClipRect()) +
+          mParameters.mOffset;
+        mPaintedLayerDataTree.AddingOwnLayer(
+          clipAGR, &scrolledClipRect, uniformColorPtr);
       } else if (item->ShouldFixToViewport(mBuilder) && itemClip.HasClip() &&
-                 item->AnimatedGeometryRootForScrollMetadata() != animatedGeometryRoot &&
+                 item->AnimatedGeometryRootForScrollMetadata() !=
+                   animatedGeometryRoot &&
                  !nsLayoutUtils::UsesAsyncScrolling(item->Frame())) {
         // This is basically the same as the case above, but for the non-APZ
         // case. At the moment, when APZ is off, there is only the root ASR
         // (because scroll frames without display ports don't create ASRs) and
         // the whole clip chain is always just one fused clip.
         // Bug 1336516 aims to change that and to remove this workaround.
-        AnimatedGeometryRoot* clipAGR = item->AnimatedGeometryRootForScrollMetadata();
+        AnimatedGeometryRoot* clipAGR =
+          item->AnimatedGeometryRootForScrollMetadata();
         nsIntRect scrolledClipRect =
           ScaleToNearestPixels(itemClip.GetClipRect()) + mParameters.mOffset;
-        mPaintedLayerDataTree.AddingOwnLayer(clipAGR,
-                                             &scrolledClipRect,
-                                             uniformColorPtr);
+        mPaintedLayerDataTree.AddingOwnLayer(
+          clipAGR, &scrolledClipRect, uniformColorPtr);
       } else if (IsScrollThumbLayer(item) && mManager->IsWidgetLayerManager()) {
         // For scrollbar thumbs, the clip we care about is the clip added by the
         // slider frame.
-        mPaintedLayerDataTree.AddingOwnLayer(animatedGeometryRoot->mParentAGR,
-                                             clipPtr,
-                                             uniformColorPtr);
+        mPaintedLayerDataTree.AddingOwnLayer(
+          animatedGeometryRoot->mParentAGR, clipPtr, uniformColorPtr);
       } else if (prerenderedTransform && mManager->IsWidgetLayerManager()) {
         if (animatedGeometryRoot->mParentAGR) {
-          mPaintedLayerDataTree.AddingOwnLayer(animatedGeometryRoot->mParentAGR,
-                                               clipPtr,
-                                               uniformColorPtr);
+          mPaintedLayerDataTree.AddingOwnLayer(
+            animatedGeometryRoot->mParentAGR, clipPtr, uniformColorPtr);
         } else {
-          mPaintedLayerDataTree.AddingOwnLayer(animatedGeometryRoot,
-                                               nullptr,
-                                               uniformColorPtr);
+          mPaintedLayerDataTree.AddingOwnLayer(
+            animatedGeometryRoot, nullptr, uniformColorPtr);
         }
       } else {
         // Using itemVisibleRect here isn't perfect. itemVisibleRect can be
         // larger or smaller than the potential bounds of item's contents in
         // animatedGeometryRoot: It's too large if there's a clipped display
         // port somewhere among item's contents (see bug 1147673), and it can
         // be too small if the contents can move, because it only looks at the
         // contents' current bounds and doesn't anticipate any animations.
         // Time will tell whether this is good enough, or whether we need to do
         // something more sophisticated here.
-        mPaintedLayerDataTree.AddingOwnLayer(animatedGeometryRoot,
-                                             &itemVisibleRect, uniformColorPtr);
+        mPaintedLayerDataTree.AddingOwnLayer(
+          animatedGeometryRoot, &itemVisibleRect, uniformColorPtr);
       }
 
       ContainerLayerParameters params = mParameters;
       params.mBackgroundColor = uniformColor;
       params.mLayerCreationHint = GetLayerCreationHint(animatedGeometryRoot);
-      params.mScrollMetadataASR = ActiveScrolledRoot::PickDescendant(mContainerScrollMetadataASR, scrollMetadataASR);
-      params.mCompositorASR = params.mScrollMetadataASR != mContainerScrollMetadataASR
-                                ? params.mScrollMetadataASR
-                                : mContainerCompositorASR;
+      params.mScrollMetadataASR = ActiveScrolledRoot::PickDescendant(
+        mContainerScrollMetadataASR, scrollMetadataASR);
+      params.mCompositorASR =
+        params.mScrollMetadataASR != mContainerScrollMetadataASR
+          ? params.mScrollMetadataASR
+          : mContainerCompositorASR;
       if (itemType == DisplayItemType::TYPE_FIXED_POSITION) {
         params.mCompositorASR = itemASR;
       }
 
       if (itemType == DisplayItemType::TYPE_PERSPECTIVE) {
         // Perspective items have a single child item, an nsDisplayTransform.
         // If the perspective item is scrolled, but the perspective-inducing
         // frame is outside the scroll frame (indicated by item->Frame()
         // being outside that scroll frame), we have to take special care to
         // make APZ scrolling work properly. APZ needs us to put the scroll
         // frame's FrameMetrics on our child transform ContainerLayer instead.
         // It's worth investigating whether this ASR adjustment can be done at
         // display item creation time.
-        scrollMetadataASR = GetASRForPerspective(scrollMetadataASR, item->Frame()->GetContainingBlock(nsIFrame::SKIP_SCROLLED_FRAME));
+        scrollMetadataASR = GetASRForPerspective(
+          scrollMetadataASR,
+          item->Frame()->GetContainingBlock(nsIFrame::SKIP_SCROLLED_FRAME));
         params.mScrollMetadataASR = scrollMetadataASR;
         itemASR = scrollMetadataASR;
       }
 
       // Just use its layer.
       // Set layerContentsVisibleRect.width/height to -1 to indicate we
       // currently don't know. If BuildContainerLayerFor gets called by
       // item->BuildLayer, this will be set to a proper rect.
@@ -4885,19 +5118,19 @@ ContainerState::ProcessDisplayItems(nsDi
         DisplayItemClip nestedClip = item->GetClip();
         if (nestedClip.HasClip()) {
           nsRect nestedClipRect = nestedClip.NonRoundedIntersection();
 
           // Transform the nested clip to be relative to the same reference
           // frame as the existing mInactiveLayerClip, so that we can intersect
           // them below.
           nestedClipRect = nsLayoutUtils::TransformFrameRectToAncestor(
-              item->ReferenceFrame(),
-              nestedClipRect,
-              mLayerBuilder->GetContainingPaintedLayerData()->mReferenceFrame);
+            item->ReferenceFrame(),
+            nestedClipRect,
+            mLayerBuilder->GetContainingPaintedLayerData()->mReferenceFrame);
 
           nestedClip.SetTo(nestedClipRect);
           combinedInactiveClip.IntersectWith(nestedClip);
           mLayerBuilder->SetInactiveLayerClip(&combinedInactiveClip);
         }
       }
 
       RefPtr<Layer> ownLayer = item->BuildLayer(mBuilder, mManager, params);
@@ -4926,26 +5159,24 @@ ContainerState::ProcessDisplayItems(nsDi
       nsRect invalid;
       if (item->IsInvalid(invalid)) {
         ownLayer->SetInvalidRectToVisibleRegion();
       }
 
       // If it's not a ContainerLayer, we need to apply the scale transform
       // ourselves.
       if (!ownLayer->AsContainerLayer()) {
-        ownLayer->SetPostScale(mParameters.mXScale,
-                               mParameters.mYScale);
+        ownLayer->SetPostScale(mParameters.mXScale, mParameters.mYScale);
       }
 
       // Update that layer's clip and visible rects.
       NS_ASSERTION(ownLayer->Manager() == mManager, "Wrong manager");
       NS_ASSERTION(!ownLayer->HasUserData(&gLayerManagerUserData),
                    "We shouldn't have a FrameLayerBuilder-managed layer here!");
-      NS_ASSERTION(itemClip.HasClip() ||
-                   itemClip.GetRoundedRectCount() == 0,
+      NS_ASSERTION(itemClip.HasClip() || itemClip.GetRoundedRectCount() == 0,
                    "If we have rounded rects, we must have a clip rect");
 
       // It has its own layer. Update that layer's clip and visible rects.
       ownLayer->SetClipRect(Nothing());
       ownLayer->SetScrolledClip(Nothing());
       ownLayer->SetAncestorMaskLayers({});
       if (itemClip.HasClip()) {
         ownLayer->SetClipRect(Some(clipRect));
@@ -4956,32 +5187,33 @@ ContainerState::ProcessDisplayItems(nsDi
           SetupMaskLayer(ownLayer, itemClip);
         }
       }
 
       if (hasScrolledClip) {
         const DisplayItemClip& scrolledClip = layerClipChain->mClip;
         LayerClip scrolledLayerClip;
         scrolledLayerClip.SetClipRect(ViewAs<ParentLayerPixel>(
-          ScaleToNearestPixels(scrolledClip.GetClipRect()) + mParameters.mOffset));
+          ScaleToNearestPixels(scrolledClip.GetClipRect()) +
+          mParameters.mOffset));
         if (scrolledClip.GetRoundedRectCount() > 0) {
           scrolledLayerClip.SetMaskLayerIndex(
-              SetupMaskLayerForScrolledClip(ownLayer.get(), scrolledClip));
+            SetupMaskLayerForScrolledClip(ownLayer.get(), scrolledClip));
         }
         ownLayer->SetScrolledClip(Some(scrolledLayerClip));
       }
 
       if (item->GetType() == DisplayItemType::TYPE_MASK) {
         MOZ_ASSERT(itemClip.GetRoundedRectCount() == 0);
 
         nsDisplayMask* maskItem = static_cast<nsDisplayMask*>(item);
         SetupMaskLayerForCSSMask(ownLayer, maskItem);
 
-        if (iter.PeekNext() &&
-            iter.PeekNext()->GetType() == DisplayItemType::TYPE_SCROLL_INFO_LAYER) {
+        if (iter.PeekNext() && iter.PeekNext()->GetType() ==
+                                 DisplayItemType::TYPE_SCROLL_INFO_LAYER) {
           // Since we do build a layer for mask, there is no need for this
           // scroll info layer anymore.
           iter.GetNext();
         }
       }
 
       // Convert the visible rect to a region and give the item
       // a chance to try restrict it further.
@@ -5023,115 +5255,142 @@ ContainerState::ProcessDisplayItems(nsDi
       if (ContainerLayer* ownContainer = ownLayer->AsContainerLayer()) {
         contentXScale = 1 / ownContainer->GetPreXScale();
         contentYScale = 1 / ownContainer->GetPreYScale();
       }
       // nsDisplayTransform::BuildLayer must set layerContentsVisibleRect.
       // We rely on this to ensure 3D transforms compute a reasonable
       // layer visible region.
       NS_ASSERTION(itemType != DisplayItemType::TYPE_TRANSFORM ||
-                   layerContentsVisibleRect.width >= 0,
+                     layerContentsVisibleRect.width >= 0,
                    "Transform items must set layerContentsVisibleRect!");
       if (mLayerBuilder->IsBuildingRetainedLayers()) {
         newLayerEntry->mLayerContentsVisibleRect = layerContentsVisibleRect;
         if (itemType == DisplayItemType::TYPE_PERSPECTIVE ||
             (itemType == DisplayItemType::TYPE_TRANSFORM &&
              (item->Frame()->Extend3DContext() ||
               item->Frame()->Combines3DTransformWithAncestors() ||
               item->Frame()->HasPerspective()))) {
           // Give untransformed visible region as outer visible region
           // to avoid failure caused by singular transforms.
           newLayerEntry->mUntransformedVisibleRegion = true;
           newLayerEntry->mVisibleRegion =
-            item->GetBuildingRectForChildren().ScaleToOutsidePixels(contentXScale, contentYScale, mAppUnitsPerDevPixel);
+            item->GetBuildingRectForChildren().ScaleToOutsidePixels(
+              contentXScale, contentYScale, mAppUnitsPerDevPixel);
         } else {
           newLayerEntry->mVisibleRegion = itemVisibleRegion;
         }
-        newLayerEntry->mOpaqueRegion = ComputeOpaqueRect(item,
-          animatedGeometryRoot, itemASR, itemClip, aList,
+        newLayerEntry->mOpaqueRegion = ComputeOpaqueRect(
+          item,
+          animatedGeometryRoot,
+          itemASR,
+          itemClip,
+          aList,
           &newLayerEntry->mHideAllLayersBelow,
           &newLayerEntry->mOpaqueForAnimatedGeometryRootParent);
       } else {
-        bool useChildrenVisible =
-          itemType == DisplayItemType::TYPE_TRANSFORM &&
-          (item->Frame()->IsPreserve3DLeaf() ||
-           item->Frame()->HasPerspective());
-        const nsIntRegion &visible = useChildrenVisible ?
-          item->GetBuildingRectForChildren().ScaleToOutsidePixels(contentXScale, contentYScale, mAppUnitsPerDevPixel):
-          itemVisibleRegion;
-
-        SetOuterVisibleRegionForLayer(ownLayer, visible,
-            layerContentsVisibleRect.width >= 0 ? &layerContentsVisibleRect : nullptr,
-            useChildrenVisible);
+        bool useChildrenVisible = itemType == DisplayItemType::TYPE_TRANSFORM &&
+                                  (item->Frame()->IsPreserve3DLeaf() ||
+                                   item->Frame()->HasPerspective());
+        const nsIntRegion& visible =
+          useChildrenVisible
+            ? item->GetBuildingRectForChildren().ScaleToOutsidePixels(
+                contentXScale, contentYScale, mAppUnitsPerDevPixel)
+            : itemVisibleRegion;
+
+        SetOuterVisibleRegionForLayer(ownLayer,
+                                      visible,
+                                      layerContentsVisibleRect.width >= 0
+                                        ? &layerContentsVisibleRect
+                                        : nullptr,
+                                      useChildrenVisible);
       }
       if (itemType == DisplayItemType::TYPE_SCROLL_INFO_LAYER) {
-        nsDisplayScrollInfoLayer* scrollItem = static_cast<nsDisplayScrollInfoLayer*>(item);
+        nsDisplayScrollInfoLayer* scrollItem =
+          static_cast<nsDisplayScrollInfoLayer*>(item);
         newLayerEntry->mOpaqueForAnimatedGeometryRootParent = false;
         newLayerEntry->mBaseScrollMetadata =
-            scrollItem->ComputeScrollMetadata(ownLayer->Manager(), mParameters);
+          scrollItem->ComputeScrollMetadata(ownLayer->Manager(), mParameters);
       } else if ((itemType == DisplayItemType::TYPE_SUBDOCUMENT ||
                   itemType == DisplayItemType::TYPE_ZOOM ||
                   itemType == DisplayItemType::TYPE_RESOLUTION) &&
-                 gfxPrefs::LayoutUseContainersForRootFrames())
-      {
+                 gfxPrefs::LayoutUseContainersForRootFrames()) {
         newLayerEntry->mBaseScrollMetadata =
-          static_cast<nsDisplaySubDocument*>(item)->ComputeScrollMetadata(ownLayer->Manager(), mParameters);
+          static_cast<nsDisplaySubDocument*>(item)->ComputeScrollMetadata(
+            ownLayer->Manager(), mParameters);
       }
 
       /**
        * No need to allocate geometry for items that aren't
        * part of a PaintedLayer.
        */
       if (ownLayer->Manager() == mLayerBuilder->GetRetainingLayerManager()) {
-        oldData =
-          mLayerBuilder->GetOldLayerForFrame(item->Frame(), item->GetPerFrameKey());
+        oldData = mLayerBuilder->GetOldLayerForFrame(item->Frame(),
+                                                     item->GetPerFrameKey());
         mLayerBuilder->StoreDataForFrame(item, ownLayer, layerState, oldData);
       }
     } else {
       const bool backfaceHidden = item->In3DContextAndBackfaceIsHidden();
       const nsIFrame* referenceFrame = item->ReferenceFrame();
 
       PaintedLayerData* paintedLayerData = selectedLayer;
 
       if (!paintedLayerData) {
-        paintedLayerData =
-          mPaintedLayerDataTree.FindPaintedLayerFor(animatedGeometryRoot, itemASR, layerClipChain,
-                                                    itemVisibleRect, backfaceHidden,
-                                                    [&](PaintedLayerData* aData) {
-            NewPaintedLayerData(aData, animatedGeometryRoot, itemASR,
-                                layerClipChain, scrollMetadataASR, topLeft,
-                                referenceFrame, backfaceHidden);
-        });
+        paintedLayerData = mPaintedLayerDataTree.FindPaintedLayerFor(
+          animatedGeometryRoot,
+          itemASR,
+          layerClipChain,
+          itemVisibleRect,
+          backfaceHidden,
+          [&](PaintedLayerData* aData) {
+            NewPaintedLayerData(aData,
+                                animatedGeometryRoot,
+                                itemASR,
+                                layerClipChain,
+                                scrollMetadataASR,
+                                topLeft,
+                                referenceFrame,
+                                backfaceHidden);
+          });
       }
       MOZ_ASSERT(paintedLayerData);
 
       if (itemType == DisplayItemType::TYPE_COMPOSITOR_HITTEST_INFO) {
         nsDisplayCompositorHitTestInfo* hitTestInfo =
           static_cast<nsDisplayCompositorHitTestInfo*>(item);
         MOZ_ASSERT(!transformNode);
         paintedLayerData->AccumulateHitTestInfo(this, hitTestInfo, nullptr);
       } else {
-        paintedLayerData->Accumulate(this, item, itemVisibleRect, itemContent,
-                                     itemClip, layerState, aList, marker,
-                                     opacityIndices, transformNode);
+        paintedLayerData->Accumulate(this,
+                                     item,
+                                     itemVisibleRect,
+                                     itemContent,
+                                     itemClip,
+                                     layerState,
+                                     aList,
+                                     marker,
+                                     opacityIndices,
+                                     transformNode);
 
         if (!paintedLayerData->mLayer) {
           // Try to recycle the old layer of this display item.
-          RefPtr<PaintedLayer> layer =
-            AttemptToRecyclePaintedLayer(animatedGeometryRoot, item,
-                                         topLeft, referenceFrame);
+          RefPtr<PaintedLayer> layer = AttemptToRecyclePaintedLayer(
+            animatedGeometryRoot, item, topLeft, referenceFrame);
           if (layer) {
             paintedLayerData->mLayer = layer;
 
-            PaintedDisplayItemLayerUserData* userData = GetPaintedDisplayItemLayerUserData(layer);
-            paintedLayerData->mAssignedDisplayItems.reserve(userData->mLastItemCount);
+            PaintedDisplayItemLayerUserData* userData =
+              GetPaintedDisplayItemLayerUserData(layer);
+            paintedLayerData->mAssignedDisplayItems.reserve(
+              userData->mLastItemCount);
 
             NS_ASSERTION(FindIndexOfLayerIn(mNewChildLayers, layer) < 0,
                          "Layer already in list???");
-            mNewChildLayers[paintedLayerData->mNewChildLayersIndex].mLayer = layer.forget();
+            mNewChildLayers[paintedLayerData->mNewChildLayersIndex].mLayer =
+              layer.forget();
           }
         }
       }
 
       const auto ClearLayerSelectionIfNeeded = [&]() {
         if (!InOpacity() && !InTransform()) {
           selectedLayer = nullptr;
           containerAGR = nullptr;
@@ -5143,33 +5402,30 @@ ContainerState::ProcessDisplayItems(nsDi
         if (!selectedLayer) {
           selectedLayer = paintedLayerData;
           containerAGR = item->GetAnimatedGeometryRoot();
           containerASR = item->GetActiveScrolledRoot();
         }
       };
 
       if (marker == DisplayItemEntryType::PUSH_TRANSFORM) {
-        nsDisplayTransform* transform =
-          static_cast<nsDisplayTransform*>(item);
-
-        const Matrix4x4Flagged& matrix =
-          transform->GetTransformForRendering();
+        nsDisplayTransform* transform = static_cast<nsDisplayTransform*>(item);
+
+        const Matrix4x4Flagged& matrix = transform->GetTransformForRendering();
 
         Maybe<nsRect> clip;
         if (itemClip.HasClip()) {
           clip.emplace(itemClip.NonRoundedIntersection());
         }
 
         transformNode = new TransformClipNode(transformNode, matrix, clip);
       }
 
-      ProcessDisplayItemMarker(marker,
-                               ClearLayerSelectionIfNeeded,
-                               SelectLayerIfNeeded);
+      ProcessDisplayItemMarker(
+        marker, ClearLayerSelectionIfNeeded, SelectLayerIfNeeded);
     }
 
     nsDisplayList* childItems = item->GetSameCoordinateSystemChildren();
     if (childItems && childItems->NeedsTransparentSurface()) {
       aList->SetNeedsTransparentSurface();
     }
   }
 
@@ -5181,25 +5437,30 @@ ContainerState::InvalidateForLayerChange
                                          PaintedLayer* aNewLayer,
                                          DisplayItemData* aData)
 {
   NS_ASSERTION(aItem->GetPerFrameKey(),
                "Display items that render using Thebes must have a key");
   Layer* oldLayer = aData ? aData->mLayer.get() : nullptr;
   if (aNewLayer != oldLayer && oldLayer) {
     // The item has changed layers.
-    // Invalidate the old bounds in the old layer and new bounds in the new layer.
+    // Invalidate the old bounds in the old layer and new bounds in the new
+    // layer.
     PaintedLayer* t = oldLayer->AsPaintedLayer();
     if (t && aData->mGeometry) {
-      // Note that whenever the layer's scale changes, we invalidate the whole thing,
-      // so it doesn't matter whether we are using the old scale at last paint
-      // or a new scale here
+    // Note that whenever the layer's scale changes, we invalidate the whole
+    // thing, so it doesn't matter whether we are using the old scale at last
+    // paint or a new scale here
 #ifdef MOZ_DUMP_PAINTING
       if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
-        printf_stderr("Display item type %s(%p) changed layers %p to %p!\n", aItem->Name(), aItem->Frame(), t, aNewLayer);
+        printf_stderr("Display item type %s(%p) changed layers %p to %p!\n",
+                      aItem->Name(),
+                      aItem->Frame(),
+                      t,
+                      aNewLayer);
       }
 #endif
       InvalidatePreTransformRect(t,
                                  aData->mGeometry->ComputeInvalidationRegion(),
                                  aData->mClip,
                                  mLayerBuilder->GetLastPaintOffset(t),
                                  aData->mTransform);
     }
@@ -5223,333 +5484,374 @@ GetInvalidationRect(nsDisplayItemGeometr
   }
 
   return clipped;
 }
 
 void
 FrameLayerBuilder::ComputeGeometryChangeForItem(DisplayItemData* aData)
 {
-  nsDisplayItem *item = aData->mItem;
+  nsDisplayItem* item = aData->mItem;
   PaintedLayer* paintedLayer = aData->mLayer->AsPaintedLayer();
-  // If aData->mOptLayer is presence, means this item has been optimized to the separate
-  // layer. Thus, skip geometry change calculation.
+  // If aData->mOptLayer is presence, means this item has been optimized to the
+  // separate layer. Thus, skip geometry change calculation.
   if (aData->mOptLayer || !item || !paintedLayer) {
     aData->EndUpdate();
     return;
   }
 
   // If we're a reused display item, then we can't be invalid, so no need to
   // do an in-depth comparison. If we haven't previously stored geometry
   // for this item (if it was an active layer), then we can't skip this
   // yet.
   nsAutoPtr<nsDisplayItemGeometry> geometry;
   if (aData->mReusedItem && aData->mGeometry) {
     aData->EndUpdate();
     return;
   }
 
   PaintedDisplayItemLayerUserData* layerData =
-    static_cast<PaintedDisplayItemLayerUserData*>(aData->mLayer->GetUserData(&gPaintedDisplayItemLayerUserData));
-  nsPoint shift = layerData->mAnimatedGeometryRootOrigin - layerData->mLastAnimatedGeometryRootOrigin;
+    static_cast<PaintedDisplayItemLayerUserData*>(
+      aData->mLayer->GetUserData(&gPaintedDisplayItemLayerUserData));
+  nsPoint shift = layerData->mAnimatedGeometryRootOrigin -
+                  layerData->mLastAnimatedGeometryRootOrigin;
 
   if (aData->mTransform) {
     // If this display item is inside a flattened transform, the shift is
     // already included in the root transform.
     shift = nsPoint();
   }
 
   const DisplayItemClip& clip = item->GetClip();
   const int32_t appUnitsPerDevPixel = layerData->mAppUnitsPerDevPixel;
 
-  // If the frame is marked as invalidated, and didn't specify a rect to invalidate then we want to
-  // invalidate both the old and new bounds, otherwise we only want to invalidate the changed areas.
-  // If we do get an invalid rect, then we want to add this on top of the change areas.
+  // If the frame is marked as invalidated, and didn't specify a rect to
+  // invalidate then we want to invalidate both the old and new bounds,
+  // otherwise we only want to invalidate the changed areas. If we do get an
+  // invalid rect, then we want to add this on top of the change areas.
   nsRect invalid;
   nsIntRegion invalidPixels;
 
   if (!aData->mGeometry) {
     // This item is being added for the first time, invalidate its entire area.
     geometry = item->AllocateGeometry(mDisplayListBuilder);
 
-    const nsRect bounds = GetInvalidationRect(geometry, clip,
-                                              aData->mTransform,
-                                              appUnitsPerDevPixel);
-
-    invalidPixels = bounds.ScaleToOutsidePixels(layerData->mXScale,
-                                                layerData->mYScale,
-                                                appUnitsPerDevPixel);
+    const nsRect bounds = GetInvalidationRect(
+      geometry, clip, aData->mTransform, appUnitsPerDevPixel);
+
+    invalidPixels = bounds.ScaleToOutsidePixels(
+      layerData->mXScale, layerData->mYScale, appUnitsPerDevPixel);
 #ifdef MOZ_DUMP_PAINTING
     if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
-      printf_stderr("Display item type %s(%p) added to layer %p!\n", item->Name(), item->Frame(), aData->mLayer.get());
+      printf_stderr("Display item type %s(%p) added to layer %p!\n",
+                    item->Name(),
+                    item->Frame(),
+                    aData->mLayer.get());
     }
 #endif
-  } else if (aData->mIsInvalid || (item->IsInvalid(invalid) && invalid.IsEmpty())) {
-    // Layout marked item/frame as needing repainting (without an explicit rect), invalidate the entire old and new areas.
+  } else if (aData->mIsInvalid ||
+             (item->IsInvalid(invalid) && invalid.IsEmpty())) {
+    // Layout marked item/frame as needing repainting (without an explicit
+    // rect), invalidate the entire old and new areas.
     geometry = item->AllocateGeometry(mDisplayListBuilder);
 
-    nsRect oldArea = GetInvalidationRect(aData->mGeometry, aData->mClip,
+    nsRect oldArea = GetInvalidationRect(aData->mGeometry,
+                                         aData->mClip,
                                          aData->mOldTransform,
                                          appUnitsPerDevPixel);
     oldArea.MoveBy(shift);
 
-    nsRect newArea = GetInvalidationRect(geometry, clip,
-                                         aData->mTransform,
-                                         appUnitsPerDevPixel);
+    nsRect newArea = GetInvalidationRect(
+      geometry, clip, aData->mTransform, appUnitsPerDevPixel);
 
     nsRegion combined;
     combined.Or(oldArea, newArea);
-    invalidPixels = combined.ScaleToOutsidePixels(layerData->mXScale,
-                                                  layerData->mYScale,
-                                                  appUnitsPerDevPixel);
+    invalidPixels = combined.ScaleToOutsidePixels(
+      layerData->mXScale, layerData->mYScale, appUnitsPerDevPixel);
 #ifdef MOZ_DUMP_PAINTING
     if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
-      printf_stderr("Display item type %s(%p) (in layer %p) belongs to an invalidated frame!\n",
-          item->Name(), item->Frame(), aData->mLayer.get());
+      printf_stderr("Display item type %s(%p) (in layer %p) belongs to an "
+                    "invalidated frame!\n",
+                    item->Name(),
+                    item->Frame(),
+                    aData->mLayer.get());
     }
 #endif
   } else {
-    // Let the display item check for geometry changes and decide what needs to be
-    // repainted.
+    // Let the display item check for geometry changes and decide what needs to
+    // be repainted.
     const nsRegion& changedFrameInvalidations =
       aData->GetChangedFrameInvalidations();
 
     aData->mGeometry->MoveBy(shift);
 
     nsRegion combined;
-    item->ComputeInvalidationRegion(mDisplayListBuilder, aData->mGeometry,
-                                    &combined);
-
-    // Only allocate a new geometry object if something actually changed, otherwise the existing
-    // one should be fine. We always reallocate for inactive layers, since these types don't
-    // implement ComputeInvalidateRegion (and rely on the ComputeDifferences call in
+    item->ComputeInvalidationRegion(
+      mDisplayListBuilder, aData->mGeometry, &combined);
+
+    // Only allocate a new geometry object if something actually changed,
+    // otherwise the existing one should be fine. We always reallocate for
+    // inactive layers, since these types don't implement
+    // ComputeInvalidateRegion (and rely on the ComputeDifferences call in
     // AddPaintedDisplayItem instead).
     if (!combined.IsEmpty() || aData->mLayerState == LAYER_INACTIVE ||
         item->NeedsGeometryUpdates()) {
       geometry = item->AllocateGeometry(mDisplayListBuilder);
     }
 
-    aData->mClip.AddOffsetAndComputeDifference(shift, aData->mGeometry->ComputeInvalidationRegion(),
-                                               clip, geometry ? geometry->ComputeInvalidationRegion() :
-                                                                aData->mGeometry->ComputeInvalidationRegion(),
-                                               &combined);
+    aData->mClip.AddOffsetAndComputeDifference(
+      shift,
+      aData->mGeometry->ComputeInvalidationRegion(),
+      clip,
+      geometry ? geometry->ComputeInvalidationRegion()
+               : aData->mGeometry->ComputeInvalidationRegion(),
+      &combined);
 
     // Add in any rect that the frame specified
     combined.Or(combined, invalid);
     combined.Or(combined, changedFrameInvalidations);
 
     // Restrict invalidation to the clipped region
     nsRegion clipRegion;
     if (clip.ComputeRegionInClips(&aData->mClip, shift, &clipRegion)) {
       combined.And(combined, clipRegion);
     }
 
-    invalidPixels = combined.ScaleToOutsidePixels(layerData->mXScale,
-                                                  layerData->mYScale,
-                                                  appUnitsPerDevPixel);
+    invalidPixels = combined.ScaleToOutsidePixels(
+      layerData->mXScale, layerData->mYScale, appUnitsPerDevPixel);
 
     if (aData->mTransform) {
       invalidPixels =
         aData->mTransform->TransformRegion(invalidPixels, appUnitsPerDevPixel);
     }
 
 #ifdef MOZ_DUMP_PAINTING
     if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
       if (!combined.IsEmpty()) {
-        printf_stderr("Display item type %s(%p) (in layer %p) changed geometry!\n",
-          item->Name(), item->Frame(), aData->mLayer.get());
+        printf_stderr(
+          "Display item type %s(%p) (in layer %p) changed geometry!\n",
+          item->Name(),
+          item->Frame(),
+          aData->mLayer.get());
       }
     }
 #endif
   }
 
   if (!invalidPixels.IsEmpty()) {
-    InvalidatePostTransformRegion(paintedLayer, invalidPixels,
-                                  layerData->mTranslation);
+    InvalidatePostTransformRegion(
+      paintedLayer, invalidPixels, layerData->mTranslation);
   }
 
   aData->EndUpdate(geometry);
 }
 
 void
 FrameLayerBuilder::AddPaintedDisplayItem(PaintedLayerData* aLayerData,
                                          AssignedDisplayItem& aItem,
                                          ContainerState& aContainerState,
                                          Layer* aLayer)
 {
   PaintedLayer* layer = aLayerData->mLayer;
   PaintedDisplayItemLayerUserData* paintedData =
-    static_cast<PaintedDisplayItemLayerUserData*>
-      (layer->GetUserData(&gPaintedDisplayItemLayerUserData));
+    static_cast<PaintedDisplayItemLayerUserData*>(
+      layer->GetUserData(&gPaintedDisplayItemLayerUserData));
   RefPtr<BasicLayerManager> tempManager;
   nsIntRect intClip;
   bool hasClip = false;
   if (aItem.mLayerState != LAYER_NONE) {
     if (aItem.mDisplayItemData) {
       tempManager = aItem.mDisplayItemData->mInactiveManager;
 
-      // We need to grab these before updating the DisplayItemData because it will overwrite them.
+      // We need to grab these before updating the DisplayItemData because it
+      // will overwrite them.
       nsRegion clip;
-      if (aItem.mItem->GetClip().ComputeRegionInClips(&aItem.mDisplayItemData->GetClip(),
-                                                      aLayerData->mAnimatedGeometryRootOffset - paintedData->mLastAnimatedGeometryRootOrigin,
-                                                      &clip)) {
-        intClip = clip.GetBounds().ScaleToOutsidePixels(paintedData->mXScale,
-                                                        paintedData->mYScale,
-                                                        paintedData->mAppUnitsPerDevPixel);
+      if (aItem.mItem->GetClip().ComputeRegionInClips(
+            &aItem.mDisplayItemData->GetClip(),
+            aLayerData->mAnimatedGeometryRootOffset -
+              paintedData->mLastAnimatedGeometryRootOrigin,
+            &clip)) {
+        intClip = clip.GetBounds().ScaleToOutsidePixels(
+          paintedData->mXScale,
+          paintedData->mYScale,
+          paintedData->mAppUnitsPerDevPixel);
       }
     }
     if (!tempManager) {
       tempManager = new BasicLayerManager(BasicLayerManager::BLM_INACTIVE);
     }
   }
 
   if (layer->Manager() == mRetainingManager) {
     DisplayItemData* data = aItem.mDisplayItemData;
     if (data && !data->mUsed) {
-      data->BeginUpdate(layer, aItem.mLayerState, aItem.mItem, aItem.mReused, aItem.mMerged);
+      data->BeginUpdate(
+        layer, aItem.mLayerState, aItem.mItem, aItem.mReused, aItem.mMerged);
     } else {
       if (data && data->mUsed) {
         // If the DID has already been used (by a previously merged frame,
-        // which is not merged this paint) we must create a new DID for the item.
+        // which is not merged this paint) we must create a new DID for the
+        // item.
         aItem.mItem->SetDisplayItemData(nullptr, nullptr);
       }
       data = StoreDataForFrame(aItem.mItem, layer, aItem.mLayerState, nullptr);
     }
     data->mInactiveManager = tempManager;
-    // We optimized this PaintedLayer into a ColorLayer/ImageLayer. Store the optimized
-    // layer here.
+    // We optimized this PaintedLayer into a ColorLayer/ImageLayer. Store the
+    // optimized layer here.
     if (aLayer != layer) {
       data->mOptLayer = aLayer;
     }
 
     data->mOldTransform = data->mTransform;
     data->mTransform = aItem.mTransform;
   }
 
   if (tempManager) {
-    FLB_LOG_PAINTED_LAYER_DECISION(aLayerData, "Creating nested FLB for item %p\n", aItem.mItem);
+    FLB_LOG_PAINTED_LAYER_DECISION(
+      aLayerData, "Creating nested FLB for item %p\n", aItem.mItem);
     FrameLayerBuilder* layerBuilder = new FrameLayerBuilder();
-    layerBuilder->Init(mDisplayListBuilder, tempManager, aLayerData, true,
+    layerBuilder->Init(mDisplayListBuilder,
+                       tempManager,
+                       aLayerData,
+                       true,
                        &aItem.mItem->GetClip());
 
     tempManager->BeginTransaction();
     if (mRetainingManager) {
       layerBuilder->DidBeginRetainedLayerTransaction(tempManager);
     }
 
-    UniquePtr<LayerProperties> props(LayerProperties::CloneFrom(tempManager->GetRoot()));
-    RefPtr<Layer> tmpLayer =
-      aItem.mItem->BuildLayer(mDisplayListBuilder, tempManager, ContainerLayerParameters());
-    // We have no easy way of detecting if this transaction will ever actually get finished.
-    // For now, I've just silenced the warning with nested transactions in BasicLayers.cpp
+    UniquePtr<LayerProperties> props(
+      LayerProperties::CloneFrom(tempManager->GetRoot()));
+    RefPtr<Layer> tmpLayer = aItem.mItem->BuildLayer(
+      mDisplayListBuilder, tempManager, ContainerLayerParameters());
+    // We have no easy way of detecting if this transaction will ever actually
+    // get finished. For now, I've just silenced the warning with nested
+    // transactions in BasicLayers.cpp
     if (!tmpLayer) {
       tempManager->EndTransaction(nullptr, nullptr);
       tempManager->SetUserData(&gLayerManagerLayerBuilder, nullptr);
       aItem.mItem = nullptr;
       return;
     }
 
     bool snap;
-    nsRect visibleRect =
-      aItem.mItem->GetBuildingRect().Intersect(aItem.mItem->GetBounds(mDisplayListBuilder, &snap));
-    nsIntRegion rgn = visibleRect.ToOutsidePixels(paintedData->mAppUnitsPerDevPixel);
+    nsRect visibleRect = aItem.mItem->GetBuildingRect().Intersect(
+      aItem.mItem->GetBounds(mDisplayListBuilder, &snap));
+    nsIntRegion rgn =
+      visibleRect.ToOutsidePixels(paintedData->mAppUnitsPerDevPixel);
 
     // Convert the visible rect to a region and give the item
     // a chance to try restrict it further.
-    nsRegion tightBounds = aItem.mItem->GetTightBounds(mDisplayListBuilder, &snap);
+    nsRegion tightBounds =
+      aItem.mItem->GetTightBounds(mDisplayListBuilder, &snap);
     if (!tightBounds.IsEmpty()) {
-      rgn.AndWith(tightBounds.ToOutsidePixels(paintedData->mAppUnitsPerDevPixel));
+      rgn.AndWith(
+        tightBounds.ToOutsidePixels(paintedData->mAppUnitsPerDevPixel));
     }
     SetOuterVisibleRegion(tmpLayer, &rgn);
 
     DisplayItemData* data = nullptr;
-    // If BuildLayer didn't call BuildContainerLayerFor, then our new layer won't have been
-    // stored in layerBuilder. Manually add it now.
+    // If BuildLayer didn't call BuildContainerLayerFor, then our new layer
+    // won't have been stored in layerBuilder. Manually add it now.
     if (mRetainingManager) {
 #ifdef DEBUG_DISPLAY_ITEM_DATA
-      LayerManagerData* parentLmd = static_cast<LayerManagerData*>
-        (layer->Manager()->GetUserData(&gLayerManagerUserData));
-      LayerManagerData* lmd = static_cast<LayerManagerData*>
-        (tempManager->GetUserData(&gLayerManagerUserData));
+      LayerManagerData* parentLmd = static_cast<LayerManagerData*>(
+        layer->Manager()->GetUserData(&gLayerManagerUserData));
+      LayerManagerData* lmd = static_cast<LayerManagerData*>(
+        tempManager->GetUserData(&gLayerManagerUserData));
       lmd->mParent = parentLmd;
 #endif
-      data = layerBuilder->GetDisplayItemDataForManager(aItem.mItem,
-                                                        tempManager);
-      data = layerBuilder->StoreDataForFrame(aItem.mItem, tmpLayer,
-                                             LAYER_ACTIVE, data);
+      data =
+        layerBuilder->GetDisplayItemDataForManager(aItem.mItem, tempManager);
+      data = layerBuilder->StoreDataForFrame(
+        aItem.mItem, tmpLayer, LAYER_ACTIVE, data);
       data->mOldTransform = data->mTransform;
       data->mTransform = aItem.mTransform;
     }
 
     tempManager->SetRoot(tmpLayer);
     layerBuilder->WillEndTransaction();
     tempManager->AbortTransaction();
 
     if (gfxUtils::DumpDisplayList() || gfxEnv::DumpPaint()) {
-      fprintf_stderr(gfxUtils::sDumpPaintFile, "Basic layer tree for painting contents of display item %s(%p):\n", aItem.mItem->Name(), aItem.mItem->Frame());
+      fprintf_stderr(
+        gfxUtils::sDumpPaintFile,
+        "Basic layer tree for painting contents of display item %s(%p):\n",
+        aItem.mItem->Name(),
+        aItem.mItem->Frame());
       std::stringstream stream;
       tempManager->Dump(stream, "", gfxEnv::DumpPaintToFile());
-      fprint_stderr(gfxUtils::sDumpPaintFile, stream);  // not a typo, fprint_stderr declared in LayersLogging.h
-    }
-
-    nsIntPoint offset = GetLastPaintOffset(layer) - GetTranslationForPaintedLayer(layer);
+      fprint_stderr(
+        gfxUtils::sDumpPaintFile,
+        stream); // not a typo, fprint_stderr declared in LayersLogging.h
+    }
+
+    nsIntPoint offset =
+      GetLastPaintOffset(layer) - GetTranslationForPaintedLayer(layer);
     props->MoveBy(-offset);
     // Effective transforms are needed by ComputeDifferences().
     tmpLayer->ComputeEffectiveTransforms(Matrix4x4());
     nsIntRegion invalid;
     if (!props->ComputeDifferences(tmpLayer, invalid, nullptr)) {
       nsRect visible = aItem.mItem->Frame()->GetVisualOverflowRect();
       invalid = visible.ToOutsidePixels(paintedData->mAppUnitsPerDevPixel);
     }
     if (aItem.mLayerState == LAYER_SVG_EFFECTS) {
-      invalid = nsSVGIntegrationUtils::AdjustInvalidAreaForSVGEffects(aItem.mItem->Frame(),
-                                                                      aItem.mItem->ToReferenceFrame(),
-                                                                      invalid);
+      invalid = nsSVGIntegrationUtils::AdjustInvalidAreaForSVGEffects(
+        aItem.mItem->Frame(), aItem.mItem->ToReferenceFrame(), invalid);
     }
     if (!invalid.IsEmpty()) {
 #ifdef MOZ_DUMP_PAINTING
       if (nsLayoutUtils::InvalidationDebuggingIsEnabled()) {
-        printf_stderr("Inactive LayerManager(%p) for display item %s(%p) has an invalid region - invalidating layer %p\n", tempManager.get(), aItem.mItem->Name(), aItem.mItem->Frame(), layer);
+        printf_stderr("Inactive LayerManager(%p) for display item %s(%p) has "
+                      "an invalid region - invalidating layer %p\n",
+                      tempManager.get(),
+                      aItem.mItem->Name(),
+                      aItem.mItem->Frame(),
+                      layer);
       }
 #endif
       invalid.ScaleRoundOut(paintedData->mXScale, paintedData->mYScale);
 
       if (hasClip) {
         invalid.And(invalid, intClip);
       }
 
       if (data && data->mTransform) {
-        invalid =
-          data->mTransform->TransformRegion(invalid,
-                                            paintedData->mAppUnitsPerDevPixel);
+        invalid = data->mTransform->TransformRegion(
+          invalid, paintedData->mAppUnitsPerDevPixel);
       }
 
-      InvalidatePostTransformRegion(layer, invalid,
-                                    GetTranslationForPaintedLayer(layer));
+      InvalidatePostTransformRegion(
+        layer, invalid, GetTranslationForPaintedLayer(layer));
     }
   }
   aItem.mInactiveLayerManager = tempManager;
 }
 
 DisplayItemData*
-FrameLayerBuilder::StoreDataForFrame(nsDisplayItem* aItem, Layer* aLayer,
-                                     LayerState aState, DisplayItemData* aData)
+FrameLayerBuilder::StoreDataForFrame(nsDisplayItem* aItem,
+                                     Layer* aLayer,
+                                     LayerState aState,
+                                     DisplayItemData* aData)
 {
   if (aData) {
     if (!aData->mUsed) {
       aData->BeginUpdate(aLayer, aState, false, aItem);
     }
     return aData;
   }
 
-  LayerManagerData* lmd = static_cast<LayerManagerData*>
-    (mRetainingManager->GetUserData(&gLayerManagerUserData));
-
-  RefPtr<DisplayItemData> data =
-    new (aItem->Frame()->PresContext()) DisplayItemData(lmd, aItem->GetPerFrameKey(), aLayer);
+  LayerManagerData* lmd = static_cast<LayerManagerData*>(
+    mRetainingManager->GetUserData(&gLayerManagerUserData));
+
+  RefPtr<DisplayItemData> data = new (aItem->Frame()->PresContext())
+    DisplayItemData(lmd, aItem->GetPerFrameKey(), aLayer);
 
   data->BeginUpdate(aLayer, aState, true, aItem);
 
   lmd->mDisplayItems.push_back(data);
   return data;
 }
 
 void
@@ -5559,121 +5861,128 @@ FrameLayerBuilder::StoreDataForFrame(nsI
                                      LayerState aState)
 {
   DisplayItemData* oldData = GetDisplayItemData(aFrame, aDisplayItemKey);
   if (oldData && oldData->mFrameList.Length() == 1) {
     oldData->BeginUpdate(aLayer, aState, false);
     return;
   }
 
-  LayerManagerData* lmd = static_cast<LayerManagerData*>
-    (mRetainingManager->GetUserData(&gLayerManagerUserData));
-
-  RefPtr<DisplayItemData> data =
-    new (aFrame->PresContext()) DisplayItemData(lmd, aDisplayItemKey, aLayer, aFrame);
+  LayerManagerData* lmd = static_cast<LayerManagerData*>(
+    mRetainingManager->GetUserData(&gLayerManagerUserData));
+
+  RefPtr<DisplayItemData> data = new (aFrame->PresContext())
+    DisplayItemData(lmd, aDisplayItemKey, aLayer, aFrame);
 
   data->BeginUpdate(aLayer, aState, true);
 
   lmd->mDisplayItems.push_back(data);
 }
 
-AssignedDisplayItem::AssignedDisplayItem(nsDisplayItem* aItem,
-                                         LayerState aLayerState,
-                                         DisplayItemData* aData,
-                                         const nsRect& aContentRect,
-                                         DisplayItemEntryType aType,
-                                         const bool aHasOpacity,
-                                         const RefPtr<TransformClipNode>& aTransform)
+AssignedDisplayItem::AssignedDisplayItem(
+  nsDisplayItem* aItem,
+  LayerState aLayerState,
+  DisplayItemData* aData,
+  const nsRect& aContentRect,
+  DisplayItemEntryType aType,
+  const bool aHasOpacity,
+  const RefPtr<TransformClipNode>& aTransform)
   : mItem(aItem)
   , mLayerState(aLayerState)
   , mDisplayItemData(aData)
   , mContentRect(aContentRect)
   , mTransform(aTransform)
   , mType(aType)
   , mReused(aItem->IsReused())
   , mMerged(aItem->HasMergedFrames())
   , mHasOpacity(aHasOpacity)
   , mHasTransform(aTransform)
   , mHasPaintRect(aItem->HasPaintRect())
-{}
+{
+}
 
 AssignedDisplayItem::~AssignedDisplayItem()
 {
   if (mInactiveLayerManager) {
     mInactiveLayerManager->SetUserData(&gLayerManagerLayerBuilder, nullptr);
   }
 }
 
 nsIntPoint
 FrameLayerBuilder::GetLastPaintOffset(PaintedLayer* aLayer)
 {
-  PaintedDisplayItemLayerUserData* layerData = GetPaintedDisplayItemLayerUserData(aLayer);
+  PaintedDisplayItemLayerUserData* layerData =
+    GetPaintedDisplayItemLayerUserData(aLayer);
   MOZ_ASSERT(layerData);
   if (layerData->mHasExplicitLastPaintOffset) {
     return layerData->mLastPaintOffset;
   }
   return GetTranslationForPaintedLayer(aLayer);
 }
 
 bool
 FrameLayerBuilder::CheckInLayerTreeCompressionMode()
 {
   if (mInLayerTreeCompressionMode) {
     return true;
   }
 
-  // If we wanted to be in layer tree compression mode, but weren't, then scheduled
-  // a delayed repaint where we will be.
-  mRootPresContext->PresShell()->GetRootFrame()->SchedulePaint(nsIFrame::PAINT_DELAYED_COMPRESS, false);
+  // If we wanted to be in layer tree compression mode, but weren't, then
+  // scheduled a delayed repaint where we will be.
+  mRootPresContext->PresShell()->GetRootFrame()->SchedulePaint(
+    nsIFrame::PAINT_DELAYED_COMPRESS, false);
 
   return false;
 }
 
 void
 ContainerState::CollectOldLayers()
 {
   for (Layer* layer = mContainerLayer->GetFirstChild(); layer;
        layer = layer->GetNextSibling()) {
     NS_ASSERTION(!layer->HasUserData(&gMaskLayerUserData),
                  "Mask layers should not be part of the layer tree.");
     if (layer->HasUserData(&gPaintedDisplayItemLayerUserData)) {
       NS_ASSERTION(layer->AsPaintedLayer(), "Wrong layer type");
-      mPaintedLayersAvailableForRecycling.PutEntry(static_cast<PaintedLayer*>(layer));
+      mPaintedLayersAvailableForRecycling.PutEntry(
+        static_cast<PaintedLayer*>(layer));
     }
 
     if (Layer* maskLayer = layer->GetMaskLayer()) {
       NS_ASSERTION(maskLayer->GetType() == Layer::TYPE_IMAGE,
                    "Could not recycle mask layer, unsupported layer type.");
-      mRecycledMaskImageLayers.Put(MaskLayerKey(layer, Nothing()), static_cast<ImageLayer*>(maskLayer));
+      mRecycledMaskImageLayers.Put(MaskLayerKey(layer, Nothing()),
+                                   static_cast<ImageLayer*>(maskLayer));
     }
     for (size_t i = 0; i < layer->GetAncestorMaskLayerCount(); i++) {
       Layer* maskLayer = layer->GetAncestorMaskLayerAt(i);
 
       NS_ASSERTION(maskLayer->GetType() == Layer::TYPE_IMAGE,
                    "Could not recycle mask layer, unsupported layer type.");
-      mRecycledMaskImageLayers.Put(MaskLayerKey(layer, Some(i)), static_cast<ImageLayer*>(maskLayer));
-    }
-  }
-}
-
-struct OpaqueRegionEntry {
+      mRecycledMaskImageLayers.Put(MaskLayerKey(layer, Some(i)),
+                                   static_cast<ImageLayer*>(maskLayer));
+    }
+  }
+}
+
+struct OpaqueRegionEntry
+{
   AnimatedGeometryRoot* mAnimatedGeometryRoot;
   const ActiveScrolledRoot* mASR;
   nsIntRegion mOpaqueRegion;
 };
 
 static OpaqueRegionEntry*
 FindOpaqueRegionEntry(nsTArray<OpaqueRegionEntry>& aEntries,
                       AnimatedGeometryRoot* aAnimatedGeometryRoot,
                       const ActiveScrolledRoot* aASR)
 {
   for (uint32_t i = 0; i < aEntries.Length(); ++i) {
     OpaqueRegionEntry* d = &aEntries[i];
-    if (d->mAnimatedGeometryRoot == aAnimatedGeometryRoot &&
-        d->mASR == aASR) {
+    if (d->mAnimatedGeometryRoot == aAnimatedGeometryRoot && d->mASR == aASR) {
       return d;
     }
   }
   return nullptr;
 }
 
 static const ActiveScrolledRoot*
 FindDirectChildASR(const ActiveScrolledRoot* aParent,
@@ -5730,17 +6039,18 @@ FixUpFixedPositionLayer(Layer* aLayer,
   // if there were no fixed annotation on it.
   const ActiveScrolledRoot* compositorASR =
     aLeafScrollMetadataASR == aContainerScrollMetadataASR
       ? aContainerCompositorASR
       : aLeafScrollMetadataASR;
 
   // The goal of the annotation is to have the layer move with aTargetASR.
   if (compositorASR && aTargetASR != compositorASR) {
-    // Mark this layer as fixed with respect to the child scroll frame of aTargetASR.
+    // Mark this layer as fixed with respect to the child scroll frame of
+    // aTargetASR.
     aLayer->SetFixedPositionData(
       FindDirectChildASR(aTargetASR, compositorASR)->GetViewId(),
       aLayer->GetFixedPositionAnchor(),
       aLayer->GetFixedPositionSides());
   } else {
     // Remove the fixed annotation from the layer, unless this layers is fixed
     // to the document's root scroll frame - in that case, the annotation is
     // needed for hit testing, because fixed layers in iframes should scroll
@@ -5779,85 +6089,88 @@ ContainerState::SetupScrollingMetadata(N
       // concerned, those two ASRs are siblings, parented to the ASR of the
       // fixed layer.
       do {
         stopASR = stopASR->mParent;
       } while (!ActiveScrolledRoot::IsAncestor(stopASR, startASR));
     }
   }
 
-  FixUpFixedPositionLayer(aEntry->mLayer, aEntry->mASR, startASR,
-                          mContainerScrollMetadataASR, mContainerCompositorASR,
+  FixUpFixedPositionLayer(aEntry->mLayer,
+                          aEntry->mASR,
+                          startASR,
+                          mContainerScrollMetadataASR,
+                          mContainerCompositorASR,
                           aEntry->mIsFixedToRootScrollFrame);
 
-  AutoTArray<ScrollMetadata,2> metricsArray;
+  AutoTArray<ScrollMetadata, 2> metricsArray;
   if (aEntry->mBaseScrollMetadata) {
     metricsArray.AppendElement(*aEntry->mBaseScrollMetadata);
 
     // The base FrameMetrics was not computed by the nsIScrollableframe, so it
     // should not have a mask layer.
     MOZ_ASSERT(!aEntry->mBaseScrollMetadata->HasMaskLayer());
   }
 
   // Any extra mask layers we need to attach to ScrollMetadatas.
   // The list may already contain an entry added for the layer's scrolled clip
   // so add to it rather than overwriting it (we clear the list when recycling
   // a layer).
-  nsTArray<RefPtr<Layer>> maskLayers(aEntry->mLayer->GetAllAncestorMaskLayers());
+  nsTArray<RefPtr<Layer>> maskLayers(
+    aEntry->mLayer->GetAllAncestorMaskLayers());
 
   // Iterate over the ASR chain and create the corresponding scroll metadatas.
   // This loop is slightly tricky because the scrollframe-to-clip relationship
   // is reversed between DisplayItemClipChain and ScrollMetadata:
   //  - DisplayItemClipChain associates the clip with the scroll frame that
   //    this clip is *moved by*, i.e. the clip is moving inside the scroll
   //    frame.
   //  - ScrollMetaData associates the scroll frame with the clip that's
   //    *just outside* the scroll frame, i.e. not moved by the scroll frame
   //    itself.
   // This discrepancy means that the leaf clip item of the clip chain is never
   // applied to any scroll meta data. Instead, it was applied earlier as the
   // layer's clip (or fused with the painted layer contents), or it was applied
   // as a ScrolledClip on the layer.
   const DisplayItemClipChain* clipChain = aEntry->mClipChain;
 
-  for (const ActiveScrolledRoot* asr = startASR; asr != stopASR; asr = asr->mParent) {
+  for (const ActiveScrolledRoot* asr = startASR; asr != stopASR;
+       asr = asr->mParent) {
     if (!asr) {
       MOZ_ASSERT_UNREACHABLE("Should have encountered stopASR on the way up.");
       break;
     }
     if (clipChain && clipChain->mASR == asr) {
       clipChain = clipChain->mParent;
     }
 
     nsIScrollableFrame* scrollFrame = asr->mScrollableFrame;
-    const DisplayItemClip* clip =
-      (clipChain && clipChain->mASR == asr->mParent) ? &clipChain->mClip : nullptr;
+    const DisplayItemClip* clip = (clipChain && clipChain->mASR == asr->mParent)
+                                    ? &clipChain->mClip
+                                    : nullptr;
 
     scrollFrame->ClipLayerToDisplayPort(aEntry->mLayer, clip, mParameters);
 
     Maybe<ScrollMetadata> metadata;
     if (mCachedScrollMetadata.mASR == asr &&
         mCachedScrollMetadata.mClip == clip) {
       metadata = mCachedScrollMetadata.mMetadata;
     } else {
-      metadata = scrollFrame->ComputeScrollMetadata(aEntry->mLayer->Manager(),
-            mContainerReferenceFrame, mParameters, clip);
+      metadata = scrollFrame->ComputeScrollMetadata(
+        aEntry->mLayer->Manager(), mContainerReferenceFrame, mParameters, clip);
       mCachedScrollMetadata.mASR = asr;
       mCachedScrollMetadata.mClip = clip;
       mCachedScrollMetadata.mMetadata = metadata;
     }
 
     if (!metadata) {
       continue;
     }
 
-    if (clip &&
-        clip->HasClip() &&
-        clip->GetRoundedRectCount() > 0)
-    {
+    if (clip && clip->HasClip() && clip->GetRoundedRectCount() > 0) {
       // The clip in between this scrollframe and its ancestor scrollframe
       // requires a mask layer. Since this mask layer should not move with
       // the APZC associated with this FrameMetrics, we attach the mask
       // layer as an additional, separate clip.
       Maybe<size_t> nextIndex = Some(maskLayers.Length());
       RefPtr<Layer> maskLayer =
         CreateMaskLayer(aEntry->mLayer, *clip, nextIndex);
       if (maskLayer) {
@@ -5880,57 +6193,66 @@ GetStationaryClipInContainer(Layer* aLay
 {
   if (size_t metricsCount = aLayer->GetScrollMetadataCount()) {
     return aLayer->GetScrollMetadata(metricsCount - 1).GetClipRect();
   }
   return aLayer->GetClipRect();
 }
 
 void
-ContainerState::PostprocessRetainedLayers(nsIntRegion* aOpaqueRegionForContainer)
-{
-  AutoTArray<OpaqueRegionEntry,4> opaqueRegions;
+ContainerState::PostprocessRetainedLayers(
+  nsIntRegion* aOpaqueRegionForContainer)
+{
+  AutoTArray<OpaqueRegionEntry, 4> opaqueRegions;
   bool hideAll = false;
   int32_t opaqueRegionForContainer = -1;
 
   for (int32_t i = mNewChildLayers.Length() - 1; i >= 0; --i) {
     NewLayerEntry* e = &mNewChildLayers.ElementAt(i);
     if (!e->mLayer) {
       continue;
     }
 
-    OpaqueRegionEntry* data = FindOpaqueRegionEntry(opaqueRegions, e->mAnimatedGeometryRoot, e->mASR);
+    OpaqueRegionEntry* data =
+      FindOpaqueRegionEntry(opaqueRegions, e->mAnimatedGeometryRoot, e->mASR);
 
     SetupScrollingMetadata(e);
 
     if (hideAll) {
       e->mVisibleRegion.SetEmpty();
     } else if (!e->mLayer->IsScrollbarContainer()) {
-      Maybe<ParentLayerIntRect> clipRect = GetStationaryClipInContainer(e->mLayer);
+      Maybe<ParentLayerIntRect> clipRect =
+        GetStationaryClipInContainer(e->mLayer);
       if (clipRect && opaqueRegionForContainer >= 0 &&
-          opaqueRegions[opaqueRegionForContainer].mOpaqueRegion.Contains(clipRect->ToUnknownRect())) {
+          opaqueRegions[opaqueRegionForContainer].mOpaqueRegion.Contains(
+            clipRect->ToUnknownRect())) {
         e->mVisibleRegion.SetEmpty();
       } else if (data) {
         e->mVisibleRegion.Sub(e->mVisibleRegion, data->mOpaqueRegion);
       }
     }
 
     SetOuterVisibleRegionForLayer(e->mLayer,
                                   e->mVisibleRegion,
-                                  e->mLayerContentsVisibleRect.width >= 0 ? &e->mLayerContentsVisibleRect : nullptr,
+                                  e->mLayerContentsVisibleRect.width >= 0
+                                    ? &e->mLayerContentsVisibleRect
+                                    : nullptr,
                                   e->mUntransformedVisibleRegion);
 
     if (!e->mOpaqueRegion.IsEmpty()) {
-      AnimatedGeometryRoot* animatedGeometryRootToCover = e->mAnimatedGeometryRoot;
+      AnimatedGeometryRoot* animatedGeometryRootToCover =
+        e->mAnimatedGeometryRoot;
       const ActiveScrolledRoot* asrToCover = e->mASR;
       if (e->mOpaqueForAnimatedGeometryRootParent &&
-          e->mAnimatedGeometryRoot->mParentAGR == mContainerAnimatedGeometryRoot) {
+          e->mAnimatedGeometryRoot->mParentAGR ==
+            mContainerAnimatedGeometryRoot) {
         animatedGeometryRootToCover = mContainerAnimatedGeometryRoot;
         asrToCover = mContainerASR;
-        data = FindOpaqueRegionEntry(opaqueRegions, animatedGeometryRootToCover, asrToCover);
+        data = FindOpaqueRegionEntry(
+          opaqueRegions, animatedGeometryRootToCover, asrToCover);
       }
 
       if (!data) {
         if (animatedGeometryRootToCover == mContainerAnimatedGeometryRoot &&
             asrToCover == mContainerASR) {
           NS_ASSERTION(opaqueRegionForContainer == -1, "Already found it?");
           opaqueRegionForContainer = opaqueRegions.Length();
         }
@@ -5960,29 +6282,31 @@ ContainerState::PostprocessRetainedLayer
       // Theoretically we could just punch out the ReadbackLayer's rectangle
       // from all mOpaqueRegions, but that's probably not worth doing.
       opaqueRegions.Clear();
       opaqueRegionForContainer = -1;
     }
   }
 
   if (opaqueRegionForContainer >= 0) {
-    aOpaqueRegionForContainer->Or(*aOpaqueRegionForContainer,
-        opaqueRegions[opaqueRegionForContainer].mOpaqueRegion);
+    aOpaqueRegionForContainer->Or(
+      *aOpaqueRegionForContainer,
+      opaqueRegions[opaqueRegionForContainer].mOpaqueRegion);
   }
 }
 
 void
 ContainerState::Finish(uint32_t* aTextContentFlags,
                        const nsIntRect& aContainerPixelBounds,
                        nsDisplayList* aChildItems)
 {
   mPaintedLayerDataTree.Finish();
 
-  if (!mParameters.mForEventsAndPluginsOnly && !gfxPrefs::LayoutUseContainersForRootFrames()) {
+  if (!mParameters.mForEventsAndPluginsOnly &&
+      !gfxPrefs::LayoutUseContainersForRootFrames()) {
     // Bug 1336544 tracks re-enabling this assertion in the
     // gfxPrefs::LayoutUseContainersForRootFrames() case.
     NS_ASSERTION(mContainerBounds.IsEqualInterior(mAccumulatedChildBounds),
                  "Bounds computation mismatch");
   }
 
   if (mLayerBuilder->IsBuildingRetainedLayers()) {
     nsIntRegion containerOpaqueRegion;
@@ -6027,36 +6351,38 @@ ContainerState::Finish(uint32_t* aTextCo
 
   // Remove old layers that have become unused.
   if (!layer) {
     layer = mContainerLayer->GetFirstChild();
   } else {
     layer = layer->GetNextSibling();
   }
   while (layer) {
-    Layer *layerToRemove = layer;
+    Layer* layerToRemove = layer;
     layer = layer->GetNextSibling();
     mContainerLayer->RemoveChild(layerToRemove);
   }
 
   *aTextContentFlags = textContentFlags;
 }
 
-static void RestrictScaleToMaxLayerSize(Size& aScale,
-                                        const nsRect& aVisibleRect,
-                                        nsIFrame* aContainerFrame,
-                                        Layer* aContainerLayer)
+static void
+RestrictScaleToMaxLayerSize(Size& aScale,
+                            const nsRect& aVisibleRect,
+                            nsIFrame* aContainerFrame,
+                            Layer* aContainerLayer)
 {
   if (!aContainerLayer->Manager()->IsWidgetLayerManager()) {
     return;
   }
 
-  nsIntRect pixelSize =
-    aVisibleRect.ScaleToOutsidePixels(aScale.width, aScale.height,
-                                      aContainerFrame->PresContext()->AppUnitsPerDevPixel());
+  nsIntRect pixelSize = aVisibleRect.ScaleToOutsidePixels(
+    aScale.width,
+    aScale.height,
+    aContainerFrame->PresContext()->AppUnitsPerDevPixel());
 
   int32_t maxLayerSize = aContainerLayer->GetMaxLayerSize();
 
   if (pixelSize.width > maxLayerSize) {
     float scale = (float)pixelSize.width / maxLayerSize;
     scale = gfxUtils::ClampToScaleFactor(scale);
     aScale.width /= scale;
   }
@@ -6073,19 +6399,19 @@ ComputeDesiredDisplaySizeForAnimation(ns
   // Use the size of the nearest widget as the maximum size.  This
   // is important since it might be a popup that is bigger than the
   // pres context's size.
   nsPresContext* presContext = aContainerFrame->PresContext();
   nsIWidget* widget = aContainerFrame->GetNearestWidget();
   if (widget) {
     return LayoutDevicePixel::ToAppUnits(widget->GetClientSize(),
                                          presContext->AppUnitsPerDevPixel());
-  } else {
-    return presContext->GetVisibleArea().Size();
-  }
+  }
+
+  return presContext->GetVisibleArea().Size();
 }
 
 static bool
 ChooseScaleAndSetTransform(FrameLayerBuilder* aLayerBuilder,
                            nsDisplayListBuilder* aDisplayListBuilder,
                            nsIFrame* aContainerFrame,
                            nsDisplayItem* aContainerItem,
                            const nsRect& aVisibleRect,
@@ -6095,92 +6421,101 @@ ChooseScaleAndSetTransform(FrameLayerBui
                            ContainerLayerParameters& aOutgoingScale)
 {
   nsIntPoint offset;
 
   Matrix4x4 transform =
     Matrix4x4::Scaling(aIncomingScale.mXScale, aIncomingScale.mYScale, 1.0);
   if (aTransform) {
     // aTransform is applied first, then the scale is applied to the result
-    transform = (*aTransform)*transform;
+    transform = (*aTransform) * transform;
     // Set any matrix entries close to integers to be those exact integers.
     // This protects against floating-point inaccuracies causing problems
     // in the checks below.
     // We use the fixed epsilon version here because we don't want the nudging
     // to depend on the scroll position.
     transform.NudgeToIntegersFixedEpsilon();
   }
   Matrix transform2d;
-  if (aContainerFrame &&
-      aLayerBuilder->GetContainingPaintedLayerData() &&
-      (!aTransform || (aTransform->Is2D(&transform2d) &&
-                       !transform2d.HasNonTranslation()))) {
-    // When we have an inactive ContainerLayer, translate the container by the offset to the
-    // reference frame (and offset all child layers by the reverse) so that the coordinate
-    // space of the child layers isn't affected by scrolling.
-    // This gets confusing for complicated transform (since we'd have to compute the scale
-    // factors for the matrix), so we don't bother. Any frames that are building an nsDisplayTransform
-    // for a css transform would have 0,0 as their offset to the reference frame, so this doesn't
+  if (aContainerFrame && aLayerBuilder->GetContainingPaintedLayerData() &&
+      (!aTransform ||
+       (aTransform->Is2D(&transform2d) && !transform2d.HasNonTranslation()))) {
+    // When we have an inactive ContainerLayer, translate the container by the
+    // offset to the reference frame (and offset all child layers by the
+    // reverse) so that the coordinate space of the child layers isn't affected
+    // by scrolling. This gets confusing for complicated transform (since we'd
+    // have to compute the scale factors for the matrix), so we don't bother.
+    // Any frames that are building an nsDisplayTransform for a css transform
+    // would have 0,0 as their offset to the reference frame, so this doesn't
     // matter.
-    nsPoint appUnitOffset = aDisplayListBuilder->ToReferenceFrame(aContainerFrame);
-    nscoord appUnitsPerDevPixel = aContainerFrame->PresContext()->AppUnitsPerDevPixel();
+    nsPoint appUnitOffset =
+      aDisplayListBuilder->ToReferenceFrame(aContainerFrame);
+    nscoord appUnitsPerDevPixel =
+      aContainerFrame->PresContext()->AppUnitsPerDevPixel();
     offset = nsIntPoint(
-        NS_lround(NSAppUnitsToDoublePixels(appUnitOffset.x, appUnitsPerDevPixel)*aIncomingScale.mXScale),
-        NS_lround(NSAppUnitsToDoublePixels(appUnitOffset.y, appUnitsPerDevPixel)*aIncomingScale.mYScale));
+      NS_lround(NSAppUnitsToDoublePixels(appUnitOffset.x, appUnitsPerDevPixel) *
+                aIncomingScale.mXScale),
+      NS_lround(NSAppUnitsToDoublePixels(appUnitOffset.y, appUnitsPerDevPixel) *
+                aIncomingScale.mYScale));
   }
   transform.PostTranslate(offset.x + aIncomingScale.mOffset.x,
                           offset.y + aIncomingScale.mOffset.y,
                           0);
 
   if (transform.IsSingular()) {
     return false;
   }
 
   bool canDraw2D = transform.CanDraw2D(&transform2d);
   Size scale;
   // XXX Should we do something for 3D transforms?
-  if (canDraw2D &&
-      !aContainerFrame->Combines3DTransformWithAncestors() &&
+  if (canDraw2D && !aContainerFrame->Combines3DTransformWithAncestors() &&
       !aContainerFrame->HasPerspective()) {
-    // If the container's transform is animated off main thread, fix a suitable scale size
-    // for animation
+    // If the container's transform is animated off main thread, fix a suitable
+    // scale size for animation
     if (aContainerItem &&
         aContainerItem->GetType() == DisplayItemType::TYPE_TRANSFORM &&
-        EffectCompositor::HasAnimationsForCompositor(
-          aContainerFrame, eCSSProperty_transform)) {
-      nsSize displaySize = ComputeDesiredDisplaySizeForAnimation(aContainerFrame);
-      // compute scale using the animation on the container, taking ancestors in to account
-      nsSize scaledVisibleSize = nsSize(aVisibleRect.Width() * aIncomingScale.mXScale,
-                                        aVisibleRect.Height() * aIncomingScale.mYScale);
+        EffectCompositor::HasAnimationsForCompositor(aContainerFrame,
+                                                     eCSSProperty_transform)) {
+      nsSize displaySize =
+        ComputeDesiredDisplaySizeForAnimation(aContainerFrame);
+      // compute scale using the animation on the container, taking ancestors in
+      // to account
+      nsSize scaledVisibleSize =
+        nsSize(aVisibleRect.Width() * aIncomingScale.mXScale,
+               aVisibleRect.Height() * aIncomingScale.mYScale);
       scale = nsLayoutUtils::ComputeSuitableScaleForAnimation(
-                aContainerFrame, scaledVisibleSize,
-                displaySize);
+        aContainerFrame, scaledVisibleSize, displaySize);
       // multiply by the scale inherited from ancestors--we use a uniform
       // scale factor to prevent blurring when the layer is rotated.
-      float incomingScale = std::max(aIncomingScale.mXScale, aIncomingScale.mYScale);
+      float incomingScale =
+        std::max(aIncomingScale.mXScale, aIncomingScale.mYScale);
       scale.width *= incomingScale;
       scale.height *= incomingScale;
     } else {
-      // Scale factors are normalized to a power of 2 to reduce the number of resolution changes
+      // Scale factors are normalized to a power of 2 to reduce the number of
+      // resolution changes
       scale = transform2d.ScaleFactors(true);
       // For frames with a changing scale transform round scale factors up to
       // nearest power-of-2 boundary so that we don't keep having to redraw
       // the content as it scales up and down. Rounding up to nearest
       // power-of-2 boundary ensures we never scale up, only down --- avoiding
-      // jaggies. It also ensures we never scale down by more than a factor of 2,
-      // avoiding bad downscaling quality.
+      // jaggies. It also ensures we never scale down by more than a factor of
+      // 2, avoiding bad downscaling quality.
       Matrix frameTransform;
       if (ActiveLayerTracker::IsScaleSubjectToAnimation(aContainerFrame)) {
         scale.width = gfxUtils::ClampToScaleFactor(scale.width);
         scale.height = gfxUtils::ClampToScaleFactor(scale.height);
 
-        // Limit animated scale factors to not grow excessively beyond the display size.
+        // Limit animated scale factors to not grow excessively beyond the
+        // display size.
         nsSize maxScale(4, 4);
         if (!aVisibleRect.IsEmpty()) {
-          nsSize displaySize = ComputeDesiredDisplaySizeForAnimation(aContainerFrame);
+          nsSize displaySize =
+            ComputeDesiredDisplaySizeForAnimation(aContainerFrame);
           maxScale = Max(maxScale, displaySize / aVisibleRect.Size());
         }
         if (scale.width > maxScale.width) {
           scale.width = gfxUtils::ClampToScaleFactor(maxScale.width, true);
         }
         if (scale.height > maxScale.height) {
           scale.height = gfxUtils::ClampToScaleFactor(maxScale.height, true);
         }
@@ -6202,74 +6537,74 @@ ChooseScaleAndSetTransform(FrameLayerBui
       RestrictScaleToMaxLayerSize(scale, aVisibleRect, aContainerFrame, aLayer);
     }
   } else {
     scale = Size(1.0, 1.0);
   }
 
   // Store the inverse of our resolution-scale on the layer
   aLayer->SetBaseTransform(transform);
-  aLayer->SetPreScale(1.0f/scale.width,
-                      1.0f/scale.height);
-  aLayer->SetInheritedScale(aIncomingScale.mXScale,
-                            aIncomingScale.mYScale);
-
-  aOutgoingScale =
-    ContainerLayerParameters(scale.width, scale.height, -offset, aIncomingScale);
+  aLayer->SetPreScale(1.0f / scale.width, 1.0f / scale.height);
+  aLayer->SetInheritedScale(aIncomingScale.mXScale, aIncomingScale.mYScale);
+
+  aOutgoingScale = ContainerLayerParameters(
+    scale.width, scale.height, -offset, aIncomingScale);
   if (aTransform) {
     aOutgoingScale.mInTransformedSubtree = true;
-    if (ActiveLayerTracker::IsStyleAnimated(aDisplayListBuilder, aContainerFrame,
-                                            eCSSProperty_transform)) {
+    if (ActiveLayerTracker::IsStyleAnimated(
+          aDisplayListBuilder, aContainerFrame, eCSSProperty_transform)) {
       aOutgoingScale.mInActiveTransformedSubtree = true;
     }
   }
   if ((aLayerBuilder->IsBuildingRetainedLayers() &&
        (!canDraw2D || transform2d.HasNonIntegerTranslation())) ||
       aContainerFrame->Extend3DContext() ||
       aContainerFrame->Combines3DTransformWithAncestors() ||
       // For async transform animation, the value would be changed at
       // any time, integer translation is not always true.
       aContainerFrame->HasAnimationOfTransform()) {
     aOutgoingScale.mDisableSubpixelAntialiasingInDescendants = true;
   }
   return true;
 }
 
 already_AddRefed<ContainerLayer>
-FrameLayerBuilder::BuildContainerLayerFor(nsDisplayListBuilder* aBuilder,
-                                          LayerManager* aManager,
-                                          nsIFrame* aContainerFrame,
-                                          nsDisplayItem* aContainerItem,
-                                          nsDisplayList* aChildren,
-                                          const ContainerLayerParameters& aParameters,
-                                          const Matrix4x4* aTransform,
-                                          uint32_t aFlags)
+FrameLayerBuilder::BuildContainerLayerFor(
+  nsDisplayListBuilder* aBuilder,
+  LayerManager* aManager,
+  nsIFrame* aContainerFrame,
+  nsDisplayItem* aContainerItem,
+  nsDisplayList* aChildren,
+  const ContainerLayerParameters& aParameters,
+  const Matrix4x4* aTransform,
+  uint32_t aFlags)
 {
   uint32_t containerDisplayItemKey =
     aContainerItem ? aContainerItem->GetPerFrameKey() : 0;
-  NS_ASSERTION(aContainerFrame, "Container display items here should have a frame");
-  NS_ASSERTION(!aContainerItem ||
-               aContainerItem->Frame() == aContainerFrame,
+  NS_ASSERTION(aContainerFrame,
+               "Container display items here should have a frame");
+  NS_ASSERTION(!aContainerItem || aContainerItem->Frame() == aContainerFrame,
                "Container display item must match given frame");
 
   if (!aParameters.mXScale || !aParameters.mYScale) {
     return nullptr;
   }
 
   RefPtr<ContainerLayer> containerLayer;
   if (aManager == mRetainingManager) {
     // Using GetOldLayerFor will search merged frames, as well as the underlying
     // frame. The underlying frame can change when a page scrolls, so this
     // avoids layer recreation in the situation that a new underlying frame is
     // picked for a layer.
     Layer* oldLayer = nullptr;
     if (aContainerItem) {
       oldLayer = GetOldLayerFor(aContainerItem);
     } else {
-      DisplayItemData *data = GetOldLayerForFrame(aContainerFrame, containerDisplayItemKey);
+      DisplayItemData* data =
+        GetOldLayerForFrame(aContainerFrame, containerDisplayItemKey);
       if (data) {
         oldLayer = data->mLayer;
       }
     }
 
     if (oldLayer) {
       NS_ASSERTION(oldLayer->Manager() == aManager, "Wrong manager");
       if (oldLayer->HasUserData(&gPaintedDisplayItemLayerUserData)) {
@@ -6286,70 +6621,87 @@ FrameLayerBuilder::BuildContainerLayerFo
   }
   if (!containerLayer) {
     // No suitable existing layer was found.
     containerLayer = aManager->CreateContainerLayer();
     if (!containerLayer)
       return nullptr;
   }
 
-  if (aContainerItem && aContainerItem->GetType() == DisplayItemType::TYPE_SCROLL_INFO_LAYER) {
+  if (aContainerItem &&
+      aContainerItem->GetType() == DisplayItemType::TYPE_SCROLL_INFO_LAYER) {
     // Empty layers only have metadata and should never have display items. We
     // early exit because later, invalidation will walk up the frame tree to
     // determine which painted layer gets invalidated. Since an empty layer
     // should never have anything to paint, it should never be invalidated.
     NS_ASSERTION(aChildren->IsEmpty(), "Should have no children");
     return containerLayer.forget();
   }
 
-  const ActiveScrolledRoot* containerASR = aContainerItem ? aContainerItem->GetActiveScrolledRoot() : nullptr;
-  const ActiveScrolledRoot* containerScrollMetadataASR = aParameters.mScrollMetadataASR;
+  const ActiveScrolledRoot* containerASR =
+    aContainerItem ? aContainerItem->GetActiveScrolledRoot() : nullptr;
+  const ActiveScrolledRoot* containerScrollMetadataASR =
+    aParameters.mScrollMetadataASR;
   const ActiveScrolledRoot* containerCompositorASR = aParameters.mCompositorASR;
 
   if (!aContainerItem && gfxPrefs::LayoutUseContainersForRootFrames()) {
     containerASR = aBuilder->ActiveScrolledRootForRootScrollframe();
     containerScrollMetadataASR = containerASR;
     containerCompositorASR = containerASR;
   }
 
   ContainerLayerParameters scaleParameters;
-  nsRect bounds = aChildren->GetClippedBoundsWithRespectToASR(aBuilder, containerASR);
+  nsRect bounds =
+    aChildren->GetClippedBoundsWithRespectToASR(aBuilder, containerASR);
   nsRect childrenVisible =
-      aContainerItem ? aContainerItem->GetBuildingRectForChildren() :
-          aContainerFrame->GetVisualOverflowRectRelativeToSelf();
-  if (!ChooseScaleAndSetTransform(this, aBuilder, aContainerFrame,
+    aContainerItem ? aContainerItem->GetBuildingRectForChildren()
+                   : aContainerFrame->GetVisualOverflowRectRelativeToSelf();
+  if (!ChooseScaleAndSetTransform(this,
+                                  aBuilder,
+                                  aContainerFrame,
                                   aContainerItem,
                                   bounds.Intersect(childrenVisible),
-                                  aTransform, aParameters,
-                                  containerLayer, scaleParameters)) {
+                                  aTransform,
+                                  aParameters,
+                                  containerLayer,
+                                  scaleParameters)) {
     return nullptr;
   }
 
   if (mRetainingManager) {
     if (aContainerItem) {
-      DisplayItemData* data = GetDisplayItemDataForManager(aContainerItem, mRetainingManager);
+      DisplayItemData* data =
+        GetDisplayItemDataForManager(aContainerItem, mRetainingManager);
       StoreDataForFrame(aContainerItem, containerLayer, LAYER_ACTIVE, data);
     } else {
-      StoreDataForFrame(aContainerFrame, containerDisplayItemKey, containerLayer, LAYER_ACTIVE);
+      StoreDataForFrame(
+        aContainerFrame, containerDisplayItemKey, containerLayer, LAYER_ACTIVE);
     }
   }
 
   nsIntRect pixBounds;
   nscoord appUnitsPerDevPixel;
 
-  nscolor backgroundColor = NS_RGBA(0,0,0,0);
+  nscolor backgroundColor = NS_RGBA(0, 0, 0, 0);
   if (aFlags & CONTAINER_ALLOW_PULL_BACKGROUND_COLOR) {
     backgroundColor = aParameters.mBackgroundColor;
   }
 
   uint32_t flags;
-  ContainerState state(aBuilder, aManager, aManager->GetLayerBuilder(),
-                       aContainerFrame, aContainerItem, bounds,
-                       containerLayer, scaleParameters,
-                       backgroundColor, containerASR, containerScrollMetadataASR,
+  ContainerState state(aBuilder,
+                       aManager,
+                       aManager->GetLayerBuilder(),
+                       aContainerFrame,
+                       aContainerItem,
+                       bounds,
+                       containerLayer,
+                       scaleParameters,
+                       backgroundColor,
+                       containerASR,
+                       containerScrollMetadataASR,
                        containerCompositorASR);
 
   state.ProcessDisplayItems(aChildren);
 
   // Set CONTENT_COMPONENT_ALPHA if any of our children have it.
   // This is suboptimal ... a child could have text that's over transparent
   // pixels in its own layer, but over opaque parts of previous siblings.
   pixBounds = state.ScaleToOutsidePixels(bounds, false);
@@ -6374,20 +6726,22 @@ FrameLayerBuilder::BuildContainerLayerFo
       flags &= ~Layer::CONTENT_COMPONENT_ALPHA;
       flags |= Layer::CONTENT_OPAQUE;
     }
   }
   containerLayer->SetContentFlags(flags);
   // If aContainerItem is non-null some BuildContainerLayer further up the
   // call stack is responsible for setting containerLayer's visible region.
   if (!aContainerItem) {
-    containerLayer->SetVisibleRegion(LayerIntRegion::FromUnknownRegion(pixBounds));
+    containerLayer->SetVisibleRegion(
+      LayerIntRegion::FromUnknownRegion(pixBounds));
   }
   if (aParameters.mLayerContentsVisibleRect) {
-    *aParameters.mLayerContentsVisibleRect = pixBounds + scaleParameters.mOffset;
+    *aParameters.mLayerContentsVisibleRect =
+      pixBounds + scaleParameters.mOffset;
   }
 
   nsPresContext::ClearNotifySubDocInvalidationData(containerLayer);
 
   return containerLayer.forget();
 }
 
 Layer*
@@ -6405,54 +6759,58 @@ FrameLayerBuilder::GetLeafLayerFor(nsDis
   }
   ResetLayerStateForRecycling(layer);
   return layer;
 }
 
 /* static */ void
 FrameLayerBuilder::InvalidateAllLayers(LayerManager* aManager)
 {
-  LayerManagerData* data = static_cast<LayerManagerData*>
-    (aManager->GetUserData(&gLayerManagerUserData));
+  LayerManagerData* data = static_cast<LayerManagerData*>(
+    aManager->GetUserData(&gLayerManagerUserData));
   if (data) {
     data->mInvalidateAllLayers = true;
   }
 }
 
 /* static */ void
-FrameLayerBuilder::InvalidateAllLayersForFrame(nsIFrame *aFrame)
+FrameLayerBuilder::InvalidateAllLayersForFrame(nsIFrame* aFrame)
 {
   const SmallPointerArray<DisplayItemData>& array = aFrame->DisplayItemData();
 
   for (uint32_t i = 0; i < array.Length(); i++) {
-    DisplayItemData::AssertDisplayItemData(array.ElementAt(i))->mParent->mInvalidateAllLayers = true;
+    DisplayItemData::AssertDisplayItemData(array.ElementAt(i))
+      ->mParent->mInvalidateAllLayers = true;
   }
 }
 
 /* static */
 Layer*
-FrameLayerBuilder::GetDedicatedLayer(nsIFrame* aFrame, DisplayItemType aDisplayItemKey)
-{
-  //TODO: This isn't completely correct, since a frame could exist as a layer
+FrameLayerBuilder::GetDedicatedLayer(nsIFrame* aFrame,
+                                     DisplayItemType aDisplayItemKey)
+{
+  // TODO: This isn't completely correct, since a frame could exist as a layer
   // in the normal widget manager, and as a different layer (or no layer)
   // in the secondary manager
 
-  const SmallPointerArray<DisplayItemData>& array = aFrame->DisplayItemData();;
+  const SmallPointerArray<DisplayItemData>& array = aFrame->DisplayItemData();
+  ;
 
   for (uint32_t i = 0; i < array.Length(); i++) {
-    DisplayItemData *element = DisplayItemData::AssertDisplayItemData(array.ElementAt(i));
+    DisplayItemData* element =
+      DisplayItemData::AssertDisplayItemData(array.ElementAt(i));
     if (!element->mParent->mLayerManager->IsWidgetLayerManager()) {
       continue;
     }
-    if (GetDisplayItemTypeFromKey(element->mDisplayItemKey) == aDisplayItemKey) {
+    if (GetDisplayItemTypeFromKey(element->mDisplayItemKey) ==
+        aDisplayItemKey) {
       if (element->mOptLayer) {
         return element->mOptLayer;
       }
 
-
       Layer* layer = element->mLayer;
       if (!layer->HasUserData(&gColorLayerUserData) &&
           !layer->HasUserData(&gImageLayerUserData) &&
           !layer->HasUserData(&gPaintedDisplayItemLayerUserData)) {
         return layer;
       }
     }
   }
@@ -6487,55 +6845,57 @@ FrameLayerBuilder::GetPaintedLayerScaleF
   if (transform.CanDraw2D(&transform2d)) {
     return ThebesMatrix(transform2d).ScaleFactors(true);
   }
 
   return gfxSize(1.0, 1.0);
 }
 
 #ifdef MOZ_DUMP_PAINTING
-static void DebugPaintItem(DrawTarget& aDrawTarget,
-                           nsPresContext* aPresContext,
-                           nsDisplayItem *aItem,
-                           nsDisplayListBuilder* aBuilder)
+static void
+DebugPaintItem(DrawTarget& aDrawTarget,
+               nsPresContext* aPresContext,
+               nsDisplayItem* aItem,
+               nsDisplayListBuilder* aBuilder)
 {
   bool snap;
   Rect bounds = NSRectToRect(aItem->GetBounds(aBuilder, &snap),
                              aPresContext->AppUnitsPerDevPixel());
 
-  RefPtr<DrawTarget> tempDT =
-    aDrawTarget.CreateSimilarDrawTarget(IntSize::Truncate(bounds.width, bounds.height),
-                                        SurfaceFormat::B8G8R8A8);
+  RefPtr<DrawTarget> tempDT = aDrawTarget.CreateSimilarDrawTarget(
+    IntSize::Truncate(bounds.width, bounds.height), SurfaceFormat::B8G8R8A8);
   RefPtr<gfxContext> context = gfxContext::CreateOrNull(tempDT);
   if (!context) {
     // Leave this as crash, it's in the debugging code, we want to know
-    gfxDevCrash(LogReason::InvalidContext) << "DebugPaintItem context problem " << gfx::hexa(tempDT);
+    gfxDevCrash(LogReason::InvalidContext)
+      << "DebugPaintItem context problem " << gfx::hexa(tempDT);
     return;
   }
   context->SetMatrix(Matrix::Translation(-bounds.x, -bounds.y));
 
   aItem->Paint(aBuilder, context);
   RefPtr<SourceSurface> surface = tempDT->Snapshot();
   DumpPaintedImage(aItem, surface);
 
-  aDrawTarget.DrawSurface(surface, bounds, Rect(Point(0,0), bounds.Size()));
+  aDrawTarget.DrawSurface(surface, bounds, Rect(Point(0, 0), bounds.Size()));
 
   aItem->SetPainted();
 }
 #endif
 
 /* static */ void
-FrameLayerBuilder::RecomputeVisibilityForItems(std::vector<AssignedDisplayItem>& aItems,
-                                               nsDisplayListBuil