Merge mozilla-central to b2g-inbound
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Tue, 28 Jan 2014 14:22:14 +0100
changeset 165535 0e57e50718a2f0d4e275ef6f1233d3ed5765a3f0
parent 165534 7bc0d1e21cb7e5a5b18c81cdb53079a122e22cbe (current diff)
parent 165519 340704b289c77ff93472cd13abcae29b64abceae (diff)
child 165536 201cd05e5f8d8869f2f168a799107bae613bd0c7
push id26096
push userryanvm@gmail.com
push dateTue, 28 Jan 2014 21:12:38 +0000
treeherdermozilla-central@245b92f1de4f [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone29.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 b2g-inbound
browser/metro/base/content/browser.css
dom/interfaces/base/nsIDOMCRMFObject.idl
gfx/angle/src/libGLESv2/constants.h
mobile/android/base/db/HomeListsProvider.java
mobile/android/base/resources/layout/two_line_page_row.xml
mobile/android/base/resources/raw/fake_list_items.json
toolkit/components/osfile/tests/xpcshell/test_profiledir.js
--- a/accessible/src/jsat/Constants.jsm
+++ b/accessible/src/jsat/Constants.jsm
@@ -1,39 +1,52 @@
 const Ci = Components.interfaces;
 const Cu = Components.utils;
 
 Cu.import('resource://gre/modules/XPCOMUtils.jsm');
 
-this.EXPORTED_SYMBOLS = ['Roles', 'Events', 'Relations', 'Filters'];
+this.EXPORTED_SYMBOLS = ['Roles', 'Events', 'Relations', 'Filters', 'States'];
 
-function ConstantsMap (aObject, aPrefix) {
+function ConstantsMap (aObject, aPrefix, aMap = {}, aModifier = null) {
   let offset = aPrefix.length;
   for (var name in aObject) {
     if (name.indexOf(aPrefix) === 0) {
-      this[name.slice(offset)] = aObject[name];
+      aMap[name.slice(offset)] = aModifier ?
+        aModifier(aObject[name]) : aObject[name];
     }
   }
+
+  return aMap;
 }
 
 XPCOMUtils.defineLazyGetter(
   this, 'Roles',
   function() {
-    return new ConstantsMap(Ci.nsIAccessibleRole, 'ROLE_');
+    return ConstantsMap(Ci.nsIAccessibleRole, 'ROLE_');
   });
 
 XPCOMUtils.defineLazyGetter(
   this, 'Events',
   function() {
-    return new ConstantsMap(Ci.nsIAccessibleEvent, 'EVENT_');
+    return ConstantsMap(Ci.nsIAccessibleEvent, 'EVENT_');
   });
 
 XPCOMUtils.defineLazyGetter(
   this, 'Relations',
   function() {
-    return new ConstantsMap(Ci.nsIAccessibleRelation, 'RELATION_');
+    return ConstantsMap(Ci.nsIAccessibleRelation, 'RELATION_');
   });
 
 XPCOMUtils.defineLazyGetter(
   this, 'Filters',
   function() {
-    return new ConstantsMap(Ci.nsIAccessibleTraversalRule, 'FILTER_');
+    return ConstantsMap(Ci.nsIAccessibleTraversalRule, 'FILTER_');
   });
+
+XPCOMUtils.defineLazyGetter(
+  this, 'States',
+  function() {
+    let statesMap = ConstantsMap(Ci.nsIAccessibleStates, 'STATE_', {},
+                                 (val) => { return { base: val, extended: 0 }; });
+    ConstantsMap(Ci.nsIAccessibleStates, 'EXT_STATE_', statesMap,
+                 (val) => { return { base: 0, extended: val }; });
+    return statesMap;
+  });
--- a/accessible/src/jsat/EventManager.jsm
+++ b/accessible/src/jsat/EventManager.jsm
@@ -19,16 +19,18 @@ XPCOMUtils.defineLazyModuleGetter(this, 
 XPCOMUtils.defineLazyModuleGetter(this, 'Presentation',
   'resource://gre/modules/accessibility/Presentation.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'TraversalRules',
   'resource://gre/modules/accessibility/TraversalRules.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Roles',
   'resource://gre/modules/accessibility/Constants.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Events',
   'resource://gre/modules/accessibility/Constants.jsm');
+XPCOMUtils.defineLazyModuleGetter(this, 'States',
+  'resource://gre/modules/accessibility/Constants.jsm');
 
 this.EXPORTED_SYMBOLS = ['EventManager'];
 
 this.EventManager = function EventManager(aContentScope) {
   this.contentScope = aContentScope;
   this.addEventListener = this.contentScope.addEventListener.bind(
     this.contentScope);
   this.removeEventListener = this.contentScope.removeEventListener.bind(
@@ -142,23 +144,23 @@ this.EventManager.prototype = {
           Presentation.pivotChanged(position, event.oldAccessible, reason,
                                     pivot.startOffset, pivot.endOffset));
 
         break;
       }
       case Events.STATE_CHANGE:
       {
         let event = aEvent.QueryInterface(Ci.nsIAccessibleStateChangeEvent);
-        if (event.state == Ci.nsIAccessibleStates.STATE_CHECKED &&
-            !(event.isExtraState)) {
+        let state = Utils.getState(event);
+        if (state.contains(States.CHECKED)) {
           this.present(
             Presentation.
               actionInvoked(aEvent.accessible,
                             event.isEnabled ? 'check' : 'uncheck'));
-        } else if (event.state == Ci.nsIAccessibleStates.STATE_SELECTED) {
+        } else if (state.contains(States.SELECTED)) {
           this.present(
             Presentation.
               actionInvoked(aEvent.accessible,
                             event.isEnabled ? 'select' : 'unselect'));
         }
         break;
       }
       case Events.SCROLLING_START:
@@ -171,20 +173,20 @@ this.EventManager.prototype = {
       {
         let acc = aEvent.accessible;
         let characterCount = acc.
           QueryInterface(Ci.nsIAccessibleText).characterCount;
         let caretOffset = aEvent.
           QueryInterface(Ci.nsIAccessibleCaretMoveEvent).caretOffset;
 
         // Update editing state, both for presenter and other things
-        let [,extState] = Utils.getStates(acc);
+        let state = Utils.getState(acc);
         let editState = {
-          editing: !!(extState & Ci.nsIAccessibleStates.EXT_STATE_EDITABLE),
-          multiline: !!(extState & Ci.nsIAccessibleStates.EXT_STATE_MULTI_LINE),
+          editing: state.contains(States.EDITABLE),
+          multiline: state.contains(States.MULTI_LINE),
           atStart: caretOffset == 0,
           atEnd: caretOffset == characterCount
         };
 
         // Not interesting
         if (!editState.editing && editState.editing == this.editState.editing)
           break;
 
--- a/accessible/src/jsat/OutputGenerator.jsm
+++ b/accessible/src/jsat/OutputGenerator.jsm
@@ -24,16 +24,18 @@ XPCOMUtils.defineLazyModuleGetter(this, 
 XPCOMUtils.defineLazyModuleGetter(this, 'PrefCache',
   'resource://gre/modules/accessibility/Utils.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Logger',
   'resource://gre/modules/accessibility/Utils.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'PluralForm',
   'resource://gre/modules/PluralForm.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Roles',
   'resource://gre/modules/accessibility/Constants.jsm');
+XPCOMUtils.defineLazyModuleGetter(this, 'States',
+  'resource://gre/modules/accessibility/Constants.jsm');
 
 var gStringBundle = Cc['@mozilla.org/intl/stringbundle;1'].
   getService(Ci.nsIStringBundleService).
   createBundle('chrome://global/locale/AccessFu.properties');
 
 this.EXPORTED_SYMBOLS = ['UtteranceGenerator', 'BrailleGenerator'];
 
 this.OutputGenerator = {
@@ -92,36 +94,33 @@ this.OutputGenerator = {
   /**
    * Generates output for an object.
    * @param {nsIAccessible} aAccessible accessible object to generate output
    *    for.
    * @param {PivotContext} aContext object that generates and caches
    *    context information for a given accessible and its relationship with
    *    another accessible.
    * @return {Array} Two string array. The first string describes the object
-   *    and its states. The second string is the object's name. Whether the
+   *    and its state. The second string is the object's name. Whether the
    *    object's description or it's role is included is determined by
    *    {@link roleRuleMap}.
    */
   genForObject: function genForObject(aAccessible, aContext) {
     let roleString = Utils.AccRetrieval.getStringRole(aAccessible.role);
     let func = this.objectOutputFunctions[
       OutputGenerator._getOutputName(roleString)] ||
       this.objectOutputFunctions.defaultFunc;
 
     let flags = this.roleRuleMap[roleString] || 0;
 
     if (aAccessible.childCount == 0)
       flags |= INCLUDE_NAME;
 
-    let state = {};
-    let extState = {};
-    aAccessible.getState(state, extState);
-    let states = {base: state.value, ext: extState.value};
-    return func.apply(this, [aAccessible, roleString, states, flags, aContext]);
+    return func.apply(this, [aAccessible, roleString,
+                             Utils.getState(aAccessible), flags, aContext]);
   },
 
   /**
    * Generates output for an action performed.
    * @param {nsIAccessible} aAccessible accessible object that the action was
    *    invoked in.
    * @param {string} aActionName the name of the action, one of the keys in
    *    {@link gActionMap}.
@@ -235,17 +234,17 @@ this.OutputGenerator = {
   },
 
   _getOutputName: function _getOutputName(aName) {
     return aName.replace(' ', '');
   },
 
   _getLocalizedRole: function _getLocalizedRole(aRoleStr) {},
 
-  _getLocalizedStates: function _getLocalizedStates(aStates) {},
+  _getLocalizedState: function _getLocalizedState(aState) {},
 
   _getPluralFormString: function _getPluralFormString(aString, aCount) {
     let str = gStringBundle.GetStringFromName(this._getOutputName(aString));
     str = PluralForm.get(aCount, str);
     return str.replace('#1', aCount);
   },
 
   roleRuleMap: {
@@ -317,21 +316,21 @@ this.OutputGenerator = {
     'definition': NAME_FROM_SUBTREE_RULE,
     'key': NAME_FROM_SUBTREE_RULE,
     'image map': INCLUDE_DESC,
     'option': INCLUDE_DESC,
     'listbox': INCLUDE_DESC,
     'definitionlist': INCLUDE_DESC | INCLUDE_NAME},
 
   objectOutputFunctions: {
-    _generateBaseOutput: function _generateBaseOutput(aAccessible, aRoleStr, aStates, aFlags) {
+    _generateBaseOutput: function _generateBaseOutput(aAccessible, aRoleStr, aState, aFlags) {
       let output = [];
 
       if (aFlags & INCLUDE_DESC) {
-        let desc = this._getLocalizedStates(aStates);
+        let desc = this._getLocalizedState(aState);
         let roleStr = this._getLocalizedRole(aRoleStr);
         if (roleStr) {
           this._addType(desc, aAccessible, aRoleStr);
           desc.push(roleStr);
         }
         output.push(desc.join(' '));
       }
 
@@ -344,53 +343,52 @@ this.OutputGenerator = {
       }
 
       this._addName(output, aAccessible, aFlags);
       this._addLandmark(output, aAccessible);
 
       return output;
     },
 
-    label: function label(aAccessible, aRoleStr, aStates, aFlags, aContext) {
+    label: function label(aAccessible, aRoleStr, aState, aFlags, aContext) {
       if (aContext.isNestedControl ||
           aContext.accessible == Utils.getEmbeddedControl(aAccessible)) {
         // If we are on a nested control, or a nesting label,
         // we don't need the context.
         return [];
       }
 
       return this.objectOutputFunctions.defaultFunc.apply(this, arguments);
     },
 
-    entry: function entry(aAccessible, aRoleStr, aStates, aFlags) {
-      let rolestr = (aStates.ext & Ci.nsIAccessibleStates.EXT_STATE_MULTI_LINE) ?
-            'textarea' : 'entry';
+    entry: function entry(aAccessible, aRoleStr, aState, aFlags) {
+      let rolestr = aState.contains(States.MULTI_LINE) ? 'textarea' : 'entry';
       return this.objectOutputFunctions.defaultFunc.apply(
-        this, [aAccessible, rolestr, aStates, aFlags]);
+        this, [aAccessible, rolestr, aState, aFlags]);
     },
 
-    pagetab: function pagetab(aAccessible, aRoleStr, aStates, aFlags) {
+    pagetab: function pagetab(aAccessible, aRoleStr, aState, aFlags) {
       let localizedRole = this._getLocalizedRole(aRoleStr);
       let itemno = {};
       let itemof = {};
       aAccessible.groupPosition({}, itemof, itemno);
       let output = [];
-      let desc = this._getLocalizedStates(aStates);
+      let desc = this._getLocalizedState(aState);
       desc.push(
         gStringBundle.formatStringFromName(
           'objItemOf', [localizedRole, itemno.value, itemof.value], 3));
       output.push(desc.join(' '));
 
       this._addName(output, aAccessible, aFlags);
       this._addLandmark(output, aAccessible);
 
       return output;
     },
 
-    table: function table(aAccessible, aRoleStr, aStates, aFlags) {
+    table: function table(aAccessible, aRoleStr, aState, aFlags) {
       let output = [];
       let table;
       try {
         table = aAccessible.QueryInterface(Ci.nsIAccessibleTable);
       } catch (x) {
         Logger.logException(x);
         return output;
       } finally {
@@ -494,68 +492,68 @@ this.UtteranceGenerator = {
     return [gStringBundle.GetStringFromName(
               aIsEditing ? 'editingMode' : 'navigationMode')];
   },
 
   objectOutputFunctions: {
 
     __proto__: OutputGenerator.objectOutputFunctions,
 
-    defaultFunc: function defaultFunc(aAccessible, aRoleStr, aStates, aFlags) {
+    defaultFunc: function defaultFunc(aAccessible, aRoleStr, aState, aFlags) {
       return this.objectOutputFunctions._generateBaseOutput.apply(this, arguments);
     },
 
-    heading: function heading(aAccessible, aRoleStr, aStates, aFlags) {
+    heading: function heading(aAccessible, aRoleStr, aState, aFlags) {
       let level = {};
       aAccessible.groupPosition(level, {}, {});
       let utterance =
         [gStringBundle.formatStringFromName('headingLevel', [level.value], 1)];
 
       this._addName(utterance, aAccessible, aFlags);
       this._addLandmark(utterance, aAccessible);
 
       return utterance;
     },
 
-    listitem: function listitem(aAccessible, aRoleStr, aStates, aFlags) {
+    listitem: function listitem(aAccessible, aRoleStr, aState, aFlags) {
       let itemno = {};
       let itemof = {};
       aAccessible.groupPosition({}, itemof, itemno);
       let utterance = [];
       if (itemno.value == 1) // Start of list
         utterance.push(gStringBundle.GetStringFromName('listStart'));
       else if (itemno.value == itemof.value) // last item
         utterance.push(gStringBundle.GetStringFromName('listEnd'));
 
       this._addName(utterance, aAccessible, aFlags);
       this._addLandmark(utterance, aAccessible);
 
       return utterance;
     },
 
-    list: function list(aAccessible, aRoleStr, aStates, aFlags) {
+    list: function list(aAccessible, aRoleStr, aState, aFlags) {
       return this._getListUtterance
         (aAccessible, aRoleStr, aFlags, aAccessible.childCount);
     },
 
-    definitionlist: function definitionlist(aAccessible, aRoleStr, aStates, aFlags) {
+    definitionlist: function definitionlist(aAccessible, aRoleStr, aState, aFlags) {
       return this._getListUtterance
         (aAccessible, aRoleStr, aFlags, aAccessible.childCount / 2);
     },
 
-    application: function application(aAccessible, aRoleStr, aStates, aFlags) {
+    application: function application(aAccessible, aRoleStr, aState, aFlags) {
       // Don't utter location of applications, it gets tiring.
       if (aAccessible.name != aAccessible.DOMNode.location)
         return this.objectOutputFunctions.defaultFunc.apply(this,
-          [aAccessible, aRoleStr, aStates, aFlags]);
+          [aAccessible, aRoleStr, aState, aFlags]);
 
       return [];
     },
 
-    cell: function cell(aAccessible, aRoleStr, aStates, aFlags, aContext) {
+    cell: function cell(aAccessible, aRoleStr, aState, aFlags, aContext) {
       let utterance = [];
       let cell = aContext.getCellInfo(aAccessible);
       if (cell) {
         let desc = [];
         let addCellChanged = function addCellChanged(aDesc, aChanged, aString, aIndex) {
           if (aChanged) {
             aDesc.push(gStringBundle.formatStringFromName(aString,
               [aIndex + 1], 1));
@@ -607,52 +605,52 @@ this.UtteranceGenerator = {
   _getLocalizedRole: function _getLocalizedRole(aRoleStr) {
     try {
       return gStringBundle.GetStringFromName(this._getOutputName(aRoleStr));
     } catch (x) {
       return '';
     }
   },
 
-  _getLocalizedStates: function _getLocalizedStates(aStates) {
+  _getLocalizedState: function _getLocalizedState(aState) {
     let stateUtterances = [];
 
-    if (aStates.base & Ci.nsIAccessibleStates.STATE_UNAVAILABLE) {
+    if (aState.contains(States.UNAVAILABLE)) {
       stateUtterances.push(gStringBundle.GetStringFromName('stateUnavailable'));
     }
 
     // Don't utter this in Jelly Bean, we let TalkBack do it for us there.
     // This is because we expose the checked information on the node itself.
     // XXX: this means the checked state is always appended to the end, regardless
     // of the utterance ordering preference.
-    if (Utils.AndroidSdkVersion < 16 && aStates.base & Ci.nsIAccessibleStates.STATE_CHECKABLE) {
-      let stateStr = (aStates.base & Ci.nsIAccessibleStates.STATE_CHECKED) ?
+    if (Utils.AndroidSdkVersion < 16 && aState.contains(States.CHECKABLE)) {
+      let statetr = aState.contains(States.CHECKED) ?
         'stateChecked' : 'stateNotChecked';
-      stateUtterances.push(gStringBundle.GetStringFromName(stateStr));
+      stateUtterances.push(gStringBundle.GetStringFromName(statetr));
     }
 
-    if (aStates.ext & Ci.nsIAccessibleStates.EXT_STATE_EXPANDABLE) {
-      let stateStr = (aStates.base & Ci.nsIAccessibleStates.STATE_EXPANDED) ?
+    if (aState.contains(States.EXPANDABLE)) {
+      let statetr = aState.contains(States.EXPANDED) ?
         'stateExpanded' : 'stateCollapsed';
-      stateUtterances.push(gStringBundle.GetStringFromName(stateStr));
+      stateUtterances.push(gStringBundle.GetStringFromName(statetr));
     }
 
-    if (aStates.base & Ci.nsIAccessibleStates.STATE_REQUIRED) {
+    if (aState.contains(States.REQUIRED)) {
       stateUtterances.push(gStringBundle.GetStringFromName('stateRequired'));
     }
 
-    if (aStates.base & Ci.nsIAccessibleStates.STATE_TRAVERSED) {
+    if (aState.contains(States.TRAVERSED)) {
       stateUtterances.push(gStringBundle.GetStringFromName('stateTraversed'));
     }
 
-    if (aStates.base & Ci.nsIAccessibleStates.STATE_HASPOPUP) {
+    if (aState.contains(States.HASPOPUP)) {
       stateUtterances.push(gStringBundle.GetStringFromName('stateHasPopup'));
     }
 
-    if (aStates.base & Ci.nsIAccessibleStates.STATE_SELECTED) {
+    if (aState.contains(States.SELECTED)) {
       stateUtterances.push(gStringBundle.GetStringFromName('stateSelected'));
     }
 
     return stateUtterances;
   },
 
   _getListUtterance: function _getListUtterance(aAccessible, aRoleStr, aFlags, aItemCount) {
     let desc = [];
@@ -712,30 +710,30 @@ this.BrailleGenerator = {
 
     return output;
   },
 
   objectOutputFunctions: {
 
     __proto__: OutputGenerator.objectOutputFunctions,
 
-    defaultFunc: function defaultFunc(aAccessible, aRoleStr, aStates, aFlags) {
+    defaultFunc: function defaultFunc(aAccessible, aRoleStr, aState, aFlags) {
       return this.objectOutputFunctions._generateBaseOutput.apply(this, arguments);
     },
 
-    listitem: function listitem(aAccessible, aRoleStr, aStates, aFlags) {
+    listitem: function listitem(aAccessible, aRoleStr, aState, aFlags) {
       let braille = [];
 
       this._addName(braille, aAccessible, aFlags);
       this._addLandmark(braille, aAccessible);
 
       return braille;
     },
 
-    cell: function cell(aAccessible, aRoleStr, aStates, aFlags, aContext) {
+    cell: function cell(aAccessible, aRoleStr, aState, aFlags, aContext) {
       let braille = [];
       let cell = aContext.getCellInfo(aAccessible);
       if (cell) {
         let desc = [];
         let addHeaders = function addHeaders(aDesc, aHeaders) {
           if (aHeaders.length > 0) {
             aDesc.push.apply(aDesc, aHeaders);
           }
@@ -758,47 +756,47 @@ this.BrailleGenerator = {
     columnheader: function columnheader() {
       return this.objectOutputFunctions.cell.apply(this, arguments);
     },
 
     rowheader: function rowheader() {
       return this.objectOutputFunctions.cell.apply(this, arguments);
     },
 
-    statictext: function statictext(aAccessible, aRoleStr, aStates, aFlags) {
+    statictext: function statictext(aAccessible, aRoleStr, aState, aFlags) {
       // Since we customize the list bullet's output, we add the static
       // text from the first node in each listitem, so skip it here.
       if (aAccessible.parent.role == Roles.LISTITEM) {
         return [];
       }
 
       return this.objectOutputFunctions._useStateNotRole.apply(this, arguments);
     },
 
-    _useStateNotRole: function _useStateNotRole(aAccessible, aRoleStr, aStates, aFlags) {
+    _useStateNotRole: function _useStateNotRole(aAccessible, aRoleStr, aState, aFlags) {
       let braille = [];
 
-      let desc = this._getLocalizedStates(aStates);
+      let desc = this._getLocalizedState(aState);
       braille.push(desc.join(' '));
 
       this._addName(braille, aAccessible, aFlags);
       this._addLandmark(braille, aAccessible);
 
       return braille;
     },
 
-    checkbutton: function checkbutton(aAccessible, aRoleStr, aStates, aFlags) {
+    checkbutton: function checkbutton(aAccessible, aRoleStr, aState, aFlags) {
       return this.objectOutputFunctions._useStateNotRole.apply(this, arguments);
     },
 
-    radiobutton: function radiobutton(aAccessible, aRoleStr, aStates, aFlags) {
+    radiobutton: function radiobutton(aAccessible, aRoleStr, aState, aFlags) {
       return this.objectOutputFunctions._useStateNotRole.apply(this, arguments);
     },
 
-    togglebutton: function radiobutton(aAccessible, aRoleStr, aStates, aFlags) {
+    togglebutton: function radiobutton(aAccessible, aRoleStr, aState, aFlags) {
       return this.objectOutputFunctions._useStateNotRole.apply(this, arguments);
     }
   },
 
   _getContextStart: function _getContextStart(aContext) {
     if (aContext.accessible.parent.role == Roles.LINK) {
       return [aContext.accessible.parent];
     }
@@ -818,32 +816,32 @@ this.BrailleGenerator = {
         return gStringBundle.GetStringFromName(
           OutputGenerator._getOutputName(aRoleStr));
       } catch (y) {
         return '';
       }
     }
   },
 
-  _getLocalizedStates: function _getLocalizedStates(aStates) {
+  _getLocalizedState: function _getLocalizedState(aState) {
     let stateBraille = [];
 
     let getCheckedState = function getCheckedState() {
       let resultMarker = [];
-      let state = aStates.base;
-      let fill = !!(state & Ci.nsIAccessibleStates.STATE_CHECKED) ||
-                 !!(state & Ci.nsIAccessibleStates.STATE_PRESSED);
+      let state = aState;
+      let fill = state.contains(States.CHECKED) ||
+        state.contains(States.PRESSED);
 
       resultMarker.push('(');
       resultMarker.push(fill ? 'x' : ' ');
       resultMarker.push(')');
 
       return resultMarker.join('');
     };
 
-    if (aStates.base & Ci.nsIAccessibleStates.STATE_CHECKABLE) {
+    if (aState.contains(States.CHECKABLE)) {
       stateBraille.push(getCheckedState());
     }
 
     return stateBraille;
   }
 
 };
--- a/accessible/src/jsat/Presentation.jsm
+++ b/accessible/src/jsat/Presentation.jsm
@@ -17,16 +17,18 @@ XPCOMUtils.defineLazyModuleGetter(this, 
 XPCOMUtils.defineLazyModuleGetter(this, 'PivotContext',
   'resource://gre/modules/accessibility/Utils.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'UtteranceGenerator',
   'resource://gre/modules/accessibility/OutputGenerator.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'BrailleGenerator',
   'resource://gre/modules/accessibility/OutputGenerator.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Roles',
   'resource://gre/modules/accessibility/Constants.jsm');
+XPCOMUtils.defineLazyModuleGetter(this, 'States',
+  'resource://gre/modules/accessibility/Constants.jsm');
 
 this.EXPORTED_SYMBOLS = ['Presentation'];
 
 /**
  * The interface for all presenter classes. A presenter could be, for example,
  * a speech output module, or a visual cursor indicator.
  */
 function Presenter() {}
@@ -279,49 +281,47 @@ AndroidPresenter.prototype = {
         androidEvents.push({
           eventType: this.ANDROID_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY,
           text: [adjustedText.text],
           fromIndex: adjustedText.startOffset,
           toIndex: adjustedText.endOffset
         });
       }
     } else {
-      let state = Utils.getStates(aContext.accessible)[0];
+      let state = Utils.getState(aContext.accessible);
       androidEvents.push({eventType: (isExploreByTouch) ?
                            this.ANDROID_VIEW_HOVER_ENTER : focusEventType,
                          text: UtteranceGenerator.genForContext(aContext).output,
                          bounds: aContext.bounds,
                          clickable: aContext.accessible.actionCount > 0,
-                         checkable: !!(state &
-                                       Ci.nsIAccessibleStates.STATE_CHECKABLE),
-                         checked: !!(state &
-                                     Ci.nsIAccessibleStates.STATE_CHECKED),
+                         checkable: state.contains(States.CHECKABLE),
+                         checked: state.contains(States.CHECKED),
                          brailleOutput: brailleOutput});
     }
 
 
     return {
       type: this.type,
       details: androidEvents
     };
   },
 
   actionInvoked: function AndroidPresenter_actionInvoked(aObject, aActionName) {
-    let state = Utils.getStates(aObject)[0];
+    let state = Utils.getState(aObject);
 
     // Checkable objects will have a state changed event we will use instead.
-    if (state & Ci.nsIAccessibleStates.STATE_CHECKABLE)
+    if (state.contains(States.CHECKABLE))
       return null;
 
     return {
       type: this.type,
       details: [{
         eventType: this.ANDROID_VIEW_CLICKED,
         text: UtteranceGenerator.genForAction(aObject, aActionName),
-        checked: !!(state & Ci.nsIAccessibleStates.STATE_CHECKED)
+        checked: state.contains(States.CHECKED)
       }]
     };
   },
 
   tabSelected: function AndroidPresenter_tabSelected(aDocContext, aVCContext) {
     // Send a pivot change message with the full context utterance for this doc.
     return this.pivotChanged(aVCContext, Ci.nsIAccessiblePivot.REASON_NONE);
   },
--- a/accessible/src/jsat/TraversalRules.jsm
+++ b/accessible/src/jsat/TraversalRules.jsm
@@ -12,16 +12,18 @@ const Cr = Components.results;
 this.EXPORTED_SYMBOLS = ['TraversalRules'];
 
 Cu.import('resource://gre/modules/accessibility/Utils.jsm');
 Cu.import('resource://gre/modules/XPCOMUtils.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Roles',
   'resource://gre/modules/accessibility/Constants.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Filters',
   'resource://gre/modules/accessibility/Constants.jsm');
+XPCOMUtils.defineLazyModuleGetter(this, 'States',
+  'resource://gre/modules/accessibility/Constants.jsm');
 
 let gSkipEmptyImages = new PrefCache('accessibility.accessfu.skip_empty_images');
 
 function BaseTraversalRule(aRoles, aMatchFunc) {
   this._explicitMatchRoles = new Set(aRoles);
   this._matchRoles = aRoles;
   if (aRoles.indexOf(Roles.LABEL) < 0) {
     this._matchRoles.push(Roles.LABEL);
@@ -148,20 +150,17 @@ this.TraversalRules = {
     }
   ),
 
   Anchor: new BaseTraversalRule(
     [Roles.LINK],
     function Anchor_match(aAccessible)
     {
       // We want to ignore links, only focus named anchors.
-      let state = {};
-      let extraState = {};
-      aAccessible.getState(state, extraState);
-      if (state.value & Ci.nsIAccessibleStates.STATE_LINKED) {
+      if (Utils.getState(aAccessible).contains(States.LINKED)) {
         return Filters.IGNORE;
       } else {
         return Filters.MATCH;
       }
     }),
 
   Button: new BaseTraversalRule(
     [Roles.PUSHBUTTON,
@@ -216,20 +215,17 @@ this.TraversalRules = {
     [Roles.LISTITEM,
      Roles.TERM]),
 
   Link: new BaseTraversalRule(
     [Roles.LINK],
     function Link_match(aAccessible)
     {
       // We want to ignore anchors, only focus real links.
-      let state = {};
-      let extraState = {};
-      aAccessible.getState(state, extraState);
-      if (state.value & Ci.nsIAccessibleStates.STATE_LINKED) {
+      if (Utils.getState(aAccessible).contains(States.LINKED)) {
         return Filters.MATCH;
       } else {
         return Filters.IGNORE;
       }
     }),
 
   List: new BaseTraversalRule(
     [Roles.LIST,
--- a/accessible/src/jsat/Utils.jsm
+++ b/accessible/src/jsat/Utils.jsm
@@ -14,16 +14,18 @@ XPCOMUtils.defineLazyModuleGetter(this, 
 XPCOMUtils.defineLazyModuleGetter(this, 'Rect',
   'resource://gre/modules/Geometry.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Roles',
   'resource://gre/modules/accessibility/Constants.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Events',
   'resource://gre/modules/accessibility/Constants.jsm');
 XPCOMUtils.defineLazyModuleGetter(this, 'Relations',
   'resource://gre/modules/accessibility/Constants.jsm');
+XPCOMUtils.defineLazyModuleGetter(this, 'States',
+  'resource://gre/modules/accessibility/Constants.jsm');
 
 this.EXPORTED_SYMBOLS = ['Utils', 'Logger', 'PivotContext', 'PrefCache', 'SettingCache'];
 
 this.Utils = {
   _buildAppMap: {
     '{3c2e2abc-06d4-11e1-ac3b-374f68613e61}': 'b2g',
     '{ec8030f7-c20a-464f-9b0e-13a3a9e97384}': 'browser',
     '{aa3c5121-dab2-40e2-81ca-7ea25febc110}': 'mobile/android',
@@ -181,24 +183,46 @@ this.Utils = {
     switch (this.MozBuildApp) {
       case 'mobile/android':
         return aWindow.BrowserApp.selectedTab.getViewport();
       default:
         return null;
     }
   },
 
-  getStates: function getStates(aAccessible) {
-    if (!aAccessible)
-      return [0, 0];
+  getState: function getState(aAccessibleOrEvent) {
+    function State(aBase, aExtended) {
+      this.base = aBase;
+      this.extended = aExtended;
+
+      this.contains = (other) => {
+        return !!(this.base & other.base || this.extended & other.extended);
+      };
 
-    let state = {};
-    let extState = {};
-    aAccessible.getState(state, extState);
-    return [state.value, extState.value];
+      this.toString = () => {
+        let stateStrings = Utils.AccRetrieval.
+          getStringStates(this.base, this.extended);
+        let statesArray = new Array(stateStrings.length);
+        for (let i = 0; i < statesArray.length; i++) {
+          statesArray[i] = stateStrings.item(i);
+        }
+        return '[' + statesArray.join(', ') + ']';
+      };
+    }
+
+    if (aAccessibleOrEvent instanceof Ci.nsIAccessibleStateChangeEvent) {
+      return new State(
+        aAccessibleOrEvent.isExtraState ? 0 : aAccessibleOrEvent.state,
+        aAccessibleOrEvent.isExtraState ? aAccessibleOrEvent.state : 0);
+    } else {
+      let state = {};
+      let extState = {};
+      aAccessibleOrEvent.getState(state, extState);
+      return new State(state.value, extState.value);
+    }
   },
 
   getAttributes: function getAttributes(aAccessible) {
     let attributes = {};
 
     if (aAccessible && aAccessible.attributes) {
       let attributesEnum = aAccessible.attributes.enumerate();
 
@@ -246,21 +270,18 @@ this.Utils = {
   },
 
   isAliveAndVisible: function isAliveAndVisible(aAccessible) {
     if (!aAccessible) {
       return false;
     }
 
     try {
-      let extstate = {};
-      let state = {};
-      aAccessible.getState(state, extstate);
-      if (extstate.value & Ci.nsIAccessibleStates.EXT_STATE_DEFUNCT ||
-          state.value & Ci.nsIAccessibleStates.STATE_INVISIBLE ||
+      let state = this.getState(aAccessible);
+      if (state.contains(States.DEFUNCT) || state.contains(States.INVISIBLE) ||
           Utils.inHiddenSubtree(aAccessible)) {
         return false;
       }
     } catch (x) {
       return false;
     }
 
     return true;
@@ -404,22 +425,17 @@ this.Logger = {
         Utils.AccRetrieval.getStringStates(event.state, 0);
       str += ' (' + stateStrings.item(0) + ')';
     }
 
     return str;
   },
 
   statesToString: function statesToString(aAccessible) {
-    let [state, extState] = Utils.getStates(aAccessible);
-    let stringArray = [];
-    let stateStrings = Utils.AccRetrieval.getStringStates(state, extState);
-    for (var i=0; i < stateStrings.length; i++)
-      stringArray.push(stateStrings.item(i));
-    return stringArray.join(' ');
+    return Utils.getState(aAccessible).toString();
   },
 
   dumpTree: function dumpTree(aLogLevel, aRootAccessible) {
     if (aLogLevel < this.logLevel)
       return;
 
     this._dumpTreeInternal(aLogLevel, aRootAccessible, 0);
   },
@@ -582,18 +598,17 @@ PivotContext.prototype = {
       return;
     }
     let child = aAccessible.firstChild;
     while (child) {
       let include;
       if (this._includeInvisible) {
         include = true;
       } else {
-        let [state,] = Utils.getStates(child);
-        include = !(state & Ci.nsIAccessibleStates.STATE_INVISIBLE);
+        include = !(Utils.getState(child).contains(States.INVISIBLE));
       }
       if (include) {
         if (aPreorder) {
           yield child;
           [yield node for (node of this._traverse(child, aPreorder, aStop))];
         } else {
           [yield node for (node of this._traverse(child, aPreorder, aStop))];
           yield child;
@@ -711,19 +726,17 @@ PivotContext.prototype = {
       this._bounds = Utils.getBounds(this.accessibleForBounds);
     }
 
     return this._bounds.clone();
   },
 
   _isDefunct: function _isDefunct(aAccessible) {
     try {
-      let extstate = {};
-      aAccessible.getState({}, extstate);
-      return !!(extstate.value & Ci.nsIAccessibleStates.EXT_STATE_DEFUNCT);
+      return Utils.getState(aAccessible).contains(States.DEFUNCT);
     } catch (x) {
       return true;
     }
   }
 };
 
 this.PrefCache = function PrefCache(aName, aCallback, aRunCallbackNow) {
   this.name = aName;
--- a/accessible/src/jsat/content-script.js
+++ b/accessible/src/jsat/content-script.js
@@ -339,23 +339,31 @@ function scroll(aMessage) {
   if (!forwardToChild(aMessage, scroll, position)) {
     sendScrollCoordinates(position);
   }
 }
 
 function adjustRange(aMessage) {
   function sendUpDownKey(aAccessible) {
     let acc = Utils.getEmbeddedControl(aAccessible) || aAccessible;
-    if (acc.DOMNode) {
-      let evt = content.document.createEvent('KeyboardEvent');
-      let keycode = aMessage.json.direction == 'forward' ?
-        content.KeyEvent.DOM_VK_DOWN : content.KeyEvent.DOM_VK_UP;
-      evt.initKeyEvent(
-        "keypress", false, true, null, false, false, false, false, keycode, 0);
-      acc.DOMNode.dispatchEvent(evt);
+    let elem = acc.DOMNode;
+    if (elem) {
+      if (elem.tagName === 'INPUT' && elem.type === 'range') {
+        elem[aMessage.json.direction === 'forward' ? 'stepDown' : 'stepUp']();
+        let changeEvent = content.document.createEvent('UIEvent');
+        changeEvent.initEvent('change', true, true);
+        elem.dispatchEvent(changeEvent);
+      } else {
+        let evt = content.document.createEvent('KeyboardEvent');
+        let keycode = aMessage.json.direction == 'forward' ?
+              content.KeyEvent.DOM_VK_DOWN : content.KeyEvent.DOM_VK_UP;
+        evt.initKeyEvent(
+          "keypress", false, true, null, false, false, false, false, keycode, 0);
+        elem.dispatchEvent(evt);
+      }
     }
   }
 
   let position = Utils.getVirtualCursor(content.document).position;
   if (!forwardToChild(aMessage, adjustRange, position)) {
     sendUpDownKey(position);
   }
 }
--- a/browser/base/content/browser-plugins.js
+++ b/browser/base/content/browser-plugins.js
@@ -266,17 +266,18 @@ var gPluginHandler = {
   },
 
   handleEvent : function(event) {
     let eventType = event.type;
 
     if (eventType == "PluginRemoved") {
       let doc = event.target;
       let browser = gBrowser.getBrowserForDocument(doc.defaultView.top.document);
-      this._setPluginNotificationIcon(browser);
+      if (browser)
+        this._setPluginNotificationIcon(browser);
       return;
     }
 
     let plugin = event.target;
     let doc = plugin.ownerDocument;
 
     if (!(plugin instanceof Ci.nsIObjectLoadingContent))
       return;
@@ -296,16 +297,18 @@ var gPluginHandler = {
       if (!eventType) {
         // Not all bindings have handlers
         return;
       }
     }
 
     let shouldShowNotification = false;
     let browser = gBrowser.getBrowserForDocument(doc.defaultView.top.document);
+    if (!browser)
+      return;
 
     switch (eventType) {
       case "PluginCrashed":
         this.pluginInstanceCrashed(plugin, event);
         break;
 
       case "PluginNotFound":
         let installable = this.showInstallNotification(plugin, eventType);
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -827,22 +827,21 @@
 
       <toolbarbutton id="nav-bar-overflow-button"
                      class="toolbarbutton-1 chromeclass-toolbar-additional overflow-button"
                      skipintoolbarset="true"
                      tooltiptext="&navbarOverflow.label;"/>
 
       <toolbaritem id="PanelUI-button"
                    class="chromeclass-toolbar-additional"
-                   removable="false"
-                   title="&appmenu.title;">
+                   removable="false">
         <toolbarbutton id="PanelUI-menu-button"
                        class="toolbarbutton-1"
                        label="&brandShortName;"
-                       tooltiptext="&appmenu.title;"/>
+                       tooltiptext="&appmenu.tooltip;"/>
       </toolbaritem>
 
       <hbox id="window-controls" hidden="true" pack="end" skipintoolbarset="true"
             ordinal="1000">
         <toolbarbutton id="minimize-button"
                        tooltiptext="&fullScreenMinimize.tooltip;"
                        oncommand="window.minimize();"/>
 
--- a/browser/components/customizableui/content/customizeMode.inc.xul
+++ b/browser/components/customizableui/content/customizeMode.inc.xul
@@ -1,16 +1,16 @@
 <!-- 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/. -->
 
 <hbox id="customization-container" flex="1" hidden="true">
   <vbox flex="1" id="customization-palette-container">
     <label id="customization-header">
-      &customizeMode.menuAndToolbars.header;
+      &customizeMode.menuAndToolbars.header2;
     </label>
     <hbox id="customization-empty" hidden="true">
       <label>&customizeMode.menuAndToolbars.empty;</label>
       <label onclick="BrowserOpenAddonsMgr('addons://discovery/');"
              onkeypress="BrowserOpenAddonsMgr('addons://discovery/');"
              id="customization-more-tools"
              class="text-link">
         &customizeMode.menuAndToolbars.emptyLink;
--- a/browser/components/customizableui/src/CustomizeMode.jsm
+++ b/browser/components/customizableui/src/CustomizeMode.jsm
@@ -1406,20 +1406,23 @@ CustomizeMode.prototype = {
       // Otherwise, clear everything out:
       let positionManager = DragPositionManager.getManagerForArea(currentArea);
       positionManager.clearPlaceholders(currentArea, aNoTransition);
     }
   },
 
   _setGridDragActive: function(aDragOverNode, aDraggedItem, aValue) {
     let targetArea = this._getCustomizableParent(aDragOverNode);
+    let draggedWrapper = this.document.getElementById("wrapper-" + aDraggedItem.id);
+    let originArea = this._getCustomizableParent(draggedWrapper);
     let positionManager = DragPositionManager.getManagerForArea(targetArea);
     let draggedSize = this._getDragItemSize(aDragOverNode, aDraggedItem);
     let isWide = aDraggedItem.classList.contains(CustomizableUI.WIDE_PANEL_CLASS);
-    positionManager.insertPlaceholder(targetArea, aDragOverNode, isWide, draggedSize);
+    positionManager.insertPlaceholder(targetArea, aDragOverNode, isWide, draggedSize,
+                                      originArea == targetArea);
   },
 
   _getDragItemSize: function(aDragOverNode, aDraggedItem) {
     // Cache it good, cache it real good.
     if (!this._dragSizeMap)
       this._dragSizeMap = new WeakMap();
     if (!this._dragSizeMap.has(aDraggedItem))
       this._dragSizeMap.set(aDraggedItem, new WeakMap());
--- a/browser/components/customizableui/src/DragPositionManager.jsm
+++ b/browser/components/customizableui/src/DragPositionManager.jsm
@@ -121,17 +121,17 @@ AreaPositionManager.prototype = {
   },
 
   /**
    * "Insert" a "placeholder" by shifting the subsequent children out of the
    * way. We go through all the children, and shift them based on the position
    * they would have if we had inserted something before aBefore. We use CSS
    * transforms for this, which are CSS transitioned.
    */
-  insertPlaceholder: function(aContainer, aBefore, aWide, aSize) {
+  insertPlaceholder: function(aContainer, aBefore, aWide, aSize, aIsFromThisArea) {
     let isShifted = false;
     let shiftDown = aWide;
     for (let child of aContainer.children) {
       // Don't need to shift hidden nodes:
       if (child.getAttribute("hidden") == "true") {
         continue;
       }
       // If this is the node before which we're inserting, start shifting
@@ -152,27 +152,28 @@ AreaPositionManager.prototype = {
         isShifted = false;
       }
       if (isShifted) {
         // Conversely, if we're adding something before a wide node, for
         // simplicity's sake we move everything including the wide node down:
         if (this.__moveDown) {
           shiftDown = true;
         }
-        if (!this._lastPlaceholderInsertion) {
+        if (aIsFromThisArea && !this._lastPlaceholderInsertion) {
           child.setAttribute("notransition", "true");
         }
         // Determine the CSS transform based on the next node:
         child.style.transform = this._getNextPos(child, shiftDown, aSize);
       } else {
         // If we're not shifting this node, reset the transform
         child.style.transform = "";
       }
     }
-    if (aContainer.lastChild && !this._lastPlaceholderInsertion) {
+    if (aContainer.lastChild && aIsFromThisArea &&
+        !this._lastPlaceholderInsertion) {
       // Flush layout:
       aContainer.lastChild.getBoundingClientRect();
       // then remove all the [notransition]
       for (let child of aContainer.children) {
         child.removeAttribute("notransition");
       }
     }
     delete this.__moveDown;
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -771,16 +771,18 @@ bin/libfreebl_32int64_3.so
 #ifdef MOZ_MAINTENANCE_SERVICE
 @BINPATH@/maintenanceservice.exe
 @BINPATH@/maintenanceservice_installer.exe
 #endif
 
 ; [Crash Reporter]
 ;
 #ifdef MOZ_CRASHREPORTER
+@BINPATH@/components/CrashService.manifest
+@BINPATH@/components/CrashService.js
 #ifdef XP_MACOSX
 @BINPATH@/crashreporter.app/
 #else
 @BINPATH@/crashreporter@BIN_SUFFIX@
 @BINPATH@/crashreporter.ini
 #ifdef XP_UNIX
 @BINPATH@/Throbber-small.gif
 #endif
--- a/browser/locales/en-US/chrome/browser/browser.dtd
+++ b/browser/locales/en-US/chrome/browser/browser.dtd
@@ -10,17 +10,17 @@
 <!-- LOCALIZATION NOTE (mainWindow.titlemodifier) : DONT_TRANSLATE -->
 <!ENTITY mainWindow.titlemodifier "&brandFullName;">
 <!-- LOCALIZATION NOTE (mainWindow.titlemodifiermenuseparator): DONT_TRANSLATE -->
 <!ENTITY mainWindow.titlemodifiermenuseparator " - ">
 <!-- LOCALIZATION NOTE (mainWindow.titlePrivateBrowsingSuffix): This will be appended to the window's title
                                                                 inside the private browsing mode -->
 <!ENTITY mainWindow.titlePrivateBrowsingSuffix "(Private Browsing)">
 
-<!ENTITY appmenu.title                       "Customize and Control &brandFullName;">
+<!ENTITY appmenu.tooltip                     "Open menu">
 <!ENTITY navbarOverflow.label                "More tools…">
 
 <!-- Tab context menu -->
 <!ENTITY  reloadTab.label                    "Reload Tab">
 <!ENTITY  reloadTab.accesskey                "R">
 <!ENTITY  reloadAllTabs.label                "Reload All Tabs">
 <!ENTITY  reloadAllTabs.accesskey            "A">
 <!-- LOCALIZATION NOTE (closeTabsToTheEnd.label): This should indicate the
@@ -669,17 +669,17 @@ just addresses the organization to follo
 <!ENTITY social.learnMore.label "Learn more…">
 <!ENTITY social.learnMore.accesskey "l">
 <!ENTITY social.closeNotificationItem.label "Not Now">
 
 
 
 <!ENTITY customizeMode.tabTitle "Customize &brandShortName;">
 <!ENTITY customizeMode.menuAndToolbars.label "Menu and toolbars">
-<!ENTITY customizeMode.menuAndToolbars.header "More Tools to Add to the Menu and Toolbar">
+<!ENTITY customizeMode.menuAndToolbars.header2 "Additional Tools and Features">
 <!ENTITY customizeMode.menuAndToolbars.empty "Want more tools?">
 <!ENTITY customizeMode.menuAndToolbars.emptyLink "Choose from thousands of add-ons">
 <!ENTITY customizeMode.restoreDefaults "Restore Defaults">
 <!ENTITY customizeMode.toolbars "Show / Hide Toolbars">
 
 <!ENTITY social.chatBar.commandkey "c">
 <!ENTITY social.chatBar.label "Focus chats">
 <!ENTITY social.chatBar.accesskey "c">
--- a/browser/metro/base/content/appbar.js
+++ b/browser/metro/base/content/appbar.js
@@ -118,16 +118,19 @@ var Appbar = {
         Appbar._updateStarButton();
       });
     }
   },
 
   onMenuButton: function(aEvent) {
       let typesArray = [];
 
+      if (BrowserUI.isPrivateBrowsingEnabled) {
+        typesArray.push("private-browsing");
+      }
       if (!BrowserUI.isStartTabVisible) {
         typesArray.push("find-in-page");
         if (ContextCommands.getPageSource())
           typesArray.push("view-page-source");
       }
       if (ContextCommands.getStoreLink())
         typesArray.push("ms-meta-data");
       if (ConsolePanelView.enabled)
rename from browser/metro/base/content/browser.css
rename to browser/metro/base/content/bindings.css
--- a/browser/metro/base/content/browser-ui.js
+++ b/browser/metro/base/content/browser-ui.js
@@ -81,16 +81,18 @@ var BrowserUI = {
   init: function() {
     // start the debugger now so we can use it on the startup code as well
     if (Services.prefs.getBoolPref(debugServerStateChanged)) {
       this.runDebugServer();
     }
     Services.prefs.addObserver(debugServerStateChanged, this, false);
     Services.prefs.addObserver(debugServerPortChanged, this, false);
     Services.prefs.addObserver("app.crashreporter.autosubmit", this, false);
+    Services.prefs.addObserver("metro.private_browsing.enabled", this, false);
+    this.updatePrivateBrowsingUI();
 
     Services.obs.addObserver(this, "handle-xul-text-link", false);
 
     // listen content messages
     messageManager.addMessageListener("DOMTitleChanged", this);
     messageManager.addMessageListener("DOMWillOpenModalDialog", this);
     messageManager.addMessageListener("DOMWindowClose", this);
 
@@ -183,16 +185,22 @@ var BrowserUI = {
     messageManager.removeMessageListener("DOMWillOpenModalDialog", this);
     messageManager.removeMessageListener("DOMWindowClose", this);
 
     messageManager.removeMessageListener("Browser:OpenURI", this);
     messageManager.removeMessageListener("Browser:SaveAs:Return", this);
     messageManager.removeMessageListener("Content:StateChange", this);
 
     messageManager.removeMessageListener("Browser:MozApplicationManifest", OfflineApps);
+
+    Services.prefs.removeObserver(debugServerStateChanged, this);
+    Services.prefs.removeObserver(debugServerPortChanged, this);
+    Services.prefs.removeObserver("app.crashreporter.autosubmit", this);
+    Services.prefs.removeObserver("metro.private_browsing.enabled", this);
+
     Services.obs.removeObserver(this, "handle-xul-text-link");
 
     PanelUI.uninit();
     FlyoutPanelsUI.uninit();
     MetroDownloadsView.uninit();
     SettingsCharm.uninit();
     PageThumbs.uninit();
     if (WindowsPrefSync) {
@@ -406,19 +414,36 @@ var BrowserUI = {
   /*********************************
    * Tab management
    */
 
   /**
    * Open a new tab in the foreground in response to a user action.
    * See Browser.addTab for more documentation.
    */
-  addAndShowTab: function (aURI, aOwner) {
+  addAndShowTab: function (aURI, aOwner, aParams) {
     ContextUI.peekTabs(kForegroundTabAnimationDelay);
-    return Browser.addTab(aURI || kStartURI, true, aOwner);
+    return Browser.addTab(aURI || kStartURI, true, aOwner, aParams);
+  },
+
+  addAndShowPrivateTab: function (aURI, aOwner) {
+    return this.addAndShowTab(aURI, aOwner, { private: true });
+  },
+
+  get isPrivateBrowsingEnabled() {
+    return Services.prefs.getBoolPref("metro.private_browsing.enabled");
+  },
+
+  updatePrivateBrowsingUI: function () {
+    let command = document.getElementById("cmd_newPrivateTab");
+    if (this.isPrivateBrowsingEnabled) {
+      command.removeAttribute("disabled");
+    } else {
+      command.setAttribute("disabled", "true");
+    }
   },
 
   /**
    * Open a new tab in response to clicking a link in an existing tab.
    * See Browser.addTab for more documentation.
    */
   openLinkInNewTab: function (aURI, aBringFront, aOwner) {
     ContextUI.peekTabs(aBringFront ? kForegroundTabAnimationDelay
@@ -604,18 +629,19 @@ var BrowserUI = {
 
             // The user explicitly set the autosubmit option, so there is no
             // need to prompt them about crash reporting in the future
             Services.prefs.setBoolPref("app.crashreporter.prompted", true);
 
             BrowserUI.submitLastCrashReportOrShowPrompt;
 #endif
             break;
-
-
+          case "metro.private_browsing.enabled":
+            this.updatePrivateBrowsingUI();
+            break;
         }
         break;
     }
   },
 
   submitLastCrashReportOrShowPrompt: function() {
 #ifdef MOZ_CRASHREPORTER
     let lastCrashID = this.lastCrashID;
@@ -843,62 +869,66 @@ var BrowserUI = {
         break;
       // XXX this and content's sender are a little warped
       case "Browser:OpenURI":
         let referrerURI = null;
         if (json.referrer)
           referrerURI = Services.io.newURI(json.referrer, null, null);
         this.goToURI(json.uri);
         break;
-      case "Content:StateChange":
-        let currBrowser = Browser.selectedBrowser;
-        if (this.shouldCaptureThumbnails(currBrowser)) {
-          PageThumbs.captureAndStore(currBrowser);
-          let currPage = currBrowser.currentURI.spec;
+      case "Content:StateChange": {
+        let tab = Browser.selectedTab;
+        if (this.shouldCaptureThumbnails(tab)) {
+          PageThumbs.captureAndStore(tab.browser);
+          let currPage = tab.browser.currentURI.spec;
           Services.obs.notifyObservers(null, "Metro:RefreshTopsiteThumbnail", currPage);
         }
         break;
+      }
     }
 
     return {};
   },
 
-  // Private Browsing is not supported on metro at this time, when it is added
-  //  this function must be updated to skip capturing those pages
-  shouldCaptureThumbnails: function shouldCaptureThumbnails(aBrowser) {
+  shouldCaptureThumbnails: function shouldCaptureThumbnails(aTab) {
     // Capture only if it's the currently selected tab.
-    if (aBrowser != Browser.selectedBrowser) {
+    if (aTab != Browser.selectedTab) {
+      return false;
+    }
+    // Skip private tabs
+    if (aTab.isPrivate) {
       return false;
     }
     // FIXME Bug 720575 - Don't capture thumbnails for SVG or XML documents as
     //       that currently regresses Talos SVG tests.
-    let doc = aBrowser.contentDocument;
+    let browser = aTab.browser;
+    let doc = browser.contentDocument;
     if (doc instanceof SVGDocument || doc instanceof XMLDocument) {
       return false;
     }
 
     // Don't capture pages in snapped mode, this produces 2/3 black
     // thumbs or stretched out ones
     //   Ci.nsIWinMetroUtils.snapped is inaccessible on
     //   desktop/nonwindows systems
     if(Elements.windowState.getAttribute("viewstate") == "snapped") {
       return false;
     }
     // There's no point in taking screenshot of loading pages.
-    if (aBrowser.docShell.busyFlags != Ci.nsIDocShell.BUSY_FLAGS_NONE) {
+    if (browser.docShell.busyFlags != Ci.nsIDocShell.BUSY_FLAGS_NONE) {
       return false;
     }
 
     // Don't take screenshots of about: pages.
-    if (aBrowser.currentURI.schemeIs("about")) {
+    if (browser.currentURI.schemeIs("about")) {
       return false;
     }
 
     // No valid document channel. We shouldn't take a screenshot.
-    let channel = aBrowser.docShell.currentDocumentChannel;
+    let channel = browser.docShell.currentDocumentChannel;
     if (!channel) {
       return false;
     }
 
     // Don't take screenshots of internally redirecting about: pages.
     // This includes error pages.
     let uri = channel.originalURI;
     if (uri.schemeIs("about")) {
--- a/browser/metro/base/content/browser.js
+++ b/browser/metro/base/content/browser.js
@@ -471,16 +471,17 @@ var Browser = {
    *
    * @param aURI String specifying the URL to load.
    * @param aBringFront Boolean (optional) Open the new tab in the foreground?
    * @param aOwner Tab object (optional) The "parent" of the new tab.
    *   This is the tab responsible for opening the new tab.  When the new tab
    *   is closed, we will return to a parent or "sibling" tab if possible.
    * @param aParams Object (optional) with optional properties:
    *   index: Number specifying where in the tab list to insert the new tab.
+   *   private: If true, the new tab should be have Private Browsing active.
    *   flags, postData, charset, referrerURI: See loadURIWithFlags.
    */
   addTab: function browser_addTab(aURI, aBringFront, aOwner, aParams) {
     let params = aParams || {};
 
     if (aOwner && !('index' in params)) {
       // Position the new tab to the right of its owner...
       params.index = this._tabs.indexOf(aOwner) + 1;
@@ -1250,16 +1251,23 @@ function Tab(aURI, aParams, aOwner) {
   this._notification = null;
   this._loading = false;
   this._progressActive = false;
   this._progressCount = 0;
   this._chromeTab = null;
   this._eventDeferred = null;
   this._updateThumbnailTimeout = null;
 
+  this._private = false;
+  if ("private" in aParams) {
+    this._private = aParams.private;
+  } else if (aOwner) {
+    this._private = aOwner.private;
+  }
+
   this.owner = aOwner || null;
 
   // Set to 0 since new tabs that have not been viewed yet are good tabs to
   // toss if app needs more memory.
   this.lastSelected = 0;
 
   // aParams is an object that contains some properties for the initial tab
   // loading like flags, a referrerURI, a charset or even a postData.
@@ -1277,16 +1285,20 @@ Tab.prototype = {
   get notification() {
     return this._notification;
   },
 
   get chromeTab() {
     return this._chromeTab;
   },
 
+  get isPrivate() {
+    return this._private;
+  },
+
   get pageShowPromise() {
     return this._eventDeferred ? this._eventDeferred.promise : null;
   },
 
   startLoading: function startLoading() {
     if (this._loading) {
       let stack = new Error().stack;
       throw "Already Loading!\n" + stack;
@@ -1302,16 +1314,20 @@ Tab.prototype = {
   isLoading: function isLoading() {
     return this._loading;
   },
 
   create: function create(aURI, aParams, aOwner) {
     this._eventDeferred = Promise.defer();
 
     this._chromeTab = Elements.tabList.addTab(aParams.index);
+    if (this.isPrivate) {
+      this._chromeTab.setAttribute("private", "true");
+    }
+
     this._id = Browser.createTabId();
     let browser = this._createBrowser(aURI, null);
 
     let self = this;
     function onPageShowEvent(aEvent) {
       browser.removeEventListener("pageshow", onPageShowEvent);
       if (self._eventDeferred) {
         self._eventDeferred.resolve(self);
@@ -1456,16 +1472,21 @@ Tab.prototype = {
     notification.appendChild(stack);
     Elements.browsers.insertBefore(notification, aInsertBefore);
 
     notification.dir = "reverse";
 
      // let the content area manager know about this browser.
     ContentAreaObserver.onBrowserCreated(browser);
 
+    if (this.isPrivate) {
+      let ctx = browser.docShell.QueryInterface(Ci.nsILoadContext);
+      ctx.usePrivateBrowsing = true;
+    }
+
     // stop about:blank from loading
     browser.stop();
 
     let fl = browser.QueryInterface(Ci.nsIFrameLoaderOwner).frameLoader;
     fl.renderMode = Ci.nsIFrameLoader.RENDER_MODE_ASYNC_SCROLL;
 
     return browser;
   },
@@ -1480,17 +1501,19 @@ Tab.prototype = {
       this._browser = null;
       this._loading = false;
 
       Elements.browsers.removeChild(notification);
     }
   },
 
   updateThumbnail: function updateThumbnail() {
-    PageThumbs.captureToCanvas(this.browser.contentWindow, this._chromeTab.thumbnailCanvas);
+    if (!this.isPrivate) {
+      PageThumbs.captureToCanvas(this.browser.contentWindow, this._chromeTab.thumbnailCanvas);
+    }
   },
 
   updateFavicon: function updateFavicon() {
     this._chromeTab.updateFavicon(this._browser.mIconURL);
   },
 
   set active(aActive) {
     if (!this._browser)
--- a/browser/metro/base/content/browser.xul
+++ b/browser/metro/base/content/browser.xul
@@ -1,17 +1,17 @@
 <?xml version="1.0" encoding="Windows-1252" ?>
 
 <!-- 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/. -->
 
 <?xml-stylesheet href="chrome://browser/skin/platform.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/browser.css" type="text/css"?>
-<?xml-stylesheet href="chrome://browser/content/browser.css" type="text/css"?>
+<?xml-stylesheet href="chrome://browser/content/bindings.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/cssthrobber.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/tiles.css" type="text/css"?>
 <?xml-stylesheet href="chrome://branding/content/metro-about.css" type="text/css"?>
 
 <!DOCTYPE window [
 <!ENTITY % globalDTD SYSTEM "chrome://global/locale/global.dtd">
 %globalDTD;
 <!ENTITY % browserDTD SYSTEM "chrome://browser/locale/browser.dtd">
@@ -80,16 +80,17 @@
     <!-- tabs -->
     <command id="cmd_newTab" oncommand="CommandUpdater.doCommand(this.id);"/>
     <command id="cmd_newTabKey" oncommand="CommandUpdater.doCommand(this.id);"/>
     <command id="cmd_closeTab" oncommand="CommandUpdater.doCommand(this.id);"/>
     <command id="cmd_undoCloseTab" oncommand="CommandUpdater.doCommand(this.id);"/>
 #ifdef MOZ_SERVICES_SYNC
     <command id="cmd_remoteTabs" oncommand="CommandUpdater.doCommand(this.id);"/>
 #endif
+    <command id="cmd_newPrivateTab" oncommand="BrowserUI.addAndShowPrivateTab();"/>
 
     <!-- misc -->
     <command id="cmd_close" oncommand="CommandUpdater.doCommand(this.id);"/>
     <command id="cmd_quit" oncommand="CommandUpdater.doCommand(this.id);"/>
     <command id="cmd_actions" oncommand="CommandUpdater.doCommand(this.id);"/>
     <command id="cmd_panel" oncommand="CommandUpdater.doCommand(this.id);"/>
     <command id="cmd_flyout_back" oncommand="CommandUpdater.doCommand(this.id);"/>
     <command id="cmd_addBookmark" oncommand="CommandUpdater.doCommand(this.id);"/>
@@ -157,16 +158,17 @@ Desktop browser's sync prefs.
 -->
 
     <!-- manage tabs -->
     <key id="key_newTab" key="&newTab.key;" modifiers="accel" command="cmd_newTabKey"/>
     <key id="key_newTab2" key="&newTab2.key;" modifiers="accel" command="cmd_newTabKey"/>
     <key id="key_closeTab" key="&closeTab.key;" modifiers="accel" command="cmd_closeTab"/>
     <key id="key_closeTab2" keycode="VK_F4" modifiers="accel" command="cmd_closeTab"/>
     <key id="key_undoCloseTab" key="&newTab.key;" modifiers="accel,shift" command="cmd_undoCloseTab"/>
+    <key id="key_newPrivateTab" key="&newPrivateTab.key;" modifiers="accel,shift" command="cmd_newPrivateTab"/>
 
     <!-- tab selection -->
     <key id="key_nextTab" oncommand="BrowserUI.selectNextTab();" keycode="VK_TAB" modifiers="accel"/>
     <key id="key_nextTab2" oncommand="BrowserUI.selectNextTab();" keycode="VK_PAGE_DOWN" modifiers="accel"/>
     <key id="key_prevTab" oncommand="BrowserUI.selectPreviousTab();" keycode="VK_TAB" modifiers="accel,shift"/>
     <key id="key_prevTab2" oncommand="BrowserUI.selectPreviousTab();" keycode="VK_PAGE_UP" modifiers="accel"/>
     <key id="key_selectTab1" oncommand="BrowserUI.selectTabAtIndex(0);" key="1" modifiers="accel"/>
     <key id="key_selectTab2" oncommand="BrowserUI.selectTabAtIndex(1);" key="2" modifiers="accel"/>
@@ -395,38 +397,44 @@ Desktop browser's sync prefs.
 #ifdef MOZ_UPDATER
         <deck id="updateDeck" orient="vertical">
           <hbox id="updateButtonBox" align="center">
             <button id="updateButton" align="start"
                     oncommand="FlyoutPanelsUI.AboutFlyoutPanel.appUpdater.buttonOnCommand();"/>
             <spacer flex="1"/>
           </hbox>
           <hbox id="checkingForUpdates" align="center">
-            <image class="update-throbber"/><label>&update.checkingForUpdates;</label>
+            <image class="update-throbber"/>
+            <description flex="1">&update.checkingForUpdates;</description>
           </hbox>
           <hbox id="checkingAddonCompat" align="center">
-            <image class="update-throbber"/><label>&update.checkingAddonCompat;</label>
+            <image class="update-throbber"/>
+            <description flex="1">&update.checkingAddonCompat;</description>
           </hbox>
           <hbox id="downloading" align="center">
-            <image class="update-throbber"/><label>&update.downloading.start;</label><label id="downloadStatus"/><label>&update.downloading.end;</label>
+            <image class="update-throbber"/>
+            <description flex="1">
+              &update.downloading.start;<html:span id="downloadStatus"></html:span>&update.downloading.end;
+            </description>
           </hbox>
           <hbox id="applying" align="center">
-            <image class="update-throbber"/><label>&update.applying;</label>
+            <image class="update-throbber"/>
+            <description flex="1">&update.applying;</description>
           </hbox>
           <hbox id="downloadFailed" align="center">
             <label>&update.failed.start;</label><label id="failedLink" class="text-link">&update.failed.linkText;</label><label>&update.failed.end;</label>
           </hbox>
           <hbox id="adminDisabled" align="center">
-            <label>&update.adminDisabled;</label>
+            <label linewrap="true">&update.adminDisabled;</label>
           </hbox>
           <hbox id="noUpdatesFound" align="center">
-            <label>&update.noUpdatesFound;</label>
+            <label linewrap="true">&update.noUpdatesFound;</label>
           </hbox>
           <hbox id="otherInstanceHandlingUpdates" align="center">
-            <label>&update.otherInstanceHandlingUpdates;</label>
+            <label linewrap="true">&update.otherInstanceHandlingUpdates;</label>
           </hbox>
           <hbox id="manualUpdate" align="center">
             <label>&update.manual.start;</label><label id="manualLink" linewrap="true" class="text-link"/><label>&update.manual.end;</label>
           </hbox>
         </deck>
 #endif
       </vbox>
 #if MOZ_UPDATE_CHANNEL != release
@@ -802,16 +810,19 @@ Desktop browser's sync prefs.
           <richlistitem id="context-error-console" type="open-error-console" onclick="ContextCommands.errorConsole();">
             <label value="&appbarErrorConsole.label;"/>
           </richlistitem>
           <richlistitem id="context-jsshell" type="open-jsshell" onclick="ContextCommands.jsShell();">
             <label value="&appbarJSShell.label;"/>
           </richlistitem>
 
           <!-- standard buttons -->
+          <richlistitem id="context-newprivatetab" type="private-browsing" onclick="BrowserUI.addAndShowPrivateTab()">
+            <label value="&newPrivateTab.label;"/>
+          </richlistitem>
           <richlistitem id="context-findinpage" type="find-in-page" onclick="ContextCommands.findInPage();">
             <label value="&appbarFindInPage2.label;"/>
           </richlistitem>
           <richlistitem id="context-viewondesktop" type="view-on-desktop" onclick="ContextCommands.viewOnDesktop();">
             <label value="&appbarRelaunchInDesktop.label;"/>
           </richlistitem>
           <richlistitem id="context-msmetadata" type="ms-meta-data" onclick="ContextCommands.openWindowsStoreLink();">
             <label value="&appbarMSMetaData2.label;"/>
--- a/browser/metro/base/content/flyoutpanels/AboutFlyoutPanel.js
+++ b/browser/metro/base/content/flyoutpanels/AboutFlyoutPanel.js
@@ -501,17 +501,17 @@ appUpdater.prototype =
     this.setupDownloadingUI();
   },
 
   /**
    * Switches to the UI responsible for tracking the download.
    */
   setupDownloadingUI: function() {
     this.downloadStatus = document.getElementById("downloadStatus");
-    this.downloadStatus.value =
+    this.downloadStatus.textContent =
       DownloadUtils.getTransferTotal(0, this.update.selectedPatch.size);
     this.selectPanel("downloading");
     this.aus.addDownloadListener(this);
   },
 
   removeDownloadListener: function() {
     if (this.aus) {
       this.aus.removeDownloadListener(this);
@@ -593,17 +593,17 @@ appUpdater.prototype =
    */
   onStatus: function(aRequest, aContext, aStatus, aStatusArg) {
   },
 
   /**
    * See nsIProgressEventSink.idl
    */
   onProgress: function(aRequest, aContext, aProgress, aProgressMax) {
-    this.downloadStatus.value =
+    this.downloadStatus.textContent =
       DownloadUtils.getTransferTotal(aProgress, aProgressMax);
   },
 
   /**
    * See nsISupports.idl
    */
   QueryInterface: function(aIID) {
     if (!aIID.equals(Components.interfaces.nsIProgressEventSink) &&
--- a/browser/metro/base/content/pages/crashprompt.xhtml
+++ b/browser/metro/base/content/pages/crashprompt.xhtml
@@ -21,18 +21,17 @@
    - file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
 
 <html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <base href="http://www.mozilla.org/en-US/legal/privacy/firefox.html"></base>
     <meta name="viewport" content="width=device-width; user-scalable=false;" />
     <title>&crashprompt.title;</title>
     <link rel="stylesheet" href="chrome://browser/skin/platform.css" type="text/css" media="all" />
-    <link rel="stylesheet" href="chrome://browser/skin/browser.css" type="text/css" media="all" />
-    <link rel="stylesheet" href="chrome://browser/content/browser.css" type="text/css" media="all" />
+    <link rel="stylesheet" href="chrome://browser/content/bindings.css" type="text/css" media="all" />
     <link rel="stylesheet" href="chrome://browser/skin/crashprompt.css" type="text/css" media="all" />
     <!--TODO: Do we need a favicon?-->
 
     <script type="application/javascript"><![CDATA[
       Components.utils.import("resource://gre/modules/Services.jsm");
 
       function toggleDetailsVisible() {
         var arrow = document.getElementById("detailsArrow");
--- a/browser/metro/base/content/startui/Start.xul
+++ b/browser/metro/base/content/startui/Start.xul
@@ -1,18 +1,18 @@
 <?xml version="1.0"?>
 
 <!-- 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/. -->
 
 <?xml-stylesheet href="chrome://browser/skin/platform.css" type="text/css"?>
-<?xml-stylesheet href="chrome://browser/skin/browser.css" type="text/css"?>
-<?xml-stylesheet href="chrome://browser/content/browser.css" type="text/css"?>
+<?xml-stylesheet href="chrome://browser/content/bindings.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/tiles.css" type="text/css"?>
+<?xml-stylesheet href="chrome://browser/skin/start.css" type="text/css"?>
 
 <!DOCTYPE window [
 <!ENTITY % globalDTD SYSTEM "chrome://global/locale/global.dtd">
 %globalDTD;
 <!ENTITY % browserDTD SYSTEM "chrome://browser/locale/browser.dtd">
 %browserDTD;
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
 %brandDTD;
--- a/browser/metro/base/jar.mn
+++ b/browser/metro/base/jar.mn
@@ -70,17 +70,17 @@ chrome.jar:
   content/browser.js                           (content/browser.js)
 * content/browser-ui.js                        (content/browser-ui.js)
 * content/browser-scripts.js                   (content/browser-scripts.js)
   content/ContextCommands.js                   (content/ContextCommands.js)
   content/commandUtil.js                       (content/commandUtil.js)
   content/appbar.js                            (content/appbar.js)
   content/shell.xul                            (content/jsshell/shell.xul)
   content/shell.html                           (content/jsshell/shell.html)
-  content/browser.css                          (content/browser.css)
+  content/bindings.css                         (content/bindings.css)
   content/cursor.css                           (content/cursor.css)
   content/sanitize.js                          (content/sanitize.js)
   content/sanitizeUI.js                        (content/sanitizeUI.js)
   content/input.js                             (content/input.js)
   content/Util.js                              (content/Util.js)
   content/bookmarks.js                         (content/bookmarks.js)
   content/exceptions.js                        (content/exceptions.js)
   content/downloads.js                         (content/downloads.js)
new file mode 100644
--- /dev/null
+++ b/browser/metro/base/tests/mochiperf/browser_apzc.js
@@ -0,0 +1,111 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+let gStartView = null;
+
+function test() {
+  requestLongerTimeout(2);
+  runTests();
+}
+
+function setup() {
+  PanelUI.hide();
+
+  if (!BrowserUI.isStartTabVisible) {
+    let tab = yield addTab("about:start");
+    gStartView = tab.browser.contentWindow.BookmarksStartView._view;
+
+    yield waitForCondition(() => BrowserUI.isStartTabVisible);
+
+    yield hideContextUI();
+  }
+
+  BookmarksTestHelper.setup();
+  HistoryTestHelper.setup();
+}
+
+function tearDown() {
+  PanelUI.hide();
+  BookmarksTestHelper.restore();
+  HistoryTestHelper.restore();
+}
+
+gTests.push({
+  desc: "touch scroll",
+  run: function run() {
+    yield addTab(chromeRoot + "res/scroll_test.html");
+    yield hideContextUI();
+    yield hideNavBar();
+
+    let stopwatch = new StopWatch();
+    let win = Browser.selectedTab.browser.contentWindow;
+    let domUtils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
+
+    var touchdrag = new TouchDragAndHold();
+    touchdrag.useNativeEvents = true;
+    touchdrag.stepTimeout = 5;
+    touchdrag.numSteps = 20;
+
+    stopwatch.start();
+    let recordingHandle = domUtils.startFrameTimeRecording();
+    for (let count = 0; count < 3; count++) {
+      yield touchdrag.start(win, 100, (win.innerHeight - 50), 100, 50);
+      touchdrag.end();
+      yield touchdrag.start(win, 100, 50, 100, (win.innerHeight - 50));
+      touchdrag.end();
+    }
+    let intervals = domUtils.stopFrameTimeRecording(recordingHandle);
+    let msec = stopwatch.stop();
+
+
+    PerfTest.declareTest("14C693E5-3ED3-4A5D-93BC-A31F130A8CDE",
+                          "touch scroll text", "graphics", "apzc",
+                          "Measures performance of apzc scrolling for a large page of text using FTR.");
+    PerfTest.declareFrameRateResult(intervals.length, msec, "fps");
+  }
+});
+
+gTests.push({
+  desc: "touch scroll start",
+  setUp: setup,
+  tearDown: tearDown,
+  run: function run() {
+    let stopwatch = new StopWatch();
+    let win = Browser.selectedTab.browser.contentWindow;
+    let domUtils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
+
+    var touchdrag = new TouchDragAndHold();
+    touchdrag.useNativeEvents = true;
+    touchdrag.stepTimeout = 5;
+    touchdrag.numSteps = 20;
+
+    stopwatch.start();
+    let recordingHandle = domUtils.startFrameTimeRecording();
+    for (let count = 0; count < 3; count++) {
+      yield touchdrag.start(win, (win.innerWidth - 50), (win.innerHeight - 50), 50, (win.innerHeight - 50));
+      touchdrag.end();
+      yield touchdrag.start(win, 50, (win.innerHeight - 50), (win.innerWidth - 50), (win.innerHeight - 50));
+      touchdrag.end();
+    }
+    let intervals = domUtils.stopFrameTimeRecording(recordingHandle);
+    let msec = stopwatch.stop();
+
+    PerfTest.declareTest("24C693E5-3ED3-4A5D-93BC-A31F130A8CDE",
+                          "touch scroll about:start", "graphics", "apzc",
+                          "Measures performance of apzc scrolling for about:start using FTR.");
+    PerfTest.declareFrameRateResult(intervals.length, msec, "fps");
+
+    let results = PerfTest.computeHighLowBands(intervals, .1);
+    PerfTest.declareTest("2E60F8B5-8925-4628-988E-E4C0BC6B34C7",
+                          "about:start jank", "graphics", "apzc",
+                          "Displays the low, high, and average FTR frame intervals for about:start.");
+    info("results.low:" + results.low);
+    PerfTest.declareNumericalResults([
+      { value: results.low, desc: "low" },
+      { value: results.high, desc: "high" },
+      { value: results.ave, desc: "average" }
+    ]);
+  }
+});
--- a/browser/metro/base/tests/mochiperf/browser_deck_01.js
+++ b/browser/metro/base/tests/mochiperf/browser_deck_01.js
@@ -7,50 +7,47 @@ function test() {
   runTests();
 }
 
 gTests.push({
   desc: "deck offset",
   run: function run() {
     yield addTab("about:mozilla");
     yield hideContextUI();
-    yield waitForMs(5000);
+    yield hideNavBar();
+    yield waitForMs(3000);
 
     let shiftDataSet = new Array();
     let paintDataSet = new Array();
     let stopwatch = new StopWatch();
-
-    var paintCount = 0;
-    function onPaint() {
-      paintCount++;
-    }
+    let win = Browser.selectedTab.browser.contentWindow;
+    let domUtils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
 
     for (let idx = 0; idx < 10; idx++) {
-      window.addEventListener("MozAfterPaint", onPaint, true);
+      let recordingHandle = domUtils.startFrameTimeRecording();
       stopwatch.start();
       let promise = waitForEvent(window, "MozDeckOffsetChanged");
       ContentAreaObserver.shiftBrowserDeck(300);
       yield promise;
       promise = waitForEvent(window, "MozDeckOffsetChanged");
       ContentAreaObserver.shiftBrowserDeck(0);
       yield promise;
       stopwatch.stop();
       yield waitForMs(500);
-      window.removeEventListener("MozAfterPaint", onPaint, true);
+      let intervals = domUtils.stopFrameTimeRecording(recordingHandle);
       shiftDataSet.push(stopwatch.time());
-      paintDataSet.push(paintCount);
-      paintCount = 0;
+      paintDataSet.push(intervals.length);
     }
     
     PerfTest.declareTest("ecb5fbec-0b3d-490f-8d4a-13fa8963e54a",
                          "shift browser deck", "browser", "ux",
                          "Triggers multiple SKB deck shifting operations using an offset " +
                          "value of 300px. Measures total time in milliseconds for a up/down " +
-                         "shift operation plus the total number of paints. Strips outliers.");
+                         "shift operation plus the total number of frames. Strips outliers.");
     let shiftAverage = PerfTest.computeAverage(shiftDataSet, { stripOutliers: true });
     let paintAverage = PerfTest.computeAverage(paintDataSet, { stripOutliers: true });
     PerfTest.declareNumericalResults([
       { value: shiftAverage, desc: "msec" },
-      { value: paintAverage, desc: "paint count" },
+      { value: paintAverage, desc: "frame count" },
     ]);
   }
 });
 
--- a/browser/metro/base/tests/mochiperf/browser_layers_01.js
+++ b/browser/metro/base/tests/mochiperf/browser_layers_01.js
@@ -6,30 +6,30 @@
 function test() {
   runTests();
 }
 
 gTests.push({
   desc: "rotating divs",
   run: function run() {
     yield addTab(chromeRoot + "res/divs_test.html", true);
-
     yield hideContextUI();
+    yield hideNavBar();
 
     let stopwatch = new StopWatch();
-
     let win = Browser.selectedTab.browser.contentWindow;
+    let domUtils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
+    yield waitForEvent(win, "teststarted", 5000);
+    // the test runs for five seconds
+    let recordingHandle = domUtils.startFrameTimeRecording();
+    stopwatch.start();
+    let event = yield waitForEvent(win, "testfinished", 10000);
+    let intervals = domUtils.stopFrameTimeRecording(recordingHandle);
+    let msec = stopwatch.stop();
 
     PerfTest.declareTest("B924F3FA-4CB5-4453-B131-53E3611E0765",
                          "rotating divs w/text", "graphics", "content",
                          "Measures animation frames for rotating translucent divs on top of a background of text.");
-
-
-    stopwatch.start();
-    // the test runs for ten seconds
-    let event = yield waitForEvent(win, "testfinished", 20000);
-    let msec = stopwatch.stop();
-
-    PerfTest.declareNumericalResult((event.detail.frames / msec) * 1000.0, "fps");
+    PerfTest.declareFrameRateResult(intervals.length, msec, "fps");
   }
 });
 
 
--- a/browser/metro/base/tests/mochiperf/browser_miscgfx_01.js
+++ b/browser/metro/base/tests/mochiperf/browser_miscgfx_01.js
@@ -13,149 +13,96 @@ function tapRadius() {
   return Services.prefs.getIntPref("ui.dragThresholdX") / 240 * dpi; // 27.999998728434246
 }
 
 gTests.push({
   desc: "scrollBy",
   run: function run() {
     yield addTab(chromeRoot + "res/scroll_test.html");
     yield hideContextUI();
+    yield hideNavBar();
 
     let stopwatch = new StopWatch();
-
     let win = Browser.selectedTab.browser.contentWindow;
-
-    PerfTest.declareTest("79235F74-037C-4F6B-AE47-FDCCC13458C3",
-                         "scrollBy scroll", "graphics", "content",
-                         "Measures performance of single line scrolls using scrollBy for a large page of text.");
-
-    let mozpaints = 0;
-    function onPaint() {
-      mozpaints++;
-    }
-    win.addEventListener("MozAfterPaint", onPaint, true);
-
+    let domUtils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
     let deferExit = Promise.defer();
+    let recordingHandle = domUtils.startFrameTimeRecording();
 
     function step() {
-      if (stopwatch.time() < 10000) {
+      if (stopwatch.time() < 5000) {
         win.scrollBy(0, 2);
-        // XXX slaves won't paint without this
         win.mozRequestAnimationFrame(step);
         return;
       }
-      win.removeEventListener("MozAfterPaint", onPaint, true);
+
+      let intervals = domUtils.stopFrameTimeRecording(recordingHandle);
       let msec = stopwatch.stop();
-      PerfTest.declareFrameRateResult(mozpaints, msec, "fps");
-      deferExit.resolve();
-    }
-
-    stopwatch.start();
-    win.mozRequestAnimationFrame(step);
-    yield deferExit.promise;
-  }
-});
-
-gTests.push({
-  desc: "scoll touch",
-  run: function run() {
-    yield addTab(chromeRoot + "res/scroll_test.html");
-    yield hideContextUI();
-
-    let stopwatch = new StopWatch();
-
-    let win = Browser.selectedTab.browser.contentWindow;
-
-    PerfTest.declareTest("14C693E5-3ED3-4A5D-93BC-A31F130A8CDE",
-                         "touch scroll", "graphics", "content",
-                         "Measures performance of single line scrolls using touch input for a large page of text.");
-
-    let y = win.innerHeight - 10;
-    EventUtils.synthesizeTouchAtPoint(100, y, { type: "touchstart" }, win);
-    EventUtils.synthesizeTouchAtPoint(100, y, { type: "touchmove" }, win);
-    y -= tapRadius() + 5;
-    EventUtils.synthesizeTouchAtPoint(100, y, { type: "touchmove" }, win);
-
-    let mozpaints = 0;
-    function onPaint() {
-      mozpaints++;
-    }
-    win.addEventListener("MozAfterPaint", onPaint, true);
-
-    let deferExit = Promise.defer();
-
-    function step() {
-      if (stopwatch.time() < 10000) {
-        y -= 2;
-        EventUtils.synthesizeTouchAtPoint(100, y, { type: "touchmove" }, win);
-        win.mozRequestAnimationFrame(step);
-        return;
-      }
-      win.removeEventListener("MozAfterPaint", onPaint, true);
-      let msec = stopwatch.stop();
-      EventUtils.synthesizeTouchAtPoint(100, y, { type: "touchend" }, win);
-      PerfTest.declareFrameRateResult(mozpaints, msec, "fps");
+      PerfTest.declareTest("79235F74-037C-4F6B-AE47-FDCCC13458C3",
+                           "scrollBy scroll", "graphics", "content",
+                           "Measures performance of single line scrolls for a large page of text using FTR.");
+      PerfTest.declareFrameRateResult(intervals.length, msec, "fps");
       deferExit.resolve();
     }
 
     stopwatch.start();
     win.mozRequestAnimationFrame(step);
     yield deferExit.promise;
   }
 });
 
 gTests.push({
   desc: "canvas perf test",
   run: function run() {
     yield addTab(chromeRoot + "res/ripples.html");
+    yield hideContextUI();
+    yield hideNavBar();
+
     let win = Browser.selectedTab.browser.contentWindow;
-    yield hideContextUI();
+    let domUtils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
+    let recordingHandle = domUtils.startFrameTimeRecording();
     PerfTest.declareTest("6A455F96-2B2C-4B3C-B387-1AF2F1747CCF",
                          "ripples", "graphics", "canvas",
                          "Measures animation frames during a computationally " +
-                         "heavy graphics demo using canvas.");
+                         "heavy graphics demo using canvas using FTR.");
     let stopwatch = new StopWatch(true);
-    let event = yield waitForEvent(win, "test", 20000);
+    // test page runs for 5 seconds
+    let event = yield waitForEvent(win, "test", 10000);
+    let intervals = domUtils.stopFrameTimeRecording(recordingHandle);
     let msec = stopwatch.stop();
-    PerfTest.declareFrameRateResult(event.detail.frames, msec, "fps");
-
+    PerfTest.declareFrameRateResult(intervals.length, msec, "fps");
   }
 });
 
 gTests.push({
   desc: "video perf test",
   run: function run() {
     yield addTab(chromeRoot + "res/tidevideo.html");
     let win = Browser.selectedTab.browser.contentWindow;
+    let domUtils = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils);
     let video = win.document.getElementById("videoelement");
     video.pause();
     yield hideContextUI();
+    yield hideNavBar();
     yield waitForMs(1000);
     PerfTest.declareTest("7F55F9C4-0ECF-4A13-9A9C-A38D46922C0B",
                          "video playback (moz paints)", "graphics", "video",
-                         "Measures MozAfterPaints per second during five seconds of playback of an mp4.");
+                         "Measures frames per second during five seconds of playback of an mp4.");
 
-    var paintCount = 0;
-    function onPaint() {
-      paintCount++;
-    }
+    let recordingHandle = domUtils.startFrameTimeRecording();
     let stopwatch = new StopWatch(true);
-    window.addEventListener("MozAfterPaint", onPaint, true);
     video.play();
     yield waitForMs(5000);
     video.pause();
-    window.removeEventListener("MozAfterPaint", onPaint, true);
+    let intervals = domUtils.stopFrameTimeRecording(recordingHandle);
     let msec = stopwatch.stop();
-
-    PerfTest.declareNumericalResult((paintCount / msec) * 1000.0, "pps");
+    PerfTest.declareFrameRateResult(intervals.length, msec, "fps");
 
     PerfTest.declareTest("E132D333-4642-4597-B1F0-1E74B625DBD7",
                          "video playback (moz stats)", "graphics", "video",
                          "Report moz* related video performance stats during five seconds of playback of an mp4.");
     let results = [];
     results.push({ value: (video.mozDecodedFrames / msec) * 1000.0, desc: "mozDecodedFrames" });
     results.push({ value: (video.mozParsedFrames / msec) * 1000.0, desc: "mozParsedFrames", shareAxis: 0 });
     results.push({ value: (video.mozPresentedFrames / msec) * 1000.0, desc: "mozPresentedFrames", shareAxis: 0 });
     results.push({ value: (video.mozPaintedFrames / msec) * 1000.0, desc: "mozPaintedFrames", shareAxis: 0 });
     PerfTest.declareNumericalResults(results);
   }
 });
-
--- a/browser/metro/base/tests/mochiperf/head.js
+++ b/browser/metro/base/tests/mochiperf/head.js
@@ -174,16 +174,39 @@ var PerfTest = {
       if (idx != high && idx != low) {
         total += aArray[idx];
         count++;
       }
     }
     return total / count;
   },
 
+  computeHighLowBands: function computeHighLow(aArray, aPercentage) {
+    let bandCount = Math.ceil(aArray.length * aPercentage);
+    let lowGroup = 0, highGroup = 0;
+    let idx;
+
+    function compareNumbers(a, b) {
+      return a - b;
+    }
+    aArray.sort(compareNumbers);
+    for (idx = 0; idx < bandCount; idx++) {
+      lowGroup += aArray[idx];
+    }
+    let top = aArray.length - 1;
+    for (idx = top; idx > (top - bandCount); idx--) {
+      highGroup += aArray[idx];
+    }
+    return {
+      low: lowGroup / bandCount,
+      high: highGroup / bandCount,
+      ave: this.computeAverage(aArray, {})
+    };
+  },
+
   /******************************************************
    * Internal
    */
 
   _print: function _print() {
     let str = kInfoHeader;
     for (let idx = 0; idx < arguments.length; idx++) {
       str += arguments[idx];
--- a/browser/metro/base/tests/mochiperf/metro.ini
+++ b/browser/metro/base/tests/mochiperf/metro.ini
@@ -6,14 +6,15 @@ support-files =
   msgmanagerecho.js
   res/ripples.html
   res/scroll_test.html
   res/tidevideo.html
   res/tide.mp4
   res/divs_test.html
   res/fx.png
 
+[browser_apzc.js]
 [browser_miscgfx_01.js]
 [browser_tabs_01.js]
 [browser_deck_01.js]
 [browser_msgmgr_01.js]
 [browser_layers_01.js]
 [browser_firstx.js]
--- a/browser/metro/base/tests/mochiperf/res/divs_test.html
+++ b/browser/metro/base/tests/mochiperf/res/divs_test.html
@@ -65,22 +65,25 @@ function render()
   document.getElementById("div2").style.transform = "rotate(" + (rot + 30) + "deg)";
   document.getElementById("div3").style.transform = "rotate(" + (rot + 60) + "deg) " + "scale(" + scale + ")";
 }
 
 var frames = 0;
 
 function go() {
   var now = new Date();
+  var evt = document.createEvent("CustomEvent");
+  evt.initCustomEvent("teststarted", true, false, {});
+  window.dispatchEvent(evt);
   function step(timestamp) {
     render();
     frames++;
     var time = new Date();
     var diff = time.getTime() - now.getTime();
-    if (diff < 10000) {
+    if (diff < 5000) {
       window.mozRequestAnimationFrame(step);
     } else {
       var evt = document.createEvent("CustomEvent");
       evt.initCustomEvent("testfinished", true, false, { frames: frames });
       window.dispatchEvent(evt);
     }
   }
   window.mozRequestAnimationFrame(step);
--- a/browser/metro/base/tests/mochiperf/res/ripples.html
+++ b/browser/metro/base/tests/mochiperf/res/ripples.html
@@ -226,17 +226,17 @@ function run() {
   ripples.init();
   var now = new Date();
   var start = window.mozAnimationStartTime;
   function step(timestamp) {
     progress = timestamp - start;
     ripples.run(progress);
     var time = new Date();
     var diff = time.getTime() - now.getTime();
-    if (diff < 10000) { // ten seconds
+    if (diff < 5000) { // five seconds
       window.mozRequestAnimationFrame(step);
     } else {
       var evt = document.createEvent("CustomEvent");
       evt.initCustomEvent("test", true, false, { testName: "ripples", frames: ripples.frames, msec: diff });
       window.dispatchEvent(evt);
     }
   }
   window.mozRequestAnimationFrame(step);
new file mode 100644
--- /dev/null
+++ b/browser/metro/base/tests/mochitest/browser_private_browsing.js
@@ -0,0 +1,27 @@
+/* vim: set ts=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/. */
+
+"use strict";
+
+function test() {
+  runTests();
+}
+
+gTests.push({
+  desc: "Private tab sanity check",
+  run: function() {
+    let tab = Browser.addTab("about:mozilla");
+    is(tab.isPrivate, false, "Tabs are not private by default");
+    is(tab.chromeTab.hasAttribute("private"), false,
+      "non-private tab has no private attribute");
+    Browser.closeTab(tab, { forceClose: true });
+
+    tab = Browser.addTab("about:mozilla", false, null, { private: true });
+    is(tab.isPrivate, true, "Create a private tab");
+    is(tab.chromeTab.getAttribute("private"), "true",
+      "private tab has private attribute");
+    Browser.closeTab(tab, { forceClose: true });
+  }
+});
--- a/browser/metro/base/tests/mochitest/browser_progress_indicator.xul
+++ b/browser/metro/base/tests/mochitest/browser_progress_indicator.xul
@@ -1,15 +1,15 @@
 <?xml version="1.0"?>
 
 <!-- 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/. -->
 
 <?xml-stylesheet href="chrome://browser/skin/platform.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/browser.css" type="text/css"?>
-<?xml-stylesheet href="chrome://browser/content/browser.css" type="text/css"?>
+<?xml-stylesheet href="chrome://browser/content/bindings.css" type="text/css"?>
 
 <!DOCTYPE window []>
 
 <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
   <circularprogressindicator id="progress-indicator" oncommand=""/>
-</window>
\ No newline at end of file
+</window>
--- a/browser/metro/base/tests/mochitest/browser_tilegrid.xul
+++ b/browser/metro/base/tests/mochitest/browser_tilegrid.xul
@@ -1,17 +1,17 @@
 <?xml version="1.0"?>
 
 <!-- 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/. -->
 
 <?xml-stylesheet href="chrome://browser/skin/platform.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/browser.css" type="text/css"?>
-<?xml-stylesheet href="chrome://browser/content/browser.css" type="text/css"?>
+<?xml-stylesheet href="chrome://browser/content/bindings.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/tiles.css" type="text/css"?>
 <!DOCTYPE window []>
 <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
   <vbox id="alayout">
       <richgrid id="grid_layout" seltype="single" nocontext="true" flex="1">
       </richgrid>
   </vbox>
   <vbox>
--- a/browser/metro/base/tests/mochitest/head.js
+++ b/browser/metro/base/tests/mochitest/head.js
@@ -208,21 +208,32 @@ function hideContextUI()
       ContextUI.dismissContextAppbar();
       yield promise;
     }
   });
 }
 
 function showNavBar()
 {
-  let promise = waitForEvent(Elements.navbar, "transitionend");
   if (!ContextUI.navbarVisible) {
+    let promise = waitForEvent(Elements.navbar, "transitionend");
     ContextUI.displayNavbar();
     return promise;
   }
+  return Promise.resolve(null);
+}
+
+function hideNavBar()
+{
+  if (ContextUI.navbarVisible) {
+    let promise = waitForEvent(Elements.navbar, "transitionend");
+    ContextUI.dismissNavbar();
+    return promise;
+  }
+  return Promise.resolve(null);
 }
 
 function fireAppBarDisplayEvent()
 {
   let promise = waitForEvent(Elements.tray, "transitionend");
   let event = document.createEvent("Events");
   event.initEvent("MozEdgeUICompleted", true, false);
   gWindow.dispatchEvent(event);
@@ -822,16 +833,24 @@ TouchDragAndHold.prototype = {
   _native: false,
   _pointerId: 1,
   _dui: Components.interfaces.nsIDOMWindowUtils,
 
   set useNativeEvents(aValue) {
     this._native = aValue;
   },
 
+  set stepTimeout(aValue) {
+    this._timeoutStep = aValue;
+  },
+
+  set numSteps(aValue) {
+    this._numSteps = aValue;
+  },
+
   set nativePointerId(aValue) {
     this._pointerId = aValue;
   },
 
   callback: function callback() {
     if (this._win == null)
       return;
 
--- a/browser/metro/base/tests/mochitest/metro.ini
+++ b/browser/metro/base/tests/mochitest/metro.ini
@@ -48,16 +48,17 @@ support-files =
 [browser_form_selects.js]
 [browser_history.js]
 [browser_inputsource.js]
 [browser_link_click.js]
 [browser_menu_hoverstate.js]
 [browser_mouse_events.js]
 [browser_onscreen_keyboard.js]
 [browser_prefs_ui.js]
+[browser_private_browsing.js]
 [browser_prompt.js]
 [browser_remotetabs.js]
 [browser_snappedState.js]
 [browser_tabs.js]
 [browser_tabs_container.js]
 [browser_test.js]
 [browser_tiles.js]
 [browser_topsites.js]
--- a/browser/metro/components/SessionStore.js
+++ b/browser/metro/components/SessionStore.js
@@ -548,25 +548,27 @@ SessionStore.prototype = {
     tabData.entries = aHistory.entries;
     tabData.index = aHistory.index;
     tabData.attributes = { image: aBrowser.mIconURL };
 
     aBrowser.__SS_data = tabData;
   },
 
   _getTabData: function(aWindow) {
-    return aWindow.Browser.tabs.map(tab => {
-      let browser = tab.browser;
-      if (browser.__SS_data) {
-        let tabData = browser.__SS_data;
-        if (browser.__SS_extdata)
-          tabData.extData = browser.__SS_extdata;
-        return tabData;
-      }
-    });
+    return aWindow.Browser.tabs
+      .filter(tab => !tab.isPrivate)
+      .map(tab => {
+        let browser = tab.browser;
+        if (browser.__SS_data) {
+          let tabData = browser.__SS_data;
+          if (browser.__SS_extdata)
+            tabData.extData = browser.__SS_extdata;
+          return tabData;
+        }
+      });
   },
 
   _collectWindowData: function ss__collectWindowData(aWindow) {
     // Ignore windows not tracked by SessionStore
     if (!aWindow.__SSID || !this._windows[aWindow.__SSID])
       return;
 
     let winData = this._windows[aWindow.__SSID];
--- a/browser/metro/locales/en-US/chrome/browser.dtd
+++ b/browser/metro/locales/en-US/chrome/browser.dtd
@@ -4,16 +4,17 @@
 
 <!-- NAVBAR AND AUTOCOMPLETE -->
 
 <!ENTITY urlbar.emptytext      "Enter Search or Address">
 
 <!ENTITY back.label            "Back">
 <!ENTITY forward.label         "Forward">
 <!ENTITY newtab.label          "New Tab">
+<!ENTITY newPrivateTab.label   "New Private Tab">
 <!ENTITY closetab.label        "Close Tab">
 
 <!ENTITY autocompleteResultsHeader.label  "Your Results">
 
 <!ENTITY appbarErrorConsole.label      "Open error console">
 <!ENTITY appbarJSShell.label           "Open JavaScript shell">
 <!ENTITY appbarFindInPage2.label       "Find in page">
 <!ENTITY appbarRelaunchInDesktop.label "Relaunch in Desktop">
@@ -98,16 +99,18 @@
 <!ENTITY savePage.key "s">
 <!ENTITY find.key "f">
 <!ENTITY findNext.key "g">
 <!ENTITY quit.key "q">
 <!ENTITY addBookmark.key "d">
 <!ENTITY newTab.key "t">
 <!ENTITY newTab2.key "n">
 <!ENTITY closeTab.key "w">
+<!-- Private browsing (control+shift+key) -->
+<!ENTITY newPrivateTab.key "p">
 
 <!-- DEVELOPER SHORTCUTS (control+shift+key) -->
 <!ENTITY jsConsole.key "j">
 <!ENTITY optionsFlyout.key "o">
 <!ENTITY syncFlyout.key "s">
 <!ENTITY aboutFlyout.key "a">
 
 <!-- FIRT RUN EXPERIENCE -->
--- a/browser/metro/profile/metro.js
+++ b/browser/metro/profile/metro.js
@@ -28,20 +28,22 @@ pref("app.crashreporter.submitURLs", fal
 pref("app.crashreporter.prompted", false);
 
 // Debug prefs, see input.js
 pref("metro.debug.colorizeInputOverlay", false);
 pref("metro.debug.selection.displayRanges", false);
 pref("metro.debug.selection.dumpRanges", false);
 pref("metro.debug.selection.dumpEvents", false);
 
+// Private browsing is disabled by default until implementation and testing are complete
+pref("metro.private_browsing.enabled", false);
+
 // Enable tab-modal prompts
 pref("prompts.tab_modal.enabled", true);
 
-
 // Enable off main thread compositing
 pref("layers.offmainthreadcomposition.enabled", true);
 pref("layers.async-pan-zoom.enabled", true);
 pref("layers.componentalpha.enabled", false);
 
 // Prefs to control the async pan/zoom behaviour
 pref("apz.touch_start_tolerance", "0.1"); // dpi * tolerance = pixel threshold
 pref("apz.pan_repaint_interval", 50);   // prefer 20 fps
--- a/browser/metro/theme/browser.css
+++ b/browser/metro/theme/browser.css
@@ -158,16 +158,22 @@ documenttab[closing] > .documenttab-cont
   min-width: @thumbnail_width@;
   width: @thumbnail_width@;
   height: @thumbnail_height@;
 }
 #tray:not([expanded]) .documenttab-thumbnail {
   background-image: none!important;
 }
 
+/* TODO: Decide how and where to display private tabs.
+ * For now, display them in the main tab strip but hide the thumbnail. */
+documenttab[private] .documenttab-thumbnail {
+  background-color: purple;
+}
+
 .documenttab-title {
   margin: @metro_spacing_normal@ @metro_spacing_snormal@;
   margin-top: 0;
   font-size: @metro_font_normal@;
   width: @thumbnail_width@;
   padding: 4px @metro_spacing_snormal@ 8px;
 
   background: #000;
@@ -215,53 +221,21 @@ documenttab[selected] .documenttab-selec
 }
 
 /* Start UI ----------------------------------------------------------------- */
 
 #content-viewport[startpage] .active-tab-notificationbox {
   padding-bottom: @toolbar_height@;
 }
 
-#startui-page {
-  overflow-x: scroll;
-  overflow-y: hidden;
-  height: 100%;
-}
-
-#startui-page[viewstate="snapped"],
-#startui-page[viewstate="portrait"] {
-  overflow-x: hidden;
-  overflow-y: scroll;
-}
-
-#startui-body {
-  height: 100%;
-  margin: 0;
-}
-
-#start-container {
-  height: 100%;
-}
-
 #urlbar-autocomplete[viewstate="snapped"],
 #urlbar-autocomplete[viewstate="portrait"]{
   -moz-box-orient: vertical;
 }
 
-#start-container[viewstate="snapped"],
-#start-container[viewstate="portrait"] {
-  width: 100%;
-  max-width: 100%; /* ensure page doesn't expand, messing up @media rules */
-  height: auto;
-}
-
-#start-container[viewstate="snapped"] .meta-section:not([expanded]) > richgrid {
-  visibility: collapse;
-}
-
 #autocomplete-overlay {
   display: none;
   background-color: black;
   opacity: .3;
   position: fixed;
   top: 0;
   left: 0;
   right: 0;
--- a/browser/metro/theme/jar.mn
+++ b/browser/metro/theme/jar.mn
@@ -18,16 +18,17 @@ chrome.jar:
 * skin/browser.css                          (browser.css)
 * skin/content.css                          (content.css)
   skin/config.css                           (config.css)
 * skin/platform.css                         (platform.css)
 * skin/tiles.css                            (tiles.css)
   skin/touchcontrols.css                    (touchcontrols.css)
 * skin/netError.css                         (netError.css)
   skin/firstrun.css                         (firstrun.css)
+* skin/start.css                            (start.css)
 % override chrome://global/skin/about.css chrome://browser/skin/about.css
 % override chrome://global/skin/media/videocontrols.css chrome://browser/skin/touchcontrols.css
 % override chrome://global/skin/netError.css chrome://browser/skin/netError.css
 
   skin/images/panel-dark.png                (images/panel-dark.png)
   skin/images/navbar-back.png               (images/navbar-back.png)
   skin/images/navbar-back@1.4x.png          (images/navbar-back@1.4x.png)
   skin/images/navbar-back@1.8x.png          (images/navbar-back@1.8x.png)
copy from browser/metro/theme/browser.css
copy to browser/metro/theme/start.css
--- a/browser/metro/theme/browser.css
+++ b/browser/metro/theme/start.css
@@ -1,230 +1,17 @@
 /* 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/. */
 
 %filter substitution
 %include defines.inc
 
-%define forward_transition_length 200ms
-%define forward_spacing 50px
-
-/* Tab/StartUI tray ======================================================== */
-
-#tray {
-  transition: transform @metro_animation_duration@ @metro_animation_easing@;
-  transform: translateY(-@tabs_height@);
-  width: 100%;
-}
-
-#tray {
-  position: fixed;
-}
-
-#tray[expanded]:not([viewstate="snapped"]) {
-  transform: none;
-}
-
-/* Tabs -------------------------------------------------------------------- */
-
-#tabs-container {
-  background: @panel_dark_color@ @panel_dark_background@;
-  padding: 0;
-  -moz-padding-start: @metro_spacing_normal@;
-  width: 100%;
-}
-
-#tabs {
-  -moz-padding-start: 0;
-}
-
-#tabs .tabs-list {
-  display: block;
-  -moz-user-focus: ignore;
-  padding: 0;
-  background-color: transparent;
-  margin: 0;
-  overflow: auto;
-}
-
-.tabs-scrollbox > .scrollbutton-up[collapsed],
-.tabs-scrollbox > .scrollbutton-down[collapsed],
-#tabs[input="imprecise"] > .tabs-scrollbox > .scrollbutton-up,
-#tabs[input="imprecise"] > .tabs-scrollbox > .scrollbutton-down {
-  visibility: hidden !important;
-  pointer-events: none;
-}
-
-#tabs > .tabs-scrollbox > .scrollbutton-up {
-  list-style-image: url("images/tab-arrows.png") !important;
-  -moz-image-region: rect(15px 58px 63px 14px) !important;
-  padding-right: 15px;
-  width: @tabs_scrollarrow_width@;
-}
-#tabs > .tabs-scrollbox > .scrollbutton-up:hover {
-  -moz-image-region: rect(14px 102px 62px 58px) !important;
-}
-#tabs > .tabs-scrollbox > .scrollbutton-up:active {
-  -moz-image-region: rect(14px 152px 62px 108px) !important;
-}
-#tabs > .tabs-scrollbox > .scrollbutton-up[disabled] {
-  -moz-image-region: rect(15px 196px 63px 152px) !important;
-}
-
-#tabs > .tabs-scrollbox > .scrollbutton-down {
-  list-style-image: url("images/tab-arrows.png") !important;
-  -moz-image-region: rect(73px 58px 121px 14px) !important;
-  padding-left: 15px;
-  width: @tabs_scrollarrow_width@;
-}
-#tabs > .tabs-scrollbox > .scrollbutton-down:hover {
-  -moz-image-region: rect(72px 102px 120px 58px) !important;
-}
-#tabs > .tabs-scrollbox > .scrollbutton-down:active {
-  -moz-image-region: rect(72px 152px 120px 108px) !important;
-}
-#tabs > .tabs-scrollbox > .scrollbutton-down[disabled] {
-  -moz-image-region: rect(73px 196px 121px 152px) !important;
-}
-
-.tabs-scrollbox > .scrollbutton-up:not([disabled]):not([collapsed])::after {
-  content: "";
-  visibility: visible;
-  display: block;
-  background-color: rgb(90, 91, 95);
-  position: absolute;
-  top: 0;
-  left: calc(@tabs_scrollarrow_width@ + @metro_spacing_normal@); /* .scrollbutton-up width + #tabs-container left padding */
-  width: 1px;
-  height: @tabs_height@;
-}
-
-.tabs-scrollbox > .scrollbutton-down:not([disabled]):not([collapsed])::before {
-  content: "";
-  visibility: visible;
-  display: block;
-  background-color: rgb(90, 91, 95);
-  position: absolute;
-  top: 0;
-  right: calc(@tabs_scrollarrow_width@ + @newtab_button_width@); /* .scrollbutton-down width + #newtab-button width */
-  width: 1px;
-  height: @tabs_height@;
-}
-
-#tabs-container[viewstate="snapped"] {
-  visibility: hidden;
-}
-
-@-moz-keyframes open-documenttab {
-  0% {
-    opacity: 0;
-    transform: scale(0, 0);
-  }
-
-  100% {
-    opacity: 1;
-    transform: scale(1, 1);
-  }
-}
-
-@-moz-keyframes close-documenttab {
-  0% {
-    opacity: 1;
-    transform: scale(1, 1);
-  }
-
-  100% {
-    opacity: 0;
-    transform: scale(0, 0);
-  }
-}
-
-.documenttab-container {
-  animation: open-documenttab 0.4s ease-out;
-}
-
-documenttab[closing] > .documenttab-container {
-  animation: close-documenttab 0.4s ease-out;
-  animation-fill-mode: forwards;
-}
-
-.documenttab-favicon {
-  visibility: collapse;
-}
-
-.documenttab-thumbnail {
-  margin: @metro_spacing_normal@ @metro_spacing_snormal@;
-  background: white none center top no-repeat;
-  background-size: cover;
-  min-width: @thumbnail_width@;
-  width: @thumbnail_width@;
-  height: @thumbnail_height@;
-}
-#tray:not([expanded]) .documenttab-thumbnail {
-  background-image: none!important;
-}
-
-.documenttab-title {
-  margin: @metro_spacing_normal@ @metro_spacing_snormal@;
-  margin-top: 0;
-  font-size: @metro_font_normal@;
-  width: @thumbnail_width@;
-  padding: 4px @metro_spacing_snormal@ 8px;
-
-  background: #000;
-  opacity: 0.95;
-  color: #fff;
-  box-shadow: 0 0 @metro_spacing_snormal@ rgba(0, 0, 0, 0.25);
-}
-
-.documenttab-crop {
-  background: transparent url("chrome://browser/skin/images/tab-crop.png") 50% 50% no-repeat;
-}
-
-.documenttab-selection {
-  background: transparent -moz-image-rect(url("chrome://browser/skin/images/tab-overlay.png"), 0%, 100%, 50%, 0%) 50% 50% no-repeat;
-}
-
-documenttab[selected] .documenttab-selection {
-  background: transparent -moz-image-rect(url("chrome://browser/skin/images/tab-overlay.png"), 50%, 100%, 100%, 0%) 50% 50% no-repeat;
-}
-
-.documenttab-close {
-  background: none !important;
-  padding: @metro_spacing_small@ !important;
-  margin-top: @metro_spacing_snormal@;
-  -moz-margin-end: @metro_spacing_xsmall@;
-  border-color: transparent !important;
-  list-style-image: url("chrome://browser/skin/images/closetab-default.png");
-}
-
-.documenttab-close > .button-box > .button-text {
-  display: none;
-}
-
-#tabs-controls {
-  -moz-box-align: start;
-  -moz-box-orient: vertical;
-}
-
-#newtab-button {
-  list-style-image: url(chrome://browser/skin/images/newtab-default.png);
-
-  /* Add some extra padding for a larger target */
-  padding: 18px 20px 30px 20px;
-  width: @newtab_button_width@;
-}
-
 /* Start UI ----------------------------------------------------------------- */
 
-#content-viewport[startpage] .active-tab-notificationbox {
-  padding-bottom: @toolbar_height@;
-}
-
 #startui-page {
   overflow-x: scroll;
   overflow-y: hidden;
   height: 100%;
 }
 
 #startui-page[viewstate="snapped"],
 #startui-page[viewstate="portrait"] {
@@ -236,1126 +23,18 @@ documenttab[selected] .documenttab-selec
   height: 100%;
   margin: 0;
 }
 
 #start-container {
   height: 100%;
 }
 
-#urlbar-autocomplete[viewstate="snapped"],
-#urlbar-autocomplete[viewstate="portrait"]{
-  -moz-box-orient: vertical;
-}
-
 #start-container[viewstate="snapped"],
 #start-container[viewstate="portrait"] {
   width: 100%;
   max-width: 100%; /* ensure page doesn't expand, messing up @media rules */
   height: auto;
 }
 
 #start-container[viewstate="snapped"] .meta-section:not([expanded]) > richgrid {
   visibility: collapse;
 }
-
-#autocomplete-overlay {
-  display: none;
-  background-color: black;
-  opacity: .3;
-  position: fixed;
-  top: 0;
-  left: 0;
-  right: 0;
-  bottom: 0;
-}
-
-#stack[autocomplete] > #page > #content-viewport > #autocomplete-overlay {
-  display: -moz-box;
-}
-
-/* Browser Content Areas ==================================================== */
-
-/* a 'margin-top' is applied dynamically in ContentAreaObserver */
-#browsers {
-  background: white;
-  transition-property: margin-top;
-  transition-duration: .3s;
-  transition-timing-function: ease-in-out;
-}
-#browsers browser {
-  /* unset padding-bottom immediately */
-  transition-duration: 0s;
-  transition-delay:    0s;
-  transition-property: padding-bottom;
-}
-/* Selection overlay and monocles */
-#page,
-.selection-overlay {
-  -moz-stack-sizing: ignore;
-}
-
-.selection-overlay {
-  pointer-events: none;
-}
-
-.selection-overlay:-moz-focusring {
-  outline: 0 !important;
-}
-
-.selection-overlay-hidden {
-  display: none;
-}
-
-.selectionhandle {
-  background-image: url("chrome://browser/skin/images/selection-monocle.png");
-  background-repeat: no-repeat;
-  background-size: 18px 18px;
-  padding: 0px;
-  margin-top: -19px;
-  margin-left: -9px;
-  pointer-events: auto;
-}
-
-@media (min-resolution: @min_res_140pc@) {
-  /* Load 140% image when scaled by 140% */
-  .selectionhandle {
-    background-image: url("chrome://browser/skin/images/selection-monocle@1.4x.png");
-  }
-}
-
-@media (min-resolution: @min_res_180pc@) {
-  /* Load 180% image when scaled by 180% */
-  .selectionhandle {
-    background-image: url("chrome://browser/skin/images/selection-monocle@1.8x.png");
-  }
-}
-
-/* content scrollbars */
-.scroller {
-  opacity: 0;
-  background-color: rgba(0, 0, 0, 0.4) !important;
-  -moz-border-top-colors: none !important;
-  -moz-border-bottom-colors: none !important;
-  -moz-border-right-colors: none !important;
-  -moz-border-left-colors: none !important;
-  border-radius: @border_radius_tiny@;
-  border: @border_width_tiny@ solid rgba(255, 255, 255, 0.4) !important;
-}
-
-.scroller[panning] {
-  opacity: 1;
-}
-
-.scroller[orient="vertical"] {
-  min-width: @scroller_thickness@;
-  width: @scroller_thickness@;
-  min-height: @scroller_minimum@;
-}
-
-.scroller[orient="horizontal"] {
-  min-height: @scroller_thickness@;
-  height: @scroller_thickness@;
-  min-width: @scroller_minimum@;
-}
-
-/* overlay buttons */
-
-.overlay-button {
-  position: fixed;
-  top: 50%;
-  margin-top: -65px;
-  width: 118px;
-  height: 118px;
-  background-color: hsla(210,30%,10%,.2);
-  background-size: 60px;
-  background-repeat: no-repeat;
-  background-origin: padding-box;
-  background-clip: padding-box;
-  border: 6px solid hsla(0,0%,100%,.7);
-  border-radius: 50%;
-  box-shadow: 0 0 0 1px hsla(0,0%,0%,.04),
-              0 0 9px 0 hsla(0,0%,0%,.1);
-  transition-property: left, right, transform, background-position,
-                       background-color, background-size, border-color,
-                       visibility, box-shadow, top;
-  transition-duration: 550ms;
-  transition-timing-function: cubic-bezier(0.1, 0.9, 0.2, 1);
-}
-
-#overlay-back {
-  background-image: url(chrome://browser/skin/images/overlay-back.png);
-}
-
-#overlay-plus {
-  background-image: url(chrome://browser/skin/images/overlay-plus.png);
-}
-
-#overlay-back:-moz-locale-dir(ltr),
-#overlay-plus:-moz-locale-dir(rtl) {
-  left: -70px;
-  background-position: right 6px center;
-}
-
-#overlay-plus:-moz-locale-dir(ltr),
-#overlay-back:-moz-locale-dir(rtl) {
-  right: -70px;
-  background-position: left 6px center;
-}
-
-#stack[viewstate="snapped"] > .overlay-button,
-#stack[keyboardVisible] > .overlay-button,
-#stack[autocomplete] > .overlay-button,
-#stack[fullscreen] > .overlay-button,
-#appbar[visible] ~ .overlay-button,
-.overlay-button[disabled] {
-  box-shadow: none;
-  visibility: collapse;
-}
-
-#stack[keyboardVisible] > #overlay-back:-moz-locale-dir(ltr),
-#stack[keyboardVisible] > #overlay-plus:-moz-locale-dir(rtl),
-#stack[autocomplete] > #overlay-back:-moz-locale-dir(ltr),
-#stack[autocomplete] > #overlay-plus:-moz-locale-dir(rtl),
-#stack[fullscreen] > #overlay-back:-moz-locale-dir(ltr),
-#stack[fullscreen] > #overlay-plus:-moz-locale-dir(rtl),
-#appbar[visible] ~ #overlay-back:-moz-locale-dir(ltr),
-#appbar[visible] ~ #overlay-plus:-moz-locale-dir(rtl),
-#overlay-back[disabled]:-moz-locale-dir(ltr),
-#overlay-plus[disabled]:-moz-locale-dir(rtl) {
-  transform: translateX(-60px);
-}
-
-#stack[keyboardVisible] > #overlay-plus:-moz-locale-dir(ltr),
-#stack[keyboardVisible] > #overlay-back:-moz-locale-dir(rtl),
-#stack[autocomplete] > #overlay-plus:-moz-locale-dir(ltr),
-#stack[autocomplete] > #overlay-back:-moz-locale-dir(rtl),
-#stack[fullscreen] > #overlay-plus:-moz-locale-dir(ltr),
-#stack[fullscreen] > #overlay-back:-moz-locale-dir(rtl),
-#appbar[visible] ~ #overlay-plus:-moz-locale-dir(ltr),
-#appbar[visible] ~ #overlay-back:-moz-locale-dir(rtl),
-#overlay-plus[disabled]:-moz-locale-dir(ltr),
-#overlay-back[disabled]:-moz-locale-dir(rtl) {
-  transform: translateX(60px);
-}
-
-.overlay-button:hover {
-  background-color: hsla(210,30%,10%,.4);
-  background-size: 90px;
-  border-color: hsla(0,0%,100%,.9);
-}
-
-#overlay-back:-moz-locale-dir(ltr):hover,
-#overlay-plus:-moz-locale-dir(rtl):hover {
-  background-position: right 12px center;
-  transform: translateX(40px) scale(1.2);
-}
-
-#overlay-plus:-moz-locale-dir(ltr):hover,
-#overlay-back:-moz-locale-dir(rtl):hover {
-  background-position: left 12px center;
-  transform: translateX(-40px) scale(1.2);
-}
-
-#overlay-back[mousedrag],
-#overlay-plus[mousedrag] {
-  transition-property: left, right, transform, background-position,
-                       background-color, background-size, border-color,
-                       visibility, box-shadow;
-}
-
-/* Navigation bar ========================================================== */
-
-/* Most appbars are hidden by default, but we want to keep #navbar visible so
- * we can show the progress bar at all times.  Instead, we hide only the
- * toolbar portion of the navbar. */
-#navbar {
-  visibility: visible;
-}
-#navbar:not([hiding]):not([visible]) > #toolbar-overlay {
-  visibility: hidden;
-}
-
-/* Progress meter ---------------------------------------------------------- */
-
-#progress-container {
-  display: block;
-  position: absolute;
-  top: -@progress_height@;
-  height: @progress_height@;
-  width: 100%;
-  background-color: hsla(210,5%,80%,1);
-  box-shadow: 0 1px 0 hsla(210,5%,50%,.1) inset;
-  -moz-user-focus: ignore;
-}
-#progress-container[startpage] {
-  visibility: collapse;
-}
-
-#progress-control {
-  display: block;
-  height: @progress_height@;
-  background-image: -moz-linear-gradient(left, hsla(200,100%,83%,.5),
-                                         hsla(200,100%,83%,0)),
-                    -moz-linear-gradient(top, #1ab2ff, #0091ff);
-  border-right: 1px solid #0082e5;
-  transition: width .3s ease-in;
-  -moz-user-focus: ignore;
-}
-
-#progress-control:-moz-dir(rtl) {
-  transform: scaleX(-1);
-}
-
-#progress-control[fade] {
-  opacity: 0;
-  transition: width .3s ease-in, .5s opacity ease-in;
-}
-
-/* Toolbar ----------------------------------------------------------------- */
-
-#toolbar-overlay {
-  background-color: @panel_light_color@;
-}
-
-#urlbar-autocomplete {
-  padding-top: 0;
-}
-
-#toolbar {
-  padding: 0 @toolbar_horizontal_padding@;
-}
-
-#toolbar[viewstate="snapped"] {
-  padding: 0 @toolbar_snapped_horizontal_padding@;
-}
-
-#toolbar[viewstate="snapped"] > toolbarbutton {
-  margin: 0 @toolbar_snapped_horizontal_spacing@;
-}
-
-/* Combined back/forward buttons */
-
-#back-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-back.png);
-  position: relative;
-  z-index: 1;
-  transition: opacity @forward_transition_length@ ease-out;
-}
-
-#back-button[disabled] {
-  visibility: visible;
-  opacity: 0.5;
-}
-
-#forward-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-forward.png);
-  transition: margin @forward_transition_length@ ease-out,
-              visibility @forward_transition_length@ ease-out,
-              opacity @forward_transition_length@ ease-out;
-}
-
-#forward-button[disabled] {
-  -moz-margin-start: -@forward_spacing@ !important;
-  visibility: hidden;
-  opacity: 0;
-  pointer-events: none;
-}
-
-@media (min-resolution: @min_res_140pc@) {
-  #back-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-back@1.4x.png);
-  }
-
-  #forward-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-forward@1.4x.png);
-  }
-}
-
-@media (min-resolution: @min_res_180pc@) {
-  #back-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-back@1.8x.png);
-  }
-
-  #forward-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-forward@1.8x.png);
-  }
-}
-
-/* URL bar */
-#urlbar {
-  border: @metro_border_thick@ solid @urlbar_border_color@;
-  margin: 0 @toolbar_horizontal_spacing@;
-  padding: 0;
-  background-color: @field_background_color@;
-  overflow: hidden;
-}
-
-#urlbar[editing] {
-  border-color: @metro_orange@;
-}
-
-/* Identity widget */
-#identity-icon {
-  margin: 0;
-  padding: 0 @metro_spacing_snormal@;
-  list-style-image: url("chrome://browser/skin/images/identity-icons-generic.png");
-}
-
-#identity-box.verifiedDomain > #identity-icon {
-  list-style-image: url("chrome://browser/skin/images/identity-icons-https.png");
-}
-
-#identity-box.verifiedIdentity > #identity-icon {
-  list-style-image: url("chrome://browser/skin/images/identity-icons-https-ev.png");
-}
-
-#toolbar[startpage] > #urlbar:not([autocomplete]) > #identity-box > #identity-icon {
-  list-style-image: url("chrome://browser/skin/images/icons-identity-firefox.png");
-}
-
-#urlbar[autocomplete] > #identity-box > #identity-icon {
-  list-style-image: url("chrome://browser/skin/images/icon-autocomplete-search.png");
-}
-
-/* Main URL textbox */
-#urlbar-edit {
-  margin: 0 !important;
-  min-height: @urlbar_edit_height@;
-  -moz-appearance: none !important;
-  border-radius: 0;
-  border: 0 none !important;
-  padding: 0 !important;
-}
-
-#urlbar-edit > hbox > .textbox-input-box > .textbox-input:invalid {
-  /* Hide error glow around the address bar that shows by default
-   * when URLs are made invalid by trmming. */
-  box-shadow: none !important;
-}
-
-/* Combined stop-reload button */
-.urlbar-button {
-  margin: 0;
-  -moz-image-region: rect(0px, 30px, 30px, 0px);
-}
-
-.urlbar-button:hover:not(:active) {
-  -moz-image-region: rect(0px, 60px, 30px, 30px);
-  background-color: #dedfdf;
-}
-
-.urlbar-button:active {
-  -moz-image-region: rect(0px, 90px, 30px, 60px);
-  background-color: #6d7073;
-}
-
-.urlbar-button  > .toolbarbutton-icon {
-  width: 30px;
-  height: 30px;
-}
-
-#go-button {
-  list-style-image: url(chrome://browser/skin/images/urlbar-go.png)
-}
-
-#reload-button {
-  list-style-image: url(chrome://browser/skin/images/urlbar-reload.png);
-}
-
-#stop-button {
-  list-style-image: url(chrome://browser/skin/images/urlbar-stop.png);
-}
-
-@media (min-resolution: @min_res_140pc@) {
-  .urlbar-button {
-    -moz-image-region: rect(0px, 42px, 42px, 0px);
-  }
-
-  .urlbar-button:hover:not(:active) {
-    -moz-image-region: rect(0px, 84px, 42px, 42px);
-  }
-
-  .urlbar-button:active {
-    -moz-image-region: rect(0px, 126px, 42px, 84px);
-  }
-
-  #go-button {
-    list-style-image: url(chrome://browser/skin/images/urlbar-go@1.4x.png)
-  }
-
-  #reload-button {
-    list-style-image: url(chrome://browser/skin/images/urlbar-reload@1.4x.png);
-  }
-
-  #stop-button {
-    list-style-image: url(chrome://browser/skin/images/urlbar-stop@1.4x.png);
-  }
-
-  #toolbar[startpage] > #urlbar:not([autocomplete]) > #identity-box > #identity-icon {
-    list-style-image: url("chrome://browser/skin/images/icons-identity-firefox@1.4x.png");
-  }
-
-  #urlbar[autocomplete] > #identity-box > #identity-icon {
-    list-style-image: url("chrome://browser/skin/images/icon-autocomplete-search@1.4x.png");
-  }
-}
-
-@media (min-resolution: @min_res_180pc@) {
-  .urlbar-button {
-    -moz-image-region: rect(0px, 54px, 54px, 0px);
-  }
-
-  .urlbar-button:hover:not(:active) {
-    -moz-image-region: rect(0px, 108px, 54px, 54px);
-  }
-
-  .urlbar-button:active {
-    -moz-image-region: rect(0px, 162px, 54px, 108px);
-  }
-
-  #go-button {
-    list-style-image: url(chrome://browser/skin/images/urlbar-go@1.8x.png)
-  }
-
-  #reload-button {
-    list-style-image: url(chrome://browser/skin/images/urlbar-reload@1.8x.png);
-  }
-
-  #stop-button {
-    list-style-image: url(chrome://browser/skin/images/urlbar-stop@1.8x.png);
-  }
-
-  #toolbar[startpage] > #urlbar:not([autocomplete]) > #identity-box > #identity-icon {
-    list-style-image: url("chrome://browser/skin/images/icons-identity-firefox@1.8x.png");
-  }
-
-  #urlbar[autocomplete] > #identity-box > #identity-icon {
-    list-style-image: url("chrome://browser/skin/images/icon-autocomplete-search@1.8x.png");
-  }
-}
-
-/* navbar edit button: one button out of three - when editing: go, when !editing,
-   loading: stop, when !editing, !loading: reload */
-
-#go-button, #reload-button, #stop-button  {
-  visibility: collapse;
-}
-
-#urlbar[editing] > #go-button,
-#urlbar:not([editing])[loading] > #stop-button,
-#urlbar:not([editing]):not([loading]) > #reload-button {
-  visibility: visible;
-}
-
-/* Contextual toolbar controls */
-
-#toolbar-context-autocomplete,
-.hide-on-start,
-#toolbar-context-page {
-  transition-property: opacity, visibility;
-  transition-duration: @forward_transition_length@;
-  transition-timing-function: @metro_animation_easing@;
-}
-
-#toolbar-contextual:not([autocomplete]) #toolbar-context-autocomplete,
-#toolbar-contextual[startpage] .hide-on-start,
-#toolbar-contextual[autocomplete] #toolbar-context-page {
-  opacity: 0;
-  visibility: hidden;
-  pointer-events: none;
-}
-
-#toolbar[viewstate="snapped"] #toolbar-contextual {
-  visibility: collapse;
-}
-
-#download-progress:not([progress]) {
-  visibility: collapse;
-}
-
-#download-progress {
-  list-style-image: url(chrome://browser/skin/images/navbar-download.png);
-}
-
-#download-progress[progress="100"] {
-  list-style-image: url(chrome://browser/skin/images/navbar-download-finished.png);
-}
-
-#pin-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-pin.png);
-}
-
-#star-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-star.png);
-}
-
-#menu-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-menu.png);
-}
-
-#close-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-close.png);
-}
-
-@media (min-resolution: @min_res_140pc@) {
-  #download-progress {
-    list-style-image: url(chrome://browser/skin/images/navbar-download@1.4x.png);
-  }
-
-  #download-progress[progress="100"] {
-    list-style-image: url(chrome://browser/skin/images/navbar-download-finished@1.4x.png);
-  }
-
-  #pin-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-pin@1.4x.png);
-  }
-
-  #star-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-star@1.4x.png);
-  }
-
-  #menu-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-menu@1.4x.png);
-  }
-
-  #close-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-close@1.4x.png);
-  }
-}
-
-@media (min-resolution: @min_res_180pc@) {
-  #download-progress {
-    list-style-image: url(chrome://browser/skin/images/navbar-download@1.8x.png);
-  }
-
-  #download-progress[progress="100"] {
-    list-style-image: url(chrome://browser/skin/images/navbar-download-finished@1.8x.png);
-  }
-
-  #pin-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-pin@1.8x.png);
-  }
-
-  #star-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-star@1.8x.png);
-  }
-
-  #menu-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-menu@1.8x.png);
-  }
-
-  #close-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-close@1.8x.png);
-  }
-}
-
-/* Panel UI ================================================================ */
-
-#panel-container {
-  padding: 60px 40px;
-}
-
-#panel-container[viewstate="snapped"] .canSnapTiles .richgrid-item-content {
-  -moz-box-orient: horizontal;
-}
-
-#panel-close-button {
-  -moz-margin-end: 40px;
-  list-style-image: url(chrome://browser/skin/images/navbar-back.png);
-  -moz-box-pack: center;
-}
-
-@media (min-resolution: @min_res_140pc@) {
-  #panel-close-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-back@1.4x.png);
-  }
-}
-
-@media (min-resolution: @min_res_180pc@) {
-  #panel-close-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-back@1.8x.png);
-  }
-}
-
-#panel-items {
-  padding-top: 20px;
-  -moz-padding-start: 88px;
-}
-
-#panel-container[viewstate="snapped"] #panel-items {
-  padding-left: 0px;
-}
-
-/* Console Section - Panel UI ---------------------------------------------- */
-
-#console-filter-warnings,
-#console-filter-messages {
-  visibility: visible;
-}
-
-@media (max-width: 499px) {
-  #console-filter-warnings,
-  #console-filter-messages {
-    visibility: collapse;
-  }
-}
-
-.console-error-msg,
-.console-msg-text {
-  white-space: pre-wrap;
-}
-
-/* Find bar ================================================================ */
-
-#findbar {
-  background-color: @metro_orange@;
-  padding: 0;
-}
-
-#findbar > toolbar {
-  min-height: @findbar_height@ !important;
-}
-
-#findbar-textbox {
-  border: none !important;
-  width: 20em;
-}
-
-/* Override the default box ordering and make the find textbox appear to the
-   right of the icon */
-#findbar-textbox input {
-  -moz-box-ordinal-group: 2
-}
-
-#findbar-textbox[status="1"] { /* Ci.nsITypeAheadFind.FIND_NOTFOUND */
-  background: rgb(255,200,200);
-}
-
-#findbar-textbox:hover:active {
-  background: #8db8d8;
-}
-
-.textbox-search-icon {
-  list-style-image: url("chrome://browser/skin/images/search-glass-30.png");
-  -moz-image-region: auto;
-}
-
-#findbar-previous-button {
-  -moz-image-region: rect(0px, 400px, 40px, 360px);
-}
-
-#findbar-previous-button:hover:not(:active) {
-  -moz-image-region: rect(40px, 400px, 80px, 360px);
-}
-
-#findbar-previous-button:active {
-  -moz-image-region: rect(80px, 400px, 120px, 360px);
-}
-
-#findbar-next-button {
-  -moz-image-region: rect(0px, 440px, 40px, 400px);
-}
-
-#findbar-next-button:hover:not(:active) {
-  -moz-image-region: rect(40px, 440px, 80px, 400px);
-}
-
-#findbar-next-button:active {
-  -moz-image-region: rect(80px, 440px, 120px, 400px);
-}
-
-#findbar-close-button {
-  -moz-image-region: rect(0px, 480px, 40px, 440px);
-}
-
-#findbar-close-button:hover:not(:active) {
-  -moz-image-region: rect(40px, 480px, 80px, 440px);
-}
-
-#findbar-close-button:active {
-  -moz-image-region: rect(80px, 480px, 120px, 440px);
-}
-
-/* Contextual appbar ======================================================= */
-
-#contextualactions-tray {
-  background-color: @metro_orange@;
-}
-
-#contextualactions-tray > toolbarbutton {
-  opacity: 1;
-}
-#contextualactions-tray > toolbarbutton[fade] {
-  opacity: 0;
-}
-#contextualactions-tray > toolbarbutton:not([immediate]) {
-  transition-property: opacity;
-  transition-duration: .3s;
-  transition-timing-function: ease-in;
-  transition-delay: 80ms;
-}
-#contextualactions-tray > toolbarbutton > .toolbarbutton-text {
-  color: white;
-}
-
-#pin-selected-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-contextual-pin.png);
-}
-
-#unpin-selected-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-contextual-unpin.png);
-}
-
-#hide-selected-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-contextual-hide.png);
-}
-
-#delete-selected-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-contextual-delete.png);
-}
-
-#clear-selected-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-contextual-clear.png);
-}
-
-#restore-selected-button {
-  list-style-image: url(chrome://browser/skin/images/navbar-contextual-restore.png);
-}
-
-@media (min-resolution: @min_res_140pc@) {
-  #pin-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-pin@1.4x.png);
-  }
-
-  #unpin-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-unpin@1.4x.png);
-  }
-
-  #hide-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-hide@1.4x.png);
-  }
-
-  #delete-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-delete@1.4x.png);
-  }
-
-  #clear-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-clear@1.4x.png);
-  }
-
-  #restore-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-restore@1.4x.png);
-  }
-}
-
-@media (min-resolution: @min_res_180pc@) {
-  #pin-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-pin@1.8x.png);
-  }
-
-  #unpin-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-unpin@1.8x.png);
-  }
-
-  #hide-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-hide@1.8x.png);
-  }
-
-  #delete-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-delete@1.8x.png);
-  }
-
-  #clear-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-clear@1.8x.png);
-  }
-
-  #restore-selected-button {
-    list-style-image: url(chrome://browser/skin/images/navbar-contextual-restore@1.8x.png);
-  }
-}
-
-/* Download notifications ======================================================= */
-
-.download-filename-text {
-  font-weight: bold;
-}
-.download-host-text {
-  font-weight: bold;
-}
-
-/* Autoscroll popup ======================================================== */
-
-.autoscroller {
-  height: 28px;
-  width: 28px;
-  border: none;
-  margin: -14px;
-  padding: 0;
-  background-image: url("chrome://browser/skin/images/autoscroll.png");
-  background-color: transparent;
-  position: fixed;
-  visibility: hidden;
-  background-repeat: no-repeat;
-  background-origin: padding-box;
-  background-clip: padding-box;
-  background-position: right top;
-  -moz-appearance: none;
-}
-
-.autoscroller[scrolldir="NS"] {
-  background-position: right center;
-}
-
-.autoscroller[scrolldir="EW"] {
-  background-position: right bottom;
-}
-
-/* Flyouts ================================================================= */
-
-/* don't add a margin to the very top settings entry in flyouts */
-flyoutpanel > settings:first-child {
-  margin-top: 0px;
-}
-
-/* Sync flyout pane -------------------------------------------------------- */
-
-#sync-flyoutpanel {
-  font-size: @metro_font_normal@;
-  font-weight: 400;
-}
-
-#sync-flyoutpanel button {
-  font-weight: 700;
-}
-
-#sync-flyoutpanel .syncHeader {
-  font-weight: 600;
-}
-
-#sync-flyoutpanel .syncSecondaryText {
-  font-weight: 100;
-  font-size: @metro_font_snormal@;
-}
-
-#sync-flyoutpanel .syncInstructionText {
-  font-style: italic;
-}
-
-.syncThrobber .progressBall {
-   margin: 2px;
-   width: 22px;
-   height: 22px;
- }
-
-.syncThrobber .progressBallInner {
-  width: 5px;
-  height: 5px;
-  border-radius: 3px;
-}
-
-#sync-flyoutpanel .syncErrorText {
-  color: red;
-}
-
-#sync-flyoutpanel textbox {
-  margin: @metro_spacing_small@;
-  padding: @metro_spacing_xsmall@ @metro_spacing_snormal@;
-  background: @field_background_color@;
-  border: @metro_border_thick@ solid @field_mid_foreground_color@ !important;
-  color: @field_foreground_color@;
-}
-
-#sync-setup-throbber {
-  margin-top: 15px;
-  margin-left: 25px;
-}
-
-#sync-connected-device {
-  width: 200px;
-}
-
-#sync-manualsetup-failure {
-  width: 200px;
-}
-
-#sync-flyoutpanel .syncJPAKECode {
-  margin: @metro_spacing_small@;
-  padding: @metro_spacing_xsmall@ @metro_spacing_snormal@;
-  background: @field_background_color@;
-  border: @metro_border_thick@ solid @field_mid_foreground_color@ !important;
-  color: @field_foreground_color@;
-  display: block !important;
-  font-size: @metro_font_large@ !important;
-  font-weight: 600;
-  letter-spacing: 0.4em;
-  text-align: center;
-  width: 175px;
-}
-
-#sync-connected-device {
-  margin-bottom: 0px;
-  padding-bottom: 0px;
-}
-
-#sync-connected-lastSynced {
-  margin-top: 0px;
-  padding-top: 0px;
-}
-
-#sync-connected-throbber {
-  margin-top: 12px;
-  margin-left: 15px;
-}
-
-/* About flyout pane ------------------------------------------------------- */
-
-/* Colors are defined in /browser/branding/<dir>/content/metro-about.css */
-
-#about-flyoutpanel {
-  background-image: url('chrome://branding/content/metro-about-footer.png');
-  background-repeat: no-repeat;
-  background-attachment: fixed;
-  background-position: right bottom;
-}
-
-#about-flyoutpanel .text-link {
-  color: inherit;
-}
-
-#about-flyoutpanel > .flyoutpanel-wrapper > .flyoutpanel-header,
-#about-flyoutpanel > .flyoutpanel-wrapper > .flyoutpanel-contents {
-  background-color: inherit;
-  border: none;
-}
-
-#about-policy-label {
-  padding: 1.5em @metro_spacing_large@;
-  margin: 1em -@metro_spacing_large@;
-}
-
-#about-version-label {
- margin-top: 11pt;
-}
-
-#currentChannel {
-  margin: 0;
-  padding: 0;
-  font-weight: bold;
-}
-
-/* Preferences flyout pane ------------------------------------------------- */
-
-/* Lay out each <setting> in a single row */
-setting {
-  min-height: @touch_row@; /* row size */
-  -moz-box-align: center;
-  -moz-box-orient: horizontal;
-}
-
-/* ...except for some exceptions */
-.setting-expanded {
-  -moz-box-align: start;
-  -moz-box-orient: vertical;
-}
-
-setting > vbox {
-  -moz-box-flex: 1;
-}
-
-settings {
-  margin-top: 32px;
-}
-
-.settings-title {
-  font-weight: bold;
-}
-
-/* <setting> elements that are not in a <settings> group get special treatment */
-#prefs-flyoutpanel > setting,
-#sync-flyoutpanel > setting {
-  margin-top: 16px;
-}
-
-#prefs-flyoutpanel > setting .preferences-title {
-  font-weight: bold;
-}
-
-setting[type="integer"] > .preferences-alignment,
-setting[type="string"] > .preferences-alignment {
-  -moz-box-flex: 3;
-}
-
-setting[type="file"] > .preferences-alignment,
-setting[type="directory"] > .preferences-alignment {
-  -moz-box-align: center;
-}
-
-/* Removes the left side title vbox on radio setting */
-setting[type="radio"] > vbox {
-  display: none;
-}
-
-#prefs-homepage-options, #prefs-homepage-popup {
-  min-width: 200px;
-}
-
-.options-box {
-  -moz-margin-start: 28px;  /* sized based on the 32px addon image */
-}
-
-.options-box > setting:last-child {
-  border-bottom: 0;
-}
-
-.preferences-description {
-  font-size: @font_small@ !important;
-  color: grey;
-}
-
-.preferences-description:empty {
-  display: none;
-}
-
-/* Clear private data prefs */
-
-/* hide subitems when other data checkbox is not checked */
-#prefs-privdata-other:not([checked]) + #prefs-privdata-subitems {
-  display: none;
-}
-
-#prefs-privdata-subitems {
-  display: block;
-  padding-left: @metro_spacing_xnormal@;
-  font-size: @metro_font_snormal@;
-}
-
-/* arrange sub-items in two columns */
-.privdata-subitem-item {
-  display: inline-block;
-  vertical-align: middle;
-  margin: 0;
-  width: 50%;
-}
-
-#clear-notification {
-  max-height: 25px;
-}
-
-#clearprivacythrobber {
-  max-width: 25px;
-  max-height: 25px;
-}
-
-#clearprivacythrobber .progressContainer {
-  width: 25px;
-  height: 25px;
-}
-
-#clearprivacythrobber .progressBall {
-  margin: 2px;
-  width: 22px;
-  height: 22px;
-}
-
-#clear-notification-done {
-  font-weight: bold;
-}
--- a/browser/themes/shared/customizableui/customizeMode.inc.css
+++ b/browser/themes/shared/customizableui/customizeMode.inc.css
@@ -45,16 +45,20 @@
   line-height: 1.5em;
   color: rgb(64,100,128);
   font-weight: lighter;
   margin-bottom: 1em;
 }
 
 #customization-panel-container {
   padding: 15px 25px 25px;
+  background-image: linear-gradient(to bottom, #3e86ce, #3878ba);
+}
+
+#main-window[customize-entered] #customization-panel-container {
   background-image: url("chrome://browser/skin/customizableui/customizeMode-separatorHorizontal.png"),
                     url("chrome://browser/skin/customizableui/customizeMode-separatorVertical.png"),
                     url("chrome://browser/skin/customizableui/customizeMode-gridTexture.png"),
                     url("chrome://browser/skin/customizableui/background-noise-toolbar.png"),
                     linear-gradient(to bottom, #3e86ce, #3878ba);
   background-position: center top, left center, left top, left top, left top;
   background-repeat: no-repeat, no-repeat, repeat, repeat, no-repeat;
   background-size: auto 12px, 12px 100%, auto, auto, auto;
@@ -70,16 +74,17 @@ toolbarpaletteitem[mousedown] {
 }
 
 .panel-customization-placeholder,
 toolbarpaletteitem[place="palette"],
 toolbarpaletteitem[place="panel"] {
   transition: transform .3s ease-in-out;
 }
 
+toolbarpaletteitem[notransition].panel-customization-placeholder,
 toolbarpaletteitem[notransition][place="palette"],
 toolbarpaletteitem[notransition][place="panel"] {
   transition: none;
 }
 
 toolbarpaletteitem > toolbarbutton > .toolbarbutton-icon {
   transition: transform .3s cubic-bezier(.6, 2, .75, 1.5);
 }
--- a/browser/themes/shared/customizableui/panelUIOverlay.inc.css
+++ b/browser/themes/shared/customizableui/panelUIOverlay.inc.css
@@ -1,18 +1,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/. */
 
 %filter substitution
 
 %define menuPanelWidth 22.35em
 %define exitSubviewGutterWidth 38px
-%define buttonStateHover :not(:-moz-any([disabled],[open],[checked="true"],[_moz-menuactive="true"],:active)):hover
-%define buttonStateActive :not([disabled]):-moz-any([open],[checked="true"],[_moz-menuactive="true"],:hover:active)
+%define buttonStateHover :not(:-moz-any([disabled],[checked="true"],[open],:active)):hover
+%define buttonStateActive :not([disabled]):-moz-any([open],[checked="true"],:hover:active)
 
 %include ../browser.inc
 
 .panel-subviews {
   padding: 4px;
   background-color: hsla(0,0%,100%,.97);
   background-clip: padding-box;
   border-right: 1px solid hsla(210,4%,10%,.2);
@@ -505,17 +505,19 @@ toolbarpaletteitem[place="palette"] > #s
   border: 0;
   padding: .5em;
   margin: 0;
   -moz-box-flex: 1;
   /* reduce the width with 2px for each button to compensate for two separators
      of 3px. */
   min-width: calc(@menuPanelWidth@ / 3 - 2px);
   max-width: calc(@menuPanelWidth@ / 3 - 2px);
-  height: auto;
+  /* We'd prefer to use height: auto here but it leads to layout bugs in the panel. Cope:
+     1.2em for line height + 2 * .5em padding + margin on the label (2 * 2px) */
+  height: calc(2.2em + 4px);
   max-height: none;
   -moz-box-orient: horizontal;
 }
 
 #edit-controls@inAnyPanel@ > toolbarbutton[disabled] > .toolbarbutton-icon,
 #zoom-controls@inAnyPanel@ > toolbarbutton[disabled] > .toolbarbutton-icon {
   opacity: .25;
 }
--- a/build/autoconf/android.m4
+++ b/build/autoconf/android.m4
@@ -289,17 +289,17 @@ case "$target" in
     android_tools="$android_sdk_root"/tools
     android_platform_tools="$android_sdk_root"/platform-tools
     if test ! -d "$android_platform_tools" ; then
         android_platform_tools="$android_sdk"/tools # SDK Tools < r8
     fi
     # The build tools got moved around to different directories in
     # SDK Tools r22.  Try to locate them.
     android_build_tools=""
-    for suffix in android-4.3 19.0.0 18.1.0 18.0.1 18.0.0 17.0.0 android-4.2.2; do
+    for suffix in android-4.4 android-4.3 android-4.2.2 19.0.0 18.1.0 18.0.1 18.0.0 17.0.0; do
         tools_directory="$android_sdk_root/build-tools/$suffix"
         if test -d "$tools_directory" ; then
             android_build_tools="$tools_directory"
             break
         fi
     done
     if test -z "$android_build_tools" ; then
         android_build_tools="$android_platform_tools" # SDK Tools < r22
--- a/content/canvas/test/webgl/non-conf-tests/mochitest.ini
+++ b/content/canvas/test/webgl/non-conf-tests/mochitest.ini
@@ -2,9 +2,10 @@
 support-files =
   driver-info.js
   webgl-util.js
 
 [test_highp_fs.html]
 [test_no_arr_points.html]
 [test_webgl_available.html]
 [test_webgl_conformance.html]
+[test_webgl_request_context.html]
 [test_webgl_request_mismatch.html]
new file mode 100644
--- /dev/null
+++ b/content/canvas/test/webgl/non-conf-tests/test_webgl_request_context.html
@@ -0,0 +1,40 @@
+<!DOCTYPE HTML>
+<title>WebGL test: 'webgl' and 'experimental-webgl' context requests succeed,
+    'moz-webgl' context requests fail.</title>
+<script src="/MochiKit/MochiKit.js"></script>
+<script src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" href="/tests/SimpleTest/test.css">
+<script src="driver-info.js"></script>
+<body>
+<canvas id="c1"></canvas>
+<canvas id="c2"></canvas>
+<script>
+
+var testFunc = ok;
+if (DriverInfo.getOS() == DriverInfo.OS.B2G) {
+  testFunc = todo;
+}
+
+function testContextRetrieval(canvasId, creationId, shouldSucceed) {
+  var canvas = document.getElementById(canvasId);
+  ok(canvas, 'Invalid `canvasId`: ' + canvasId);
+
+  var createdGL = canvas.getContext(creationId);
+  if (shouldSucceed) {
+    testFunc(createdGL, 'Request for \'' + creationId + '\' should succeed.');
+  } else {
+    ok(!createdGL, 'Request for \'' + creationId + '\' should fail.');
+  }
+}
+
+SimpleTest.waitForExplicitFinish();
+SpecialPowers.pushPrefEnv({'set': [
+  ['webgl.force-enabled', true]
+]}, function() {
+  testContextRetrieval('c1', 'experimental-webgl', true);
+  testContextRetrieval('c2', 'moz-webgl', false);
+  SimpleTest.finish();
+});
+
+</script>
+
--- a/content/html/content/src/HTMLCanvasElement.cpp
+++ b/content/html/content/src/HTMLCanvasElement.cpp
@@ -680,18 +680,17 @@ HTMLCanvasElement::GetContext(const nsAS
   *aContext = GetContext(nullptr, aContextId, JS::NullHandleValue, rv).get();
   return rv.ErrorCode();
 }
 
 static bool
 IsContextIdWebGL(const nsAString& str)
 {
   return str.EqualsLiteral("webgl") ||
-         str.EqualsLiteral("experimental-webgl") ||
-         str.EqualsLiteral("moz-webgl");
+         str.EqualsLiteral("experimental-webgl");
 }
 
 already_AddRefed<nsISupports>
 HTMLCanvasElement::GetContext(JSContext* aCx,
                               const nsAString& aContextId,
                               JS::Handle<JS::Value> aContextOptions,
                               ErrorResult& rv)
 {
--- a/content/media/SharedThreadPool.cpp
+++ b/content/media/SharedThreadPool.cpp
@@ -10,17 +10,17 @@
 #include "nsDataHashtable.h"
 #include "VideoUtils.h"
 #include "nsXPCOMCIDInternal.h"
 #include "nsComponentManagerUtils.h"
 #include "mozilla/Preferences.h"
 
 #ifdef XP_WIN
 // Required to init MSCOM by MSCOMInitThreadPoolListener.
-#include <Objbase.h>
+#include <objbase.h>
 #endif
 
 namespace mozilla {
 
 // Created and destroyed on the main thread.
 static StaticAutoPtr<ReentrantMonitor> sMonitor;
 
 // Hashtable, maps thread pool name to SharedThreadPool instance.
--- a/dom/base/Crypto.cpp
+++ b/dom/base/Crypto.cpp
@@ -145,17 +145,17 @@ Crypto::SetEnableSmartCardEvents(bool aE
   aRv.Throw(NS_ERROR_NOT_IMPLEMENTED);
 }
 
 void
 Crypto::GetVersion(nsString& aVersion)
 {
 }
 
-already_AddRefed<nsIDOMCRMFObject>
+mozilla::dom::CRMFObject*
 Crypto::GenerateCRMFRequest(JSContext* aContext,
                             const nsCString& aReqDN,
                             const nsCString& aRegToken,
                             const nsCString& aAuthenticator,
                             const nsCString& aEaCert,
                             const nsCString& aJsCallback,
                             const Sequence<JS::Value>& aArgs,
                             ErrorResult& aRv)
--- a/dom/base/Crypto.h
+++ b/dom/base/Crypto.h
@@ -3,17 +3,21 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef mozilla_dom_Crypto_h
 #define mozilla_dom_Crypto_h
 
 #ifdef MOZ_DISABLE_CRYPTOLEGACY
 #include "nsIDOMCrypto.h"
 #else
 #include "nsIDOMCryptoLegacy.h"
-class nsIDOMCRMFObject;
+namespace mozilla {
+namespace dom {
+class CRMFObject;
+}
+}
 #endif
 
 #include "nsPIDOMWindow.h"
 
 #include "nsWrapperCache.h"
 #include "mozilla/dom/TypedArray.h"
 #define NS_DOMCRYPTO_CID \
   {0x929d9320, 0x251e, 0x11d4, { 0x8a, 0x7c, 0x00, 0x60, 0x08, 0xc8, 0x44, 0xc3} }
@@ -41,17 +45,17 @@ public:
 		  ErrorResult& aRv);
 
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
   virtual bool EnableSmartCardEvents();
   virtual void SetEnableSmartCardEvents(bool aEnable, ErrorResult& aRv);
 
   virtual void GetVersion(nsString& aVersion);
 
-  virtual already_AddRefed<nsIDOMCRMFObject>
+  virtual mozilla::dom::CRMFObject*
   GenerateCRMFRequest(JSContext* aContext,
                       const nsCString& aReqDN,
                       const nsCString& aRegToken,
                       const nsCString& aAuthenticator,
                       const nsCString& aEaCert,
                       const nsCString& aJsCallback,
                       const Sequence<JS::Value>& aArgs,
                       ErrorResult& aRv);
--- a/dom/base/Navigator.cpp
+++ b/dom/base/Navigator.cpp
@@ -1684,17 +1684,19 @@ Navigator::HasMobileMessageSupport(JSCon
 
 #ifndef MOZ_WEBSMS_BACKEND
   return false;
 #endif
 
   // First of all, the general pref has to be turned on.
   bool enabled = false;
   Preferences::GetBool("dom.sms.enabled", &enabled);
-  NS_ENSURE_TRUE(enabled, false);
+  if (!enabled) {
+    return false;
+  }
 
   NS_ENSURE_TRUE(win, false);
   NS_ENSURE_TRUE(win->GetDocShell(), false);
 
   if (!CheckPermission(win, "sms")) {
     return false;
   }
 
@@ -1705,17 +1707,19 @@ Navigator::HasMobileMessageSupport(JSCon
 bool
 Navigator::HasTelephonySupport(JSContext* cx, JSObject* aGlobal)
 {
   JS::Rooted<JSObject*> global(cx, aGlobal);
 
   // First of all, the general pref has to be turned on.
   bool enabled = false;
   Preferences::GetBool("dom.telephony.enabled", &enabled);
-  NS_ENSURE_TRUE(enabled, false);
+  if (!enabled) {
+    return false;
+  }
 
   nsCOMPtr<nsPIDOMWindow> win = GetWindowFromGlobal(global);
   return win && CheckPermission(win, "telephony");
 }
 
 /* static */
 bool
 Navigator::HasCameraSupport(JSContext* /* unused */, JSObject* aGlobal)
@@ -1886,17 +1890,19 @@ Navigator::HasInputMethodSupport(JSConte
 bool
 Navigator::HasDataStoreSupport(JSContext* cx, JSObject* aGlobal)
 {
   JS::Rooted<JSObject*> global(cx, aGlobal);
 
   // First of all, the general pref has to be turned on.
   bool enabled = false;
   Preferences::GetBool("dom.datastore.enabled", &enabled);
-  NS_ENSURE_TRUE(enabled, false);
+  if (!enabled) {
+    return false;
+  }
 
   // Just for testing, we can enable DataStore for any kind of app.
   if (Preferences::GetBool("dom.testing.datastore_enabled_for_hosted_apps", false)) {
     return true;
   }
 
   nsCOMPtr<nsPIDOMWindow> win = GetWindowFromGlobal(global);
   if (!win) {
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -105,19 +105,16 @@
 #include "nsIDOMCSSMozDocumentRule.h"
 #include "nsIDOMCSSSupportsRule.h"
 #include "nsIDOMMozCSSKeyframeRule.h"
 #include "nsIDOMMozCSSKeyframesRule.h"
 #include "nsIDOMCSSPageRule.h"
 #include "nsIDOMCSSStyleRule.h"
 #include "nsIDOMCSSStyleSheet.h"
 #include "nsIDOMXULCommandDispatcher.h"
-#ifndef MOZ_DISABLE_CRYPTOLEGACY
-#include "nsIDOMCRMFObject.h"
-#endif
 #include "nsIControllers.h"
 #include "nsIBoxObject.h"
 #ifdef MOZ_XUL
 #include "nsITreeSelection.h"
 #include "nsITreeContentView.h"
 #include "nsITreeView.h"
 #include "nsIXULTemplateBuilder.h"
 #include "nsITreeColumns.h"
@@ -223,20 +220,16 @@ static NS_DEFINE_CID(kDOMSOF_CID, NS_DOM
 /**
  * To generate the bitmap for a class that we're sure doesn't implement any of
  * the interfaces in DOMCI_CASTABLE_INTERFACES.
  */
 #define DOMCI_DATA_NO_CLASS(_dom_class)                                       \
 const uint32_t kDOMClassInfo_##_dom_class##_interfaces =                      \
   0;
 
-#ifndef MOZ_DISABLE_CRYPTOLEGACY
-DOMCI_DATA_NO_CLASS(CRMFObject)
-#endif
-
 DOMCI_DATA_NO_CLASS(ContentFrameMessageManager)
 DOMCI_DATA_NO_CLASS(ChromeMessageBroadcaster)
 DOMCI_DATA_NO_CLASS(ChromeMessageSender)
 
 DOMCI_DATA_NO_CLASS(DOMPrototype)
 DOMCI_DATA_NO_CLASS(DOMConstructor)
 
 DOMCI_DATA_NO_CLASS(UserDataHandler)
@@ -349,22 +342,16 @@ static nsDOMClassInfoData sClassInfoData
                                       DEFAULT_SCRIPTABLE_FLAGS)
 #ifdef MOZ_XUL
   NS_DEFINE_CHROME_XBL_CLASSINFO_DATA(TreeSelection, nsDOMGenericSH,
                                       DEFAULT_SCRIPTABLE_FLAGS)
   NS_DEFINE_CHROME_XBL_CLASSINFO_DATA(TreeContentView, nsDOMGenericSH,
                                       DEFAULT_SCRIPTABLE_FLAGS)
 #endif
 
-  // Crypto classes
-#ifndef MOZ_DISABLE_CRYPTOLEGACY
-  NS_DEFINE_CLASSINFO_DATA(CRMFObject, nsDOMGenericSH,
-                           DOM_DEFAULT_SCRIPTABLE_FLAGS)
-#endif
-
   // DOM Chrome Window class.
   NS_DEFINE_CHROME_XBL_CLASSINFO_DATA(ChromeWindow, nsWindowSH,
                                       DEFAULT_SCRIPTABLE_FLAGS |
                                       WINDOW_SCRIPTABLE_FLAGS)
 
 #ifdef MOZ_XUL
   NS_DEFINE_CHROME_XBL_CLASSINFO_DATA(XULTemplateBuilder, nsDOMGenericSH,
                                       DEFAULT_SCRIPTABLE_FLAGS)
@@ -1011,22 +998,16 @@ nsDOMClassInfo::Init()
   DOM_CLASSINFO_MAP_END
 
   DOM_CLASSINFO_MAP_BEGIN(TreeContentView, nsITreeContentView)
     DOM_CLASSINFO_MAP_ENTRY(nsITreeContentView)
     DOM_CLASSINFO_MAP_ENTRY(nsITreeView)
   DOM_CLASSINFO_MAP_END
 #endif
 
-#ifndef MOZ_DISABLE_CRYPTOLEGACY
-   DOM_CLASSINFO_MAP_BEGIN(CRMFObject, nsIDOMCRMFObject)
-     DOM_CLASSINFO_MAP_ENTRY(nsIDOMCRMFObject)
-   DOM_CLASSINFO_MAP_END
-#endif
-
   DOM_CLASSINFO_MAP_BEGIN_NO_CLASS_IF(ChromeWindow, nsIDOMWindow)
     DOM_CLASSINFO_WINDOW_MAP_ENTRIES
     DOM_CLASSINFO_MAP_ENTRY(nsIDOMChromeWindow)
 #ifdef MOZ_WEBSPEECH
     DOM_CLASSINFO_MAP_ENTRY(nsISpeechSynthesisGetter)
 #endif
   DOM_CLASSINFO_MAP_END
 
--- a/dom/base/nsDOMClassInfoClasses.h
+++ b/dom/base/nsDOMClassInfoClasses.h
@@ -25,21 +25,16 @@ DOMCI_CLASS(XULCommandDispatcher)
 #endif
 DOMCI_CLASS(XULControllers)
 DOMCI_CLASS(BoxObject)
 #ifdef MOZ_XUL
 DOMCI_CLASS(TreeSelection)
 DOMCI_CLASS(TreeContentView)
 #endif
 
-// Crypto classes
-#ifndef MOZ_DISABLE_CRYPTOLEGACY
-DOMCI_CLASS(CRMFObject)
-#endif
-
 // DOM Chrome Window class, almost identical to Window
 DOMCI_CLASS(ChromeWindow)
 
 #ifdef MOZ_XUL
 DOMCI_CLASS(XULTemplateBuilder)
 DOMCI_CLASS(XULTreeBuilder)
 #endif
 
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -246,16 +246,22 @@ DOMInterfaces = {
     'implicitJSContext': [ 'buffer' ],
     'resultNotAddRefed': [ 'buffer' ],
 },
 
 'Coordinates': {
     'headerFile': 'nsGeoPosition.h'
 },
 
+'CRMFObject': {
+    'headerFile': 'nsCrypto.h',
+    'nativeOwnership': 'owned',
+    'wrapperCache': False,
+},
+
 'Crypto' : {
     'implicitJSContext': [ 'generateCRMFRequest', 'signText' ],
     'headerFile': 'Crypto.h'
 },
 
 'CSS': {
     'concrete': False,
 },
--- a/dom/interfaces/base/domstubs.idl
+++ b/dom/interfaces/base/domstubs.idl
@@ -71,15 +71,14 @@ interface nsIDOMRect;
 interface nsIDOMCSSStyleRule;
 interface nsIDOMCSSStyleRuleCollection;
 interface nsIDOMHTMLTableCaptionElement;
 
 // Range
 interface nsIDOMRange;
 
 // Crypto
-interface nsIDOMCRMFObject;
 interface nsIDOMCrypto;
 interface nsIDOMPkcs11;
 
 // Used font face (for inspector)
 interface nsIDOMFontFace;
 interface nsIDOMFontFaceList;
--- a/dom/interfaces/base/moz.build
+++ b/dom/interfaces/base/moz.build
@@ -11,17 +11,16 @@ XPIDL_SOURCES += [
     'nsIContentPermissionPrompt.idl',
     'nsIContentPrefService.idl',
     'nsIContentPrefService2.idl',
     'nsIContentURIGrouper.idl',
     'nsIDOMChromeWindow.idl',
     'nsIDOMClientRect.idl',
     'nsIDOMClientRectList.idl',
     'nsIDOMConstructor.idl',
-    'nsIDOMCRMFObject.idl',
     'nsIDOMGlobalObjectConstructor.idl',
     'nsIDOMGlobalPropertyInitializer.idl',
     'nsIDOMHistory.idl',
     'nsIDOMJSWindow.idl',
     'nsIDOMLocation.idl',
     'nsIDOMModalContentWindow.idl',
     'nsIDOMNavigator.idl',
     'nsIDOMPkcs11.idl',
deleted file mode 100644
--- a/dom/interfaces/base/nsIDOMCRMFObject.idl
+++ /dev/null
@@ -1,12 +0,0 @@
-/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* 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/. */
-
-#include "domstubs.idl"
-
-[scriptable, uuid(16da46c0-208d-11d4-8a7c-006008c844c3)]
-interface nsIDOMCRMFObject : nsISupports
-{
-  readonly attribute DOMString        request;
-};
--- a/dom/interfaces/base/nsIDOMCryptoLegacy.idl
+++ b/dom/interfaces/base/nsIDOMCryptoLegacy.idl
@@ -1,16 +1,15 @@
 /* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* 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/. */
 
 #include "domstubs.idl"
 
-interface nsIDOMCRMFObject;
 interface nsIDOMWindow;
 
 [uuid(c25ecf08-3f46-4420-bee4-8505792fd63a)]
 interface nsIDOMCrypto : nsISupports
 {
   [notxpcom] void init(in nsIDOMWindow window);
   attribute boolean         enableSmartCardEvents;
 };
--- a/dom/tests/mochitest/general/test_interfaces.html
+++ b/dom/tests/mochitest/general/test_interfaces.html
@@ -206,18 +206,16 @@ var interfaceNamesInGlobalScope =
     "Comment",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "CompositionEvent",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "Controllers",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "ConvolverNode",
 // IMPORTANT: Do not change this list without review from a DOM peer!
-    {name: "CRMFObject", desktop: true},
-// IMPORTANT: Do not change this list without review from a DOM peer!
     "Crypto",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "CSS",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "CSS2Properties",
 // IMPORTANT: Do not change this list without review from a DOM peer!
     "CSSCharsetRule",
 // IMPORTANT: Do not change this list without review from a DOM peer!
new file mode 100644
--- /dev/null
+++ b/dom/webidl/CRMFObject.webidl
@@ -0,0 +1,10 @@
+/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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/.
+ */
+
+[NoInterfaceObject]
+interface CRMFObject {
+  readonly attribute DOMString request;
+};
--- a/dom/webidl/Crypto.webidl
+++ b/dom/webidl/Crypto.webidl
@@ -14,32 +14,30 @@ interface RandomSource {
 };
 
 Crypto implements RandomSource;
 
 interface Crypto {
 };
 
 #ifndef MOZ_DISABLE_CRYPTOLEGACY
-interface CRMFObject;
-
 [NoInterfaceObject]
 interface CryptoLegacy {
   readonly attribute DOMString version;
 
   [SetterThrows]
   attribute boolean enableSmartCardEvents;
 
-  [Throws]
-  CRMFObject generateCRMFRequest(ByteString? reqDN,
-                                 ByteString? regToken,
-                                 ByteString? authenticator,
-                                 ByteString? eaCert,
-                                 ByteString? jsCallback,
-                                 any... args);
+  [Throws,NewObject]
+  CRMFObject? generateCRMFRequest(ByteString? reqDN,
+                                  ByteString? regToken,
+                                  ByteString? authenticator,
+                                  ByteString? eaCert,
+                                  ByteString? jsCallback,
+                                  any... args);
 
   [Throws]
   DOMString importUserCertificates(DOMString nickname,
                                    DOMString cmmfResponse,
                                    boolean doForcedBackup);
 
   [Throws]
   DOMString popChallengeResponse(DOMString challenge);
--- a/dom/webidl/moz.build
+++ b/dom/webidl/moz.build
@@ -547,16 +547,21 @@ if CONFIG['MOZ_WEBSPEECH']:
         'SpeechRecognitionEvent.webidl',
     ]
 
 if CONFIG['MOZ_B2G_FM']:
     WEBIDL_FILES += [
         'FMRadio.webidl',
     ]
 
+if not CONFIG['MOZ_DISABLE_CRYPTOLEGACY']:
+    WEBIDL_FILES += [
+        'CRMFObject.webidl',
+    ]
+
 GENERATED_EVENTS_WEBIDL_FILES = [
     'BlobEvent.webidl',
     'CallGroupErrorEvent.webidl',
     'CFStateChangeEvent.webidl',
     'DataErrorEvent.webidl',
     'DataStoreChangeEvent.webidl',
     'DeviceLightEvent.webidl',
     'DeviceProximityEvent.webidl',
--- a/gfx/2d/Matrix.h
+++ b/gfx/2d/Matrix.h
@@ -215,16 +215,25 @@ public:
    * scaling and translation.
    */
   bool PreservesAxisAlignedRectangles() const {
       return ((FuzzyEqual(_11, 0.0) && FuzzyEqual(_22, 0.0))
           || (FuzzyEqual(_12, 0.0) && FuzzyEqual(_21, 0.0)));
   }
 
   /**
+   * Returns true if the matrix has any transform other
+   * than a translation or scale; this is, if there is
+   * no rotation.
+   */
+  bool HasNonAxisAlignedTransform() const {
+      return !FuzzyEqual(_21, 0.0) || !FuzzyEqual(_12, 0.0);
+  }
+
+  /**
    * Returns true if the matrix has non-integer scale
    */
   bool HasNonIntegerScale() const {
       return !FuzzyEqual(_11, floor(_11 + 0.5)) ||
              !FuzzyEqual(_22, floor(_22 + 0.5));
   }
 
 private:
new file mode 100644
--- /dev/null
+++ b/gfx/angle/angle-build-mingw.patch
@@ -0,0 +1,201 @@
+From: Jacek Caban <jacek@codeweavers.com>
+Bug 945292 - Fixed ANGLE compilation on mingw.
+
+
+diff --git a/gfx/angle/src/common/debug.h b/gfx/angle/src/common/debug.h
+index 23ee26d..060b727 100644
+--- a/gfx/angle/src/common/debug.h
++++ b/gfx/angle/src/common/debug.h
+@@ -94,18 +94,20 @@ namespace gl
+ #define UNREACHABLE() do { \
+     ERR("\t! Unreachable reached: %s(%d)\n", __FUNCTION__, __LINE__); \
+     assert(false); \
+     } while(0)
+ #else
+     #define UNREACHABLE() ERR("\t! Unreachable reached: %s(%d)\n", __FUNCTION__, __LINE__)
+ #endif
+ 
+-// A macro that determines whether an object has a given runtime type.
+-#if !defined(NDEBUG) && (!defined(_MSC_VER) || defined(_CPPRTTI))
++// A macro that determines whether an object has a given runtime type. MSVC uses _CPPRTTI.
++// GCC uses __GXX_RTTI, but the macro was introduced in version 4.3, so we assume that all older
++// versions support RTTI.
++#if !defined(NDEBUG) && (!defined(_MSC_VER) || defined(_CPPRTTI)) && (!defined(__GNUC__) || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3) || defined(__GXX_RTTI))
+ #define HAS_DYNAMIC_TYPE(type, obj) (dynamic_cast<type >(obj) != NULL)
+ #else
+ #define HAS_DYNAMIC_TYPE(type, obj) true
+ #endif
+ 
+ // A macro functioning as a compile-time assert to validate constant conditions
+ #define META_ASSERT(condition) typedef int COMPILE_TIME_ASSERT_##__LINE__[static_cast<bool>(condition)?1:-1]
+ 
+diff --git a/gfx/angle/src/libGLESv2/Constants.h b/gfx/angle/src/libGLESv2/Constants.h
+new file mode 100644
+index 0000000..9f24d66
+--- /dev/null
++++ b/gfx/angle/src/libGLESv2/Constants.h
+@@ -0,0 +1,34 @@
++//
++// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
++// Use of this source code is governed by a BSD-style license that can be
++// found in the LICENSE file.
++//
++
++// Contants.h: Defines some implementation specific and gl constants
++
++#ifndef LIBGLESV2_CONSTANTS_H_
++#define LIBGLESV2_CONSTANTS_H_
++
++namespace gl
++{
++
++enum
++{
++    MAX_VERTEX_ATTRIBS = 16,
++    MAX_TEXTURE_IMAGE_UNITS = 16,
++
++    // Implementation upper limits, real maximums depend on the hardware
++    IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 16,
++    IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS = MAX_TEXTURE_IMAGE_UNITS + IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS,    
++
++    IMPLEMENTATION_MAX_VARYING_VECTORS = 32,
++    IMPLEMENTATION_MAX_DRAW_BUFFERS = 8
++};
++
++const float ALIASED_LINE_WIDTH_RANGE_MIN = 1.0f;
++const float ALIASED_LINE_WIDTH_RANGE_MAX = 1.0f;
++const float ALIASED_POINT_SIZE_RANGE_MIN = 1.0f;
++
++}
++
++#endif // LIBGLESV2_CONSTANTS_H_
+diff --git a/gfx/angle/src/libGLESv2/Framebuffer.h b/gfx/angle/src/libGLESv2/Framebuffer.h
+index b54e008..50bfd4f 100644
+--- a/gfx/angle/src/libGLESv2/Framebuffer.h
++++ b/gfx/angle/src/libGLESv2/Framebuffer.h
+@@ -7,17 +7,17 @@
+ // Framebuffer.h: Defines the gl::Framebuffer class. Implements GL framebuffer
+ // objects and related functionality. [OpenGL ES 2.0.24] section 4.4 page 105.
+ 
+ #ifndef LIBGLESV2_FRAMEBUFFER_H_
+ #define LIBGLESV2_FRAMEBUFFER_H_
+ 
+ #include "common/angleutils.h"
+ #include "common/RefCountObject.h"
+-#include "constants.h"
++#include "Constants.h"
+ 
+ namespace rx
+ {
+ class Renderer;
+ }
+ 
+ namespace gl
+ {
+diff --git a/gfx/angle/src/libGLESv2/constants.h b/gfx/angle/src/libGLESv2/constants.h
+deleted file mode 100644
+index 9f24d66..0000000
+--- a/gfx/angle/src/libGLESv2/constants.h
++++ /dev/null
+@@ -1,34 +0,0 @@
+-//
+-// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
+-// Use of this source code is governed by a BSD-style license that can be
+-// found in the LICENSE file.
+-//
+-
+-// Contants.h: Defines some implementation specific and gl constants
+-
+-#ifndef LIBGLESV2_CONSTANTS_H_
+-#define LIBGLESV2_CONSTANTS_H_
+-
+-namespace gl
+-{
+-
+-enum
+-{
+-    MAX_VERTEX_ATTRIBS = 16,
+-    MAX_TEXTURE_IMAGE_UNITS = 16,
+-
+-    // Implementation upper limits, real maximums depend on the hardware
+-    IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 16,
+-    IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS = MAX_TEXTURE_IMAGE_UNITS + IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS,    
+-
+-    IMPLEMENTATION_MAX_VARYING_VECTORS = 32,
+-    IMPLEMENTATION_MAX_DRAW_BUFFERS = 8
+-};
+-
+-const float ALIASED_LINE_WIDTH_RANGE_MIN = 1.0f;
+-const float ALIASED_LINE_WIDTH_RANGE_MAX = 1.0f;
+-const float ALIASED_POINT_SIZE_RANGE_MIN = 1.0f;
+-
+-}
+-
+-#endif // LIBGLESV2_CONSTANTS_H_
+diff --git a/gfx/angle/src/libGLESv2/precompiled.h b/gfx/angle/src/libGLESv2/precompiled.h
+index f62e71b..58ad181 100644
+--- a/gfx/angle/src/libGLESv2/precompiled.h
++++ b/gfx/angle/src/libGLESv2/precompiled.h
+@@ -28,15 +28,15 @@
+ #include <map>
+ #include <set>
+ #include <sstream>
+ #include <string>
+ #include <unordered_map>
+ #include <vector>
+ 
+ #include <d3d9.h>
+-#include <D3D11.h>
++#include <d3d11.h>
+ #include <dxgi.h>
+ #include <d3dcompiler.h>
+ 
+ #ifdef _MSC_VER
+ #include <hash_map>
+ #endif
+diff --git a/gfx/angle/src/libGLESv2/renderer/Renderer11.cpp b/gfx/angle/src/libGLESv2/renderer/Renderer11.cpp
+index 774cd71..1f2b31d 100644
+--- a/gfx/angle/src/libGLESv2/renderer/Renderer11.cpp
++++ b/gfx/angle/src/libGLESv2/renderer/Renderer11.cpp
+@@ -7,17 +7,17 @@
+ 
+ // Renderer11.cpp: Implements a back-end specific class for the D3D11 renderer.
+ 
+ #include "libGLESv2/main.h"
+ #include "libGLESv2/utilities.h"
+ #include "libGLESv2/Buffer.h"
+ #include "libGLESv2/ProgramBinary.h"
+ #include "libGLESv2/Framebuffer.h"
+-#include "libGLESv2/RenderBuffer.h"
++#include "libGLESv2/Renderbuffer.h"
+ #include "libGLESv2/renderer/Renderer11.h"
+ #include "libGLESv2/renderer/RenderTarget11.h"
+ #include "libGLESv2/renderer/renderer11_utils.h"
+ #include "libGLESv2/renderer/ShaderExecutable11.h"
+ #include "libGLESv2/renderer/SwapChain11.h"
+ #include "libGLESv2/renderer/Image11.h"
+ #include "libGLESv2/renderer/VertexBuffer11.h"
+ #include "libGLESv2/renderer/IndexBuffer11.h"
+diff --git a/gfx/angle/src/libGLESv2/renderer/Renderer11.h b/gfx/angle/src/libGLESv2/renderer/Renderer11.h
+index f024855..90ef04d 100644
+--- a/gfx/angle/src/libGLESv2/renderer/Renderer11.h
++++ b/gfx/angle/src/libGLESv2/renderer/Renderer11.h
+@@ -230,17 +230,17 @@ class Renderer11 : public Renderer
+     bool mDepthTextureSupport;
+ 
+     // Multisample format support
+     struct MultisampleSupportInfo
+     {
+         unsigned int qualityLevels[D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT];
+     };
+ 
+-    typedef std::unordered_map<DXGI_FORMAT, MultisampleSupportInfo> MultisampleSupportMap;
++    typedef std::unordered_map<DXGI_FORMAT, MultisampleSupportInfo, std::hash<int> > MultisampleSupportMap;
+     MultisampleSupportMap mMultisampleSupportMap;
+ 
+     unsigned int mMaxSupportedSamples;
+ 
+     // current render target states
+     unsigned int mAppliedRenderTargetSerials[gl::IMPLEMENTATION_MAX_DRAW_BUFFERS];
+     unsigned int mAppliedDepthbufferSerial;
+     unsigned int mAppliedStencilbufferSerial;
--- a/gfx/angle/src/common/debug.h
+++ b/gfx/angle/src/common/debug.h
@@ -94,18 +94,20 @@ namespace gl
 #define UNREACHABLE() do { \
     ERR("\t! Unreachable reached: %s(%d)\n", __FUNCTION__, __LINE__); \
     assert(false); \
     } while(0)
 #else
     #define UNREACHABLE() ERR("\t! Unreachable reached: %s(%d)\n", __FUNCTION__, __LINE__)
 #endif
 
-// A macro that determines whether an object has a given runtime type.
-#if !defined(NDEBUG) && (!defined(_MSC_VER) || defined(_CPPRTTI))
+// A macro that determines whether an object has a given runtime type. MSVC uses _CPPRTTI.
+// GCC uses __GXX_RTTI, but the macro was introduced in version 4.3, so we assume that all older
+// versions support RTTI.
+#if !defined(NDEBUG) && (!defined(_MSC_VER) || defined(_CPPRTTI)) && (!defined(__GNUC__) || __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3) || defined(__GXX_RTTI))
 #define HAS_DYNAMIC_TYPE(type, obj) (dynamic_cast<type >(obj) != NULL)
 #else
 #define HAS_DYNAMIC_TYPE(type, obj) true
 #endif
 
 // A macro functioning as a compile-time assert to validate constant conditions
 #define META_ASSERT(condition) typedef int COMPILE_TIME_ASSERT_##__LINE__[static_cast<bool>(condition)?1:-1]
 
new file mode 100644
--- /dev/null
+++ b/gfx/angle/src/libGLESv2/Constants.h
@@ -0,0 +1,34 @@
+//
+// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+//
+
+// Contants.h: Defines some implementation specific and gl constants
+
+#ifndef LIBGLESV2_CONSTANTS_H_
+#define LIBGLESV2_CONSTANTS_H_
+
+namespace gl
+{
+
+enum
+{
+    MAX_VERTEX_ATTRIBS = 16,
+    MAX_TEXTURE_IMAGE_UNITS = 16,
+
+    // Implementation upper limits, real maximums depend on the hardware
+    IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 16,
+    IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS = MAX_TEXTURE_IMAGE_UNITS + IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS,    
+
+    IMPLEMENTATION_MAX_VARYING_VECTORS = 32,
+    IMPLEMENTATION_MAX_DRAW_BUFFERS = 8
+};
+
+const float ALIASED_LINE_WIDTH_RANGE_MIN = 1.0f;
+const float ALIASED_LINE_WIDTH_RANGE_MAX = 1.0f;
+const float ALIASED_POINT_SIZE_RANGE_MIN = 1.0f;
+
+}
+
+#endif // LIBGLESV2_CONSTANTS_H_
--- a/gfx/angle/src/libGLESv2/Framebuffer.h
+++ b/gfx/angle/src/libGLESv2/Framebuffer.h
@@ -7,17 +7,17 @@
 // Framebuffer.h: Defines the gl::Framebuffer class. Implements GL framebuffer
 // objects and related functionality. [OpenGL ES 2.0.24] section 4.4 page 105.
 
 #ifndef LIBGLESV2_FRAMEBUFFER_H_
 #define LIBGLESV2_FRAMEBUFFER_H_
 
 #include "common/angleutils.h"
 #include "common/RefCountObject.h"
-#include "constants.h"
+#include "Constants.h"
 
 namespace rx
 {
 class Renderer;
 }
 
 namespace gl
 {
deleted file mode 100644
--- a/gfx/angle/src/libGLESv2/constants.h
+++ /dev/null
@@ -1,34 +0,0 @@
-//
-// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-//
-
-// Contants.h: Defines some implementation specific and gl constants
-
-#ifndef LIBGLESV2_CONSTANTS_H_
-#define LIBGLESV2_CONSTANTS_H_
-
-namespace gl
-{
-
-enum
-{
-    MAX_VERTEX_ATTRIBS = 16,
-    MAX_TEXTURE_IMAGE_UNITS = 16,
-
-    // Implementation upper limits, real maximums depend on the hardware
-    IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 16,
-    IMPLEMENTATION_MAX_COMBINED_TEXTURE_IMAGE_UNITS = MAX_TEXTURE_IMAGE_UNITS + IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS,    
-
-    IMPLEMENTATION_MAX_VARYING_VECTORS = 32,
-    IMPLEMENTATION_MAX_DRAW_BUFFERS = 8
-};
-
-const float ALIASED_LINE_WIDTH_RANGE_MIN = 1.0f;
-const float ALIASED_LINE_WIDTH_RANGE_MAX = 1.0f;
-const float ALIASED_POINT_SIZE_RANGE_MIN = 1.0f;
-
-}
-
-#endif // LIBGLESV2_CONSTANTS_H_
--- a/gfx/angle/src/libGLESv2/precompiled.h
+++ b/gfx/angle/src/libGLESv2/precompiled.h
@@ -28,15 +28,15 @@
 #include <map>
 #include <set>
 #include <sstream>
 #include <string>
 #include <unordered_map>
 #include <vector>
 
 #include <d3d9.h>
-#include <D3D11.h>
+#include <d3d11.h>
 #include <dxgi.h>
 #include <d3dcompiler.h>
 
 #ifdef _MSC_VER
 #include <hash_map>
 #endif
--- a/gfx/angle/src/libGLESv2/renderer/Renderer11.cpp
+++ b/gfx/angle/src/libGLESv2/renderer/Renderer11.cpp
@@ -7,17 +7,17 @@
 
 // Renderer11.cpp: Implements a back-end specific class for the D3D11 renderer.
 
 #include "libGLESv2/main.h"
 #include "libGLESv2/utilities.h"
 #include "libGLESv2/Buffer.h"
 #include "libGLESv2/ProgramBinary.h"
 #include "libGLESv2/Framebuffer.h"
-#include "libGLESv2/RenderBuffer.h"
+#include "libGLESv2/Renderbuffer.h"
 #include "libGLESv2/renderer/Renderer11.h"
 #include "libGLESv2/renderer/RenderTarget11.h"
 #include "libGLESv2/renderer/renderer11_utils.h"
 #include "libGLESv2/renderer/ShaderExecutable11.h"
 #include "libGLESv2/renderer/SwapChain11.h"
 #include "libGLESv2/renderer/Image11.h"
 #include "libGLESv2/renderer/VertexBuffer11.h"
 #include "libGLESv2/renderer/IndexBuffer11.h"
--- a/gfx/angle/src/libGLESv2/renderer/Renderer11.h
+++ b/gfx/angle/src/libGLESv2/renderer/Renderer11.h
@@ -230,17 +230,17 @@ class Renderer11 : public Renderer
     bool mDepthTextureSupport;
 
     // Multisample format support
     struct MultisampleSupportInfo
     {
         unsigned int qualityLevels[D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT];
     };
 
-    typedef std::unordered_map<DXGI_FORMAT, MultisampleSupportInfo> MultisampleSupportMap;
+    typedef std::unordered_map<DXGI_FORMAT, MultisampleSupportInfo, std::hash<int> > MultisampleSupportMap;
     MultisampleSupportMap mMultisampleSupportMap;
 
     unsigned int mMaxSupportedSamples;
 
     // current render target states
     unsigned int mAppliedRenderTargetSerials[gl::IMPLEMENTATION_MAX_DRAW_BUFFERS];
     unsigned int mAppliedDepthbufferSerial;
     unsigned int mAppliedStencilbufferSerial;
--- a/gfx/layers/Compositor.h
+++ b/gfx/layers/Compositor.h
@@ -99,17 +99,16 @@
  * interfaces:
  * - Compositor (ex. CompositorOGL)
  * - TextureHost (ex. SharedTextureHostOGL)
  * Depending on the type of data that needs to be serialized, you may need to
  * add specific TextureClient implementations.
  */
 
 class nsIWidget;
-struct gfxMatrix;
 struct nsIntSize;
 class nsIntRegion;
 
 namespace mozilla {
 namespace gfx {
 class Matrix;
 class Matrix4x4;
 class DrawTarget;
@@ -358,17 +357,17 @@ public:
    * BeginFrame. BeginFrame sets a size and transform for the default render
    * target, usually the screen. Calling this method prepares the compositor to
    * render using a different viewport (that is, size and transform), usually
    * associated with a new render target.
    * aWorldTransform is the transform from user space to the new viewport's
    * coordinate space.
    */
   virtual void PrepareViewport(const gfx::IntSize& aSize,
-                               const gfxMatrix& aWorldTransform) = 0;
+                               const gfx::Matrix& aWorldTransform) = 0;
 
   /**
    * Whether textures created by this compositor can receive partial updates.
    */
   virtual bool SupportsPartialTextureUpdate() = 0;
 
   void SetDiagnosticTypes(DiagnosticTypes aDiagnostics)
   {
--- a/gfx/layers/ImageLayers.cpp
+++ b/gfx/layers/ImageLayers.cpp
@@ -1,16 +1,15 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * 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/. */
 
 #include "ImageLayers.h"
 #include "ImageContainer.h"             // for ImageContainer
-#include "gfx3DMatrix.h"                // for gfx3DMatrix
 #include "gfxRect.h"                    // for gfxRect
 #include "nsDebug.h"                    // for NS_ASSERTION
 #include "nsISupportsImpl.h"            // for ImageContainer::Release, etc
 #include "gfx2DGlue.h"
 
 namespace mozilla {
 namespace layers {
 
--- a/gfx/layers/Layers.cpp
+++ b/gfx/layers/Layers.cpp
@@ -579,25 +579,23 @@ Layer::CalculateScissorRect(const nsIntR
   if (clipRect->IsEmpty()) {
     // We might have a non-translation transform in the container so we can't
     // use the code path below.
     return nsIntRect(currentClip.TopLeft(), nsIntSize(0, 0));
   }
 
   nsIntRect scissor = *clipRect;
   if (!container->UseIntermediateSurface()) {
-    gfxMatrix matrix;
-    gfx3DMatrix effectiveTransform;
-    To3DMatrix(container->GetEffectiveTransform(), effectiveTransform);
-    DebugOnly<bool> is2D = effectiveTransform.Is2D(&matrix);
+    gfx::Matrix matrix;
+    DebugOnly<bool> is2D = container->GetEffectiveTransform().Is2D(&matrix);
     // See DefaultComputeEffectiveTransforms below
     NS_ASSERTION(is2D && matrix.PreservesAxisAlignedRectangles(),
                  "Non preserves axis aligned transform with clipped child should have forced intermediate surface");
-    gfxRect r(scissor.x, scissor.y, scissor.width, scissor.height);
-    gfxRect trScissor = matrix.TransformBounds(r);
+    gfx::Rect r(scissor.x, scissor.y, scissor.width, scissor.height);
+    gfxRect trScissor = gfx::ThebesRect(matrix.TransformBounds(r));
     trScissor.Round();
     if (!gfxUtils::GfxRectToIntRect(trScissor, &scissor)) {
       return nsIntRect(currentClip.TopLeft(), nsIntSize(0, 0));
     }
 
     // Find the nearest ancestor with an intermediate surface
     do {
       container = container->GetParent();
@@ -793,16 +791,18 @@ ContainerLayer::RepositionChild(Layer* a
   NS_ASSERTION(aChild->Manager() == Manager(),
                "Child has wrong manager");
   NS_ASSERTION(aChild->GetParent() == this,
                "aChild not our child");
   NS_ASSERTION(!aAfter ||
                (aAfter->Manager() == Manager() &&
                 aAfter->GetParent() == this),
                "aAfter is not our child");
+  NS_ASSERTION(aChild != aAfter,
+               "aChild cannot be the same as aAfter");
 
   Layer* prev = aChild->GetPrevSibling();
   Layer* next = aChild->GetNextSibling();
   if (prev == aAfter) {
     // aChild is already in the correct position, nothing to do.
     return;
   }
   if (prev) {
@@ -896,24 +896,22 @@ ContainerLayer::DefaultComputeEffectiveT
     useIntermediateSurface = true;
 #endif
   } else {
     float opacity = GetEffectiveOpacity();
     if (opacity != 1.0f && HasMultipleChildren()) {
       useIntermediateSurface = true;
     } else {
       useIntermediateSurface = false;
-      gfxMatrix contTransform;
-      gfx3DMatrix effectiveTransform;
-      To3DMatrix(mEffectiveTransform, effectiveTransform);
-      if (!effectiveTransform.Is2D(&contTransform) ||
+      gfx::Matrix contTransform;
+      if (!mEffectiveTransform.Is2D(&contTransform) ||
 #ifdef MOZ_GFX_OPTIMIZE_MOBILE
         !contTransform.PreservesAxisAlignedRectangles()) {
 #else
-        contTransform.HasNonIntegerTranslation()) {
+        gfx::ThebesMatrix(contTransform).HasNonIntegerTranslation()) {
 #endif
         for (Layer* child = GetFirstChild(); child; child = child->GetNextSibling()) {
           const nsIntRect *clipRect = child->GetEffectiveClipRect();
           /* We can't (easily) forward our transform to children with a non-empty clip
            * rect since it would need to be adjusted for the transform. See
            * the calculations performed by CalculateScissorRect above.
            * Nor for a child with a mask layer.
            */
--- a/gfx/layers/LayersLogging.cpp
+++ b/gfx/layers/LayersLogging.cpp
@@ -4,17 +4,16 @@
 /* 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/. */
 
 #include "LayersLogging.h"
 #include <stdint.h>                     // for uint8_t
 #include "gfx3DMatrix.h"                // for gfx3DMatrix
 #include "gfxColor.h"                   // for gfxRGBA
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "mozilla/gfx/Matrix.h"         // for Matrix4x4, Matrix
 #include "nsDebug.h"                    // for NS_ERROR
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsRect.h"                     // for nsIntRect
 #include "nsSize.h"                     // for nsIntSize
 
 using namespace mozilla::gfx;
 
@@ -65,41 +64,16 @@ AppendToString(nsACString& s, const gfxR
   s += pfx;
   s += nsPrintfCString(
     "rgba(%d, %d, %d, %g)",
     uint8_t(c.r*255.0), uint8_t(c.g*255.0), uint8_t(c.b*255.0), c.a);
   return s += sfx;
 }
 
 nsACString&
-AppendToString(nsACString& s, const gfx3DMatrix& m,
-               const char* pfx, const char* sfx)
-{
-  s += pfx;
-  if (m.IsIdentity())
-    s += "[ I ]";
-  else {
-    gfxMatrix matrix;
-    if (m.Is2D(&matrix)) {
-      s += nsPrintfCString(
-        "[ %g %g; %g %g; %g %g; ]",
-        matrix.xx, matrix.yx, matrix.xy, matrix.yy, matrix.x0, matrix.y0);
-    } else {
-      s += nsPrintfCString(
-        "[ %g %g %g %g; %g %g %g %g; %g %g %g %g; %g %g %g %g; ]",
-        m._11, m._12, m._13, m._14,
-        m._21, m._22, m._23, m._24,
-        m._31, m._32, m._33, m._34,
-        m._41, m._42, m._43, m._44);
-    }
-  }
-  return s += sfx;
-}
-
-nsACString&
 AppendToString(nsACString& s, const nsIntPoint& p,
                const char* pfx, const char* sfx)
 {
   s += pfx;
   s += nsPrintfCString("(x=%d, y=%d)", p.x, p.y);
   return s += sfx;
 }
 
--- a/gfx/layers/ReadbackProcessor.cpp
+++ b/gfx/layers/ReadbackProcessor.cpp
@@ -5,17 +5,16 @@
 
 #include "ReadbackProcessor.h"
 #include <sys/types.h>                  // for int32_t
 #include "Layers.h"                     // for Layer, ThebesLayer, etc
 #include "ReadbackLayer.h"              // for ReadbackLayer, ReadbackSink
 #include "gfx3DMatrix.h"                // for gfx3DMatrix
 #include "gfxColor.h"                   // for gfxRGBA
 #include "gfxContext.h"                 // for gfxContext
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "gfxRect.h"                    // for gfxRect
 #include "mozilla/gfx/BasePoint.h"      // for BasePoint
 #include "mozilla/gfx/BaseRect.h"       // for BaseRect
 #include "nsAutoPtr.h"                  // for nsRefPtr, nsAutoPtr
 #include "nsDebug.h"                    // for NS_ASSERTION
 #include "nsISupportsImpl.h"            // for gfxContext::Release, etc
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsRegion.h"                   // for nsIntRegion
--- a/gfx/layers/RotatedBuffer.cpp
+++ b/gfx/layers/RotatedBuffer.cpp
@@ -6,17 +6,16 @@
 #include "RotatedBuffer.h"
 #include <sys/types.h>                  // for int32_t
 #include <algorithm>                    // for max
 #include "BasicImplData.h"              // for BasicImplData
 #include "BasicLayersImpl.h"            // for ToData
 #include "BufferUnrotate.h"             // for BufferUnrotate
 #include "GeckoProfiler.h"              // for PROFILER_LABEL
 #include "Layers.h"                     // for ThebesLayer, Layer, etc
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "gfxUtils.h"                   // for gfxUtils
 #include "mozilla/ArrayUtils.h"         // for ArrayLength
 #include "mozilla/gfx/BasePoint.h"      // for BasePoint
 #include "mozilla/gfx/BaseRect.h"       // for BaseRect
 #include "mozilla/gfx/BaseSize.h"       // for BaseSize
 #include "mozilla/gfx/Matrix.h"         // for Matrix
 #include "mozilla/gfx/Point.h"          // for Point, IntPoint
@@ -183,17 +182,17 @@ RotatedContentBuffer::IsClippingCheap(Dr
 }
 
 void
 RotatedContentBuffer::DrawTo(ThebesLayer* aLayer,
                              DrawTarget* aTarget,
                              float aOpacity,
                              CompositionOp aOp,
                              gfxASurface* aMask,
-                             const gfxMatrix* aMaskTransform)
+                             const Matrix* aMaskTransform)
 {
   if (!EnsureBuffer()) {
     return;
   }
 
   bool clipped = false;
 
   // If the entire buffer is valid, we can just draw the whole thing,
@@ -215,17 +214,17 @@ RotatedContentBuffer::DrawTo(ThebesLayer
 
   RefPtr<gfx::SourceSurface> mask;
   if (aMask) {
     mask = gfxPlatform::GetPlatform()->GetSourceSurfaceForSurface(aTarget, aMask);
   }
 
   Matrix maskTransform;
   if (aMaskTransform) {
-    maskTransform = ToMatrix(*aMaskTransform);
+    maskTransform = *aMaskTransform;
   }
 
   DrawBufferWithRotation(aTarget, BUFFER_BLACK, aOpacity, aOp, mask, &maskTransform);
   if (clipped) {
     aTarget->PopClip();
   }
 }
 
--- a/gfx/layers/RotatedBuffer.h
+++ b/gfx/layers/RotatedBuffer.h
@@ -16,17 +16,16 @@
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsDebug.h"                    // for NS_RUNTIMEABORT
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsRect.h"                     // for nsIntRect
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTraceRefcnt.h"              // for MOZ_COUNT_CTOR, etc
 #include "LayersTypes.h"
 
-struct gfxMatrix;
 struct nsIntSize;
 
 namespace mozilla {
 namespace gfx {
 class Matrix;
 }
 
 namespace layers {
@@ -287,17 +286,17 @@ public:
    * drawn before this is called. The contents of the buffer are drawn
    * to aTarget.
    */
   void DrawTo(ThebesLayer* aLayer,
               gfx::DrawTarget* aTarget,
               float aOpacity,
               gfx::CompositionOp aOp,
               gfxASurface* aMask,
-              const gfxMatrix* aMaskTransform);
+              const gfx::Matrix* aMaskTransform);
 
 protected:
   TemporaryRef<gfx::DrawTarget>
   SetDTBuffer(gfx::DrawTarget* aBuffer,
               const nsIntRect& aBufferRect,
               const nsIntPoint& aBufferRotation)
   {
     RefPtr<gfx::DrawTarget> tmp = mDTBuffer.forget();
--- a/gfx/layers/basic/AutoMaskData.h
+++ b/gfx/layers/basic/AutoMaskData.h
@@ -29,33 +29,33 @@ public:
 
   /**
    * Construct this out of either a gfxASurface or a
    * SurfaceDescriptor.  Construct() must only be called once.
    * GetSurface() and GetTransform() must not be called until this has
    * been constructed.
    */
 
-  void Construct(const gfxMatrix& aTransform,
+  void Construct(const gfx::Matrix& aTransform,
                  gfxASurface* aSurface);
 
-  void Construct(const gfxMatrix& aTransform,
+  void Construct(const gfx::Matrix& aTransform,
                  const SurfaceDescriptor& aSurface);
 
   /** The returned surface can't escape the scope of |this|. */
   gfxASurface* GetSurface();
-  const gfxMatrix& GetTransform();
+  const gfx::Matrix& GetTransform();
 
 private:
   bool IsConstructed();
 
-  gfxMatrix mTransform;
+  gfx::Matrix mTransform;
   nsRefPtr<gfxASurface> mSurface;
   Maybe<AutoOpenSurface> mSurfaceOpener;
 
   AutoMaskData(const AutoMaskData&) MOZ_DELETE;
   AutoMaskData& operator=(const AutoMaskData&) MOZ_DELETE;
 };
 
 }
 }
 
-#endif // GFX_AUTOMASKDATA_H_
\ No newline at end of file
+#endif // GFX_AUTOMASKDATA_H_
--- a/gfx/layers/basic/BasicCompositor.h
+++ b/gfx/layers/basic/BasicCompositor.h
@@ -107,17 +107,17 @@ public:
   }
   
   virtual void SetScreenRenderOffset(const ScreenPoint& aOffset) MOZ_OVERRIDE {
   }
 
   virtual void MakeCurrent(MakeCurrentFlags aFlags = 0) { }
 
   virtual void PrepareViewport(const gfx::IntSize& aSize,
-                               const gfxMatrix& aWorldTransform) MOZ_OVERRIDE { }
+                               const gfx::Matrix& aWorldTransform) MOZ_OVERRIDE { }
 
   virtual void NotifyLayersTransaction() MOZ_OVERRIDE { }
 
   virtual const char* Name() const { return "Basic"; }
 
   virtual nsIWidget* GetWidget() const MOZ_OVERRIDE { return mWidget; }
 
   gfx::DrawTarget *GetDrawTarget() { return mDrawTarget; }
--- a/gfx/layers/basic/BasicContainerLayer.cpp
+++ b/gfx/layers/basic/BasicContainerLayer.cpp
@@ -10,18 +10,16 @@
 #include "basic/BasicLayers.h"          // for BasicLayerManager
 #include "mozilla/gfx/BaseRect.h"       // for BaseRect
 #include "mozilla/mozalloc.h"           // for operator new
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsISupportsImpl.h"            // for Layer::AddRef, etc
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsRect.h"                     // for nsIntRect
-#include "gfx3DMatrix.h"                // for gfx3DMatrix
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "nsRegion.h"                   // for nsIntRegion
 
 using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace layers {
 
 BasicContainerLayer::~BasicContainerLayer()
@@ -76,40 +74,36 @@ BasicContainerLayer::ComputeEffectiveTra
     GetForceIsolatedGroup() ||
     (GetMixBlendMode() != gfxContext::OPERATOR_OVER && HasMultipleChildren()) ||
     (GetEffectiveOpacity() != 1.0 && (HasMultipleChildren() || hasSingleBlendingChild));
 }
 
 bool
 BasicContainerLayer::ChildrenPartitionVisibleRegion(const nsIntRect& aInRect)
 {
-  gfxMatrix transform;
-  gfx3DMatrix effectiveTransform;
-  gfx::To3DMatrix(GetEffectiveTransform(), effectiveTransform);
-  if (!effectiveTransform.CanDraw2D(&transform) ||
-      transform.HasNonIntegerTranslation())
+  Matrix transform;
+  if (!GetEffectiveTransform().CanDraw2D(&transform) ||
+      ThebesMatrix(transform).HasNonIntegerTranslation())
     return false;
 
-  nsIntPoint offset(int32_t(transform.x0), int32_t(transform.y0));
+  nsIntPoint offset(int32_t(transform._31), int32_t(transform._32));
   nsIntRect rect = aInRect.Intersect(GetEffectiveVisibleRegion().GetBounds() + offset);
   nsIntRegion covered;
 
   for (Layer* l = mFirstChild; l; l = l->GetNextSibling()) {
     if (ToData(l)->IsHidden())
       continue;
 
-    gfxMatrix childTransform;
-    gfx3DMatrix effectiveTransform;
-    gfx::To3DMatrix(l->GetEffectiveTransform(), effectiveTransform);
-    if (!effectiveTransform.CanDraw2D(&childTransform) ||
-        childTransform.HasNonIntegerTranslation() ||
+    Matrix childTransform;
+    if (!l->GetEffectiveTransform().CanDraw2D(&childTransform) ||
+        ThebesMatrix(childTransform).HasNonIntegerTranslation() ||
         l->GetEffectiveOpacity() != 1.0)
       return false;
     nsIntRegion childRegion = l->GetEffectiveVisibleRegion();
-    childRegion.MoveBy(int32_t(childTransform.x0), int32_t(childTransform.y0));
+    childRegion.MoveBy(int32_t(childTransform._31), int32_t(childTransform._32));
     childRegion.And(childRegion, rect);
     if (l->GetClipRect()) {
       childRegion.And(childRegion, *l->GetClipRect() + offset);
     }
     nsIntRegion intersection;
     intersection.And(covered, childRegion);
     if (!intersection.IsEmpty())
       return false;
--- a/gfx/layers/basic/BasicLayerManager.cpp
+++ b/gfx/layers/basic/BasicLayerManager.cpp
@@ -155,27 +155,25 @@ public:
       ClearOpaqueRect();
     }
   }
 
   // Gets the effective transform and returns true if it is a 2D
   // transform.
   bool Setup2DTransform()
   {
-    gfx3DMatrix effectiveTransform;
-    To3DMatrix(mLayer->GetEffectiveTransform(), effectiveTransform);
     // Will return an identity matrix for 3d transforms.
-    return effectiveTransform.CanDraw2D(&mTransform);
+    return mLayer->GetEffectiveTransform().CanDraw2D(&mTransform);
   }
 
   // Applies the effective transform if it's 2D. If it's a 3D transform then
   // it applies an identity.
   void Apply2DTransform()
   {
-    mTarget->SetMatrix(mTransform);
+    mTarget->SetMatrix(ThebesMatrix(mTransform));
   }
 
   // Set the opaque rect to match the bounds of the visible region.
   void AnnotateOpaqueRect()
   {
     const nsIntRegion& visibleRegion = mLayer->GetEffectiveVisibleRegion();
     const nsIntRect& bounds = visibleRegion.GetBounds();
 
@@ -227,17 +225,17 @@ public:
   }
 
   gfxContext* mTarget;
   gfxContextMatrixAutoSaveRestore mTargetMatrixSR;
   Layer* mLayer;
   LayerManager::DrawThebesLayerCallback mCallback;
   void* mCallbackData;
   ReadbackProcessor* mReadback;
-  gfxMatrix mTransform;
+  Matrix mTransform;
   bool mPushedOpaqueRect;
 };
 
 BasicLayerManager::BasicLayerManager(nsIWidget* aWidget) :
   mPhase(PHASE_NONE),
   mWidget(aWidget)
   , mDoubleBuffering(BufferMode::BUFFER_NONE), mUsingDefaultTarget(false)
   , mCachedSurfaceInUse(false)
@@ -349,22 +347,22 @@ BasicLayerManager::BeginTransactionWithT
 #endif
 
   NS_ASSERTION(!InTransaction(), "Nested transactions not allowed");
   mPhase = PHASE_CONSTRUCTION;
   mTarget = aTarget;
 }
 
 static void
-TransformIntRect(nsIntRect& aRect, const gfxMatrix& aMatrix,
+TransformIntRect(nsIntRect& aRect, const Matrix& aMatrix,
                  nsIntRect (*aRoundMethod)(const gfxRect&))
 {
-  gfxRect gr = gfxRect(aRect.x, aRect.y, aRect.width, aRect.height);
+  Rect gr = Rect(aRect.x, aRect.y, aRect.width, aRect.height);
   gr = aMatrix.TransformBounds(gr);
-  aRect = (*aRoundMethod)(gr);
+  aRect = (*aRoundMethod)(ThebesRect(gr));
 }
 
 /**
  * This function assumes that GetEffectiveTransform transforms
  * all layers to the same coordinate system (the "root coordinate system").
  * It can't be used as is by accelerated layers because of intermediate surfaces.
  * This must set the hidden flag to true or false on *all* layers in the subtree.
  * It also sets the operator for all layers to "OVER", and call
@@ -398,20 +396,18 @@ MarkLayersHidden(Layer* aLayer, const ns
 
   {
     const nsIntRect* clipRect = aLayer->GetEffectiveClipRect();
     if (clipRect) {
       nsIntRect cr = *clipRect;
       // clipRect is in the container's coordinate system. Get it into the
       // global coordinate system.
       if (aLayer->GetParent()) {
-        gfxMatrix tr;
-        gfx3DMatrix effectiveTransform;
-        gfx::To3DMatrix(aLayer->GetParent()->GetEffectiveTransform(), effectiveTransform);
-        if (effectiveTransform.CanDraw2D(&tr)) {
+        Matrix tr;
+        if (aLayer->GetParent()->GetEffectiveTransform().CanDraw2D(&tr)) {
           // Clip rect is applied after aLayer's transform, i.e., in the coordinate
           // system of aLayer's parent.
           TransformIntRect(cr, tr, ToInsideIntRect);
         } else {
           cr.SetRect(0, 0, 0, 0);
         }
       }
       newClipRect.IntersectRect(newClipRect, cr);
@@ -419,20 +415,18 @@ MarkLayersHidden(Layer* aLayer, const ns
   }
 
   BasicImplData* data = ToData(aLayer);
   data->SetOperator(gfxContext::OPERATOR_OVER);
   data->SetClipToVisibleRegion(false);
   data->SetDrawAtomically(false);
 
   if (!aLayer->AsContainerLayer()) {
-    gfxMatrix transform;
-    gfx3DMatrix effectiveTransform;
-    gfx::To3DMatrix(aLayer->GetEffectiveTransform(), effectiveTransform);
-    if (!effectiveTransform.CanDraw2D(&transform)) {
+    Matrix transform;
+    if (!aLayer->GetEffectiveTransform().CanDraw2D(&transform)) {
       data->SetHidden(false);
       return;
     }
 
     nsIntRegion region = aLayer->GetEffectiveVisibleRegion();
     nsIntRect r = region.GetBounds();
     TransformIntRect(r, transform, ToOutsideIntRect);
     r.IntersectRect(r, aDirtyRect);
@@ -482,23 +476,21 @@ ApplyDoubleBuffering(Layer* aLayer, cons
 
   {
     const nsIntRect* clipRect = aLayer->GetEffectiveClipRect();
     if (clipRect) {
       nsIntRect cr = *clipRect;
       // clipRect is in the container's coordinate system. Get it into the
       // global coordinate system.
       if (aLayer->GetParent()) {
-        gfxMatrix tr;
-        gfx3DMatrix effectiveTransform;
-        gfx::To3DMatrix(aLayer->GetParent()->GetEffectiveTransform(), effectiveTransform);
-        if (effectiveTransform.CanDraw2D(&tr)) {
-          NS_ASSERTION(!tr.HasNonIntegerTranslation(),
+        Matrix tr;
+        if (aLayer->GetParent()->GetEffectiveTransform().CanDraw2D(&tr)) {
+          NS_ASSERTION(!ThebesMatrix(tr).HasNonIntegerTranslation(),
                        "Parent can only have an integer translation");
-          cr += nsIntPoint(int32_t(tr.x0), int32_t(tr.y0));
+          cr += nsIntPoint(int32_t(tr._31), int32_t(tr._32));
         } else {
           NS_ERROR("Parent can only have an integer translation");
         }
       }
       newVisibleRect.IntersectRect(newVisibleRect, cr);
     }
   }
 
--- a/gfx/layers/basic/BasicLayersImpl.cpp
+++ b/gfx/layers/basic/BasicLayersImpl.cpp
@@ -2,39 +2,38 @@
  * 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/. */
 
 #include "BasicLayersImpl.h"
 #include <new>                          // for operator new
 #include "Layers.h"                     // for Layer, etc
 #include "basic/BasicImplData.h"        // for BasicImplData
-#include "gfx3DMatrix.h"                // for gfx3DMatrix
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/DebugOnly.h"          // for DebugOnly
 #include "mozilla/layers/CompositorTypes.h"
 #include "mozilla/layers/ISurfaceAllocator.h"
 #include "AutoMaskData.h"
 
 using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace layers {
 
 void
-AutoMaskData::Construct(const gfxMatrix& aTransform,
+AutoMaskData::Construct(const gfx::Matrix& aTransform,
                         gfxASurface* aSurface)
 {
   MOZ_ASSERT(!IsConstructed());
   mTransform = aTransform;
   mSurface = aSurface;
 }
 
 void
-AutoMaskData::Construct(const gfxMatrix& aTransform,
+AutoMaskData::Construct(const gfx::Matrix& aTransform,
                         const SurfaceDescriptor& aSurface)
 {
   MOZ_ASSERT(!IsConstructed());
   mTransform = aTransform;
   mSurfaceOpener.construct(OPEN_READ_ONLY, aSurface);
 }
 
 gfxASurface*
@@ -42,17 +41,17 @@ AutoMaskData::GetSurface()
 {
   MOZ_ASSERT(IsConstructed());
   if (mSurface) {
     return mSurface.get();
   }
   return mSurfaceOpener.ref().Get();
 }
 
-const gfxMatrix&
+const gfx::Matrix&
 AutoMaskData::GetTransform()
 {
   MOZ_ASSERT(IsConstructed());
   return mTransform;
 }
 
 bool
 AutoMaskData::IsConstructed()
@@ -65,19 +64,18 @@ bool
 GetMaskData(Layer* aMaskLayer, AutoMaskData* aMaskData)
 {
   if (aMaskLayer) {
     nsRefPtr<gfxASurface> surface;
     SurfaceDescriptor descriptor;
     if (static_cast<BasicImplData*>(aMaskLayer->ImplData())
         ->GetAsSurface(getter_AddRefs(surface), &descriptor) &&
         (surface || IsSurfaceDescriptorValid(descriptor))) {
-      gfxMatrix transform;
-      gfx3DMatrix effectiveTransform;
-      gfx::To3DMatrix(aMaskLayer->GetEffectiveTransform(), effectiveTransform);
+      Matrix transform;
+      Matrix4x4 effectiveTransform = aMaskLayer->GetEffectiveTransform();
       DebugOnly<bool> maskIs2D = effectiveTransform.CanDraw2D(&transform);
       NS_ASSERTION(maskIs2D, "How did we end up with a 3D transform here?!");
       if (surface) {
         aMaskData->Construct(transform, surface);
       } else {
         aMaskData->Construct(transform, descriptor);
       }
       return true;
@@ -91,17 +89,17 @@ PaintWithMask(gfxContext* aContext, floa
 {
   AutoMaskData mask;
   if (GetMaskData(aMaskLayer, &mask)) {
     if (aOpacity < 1.0) {
       aContext->PushGroup(gfxContentType::COLOR_ALPHA);
       aContext->Paint(aOpacity);
       aContext->PopGroupToSource();
     }
-    aContext->SetMatrix(mask.GetTransform());
+    aContext->SetMatrix(ThebesMatrix(mask.GetTransform()));
     aContext->Mask(mask.GetSurface());
     return;
   }
 
   // if there is no mask, just paint normally
   aContext->Paint(aOpacity);
 }
 
@@ -109,22 +107,22 @@ void
 FillWithMask(gfxContext* aContext, float aOpacity, Layer* aMaskLayer)
 {
   AutoMaskData mask;
   if (GetMaskData(aMaskLayer, &mask)) {
     if (aOpacity < 1.0) {
       aContext->PushGroup(gfxContentType::COLOR_ALPHA);
       aContext->FillWithOpacity(aOpacity);
       aContext->PopGroupToSource();
-      aContext->SetMatrix(mask.GetTransform());
+      aContext->SetMatrix(ThebesMatrix(mask.GetTransform()));
       aContext->Mask(mask.GetSurface());
     } else {
       aContext->Save();
       aContext->Clip();
-      aContext->SetMatrix(mask.GetTransform());
+      aContext->SetMatrix(ThebesMatrix(mask.GetTransform()));
       aContext->Mask(mask.GetSurface());
       aContext->NewPath();
       aContext->Restore();
     }
     return;
   }
 
   // if there is no mask, just fill normally
--- a/gfx/layers/basic/BasicLayersImpl.h
+++ b/gfx/layers/basic/BasicLayersImpl.h
@@ -6,17 +6,16 @@
 #ifndef GFX_BASICLAYERSIMPL_H
 #define GFX_BASICLAYERSIMPL_H
 
 #include "BasicImplData.h"              // for BasicImplData
 #include "BasicLayers.h"                // for BasicLayerManager
 #include "ReadbackLayer.h"              // for ReadbackLayer
 #include "gfxASurface.h"                // for gfxASurface
 #include "gfxContext.h"                 // for gfxContext, etc
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "ipc/AutoOpenSurface.h"        // for AutoOpenSurface
 #include "mozilla/Attributes.h"         // for MOZ_DELETE, MOZ_STACK_CLASS
 #include "mozilla/Maybe.h"              // for Maybe
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsDebug.h"                    // for NS_ASSERTION
 #include "nsISupportsImpl.h"            // for gfxContext::Release, etc
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTraceRefcnt.h"              // for MOZ_COUNT_CTOR, etc
--- a/gfx/layers/basic/BasicThebesLayer.cpp
+++ b/gfx/layers/basic/BasicThebesLayer.cpp
@@ -24,18 +24,16 @@
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsISupportsImpl.h"            // for gfxContext::Release, etc
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsRect.h"                     // for nsIntRect
 #include "nsTArray.h"                   // for nsTArray, nsTArray_Impl
 #include "AutoMaskData.h"
 #include "gfx2DGlue.h"
 
-struct gfxMatrix;
-
 using namespace mozilla::gfx;
 
 namespace mozilla {
 namespace layers {
 
 static nsIntRegion
 IntersectWithClip(const nsIntRegion& aRegion, gfxContext* aContext)
 {
@@ -121,40 +119,40 @@ BasicThebesLayer::PaintThebes(gfxContext
 
   gfxRect clipExtents;
   clipExtents = aContext->GetClipExtents();
 
   // Pull out the mask surface and transform here, because the mask
   // is internal to basic layers
   AutoMaskData mask;
   gfxASurface* maskSurface = nullptr;
-  const gfxMatrix* maskTransform = nullptr;
+  Matrix maskTransform;
   if (GetMaskData(aMaskLayer, &mask)) {
     maskSurface = mask.GetSurface();
-    maskTransform = &mask.GetTransform();
+    maskTransform = mask.GetTransform();
   }
 
   if (!IsHidden() && !clipExtents.IsEmpty()) {
     mContentClient->DrawTo(this, aContext->GetDrawTarget(), opacity,
                            CompositionOpForOp(GetOperator()),
-                           maskSurface, maskTransform);
+                           maskSurface, &maskTransform);
   }
 
   for (uint32_t i = 0; i < readbackUpdates.Length(); ++i) {
     ReadbackProcessor::Update& update = readbackUpdates[i];
     nsIntPoint offset = update.mLayer->GetBackgroundLayerOffset();
     nsRefPtr<gfxContext> ctx =
       update.mLayer->GetSink()->BeginUpdate(update.mUpdateRect + offset,
                                             update.mSequenceCounter);
     if (ctx) {
       NS_ASSERTION(opacity == 1.0, "Should only read back opaque layers");
       ctx->Translate(gfxPoint(offset.x, offset.y));
       mContentClient->DrawTo(this, ctx->GetDrawTarget(), 1.0,
                              CompositionOpForOp(ctx->CurrentOperator()),
-                             maskSurface, maskTransform);
+                             maskSurface, &maskTransform);
       update.mLayer->GetSink()->EndUpdate(ctx, update.mUpdateRect + offset);
     }
   }
 }
 
 void
 BasicThebesLayer::Validate(LayerManager::DrawThebesLayerCallback aCallback,
                            void* aCallbackData)
--- a/gfx/layers/basic/BasicThebesLayer.h
+++ b/gfx/layers/basic/BasicThebesLayer.h
@@ -5,17 +5,16 @@
 
 #ifndef GFX_BASICTHEBESLAYER_H
 #define GFX_BASICTHEBESLAYER_H
 
 #include "Layers.h"                     // for ThebesLayer, LayerManager, etc
 #include "RotatedBuffer.h"              // for RotatedContentBuffer, etc
 #include "BasicImplData.h"              // for BasicImplData
 #include "BasicLayers.h"                // for BasicLayerManager
-#include "gfx3DMatrix.h"                // for gfx3DMatrix
 #include "gfxPoint.h"                   // for gfxPoint
 #include "mozilla/RefPtr.h"             // for RefPtr
 #include "mozilla/gfx/BasePoint.h"      // for BasePoint
 #include "mozilla/layers/ContentClient.h"  // for ContentClientBasic
 #include "mozilla/mozalloc.h"           // for operator delete
 #include "nsDebug.h"                    // for NS_ASSERTION
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTraceRefcnt.h"              // for MOZ_COUNT_CTOR, etc
--- a/gfx/layers/client/ClientContainerLayer.h
+++ b/gfx/layers/client/ClientContainerLayer.h
@@ -4,18 +4,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef GFX_CLIENTCONTAINERLAYER_H
 #define GFX_CLIENTCONTAINERLAYER_H
 
 #include <stdint.h>                     // for uint32_t
 #include "ClientLayerManager.h"         // for ClientLayerManager, etc
 #include "Layers.h"                     // for Layer, ContainerLayer, etc
-#include "gfx3DMatrix.h"                // for gfx3DMatrix
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "nsDebug.h"                    // for NS_ASSERTION
 #include "nsISupportsUtils.h"           // for NS_ADDREF, NS_RELEASE
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTArray.h"                   // for nsAutoTArray
 #include "nsTraceRefcnt.h"              // for MOZ_COUNT_CTOR, etc
 
 namespace mozilla {
@@ -50,22 +48,20 @@ public:
     }
     
     // Setup mSupportsComponentAlphaChildren in the same way 
     // that ContainerLayerComposite will do.
     if (UseIntermediateSurface()) {
       if (GetEffectiveVisibleRegion().GetNumRects() != 1 ||
           !(GetContentFlags() & Layer::CONTENT_OPAQUE))
       {
-        gfx3DMatrix transform3D;
-        gfx::To3DMatrix(GetEffectiveTransform(), transform3D);
-        gfxMatrix transform;
+        gfx::Matrix transform;
         if (HasOpaqueAncestorLayer(this) &&
-            transform3D.Is2D(&transform) && 
-            !transform.HasNonIntegerTranslation()) {
+            GetEffectiveTransform().Is2D(&transform) &&
+            !gfx::ThebesMatrix(transform).HasNonIntegerTranslation()) {
           SetSupportsComponentAlphaChildren(
             gfxPlatform::ComponentAlphaEnabled());
         }
       }
     } else {
       SetSupportsComponentAlphaChildren(
         (GetContentFlags() & Layer::CONTENT_OPAQUE) ||
         (GetParent() && GetParent()->SupportsComponentAlphaChildren()));
@@ -112,17 +108,17 @@ public:
   {
     NS_ASSERTION(ClientManager()->InConstruction(),
                  "Can only set properties in construction phase");
     ClientManager()->AsShadowForwarder()->RepositionChild(ClientManager()->Hold(this),
                                                           ClientManager()->Hold(aChild),
                                                           aAfter ? ClientManager()->Hold(aAfter) : nullptr);
     ContainerLayer::RepositionChild(aChild, aAfter);
   }
-  
+
   virtual Layer* AsLayer() { return this; }
   virtual ShadowableLayer* AsShadowableLayer() { return this; }
 
   virtual void ComputeEffectiveTransforms(const gfx::Matrix4x4& aTransformToSurface)
   {
     DefaultComputeEffectiveTransforms(aTransformToSurface);
   }
 
--- a/gfx/layers/client/ContentClient.h
+++ b/gfx/layers/client/ContentClient.h
@@ -23,17 +23,16 @@
 #include "mozilla/mozalloc.h"           // for operator delete
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsRect.h"                     // for nsIntRect
 #include "nsRegion.h"                   // for nsIntRegion
 #include "nsTArray.h"                   // for nsTArray
 
 class gfxContext;
-struct gfxMatrix;
 class gfxASurface;
 
 namespace mozilla {
 namespace gfx {
 class DrawTarget;
 }
 
 namespace layers {
@@ -153,17 +152,17 @@ public:
     BorrowDrawTarget::ReturnDrawTarget(aReturned);
   }
 
   void DrawTo(ThebesLayer* aLayer,
               gfx::DrawTarget* aTarget,
               float aOpacity,
               gfx::CompositionOp aOp,
               gfxASurface* aMask,
-              const gfxMatrix* aMaskTransform)
+              const gfx::Matrix* aMaskTransform)
   {
     RotatedContentBuffer::DrawTo(aLayer, aTarget, aOpacity, aOp,
                                  aMask, aMaskTransform);
   }
 
   virtual void CreateBuffer(ContentType aType, const nsIntRect& aRect, uint32_t aFlags,
                             RefPtr<gfx::DrawTarget>* aBlackDT, RefPtr<gfx::DrawTarget>* aWhiteDT) MOZ_OVERRIDE;
 
--- a/gfx/layers/composite/AsyncCompositionManager.cpp
+++ b/gfx/layers/composite/AsyncCompositionManager.cpp
@@ -6,17 +6,16 @@
 
 #include "mozilla/layers/AsyncCompositionManager.h"
 #include <stdint.h>                     // for uint32_t
 #include "AnimationCommon.h"            // for ComputedTimingFunction
 #include "CompositorParent.h"           // for CompositorParent, etc
 #include "FrameMetrics.h"               // for FrameMetrics
 #include "LayerManagerComposite.h"      // for LayerManagerComposite, etc
 #include "Layers.h"                     // for Layer, ContainerLayer, etc
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "gfxPoint.h"                   // for gfxPoint, gfxSize
 #include "gfxPoint3D.h"                 // for gfxPoint3D
 #include "mozilla/WidgetUtils.h"        // for ComputeTransformForRotation
 #include "mozilla/gfx/BaseRect.h"       // for BaseRect
 #include "mozilla/gfx/Point.h"          // for RoundedToInt, PointTyped
 #include "mozilla/gfx/Rect.h"           // for RoundedToInt, RectTyped
 #include "mozilla/gfx/ScaleFactor.h"    // for ScaleFactor
 #include "mozilla/layers/AsyncPanZoomController.h"
@@ -167,25 +166,25 @@ TranslateShadowLayer2D(Layer* aLayer,
     transformedClipRect.MoveBy(aTranslation.x, aTranslation.y);
     layerComposite->SetShadowClipRect(&transformedClipRect);
   }
 }
 
 static bool
 AccumulateLayerTransforms2D(Layer* aLayer,
                             Layer* aAncestor,
-                            gfxMatrix& aMatrix)
+                            Matrix& aMatrix)
 {
   // Accumulate the transforms between this layer and the subtree root layer.
   for (Layer* l = aLayer; l && l != aAncestor; l = l->GetParent()) {
     Matrix l2D;
     if (!GetBaseTransform2D(l, &l2D)) {
       return false;
     }
-    aMatrix.Multiply(ThebesMatrix(l2D));
+    aMatrix *= l2D;
   }
 
   return true;
 }
 
 static LayerPoint
 GetLayerFixedMarginsOffset(Layer* aLayer,
                            const LayerMargin& aFixedLayerMargins)
@@ -226,52 +225,52 @@ IntervalOverlap(gfxFloat aTranslation, g
   } else {
     return std::min(0.0, std::max(aMin, aTranslation) - std::min(aMax, 0.0));
   }
 }
 
 void
 AsyncCompositionManager::AlignFixedAndStickyLayers(Layer* aLayer,
                                                    Layer* aTransformedSubtreeRoot,
-                                                   const gfx3DMatrix& aPreviousTransformForRoot,
+                                                   const Matrix4x4& aPreviousTransformForRoot,
                                                    const LayerMargin& aFixedLayerMargins)
 {
   bool isRootFixed = aLayer->GetIsFixedPosition() &&
     !aLayer->GetParent()->GetIsFixedPosition();
   bool isStickyForSubtree = aLayer->GetIsStickyPosition() &&
     aTransformedSubtreeRoot->AsContainerLayer() &&
     aLayer->GetStickyScrollContainerId() ==
       aTransformedSubtreeRoot->AsContainerLayer()->GetFrameMetrics().mScrollId;
   if (aLayer != aTransformedSubtreeRoot && (isRootFixed || isStickyForSubtree)) {
     // Insert a translation so that the position of the anchor point is the same
     // before and after the change to the transform of aTransformedSubtreeRoot.
     // This currently only works for fixed layers with 2D transforms.
 
     // Accumulate the transforms between this layer and the subtree root layer.
-    gfxMatrix ancestorTransform;
+    Matrix ancestorTransform;
     if (!AccumulateLayerTransforms2D(aLayer->GetParent(), aTransformedSubtreeRoot,
                                      ancestorTransform)) {
       return;
     }
 
-    gfxMatrix oldRootTransform;
+    Matrix oldRootTransform;
     Matrix newRootTransform;
     if (!aPreviousTransformForRoot.Is2D(&oldRootTransform) ||
         !aTransformedSubtreeRoot->GetLocalTransform().Is2D(&newRootTransform)) {
       return;
     }
 
     // Calculate the cumulative transforms between the subtree root with the
     // old transform and the current transform.
-    gfxMatrix oldCumulativeTransform = ancestorTransform * oldRootTransform;
-    gfxMatrix newCumulativeTransform = ancestorTransform * ThebesMatrix(newRootTransform);
+    Matrix oldCumulativeTransform = ancestorTransform * oldRootTransform;
+    Matrix newCumulativeTransform = ancestorTransform * newRootTransform;
     if (newCumulativeTransform.IsSingular()) {
       return;
     }
-    gfxMatrix newCumulativeTransformInverse = newCumulativeTransform;
+    Matrix newCumulativeTransformInverse = newCumulativeTransform;
     newCumulativeTransformInverse.Invert();
 
     // Now work out the translation necessary to make sure the layer doesn't
     // move given the new sub-tree root transform.
     Matrix layerTransform;
     if (!GetBaseTransform2D(aLayer, &layerTransform)) {
       return;
     }
@@ -295,20 +294,19 @@ AsyncCompositionManager::AlignFixedAndSt
 
     // Transforming the locallyTransformedAnchor by oldCumulativeTransform
     // returns the layer's anchor point relative to the parent of
     // aTransformedSubtreeRoot, before the new transform was applied.
     // Then, applying newCumulativeTransformInverse maps that point relative
     // to the layer's parent, which is the same coordinate space as
     // locallyTransformedAnchor again, allowing us to subtract them and find
     // out the offset necessary to make sure the layer stays stationary.
-    gfxPoint oldAnchorPositionInNewSpace =
-      newCumulativeTransformInverse.Transform(
-        oldCumulativeTransform.Transform(ThebesPoint(locallyTransformedOffsetAnchor)));
-    gfxPoint translation = oldAnchorPositionInNewSpace - ThebesPoint(locallyTransformedAnchor);
+    Point oldAnchorPositionInNewSpace =
+      newCumulativeTransformInverse * (oldCumulativeTransform * locallyTransformedOffsetAnchor);
+    Point translation = oldAnchorPositionInNewSpace - locallyTransformedAnchor;
 
     if (aLayer->GetIsStickyPosition()) {
       // For sticky positioned layers, the difference between the two rectangles
       // defines a pair of translation intervals in each dimension through which
       // the layer should not move relative to the scroll container. To
       // accomplish this, we limit each dimension of the |translation| to that
       // part of it which overlaps those intervals.
       const LayerRect& stickyOuter = aLayer->GetStickyScrollRangeOuter();
@@ -316,32 +314,30 @@ AsyncCompositionManager::AlignFixedAndSt
 
       translation.y = IntervalOverlap(translation.y, stickyOuter.y, stickyOuter.YMost()) -
                       IntervalOverlap(translation.y, stickyInner.y, stickyInner.YMost());
       translation.x = IntervalOverlap(translation.x, stickyOuter.x, stickyOuter.XMost()) -
                       IntervalOverlap(translation.x, stickyInner.x, stickyInner.XMost());
     }
 
     // Finally, apply the 2D translation to the layer transform.
-    TranslateShadowLayer2D(aLayer, translation);
+    TranslateShadowLayer2D(aLayer, ThebesPoint(translation));
 
     // The transform has now been applied, so there's no need to iterate over
     // child layers.
     return;
   }
 
   // Fixed layers are relative to their nearest scrollable layer, so when we
   // encounter a scrollable layer, reset the transform to that layer and remove
   // the fixed margins.
   if (aLayer->AsContainerLayer() &&
       aLayer->AsContainerLayer()->GetFrameMetrics().IsScrollable() &&
       aLayer != aTransformedSubtreeRoot) {
-    gfx3DMatrix matrix;
-    To3DMatrix(aLayer->GetTransform(), matrix);
-    AlignFixedAndStickyLayers(aLayer, aLayer, matrix, LayerMargin(0, 0, 0, 0));
+    AlignFixedAndStickyLayers(aLayer, aLayer, aLayer->GetTransform(), LayerMargin(0, 0, 0, 0));
     return;
   }
 
   for (Layer* child = aLayer->GetFirstChild();
        child; child = child->GetNextSibling()) {
     AlignFixedAndStickyLayers(child, aTransformedSubtreeRoot,
                               aPreviousTransformForRoot, aFixedLayerMargins);
   }
@@ -487,18 +483,17 @@ AsyncCompositionManager::ApplyAsyncConte
 
   ContainerLayer* container = aLayer->AsContainerLayer();
   if (!container) {
     return appliedTransform;
   }
 
   if (AsyncPanZoomController* controller = container->GetAsyncPanZoomController()) {
     LayerComposite* layerComposite = aLayer->AsLayerComposite();
-    gfx3DMatrix oldTransform;
-    To3DMatrix(aLayer->GetTransform(), oldTransform);
+    Matrix4x4 oldTransform = aLayer->GetTransform();
 
     ViewTransform treeTransform;
     ScreenPoint scrollOffset;
     *aWantNextFrame |=
       controller->SampleContentTransformForFrame(aCurrentFrame,
                                                  &treeTransform,
                                                  scrollOffset);
 
@@ -636,17 +631,17 @@ AsyncCompositionManager::TransformScroll
   LayerComposite* layerComposite = aLayer->AsLayerComposite();
   ContainerLayer* container = aLayer->AsContainerLayer();
 
   const FrameMetrics& metrics = container->GetFrameMetrics();
   // We must apply the resolution scale before a pan/zoom transform, so we call
   // GetTransform here.
   gfx3DMatrix currentTransform;
   To3DMatrix(aLayer->GetTransform(), currentTransform);
-  gfx3DMatrix oldTransform = currentTransform;
+  Matrix4x4 oldTransform = aLayer->GetTransform();
 
   gfx3DMatrix treeTransform;
 
   CSSToLayerScale geckoZoom = metrics.LayersPixelsPerCSSPixel();
 
   LayerIntPoint scrollOffsetLayerPixels = RoundedToInt(metrics.mScrollOffset * geckoZoom);
 
   if (mIsFirstPaint) {
@@ -741,17 +736,19 @@ AsyncCompositionManager::TransformScroll
       (userScroll.x + metrics.mCompositionBounds.width);
   }
   if (userScroll.y < contentScreenRect.y) {
     overscrollTranslation.y = contentScreenRect.y - userScroll.y;
   } else if (userScroll.y + metrics.mCompositionBounds.height > contentScreenRect.YMost()) {
     overscrollTranslation.y = contentScreenRect.YMost() -
       (userScroll.y + metrics.mCompositionBounds.height);
   }
-  oldTransform.Translate(overscrollTranslation);
+  oldTransform.Translate(overscrollTranslation.x,
+                         overscrollTranslation.y,
+                         overscrollTranslation.z);
 
   gfx::Size underZoomScale(1.0f, 1.0f);
   if (mContentRect.width * userZoom.scale < metrics.mCompositionBounds.width) {
     underZoomScale.width = (mContentRect.width * userZoom.scale) /
       metrics.mCompositionBounds.width;
   }
   if (mContentRect.height * userZoom.scale < metrics.mCompositionBounds.height) {
     underZoomScale.height = (mContentRect.height * userZoom.scale) /
--- a/gfx/layers/composite/AsyncCompositionManager.h
+++ b/gfx/layers/composite/AsyncCompositionManager.h
@@ -158,17 +158,17 @@ private:
    * as it was when aTransformedSubtreeRoot's GetLocalTransform() was
    * aPreviousTransformForRoot. For sticky position layers, the translation is
    * further intersected with the layer's sticky scroll ranges.
    * This function will also adjust layers so that the given content document
    * fixed position margins will be respected during asynchronous panning and
    * zooming.
    */
   void AlignFixedAndStickyLayers(Layer* aLayer, Layer* aTransformedSubtreeRoot,
-                                 const gfx3DMatrix& aPreviousTransformForRoot,
+                                 const gfx::Matrix4x4& aPreviousTransformForRoot,
                                  const LayerMargin& aFixedLayerMargins);
 
   /**
    * DRAWING PHASE ONLY
    *
    * For reach RefLayer in our layer tree, look up its referent and connect it
    * to the layer tree, if found.
    */
--- a/gfx/layers/composite/CanvasLayerComposite.cpp
+++ b/gfx/layers/composite/CanvasLayerComposite.cpp
@@ -17,16 +17,17 @@
 #include "nsAString.h"
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsPoint.h"                    // for nsIntPoint
 #include "nsString.h"                   // for nsAutoCString
 #include "nsTraceRefcnt.h"              // for MOZ_COUNT_CTOR, etc
 
 using namespace mozilla;
 using namespace mozilla::layers;
+using namespace mozilla::gfx;
 
 CanvasLayerComposite::CanvasLayerComposite(LayerManagerComposite* aManager)
   : CanvasLayer(aManager, nullptr)
   , LayerComposite(aManager)
   , mImageHost(nullptr)
 {
   MOZ_COUNT_CTOR(CanvasLayerComposite);
   mImplData = static_cast<LayerComposite*>(this);
@@ -75,21 +76,19 @@ CanvasLayerComposite::RenderLayer(const 
   }
 #endif
 
   GraphicsFilter filter = mFilter;
 #ifdef ANDROID
   // Bug 691354
   // Using the LINEAR filter we get unexplained artifacts.
   // Use NEAREST when no scaling is required.
-  gfxMatrix matrix;
-  gfx3DMatrix effectiveTransform;
-  gfx::To3DMatrix(GetEffectiveTransform(), effectiveTransform);
-  bool is2D = effectiveTransform.Is2D(&matrix);
-  if (is2D && !matrix.HasNonTranslationOrFlip()) {
+  Matrix matrix;
+  bool is2D = GetEffectiveTransform().Is2D(&matrix);
+  if (is2D && !ThebesMatrix(matrix).HasNonTranslationOrFlip()) {
     filter = GraphicsFilter::FILTER_NEAREST;
   }
 #endif
 
   EffectChain effectChain(this);
 
   LayerManagerComposite::AutoAddMaskEffect autoMaskEffect(mMaskLayer, effectChain);
   gfx::Rect clipRect(aClipRect.x, aClipRect.y, aClipRect.width, aClipRect.height);
--- a/gfx/layers/composite/ContainerLayerComposite.cpp
+++ b/gfx/layers/composite/ContainerLayerComposite.cpp
@@ -5,17 +5,16 @@
 
 #include "ContainerLayerComposite.h"
 #include <algorithm>                    // for min
 #include "FrameMetrics.h"               // for FrameMetrics
 #include "Units.h"                      // for LayerRect, LayerPixel, etc
 #include "gfx2DGlue.h"                  // for ToMatrix4x4
 #include "gfx3DMatrix.h"                // for gfx3DMatrix
 #include "gfxImageSurface.h"            // for gfxImageSurface
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "gfxPlatform.h"                // for gfxPlatform
 #include "gfxUtils.h"                   // for gfxUtils, etc
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/RefPtr.h"             // for RefPtr
 #include "mozilla/gfx/BaseRect.h"       // for BaseRect
 #include "mozilla/gfx/Matrix.h"         // for Matrix4x4
 #include "mozilla/gfx/Point.h"          // for Point, IntPoint
 #include "mozilla/gfx/Rect.h"           // for IntRect, Rect
@@ -237,28 +236,27 @@ ContainerRender(ContainerT* aContainer,
     surfaceRect.height = std::min(maxTextureSize, surfaceRect.height);
     if (aContainer->GetEffectiveVisibleRegion().GetNumRects() == 1 &&
         (aContainer->GetContentFlags() & Layer::CONTENT_OPAQUE))
     {
       // don't need a background, we're going to paint all opaque stuff
       aContainer->mSupportsComponentAlphaChildren = true;
       mode = INIT_MODE_NONE;
     } else {
-      gfx3DMatrix transform3D;
-      gfx::To3DMatrix(aContainer->GetEffectiveTransform(), transform3D);
-      gfxMatrix transform;
+      const gfx::Matrix4x4& transform3D = aContainer->GetEffectiveTransform();
+      gfx::Matrix transform;
       // If we have an opaque ancestor layer, then we can be sure that
       // all the pixels we draw into are either opaque already or will be
       // covered by something opaque. Otherwise copying up the background is
       // not safe.
       if (HasOpaqueAncestorLayer(aContainer) &&
-          transform3D.Is2D(&transform) && !transform.HasNonIntegerTranslation()) {
+          transform3D.Is2D(&transform) && !ThebesMatrix(transform).HasNonIntegerTranslation()) {
         surfaceCopyNeeded = gfxPlatform::ComponentAlphaEnabled();
-        sourcePoint.x += transform.x0;
-        sourcePoint.y += transform.y0;
+        sourcePoint.x += transform._31;
+        sourcePoint.y += transform._32;
         aContainer->mSupportsComponentAlphaChildren
           = gfxPlatform::ComponentAlphaEnabled();
       }
     }
 
     sourcePoint -= compositor->GetCurrentRenderTarget()->GetOrigin();
     if (surfaceCopyNeeded) {
       surface = compositor->CreateRenderTargetFromSource(surfaceRect, previousTarget, sourcePoint);
--- a/gfx/layers/composite/ThebesLayerComposite.cpp
+++ b/gfx/layers/composite/ThebesLayerComposite.cpp
@@ -3,17 +3,16 @@
  * 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/. */
 
 #include "ThebesLayerComposite.h"
 #include "CompositableHost.h"           // for TiledLayerProperties, etc
 #include "FrameMetrics.h"               // for FrameMetrics
 #include "Units.h"                      // for CSSRect, LayerPixel, etc
 #include "gfx2DGlue.h"                  // for ToMatrix4x4
-#include "gfx3DMatrix.h"                // for gfx3DMatrix
 #include "gfxUtils.h"                   // for gfxUtils, etc
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/gfx/Matrix.h"         // for Matrix4x4
 #include "mozilla/gfx/Point.h"          // for Point
 #include "mozilla/gfx/Rect.h"           // for RoundedToInt, Rect
 #include "mozilla/gfx/Types.h"          // for Filter::Filter::LINEAR
 #include "mozilla/layers/Compositor.h"  // for Compositor
 #include "mozilla/layers/ContentHost.h"  // for ContentHost
--- a/gfx/layers/d3d10/ContainerLayerD3D10.cpp
+++ b/gfx/layers/d3d10/ContainerLayerD3D10.cpp
@@ -3,16 +3,18 @@
  * 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/. */
 
 #include "ContainerLayerD3D10.h"
 
 #include "ThebesLayerD3D10.h"
 #include "ReadbackProcessor.h"
 
+using namespace mozilla::gfx;
+
 namespace mozilla {
 namespace layers {
 
 ContainerLayerD3D10::ContainerLayerD3D10(LayerManagerD3D10 *aManager)
   : ContainerLayer(aManager, nullptr)
   , LayerD3D10(aManager)
 {
   mImplData = static_cast<LayerD3D10*>(this);
@@ -101,33 +103,32 @@ ContainerLayerD3D10::RenderLayer()
     NS_ASSERTION(SUCCEEDED(hr), "Failed to create render target view for ContainerLayerD3D10!");
 
     effect()->GetVariableByName("vRenderTargetOffset")->
       GetRawValue(previousRenderTargetOffset, 0, 8);
 
     previousViewportSize = mD3DManager->GetViewport();
 
     if (mVisibleRegion.GetNumRects() != 1 || !(GetContentFlags() & CONTENT_OPAQUE)) {
-      gfx3DMatrix transform3D;
-      gfx::To3DMatrix(GetEffectiveTransform(), transform3D);
-      gfxMatrix transform;
+      Matrix4x4 transform3D = GetEffectiveTransform();
+      Matrix transform;
       // If we have an opaque ancestor layer, then we can be sure that
       // all the pixels we draw into are either opaque already or will be
       // covered by something opaque. Otherwise copying up the background is
       // not safe.
       if (mSupportsComponentAlphaChildren) {
         bool is2d = transform3D.Is2D(&transform);
         NS_ASSERTION(is2d, "Transform should be 2d when mSupportsComponentAlphaChildren.");
 
         // Copy background up from below. This applies any 2D transform that is
         // applied to use relative to our parent, and compensates for the offset
         // that was applied on our parent's rendering.
         D3D10_BOX srcBox;
-        srcBox.left = std::max<int32_t>(visibleRect.x + int32_t(transform.x0) - int32_t(previousRenderTargetOffset[0]), 0);
-        srcBox.top = std::max<int32_t>(visibleRect.y + int32_t(transform.y0) - int32_t(previousRenderTargetOffset[1]), 0);
+        srcBox.left = std::max<int32_t>(visibleRect.x + int32_t(transform._31) - int32_t(previousRenderTargetOffset[0]), 0);
+        srcBox.top = std::max<int32_t>(visibleRect.y + int32_t(transform._32) - int32_t(previousRenderTargetOffset[1]), 0);
         srcBox.right = std::min<int32_t>(srcBox.left + visibleRect.width, previousViewportSize.width);
         srcBox.bottom = std::min<int32_t>(srcBox.top + visibleRect.height, previousViewportSize.height);
         srcBox.back = 1;
         srcBox.front = 0;
 
         nsRefPtr<ID3D10Resource> srcResource;
         previousRTView->GetResource(getter_AddRefs(srcResource));
 
@@ -243,26 +244,25 @@ ContainerLayerD3D10::LayerManagerDestroy
 void
 ContainerLayerD3D10::Validate()
 {
   nsIntRect visibleRect = mVisibleRegion.GetBounds();
 
   mSupportsComponentAlphaChildren = false;
 
   if (UseIntermediateSurface()) {
-    gfx3DMatrix transform3D;
-    gfx::To3DMatrix(GetEffectiveTransform(), transform3D);
-    gfxMatrix transform;
+    Matrix4x4 transform3D = GetEffectiveTransform();
+    Matrix transform;
 
     if (mVisibleRegion.GetNumRects() == 1 && (GetContentFlags() & CONTENT_OPAQUE)) {
       // don't need a background, we're going to paint all opaque stuff
       mSupportsComponentAlphaChildren = true;
     } else {
       if (HasOpaqueAncestorLayer(this) &&
-          transform3D.Is2D(&transform) && !transform.HasNonIntegerTranslation() &&
+          transform3D.Is2D(&transform) && !ThebesMatrix(transform).HasNonIntegerTranslation() &&
           GetParent()->GetEffectiveVisibleRegion().GetBounds().Contains(visibleRect))
       {
         // In this case we can copy up the background. See RenderLayer.
         mSupportsComponentAlphaChildren = true;
       }
     }
   } else {
     mSupportsComponentAlphaChildren = (GetContentFlags() & CONTENT_OPAQUE) ||
--- a/gfx/layers/d3d10/LayerManagerD3D10.cpp
+++ b/gfx/layers/d3d10/LayerManagerD3D10.cpp
@@ -854,22 +854,21 @@ LayerD3D10::LoadMaskTexture()
     IntSize size;
     nsRefPtr<ID3D10ShaderResourceView> maskSRV =
       static_cast<LayerD3D10*>(maskLayer->ImplData())->GetAsTexture(&size);
   
     if (!maskSRV) {
       return SHADER_NO_MASK;
     }
 
-    gfxMatrix maskTransform;
-    gfx3DMatrix effectiveTransform;
-    gfx::To3DMatrix(maskLayer->GetEffectiveTransform(), effectiveTransform);
+    Matrix maskTransform;
+    Matrix4x4 effectiveTransform = maskLayer->GetEffectiveTransform();
     bool maskIs2D = effectiveTransform.CanDraw2D(&maskTransform);
     NS_ASSERTION(maskIs2D, "How did we end up with a 3D transform here?!");
-    gfxRect bounds = gfxRect(gfxPoint(), ThebesIntSize(size));
+    Rect bounds = Rect(Point(), Size(size));
     bounds = maskTransform.TransformBounds(bounds);
 
     effect()->GetVariableByName("vMaskQuad")->AsVector()->SetFloatVector(
       ShaderConstantRectD3D10(
         (float)bounds.x,
         (float)bounds.y,
         (float)bounds.width,
         (float)bounds.height)
--- a/gfx/layers/d3d11/CompositorD3D11.cpp
+++ b/gfx/layers/d3d11/CompositorD3D11.cpp
@@ -452,17 +452,17 @@ void
 CompositorD3D11::SetRenderTarget(CompositingRenderTarget* aRenderTarget)
 {
   MOZ_ASSERT(aRenderTarget);
   CompositingRenderTargetD3D11* newRT =
     static_cast<CompositingRenderTargetD3D11*>(aRenderTarget);
   ID3D11RenderTargetView* view = newRT->mRTView;
   mCurrentRT = newRT;
   mContext->OMSetRenderTargets(1, &view, nullptr);
-  PrepareViewport(newRT->GetSize(), gfxMatrix());
+  PrepareViewport(newRT->GetSize(), gfx::Matrix());
 }
 
 void
 CompositorD3D11::SetPSForEffect(Effect* aEffect, MaskType aMaskType)
 {
   switch (aEffect->mType) {
   case EFFECT_SOLID_COLOR:
     mContext->PSSetShader(mAttachments->mSolidColorShader[aMaskType], nullptr, 0);
@@ -743,36 +743,36 @@ CompositorD3D11::EndFrame()
     }
   }
   
   mCurrentRT = nullptr;
 }
 
 void
 CompositorD3D11::PrepareViewport(const gfx::IntSize& aSize,
-                                 const gfxMatrix& aWorldTransform)
+                                 const gfx::Matrix& aWorldTransform)
 {
   D3D11_VIEWPORT viewport;
   viewport.MaxDepth = 1.0f;
   viewport.MinDepth = 0;
   viewport.Width = aSize.width;
   viewport.Height = aSize.height;
   viewport.TopLeftX = 0;
   viewport.TopLeftY = 0;
 
   mContext->RSSetViewports(1, &viewport);
 
-  gfxMatrix viewMatrix;
-  viewMatrix.Translate(-gfxPoint(1.0, -1.0));
+  Matrix viewMatrix;
+  viewMatrix.Translate(-1.0, 1.0);
   viewMatrix.Scale(2.0f / float(aSize.width), 2.0f / float(aSize.height));
   viewMatrix.Scale(1.0f, -1.0f);
 
   viewMatrix = aWorldTransform * viewMatrix;
 
-  gfx3DMatrix projection = gfx3DMatrix::From2D(viewMatrix);
+  Matrix4x4 projection = Matrix4x4::From2D(viewMatrix);
   projection._33 = 0.0f;
 
   memcpy(&mVSConstants.projection, &projection, sizeof(mVSConstants.projection));
 }
 
 void
 CompositorD3D11::EnsureSize()
 {
--- a/gfx/layers/d3d11/CompositorD3D11.h
+++ b/gfx/layers/d3d11/CompositorD3D11.h
@@ -123,17 +123,17 @@ public:
    */
   virtual void AbortFrame() MOZ_OVERRIDE {}
 
   /**
    * Setup the viewport and projection matrix for rendering
    * to a window of the given dimensions.
    */
   virtual void PrepareViewport(const gfx::IntSize& aSize,
-                               const gfxMatrix& aWorldTransform) MOZ_OVERRIDE;
+                               const gfx::Matrix& aWorldTransform) MOZ_OVERRIDE;
 
   virtual bool SupportsPartialTextureUpdate() MOZ_OVERRIDE { return true; }
 
 #ifdef MOZ_DUMP_PAINTING
   virtual const char* Name() const MOZ_OVERRIDE { return "Direct3D 11"; }
 #endif
 
   virtual void NotifyLayersTransaction() MOZ_OVERRIDE { }
--- a/gfx/layers/d3d9/CompositorD3D9.cpp
+++ b/gfx/layers/d3d9/CompositorD3D9.cpp
@@ -183,17 +183,17 @@ CompositorD3D9::CreateRenderTargetFromSo
 
 void
 CompositorD3D9::SetRenderTarget(CompositingRenderTarget *aRenderTarget)
 {
   MOZ_ASSERT(aRenderTarget && mDeviceManager);
   RefPtr<CompositingRenderTargetD3D9> oldRT = mCurrentRT;
   mCurrentRT = static_cast<CompositingRenderTargetD3D9*>(aRenderTarget);
   mCurrentRT->BindRenderTarget(device());
-  PrepareViewport(mCurrentRT->GetSize(), gfxMatrix());
+  PrepareViewport(mCurrentRT->GetSize(), Matrix());
 }
 
 static DeviceManagerD3D9::ShaderMode
 ShaderModeForEffectType(EffectTypes aEffectType)
 {
   switch (aEffectType) {
   case EFFECT_SOLID_COLOR:
     return DeviceManagerD3D9::SOLIDCOLORLAYER;
@@ -646,29 +646,29 @@ CompositorD3D9::EndFrame()
   }
 
   mCurrentRT = nullptr;
   mDefaultRT = nullptr;
 }
 
 void
 CompositorD3D9::PrepareViewport(const gfx::IntSize& aSize,
-                                const gfxMatrix &aWorldTransform)
+                                const Matrix &aWorldTransform)
 {
-  gfx3DMatrix viewMatrix;
+  Matrix4x4 viewMatrix;
   /*
    * Matrix to transform to viewport space ( <-1.0, 1.0> topleft,
    * <1.0, -1.0> bottomright)
    */
   viewMatrix._11 = 2.0f / aSize.width;
   viewMatrix._22 = -2.0f / aSize.height;
   viewMatrix._41 = -1.0f;
   viewMatrix._42 = 1.0f;
 
-  viewMatrix = gfx3DMatrix::From2D(aWorldTransform) * viewMatrix;
+  viewMatrix = Matrix4x4::From2D(aWorldTransform) * viewMatrix;
 
   HRESULT hr = device()->SetVertexShaderConstantF(CBmProjection, &viewMatrix._11, 4);
 
   if (FAILED(hr)) {
     NS_WARNING("Failed to set projection matrix");
   }
 }
 
--- a/gfx/layers/d3d9/CompositorD3D9.h
+++ b/gfx/layers/d3d9/CompositorD3D9.h
@@ -70,17 +70,17 @@ public:
 
   virtual void EndFrame() MOZ_OVERRIDE;
 
   virtual void EndFrameForExternalComposition(const gfx::Matrix& aTransform) MOZ_OVERRIDE {}
 
   virtual void AbortFrame() MOZ_OVERRIDE {}
 
   virtual void PrepareViewport(const gfx::IntSize& aSize,
-                               const gfxMatrix& aWorldTransform) MOZ_OVERRIDE;
+                               const gfx::Matrix& aWorldTransform) MOZ_OVERRIDE;
 
   virtual bool SupportsPartialTextureUpdate() MOZ_OVERRIDE{ return true; }
 
 #ifdef MOZ_DUMP_PAINTING
   virtual const char* Name() const MOZ_OVERRIDE { return "Direct3D9"; }
 #endif
 
   virtual void NotifyLayersTransaction() MOZ_OVERRIDE {}
--- a/gfx/layers/d3d9/ContainerLayerD3D9.cpp
+++ b/gfx/layers/d3d9/ContainerLayerD3D9.cpp
@@ -3,16 +3,18 @@
  * 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/. */
 
 #include "ContainerLayerD3D9.h"
 
 #include "ThebesLayerD3D9.h"
 #include "ReadbackProcessor.h"
 
+using namespace mozilla::gfx;
+
 namespace mozilla {
 namespace layers {
 
 ContainerLayerD3D9::ContainerLayerD3D9(LayerManagerD3D9 *aManager)
   : ContainerLayer(aManager, nullptr)
   , LayerD3D9(aManager)
 {
   mImplData = static_cast<LayerD3D9*>(this);
@@ -84,32 +86,31 @@ ContainerLayerD3D9::RenderLayer()
       device()->SetRenderTarget(0, renderSurface);
     }
 
     if (mVisibleRegion.GetNumRects() == 1 && 
         (GetContentFlags() & CONTENT_OPAQUE)) {
       // don't need a background, we're going to paint all opaque stuff
       mSupportsComponentAlphaChildren = true;
     } else {
-      gfx3DMatrix transform3D;
-      gfx::To3DMatrix(GetEffectiveTransform(), transform3D);
-      gfxMatrix transform;
+      Matrix4x4 transform3D = GetEffectiveTransform();
+      Matrix transform;
       // If we have an opaque ancestor layer, then we can be sure that
       // all the pixels we draw into are either opaque already or will be
       // covered by something opaque. Otherwise copying up the background is
       // not safe.
       HRESULT hr = E_FAIL;
       if (HasOpaqueAncestorLayer(this) &&
-          transform3D.Is2D(&transform) && !transform.HasNonIntegerTranslation()) {
+          transform3D.Is2D(&transform) && !ThebesMatrix(transform).HasNonIntegerTranslation()) {
         // Copy background up from below
         RECT dest = { 0, 0, visibleRect.width, visibleRect.height };
         RECT src = dest;
         ::OffsetRect(&src,
-                     visibleRect.x + int32_t(transform.x0),
-                     visibleRect.y + int32_t(transform.y0));
+                     visibleRect.x + int32_t(transform._31),
+                     visibleRect.y + int32_t(transform._32));
         if (!mD3DManager->CompositingDisabled()) {
           hr = device()->
             StretchRect(previousRenderTarget, &src, renderSurface, &dest, D3DTEXF_NONE);
         }
       }
       if (hr == S_OK) {
         mSupportsComponentAlphaChildren = true;
       } else if (!mD3DManager->CompositingDisabled()) {
--- a/gfx/layers/d3d9/DeviceManagerD3D9.cpp
+++ b/gfx/layers/d3d9/DeviceManagerD3D9.cpp
@@ -544,30 +544,29 @@ DeviceManagerD3D9::CreateSwapChain(HWND 
   * input to the shaders.
   * Returns true if a texture is loaded, false if 
   * a texture for the mask layer could not be loaded.
   */
 bool
 LoadMaskTexture(Layer* aMask, IDirect3DDevice9* aDevice,
                 uint32_t aMaskTexRegister)
 {
-  gfx::IntSize size;
+  IntSize size;
   nsRefPtr<IDirect3DTexture9> texture =
     static_cast<LayerD3D9*>(aMask->ImplData())->GetAsTexture(&size);
 
   if (!texture) {
     return false;
   }
 
-  gfxMatrix maskTransform;
-  gfx3DMatrix effectiveTransform;
-  gfx::To3DMatrix(aMask->GetEffectiveTransform(), effectiveTransform);
+  Matrix maskTransform;
+  Matrix4x4 effectiveTransform = aMask->GetEffectiveTransform();
   bool maskIs2D = effectiveTransform.CanDraw2D(&maskTransform);
   NS_ASSERTION(maskIs2D, "How did we end up with a 3D transform here?!");
-  gfxRect bounds = gfxRect(gfxPoint(), gfx::ThebesIntSize(size));
+  Rect bounds = Rect(Point(), Size(size));
   bounds = maskTransform.TransformBounds(bounds);
 
   aDevice->SetVertexShaderConstantF(DeviceManagerD3D9::sMaskQuadRegister,
                                     ShaderConstantRect((float)bounds.x,
                                                        (float)bounds.y,
                                                        (float)bounds.width,
                                                        (float)bounds.height),
                                     1);
--- a/gfx/layers/opengl/CompositingRenderTargetOGL.h
+++ b/gfx/layers/opengl/CompositingRenderTargetOGL.h
@@ -3,17 +3,16 @@
  * 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_GFX_COMPOSITINGRENDERTARGETOGL_H
 #define MOZILLA_GFX_COMPOSITINGRENDERTARGETOGL_H
 
 #include "GLContextTypes.h"             // for GLContext
 #include "GLDefs.h"                     // for GLenum, LOCAL_GL_FRAMEBUFFER, etc
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/Attributes.h"         // for MOZ_OVERRIDE
 #include "mozilla/RefPtr.h"             // for RefPtr, TemporaryRef
 #include "mozilla/gfx/Point.h"          // for IntSize, IntSizeTyped
 #include "mozilla/gfx/Types.h"          // for SurfaceFormat, etc
 #include "mozilla/layers/Compositor.h"  // for SurfaceInitMode, etc
 #include "mozilla/layers/TextureHost.h" // for CompositingRenderTarget
 #include "mozilla/layers/CompositorOGL.h"  // for CompositorOGL
@@ -80,17 +79,17 @@ public:
 
   /**
    * Create a render target around the default FBO, for rendering straight to
    * the window.
    */
   static TemporaryRef<CompositingRenderTargetOGL>
   RenderTargetForWindow(CompositorOGL* aCompositor,
                         const gfx::IntSize& aSize,
-                        const gfxMatrix& aTransform)
+                        const gfx::Matrix& aTransform)
   {
     RefPtr<CompositingRenderTargetOGL> result
       = new CompositingRenderTargetOGL(aCompositor, gfx::IntPoint(0, 0), 0, 0);
     result->mTransform = aTransform;
     result->mInitParams = InitParams(aSize, 0, INIT_MODE_NONE);
     result->mInitParams.mStatus = InitParams::INITIALIZED;
     return result.forget();
   }
@@ -145,33 +144,33 @@ public:
 
   gfx::SurfaceFormat GetFormat() const MOZ_OVERRIDE
   {
     // XXX - Should it be implemented ? is the above assert true ?
     MOZ_ASSERT(false, "Not implemented");
     return gfx::SurfaceFormat::UNKNOWN;
   }
 
-  const gfxMatrix& GetTransform() {
+  const gfx::Matrix& GetTransform() {
     return mTransform;
   }
 
 #ifdef MOZ_DUMP_PAINTING
   virtual TemporaryRef<gfx::DataSourceSurface> Dump(Compositor* aCompositor);
 #endif
 
 private:
   /**
    * Actually do the initialisation. Note that we leave our FBO bound, and so
    * calling this method is only suitable when about to use this render target.
    */
   void InitializeImpl();
 
   InitParams mInitParams;
-  gfxMatrix mTransform;
+  gfx::Matrix mTransform;
   CompositorOGL* mCompositor;
   GLContext* mGL;
   GLuint mTextureHandle;
   GLuint mFBO;
 };
 
 }
 }
--- a/gfx/layers/opengl/CompositorOGL.cpp
+++ b/gfx/layers/opengl/CompositorOGL.cpp
@@ -226,18 +226,18 @@ FPSState::DrawFPS(TimeStamp aNow,
 
   aContext->fActiveTexture(LOCAL_GL_TEXTURE0);
   aContext->fBindTexture(LOCAL_GL_TEXTURE_2D, mTexture);
 
   aProgram->Activate();
   aProgram->SetTextureUnit(0);
   aProgram->SetLayerQuadRect(gfx::Rect(0.f, 0.f, viewport[2], viewport[3]));
   aProgram->SetLayerOpacity(1.f);
-  aProgram->SetTextureTransform(gfx3DMatrix());
-  aProgram->SetLayerTransform(gfx3DMatrix());
+  aProgram->SetTextureTransform(Matrix4x4());
+  aProgram->SetLayerTransform(Matrix4x4());
   aProgram->SetRenderOffset(0, 0);
 
   aContext->fBlendFuncSeparate(LOCAL_GL_ONE, LOCAL_GL_ZERO,
                                LOCAL_GL_ONE, LOCAL_GL_ZERO);
 
   DrawQuads(aContext, mVBOs, aProgram, rects);
 }
 
@@ -623,61 +623,65 @@ CompositorOGL::BindAndDrawQuadWithTextur
                      texCoordRect.width, texCoordRect.height);
     DecomposeIntoNoRepeatTriangles(tcRect,
                                    nsIntSize(realTexSize.width, realTexSize.height),
                                    rects, flipped);
   }
 
   gfx3DMatrix textureTransform;
   if (rects.IsSimpleQuad(textureTransform)) {
-    aProg->SetTextureTransform(aTextureTransform * textureTransform);
+    Matrix4x4 transform;
+    ToMatrix4x4(aTextureTransform * textureTransform, transform);
+    aProg->SetTextureTransform(transform);
     BindAndDrawQuad(aProg, false);
   } else {
-    aProg->SetTextureTransform(aTextureTransform);
+    Matrix4x4 transform;
+    ToMatrix4x4(aTextureTransform, transform);
+    aProg->SetTextureTransform(transform);
     DrawQuads(mGLContext, mVBOs, aProg, rects);
   }
 }
 
 void
 CompositorOGL::PrepareViewport(const gfx::IntSize& aSize,
-                               const gfxMatrix& aWorldTransform)
+                               const Matrix& aWorldTransform)
 {
   // Set the viewport correctly.
   mGLContext->fViewport(0, 0, aSize.width, aSize.height);
 
   mHeight = aSize.height;
 
   // We flip the view matrix around so that everything is right-side up; we're
   // drawing directly into the window's back buffer, so this keeps things
   // looking correct.
   // XXX: We keep track of whether the window size changed, so we could skip
   // this update if it hadn't changed since the last call. We will need to
   // track changes to aTransformPolicy and aWorldTransform for this to work
   // though.
 
   // Matrix to transform (0, 0, aWidth, aHeight) to viewport space (-1.0, 1.0,
   // 2, 2) and flip the contents.
-  gfxMatrix viewMatrix;
-  viewMatrix.Translate(-gfxPoint(1.0, -1.0));
+  Matrix viewMatrix;
+  viewMatrix.Translate(-1.0, 1.0);
   viewMatrix.Scale(2.0f / float(aSize.width), 2.0f / float(aSize.height));
   viewMatrix.Scale(1.0f, -1.0f);
   if (!mTarget) {
-    viewMatrix.Translate(gfxPoint(mRenderOffset.x, mRenderOffset.y));
+    viewMatrix.Translate(mRenderOffset.x, mRenderOffset.y);
   }
 
   viewMatrix = aWorldTransform * viewMatrix;
 
-  gfx3DMatrix matrix3d = gfx3DMatrix::From2D(viewMatrix);
+  Matrix4x4 matrix3d = Matrix4x4::From2D(viewMatrix);
   matrix3d._33 = 0.0f;
 
   SetLayerProgramProjectionMatrix(matrix3d);
 }
 
 void
-CompositorOGL::SetLayerProgramProjectionMatrix(const gfx3DMatrix& aMatrix)
+CompositorOGL::SetLayerProgramProjectionMatrix(const Matrix4x4& aMatrix)
 {
   for (unsigned int i = 0; i < mPrograms.Length(); ++i) {
     for (uint32_t mask = MaskNone; mask < NumMaskTypes; ++mask) {
       if (mPrograms[i].mVariations[mask]) {
         mPrograms[i].mVariations[mask]->CheckAndSetProjectionMatrix(aMatrix);
       }
     }
   }
@@ -841,17 +845,17 @@ CompositorOGL::BeginFrame(const nsIntReg
   mPixelsFilled = 0;
 
 #if MOZ_ANDROID_OMTC
   TexturePoolOGL::Fill(gl());
 #endif
 
   mCurrentRenderTarget = CompositingRenderTargetOGL::RenderTargetForWindow(this,
                             IntSize(width, height),
-                            ThebesMatrix(aTransform));
+                            aTransform);
   mCurrentRenderTarget->BindRenderTarget();
 #ifdef DEBUG
   mWindowRenderTarget = mCurrentRenderTarget;
 #endif
 
   // Default blend function implements "OVER"
   mGLContext->fBlendFuncSeparate(LOCAL_GL_ONE, LOCAL_GL_ONE_MINUS_SRC_ALPHA,
                                  LOCAL_GL_ONE, LOCAL_GL_ONE);
@@ -1294,17 +1298,17 @@ CompositorOGL::DrawQuadInternal(const Re
 
       ShaderProgramOGL *program = GetProgram(GetFBOLayerProgramType(), maskType);
 
       surface->BindTexture(LOCAL_GL_TEXTURE0, mFBOTextureTarget);
 
       program->Activate();
       program->SetTextureUnit(0);
       program->SetLayerOpacity(aOpacity);
-      program->SetTextureTransform(gfx3DMatrix());
+      program->SetTextureTransform(Matrix4x4());
 
       AutoSaveTexture bindMask(mGLContext, LOCAL_GL_TEXTURE1);
       if (maskType != MaskNone) {
         sourceMask->BindTexture(LOCAL_GL_TEXTURE1);
         program->SetMaskTextureUnit(1);
         program->SetMaskLayerTransform(maskQuadTransform);
       }
 
@@ -1448,17 +1452,17 @@ CompositorOGL::EndFrameForExternalCompos
     }
     double fps = mFPS->mCompositionFps.AddFrameAndGetFps(TimeStamp::Now());
     printf_stderr("HWComposer: FPS is %g\n", fps);
   }
 
   // This lets us reftest and screenshot content rendered externally
   if (mTarget) {
     MakeCurrent();
-    CopyToTarget(mTarget, ThebesMatrix(aTransform));
+    CopyToTarget(mTarget, aTransform);
     mGLContext->fBindBuffer(LOCAL_GL_ARRAY_BUFFER, 0);
   }
 }
 
 void
 CompositorOGL::AbortFrame()
 {
   mGLContext->fBindBuffer(LOCAL_GL_ARRAY_BUFFER, 0);
@@ -1469,17 +1473,17 @@ CompositorOGL::AbortFrame()
 void
 CompositorOGL::SetDestinationSurfaceSize(const gfx::IntSize& aSize)
 {
   mSurfaceSize.width = aSize.width;
   mSurfaceSize.height = aSize.height;
 }
 
 void
-CompositorOGL::CopyToTarget(DrawTarget *aTarget, const gfxMatrix& aTransform)
+CompositorOGL::CopyToTarget(DrawTarget *aTarget, const gfx::Matrix& aTransform)
 {
   IntRect rect;
   if (mUseExternalSurfaceSize) {
     rect = IntRect(0, 0, mSurfaceSize.width, mSurfaceSize.height);
   } else {
     rect = IntRect(0, 0, mWidgetSize.width, mWidgetSize.height);
   }
   GLint width = rect.width;
@@ -1508,17 +1512,17 @@ CompositorOGL::CopyToTarget(DrawTarget *
     new gfxImageSurface(map.mData,
                         gfxIntSize(width, height),
                         map.mStride,
                         gfxImageFormat::ARGB32);
   ReadPixelsIntoImageSurface(mGLContext, surf);
   source->Unmap();
 
   // Map from GL space to Cairo space and reverse the world transform.
-  Matrix glToCairoTransform = ToMatrix(aTransform);
+  Matrix glToCairoTransform = aTransform;
   glToCairoTransform.Invert();
   glToCairoTransform.Scale(1.0, -1.0);
   glToCairoTransform.Translate(0.0, -height);
 
   Matrix oldMatrix = aTarget->GetTransform();
   aTarget->SetTransform(glToCairoTransform);
   Rect floatRect = Rect(rect.x, rect.y, rect.width, rect.height);
   aTarget->DrawSurface(source, floatRect, floatRect, DrawSurfaceOptions(), DrawOptions(1.0f, CompositionOp::OP_SOURCE));
--- a/gfx/layers/opengl/CompositorOGL.h
+++ b/gfx/layers/opengl/CompositorOGL.h
@@ -29,17 +29,16 @@
 #include "nsThreadUtils.h"              // for nsRunnable
 #include "nsTraceRefcnt.h"              // for MOZ_COUNT_CTOR, etc
 #include "nsXULAppAPI.h"                // for XRE_GetProcessType
 #include "nscore.h"                     // for NS_IMETHOD
 #include "VBOArena.h"                   // for gl::VBOArena
 
 class gfx3DMatrix;
 class nsIWidget;
-struct gfxMatrix;
 
 namespace mozilla {
 class TimeStamp;
 
 namespace gfx {
 class Matrix4x4;
 }
 
@@ -140,17 +139,17 @@ public:
   virtual void MakeCurrent(MakeCurrentFlags aFlags = 0) MOZ_OVERRIDE;
 
   virtual void SetTargetContext(gfx::DrawTarget* aTarget) MOZ_OVERRIDE
   {
     mTarget = aTarget;
   }
 
   virtual void PrepareViewport(const gfx::IntSize& aSize,
-                               const gfxMatrix& aWorldTransform) MOZ_OVERRIDE;
+                               const gfx::Matrix& aWorldTransform) MOZ_OVERRIDE;
 
 
 #ifdef MOZ_DUMP_PAINTING
   virtual const char* Name() const MOZ_OVERRIDE { return "OGL"; }
 #endif // MOZ_DUMP_PAINTING
 
   virtual void NotifyLayersTransaction() MOZ_OVERRIDE;
 
@@ -267,17 +266,17 @@ private:
                           gfx::Rect *aClipRectOut = nullptr,
                           gfx::Rect *aRenderBoundsOut = nullptr) MOZ_OVERRIDE;
 
   ShaderProgramType GetProgramTypeForEffect(Effect* aEffect) const;
 
   /**
    * Updates all layer programs with a new projection matrix.
    */
-  void SetLayerProgramProjectionMatrix(const gfx3DMatrix& aMatrix);
+  void SetLayerProgramProjectionMatrix(const gfx::Matrix4x4& aMatrix);
 
   /**
    * Helper method for Initialize, creates all valid variations of a program
    * and adds them to mPrograms
    */
   void AddPrograms(ShaderProgramType aType);
 
   ShaderProgramOGL* GetProgram(ShaderProgramType aType,
@@ -319,17 +318,17 @@ private:
                                       TextureSource *aTexture);
 
   void CleanupResources();
 
   /**
    * Copies the content of our backbuffer to the set transaction target.
    * Does not restore the target FBO, so only call from EndFrame.
    */
-  void CopyToTarget(gfx::DrawTarget* aTarget, const gfxMatrix& aWorldMatrix);
+  void CopyToTarget(gfx::DrawTarget* aTarget, const gfx::Matrix& aWorldMatrix);
 
   /**
    * Records the passed frame timestamp and returns the current estimated FPS.
    */
   double AddFrameAndGetFps(const TimeStamp& timestamp);
 
   /**
    * Implements the flipping of the y-axis to convert from layers/compositor
--- a/gfx/layers/opengl/OGLShaderProgram.cpp
+++ b/gfx/layers/opengl/OGLShaderProgram.cpp
@@ -1,15 +1,14 @@
 /* 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/. */
 
 #include "OGLShaderProgram.h"
 #include <stdint.h>                     // for uint32_t
-#include "gfxMatrix.h"                  // for gfxMatrix
 #include "gfxRect.h"                    // for gfxRect
 #include "mozilla/DebugOnly.h"          // for DebugOnly
 #include "nsAString.h"
 #include "nsAutoPtr.h"                  // for nsRefPtr
 #include "nsString.h"                   // for nsAutoCString
 #include "prenv.h"                      // for PR_GetEnv
 #include "OGLShaders.h"
 #include "Layers.h"
--- a/gfx/layers/opengl/OGLShaderProgram.h
+++ b/gfx/layers/opengl/OGLShaderProgram.h
@@ -250,20 +250,16 @@ public:
     return mTexCoordMultiplierUniformLocation;
   }
 
   /**
    * The following set of methods set a uniform argument to the shader program.
    * Not all uniforms may be set for all programs, and such uses will throw
    * an assertion.
    */
-  void SetLayerTransform(const gfx3DMatrix& aMatrix) {
-    SetMatrixUniform(mProfile.LookupUniformLocation("uLayerTransform"), aMatrix);
-  }
-
   void SetLayerTransform(const gfx::Matrix4x4& aMatrix) {
     SetMatrixUniform(mProfile.LookupUniformLocation("uLayerTransform"), aMatrix);
   }
 
   void SetMaskLayerTransform(const gfx::Matrix4x4& aMatrix) {
     SetMatrixUniform(mProfile.LookupUniformLocation("uMaskQuadTransform"), aMatrix);
   }
 
@@ -281,34 +277,30 @@ public:
     m._11 = aRect.width;
     m._22 = aRect.height;
     m._41 = aRect.x;
     m._42 = aRect.y;
     SetMatrixUniform(mProfile.LookupUniformLocation("uLayerQuadTransform"), m);
   }
 
   // activates this program and sets its projection matrix, if the program uses one
-  void CheckAndSetProjectionMatrix(const gfx3DMatrix& aMatrix)
+  void CheckAndSetProjectionMatrix(const gfx::Matrix4x4& aMatrix)
   {
     if (mProfile.mHasMatrixProj) {
       mIsProjectionMatrixStale = true;
       mProjectionMatrix = aMatrix;
     }
   }
 
-  void SetProjectionMatrix(const gfx3DMatrix& aMatrix) {
+  void SetProjectionMatrix(const gfx::Matrix4x4& aMatrix) {
     SetMatrixUniform(mProfile.LookupUniformLocation("uMatrixProj"), aMatrix);
     mIsProjectionMatrixStale = false;
   }
 
   // sets this program's texture transform, if it uses one
-  void SetTextureTransform(const gfx3DMatrix& aMatrix) {
-    SetMatrixUniform(mProfile.LookupUniformLocation("uTextureTransform"), aMatrix);
-  }
-
   void SetTextureTransform(const gfx::Matrix4x4& aMatrix) {
     SetMatrixUniform(mProfile.LookupUniformLocation("uTextureTransform"), aMatrix);
   }
 
   void SetRenderOffset(const nsIntPoint& aOffset) {
     float vals[4] = { float(aOffset.x), float(aOffset.y), 0.0f, 0.0f };
     SetUniform(mProfile.LookupUniformLocation("uRenderTargetOffset"), 4, vals);
   }
@@ -368,17 +360,17 @@ public:
     SetUniform(mTexCoordMultiplierUniformLocation, 2, f);
   }
 
   // the names of attributes
   static const char* const VertexCoordAttrib;
   static const char* const TexCoordAttrib;
 
 protected:
-  gfx3DMatrix mProjectionMatrix;
+  gfx::Matrix4x4 mProjectionMatrix;
   // true if the projection matrix needs setting
   bool mIsProjectionMatrixStale;
 
   RefPtr<GLContext> mGL;
   // the OpenGL id of the program
   GLuint mProgram;
   ProgramProfileOGL mProfile;
   enum {
--- a/ipc/app/macbuild/Contents/Info.plist.in
+++ b/ipc/app/macbuild/Contents/Info.plist.in
@@ -22,12 +22,14 @@
 	<dict>
 		<key>i386</key>
 		<string>10.5.0</string>
 		<key>x86_64</key>
 		<string>10.6.0</string>
 	</dict>
 	<key>LSUIElement</key>
 	<string>1</string>
-  <key>NSSupportsAutomaticGraphicsSwitching</key>
-  <true/>
+	<key>NSSupportsAutomaticGraphicsSwitching</key>
+	<true/>
+	<key>NSPrincipalClass</key>
+	<string>NSApplication</string>
 </dict>
 </plist>
--- a/js/public/CallNonGenericMethod.h
+++ b/js/public/CallNonGenericMethod.h
@@ -87,27 +87,27 @@ CallMethodIfWrapped(JSContext *cx, IsAcc
 // |this| and call the implementation function on the unwrapped |this|.  If
 // that succeeds, all well and good.  If it doesn't succeed, a TypeError will
 // be thrown.
 //
 // Note: JS::CallNonGenericMethod will only work correctly if it's called in
 //       tail position in a JSNative.  Do not call it from any other place.
 //
 template<IsAcceptableThis Test, NativeImpl Impl>
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 CallNonGenericMethod(JSContext *cx, CallArgs args)
 {
     HandleValue thisv = args.thisv();
     if (Test(thisv))
         return Impl(cx, args);
 
     return detail::CallMethodIfWrapped(cx, Test, Impl, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 CallNonGenericMethod(JSContext *cx, IsAcceptableThis Test, NativeImpl Impl, CallArgs args)
 {
     HandleValue thisv = args.thisv();
     if (Test(thisv))
         return Impl(cx, args);
 
     return detail::CallMethodIfWrapped(cx, Test, Impl, args);
 }
--- a/js/public/Class.h
+++ b/js/public/Class.h
@@ -34,17 +34,17 @@ class PropertyId;
 class PropertyName;
 class Shape;
 class SpecialId;
 
 // This is equal to JSFunction::class_.  Use it in places where you don't want
 // to #include jsfun.h.
 extern JS_FRIEND_DATA(const js::Class* const) FunctionClassPtr;
 
-static JS_ALWAYS_INLINE jsid
+static MOZ_ALWAYS_INLINE jsid
 SPECIALID_TO_JSID(const SpecialId &sid);
 
 /*
  * We partition the ways to refer to a property into three: by an index
  * (uint32_t); by a string whose characters do not represent an index
  * (PropertyName, see vm/String.h); and by various special values.
  *
  * Special values are encoded using SpecialId, which is layout-compatible but
@@ -53,17 +53,17 @@ SPECIALID_TO_JSID(const SpecialId &sid);
  * valid identifier.  In the future, a SpecialId may also be an object used by
  * Harmony-proposed private names.
  */
 class SpecialId
 {
     uintptr_t bits_;
 
     /* Needs access to raw bits. */
-    friend JS_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid);
+    friend MOZ_ALWAYS_INLINE jsid SPECIALID_TO_JSID(const SpecialId &sid);
     friend class PropertyId;
 
     static const uintptr_t TYPE_VOID = JSID_TYPE_VOID;
     static const uintptr_t TYPE_OBJECT = JSID_TYPE_OBJECT;
     static const uintptr_t TYPE_MASK = JSID_TYPE_MASK;
 
     SpecialId(uintptr_t bits) : bits_(bits) { }
 
@@ -108,34 +108,34 @@ class SpecialId
         return sid;
     }
 
     bool isVoid() const {
         return bits_ == TYPE_VOID;
     }
 };
 
-static JS_ALWAYS_INLINE jsid
+static MOZ_ALWAYS_INLINE jsid
 SPECIALID_TO_JSID(const SpecialId &sid)
 {
     jsid id;
     JSID_BITS(id) = sid.bits_;
     JS_ASSERT_IF(sid.isObject(), JSID_IS_OBJECT(id) && JSID_TO_OBJECT(id) == sid.toObject());
     JS_ASSERT_IF(sid.isVoid(), JSID_IS_VOID(id));
     JS_ASSERT_IF(sid.isEmpty(), JSID_IS_EMPTY(id));
     return id;
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_SPECIAL(jsid id)
 {
     return JSID_IS_OBJECT(id) || JSID_IS_EMPTY(id) || JSID_IS_VOID(id);
 }
 
-static JS_ALWAYS_INLINE SpecialId
+static MOZ_ALWAYS_INLINE SpecialId
 JSID_TO_SPECIALID(jsid id)
 {
     JS_ASSERT(JSID_IS_SPECIAL(id));
     if (JSID_IS_OBJECT(id))
         return SpecialId(*JSID_TO_OBJECT(id));
     if (JSID_IS_EMPTY(id))
         return SpecialId::empty();
     JS_ASSERT(JSID_IS_VOID(id));
@@ -630,23 +630,23 @@ JS_STATIC_ASSERT(offsetof(JSClass, resol
 JS_STATIC_ASSERT(offsetof(JSClass, convert) == offsetof(Class, convert));
 JS_STATIC_ASSERT(offsetof(JSClass, finalize) == offsetof(Class, finalize));
 JS_STATIC_ASSERT(offsetof(JSClass, call) == offsetof(Class, call));
 JS_STATIC_ASSERT(offsetof(JSClass, construct) == offsetof(Class, construct));
 JS_STATIC_ASSERT(offsetof(JSClass, hasInstance) == offsetof(Class, hasInstance));
 JS_STATIC_ASSERT(offsetof(JSClass, trace) == offsetof(Class, trace));
 JS_STATIC_ASSERT(sizeof(JSClass) == sizeof(Class));
 
-static JS_ALWAYS_INLINE const JSClass *
+static MOZ_ALWAYS_INLINE const JSClass *
 Jsvalify(const Class *c)
 {
     return (const JSClass *)c;
 }
 
-static JS_ALWAYS_INLINE const Class *
+static MOZ_ALWAYS_INLINE const Class *
 Valueify(const JSClass *c)
 {
     return (const Class *)c;
 }
 
 /*
  * Enumeration describing possible values of the [[Class]] internal property
  * value of objects.
--- a/js/public/GCAPI.h
+++ b/js/public/GCAPI.h
@@ -427,17 +427,17 @@ extern JS_FRIEND_API(bool)
 UnmarkGrayGCThingRecursively(void *thing, JSGCTraceKind kind);
 
 /*
  * This should be called when an object that is marked gray is exposed to the JS
  * engine (by handing it to running JS code or writing it into live JS
  * data). During incremental GC, since the gray bits haven't been computed yet,
  * we conservatively mark the object black.
  */
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 ExposeGCThingToActiveJS(void *thing, JSGCTraceKind kind)
 {
     JS_ASSERT(kind != JSTRACE_SHAPE);
 
     shadow::Runtime *rt = js::gc::GetGCThingRuntime(thing);
 #ifdef JSGC_GENERATIONAL
     /*
      * GC things residing in the nursery cannot be gray: they have no mark bits.
@@ -448,48 +448,48 @@ ExposeGCThingToActiveJS(void *thing, JSG
         return;
 #endif
     if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind))
         IncrementalReferenceBarrier(thing, kind);
     else if (GCThingIsMarkedGray(thing))
         UnmarkGrayGCThingRecursively(thing, kind);
 }
 
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 ExposeValueToActiveJS(const Value &v)
 {
     if (v.isMarkable())
         ExposeGCThingToActiveJS(v.toGCThing(), v.gcKind());
 }
 
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 ExposeObjectToActiveJS(JSObject *obj)
 {
     ExposeGCThingToActiveJS(obj, JSTRACE_OBJECT);
 }
 
 /*
  * If a GC is currently marking, mark the object black.
  */
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 MarkGCThingAsLive(JSRuntime *rt_, void *thing, JSGCTraceKind kind)
 {
     shadow::Runtime *rt = shadow::Runtime::asShadowRuntime(rt_);
 #ifdef JSGC_GENERATIONAL
     /*
      * Any object in the nursery will not be freed during any GC running at that time.
      */
     if (js::gc::IsInsideNursery(rt, thing))
         return;
 #endif
     if (IsIncrementalBarrierNeededOnGCThing(rt, thing, kind))
         IncrementalReferenceBarrier(thing, kind);
 }
 
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 MarkStringAsLive(Zone *zone, JSString *string)
 {
     JSRuntime *rt = JS::shadow::Zone::asShadowZone(zone)->runtimeFromMainThread();
     MarkGCThingAsLive(rt, string, JSTRACE_STRING);
 }
 
 /*
  * Internal to Firefox.
--- a/js/public/HashTable.h
+++ b/js/public/HashTable.h
@@ -1212,17 +1212,17 @@ class HashTable : private AllocPolicy
 
         // Collision: double hash.
         DoubleHash dh = hash2(keyHash);
 
         // Save the first removed entry pointer so we can recycle later.
         Entry *firstRemoved = nullptr;
 
         while(true) {
-            if (JS_UNLIKELY(entry->isRemoved())) {
+            if (MOZ_UNLIKELY(entry->isRemoved())) {
                 if (!firstRemoved)
                     firstRemoved = entry;
             } else {
                 entry->setCollision(collisionBit);
             }
 
             METER(stats.steps++);
             h1 = applyDoubleHash(h1, dh);
--- a/js/public/HeapAPI.h
+++ b/js/public/HeapAPI.h
@@ -108,87 +108,87 @@ struct Zone
 };
 
 } /* namespace shadow */
 } /* namespace JS */
 
 namespace js {
 namespace gc {
 
-static JS_ALWAYS_INLINE uintptr_t *
+static MOZ_ALWAYS_INLINE uintptr_t *
 GetGCThingMarkBitmap(const void *thing)
 {
     JS_ASSERT(thing);
     uintptr_t addr = uintptr_t(thing);
     addr &= ~js::gc::ChunkMask;
     addr |= js::gc::ChunkMarkBitmapOffset;
     return reinterpret_cast<uintptr_t *>(addr);
 }
 
-static JS_ALWAYS_INLINE JS::shadow::Runtime *
+static MOZ_ALWAYS_INLINE JS::shadow::Runtime *
 GetGCThingRuntime(const void *thing)
 {
     JS_ASSERT(thing);
     uintptr_t addr = uintptr_t(thing);
     addr &= ~js::gc::ChunkMask;
     addr |= js::gc::ChunkRuntimeOffset;
     return *reinterpret_cast<JS::shadow::Runtime **>(addr);
 }
 
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 GetGCThingMarkWordAndMask(const void *thing, uint32_t color,
                           uintptr_t **wordp, uintptr_t *maskp)
 {
     uintptr_t addr = uintptr_t(thing);
     size_t bit = (addr & js::gc::ChunkMask) / js::gc::CellSize + color;
     JS_ASSERT(bit < js::gc::ChunkMarkBitmapBits);
     uintptr_t *bitmap = GetGCThingMarkBitmap(thing);
     const uintptr_t nbits = sizeof(*bitmap) * CHAR_BIT;
     *maskp = uintptr_t(1) << (bit % nbits);
     *wordp = &bitmap[bit / nbits];
 }
 
-static JS_ALWAYS_INLINE JS::shadow::ArenaHeader *
+static MOZ_ALWAYS_INLINE JS::shadow::ArenaHeader *
 GetGCThingArena(void *thing)
 {
     uintptr_t addr = uintptr_t(thing);
     addr &= ~js::gc::ArenaMask;
     return reinterpret_cast<JS::shadow::ArenaHeader *>(addr);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 IsInsideNursery(const JS::shadow::Runtime *runtime, const void *p)
 {
 #ifdef JSGC_GENERATIONAL
     return uintptr_t(p) >= runtime->gcNurseryStart_ && uintptr_t(p) < runtime->gcNurseryEnd_;
 #else
     return false;
 #endif
 }
 
 } /* namespace gc */
 
 } /* namespace js */
 
 namespace JS {
 
-static JS_ALWAYS_INLINE Zone *
+static MOZ_ALWAYS_INLINE Zone *
 GetGCThingZone(void *thing)
 {
     JS_ASSERT(thing);
     return js::gc::GetGCThingArena(thing)->zone;
 }
 
-static JS_ALWAYS_INLINE Zone *
+static MOZ_ALWAYS_INLINE Zone *
 GetObjectZone(JSObject *obj)
 {
     return GetGCThingZone(obj);
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 GCThingIsMarkedGray(void *thing)
 {
 #ifdef JSGC_GENERATIONAL
     /*
      * GC things residing in the nursery cannot be gray: they have no mark bits.
      * All live objects in the nursery are moved to tenured at the beginning of
      * each GC slice, so the gray marker never sees nursery things.
      */
@@ -196,17 +196,17 @@ GCThingIsMarkedGray(void *thing)
     if (js::gc::IsInsideNursery(rt, thing))
         return false;
 #endif
     uintptr_t *word, mask;
     js::gc::GetGCThingMarkWordAndMask(thing, js::gc::GRAY, &word, &mask);
     return *word & mask;
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 IsIncrementalBarrierNeededOnGCThing(shadow::Runtime *rt, void *thing, JSGCTraceKind kind)
 {
     if (!rt->needsBarrier_)
         return false;
     JS::Zone *zone = GetGCThingZone(thing);
     return reinterpret_cast<shadow::Zone *>(zone)->needsBarrier_;
 }
 
--- a/js/public/Id.h
+++ b/js/public/Id.h
@@ -41,111 +41,111 @@ struct jsid
 #define JSID_TYPE_VOID                   0x2
 #define JSID_TYPE_OBJECT                 0x4
 #define JSID_TYPE_MASK                   0x7
 
 // Avoid using canonical 'id' for jsid parameters since this is a magic word in
 // Objective-C++ which, apparently, wants to be able to #include jsapi.h.
 #define id iden
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_STRING(jsid id)
 {
     return (JSID_BITS(id) & JSID_TYPE_MASK) == 0;
 }
 
-static JS_ALWAYS_INLINE JSString *
+static MOZ_ALWAYS_INLINE JSString *
 JSID_TO_STRING(jsid id)
 {
     JS_ASSERT(JSID_IS_STRING(id));
     return (JSString *)JSID_BITS(id);
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_ZERO(jsid id)
 {
     return JSID_BITS(id) == 0;
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_INT(jsid id)
 {
     return !!(JSID_BITS(id) & JSID_TYPE_INT);
 }
 
-static JS_ALWAYS_INLINE int32_t
+static MOZ_ALWAYS_INLINE int32_t
 JSID_TO_INT(jsid id)
 {
     JS_ASSERT(JSID_IS_INT(id));
     return ((uint32_t)JSID_BITS(id)) >> 1;
 }
 
 #define JSID_INT_MIN  0
 #define JSID_INT_MAX  INT32_MAX
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 INT_FITS_IN_JSID(int32_t i)
 {
     return i >= 0;
 }
 
-static JS_ALWAYS_INLINE jsid
+static MOZ_ALWAYS_INLINE jsid
 INT_TO_JSID(int32_t i)
 {
     jsid id;
     JS_ASSERT(INT_FITS_IN_JSID(i));
     JSID_BITS(id) = ((i << 1) | JSID_TYPE_INT);
     return id;
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_OBJECT(jsid id)
 {
     return (JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_OBJECT &&
            (size_t)JSID_BITS(id) != JSID_TYPE_OBJECT;
 }
 
-static JS_ALWAYS_INLINE JSObject *
+static MOZ_ALWAYS_INLINE JSObject *
 JSID_TO_OBJECT(jsid id)
 {
     JS_ASSERT(JSID_IS_OBJECT(id));
     return (JSObject *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK);
 }
 
-static JS_ALWAYS_INLINE jsid
+static MOZ_ALWAYS_INLINE jsid
 OBJECT_TO_JSID(JSObject *obj)
 {
     jsid id;
     JS_ASSERT(obj != nullptr);
     JS_ASSERT(((size_t)obj & JSID_TYPE_MASK) == 0);
     JSID_BITS(id) = ((size_t)obj | JSID_TYPE_OBJECT);
     return id;
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_GCTHING(jsid id)
 {
     return JSID_IS_STRING(id) || JSID_IS_OBJECT(id);
 }
 
-static JS_ALWAYS_INLINE void *
+static MOZ_ALWAYS_INLINE void *
 JSID_TO_GCTHING(jsid id)
 {
     return (void *)(JSID_BITS(id) & ~(size_t)JSID_TYPE_MASK);
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_VOID(const jsid id)
 {
     JS_ASSERT_IF(((size_t)JSID_BITS(id) & JSID_TYPE_MASK) == JSID_TYPE_VOID,
                  JSID_BITS(id) == JSID_TYPE_VOID);
     return ((size_t)JSID_BITS(id) == JSID_TYPE_VOID);
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_EMPTY(const jsid id)
 {
     return ((size_t)JSID_BITS(id) == JSID_TYPE_OBJECT);
 }
 
 #undef id
 
 extern JS_PUBLIC_DATA(const jsid) JSID_VOID;
--- a/js/public/Utility.h
+++ b/js/public/Utility.h
@@ -78,17 +78,17 @@ extern JS_PUBLIC_API(void) JS_Abort(void
  * oomAfterAllocations COUNT is passed, we fail continuously after the NUM'th
  * allocation from now.
  */
 extern JS_PUBLIC_DATA(uint32_t) OOM_maxAllocations; /* set in builtins/TestingFunctions.cpp */
 extern JS_PUBLIC_DATA(uint32_t) OOM_counter; /* data race, who cares. */
 
 #ifdef JS_OOM_DO_BACKTRACES
 #define JS_OOM_BACKTRACE_SIZE 32
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 PrintBacktrace()
 {
     void* OOM_trace[JS_OOM_BACKTRACE_SIZE];
     char** OOM_traceSymbols = nullptr;
     int32_t OOM_traceSize = 0;
     int32_t OOM_traceIdx = 0;
     OOM_traceSize = backtrace(OOM_trace, JS_OOM_BACKTRACE_SIZE);
     OOM_traceSymbols = backtrace_symbols(OOM_trace, OOM_traceSize);
@@ -364,64 +364,64 @@ static inline void js_free(void* p)
                      mozilla::Forward<P7>(p7),\
                      mozilla::Forward<P8>(p8),\
                      mozilla::Forward<P9>(p9),\
                      mozilla::Forward<P10>(p10),\
                      mozilla::Forward<P11>(p11),\
                      mozilla::Forward<P12>(p12)))\
     }\
 
-JS_DECLARE_NEW_METHODS(js_new, js_malloc, static JS_ALWAYS_INLINE)
+JS_DECLARE_NEW_METHODS(js_new, js_malloc, static MOZ_ALWAYS_INLINE)
 
 template <class T>
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 js_delete(T *p)
 {
     if (p) {
         p->~T();
         js_free(p);
     }
 }
 
 template<class T>
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 js_delete_poison(T *p)
 {
     if (p) {
         p->~T();
         memset(p, 0x3B, sizeof(T));
         js_free(p);
     }
 }
 
 template <class T>
-static JS_ALWAYS_INLINE T *
+static MOZ_ALWAYS_INLINE T *
 js_pod_malloc()
 {
     return (T *)js_malloc(sizeof(T));
 }
 
 template <class T>
-static JS_ALWAYS_INLINE T *
+static MOZ_ALWAYS_INLINE T *
 js_pod_calloc()
 {
     return (T *)js_calloc(sizeof(T));
 }
 
 template <class T>
-static JS_ALWAYS_INLINE T *
+static MOZ_ALWAYS_INLINE T *
 js_pod_malloc(size_t numElems)
 {
     if (numElems & mozilla::tl::MulOverflowMask<sizeof(T)>::value)
         return nullptr;
     return (T *)js_malloc(numElems * sizeof(T));
 }
 
 template <class T>
-static JS_ALWAYS_INLINE T *
+static MOZ_ALWAYS_INLINE T *
 js_pod_calloc(size_t numElems)
 {
     if (numElems & mozilla::tl::MulOverflowMask<sizeof(T)>::value)
         return nullptr;
     return (T *)js_calloc(numElems * sizeof(T));
 }
 
 namespace js {
--- a/js/src/builtin/RegExp.cpp
+++ b/js/src/builtin/RegExp.cpp
@@ -301,23 +301,23 @@ CompileRegExpObject(JSContext *cx, RegEx
     RegExpObject *reobj = builder.build(escapedSourceStr, RegExpFlag(flags | res->getFlags()));
     if (!reobj)
         return false;
 
     args.rval().setObject(*reobj);
     return true;
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 IsRegExp(HandleValue v)
 {
     return v.isObject() && v.toObject().is<RegExpObject>();
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 regexp_compile_impl(JSContext *cx, CallArgs args)
 {
     JS_ASSERT(IsRegExp(args.thisv()));
     RegExpObjectBuilder builder(cx, &args.thisv().toObject().as<RegExpObject>());
     return CompileRegExpObject(cx, builder, args);
 }
 
 static bool
@@ -346,17 +346,17 @@ regexp_construct(JSContext *cx, unsigned
             return true;
         }
     }
 
     RegExpObjectBuilder builder(cx);
     return CompileRegExpObject(cx, builder, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 regexp_toString_impl(JSContext *cx, CallArgs args)
 {
     JS_ASSERT(IsRegExp(args.thisv()));
 
     JSString *str = args.thisv().toObject().as<RegExpObject>().toString(cx);
     if (!str)
         return false;
 
--- a/js/src/ctypes/CTypes.cpp
+++ b/js/src/ctypes/CTypes.cpp
@@ -786,28 +786,28 @@ static const JSFunctionSpec sModuleFunct
   JS_FN("CDataFinalizer", CDataFinalizer::Construct, 2, CTYPESFN_FLAGS),
   JS_FN("open", Library::Open, 1, CTYPESFN_FLAGS),
   JS_FN("cast", CData::Cast, 2, CTYPESFN_FLAGS),
   JS_FN("getRuntime", CData::GetRuntime, 1, CTYPESFN_FLAGS),
   JS_FN("libraryName", Library::Name, 1, CTYPESFN_FLAGS),
   JS_FS_END
 };
 
-static JS_ALWAYS_INLINE JSString*
+static MOZ_ALWAYS_INLINE JSString*
 NewUCString(JSContext* cx, const AutoString& from)
 {
   return JS_NewUCStringCopyN(cx, from.begin(), from.length());
 }
 
 /*
  * Return a size rounded up to a multiple of a power of two.
  *
  * Note: |align| must be a power of 2.
  */
-static JS_ALWAYS_INLINE size_t
+static MOZ_ALWAYS_INLINE size_t
 Align(size_t val, size_t align)
 {
   // Ensure that align is a power of two.
   MOZ_ASSERT(align != 0 && (align & (align - 1)) == 0);
   return ((val - 1) | (align - 1)) + 1;
 }
 
 static ABICode
@@ -1418,65 +1418,65 @@ JS_STATIC_ASSERT(sizeof(size_t) == sizeo
 JS_STATIC_ASSERT(sizeof(float) == 4);
 JS_STATIC_ASSERT(sizeof(PRFuncPtr) == sizeof(void*));
 JS_STATIC_ASSERT(NumericLimits<double>::is_signed);
 
 // Templated helper to convert FromType to TargetType, for the default case
 // where the trivial POD constructor will do.
 template<class TargetType, class FromType>
 struct ConvertImpl {
-  static JS_ALWAYS_INLINE TargetType Convert(FromType d) {
+  static MOZ_ALWAYS_INLINE TargetType Convert(FromType d) {
     return TargetType(d);
   }
 };
 
 #ifdef _MSC_VER
 // MSVC can't perform double to unsigned __int64 conversion when the
 // double is greater than 2^63 - 1. Help it along a little.
 template<>
 struct ConvertImpl<uint64_t, double> {
-  static JS_ALWAYS_INLINE uint64_t Convert(double d) {
+  static MOZ_ALWAYS_INLINE uint64_t Convert(double d) {
     return d > 0x7fffffffffffffffui64 ?
            uint64_t(d - 0x8000000000000000ui64) + 0x8000000000000000ui64 :
            uint64_t(d);
   }
 };
 #endif
 
 // C++ doesn't guarantee that exact values are the only ones that will
 // round-trip. In fact, on some platforms, including SPARC, there are pairs of
 // values, a uint64_t and a double, such that neither value is exactly
 // representable in the other type, but they cast to each other.
 #ifdef SPARC
 // Simulate x86 overflow behavior
 template<>
 struct ConvertImpl<uint64_t, double> {
-  static JS_ALWAYS_INLINE uint64_t Convert(double d) {
+  static MOZ_ALWAYS_INLINE uint64_t Convert(double d) {
     return d >= 0xffffffffffffffff ?
            0x8000000000000000 : uint64_t(d);
   }
 };
 
 template<>
 struct ConvertImpl<int64_t, double> {
-  static JS_ALWAYS_INLINE int64_t Convert(double d) {
+  static MOZ_ALWAYS_INLINE int64_t Convert(double d) {
     return d >= 0x7fffffffffffffff ?
            0x8000000000000000 : int64_t(d);
   }
 };
 #endif
 
 template<class TargetType, class FromType>
-static JS_ALWAYS_INLINE TargetType Convert(FromType d)
+static MOZ_ALWAYS_INLINE TargetType Convert(FromType d)
 {
   return ConvertImpl<TargetType, FromType>::Convert(d);
 }
 
 template<class TargetType, class FromType>
-static JS_ALWAYS_INLINE bool IsAlwaysExact()
+static MOZ_ALWAYS_INLINE bool IsAlwaysExact()
 {
   // Return 'true' if TargetType can always exactly represent FromType.
   // This means that:
   // 1) TargetType must be the same or more bits wide as FromType. For integers
   //    represented in 'n' bits, unsigned variants will have 'n' digits while
   //    signed will have 'n - 1'. For floating point types, 'digits' is the
   //    mantissa width.
   // 2) If FromType is signed, TargetType must also be signed. (Floating point
@@ -1495,44 +1495,44 @@ static JS_ALWAYS_INLINE bool IsAlwaysExa
 
   return true;
 }
 
 // Templated helper to determine if FromType 'i' converts losslessly to
 // TargetType 'j'. Default case where both types are the same signedness.
 template<class TargetType, class FromType, bool TargetSigned, bool FromSigned>
 struct IsExactImpl {
-  static JS_ALWAYS_INLINE bool Test(FromType i, TargetType j) {
+  static MOZ_ALWAYS_INLINE bool Test(FromType i, TargetType j) {
     JS_STATIC_ASSERT(NumericLimits<TargetType>::is_exact);
     return FromType(j) == i;
   }
 };
 
 // Specialization where TargetType is unsigned, FromType is signed.
 template<class TargetType, class FromType>
 struct IsExactImpl<TargetType, FromType, false, true> {
-  static JS_ALWAYS_INLINE bool Test(FromType i, TargetType j) {
+  static MOZ_ALWAYS_INLINE bool Test(FromType i, TargetType j) {
     JS_STATIC_ASSERT(NumericLimits<TargetType>::is_exact);
     return i >= 0 && FromType(j) == i;
   }
 };
 
 // Specialization where TargetType is signed, FromType is unsigned.
 template<class TargetType, class FromType>
 struct IsExactImpl<TargetType, FromType, true, false> {
-  static JS_ALWAYS_INLINE bool Test(FromType i, TargetType j) {
+  static MOZ_ALWAYS_INLINE bool Test(FromType i, TargetType j) {
     JS_STATIC_ASSERT(NumericLimits<TargetType>::is_exact);
     return TargetType(i) >= 0 && FromType(j) == i;
   }
 };
 
 // Convert FromType 'i' to TargetType 'result', returning true iff 'result'
 // is an exact representation of 'i'.
 template<class TargetType, class FromType>
-static JS_ALWAYS_INLINE bool ConvertExact(FromType i, TargetType* result)
+static MOZ_ALWAYS_INLINE bool ConvertExact(FromType i, TargetType* result)
 {
   // Require that TargetType is integral, to simplify conversion.
   JS_STATIC_ASSERT(NumericLimits<TargetType>::is_exact);
 
   *result = Convert<TargetType>(i);
 
   // See if we can avoid a dynamic check.
   if (IsAlwaysExact<TargetType, FromType>())
@@ -1544,32 +1544,32 @@ static JS_ALWAYS_INLINE bool ConvertExac
                      NumericLimits<TargetType>::is_signed,
                      NumericLimits<FromType>::is_signed>::Test(i, *result);
 }
 
 // Templated helper to determine if Type 'i' is negative. Default case
 // where IntegerType is unsigned.
 template<class Type, bool IsSigned>
 struct IsNegativeImpl {
-  static JS_ALWAYS_INLINE bool Test(Type i) {
+  static MOZ_ALWAYS_INLINE bool Test(Type i) {
     return false;
   }
 };
 
 // Specialization where Type is signed.
 template<class Type>
 struct IsNegativeImpl<Type, true> {
-  static JS_ALWAYS_INLINE bool Test(Type i) {
+  static MOZ_ALWAYS_INLINE bool Test(Type i) {
     return i < 0;
   }
 };
 
 // Determine whether Type 'i' is negative.
 template<class Type>
-static JS_ALWAYS_INLINE bool IsNegative(Type i)
+static MOZ_ALWAYS_INLINE bool IsNegative(Type i)
 {
   return IsNegativeImpl<Type, NumericLimits<Type>::is_signed>::Test(i);
 }
 
 // Implicitly convert val to bool, allowing bool, int, and double
 // arguments numerically equal to 0 or 1.
 static bool
 jsvalToBool(JSContext* cx, jsval val, bool* result)
@@ -5400,17 +5400,17 @@ PrepareReturnType(JSContext* cx, jsval t
   }
 
   // libffi cannot pass types of zero size by value.
   JS_ASSERT(typeCode == TYPE_void_t || CType::GetSize(result) != 0);
 
   return result;
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 IsEllipsis(JSContext* cx, jsval v, bool* isEllipsis)
 {
   *isEllipsis = false;
   if (!JSVAL_IS_STRING(v))
     return true;
   JSString* str = JSVAL_TO_STRING(v);
   if (str->length() != 3)
     return true;
--- a/js/src/ctypes/CTypes.h
+++ b/js/src/ctypes/CTypes.h
@@ -166,17 +166,17 @@ bool
 DeflateStringToUTF8Buffer(JSContext *maybecx, const jschar *src, size_t srclen,
                           char *dst, size_t *dstlenp);
 
 
 /*******************************************************************************
 ** Function and struct API definitions
 *******************************************************************************/
 
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 ASSERT_OK(bool ok)
 {
   JS_ASSERT(ok);
 }
 
 // for JS error reporting
 enum ErrorNum {
 #define MSG_DEF(name, number, count, exception, format) \
--- a/js/src/ds/InlineMap.h
+++ b/js/src/ds/InlineMap.h
@@ -67,17 +67,17 @@ class InlineMap
         }
 
         inlNext = InlineElems + 1;
         JS_ASSERT(map.count() == inlCount);
         JS_ASSERT(usingMap());
         return true;
     }
 
-    JS_NEVER_INLINE
+    MOZ_NEVER_INLINE
     bool switchAndAdd(const K &key, const V &value) {
         if (!switchToMap())
             return false;
 
         return map.putNew(key, value);
     }
 
   public:
@@ -209,30 +209,30 @@ class InlineMap
         return inl;
     }
 
     const InlineElem *inlineEnd() const {
         JS_ASSERT(!isMap());
         return inl + inlNext;
     }
 
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     Ptr lookup(const K &key) {
         if (usingMap())
             return Ptr(map.lookup(key));
 
         for (InlineElem *it = inl, *end = inl + inlNext; it != end; ++it) {
             if (it->key == key)
                 return Ptr(it);
         }
 
         return Ptr(nullptr);
     }
 
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     AddPtr lookupForAdd(const K &key) {
         if (usingMap())
             return AddPtr(map.lookupForAdd(key));
 
         for (InlineElem *it = inl, *end = inl + inlNext; it != end; ++it) {
             if (it->key == key)
                 return AddPtr(it, true);
         }
@@ -240,17 +240,17 @@ class InlineMap
         /*
          * The add pointer that's returned here may indicate the limit entry of
          * the linear space, in which case the |add| operation will initialize
          * the map if necessary and add the entry there.
          */
         return AddPtr(inl + inlNext, false);
     }
 
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     bool add(AddPtr &p, const K &key, const V &value) {
         JS_ASSERT(!p);
 
         if (p.isInlinePtr) {
             InlineElem *addPtr = p.inlAddPtr;
             JS_ASSERT(addPtr == inl + inlNext);
 
             /* Switching to map mode before we add this pointer. */
@@ -264,17 +264,17 @@ class InlineMap
             ++inlCount;
             ++inlNext;
             return true;
         }
 
         return map.add(p.mapAddPtr, key, value);
     }
 
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     bool put(const K &key, const V &value) {
         AddPtr p = lookupForAdd(key);
         if (p) {
             p.value() = value;
             return true;
         }
         return add(p, key, value);
     }
--- a/js/src/ds/LifoAlloc.h
+++ b/js/src/ds/LifoAlloc.h
@@ -23,17 +23,17 @@
 #include "jsutil.h"
 
 namespace js {
 
 namespace detail {
 
 static const size_t LIFO_ALLOC_ALIGN = 8;
 
-JS_ALWAYS_INLINE
+MOZ_ALWAYS_INLINE
 char *
 AlignPtr(void *orig)
 {
     static_assert(mozilla::tl::FloorLog2<LIFO_ALLOC_ALIGN>::value ==
                   mozilla::tl::CeilingLog2<LIFO_ALLOC_ALIGN>::value,
                   "LIFO_ALLOC_ALIGN must be a power of two");
 
     char *result = (char *) ((uintptr_t(orig) + (LIFO_ALLOC_ALIGN - 1)) & (~LIFO_ALLOC_ALIGN + 1));
@@ -119,26 +119,26 @@ class BumpChunk
 
     bool canAlloc(size_t n);
 
     size_t unused() {
         return limit - AlignPtr(bump);
     }
 
     // Try to perform an allocation of size |n|, return null if not possible.
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     void *tryAlloc(size_t n) {
         char *aligned = AlignPtr(bump);
         char *newBump = aligned + n;
 
         if (newBump > limit)
             return nullptr;
 
         // Check for overflow.
-        if (JS_UNLIKELY(newBump < bump))
+        if (MOZ_UNLIKELY(newBump < bump))
             return nullptr;
 
         JS_ASSERT(canAlloc(n)); // Ensure consistency between "can" and "try".
         setBump(newBump);
         return aligned;
     }
 
     void *allocInfallible(size_t n) {
@@ -253,46 +253,46 @@ class LifoAlloc
     void freeAll();
 
     static const unsigned HUGE_ALLOCATION = 50 * 1024 * 1024;
     void freeAllIfHugeAndUnused() {
         if (markCount == 0 && curSize_ > HUGE_ALLOCATION)
             freeAll();
     }
 
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     void *alloc(size_t n) {
         JS_OOM_POSSIBLY_FAIL();
 
         void *result;
         if (latest && (result = latest->tryAlloc(n)))
             return result;
 
         if (!getOrCreateChunk(n))
             return nullptr;
 
         return latest->allocInfallible(n);
     }
 
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     void *allocInfallible(size_t n) {
         void *result;
         if (latest && (result = latest->tryAlloc(n)))
             return result;
 
         mozilla::DebugOnly<BumpChunk *> chunk = getOrCreateChunk(n);
         JS_ASSERT(chunk);
 
         return latest->allocInfallible(n);
     }
 
     // Ensures that enough space exists to satisfy N bytes worth of
     // allocation requests, not necessarily contiguous. Note that this does
     // not guarantee a successful single allocation of N bytes.
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     bool ensureUnusedApproximate(size_t n) {
         size_t total = 0;
         for (BumpChunk *chunk = latest; chunk; chunk = chunk->next()) {
             total += chunk->unused();
             if (total >= n)
                 return true;
         }
         BumpChunk *latestBefore = latest;
@@ -389,22 +389,22 @@ class LifoAlloc
     }
 
     // Get the peak size of the arena chunks (including unused space and
     // bookkeeping space).
     size_t peakSizeOfExcludingThis() const { return peakSize_; }
 
     // Doesn't perform construction; useful for lazily-initialized POD types.
     template <typename T>
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     T *newPod() {
         return static_cast<T *>(alloc(sizeof(T)));
     }
 
-    JS_DECLARE_NEW_METHODS(new_, alloc, JS_ALWAYS_INLINE)
+    JS_DECLARE_NEW_METHODS(new_, alloc, MOZ_ALWAYS_INLINE)
 
     // A mutable enumeration of the allocated data.
     class Enum
     {
         friend class LifoAlloc;
         friend class detail::BumpChunk;
 
         LifoAlloc *alloc_;  // The LifoAlloc being traversed.
--- a/js/src/ds/Sort.h
+++ b/js/src/ds/Sort.h
@@ -9,29 +9,29 @@
 
 #include "jstypes.h"
 
 namespace js {
 
 namespace detail {
 
 template<typename T>
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 CopyNonEmptyArray(T *dst, const T *src, size_t nelems)
 {
     JS_ASSERT(nelems != 0);
     const T *end = src + nelems;
     do {
         *dst++ = *src++;
     } while (src != end);
 }
 
 /* Helper function for MergeSort. */
 template<typename T, typename Comparator>
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 MergeArrayRuns(T *dst, const T *src, size_t run1, size_t run2, Comparator c)
 {
     JS_ASSERT(run1 >= 1);
     JS_ASSERT(run2 >= 1);
 
     /* Copy runs already in sorted order. */
     const T *b = src + run1;
     bool lessOrEqual;
--- a/js/src/frontend/BytecodeEmitter.cpp
+++ b/js/src/frontend/BytecodeEmitter.cpp
@@ -4818,17 +4818,17 @@ EmitFor(ExclusiveContext *cx, BytecodeEm
 
     if (pn->pn_left->isKind(PNK_FOROF))
         return EmitForOf(cx, bce, pn, top);
 
     JS_ASSERT(pn->pn_left->isKind(PNK_FORHEAD));
     return EmitNormalFor(cx, bce, pn, top);
 }
 
-static JS_NEVER_INLINE bool
+static MOZ_NEVER_INLINE bool
 EmitFunc(ExclusiveContext *cx, BytecodeEmitter *bce, ParseNode *pn)
 {
     FunctionBox *funbox = pn->pn_funbox;
     RootedFunction fun(cx, funbox->function());
     JS_ASSERT_IF(fun->isInterpretedLazy(), fun->lazyScript());
 
     /*
      * Set the EMITTEDFUNCTION flag in function definitions once they have been
--- a/js/src/frontend/BytecodeEmitter.h
+++ b/js/src/frontend/BytecodeEmitter.h
@@ -174,17 +174,17 @@ struct BytecodeEmitter
      */
     BytecodeEmitter(BytecodeEmitter *parent, Parser<FullParseHandler> *parser, SharedContext *sc,
                     HandleScript script, bool insideEval, HandleScript evalCaller,
                     bool hasGlobalScope, uint32_t lineNum, EmitterMode emitterMode = Normal);
     bool init();
 
     bool isAliasedName(ParseNode *pn);
 
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     bool makeAtomIndex(JSAtom *atom, jsatomid *indexp) {
         AtomIndexAddPtr p = atomIndices->lookupForAdd(atom);
         if (p) {
             *indexp = p.value();
             return true;
         }
 
         jsatomid index = atomIndices->count();
--- a/js/src/frontend/ParseMaps.h
+++ b/js/src/frontend/ParseMaps.h
@@ -197,17 +197,17 @@ class DefinitionSingle
     typename ParseHandler::DefinitionNode get() {
         return ParseHandler::definitionFromBits(bits);
     }
 };
 
 struct AtomDefnMapPtr : public AtomThingMapPtr<AtomDefnMap>
 {
     template <typename ParseHandler>
-    JS_ALWAYS_INLINE
+    MOZ_ALWAYS_INLINE
     typename ParseHandler::DefinitionNode lookupDefn(JSAtom *atom) {
         AtomDefnMap::Ptr p = map_->lookup(atom);
         return p ? p.value().get<ParseHandler>() : ParseHandler::nullDefinition();
     }
 };
 
 typedef OwnedAtomThingMapPtr<AtomDefnMapPtr> OwnedAtomDefnMapPtr;
 
--- a/js/src/frontend/Parser.cpp
+++ b/js/src/frontend/Parser.cpp
@@ -5396,17 +5396,17 @@ Precedence(ParseNodeKind pnk) {
         return 0;
 
     JS_ASSERT(pnk >= PNK_BINOP_FIRST);
     JS_ASSERT(pnk <= PNK_BINOP_LAST);
     return PrecedenceTable[pnk - PNK_BINOP_FIRST];
 }
 
 template <typename ParseHandler>
-JS_ALWAYS_INLINE typename ParseHandler::Node
+MOZ_ALWAYS_INLINE typename ParseHandler::Node
 Parser<ParseHandler>::orExpr1()
 {
     // Shift-reduce parser for the left-associative binary operator part of
     // the JS syntax.
 
     // Conceptually there's just one stack, a stack of pairs (lhs, op).
     // It's implemented using two separate arrays, though.
     Node nodeStack[PRECEDENCE_CLASSES];
@@ -5462,17 +5462,17 @@ Parser<ParseHandler>::orExpr1()
     }
 
     JS_ASSERT(depth == 0);
     pc->parsingForInit = oldParsingForInit;
     return pn;
 }
 
 template <typename ParseHandler>
-JS_ALWAYS_INLINE typename ParseHandler::Node
+MOZ_ALWAYS_INLINE typename ParseHandler::Node
 Parser<ParseHandler>::condExpr1()
 {
     Node condition = orExpr1();
     if (!condition || !tokenStream.isCurrentTokenType(TOK_HOOK))
         return condition;
 
     /*
      * Always accept the 'in' operator in the middle clause of a ternary,
--- a/js/src/frontend/TokenStream.cpp
+++ b/js/src/frontend/TokenStream.cpp
@@ -129,17 +129,17 @@ TokenStream::SourceCoords::SourceCoords(
     // appends cannot fail because |lineStartOffsets_| has statically-allocated
     // elements.
     JS_ASSERT(lineStartOffsets_.capacity() >= 2);
     (void)lineStartOffsets_.reserve(2);
     lineStartOffsets_.infallibleAppend(0);
     lineStartOffsets_.infallibleAppend(maxPtr);
 }
 
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 TokenStream::SourceCoords::add(uint32_t lineNum, uint32_t lineStartOffset)
 {
     uint32_t lineIndex = lineNumToIndex(lineNum);
     uint32_t sentinelIndex = lineStartOffsets_.length() - 1;
 
     JS_ASSERT(lineStartOffsets_[0] == 0 && lineStartOffsets_[sentinelIndex] == MAX_PTR);
 
     if (lineIndex == sentinelIndex) {
@@ -155,33 +155,33 @@ TokenStream::SourceCoords::add(uint32_t 
 
     } else {
         // We have seen this newline before (and ungot it).  Do nothing (other
         // than checking it hasn't mysteriously changed).
         JS_ASSERT(lineStartOffsets_[lineIndex] == lineStartOffset);
     }
 }
 
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 TokenStream::SourceCoords::fill(const TokenStream::SourceCoords &other)
 {
     JS_ASSERT(lineStartOffsets_.back() == MAX_PTR);
     JS_ASSERT(other.lineStartOffsets_.back() == MAX_PTR);
 
     if (lineStartOffsets_.length() >= other.lineStartOffsets_.length())
         return;
 
     uint32_t sentinelIndex = lineStartOffsets_.length() - 1;
     lineStartOffsets_[sentinelIndex] = other.lineStartOffsets_[sentinelIndex];
 
     for (size_t i = sentinelIndex + 1; i < other.lineStartOffsets_.length(); i++)
         (void)lineStartOffsets_.append(other.lineStartOffsets_[i]);
 }
 
-JS_ALWAYS_INLINE uint32_t
+MOZ_ALWAYS_INLINE uint32_t
 TokenStream::SourceCoords::lineIndexOf(uint32_t offset) const
 {
     uint32_t iMin, iMax, iMid;
 
     if (lineStartOffsets_[lastLineIndex_] <= offset) {
         // If we reach here, offset is on a line the same as or higher than
         // last time.  Check first for the +0, +1, +2 cases, because they
         // typically cover 85--98% of cases.
@@ -343,53 +343,53 @@ TokenStream::~TokenStream()
 #if defined(HAVE_GETC_UNLOCKED)
 # define fast_getc getc_unlocked
 #elif defined(HAVE__GETC_NOLOCK)
 # define fast_getc _getc_nolock
 #else
 # define fast_getc getc
 #endif
 
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 TokenStream::updateLineInfoForEOL()
 {
     prevLinebase = linebase;
     linebase = userbuf.addressOfNextRawChar();
     lineno++;
     srcCoords.add(lineno, linebase - userbuf.base());
 }
 
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 TokenStream::updateFlagsForEOL()
 {
     flags.isDirtyLine = false;
 }
 
 // This gets the next char, normalizing all EOL sequences to '\n' as it goes.
 int32_t
 TokenStream::getChar()
 {
     int32_t c;
-    if (JS_LIKELY(userbuf.hasRawChars())) {
+    if (MOZ_LIKELY(userbuf.hasRawChars())) {
         c = userbuf.getRawChar();
 
         // Normalize the jschar if it was a newline.  We need to detect any of
         // these four characters:  '\n' (0x000a), '\r' (0x000d),
         // LINE_SEPARATOR (0x2028), PARA_SEPARATOR (0x2029).  Testing for each
         // one in turn is slow, so we use a single probabilistic check, and if
         // that succeeds, test for them individually.
         //
         // We use the bottom 8 bits to index into a lookup table, succeeding
         // when d&0xff is 0xa, 0xd, 0x28 or 0x29.  Among ASCII chars (which
         // are by the far the most common) this gives false positives for '('
         // (0x0028) and ')' (0x0029).  We could avoid those by incorporating
         // the 13th bit of d into the lookup, but that requires extra shifting
         // and masking and isn't worthwhile.  See TokenStream::TokenStream()
         // for the initialization of the relevant entries in the table.
-        if (JS_UNLIKELY(maybeEOL[c & 0xff])) {
+        if (MOZ_UNLIKELY(maybeEOL[c & 0xff])) {
             if (c == '\n')
                 goto eol;
             if (c == '\r') {
                 // If it's a \r\n sequence: treat as a single EOL, skip over the \n.
                 if (userbuf.hasRawChars())
                     userbuf.matchRawChar('\n');
                 goto eol;
             }
@@ -410,17 +410,17 @@ TokenStream::getChar()
 // This gets the next char. It does nothing special with EOL sequences, not
 // even updating the line counters.  It can be used safely if (a) the
 // resulting char is guaranteed to be ungotten (by ungetCharIgnoreEOL()) if
 // it's an EOL, and (b) the line-related state (lineno, linebase) is not used
 // before it's ungotten.
 int32_t
 TokenStream::getCharIgnoreEOL()
 {
-    if (JS_LIKELY(userbuf.hasRawChars()))
+    if (MOZ_LIKELY(userbuf.hasRawChars()))
         return userbuf.getRawChar();
 
     flags.isEOF = true;
     return EOF;
 }
 
 void
 TokenStream::ungetChar(int32_t c)
@@ -883,30 +883,30 @@ TokenStream::getSourceMappingURL(bool is
 {
     // Match comments of the form "//# sourceMappingURL=<url>" or
     // "/\* //# sourceMappingURL=<url> *\/"
 
     return getDirective(isMultiline, shouldWarnDeprecated, " sourceMappingURL=", 18,
                         "sourceMappingURL", &sourceMapURL_);
 }
 
-JS_ALWAYS_INLINE Token *
+MOZ_ALWAYS_INLINE Token *
 TokenStream::newToken(ptrdiff_t adjust)
 {
     cursor = (cursor + 1) & ntokensMask;
     Token *tp = &tokens[cursor];
     tp->pos.begin = userbuf.addressOfNextRawChar() + adjust - userbuf.base();
 
     // NOTE: tp->pos.end is not set until the very end of getTokenInternal().
     MOZ_MAKE_MEM_UNDEFINED(&tp->pos.end, sizeof(tp->pos.end));
 
     return tp;
 }
 
-JS_ALWAYS_INLINE JSAtom *
+MOZ_ALWAYS_INLINE JSAtom *
 TokenStream::atomize(ExclusiveContext *cx, CharBuffer &cb)
 {
     return AtomizeChars(cx, cb.begin(), cb.length());
 }
 
 #ifdef DEBUG
 static bool
 IsTokenSane(Token *tp)
@@ -1053,29 +1053,29 @@ TokenStream::getTokenInternal(Modifier m
     FirstCharKind c1kind;
     const jschar *numStart;
     bool hasExp;
     DecimalPoint decimalPoint;
     const jschar *identStart;
     bool hadUnicodeEscape;
 
   retry:
-    if (JS_UNLIKELY(!userbuf.hasRawChars())) {
+    if (MOZ_UNLIKELY(!userbuf.hasRawChars())) {
         tp = newToken(0);
         tp->type = TOK_EOF;
         flags.isEOF = true;
         goto out;
     }
 
     c = userbuf.getRawChar();
     JS_ASSERT(c != EOF);
 
     // Chars not in the range 0..127 are rare.  Getting them out of the way
     // early allows subsequent checking to be faster.
-    if (JS_UNLIKELY(c >= 128)) {
+    if (MOZ_UNLIKELY(c >= 128)) {
         if (IsSpaceOrBOM2(c)) {
             if (c == LINE_SEPARATOR || c == PARA_SEPARATOR) {
                 updateLineInfoForEOL();
                 updateFlagsForEOL();
             }
 
             goto retry;
         }
--- a/js/src/frontend/TokenStream.h
+++ b/js/src/frontend/TokenStream.h
@@ -534,17 +534,17 @@ class MOZ_STACK_CLASS TokenStream
         return tokens[(cursor + 1) & ntokensMask].pos;
     }
 
     // This is like peekToken(), with one exception:  if there is an EOL
     // between the end of the current token and the start of the next token, it
     // returns TOK_EOL.  In that case, no token with TOK_EOL is actually
     // created, just a TOK_EOL TokenKind is returned, and currentToken()
     // shouldn't be consulted.  (This is the only place TOK_EOL is produced.)
-    JS_ALWAYS_INLINE TokenKind peekTokenSameLine(Modifier modifier = None) {
+    MOZ_ALWAYS_INLINE TokenKind peekTokenSameLine(Modifier modifier = None) {
        const Token &curr = currentToken();
 
         // If lookahead != 0, we have scanned ahead at least one token, and
         // |lineno| is the line that the furthest-scanned token ends on.  If
         // it's the same as the line that the current token ends on, that's a
         // stronger condition than what we are looking for, and we don't need
         // to return TOK_EOL.
         if (lookahead != 0 && srcCoords.isOnThisLine(curr.pos.end, lineno))
@@ -849,17 +849,17 @@ class MOZ_STACK_CLASS TokenStream
                       const char *directive, int directiveLength,
                       const char *errorMsgPragma, jschar **destination);
     bool getDisplayURL(bool isMultiline, bool shouldWarnDeprecated);
     bool getSourceMappingURL(bool isMultiline, bool shouldWarnDeprecated);
 
     // |expect| cannot be an EOL char.
     bool matchChar(int32_t expect) {
         MOZ_ASSERT(!TokenBuf::isRawEOLChar(expect));
-        return JS_LIKELY(userbuf.hasRawChars()) &&
+        return MOZ_LIKELY(userbuf.hasRawChars()) &&
                userbuf.matchRawChar(expect);
     }
 
     void consumeKnownChar(int32_t expect) {
         mozilla::DebugOnly<int32_t> c = getChar();
         JS_ASSERT(c == expect);
     }
 
--- a/js/src/gc/Barrier.h
+++ b/js/src/gc/Barrier.h
@@ -177,49 +177,49 @@ void
 MarkStringUnbarriered(JSTracer *trc, JSString **str, const char *name);
 
 // Note that some subclasses (e.g. ObjectImpl) specialize some of these
 // methods.
 template <typename T>
 class BarrieredCell : public gc::Cell
 {
   public:
-    JS_ALWAYS_INLINE JS::Zone *zone() const { return tenuredZone(); }
-    JS_ALWAYS_INLINE JS::shadow::Zone *shadowZone() const { return JS::shadow::Zone::asShadowZone(zone()); }
-    JS_ALWAYS_INLINE JS::Zone *zoneFromAnyThread() const { return tenuredZoneFromAnyThread(); }
-    JS_ALWAYS_INLINE JS::shadow::Zone *shadowZoneFromAnyThread() const {
+    MOZ_ALWAYS_INLINE JS::Zone *zone() const { return tenuredZone(); }
+    MOZ_ALWAYS_INLINE JS::shadow::Zone *shadowZone() const { return JS::shadow::Zone::asShadowZone(zone()); }
+    MOZ_ALWAYS_INLINE JS::Zone *zoneFromAnyThread() const { return tenuredZoneFromAnyThread(); }
+    MOZ_ALWAYS_INLINE JS::shadow::Zone *shadowZoneFromAnyThread() const {
         return JS::shadow::Zone::asShadowZone(zoneFromAnyThread());
     }
 
-    static JS_ALWAYS_INLINE void readBarrier(T *thing) {
+    static MOZ_ALWAYS_INLINE void readBarrier(T *thing) {
 #ifdef JSGC_INCREMENTAL
         // Off thread Ion compilation never occurs when barriers are active.
         js::AutoThreadSafeAccess ts(thing);
 
         JS::shadow::Zone *shadowZone = thing->shadowZoneFromAnyThread();
         if (shadowZone->needsBarrier()) {
             MOZ_ASSERT(!RuntimeFromMainThreadIsHeapMajorCollecting(shadowZone));
             T *tmp = thing;
             js::gc::MarkUnbarriered<T>(shadowZone->barrierTracer(), &tmp, "read barrier");
             JS_ASSERT(tmp == thing);
         }
 #endif
     }
 
-    static JS_ALWAYS_INLINE bool needWriteBarrierPre(JS::Zone *zone) {
+    static MOZ_ALWAYS_INLINE bool needWriteBarrierPre(JS::Zone *zone) {
 #ifdef JSGC_INCREMENTAL
         return JS::shadow::Zone::asShadowZone(zone)->needsBarrier();
 #else
         return false;
 #endif
     }
 
-    static JS_ALWAYS_INLINE bool isNullLike(T *thing) { return !thing; }
+    static MOZ_ALWAYS_INLINE bool isNullLike(T *thing) { return !thing; }
 
-    static JS_ALWAYS_INLINE void writeBarrierPre(T *thing) {
+    static MOZ_ALWAYS_INLINE void writeBarrierPre(T *thing) {
 #ifdef JSGC_INCREMENTAL
         if (isNullLike(thing) || !thing->shadowRuntimeFromAnyThread()->needsBarrier())
             return;
 
         JS::shadow::Zone *shadowZone = thing->shadowZoneFromAnyThread();
         if (shadowZone->needsBarrier()) {
             MOZ_ASSERT(!RuntimeFromMainThreadIsHeapMajorCollecting(shadowZone));
             T *tmp = thing;
@@ -249,17 +249,17 @@ ShadowZoneOfObject(JSObject *obj)
 }
 
 static inline JS::shadow::Zone *
 ShadowZoneOfString(JSString *str)
 {
     return JS::shadow::Zone::asShadowZone(reinterpret_cast<const js::gc::Cell *>(str)->tenuredZone());
 }
 
-JS_ALWAYS_INLINE JS::Zone *
+MOZ_ALWAYS_INLINE JS::Zone *
 ZoneOfValue(const JS::Value &value)
 {
     JS_ASSERT(value.isMarkable());
     if (value.isObject())
         return ZoneOfObject(value.toObject());
     return static_cast<js::gc::Cell *>(value.toGCThing())->tenuredZone();
 }
 
@@ -274,17 +274,17 @@ ShadowZoneOfObjectFromAnyThread(JSObject
 
 static inline JS::shadow::Zone *
 ShadowZoneOfStringFromAnyThread(JSString *str)
 {
     return JS::shadow::Zone::asShadowZone(
         reinterpret_cast<const js::gc::Cell *>(str)->tenuredZoneFromAnyThread());
 }
 
-JS_ALWAYS_INLINE JS::Zone *
+MOZ_ALWAYS_INLINE JS::Zone *
 ZoneOfValueFromAnyThread(const JS::Value &value)
 {
     JS_ASSERT(value.isMarkable());
     if (value.isObject())
         return ZoneOfObjectFromAnyThread(value.toObject());
     return static_cast<js::gc::Cell *>(value.toGCThing())->tenuredZoneFromAnyThread();
 }
 
--- a/js/src/gc/Heap.h
+++ b/js/src/gc/Heap.h
@@ -271,19 +271,19 @@ struct FreeSpan
     /* See comments before FreeSpan for details. */
     MOZ_ALWAYS_INLINE void *allocate(size_t thingSize) {
         JS_ASSERT(thingSize % CellSize == 0);
         checkSpan();
         uintptr_t thing = first;
         if (thing < last) {
             /* Bump-allocate from the current span. */
             first = thing + thingSize;
-        } else if (JS_LIKELY(thing == last)) {
+        } else if (MOZ_LIKELY(thing == last)) {
             /*
-             * Move to the next span. We use JS_LIKELY as without PGO
+             * Move to the next span. We use MOZ_LIKELY as without PGO
              * compilers mis-predict == here as unlikely to succeed.
              */
             *this = *reinterpret_cast<FreeSpan *>(thing);
         } else {
             return nullptr;
         }
         checkSpan();
         return reinterpret_cast<void *>(thing);
--- a/js/src/gc/Marking.cpp
+++ b/js/src/gc/Marking.cpp
@@ -460,17 +460,17 @@ gc::MarkGCThingUnbarriered(JSTracer *trc
 static inline void
 MarkIdInternal(JSTracer *trc, jsid *id)
 {
     if (JSID_IS_STRING(*id)) {
         JSString *str = JSID_TO_STRING(*id);
         JS_SET_TRACING_LOCATION(trc, (void *)id);
         MarkInternal(trc, &str);
         *id = NON_INTEGER_ATOM_TO_JSID(reinterpret_cast<JSAtom *>(str));
-    } else if (JS_UNLIKELY(JSID_IS_OBJECT(*id))) {
+    } else if (MOZ_UNLIKELY(JSID_IS_OBJECT(*id))) {
         JSObject *obj = JSID_TO_OBJECT(*id);
         JS_SET_TRACING_LOCATION(trc, (void *)id);
         MarkInternal(trc, &obj);
         *id = OBJECT_TO_JSID(obj);
     } else {
         /* Unset realLocation manually if we do not call MarkInternal. */
         JS_UNSET_TRACING_LOCATION(trc);
     }
@@ -876,17 +876,17 @@ static void
 ScanShape(GCMarker *gcmarker, Shape *shape)
 {
   restart:
     PushMarkStack(gcmarker, shape->base());
 
     const BarrieredId &id = shape->propidRef();
     if (JSID_IS_STRING(id))
         PushMarkStack(gcmarker, JSID_TO_STRING(id));
-    else if (JS_UNLIKELY(JSID_IS_OBJECT(id)))
+    else if (MOZ_UNLIKELY(JSID_IS_OBJECT(id)))
         PushMarkStack(gcmarker, JSID_TO_OBJECT(id));
 
     shape = shape->previous();
     if (shape && shape->markIfUnmarked(gcmarker->getMarkColor()))
         goto restart;
 }
 
 static inline void
--- a/js/src/gc/Marking.h
+++ b/js/src/gc/Marking.h
@@ -112,17 +112,17 @@ DeclMarker(String, JSLinearString)
 DeclMarker(String, PropertyName)
 DeclMarker(TypeObject, types::TypeObject)
 
 #undef DeclMarker
 
 /* Return true if the pointer is nullptr, or if it is a tagged pointer to
  * nullptr.
  */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 IsNullTaggedPointer(void *p)
 {
     return uintptr_t(p) < 32;
 }
 
 /*** Externally Typed Marking ***/
 
 /*
--- a/js/src/gc/Nursery-inl.h
+++ b/js/src/gc/Nursery-inl.h
@@ -63,17 +63,17 @@ class RelocationOverlay
         return next_;
     }
 };
 
 } /* namespace gc */
 } /* namespace js */
 
 template <typename T>
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 js::Nursery::getForwardedPointer(T **ref)
 {
     JS_ASSERT(ref);
     JS_ASSERT(isInside(*ref));
     const gc::RelocationOverlay *overlay = reinterpret_cast<const gc::RelocationOverlay *>(*ref);
     if (!overlay->isForwarded())
         return false;
     /* This static cast from Cell* restricts T to valid (GC thing) types. */
--- a/js/src/gc/Nursery.cpp
+++ b/js/src/gc/Nursery.cpp
@@ -285,17 +285,17 @@ class MinorCollectionTracer : public JST
     RelocationOverlay **tail;
 
     /* Save and restore all of the runtime state we use during MinorGC. */
     bool savedRuntimeNeedBarrier;
     AutoDisableProxyCheck disableStrictProxyChecking;
     AutoEnterOOMUnsafeRegion oomUnsafeRegion;
 
     /* Insert the given relocation entry into the list of things to visit. */
-    JS_ALWAYS_INLINE void insertIntoFixupList(RelocationOverlay *entry) {
+    MOZ_ALWAYS_INLINE void insertIntoFixupList(RelocationOverlay *entry) {
         *tail = entry;
         tail = &entry->next_;
         *tail = nullptr;
     }
 
     MinorCollectionTracer(JSRuntime *rt, Nursery *nursery)
       : JSTracer(),
         nursery(nursery),
@@ -450,17 +450,17 @@ js::Nursery::collectToFixedPoint(MinorCo
             entry.count++;
         } else if (!entry.type) {
             entry.type = obj->type();
             entry.count = 1;
         }
     }
 }
 
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 js::Nursery::traceObject(MinorCollectionTracer *trc, JSObject *obj)
 {
     const Class *clasp = obj->getClass();
     if (clasp->trace)
         clasp->trace(trc, obj);
 
     if (!obj->isNative())
         return;
@@ -469,30 +469,30 @@ js::Nursery::traceObject(MinorCollection
         markSlots(trc, obj->getDenseElements(), obj->getDenseInitializedLength());
 
     HeapSlot *fixedStart, *fixedEnd, *dynStart, *dynEnd;
     obj->getSlotRange(0, obj->slotSpan(), &fixedStart, &fixedEnd, &dynStart, &dynEnd);
     markSlots(trc, fixedStart, fixedEnd);
     markSlots(trc, dynStart, dynEnd);
 }
 
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 js::Nursery::markSlots(MinorCollectionTracer *trc, HeapSlot *vp, uint32_t nslots)
 {
     markSlots(trc, vp, vp + nslots);
 }
 
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 js::Nursery::markSlots(MinorCollectionTracer *trc, HeapSlot *vp, HeapSlot *end)
 {
     for (; vp != end; ++vp)
         markSlot(trc, vp);
 }
 
-JS_ALWAYS_INLINE void
+MOZ_ALWAYS_INLINE void
 js::Nursery::markSlot(MinorCollectionTracer *trc, HeapSlot *slotp)
 {
     if (!slotp->isObject())
         return;
 
     JSObject *obj = &slotp->toObject();
     if (!isInside(obj))
         return;
--- a/js/src/gc/Nursery.h
+++ b/js/src/gc/Nursery.h
@@ -69,17 +69,17 @@ class Nursery
     void enable();
     void disable();
     bool isEnabled() const { return numActiveChunks_ != 0; }
 
     /* Return true if no allocations have been made since the last collection. */
     bool isEmpty() const;
 
     template <typename T>
-    JS_ALWAYS_INLINE bool isInside(const T *p) const {
+    MOZ_ALWAYS_INLINE bool isInside(const T *p) const {
         return gc::IsInsideNursery((JS::shadow::Runtime *)runtime_, p);
     }
 
     /*
      * Allocate and return a pointer to a new GC thing. Returns nullptr if the
      * Nursery is full.
      */
     void *allocate(size_t size);
@@ -119,17 +119,17 @@ class Nursery
     void collect(JSRuntime *rt, JS::gcreason::Reason reason, TypeObjectList *pretenureTypes);
 
     /*
      * Check if the thing at |*ref| in the Nursery has been forwarded. If so,
      * sets |*ref| to the new location of the object and returns true. Otherwise
      * returns false and leaves |*ref| unset.
      */
     template <typename T>
-    JS_ALWAYS_INLINE bool getForwardedPointer(T **ref);
+    MOZ_ALWAYS_INLINE bool getForwardedPointer(T **ref);
 
     /* Forward a slots/elements pointer stored in an Ion frame. */
     void forwardBufferPointer(HeapSlot **pSlotsElems);
 
     size_t sizeOfHeap() { return start() ? NurserySize : 0; }
 
 #ifdef JS_GC_ZEAL
     /*
@@ -197,45 +197,45 @@ class Nursery
     static_assert(sizeof(NurseryChunkLayout) == gc::ChunkSize,
                   "Nursery chunk size must match gc::Chunk size.");
     NurseryChunkLayout &chunk(int index) const {
         JS_ASSERT(index < NumNurseryChunks);
         JS_ASSERT(start());
         return reinterpret_cast<NurseryChunkLayout *>(start())[index];
     }
 
-    JS_ALWAYS_INLINE uintptr_t start() const {
+    MOZ_ALWAYS_INLINE uintptr_t start() const {
         JS_ASSERT(runtime_);
         return ((JS::shadow::Runtime *)runtime_)->gcNurseryStart_;
     }
 
-    JS_ALWAYS_INLINE uintptr_t heapEnd() const {
+    MOZ_ALWAYS_INLINE uintptr_t heapEnd() const {
         JS_ASSERT(runtime_);
         return ((JS::shadow::Runtime *)runtime_)->gcNurseryEnd_;
     }
 
-    JS_ALWAYS_INLINE void setCurrentChunk(int chunkno) {
+    MOZ_ALWAYS_INLINE void setCurrentChunk(int chunkno) {
         JS_ASSERT(chunkno < NumNurseryChunks);
         JS_ASSERT(chunkno < numActiveChunks_);
         currentChunk_ = chunkno;
         position_ = chunk(chunkno).start();
         currentStart_ = chunk(0).start();
         currentEnd_ = chunk(chunkno).end();
     }
 
-    JS_ALWAYS_INLINE uintptr_t allocationEnd() const {
+    MOZ_ALWAYS_INLINE uintptr_t allocationEnd() const {
         JS_ASSERT(numActiveChunks_ > 0);
         return chunk(numActiveChunks_ - 1).end();
     }
 
-    JS_ALWAYS_INLINE bool isFullyGrown() const {
+    MOZ_ALWAYS_INLINE bool isFullyGrown() const {
         return numActiveChunks_ == NumNurseryChunks;
     }
 
-    JS_ALWAYS_INLINE uintptr_t currentEnd() const {
+    MOZ_ALWAYS_INLINE uintptr_t currentEnd() const {
         JS_ASSERT(runtime_);
         JS_ASSERT(currentEnd_ == chunk(currentChunk_).end());
         return currentEnd_;
     }
     void *addressOfCurrentEnd() const {
         JS_ASSERT(runtime_);
         return (void *)&currentEnd_;
     }
@@ -253,20 +253,20 @@ class Nursery
 
     struct TenureCountCache;
 
     /*
      * Move the object at |src| in the Nursery to an already-allocated cell
      * |dst| in Tenured.
      */
     void collectToFixedPoint(gc::MinorCollectionTracer *trc, TenureCountCache &tenureCounts);
-    JS_ALWAYS_INLINE void traceObject(gc::MinorCollectionTracer *trc, JSObject *src);
-    JS_ALWAYS_INLINE void markSlots(gc::MinorCollectionTracer *trc, HeapSlot *vp, uint32_t nslots);
-    JS_ALWAYS_INLINE void markSlots(gc::MinorCollectionTracer *trc, HeapSlot *vp, HeapSlot *end);
-    JS_ALWAYS_INLINE void markSlot(gc::MinorCollectionTracer *trc, HeapSlot *slotp);
+    MOZ_ALWAYS_INLINE void traceObject(gc::MinorCollectionTracer *trc, JSObject *src);
+    MOZ_ALWAYS_INLINE void markSlots(gc::MinorCollectionTracer *trc, HeapSlot *vp, uint32_t nslots);
+    MOZ_ALWAYS_INLINE void markSlots(gc::MinorCollectionTracer *trc, HeapSlot *vp, HeapSlot *end);
+    MOZ_ALWAYS_INLINE void markSlot(gc::MinorCollectionTracer *trc, HeapSlot *slotp);
     void *moveToTenured(gc::MinorCollectionTracer *trc, JSObject *src);
     size_t moveObjectToTenured(JSObject *dst, JSObject *src, gc::AllocKind dstKind);
     size_t moveElementsToTenured(JSObject *dst, JSObject *src, gc::AllocKind dstKind);
     size_t moveSlotsToTenured(JSObject *dst, JSObject *src, gc::AllocKind dstKind);
 
     /* Handle relocation of slots/elements pointers stored in Ion frames. */
     void setSlotsForwardingPointer(HeapSlot *oldSlots, HeapSlot *newSlots, uint32_t nslots);
     void setElementsForwardingPointer(ObjectElements *oldHeader, ObjectElements *newHeader,
--- a/js/src/gc/RootMarking.cpp
+++ b/js/src/gc/RootMarking.cpp
@@ -290,17 +290,17 @@ MarkRangeConservativelyAndSkipIon(JSTrac
         i = jitEnd;
     }
 #endif
 
     // Mark everything after the most recent Ion activation.
     MarkRangeConservatively(trc, i, end);
 }
 
-static JS_NEVER_INLINE void
+static MOZ_NEVER_INLINE void
 MarkConservativeStackRoots(JSTracer *trc, bool useSavedRoots)
 {
     JSRuntime *rt = trc->runtime;
 
 #ifdef DEBUG
     if (useSavedRoots) {
         for (PerThreadData::SavedGCRoot *root = rt->mainThread.gcSavedRoots.begin();
              root != rt->mainThread.gcSavedRoots.end();
@@ -354,17 +354,17 @@ js::MarkStackRangeConservatively(JSTrace
     JS_ASSERT(begin <= end);
     for (const uintptr_t *i = begin; i < end; i += sizeof(Value) / sizeof(uintptr_t))
         MarkWordConservatively(trc, *i);
 #else
     MarkRangeConservatively(trc, begin, end);
 #endif
 }
 
-JS_NEVER_INLINE void
+MOZ_NEVER_INLINE void
 ConservativeGCData::recordStackTop()
 {
     /* Update the native stack pointer if it points to a bigger stack. */
     uintptr_t dummy;
     nativeStackTop = &dummy;
 
     /*
      * To record and update the register snapshot for the conservative scanning
--- a/js/src/gc/StoreBuffer.cpp
+++ b/js/src/gc/StoreBuffer.cpp
@@ -16,49 +16,49 @@
 #include "jsgcinlines.h"
 
 using namespace js;
 using namespace js::gc;
 using mozilla::ReentrancyGuard;
 
 /*** SlotEdge ***/
 
-JS_ALWAYS_INLINE HeapSlot *
+MOZ_ALWAYS_INLINE HeapSlot *
 StoreBuffer::SlotEdge::slotLocation() const
 {
     if (kind == HeapSlot::Element) {
         if (offset >= object->getDenseInitializedLength())
             return nullptr;
         return (HeapSlot *)&object->getDenseElement(offset);
     }
     if (offset >= object->slotSpan())
         return nullptr;
     return &object->getSlotRef(offset);
 }
 
-JS_ALWAYS_INLINE void *
+MOZ_ALWAYS_INLINE void *
 StoreBuffer::SlotEdge::deref() const
 {
     HeapSlot *loc = slotLocation();
     return (loc && loc->isGCThing()) ? loc->toGCThing() : nullptr;
 }
 
-JS_ALWAYS_INLINE void *
+MOZ_ALWAYS_INLINE void *
 StoreBuffer::SlotEdge::location() const
 {
     return (void *)slotLocation();
 }
 
 bool
 StoreBuffer::SlotEdge::inRememberedSet(const Nursery &nursery) const
 {
     return !nursery.isInside(object) && nursery.isInside(deref());
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 StoreBuffer::SlotEdge::isNullEdge() const
 {
     return !deref();
 }
 
 void
 StoreBuffer::WholeCellEdges::mark(JSTracer *trc)
 {
--- a/js/src/gc/StoreBuffer.h
+++ b/js/src/gc/StoreBuffer.h
@@ -286,22 +286,22 @@ class StoreBuffer
         bool operator==(const SlotEdge &other) const {
             return object == other.object && offset == other.offset && kind == other.kind;
         }
 
         bool operator!=(const SlotEdge &other) const {
             return object != other.object || offset != other.offset || kind != other.kind;
         }
 
-        JS_ALWAYS_INLINE HeapSlot *slotLocation() const;
+        MOZ_ALWAYS_INLINE HeapSlot *slotLocation() const;
 
-        JS_ALWAYS_INLINE void *deref() const;
-        JS_ALWAYS_INLINE void *location() const;
+        MOZ_ALWAYS_INLINE void *deref() const;
+        MOZ_ALWAYS_INLINE void *location() const;
         bool inRememberedSet(const Nursery &nursery) const;
-        JS_ALWAYS_INLINE bool isNullEdge() const;
+        MOZ_ALWAYS_INLINE bool isNullEdge() const;
 
         void mark(JSTracer *trc);
     };
 
     struct WholeCellEdges
     {
         Cell *tenured;
 
--- a/js/src/gc/Verifier.cpp
+++ b/js/src/gc/Verifier.cpp
@@ -31,17 +31,17 @@ using namespace mozilla;
 
 template <typename T>
 bool
 CheckNonAddressThing(uintptr_t *w, Rooted<T> *rootp)
 {
     return w >= (uintptr_t*)rootp->address() && w < (uintptr_t*)(rootp->address() + 1);
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 CheckStackRootThing(uintptr_t *w, Rooted<void *> *rootp, ThingRootKind kind)
 {
     if (kind == THING_ROOT_BINDINGS)
         return CheckNonAddressThing(w, reinterpret_cast<Rooted<Bindings> *>(rootp));
 
     if (kind == THING_ROOT_PROPERTY_DESCRIPTOR)
         return CheckNonAddressThing(w, reinterpret_cast<Rooted<PropertyDescriptor> *>(rootp));
 
--- a/js/src/gc/Zone.h
+++ b/js/src/gc/Zone.h
@@ -288,17 +288,17 @@ struct Zone : public JS::shadow::Zone,
     void resetGCMallocBytes();
     void setGCMaxMallocBytes(size_t value);
     void updateMallocCounter(size_t nbytes) {
         /*
          * Note: this code may be run from worker threads.  We
          * tolerate any thread races when updating gcMallocBytes.
          */
         gcMallocBytes -= ptrdiff_t(nbytes);
-        if (JS_UNLIKELY(isTooMuchMalloc()))
+        if (MOZ_UNLIKELY(isTooMuchMalloc()))
             onTooMuchMalloc();
     }
 
     bool isTooMuchMalloc() const {
         return gcMallocBytes <= 0;
      }
 
     void onTooMuchMalloc();
--- a/js/src/jit/BaselineIC.cpp
+++ b/js/src/jit/BaselineIC.cpp
@@ -6317,17 +6317,17 @@ DoGetPropFallback(JSContext *cx, Baselin
     if (!obj)
         return false;
 
     if (!JSObject::getGeneric(cx, obj, obj, id, res))
         return false;
 
 #if JS_HAS_NO_SUCH_METHOD
     // Handle objects with __noSuchMethod__.
-    if (op == JSOP_CALLPROP && JS_UNLIKELY(res.isUndefined()) && val.isObject()) {
+    if (op == JSOP_CALLPROP && MOZ_UNLIKELY(res.isUndefined()) && val.isObject()) {
         if (!OnUnknownMethod(cx, obj, IdToValue(id), res))
             return false;
     }
 #endif
 
     types::TypeScript::Monitor(cx, script, pc, res);
 
     // Add a type monitor stub for the resulting value.
--- a/js/src/jit/IonCaches.cpp
+++ b/js/src/jit/IonCaches.cpp
@@ -1737,17 +1737,17 @@ GetPropertyIC::update(JSContext *cx, siz
         jsbytecode *pc;
         cache.getScriptedLocation(&script, &pc);
 
         // If the cache is idempotent, the property exists so we don't have to
         // call __noSuchMethod__.
 
 #if JS_HAS_NO_SUCH_METHOD
         // Handle objects with __noSuchMethod__.
-        if (JSOp(*pc) == JSOP_CALLPROP && JS_UNLIKELY(vp.isUndefined())) {
+        if (JSOp(*pc) == JSOP_CALLPROP && MOZ_UNLIKELY(vp.isUndefined())) {
             if (!OnUnknownMethod(cx, obj, IdToValue(id), vp))
                 return false;
         }
 #endif
 
         // Monitor changes to cache entry.
         if (!cache.monitoredResult())
             types::TypeScript::Monitor(cx, script, pc, vp);
--- a/js/src/jit/IonFrames.cpp
+++ b/js/src/jit/IonFrames.cpp
@@ -1240,17 +1240,17 @@ GetPcScript(JSContext *cx, JSScript **sc
         JS_ASSERT(it.prevType() == IonFrame_BaselineJS);
     }
 
     uint8_t *retAddr = it.returnAddress();
     uint32_t hash = PcScriptCache::Hash(retAddr);
     JS_ASSERT(retAddr != nullptr);
 
     // Lazily initialize the cache. The allocation may safely fail and will not GC.
-    if (JS_UNLIKELY(rt->ionPcScriptCache == nullptr)) {
+    if (MOZ_UNLIKELY(rt->ionPcScriptCache == nullptr)) {
         rt->ionPcScriptCache = (PcScriptCache *)js_malloc(sizeof(struct PcScriptCache));
         if (rt->ionPcScriptCache)
             rt->ionPcScriptCache->clear(rt->gcNumber);
     }
 
     // Attempt to lookup address in cache.
     if (rt->ionPcScriptCache && rt->ionPcScriptCache->get(rt, hash, retAddr, scriptRes, pcRes))
         return;
--- a/js/src/jit/VMFunctions.cpp
+++ b/js/src/jit/VMFunctions.cpp
@@ -451,17 +451,17 @@ SetProperty(JSContext *cx, HandleObject 
         // Aliased var assigns ignore readonly attributes on the property, as
         // required for initializing 'const' closure variables.
         Shape *shape = obj->nativeLookup(cx, name);
         JS_ASSERT(shape && shape->hasSlot());
         obj->nativeSetSlotWithType(cx, shape, value);
         return true;
     }
 
-    if (JS_LIKELY(!obj->getOps()->setProperty)) {
+    if (MOZ_LIKELY(!obj->getOps()->setProperty)) {
         unsigned defineHow = (op == JSOP_SETNAME || op == JSOP_SETGNAME) ? DNP_UNQUALIFIED : 0;
         return baseops::SetPropertyHelper<SequentialExecution>(cx, obj, obj, id, defineHow, &v,
                                                                strict);
     }
 
     return JSObject::setGeneric(cx, obj, obj, id, &v, strict);
 }
 
--- a/js/src/jsalloc.h
+++ b/js/src/jsalloc.h
@@ -47,31 +47,31 @@ class TempAllocPolicy
     JS_FRIEND_API(void *) onOutOfMemory(void *p, size_t nbytes);
 
   public:
     TempAllocPolicy(JSContext *cx) : cx_((ContextFriendFields *) cx) {} // :(
     TempAllocPolicy(ContextFriendFields *cx) : cx_(cx) {}
 
     void *malloc_(size_t bytes) {
         void *p = js_malloc(bytes);
-        if (JS_UNLIKELY(!p))
+        if (MOZ_UNLIKELY(!p))
             p = onOutOfMemory(nullptr, bytes);
         return p;
     }
 
     void *calloc_(size_t bytes) {
         void *p = js_calloc(bytes);
-        if (JS_UNLIKELY(!p))
+        if (MOZ_UNLIKELY(!p))
             p = onOutOfMemory(nullptr, bytes);
         return p;
     }
 
     void *realloc_(void *p, size_t oldBytes, size_t bytes) {
         void *p2 = js_realloc(p, bytes);
-        if (JS_UNLIKELY(!p2))
+        if (MOZ_UNLIKELY(!p2))
             p2 = onOutOfMemory(p2, bytes);
         return p2;
     }
 
     void free_(void *p) {
         js_free(p);
     }
 
--- a/js/src/jsapi-tests/testPersistentRooted.cpp
+++ b/js/src/jsapi-tests/testPersistentRooted.cpp
@@ -42,17 +42,17 @@ struct Kennel {
     PersistentRootedObject obj;
     Kennel(JSContext *cx) : obj(cx) { }
     Kennel(JSContext *cx, const HandleObject &woof) : obj(cx, woof) { };
 };
 
 // A function for allocating a Kennel and a barker. Only allocating
 // PersistentRooteds on the heap, and in this function, helps ensure that the
 // conservative GC doesn't find stray references to the barker. Ugh.
-JS_NEVER_INLINE static Kennel *
+MOZ_NEVER_INLINE static Kennel *
 Allocate(JSContext *cx)
 {
     RootedObject barker(cx, JS_NewObject(cx, &BarkWhenTracedClass::class_, JS::NullPtr(), JS::NullPtr()));
     if (!barker)
         return nullptr;
 
     return new Kennel(cx, barker);
 }
--- a/js/src/jsapi-tests/testRegExpInstanceProperties.cpp
+++ b/js/src/jsapi-tests/testRegExpInstanceProperties.cpp
@@ -34,17 +34,17 @@ BEGIN_TEST(testRegExpInstanceProperties)
 
     return true;
 }
 
 /*
  * Do this all in a nested function evaluation so as (hopefully) not to get
  * screwed up by the conservative stack scanner when GCing.
  */
-JS_NEVER_INLINE bool helper(JSObject *regexpProto)
+MOZ_NEVER_INLINE bool helper(JSObject *regexpProto)
 {
     CHECK(!regexpProto->inDictionaryMode());
 
     // Verify the compartment's cached shape is being used by RegExp.prototype.
     const js::Shape *shape = regexpProto->lastProperty();
     js::AutoShapeRooter root(cx, shape);
     for (js::Shape::Range r = shape;
          &r.front() != regexpProto->compartment()->initialRegExpShape;
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -4733,17 +4733,17 @@ JS_DecompileFunctionBody(JSContext *cx, 
 {
     JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
     AssertHeapIsIdle(cx);
     CHECK_REQUEST(cx);
     assertSameCompartment(cx, fun);
     return FunctionToString(cx, fun, true, !(indent & JS_DONT_PRETTY_PRINT));
 }
 
-JS_NEVER_INLINE JS_PUBLIC_API(bool)
+MOZ_NEVER_INLINE JS_PUBLIC_API(bool)
 JS_ExecuteScript(JSContext *cx, JSObject *objArg, JSScript *scriptArg, jsval *rval)
 {
     RootedObject obj(cx, objArg);
     RootedScript script(cx, scriptArg);
 
     JS_ASSERT(!cx->runtime()->isAtomsCompartment(cx->compartment()));
     AssertHeapIsIdle(cx);
     CHECK_REQUEST(cx);
@@ -5962,17 +5962,17 @@ JS_GetCurrentThread()
 {
 #ifdef JS_THREADSAFE
     return reinterpret_cast<intptr_t>(PR_GetCurrentThread());
 #else
     return 0;
 #endif
 }
 
-extern JS_NEVER_INLINE JS_PUBLIC_API(void)
+extern MOZ_NEVER_INLINE JS_PUBLIC_API(void)
 JS_AbortIfWrongThread(JSRuntime *rt)
 {
     if (!CurrentThreadCanAccessRuntime(rt))
         MOZ_CRASH();
     if (!js::TlsPerThreadData.get()->associatedWith(rt))
         MOZ_CRASH();
 }
 
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -853,17 +853,17 @@ typedef void
 (* JSZoneCallback)(JS::Zone *zone);
 
 typedef void
 (* JSCompartmentNameCallback)(JSRuntime *rt, JSCompartment *compartment,
                               char *buf, size_t bufsize);
 
 /************************************************************************/
 
-static JS_ALWAYS_INLINE jsval
+static MOZ_ALWAYS_INLINE jsval
 JS_NumberValue(double d)
 {
     int32_t i;
     d = JS::CanonicalizeNaN(d);
     if (mozilla::DoubleIsInt32(d, &i))
         return INT_TO_JSVAL(i);
     return DOUBLE_TO_JSVAL(d);
 }
@@ -882,17 +882,17 @@ JS_StringHasBeenInterned(JSContext *cx, 
  */
 JS_PUBLIC_API(jsid)
 INTERNED_STRING_TO_JSID(JSContext *cx, JSString *str);
 
 /*
  * Returns true iff the given jsval is immune to GC and can be used across
  * multiple JSRuntimes without requiring any conversion API.
  */
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSVAL_IS_UNIVERSAL(jsval v)
 {
     return !JSVAL_IS_GCTHING(v);
 }
 
 namespace JS {
 
 class AutoIdRooter : private AutoGCRooter
@@ -1071,33 +1071,33 @@ ToBooleanSlow(JS::HandleValue v);
  */
 extern JS_PUBLIC_API(JSString*)
 ToStringSlow(JSContext *cx, JS::HandleValue v);
 } /* namespace js */
 
 namespace JS {
 
 /* ES5 9.3 ToNumber. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 ToNumber(JSContext *cx, HandleValue v, double *out)
 {
     AssertArgumentsAreSane(cx, v);
     {
         js::SkipRoot root(cx, &v);
         js::MaybeCheckStackRoots(cx);
     }
 
     if (v.isNumber()) {
         *out = v.toNumber();
         return true;
     }
     return js::ToNumberSlow(cx, v, out);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 ToBoolean(HandleValue v)
 {
     if (v.isBoolean())
         return v.toBoolean();
     if (v.isInt32())
         return v.toInt32() != 0;
     if (v.isNullOrUndefined())
         return false;
@@ -1105,17 +1105,17 @@ ToBoolean(HandleValue v)
         double d = v.toDouble();
         return !mozilla::IsNaN(d) && d != 0;
     }
 
     /* The slow path handles strings and objects. */
     return js::ToBooleanSlow(v);
 }
 
-JS_ALWAYS_INLINE JSString*
+MOZ_ALWAYS_INLINE JSString*
 ToString(JSContext *cx, HandleValue v)
 {
     if (v.isString())
         return v.toString();
     return js::ToStringSlow(cx, v);
 }
 
 } /* namespace JS */
@@ -1149,70 +1149,70 @@ ToInt64Slow(JSContext *cx, JS::HandleVal
 
 /* DO NOT CALL THIS. Use JS::ToUint64. */
 extern JS_PUBLIC_API(bool)
 ToUint64Slow(JSContext *cx, JS::HandleValue v, uint64_t *out);
 } /* namespace js */
 
 namespace JS {
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 ToUint16(JSContext *cx, JS::HandleValue v, uint16_t *out)
 {
     AssertArgumentsAreSane(cx, v);
     js::MaybeCheckStackRoots(cx);
 
     if (v.isInt32()) {
         *out = uint16_t(v.toInt32());
         return true;
     }
     return js::ToUint16Slow(cx, v, out);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 ToInt32(JSContext *cx, JS::HandleValue v, int32_t *out)
 {
     AssertArgumentsAreSane(cx, v);
     js::MaybeCheckStackRoots(cx);
 
     if (v.isInt32()) {
         *out = v.toInt32();
         return true;
     }
     return js::ToInt32Slow(cx, v, out);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 ToUint32(JSContext *cx, JS::HandleValue v, uint32_t *out)
 {
     AssertArgumentsAreSane(cx, v);
     js::MaybeCheckStackRoots(cx);
 
     if (v.isInt32()) {
         *out = uint32_t(v.toInt32());
         return true;
     }
     return js::ToUint32Slow(cx, v, out);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 ToInt64(JSContext *cx, JS::HandleValue v, int64_t *out)
 {
     AssertArgumentsAreSane(cx, v);
     js::MaybeCheckStackRoots(cx);
 
     if (v.isInt32()) {
         *out = int64_t(v.toInt32());
         return true;
     }
 
     return js::ToInt64Slow(cx, v, out);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 ToUint64(JSContext *cx, JS::HandleValue v, uint64_t *out)
 {
     AssertArgumentsAreSane(cx, v);
     js::MaybeCheckStackRoots(cx);
 
     if (v.isInt32()) {
         /* Account for sign extension of negatives into the longer 64bit space. */
         *out = uint64_t(int64_t(v.toInt32()));
@@ -2023,29 +2023,29 @@ JS_RemoveExtraGCRootsTracer(JSRuntime *r
  *
  * See the JSTraceOp typedef.
  */
 
 /*
  * Use the following macros to check if a particular jsval is a traceable
  * thing and to extract the thing and its kind to pass to JS_CallTracer.
  */
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSVAL_IS_TRACEABLE(jsval v)
 {
     return JSVAL_IS_TRACEABLE_IMPL(JSVAL_TO_IMPL(v));
 }
 
-static JS_ALWAYS_INLINE void *
+static MOZ_ALWAYS_INLINE void *
 JSVAL_TO_TRACEABLE(jsval v)
 {
     return JSVAL_TO_GCTHING(v);
 }
 
-static JS_ALWAYS_INLINE JSGCTraceKind
+static MOZ_ALWAYS_INLINE JSGCTraceKind
 JSVAL_TRACE_KIND(jsval v)
 {
     JS_ASSERT(JSVAL_IS_GCTHING(v));
     return (JSGCTraceKind) JSVAL_TRACE_KIND_IMPL(JSVAL_TO_IMPL(v));
 }
 
 #ifdef JS_DEBUG
 
@@ -4097,31 +4097,31 @@ extern JS_PUBLIC_API(const jschar *)
 JS_GetStringCharsZAndLength(JSContext *cx, JSString *str, size_t *length);
 
 extern JS_PUBLIC_API(JSFlatString *)
 JS_FlattenString(JSContext *cx, JSString *str);
 
 extern JS_PUBLIC_API(const jschar *)
 JS_GetFlatStringChars(JSFlatString *str);
 
-static JS_ALWAYS_INLINE JSFlatString *
+static MOZ_ALWAYS_INLINE JSFlatString *
 JSID_TO_FLAT_STRING(jsid id)
 {
     JS_ASSERT(JSID_IS_STRING(id));
     return (JSFlatString *)(JSID_BITS(id));
 }
 
-static JS_ALWAYS_INLINE JSFlatString *
+static MOZ_ALWAYS_INLINE JSFlatString *
 JS_ASSERT_STRING_IS_FLAT(JSString *str)
 {
     JS_ASSERT(JS_GetFlatStringChars((JSFlatString *)str));
     return (JSFlatString *)str;
 }
 
-static JS_ALWAYS_INLINE JSString *
+static MOZ_ALWAYS_INLINE JSString *
 JS_FORGET_STRING_FLATNESS(JSFlatString *fstr)
 {
     return (JSString *)fstr;
 }
 
 /*
  * Additional APIs that avoid fallibility when given a flat string.
  */
--- a/js/src/jsarray.cpp
+++ b/js/src/jsarray.cpp
@@ -866,23 +866,23 @@ AddLengthProperty(ExclusiveContext *cx, 
     JS_ASSERT(!obj->nativeLookup(cx, lengthId));
 
     return JSObject::addProperty(cx, obj, lengthId, array_length_getter, array_length_setter,
                                  SHAPE_INVALID_SLOT, JSPROP_PERMANENT | JSPROP_SHARED, 0, 0,
                                  /* allowDictionary = */ false);
 }
 
 #if JS_HAS_TOSOURCE
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 IsArray(HandleValue v)
 {
     return v.isObject() && v.toObject().is<ArrayObject>();
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 array_toSource_impl(JSContext *cx, CallArgs args)
 {
     JS_ASSERT(IsArray(args.thisv()));
 
     Rooted<JSObject*> obj(cx, &args.thisv().toObject());
     RootedValue elt(cx);
 
     AutoCycleDetector detector(cx, obj);
@@ -2333,17 +2333,17 @@ CanOptimizeForDenseStorage(HandleObject 
      * visited.  See bug 690622.
      *
      * Another potential wrinkle: what if the enumeration is happening on an
      * object which merely has |arr| on its prototype chain?  It turns out this
      * case can't happen, because any dense array used as the prototype of
      * another object is first slowified, for type inference's sake.
      */
     types::TypeObject *arrType = arr->getType(cx);
-    if (JS_UNLIKELY(!arrType || arrType->hasAllFlags(OBJECT_FLAG_ITERATED)))
+    if (MOZ_UNLIKELY(!arrType || arrType->hasAllFlags(OBJECT_FLAG_ITERATED)))
         return false;
 
     /*
      * Now watch out for getters and setters along the prototype chain or in
      * other indexed properties on the object.  (Note that non-writable length
      * is subsumed by the initializedLength comparison.)
      */
     return !ObjectMayHaveExtraIndexedProperties(arr) &&
@@ -3135,17 +3135,17 @@ EnsureNewArrayElements(ExclusiveContext 
         return false;
 
     JS_ASSERT_IF(cap, !obj->hasDynamicElements());
 
     return true;
 }
 
 template<bool allocateCapacity>
-static JS_ALWAYS_INLINE ArrayObject *
+static MOZ_ALWAYS_INLINE ArrayObject *
 NewArray(ExclusiveContext *cxArg, uint32_t length,
          JSObject *protoArg, NewObjectKind newKind = GenericObject)
 {
     gc::AllocKind allocKind = GuessArrayGCKind(length);
     JS_ASSERT(CanBeFinalizedInBackground(allocKind, &ArrayObject::class_));
     allocKind = GetBackgroundAllocKind(allocKind);
 
     NewObjectCache::EntryIndex entry = -1;
--- a/js/src/jsarray.h
+++ b/js/src/jsarray.h
@@ -22,17 +22,17 @@ js_IdIsIndex(jsid id, uint32_t *indexp)
 {
     if (JSID_IS_INT(id)) {
         int32_t i = JSID_TO_INT(id);
         JS_ASSERT(i >= 0);
         *indexp = (uint32_t)i;
         return true;
     }
 
-    if (JS_UNLIKELY(!JSID_IS_STRING(id)))
+    if (MOZ_UNLIKELY(!JSID_IS_STRING(id)))
         return false;
 
     return js::StringIsArrayIndex(JSID_TO_ATOM(id), indexp);
 }
 
 extern JSObject *
 js_InitArrayClass(JSContext *cx, js::HandleObject obj);
 
--- a/js/src/jsatom.cpp
+++ b/js/src/jsatom.cpp
@@ -225,17 +225,17 @@ AtomIsInterned(JSContext *cx, JSAtom *at
     return p->isTagged();
 }
 
 /*
  * When the jschars reside in a freshly allocated buffer the memory can be used
  * as a new JSAtom's storage without copying. The contract is that the caller no
  * longer owns the memory and this method is responsible for freeing the memory.
  */
-JS_ALWAYS_INLINE
+MOZ_ALWAYS_INLINE
 static JSAtom *
 AtomizeAndTakeOwnership(ExclusiveContext *cx, jschar *tbchars, size_t length, InternBehavior ib)
 {
     JS_ASSERT(tbchars[length] == 0);
 
     if (JSAtom *s = cx->staticStrings().lookup(tbchars, length)) {
         js_free(tbchars);
         return s;
@@ -275,17 +275,17 @@ AtomizeAndTakeOwnership(ExclusiveContext
         js_ReportOutOfMemory(cx); /* SystemAllocPolicy does not report OOM. */
         return nullptr;
     }
 
     return atom;
 }
 
 /* |tbchars| must not point into an inline or short string. */
-JS_ALWAYS_INLINE
+MOZ_ALWAYS_INLINE
 static JSAtom *
 AtomizeAndCopyChars(ExclusiveContext *cx, const jschar *tbchars, size_t length, InternBehavior ib)
 {
     if (JSAtom *s = cx->staticStrings().lookup(tbchars, length))
          return s;
 
     /*
      * If a GC occurs at js_NewStringCopy then |p| will still have the correct
--- a/js/src/jsatom.h
+++ b/js/src/jsatom.h
@@ -22,17 +22,17 @@ struct JSIdArray {
     int length;
     js::HeapId vector[1];    /* actually, length jsid words */
 };
 
 namespace js {
 
 JS_STATIC_ASSERT(sizeof(HashNumber) == 4);
 
-static JS_ALWAYS_INLINE js::HashNumber
+static MOZ_ALWAYS_INLINE js::HashNumber
 HashId(jsid id)
 {
     return mozilla::HashGeneric(JSID_BITS(id));
 }
 
 struct JsidHasher
 {
     typedef jsid Lookup;
--- a/js/src/jsatominlines.h
+++ b/js/src/jsatominlines.h
@@ -114,23 +114,23 @@ IndexToId(ExclusiveContext *cx, uint32_t
     if (index <= JSID_INT_MAX) {
         idp.set(INT_TO_JSID(index));
         return true;
     }
 
     return IndexToIdSlow(cx, index, idp);
 }
 
-static JS_ALWAYS_INLINE JSFlatString *
+static MOZ_ALWAYS_INLINE JSFlatString *
 IdToString(JSContext *cx, jsid id)
 {
     if (JSID_IS_STRING(id))
         return JSID_TO_ATOM(id);
 
-    if (JS_LIKELY(JSID_IS_INT(id)))
+    if (MOZ_LIKELY(JSID_IS_INT(id)))
         return Int32ToString<CanGC>(cx, JSID_TO_INT(id));
 
     RootedValue idv(cx, IdToValue(id));
     JSString *str = ToStringSlow<CanGC>(cx, idv);
     if (!str)
         return nullptr;
 
     return str->ensureFlat(cx);
--- a/js/src/jsbool.cpp
+++ b/js/src/jsbool.cpp
@@ -32,24 +32,24 @@ const Class BooleanObject::class_ = {
     JS_DeletePropertyStub,   /* delProperty */
     JS_PropertyStub,         /* getProperty */
     JS_StrictPropertyStub,   /* setProperty */
     JS_EnumerateStub,
     JS_ResolveStub,
     JS_ConvertStub
 };
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 IsBoolean(HandleValue v)
 {
     return v.isBoolean() || (v.isObject() && v.toObject().is<BooleanObject>());
 }
 
 #if JS_HAS_TOSOURCE
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 bool_toSource_impl(JSContext *cx, CallArgs args)
 {
     HandleValue thisv = args.thisv();
     JS_ASSERT(IsBoolean(thisv));
 
     bool b = thisv.isBoolean() ? thisv.toBoolean() : thisv.toObject().as<BooleanObject>().unbox();
 
     StringBuffer sb(cx);
@@ -66,17 +66,17 @@ bool_toSource_impl(JSContext *cx, CallAr
 static bool
 bool_toSource(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsBoolean, bool_toSource_impl>(cx, args);
 }
 #endif
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 bool_toString_impl(JSContext *cx, CallArgs args)
 {
     HandleValue thisv = args.thisv();
     JS_ASSERT(IsBoolean(thisv));
 
     bool b = thisv.isBoolean() ? thisv.toBoolean() : thisv.toObject().as<BooleanObject>().unbox();
     args.rval().setString(js_BooleanToString(cx, b));
     return true;
@@ -84,17 +84,17 @@ bool_toString_impl(JSContext *cx, CallAr
 
 static bool
 bool_toString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsBoolean, bool_toString_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 bool_valueOf_impl(JSContext *cx, CallArgs args)
 {
     HandleValue thisv = args.thisv();
     JS_ASSERT(IsBoolean(thisv));
 
     bool b = thisv.isBoolean() ? thisv.toBoolean() : thisv.toObject().as<BooleanObject>().unbox();
     args.rval().setBoolean(b);
     return true;
--- a/js/src/jscntxtinlines.h
+++ b/js/src/jscntxtinlines.h
@@ -203,17 +203,17 @@ assertSameCompartment(ThreadSafeContext 
     c.check(t4);
     c.check(t5);
 #endif
 }
 
 #undef START_ASSERT_SAME_COMPARTMENT
 
 STATIC_PRECONDITION_ASSUME(ubound(args.argv_) >= argc)
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 CallJSNative(JSContext *cx, Native native, const CallArgs &args)
 {
     JS_CHECK_RECURSION(cx, return false);
 
 #ifdef DEBUG
     bool alreadyThrowing = cx->isExceptionPending();
 #endif
     assertSameCompartment(cx, args);
@@ -221,33 +221,33 @@ CallJSNative(JSContext *cx, Native nativ
     if (ok) {
         assertSameCompartment(cx, args.rval());
         JS_ASSERT_IF(!alreadyThrowing, !cx->isExceptionPending());
     }
     return ok;
 }
 
 STATIC_PRECONDITION_ASSUME(ubound(args.argv_) >= argc)
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 CallNativeImpl(JSContext *cx, NativeImpl impl, const CallArgs &args)
 {
 #ifdef DEBUG
     bool alreadyThrowing = cx->isExceptionPending();
 #endif
     assertSameCompartment(cx, args);
     bool ok = impl(cx, args);
     if (ok) {
         assertSameCompartment(cx, args.rval());
         JS_ASSERT_IF(!alreadyThrowing, !cx->isExceptionPending());
     }
     return ok;
 }
 
 STATIC_PRECONDITION(ubound(args.argv_) >= argc)
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 CallJSNativeConstructor(JSContext *cx, Native native, const CallArgs &args)
 {
 #ifdef DEBUG
     RootedObject callee(cx, &args.callee());
 #endif
 
     JS_ASSERT(args.thisv().isMagic());
     if (!CallJSNative(cx, native, args))
@@ -277,29 +277,29 @@ CallJSNativeConstructor(JSContext *cx, N
                  native != js::CallOrConstructBoundFunction &&
                  native != js::IteratorConstructor &&
                  (!callee->is<JSFunction>() || callee->as<JSFunction>().native() != obj_construct),
                  !args.rval().isPrimitive() && callee != &args.rval().toObject());
 
     return true;
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 CallJSPropertyOp(JSContext *cx, PropertyOp op, HandleObject receiver, HandleId id, MutableHandleValue vp)
 {
     JS_CHECK_RECURSION(cx, return false);
 
     assertSameCompartment(cx, receiver, id, vp);
     bool ok = op(cx, receiver, id, vp);
     if (ok)
         assertSameCompartment(cx, vp);
     return ok;
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 CallJSPropertyOpSetter(JSContext *cx, StrictPropertyOp op, HandleObject obj, HandleId id,
                        bool strict, MutableHandleValue vp)
 {
     JS_CHECK_RECURSION(cx, return false);
 
     assertSameCompartment(cx, obj, id, vp);
     return op(cx, obj, id, strict, vp);
 }
--- a/js/src/jsdate.cpp
+++ b/js/src/jsdate.cpp
@@ -1381,40 +1381,40 @@ DateObject::fillLocalTimeSlots(DateTimeI
 
 inline double
 DateObject::cachedLocalTime(DateTimeInfo *dtInfo)
 {
     fillLocalTimeSlots(dtInfo);
     return getReservedSlot(LOCAL_TIME_SLOT).toDouble();
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 IsDate(HandleValue v)
 {
     return v.isObject() && v.toObject().is<DateObject>();
 }
 
 /*
  * See ECMA 15.9.5.4 thru 15.9.5.23
  */
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getTime_impl(JSContext *cx, CallArgs args)
 {
     args.rval().set(args.thisv().toObject().as<DateObject>().UTCTime());
     return true;
 }
 
 static bool
 date_getTime(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getTime_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getYear_impl(JSContext *cx, CallArgs args)
 {
     DateObject *dateObj = &args.thisv().toObject().as<DateObject>();
     dateObj->fillLocalTimeSlots(&cx->runtime()->dateTimeInfo);
 
     Value yearVal = dateObj->getReservedSlot(LOCAL_YEAR_SLOT);
     if (yearVal.isInt32()) {
         /* Follow ECMA-262 to the letter, contrary to IE JScript. */
@@ -1429,34 +1429,34 @@ DateObject::getYear_impl(JSContext *cx, 
 
 static bool
 date_getYear(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getYear_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getFullYear_impl(JSContext *cx, CallArgs args)
 {
     DateObject *dateObj = &args.thisv().toObject().as<DateObject>();
     dateObj->fillLocalTimeSlots(&cx->runtime()->dateTimeInfo);
 
     args.rval().set(dateObj->getReservedSlot(LOCAL_YEAR_SLOT));
     return true;
 }
 
 static bool
 date_getFullYear(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getFullYear_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getUTCFullYear_impl(JSContext *cx, CallArgs args)
 {
     double result = args.thisv().toObject().as<DateObject>().UTCTime().toNumber();
     if (IsFinite(result))
         result = YearFromTime(result);
 
     args.rval().setNumber(result);
     return true;
@@ -1464,66 +1464,66 @@ DateObject::getUTCFullYear_impl(JSContex
 
 static bool
 date_getUTCFullYear(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getUTCFullYear_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getMonth_impl(JSContext *cx, CallArgs args)
 {
     DateObject *dateObj = &args.thisv().toObject().as<DateObject>();
     dateObj->fillLocalTimeSlots(&cx->runtime()->dateTimeInfo);
 
     args.rval().set(dateObj->getReservedSlot(LOCAL_MONTH_SLOT));
     return true;
 }
 
 static bool
 date_getMonth(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getMonth_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getUTCMonth_impl(JSContext *cx, CallArgs args)
 {
     double d = args.thisv().toObject().as<DateObject>().UTCTime().toNumber();
     args.rval().setNumber(MonthFromTime(d));
     return true;
 }
 
 static bool
 date_getUTCMonth(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getUTCMonth_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getDate_impl(JSContext *cx, CallArgs args)
 {
     DateObject *dateObj = &args.thisv().toObject().as<DateObject>();
     dateObj->fillLocalTimeSlots(&cx->runtime()->dateTimeInfo);
 
     args.rval().set(dateObj->getReservedSlot(LOCAL_DATE_SLOT));
     return true;
 }
 
 static bool
 date_getDate(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getDate_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getUTCDate_impl(JSContext *cx, CallArgs args)
 {
     double result = args.thisv().toObject().as<DateObject>().UTCTime().toNumber();
     if (IsFinite(result))
         result = DateFromTime(result);
 
     args.rval().setNumber(result);
     return true;
@@ -1531,34 +1531,34 @@ DateObject::getUTCDate_impl(JSContext *c
 
 static bool
 date_getUTCDate(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getUTCDate_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getDay_impl(JSContext *cx, CallArgs args)
 {
     DateObject *dateObj = &args.thisv().toObject().as<DateObject>();
     dateObj->fillLocalTimeSlots(&cx->runtime()->dateTimeInfo);
 
     args.rval().set(dateObj->getReservedSlot(LOCAL_DAY_SLOT));
     return true;
 }
 
 static bool
 date_getDay(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getDay_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getUTCDay_impl(JSContext *cx, CallArgs args)
 {
     double result = args.thisv().toObject().as<DateObject>().UTCTime().toNumber();
     if (IsFinite(result))
         result = WeekDay(result);
 
     args.rval().setNumber(result);
     return true;
@@ -1566,34 +1566,34 @@ DateObject::getUTCDay_impl(JSContext *cx
 
 static bool
 date_getUTCDay(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getUTCDay_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getHours_impl(JSContext *cx, CallArgs args)
 {
     DateObject *dateObj = &args.thisv().toObject().as<DateObject>();
     dateObj->fillLocalTimeSlots(&cx->runtime()->dateTimeInfo);
 
     args.rval().set(dateObj->getReservedSlot(LOCAL_HOURS_SLOT));
     return true;
 }
 
 static bool
 date_getHours(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getHours_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getUTCHours_impl(JSContext *cx, CallArgs args)
 {
     double result = args.thisv().toObject().as<DateObject>().UTCTime().toNumber();
     if (IsFinite(result))
         result = HourFromTime(result);
 
     args.rval().setNumber(result);
     return true;
@@ -1601,34 +1601,34 @@ DateObject::getUTCHours_impl(JSContext *
 
 static bool
 date_getUTCHours(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getUTCHours_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getMinutes_impl(JSContext *cx, CallArgs args)
 {
     DateObject *dateObj = &args.thisv().toObject().as<DateObject>();
     dateObj->fillLocalTimeSlots(&cx->runtime()->dateTimeInfo);
 
     args.rval().set(dateObj->getReservedSlot(LOCAL_MINUTES_SLOT));
     return true;
 }
 
 static bool
 date_getMinutes(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getMinutes_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getUTCMinutes_impl(JSContext *cx, CallArgs args)
 {
     double result = args.thisv().toObject().as<DateObject>().UTCTime().toNumber();
     if (IsFinite(result))
         result = MinFromTime(result);
 
     args.rval().setNumber(result);
     return true;
@@ -1638,17 +1638,17 @@ static bool
 date_getUTCMinutes(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getUTCMinutes_impl>(cx, args);
 }
 
 /* Date.getSeconds is mapped to getUTCSeconds */
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getUTCSeconds_impl(JSContext *cx, CallArgs args)
 {
     DateObject *dateObj = &args.thisv().toObject().as<DateObject>();
     dateObj->fillLocalTimeSlots(&cx->runtime()->dateTimeInfo);
 
     args.rval().set(dateObj->getReservedSlot(LOCAL_SECONDS_SLOT));
     return true;
 }
@@ -1657,17 +1657,17 @@ static bool
 date_getUTCSeconds(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getUTCSeconds_impl>(cx, args);
 }
 
 /* Date.getMilliseconds is mapped to getUTCMilliseconds */
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getUTCMilliseconds_impl(JSContext *cx, CallArgs args)
 {
     double result = args.thisv().toObject().as<DateObject>().UTCTime().toNumber();
     if (IsFinite(result))
         result = msFromTime(result);
 
     args.rval().setNumber(result);
     return true;
@@ -1675,17 +1675,17 @@ DateObject::getUTCMilliseconds_impl(JSCo
 
 static bool
 date_getUTCMilliseconds(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getUTCMilliseconds_impl>(cx, args);
 }
 
-/* static */ JS_ALWAYS_INLINE bool
+/* static */ MOZ_ALWAYS_INLINE bool
 DateObject::getTimezoneOffset_impl(JSContext *cx, CallArgs args)
 {
     DateObject *dateObj = &args.thisv().toObject().as<DateObject>();
     double utctime = dateObj->UTCTime().toNumber();
     double localtime = dateObj->cachedLocalTime(&cx->runtime()->dateTimeInfo);
 
     /*
      * Return the time zone offset in minutes for the current locale that is
@@ -1699,17 +1699,17 @@ DateObject::getTimezoneOffset_impl(JSCon
 
 static bool
 date_getTimezoneOffset(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, DateObject::getTimezoneOffset_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setTime_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
     if (args.length() == 0) {
         dateObj->setUTCTime(GenericNaN(), args.rval().address());
         return true;
     }
 
@@ -1754,17 +1754,17 @@ GetMinsOrDefault(JSContext *cx, const Ca
     if (args.length() <= i) {
         *mins = MinFromTime(t);
         return true;
     }
     return ToNumber(cx, args[i], mins);
 }
 
 /* ES5 15.9.5.28. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setMilliseconds_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = LocalTime(dateObj->UTCTime().toNumber(), &cx->runtime()->dateTimeInfo);
 
     /* Step 2. */
@@ -1784,17 +1784,17 @@ date_setMilliseconds_impl(JSContext *cx,
 static bool
 date_setMilliseconds(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setMilliseconds_impl>(cx, args);
 }
 
 /* ES5 15.9.5.29. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setUTCMilliseconds_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = dateObj->UTCTime().toNumber();
 
     /* Step 2. */
@@ -1814,17 +1814,17 @@ date_setUTCMilliseconds_impl(JSContext *
 static bool
 date_setUTCMilliseconds(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setUTCMilliseconds_impl>(cx, args);
 }
 
 /* ES5 15.9.5.30. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setSeconds_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = LocalTime(dateObj->UTCTime().toNumber(), &cx->runtime()->dateTimeInfo);
 
     /* Step 2. */
@@ -1851,17 +1851,17 @@ date_setSeconds_impl(JSContext *cx, Call
 /* ES5 15.9.5.31. */
 static bool
 date_setSeconds(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setSeconds_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setUTCSeconds_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = dateObj->UTCTime().toNumber();
 
     /* Step 2. */
@@ -1888,17 +1888,17 @@ date_setUTCSeconds_impl(JSContext *cx, C
 /* ES5 15.9.5.32. */
 static bool
 date_setUTCSeconds(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setUTCSeconds_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setMinutes_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = LocalTime(dateObj->UTCTime().toNumber(), &cx->runtime()->dateTimeInfo);
 
     /* Step 2. */
@@ -1930,17 +1930,17 @@ date_setMinutes_impl(JSContext *cx, Call
 /* ES5 15.9.5.33. */
 static bool
 date_setMinutes(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setMinutes_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setUTCMinutes_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = dateObj->UTCTime().toNumber();
 
     /* Step 2. */
@@ -1972,17 +1972,17 @@ date_setUTCMinutes_impl(JSContext *cx, C
 /* ES5 15.9.5.34. */
 static bool
 date_setUTCMinutes(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setUTCMinutes_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setHours_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = LocalTime(dateObj->UTCTime().toNumber(), &cx->runtime()->dateTimeInfo);
 
     /* Step 2. */
@@ -2019,17 +2019,17 @@ date_setHours_impl(JSContext *cx, CallAr
 /* ES5 15.9.5.35. */
 static bool
 date_setHours(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setHours_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setUTCHours_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = dateObj->UTCTime().toNumber();
 
     /* Step 2. */
@@ -2066,17 +2066,17 @@ date_setUTCHours_impl(JSContext *cx, Cal
 /* ES5 15.9.5.36. */
 static bool
 date_setUTCHours(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setUTCHours_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setDate_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = LocalTime(dateObj->UTCTime().toNumber(), &cx->runtime()->dateTimeInfo);
 
     /* Step 2. */
@@ -2098,17 +2098,17 @@ date_setDate_impl(JSContext *cx, CallArg
 /* ES5 15.9.5.37. */
 static bool
 date_setDate(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setDate_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setUTCDate_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = dateObj->UTCTime().toNumber();
 
     /* Step 2. */
@@ -2150,17 +2150,17 @@ GetMonthOrDefault(JSContext *cx, const C
     if (args.length() <= i) {
         *month = MonthFromTime(t);
         return true;
     }
     return ToNumber(cx, args[i], month);
 }
 
 /* ES5 15.9.5.38. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setMonth_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = LocalTime(dateObj->UTCTime().toNumber(), &cx->runtime()->dateTimeInfo);
 
     /* Step 2. */
@@ -2187,17 +2187,17 @@ date_setMonth_impl(JSContext *cx, CallAr
 static bool
 date_setMonth(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setMonth_impl>(cx, args);
 }
 
 /* ES5 15.9.5.39. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setUTCMonth_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = dateObj->UTCTime().toNumber();
 
     /* Step 2. */
@@ -2240,17 +2240,17 @@ ThisLocalTimeOrZero(Handle<DateObject*> 
 static double
 ThisUTCTimeOrZero(Handle<DateObject*> dateObj)
 {
     double t = dateObj->as<DateObject>().UTCTime().toNumber();
     return IsNaN(t) ? +0 : t;
 }
 
 /* ES5 15.9.5.40. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setFullYear_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = ThisLocalTimeOrZero(dateObj, &cx->runtime()->dateTimeInfo);
 
     /* Step 2. */
@@ -2282,17 +2282,17 @@ date_setFullYear_impl(JSContext *cx, Cal
 static bool
 date_setFullYear(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setFullYear_impl>(cx, args);
 }
 
 /* ES5 15.9.5.41. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setUTCFullYear_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = ThisUTCTimeOrZero(dateObj);
 
     /* Step 2. */
@@ -2324,17 +2324,17 @@ date_setUTCFullYear_impl(JSContext *cx, 
 static bool
 date_setUTCFullYear(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_setUTCFullYear_impl>(cx, args);
 }
 
 /* ES5 Annex B.2.5. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_setYear_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     /* Step 1. */
     double t = ThisLocalTimeOrZero(dateObj, &cx->runtime()->dateTimeInfo);
 
     /* Step 2. */
@@ -2409,17 +2409,17 @@ print_iso_string(char* buf, size_t size,
                 int(DateFromTime(utctime)),
                 int(HourFromTime(utctime)),
                 int(MinFromTime(utctime)),
                 int(SecFromTime(utctime)),
                 int(msFromTime(utctime)));
 }
 
 /* ES5 B.2.6. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toGMTString_impl(JSContext *cx, CallArgs args)
 {
     double utctime = args.thisv().toObject().as<DateObject>().UTCTime().toNumber();
 
     char buf[100];
     if (!IsFinite(utctime))
         JS_snprintf(buf, sizeof buf, js_NaN_date_str);
     else
@@ -2435,17 +2435,17 @@ date_toGMTString_impl(JSContext *cx, Cal
 /* ES5 15.9.5.43. */
 static bool
 date_toGMTString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_toGMTString_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toISOString_impl(JSContext *cx, CallArgs args)
 {
     double utctime = args.thisv().toObject().as<DateObject>().UTCTime().toNumber();
     if (!IsFinite(utctime)) {
         JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_INVALID_DATE);
         return false;
     }
 
@@ -2715,32 +2715,32 @@ ToLocaleStringHelper(JSContext *cx, Hand
                           "%#c"
 #else
                           "%c"
 #endif
                          , rval);
 }
 
 /* ES5 15.9.5.5. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toLocaleString_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
     return ToLocaleStringHelper(cx, dateObj, args.rval());
 }
 
 static bool
 date_toLocaleString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_toLocaleString_impl>(cx, args);
 }
 
 /* ES5 15.9.5.6. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toLocaleDateString_impl(JSContext *cx, CallArgs args)
 {
     /*
      * Use '%#x' for windows, because '%x' is backward-compatible and non-y2k
      * with msvc; '%#x' requests that a full year be used in the result string.
      */
     static const char format[] =
 #if defined(_WIN32) && !defined(__MWERKS__)
@@ -2757,32 +2757,32 @@ date_toLocaleDateString_impl(JSContext *
 static bool
 date_toLocaleDateString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_toLocaleDateString_impl>(cx, args);
 }
 
 /* ES5 15.9.5.7. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toLocaleTimeString_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
     return ToLocaleFormatHelper(cx, dateObj, "%X", args.rval());
 }
 
 static bool
 date_toLocaleTimeString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_toLocaleTimeString_impl>(cx, args);
 }
 #endif /* !EXPOSE_INTL_API */
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toLocaleFormat_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
 
     if (args.length() == 0) {
         /*
          * Use '%#c' for windows, because '%c' is backward-compatible and non-y2k
          * with msvc; '%#c' requests that a full year be used in the result string.
@@ -2810,47 +2810,47 @@ date_toLocaleFormat_impl(JSContext *cx, 
 static bool
 date_toLocaleFormat(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_toLocaleFormat_impl>(cx, args);
 }
 
 /* ES5 15.9.5.4. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toTimeString_impl(JSContext *cx, CallArgs args)
 {
     return date_format(cx, args.thisv().toObject().as<DateObject>().UTCTime().toNumber(),
                        FORMATSPEC_TIME, args.rval());
 }
 
 static bool
 date_toTimeString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_toTimeString_impl>(cx, args);
 }
 
 /* ES5 15.9.5.3. */
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toDateString_impl(JSContext *cx, CallArgs args)
 {
     return date_format(cx, args.thisv().toObject().as<DateObject>().UTCTime().toNumber(),
                        FORMATSPEC_DATE, args.rval());
 }
 
 static bool
 date_toDateString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_toDateString_impl>(cx, args);
 }
 
 #if JS_HAS_TOSOURCE
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toSource_impl(JSContext *cx, CallArgs args)
 {
     StringBuffer sb(cx);
     if (!sb.append("(new Date(") ||
         !NumberValueToStringBuffer(cx, args.thisv().toObject().as<DateObject>().UTCTime(), sb) ||
         !sb.append("))"))
     {
         return false;
@@ -2866,31 +2866,31 @@ date_toSource_impl(JSContext *cx, CallAr
 static bool
 date_toSource(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_toSource_impl>(cx, args);
 }
 #endif
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_toString_impl(JSContext *cx, CallArgs args)
 {
     return date_format(cx, args.thisv().toObject().as<DateObject>().UTCTime().toNumber(),
                        FORMATSPEC_FULL, args.rval());
 }
 
 static bool
 date_toString(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     return CallNonGenericMethod<IsDate, date_toString_impl>(cx, args);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 date_valueOf_impl(JSContext *cx, CallArgs args)
 {
     Rooted<DateObject*> dateObj(cx, &args.thisv().toObject().as<DateObject>());
     args.rval().set(dateObj->UTCTime());
     return true;
 }
 
 static bool
--- a/js/src/jsfriendapi.h
+++ b/js/src/jsfriendapi.h
@@ -476,17 +476,17 @@ IsCallObject(JSObject *obj);
 
 inline JSObject *
 GetObjectParent(JSObject *obj)
 {
     JS_ASSERT(!IsScopeObject(obj));
     return reinterpret_cast<shadow::Object*>(obj)->shape->base->parent;
 }
 
-static JS_ALWAYS_INLINE JSCompartment *
+static MOZ_ALWAYS_INLINE JSCompartment *
 GetObjectCompartment(JSObject *obj)
 {
     return reinterpret_cast<shadow::Object*>(obj)->shape->base->compartment;
 }
 
 JS_FRIEND_API(JSObject *)
 GetObjectParentMaybeScope(JSObject *obj);
 
@@ -1654,40 +1654,40 @@ inline int CheckIsParallelNative(JSParal
 #define JS_JITINFO_NATIVE_PARALLEL_THREADSAFE(infoName, wrapperName, serialOp) \
     bool wrapperName##_ParallelNativeThreadSafeWrapper(js::ForkJoinSlice *slice, unsigned argc, \
                                                        JS::Value *vp)   \
     {                                                                   \
         return JSParallelNativeThreadSafeWrapper<serialOp>(slice, argc, vp); \
     }                                                                   \
     JS_JITINFO_NATIVE_PARALLEL(infoName, wrapperName##_ParallelNativeThreadSafeWrapper)
 
-static JS_ALWAYS_INLINE const JSJitInfo *
+static MOZ_ALWAYS_INLINE const JSJitInfo *
 FUNCTION_VALUE_TO_JITINFO(const JS::Value& v)
 {
     JS_ASSERT(js::GetObjectClass(&v.toObject()) == js::FunctionClassPtr);
     return reinterpret_cast<js::shadow::Function *>(&v.toObject())->jitinfo;
 }
 
 /* Statically asserted in jsfun.h. */
 static const unsigned JS_FUNCTION_INTERPRETED_BIT = 0x1;
 
-static JS_ALWAYS_INLINE void
+static MOZ_ALWAYS_INLINE void
 SET_JITINFO(JSFunction * func, const JSJitInfo *info)
 {
     js::shadow::Function *fun = reinterpret_cast<js::shadow::Function *>(func);
     JS_ASSERT(!(fun->flags & JS_FUNCTION_INTERPRETED_BIT));
     fun->jitinfo = info;
 }
 
 /*
  * Engine-internal extensions of jsid.  This code is here only until we
  * eliminate Gecko's dependencies on it!
  */
 
-static JS_ALWAYS_INLINE jsid
+static MOZ_ALWAYS_INLINE jsid
 JSID_FROM_BITS(size_t bits)
 {
     jsid id;
     JSID_BITS(id) = bits;
     return id;
 }
 
 namespace js {
@@ -1712,56 +1712,56 @@ bool IdMatchesAtom(jsid id, JSAtom *atom
  *   integer atoms representable as integer jsids, and does this conversion.
  *
  * - When given a PropertyName*, NameToId can be used which which does not need
  *   to do any dynamic checks.
  *
  * Thus, it is only the rare third case which needs this function, which
  * handles any JSAtom* that is known not to be representable with an int jsid.
  */
-static JS_ALWAYS_INLINE jsid
+static MOZ_ALWAYS_INLINE jsid
 NON_INTEGER_ATOM_TO_JSID(JSAtom *atom)
 {
     JS_ASSERT(((size_t)atom & 0x7) == 0);
     jsid id = JSID_FROM_BITS((size_t)atom);
     JS_ASSERT(js::detail::IdMatchesAtom(id, atom));
     return id;
 }
 
 /* All strings stored in jsids are atomized, but are not necessarily property names. */
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_ATOM(jsid id)
 {
     return JSID_IS_STRING(id);
 }
 
-static JS_ALWAYS_INLINE bool
+static MOZ_ALWAYS_INLINE bool
 JSID_IS_ATOM(jsid id, JSAtom *atom)
 {
     return id == JSID_FROM_BITS((size_t)atom);
 }
 
-static JS_ALWAYS_INLINE JSAtom *
+static MOZ_ALWAYS_INLINE JSAtom *
 JSID_TO_ATOM(jsid id)
 {
     return (JSAtom *)JSID_TO_STRING(id);
 }
 
 JS_STATIC_ASSERT(sizeof(jsid) == sizeof(void*));
 
 namespace js {
 
-static JS_ALWAYS_INLINE JS::Value
+static MOZ_ALWAYS_INLINE JS::Value
 IdToValue(jsid id)
 {
     if (JSID_IS_STRING(id))
         return JS::StringValue(JSID_TO_STRING(id));
-    if (JS_LIKELY(JSID_IS_INT(id)))
+    if (MOZ_LIKELY(JSID_IS_INT(id)))
         return JS::Int32Value(JSID_TO_INT(id));
-    if (JS_LIKELY(JSID_IS_OBJECT(id)))
+    if (MOZ_LIKELY(JSID_IS_OBJECT(id)))
         return JS::ObjectValue(*JSID_TO_OBJECT(id));
     JS_ASSERT(JSID_IS_VOID(id));
     return JS::UndefinedValue();
 }
 
 extern JS_FRIEND_API(bool)
 IsReadOnlyDateMethod(JS::IsAcceptableThis test, JS::NativeImpl method);
 
--- a/js/src/jsgc.cpp
+++ b/js/src/jsgc.cpp
@@ -907,21 +907,21 @@ ArenaHeader *
 Chunk::allocateArena(Zone *zone, AllocKind thingKind)
 {
     JS_ASSERT(hasAvailableArenas());
 
     JSRuntime *rt = zone->runtimeFromAnyThread();
     if (!rt->isHeapMinorCollecting() && rt->gcBytes >= rt->gcMaxBytes)
         return nullptr;
 
-    ArenaHeader *aheader = JS_LIKELY(info.numArenasFreeCommitted > 0)
+    ArenaHeader *aheader = MOZ_LIKELY(info.numArenasFreeCommitted > 0)
                            ? fetchNextFreeArena(rt)
                            : fetchNextDecommittedArena();
     aheader->init(zone, thingKind);
-    if (JS_UNLIKELY(!hasAvailableArenas()))
+    if (MOZ_UNLIKELY(!hasAvailableArenas()))
         removeFromAvailableList();
 
     rt->gcBytes += ArenaSize;
     zone->gcBytes += ArenaSize;
 
     if (zone->gcBytes >= zone->gcTriggerBytes) {
         AutoUnlockGC unlock(rt);
         TriggerZoneGC(zone, JS::gcreason::ALLOC_TRIGGER);
@@ -1407,17 +1407,17 @@ ArenaLists::allocateFromArenaInline(Zone
             al->cursor = &aheader->next;
 
             /*
              * Move the free span stored in the arena to the free list and
              * allocate from it.
              */
             freeLists[thingKind] = aheader->getFirstFreeSpan();
             aheader->setAsFullyUsed();
-            if (JS_UNLIKELY(zone->wasGCStarted())) {
+            if (MOZ_UNLIKELY(zone->wasGCStarted())) {
                 if (zone->needsBarrier()) {
                     aheader->allocatedDuringIncremental = true;
                     zone->runtimeFromMainThread()->gcMarker.delayMarkingArena(aheader);
                 } else if (zone->isGCSweeping()) {
                     PushArenaAllocatedDuringSweep(zone->runtimeFromMainThread(), aheader);
                 }
             }
             return freeLists[thingKind].infallibleAllocate(Arena::thingSize(thingKind));
@@ -1440,17 +1440,17 @@ ArenaLists::allocateFromArenaInline(Zone
      * cursor, so after the GC the most recently added arena will be used first
      * for allocations improving cache locality.
      */
     JS_ASSERT(!*al->cursor);
     ArenaHeader *aheader = chunk->allocateArena(zone, thingKind);
     if (!aheader)
         return nullptr;
 
-    if (JS_UNLIKELY(zone->wasGCStarted())) {
+    if (MOZ_UNLIKELY(zone->wasGCStarted())) {
         if (zone->needsBarrier()) {
             aheader->allocatedDuringIncremental = true;
             zone->runtimeFromMainThread()->gcMarker.delayMarkingArena(aheader);
         } else if (zone->isGCSweeping()) {
             PushArenaAllocatedDuringSweep(zone->runtimeFromMainThread(), aheader);
         }
     }
     aheader->next = al->head;
@@ -1673,33 +1673,33 @@ ArenaLists::refillFreeList(ThreadSafeCon
                  zone->gcBytes > zone->gcTriggerBytes;
 
 #ifdef JS_THREADSAFE
     JS_ASSERT_IF(cx->isJSContext() && allowGC,
                  !cx->asJSContext()->runtime()->currentThreadHasExclusiveAccess());
 #endif
 
     for (;;) {
-        if (JS_UNLIKELY(runGC)) {
+        if (MOZ_UNLIKELY(runGC)) {
             if (void *thing = RunLastDitchGC(cx->asJSContext(), zone, thingKind))
                 return thing;
         }
 
         if (cx->isJSContext()) {
             /*
              * allocateFromArena may fail while the background finalization still
              * run. If we are on the main thread, we want to wait for it to finish
              * and restart. However, checking for that is racy as the background
              * finalization could free some things after allocateFromArena decided
              * to fail but at this point it may have already stopped. To avoid
              * this race we always try to allocate twice.
              */
             for (bool secondAttempt = false; ; secondAttempt = true) {
                 void *thing = cx->allocator()->arenas.allocateFromArenaInline(zone, thingKind);
-                if (JS_LIKELY(!!thing))
+                if (MOZ_LIKELY(!!thing))
                     return thing;
                 if (secondAttempt)
                     break;
 
                 cx->asJSContext()->runtime()->gcHelperThread.waitBackgroundSweepEnd();
             }
         } else {
 #ifdef JS_THREADSAFE
@@ -4741,17 +4741,17 @@ BudgetIncrementalGC(JSRuntime *rt, int64
  * Run one GC "cycle" (either a slice of incremental GC or an entire
  * non-incremental GC. We disable inlining to ensure that the bottom of the
  * stack with possible GC roots recorded in MarkRuntime excludes any pointers we
  * use during the marking implementation.
  *
  * Returns true if we "reset" an existing incremental GC, which would force us
  * to run another cycle.
  */
-static JS_NEVER_INLINE bool
+static MOZ_NEVER_INLINE bool
 GCCycle(JSRuntime *rt, bool incremental, int64_t budget,
         JSGCInvocationKind gckind, JS::gcreason::Reason reason)
 {
     /* If we attempt to invoke the GC while we are running in the GC, assert. */
     JS_ASSERT(!rt->isHeapBusy());
 
     AutoGCSession gcsession(rt);
 
--- a/js/src/jsgc.h
+++ b/js/src/jsgc.h
@@ -564,17 +564,17 @@ class ArenaLists
              * lists.
              */
             JS_ASSERT(aheader->getFirstFreeSpan().isSameNonEmptySpan(headSpan));
             return true;
         }
         return false;
     }
 
-    JS_ALWAYS_INLINE void *allocateFromFreeList(AllocKind thingKind, size_t thingSize) {
+    MOZ_ALWAYS_INLINE void *allocateFromFreeList(AllocKind thingKind, size_t thingSize) {
         return freeLists[thingKind].allocate(thingSize);
     }
 
     template <AllowGC allowGC>
     static void *refillFreeList(ThreadSafeContext *cx, AllocKind thingKind);
 
     /*
      * Moves all arenas from |fromArenaLists| into |this|.  In
--- a/js/src/jsgcinlines.h
+++ b/js/src/jsgcinlines.h
@@ -215,17 +215,17 @@ class CellIterImpl
         JS_ASSERT(!done());
         return cell;
     }
 
     void next() {
         for (;;) {
             if (thing != span->first)
                 break;
-            if (JS_LIKELY(span->hasNext())) {
+            if (MOZ_LIKELY(span->hasNext())) {
                 thing = span->last + thingSize;
                 span = span->nextSpan();
                 break;
             }
             if (aiter.done()) {
                 cell = nullptr;
                 return;
             }
--- a/js/src/jsiter.cpp
+++ b/js/src/jsiter.cpp
@@ -96,23 +96,23 @@ Enumerate(JSContext *cx, HandleObject po
     /*
      * We implement __proto__ using a property on |Object.prototype|, but
      * because __proto__ is highly deserving of removal, we don't want it to
      * show up in property enumeration, even if only for |Object.prototype|
      * (think introspection by Prototype-like frameworks that add methods to
      * the built-in prototypes).  So exclude __proto__ if the object where the
      * property was found has no [[Prototype]] and might be |Object.prototype|.
      */
-    if (JS_UNLIKELY(!pobj->getTaggedProto().isObject() && JSID_IS_ATOM(id, cx->names().proto)))
+    if (MOZ_UNLIKELY(!pobj->getTaggedProto().isObject() && JSID_IS_ATOM(id, cx->names().proto)))
         return true;
 
     if (!(flags & JSITER_OWNONLY) || pobj->is<ProxyObject>() || pobj->getOps()->enumerate) {
         /* If we've already seen this, we definitely won't add it. */
         IdSet::AddPtr p = ht.lookupForAdd(id);
-        if (JS_UNLIKELY(!!p))
+        if (MOZ_UNLIKELY(!!p))
             return true;
 
         /*
          * It's not necessary to add properties to the hash table at the end of
          * the prototype chain, but custom enumeration behaviors might return
          * duplicated properties, so always add in such cases.
          */
         if ((pobj->is<ProxyObject>() || pobj->getProto() || pobj->getOps()->enumerate) && !ht.add(p, id))
@@ -664,23 +664,23 @@ js::GetIterator(JSContext *cx, HandleObj
         if (!vp.isUndefined())
             return true;
     }
 
     /* NB: for (var p in null) succeeds by iterating over no properties. */
 
     AutoIdVector keys(cx);
     if (flags & JSITER_FOREACH) {
-        if (JS_LIKELY(obj != nullptr) && !Snapshot(cx, obj, flags, &keys))
+        if (MOZ_LIKELY(obj != nullptr) && !Snapshot(cx, obj, flags, &keys))
             return false;
         JS_ASSERT(shapes.empty());
         if (!VectorToValueIterator(cx, obj, flags, keys, vp))
             return false;
     } else {
-        if (JS_LIKELY(obj != nullptr) && !Snapshot(cx, obj, flags, &keys))
+        if (MOZ_LIKELY(obj != nullptr) && !Snapshot(cx, obj, flags, &keys))
             return false;
         if (!VectorToKeyIterator(cx, obj, flags, keys, shapes.length(), key, vp))
             return false;
     }
 
     PropertyIteratorObject *iterobj = &vp.toObject().as<PropertyIteratorObject>();
 
     /* Cache the iterator object if possible. */
@@ -752,23 +752,23 @@ js::IteratorConstructor(JSContext *cx, u
     unsigned flags = JSITER_OWNONLY | (keyonly ? 0 : (JSITER_FOREACH | JSITER_KEYVALUE));
 
     if (!ValueToIterator(cx, flags, args[0]))
         return false;
     args.rval().set(args[0]);
     return true;
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 IsIterator(HandleValue v)
 {
     return v.isObject() && v.toObject().hasClass(&PropertyIteratorObject::class_);
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 iterator_next_impl(JSContext *cx, CallArgs args)
 {
     JS_ASSERT(IsIterator(args.thisv()));
 
     RootedObject thisObj(cx, &args.thisv().toObject());
 
     if (!js_IteratorMore(cx, thisObj, args.rval()))
         return false;
@@ -1693,17 +1693,17 @@ SendToGenerator(JSContext *cx, JSGenerat
                 ok = js_ThrowStopIteration(cx);
         }
     }
 
     SetGeneratorClosed(cx, gen);
     return ok;
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 star_generator_next(JSContext *cx, CallArgs args)
 {
     RootedObject thisObj(cx, &args.thisv().toObject());
     JSGenerator *gen = thisObj->as<StarGeneratorObject>().getGenerator();
 
     if (gen->state == JSGEN_CLOSED) {
         JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_GENERATOR_FINISHED);
         return false;
@@ -1715,32 +1715,32 @@ star_generator_next(JSContext *cx, CallA
                             JSDVG_SEARCH_STACK, val, js::NullPtr());
         return false;
     }
 
     return SendToGenerator(cx, JSGENOP_SEND, thisObj, gen, args.get(0), StarGenerator,
                            args.rval());
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 star_generator_throw(JSContext *cx, CallArgs args)
 {
     RootedObject thisObj(cx, &args.thisv().toObject());
 
     JSGenerator *gen = thisObj->as<StarGeneratorObject>().getGenerator();
     if (gen->state == JSGEN_CLOSED) {
         JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_GENERATOR_FINISHED);
         return false;
     }
 
     return SendToGenerator(cx, JSGENOP_THROW, thisObj, gen, args.get(0), StarGenerator,
                            args.rval());
 }
 
-JS_ALWAYS_INLINE bool
+MOZ_ALWAYS_INLINE bool
 legacy_generator_next(JSContext *cx, CallArgs args)
 {
     RootedObject thisObj(cx, &args.thisv().toObject());