Merge inbound to m-c.
authorRyan VanderMeulen <ryanvm@gmail.com>
Fri, 28 Feb 2014 16:03:19 -0500
changeset 171668 8abc76dedec2905c6b150ace5f6ffe3f07d82751
parent 171667 74cf230995da4bcbc7bc864402989cb95c97b734 (current diff)
parent 171593 1f082a704d6d0f7024286df961009883a1445f84 (diff)
child 171669 2ffb87a2c0cfc3d9fff900b552f001a7cadfa965
child 171785 472fd46c20fde1e017c5b7fa3f4f3dc37fd943cf
child 171815 db52c6289d9de2b5a44dc57ebe1b7013c20f613b
push id270
push userpvanderbeken@mozilla.com
push dateThu, 06 Mar 2014 09:24:21 +0000
milestone30.0a1
Merge inbound to m-c.
dom/events/nsDOMNotifyAudioAvailableEvent.cpp
dom/events/nsDOMNotifyAudioAvailableEvent.h
dom/events/nsDOMNotifyPaintEvent.cpp
dom/events/nsDOMNotifyPaintEvent.h
dom/events/nsDOMScrollAreaEvent.cpp
dom/events/nsDOMScrollAreaEvent.h
dom/events/nsDOMTouchEvent.cpp
dom/events/nsDOMTouchEvent.h
dom/events/nsDOMTransitionEvent.cpp
dom/events/nsDOMTransitionEvent.h
dom/events/nsDOMUIEvent.cpp
dom/events/nsDOMUIEvent.h
dom/events/nsDOMXULCommandEvent.cpp
dom/events/nsDOMXULCommandEvent.h
dom/smil/nsDOMTimeEvent.cpp
dom/smil/nsDOMTimeEvent.h
xpcom/reflect/xptcall/src/md/unix/xptcinvoke_asm_ppc64_linux.s
xpcom/reflect/xptcall/src/md/unix/xptcstubs_asm_ppc64_linux.s
--- a/accessible/src/base/nsCoreUtils.cpp
+++ b/accessible/src/base/nsCoreUtils.cpp
@@ -18,21 +18,21 @@
 #include "nsIDocShell.h"
 #include "nsEventListenerManager.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIScrollableFrame.h"
 #include "nsEventStateManager.h"
 #include "nsISelectionPrivate.h"
 #include "nsISelectionController.h"
+#include "mozilla/dom/TouchEvent.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/TouchEvents.h"
 #include "nsView.h"
 #include "nsGkAtoms.h"
-#include "nsDOMTouchEvent.h"
 
 #include "nsComponentManagerUtils.h"
 
 #include "nsITreeBoxObject.h"
 #include "nsITreeColumns.h"
 #include "mozilla/dom/Element.h"
 
 using namespace mozilla;
@@ -136,27 +136,26 @@ nsCoreUtils::DispatchMouseEvent(uint32_t
   aPresShell->HandleEventWithTarget(&event, aFrame, aContent, &status);
 }
 
 void
 nsCoreUtils::DispatchTouchEvent(uint32_t aEventType, int32_t aX, int32_t aY,
                                 nsIContent* aContent, nsIFrame* aFrame,
                                 nsIPresShell* aPresShell, nsIWidget* aRootWidget)
 {
-  if (!nsDOMTouchEvent::PrefEnabled())
+  if (!dom::TouchEvent::PrefEnabled())
     return;
 
   WidgetTouchEvent event(true, aEventType, aRootWidget);
 
   event.time = PR_IntervalNow();
 
   // XXX: Touch has an identifier of -1 to hint that it is synthesized.
-  nsRefPtr<mozilla::dom::Touch> t =
-    new mozilla::dom::Touch(-1, nsIntPoint(aX, aY),
-                            nsIntPoint(1, 1), 0.0f, 1.0f);
+  nsRefPtr<dom::Touch> t = new dom::Touch(-1, nsIntPoint(aX, aY),
+                                          nsIntPoint(1, 1), 0.0f, 1.0f);
   t->SetTarget(aContent);
   event.touches.AppendElement(t);
   nsEventStatus status = nsEventStatus_eIgnore;
   aPresShell->HandleEventWithTarget(&event, aFrame, aContent, &status);
 }
 
 uint32_t
 nsCoreUtils::GetAccessKeyFor(nsIContent* aContent)
--- a/accessible/src/generic/Accessible.cpp
+++ b/accessible/src/generic/Accessible.cpp
@@ -928,17 +928,16 @@ Accessible::GetBoundsRect(nsRect& aTotal
       nsIFrame* canvasFrame = frame->GetParent();
       while (canvasFrame && (canvasFrame->GetType() != nsGkAtoms::HTMLCanvasFrame))
         canvasFrame = canvasFrame->GetParent();
 
       // make the canvas the bounding frame
       if (canvasFrame) {
         *aBoundingFrame = canvasFrame;
 
-        nsPresContext* presContext = mDoc->PresContext();
         aTotalBounds = *hitRegionRect;
 
         return;
       }
     }
 
     *aBoundingFrame = nsLayoutUtils::GetContainingBlockForClientRect(frame);
     aTotalBounds = nsLayoutUtils::
--- a/accessible/src/generic/HyperTextAccessible.cpp
+++ b/accessible/src/generic/HyperTextAccessible.cpp
@@ -1786,17 +1786,16 @@ HyperTextAccessible::GetSpellTextAttribu
   if (!domSel)
     return NS_OK;
 
   int32_t rangeCount = domSel->GetRangeCount();
   if (rangeCount <= 0)
     return NS_OK;
 
   int32_t startHTOffset = 0, endHTOffset = 0;
-  nsresult rv = NS_OK;
   for (int32_t idx = 0; idx < rangeCount; idx++) {
     nsRange* range = domSel->GetRangeAt(idx);
     if (range->Collapsed())
       continue;
 
     // See if the point comes after the range in which case we must continue in
     // case there is another range after this one.
     nsINode* endNode = range->GetEndParent();
--- a/build/automation.py.in
+++ b/build/automation.py.in
@@ -528,17 +528,17 @@ class Automation(object):
       try:
         totalMemory = int(os.popen("free").readlines()[1].split()[1])
 
         # Only 4 GB RAM or less available? Use custom ASan options to reduce
         # the amount of resources required to do the tests. Standard options 
         # will otherwise lead to OOM conditions on the current test slaves.
         if totalMemory <= 1024 * 1024 * 4:
           self.log.info("INFO | automation.py | ASan running in low-memory configuration")
-          env["ASAN_OPTIONS"] = "quarantine_size=50331648"
+          env["ASAN_OPTIONS"] = "quarantine_size=50331648:malloc_context_size=5"
         else:
           self.log.info("INFO | automation.py | ASan running in default memory configuration")
       except OSError,err:
         self.log.info("Failed determine available memory, disabling ASan low-memory configuration: %s", err.strerror)
       except:
         self.log.info("Failed determine available memory, disabling ASan low-memory configuration")
 
     return env
--- a/build/automationutils.py
+++ b/build/automationutils.py
@@ -474,17 +474,17 @@ def environment(xrePath, env=None, crash
       totalMemory = systemMemory()
 
       # Only 4 GB RAM or less available? Use custom ASan options to reduce
       # the amount of resources required to do the tests. Standard options
       # will otherwise lead to OOM conditions on the current test slaves.
       message = "INFO | runtests.py | ASan running in %s configuration"
       if totalMemory <= 1024 * 1024 * 4:
         message = message % 'low-memory'
-        env["ASAN_OPTIONS"] = "quarantine_size=50331648"
+        env["ASAN_OPTIONS"] = "quarantine_size=50331648:malloc_context_size=5"
       else:
         message = message % 'default memory'
     except OSError,err:
       log.info("Failed determine available memory, disabling ASan low-memory configuration: %s", err.strerror)
     except:
       log.info("Failed determine available memory, disabling ASan low-memory configuration")
     else:
       log.info(message)
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -27,17 +27,16 @@
 
 class imgIRequest;
 class nsAString;
 class nsBindingManager;
 class nsCSSStyleSheet;
 class nsIDocShell;
 class nsDocShell;
 class nsDOMNavigationTiming;
-class nsDOMTouchList;
 class nsEventStates;
 class nsFrameLoader;
 class nsHTMLCSSStyleSheet;
 class nsHTMLDocument;
 class nsHTMLStyleSheet;
 class nsIAtom;
 class nsIBFCacheEntry;
 class nsIBoxObject;
@@ -108,16 +107,17 @@ class FrameRequestCallback;
 class HTMLBodyElement;
 struct LifecycleCallbackArgs;
 class Link;
 class GlobalObject;
 class NodeFilter;
 class NodeIterator;
 class ProcessingInstruction;
 class Touch;
+class TouchList;
 class TreeWalker;
 class UndoManager;
 class XPathEvaluator;
 template<typename> class OwningNonNull;
 template<typename> class Sequence;
 
 template<typename, typename> class CallbackObjectHolder;
 typedef CallbackObjectHolder<NodeFilter, nsIDOMNodeFilter> NodeFilterHolder;
@@ -2195,21 +2195,21 @@ public:
              nsISupports* aResult, mozilla::ErrorResult& rv);
   // Touch event handlers already on nsINode
   already_AddRefed<mozilla::dom::Touch>
     CreateTouch(nsIDOMWindow* aView, mozilla::dom::EventTarget* aTarget,
                 int32_t aIdentifier, int32_t aPageX, int32_t aPageY,
                 int32_t aScreenX, int32_t aScreenY, int32_t aClientX,
                 int32_t aClientY, int32_t aRadiusX, int32_t aRadiusY,
                 float aRotationAngle, float aForce);
-  already_AddRefed<nsDOMTouchList> CreateTouchList();
-  already_AddRefed<nsDOMTouchList>
+  already_AddRefed<mozilla::dom::TouchList> CreateTouchList();
+  already_AddRefed<mozilla::dom::TouchList>
     CreateTouchList(mozilla::dom::Touch& aTouch,
                     const mozilla::dom::Sequence<mozilla::dom::OwningNonNull<mozilla::dom::Touch> >& aTouches);
-  already_AddRefed<nsDOMTouchList>
+  already_AddRefed<mozilla::dom::TouchList>
     CreateTouchList(const mozilla::dom::Sequence<mozilla::dom::OwningNonNull<mozilla::dom::Touch> >& aTouches);
 
   void SetStyleSheetChangeEventsEnabled(bool aValue)
   {
     mStyleSheetChangeEventsEnabled = aValue;
   }
 
   bool StyleSheetChangeEventsEnabled() const
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -34,16 +34,17 @@
 #include "mozilla/Base64.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/dom/DocumentFragment.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/HTMLMediaElement.h"
 #include "mozilla/dom/HTMLTemplateElement.h"
 #include "mozilla/dom/HTMLContentElement.h"
 #include "mozilla/dom/TextDecoder.h"
+#include "mozilla/dom/TouchEvent.h"
 #include "mozilla/dom/ShadowRoot.h"
 #include "mozilla/InternalMutationEvent.h"
 #include "mozilla/Likely.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Selection.h"
 #include "mozilla/TextEvents.h"
 #include "nsAString.h"
@@ -65,17 +66,16 @@
 #include "nsCycleCollector.h"
 #include "nsDataHashtable.h"
 #include "nsDocShellCID.h"
 #include "nsDocument.h"
 #include "nsDOMCID.h"
 #include "mozilla/dom/DataTransfer.h"
 #include "nsDOMJSUtils.h"
 #include "nsDOMMutationObserver.h"
-#include "nsDOMTouchEvent.h"
 #include "nsError.h"
 #include "nsEventDispatcher.h"
 #include "nsEventListenerManager.h"
 #include "nsEventStateManager.h"
 #include "nsFocusManager.h"
 #include "nsGenericHTMLElement.h"
 #include "nsGenericHTMLFrameElement.h"
 #include "nsGkAtoms.h"
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -174,18 +174,18 @@
 #include "mozilla/dom/DOMImplementation.h"
 #include "mozilla/dom/ShadowRoot.h"
 #include "mozilla/dom/Comment.h"
 #include "nsTextNode.h"
 #include "mozilla/dom/Link.h"
 #include "mozilla/dom/HTMLElementBinding.h"
 #include "mozilla/dom/SVGElementBinding.h"
 #include "nsXULAppAPI.h"
-#include "nsDOMTouchEvent.h"
 #include "mozilla/dom/Touch.h"
+#include "mozilla/dom/TouchEvent.h"
 #include "DictionaryHelpers.h"
 #include "GeneratedEvents.h"
 
 #include "mozilla/Preferences.h"
 
 #include "imgILoader.h"
 #include "imgRequestProxy.h"
 #include "nsWrapperCacheInlines.h"
@@ -10008,39 +10008,39 @@ nsIDocument::CreateTouch(nsIDOMWindow* a
                                     aScreenX, aScreenY,
                                     aClientX, aClientY,
                                     aRadiusX, aRadiusY,
                                     aRotationAngle,
                                     aForce);
   return touch.forget();
 }
 
-already_AddRefed<nsDOMTouchList>
+already_AddRefed<TouchList>
 nsIDocument::CreateTouchList()
 {
-  nsRefPtr<nsDOMTouchList> retval = new nsDOMTouchList(ToSupports(this));
+  nsRefPtr<TouchList> retval = new TouchList(ToSupports(this));
   return retval.forget();
 }
 
-already_AddRefed<nsDOMTouchList>
+already_AddRefed<TouchList>
 nsIDocument::CreateTouchList(Touch& aTouch,
                              const Sequence<OwningNonNull<Touch> >& aTouches)
 {
-  nsRefPtr<nsDOMTouchList> retval = new nsDOMTouchList(ToSupports(this));
+  nsRefPtr<TouchList> retval = new TouchList(ToSupports(this));
   retval->Append(&aTouch);
   for (uint32_t i = 0; i < aTouches.Length(); ++i) {
     retval->Append(aTouches[i].get());
   }
   return retval.forget();
 }
 
-already_AddRefed<nsDOMTouchList>
+already_AddRefed<TouchList>
 nsIDocument::CreateTouchList(const Sequence<OwningNonNull<Touch> >& aTouches)
 {
-  nsRefPtr<nsDOMTouchList> retval = new nsDOMTouchList(ToSupports(this));
+  nsRefPtr<TouchList> retval = new TouchList(ToSupports(this));
   for (uint32_t i = 0; i < aTouches.Length(); ++i) {
     retval->Append(aTouches[i].get());
   }
   return retval.forget();
 }
 
 already_AddRefed<nsDOMCaretPosition>
 nsIDocument::CaretPositionFromPoint(float aX, float aY)
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -92,19 +92,19 @@
 #include "mozilla/BloomFilter.h"
 
 #include "HTMLPropertiesCollection.h"
 #include "nsVariant.h"
 #include "nsDOMSettableTokenList.h"
 #include "nsThreadUtils.h"
 #include "nsTextFragment.h"
 #include "mozilla/dom/BindingUtils.h"
+#include "mozilla/dom/TouchEvent.h"
 #include "mozilla/ErrorResult.h"
 #include "nsHTMLDocument.h"
-#include "nsDOMTouchEvent.h"
 #include "nsGlobalWindow.h"
 #include "mozilla/dom/HTMLBodyElement.h"
 #include "imgIContainer.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 class nsINodeInfo;
@@ -1950,17 +1950,17 @@ nsGenericHTMLElement::SetUndoScopeIntern
   }
   return NS_OK;
 }
 
 // static
 bool
 nsGenericHTMLElement::TouchEventsEnabled(JSContext* /* unused */, JSObject* /* unused */)
 {
-  return nsDOMTouchEvent::PrefEnabled();
+  return TouchEvent::PrefEnabled();
 }
 
 //----------------------------------------------------------------------
 
 nsGenericHTMLFormElement::nsGenericHTMLFormElement(already_AddRefed<nsINodeInfo> aNodeInfo)
   : nsGenericHTMLElement(aNodeInfo)
   , mForm(nullptr)
   , mFieldSet(nullptr)
--- a/content/media/MediaSegment.h
+++ b/content/media/MediaSegment.h
@@ -263,18 +263,18 @@ protected:
     }
     mChunks.MoveElementsFrom(aSource->mChunks);
   }
 
   void AppendSliceInternal(const MediaSegmentBase<C, Chunk>& aSource,
                            TrackTicks aStart, TrackTicks aEnd)
   {
     NS_ASSERTION(aStart <= aEnd, "Endpoints inverted");
-    NS_ASSERTION(aStart >= 0 && aEnd <= aSource.mDuration,
-                 "Slice out of range");
+    NS_WARN_IF_FALSE(aStart >= 0 && aEnd <= aSource.mDuration,
+                     "Slice out of range");
     mDuration += aEnd - aStart;
     TrackTicks offset = 0;
     for (uint32_t i = 0; i < aSource.mChunks.Length() && offset < aEnd; ++i) {
       const Chunk& c = aSource.mChunks[i];
       TrackTicks start = std::max(aStart, offset);
       TrackTicks nextOffset = offset + c.GetDuration();
       TrackTicks end = std::min(aEnd, nextOffset);
       if (start < end) {
--- a/content/media/MediaStreamGraph.cpp
+++ b/content/media/MediaStreamGraph.cpp
@@ -1234,19 +1234,19 @@ MediaStreamGraphImpl::RunThread()
             // Since an AudioNodeStream is present, go ahead and
             // produce audio block by block for all the rest of the streams.
             ProduceDataForStreamsBlockByBlock(i, n->SampleRate(), prevComputedTime, mStateComputedTime);
             ticksProcessed += TimeToTicksRoundDown(n->SampleRate(), mStateComputedTime - prevComputedTime);
             doneAllProducing = true;
           } else {
             ps->ProduceOutput(prevComputedTime, mStateComputedTime,
                               ProcessedMediaStream::ALLOW_FINISH);
-            NS_ASSERTION(stream->mBuffer.GetEnd() >=
-                         GraphTimeToStreamTime(stream, mStateComputedTime),
-                       "Stream did not produce enough data");
+            NS_WARN_IF_FALSE(stream->mBuffer.GetEnd() >=
+                             GraphTimeToStreamTime(stream, mStateComputedTime),
+                             "Stream did not produce enough data");
           }
         }
       }
       NotifyHasCurrentData(stream);
       if (mRealtime) {
         // Only playback audio and video in real-time mode
         CreateOrDestroyAudioStreams(prevComputedTime, stream);
         PlayAudio(stream, prevComputedTime, mStateComputedTime);
--- a/content/media/StreamBuffer.h
+++ b/content/media/StreamBuffer.h
@@ -58,17 +58,17 @@ inline StreamTime TicksToTimeRound(Track
   NS_ASSERTION(0 < aRate && aRate <= TRACK_RATE_MAX, "Bad rate");
   NS_ASSERTION(0 <= aTicks && aTicks <= TRACK_TICKS_MAX, "Bad samples");
   return ((aTicks << MEDIA_TIME_FRAC_BITS) + aRate/2)/aRate;
 }
 
 inline StreamTime TicksToTimeRoundDown(TrackRate aRate, TrackTicks aTicks)
 {
   NS_ASSERTION(0 < aRate && aRate <= TRACK_RATE_MAX, "Bad rate");
-  NS_ASSERTION(0 <= aTicks && aTicks <= TRACK_TICKS_MAX, "Bad samples");
+  NS_WARN_IF_FALSE(0 <= aTicks && aTicks <= TRACK_TICKS_MAX, "Bad samples");
   return (aTicks << MEDIA_TIME_FRAC_BITS)/aRate;
 }
 
 /**
  * This object contains the decoded data for a stream's tracks.
  * A StreamBuffer can be appended to. Logically a StreamBuffer only gets longer,
  * but we also have the ability to "forget" data before a certain time that
  * we know won't be used again. (We prune a whole number of seconds internally.)
--- a/content/media/TrackUnionStream.h
+++ b/content/media/TrackUnionStream.h
@@ -244,18 +244,18 @@ protected:
       if (interval.mStart >= interval.mEnd)
         break;
       next = interval.mEnd;
 
       // Ticks >= startTicks and < endTicks are in the interval
       StreamTime outputEnd = GraphTimeToStreamTime(interval.mEnd);
       TrackTicks startTicks = outputTrack->GetEnd();
       StreamTime outputStart = GraphTimeToStreamTime(interval.mStart);
-      NS_ASSERTION(startTicks == TimeToTicksRoundUp(rate, outputStart),
-                   "Samples missing");
+      NS_WARN_IF_FALSE(startTicks == TimeToTicksRoundUp(rate, outputStart),
+                       "Samples missing");
       TrackTicks endTicks = TimeToTicksRoundUp(rate, outputEnd);
       TrackTicks ticks = endTicks - startTicks;
       StreamTime inputStart = source->GraphTimeToStreamTime(interval.mStart);
 
       if (interval.mInputIsBlocked) {
         // Maybe the input track ended?
         segment->AppendNullData(ticks);
         STREAM_LOG(PR_LOG_DEBUG+1, ("TrackUnionStream %p appending %lld ticks of null data to track %d",
--- a/content/svg/content/src/SVGZoomEvent.cpp
+++ b/content/svg/content/src/SVGZoomEvent.cpp
@@ -15,18 +15,18 @@ namespace mozilla {
 namespace dom {
 
 //----------------------------------------------------------------------
 // Implementation
 
 SVGZoomEvent::SVGZoomEvent(EventTarget* aOwner,
                            nsPresContext* aPresContext,
                            WidgetGUIEvent* aEvent)
-  : nsDOMUIEvent(aOwner, aPresContext,
-                 aEvent ? aEvent : new WidgetGUIEvent(false, NS_SVG_ZOOM, 0))
+  : UIEvent(aOwner, aPresContext,
+            aEvent ? aEvent : new WidgetGUIEvent(false, NS_SVG_ZOOM, 0))
   , mPreviousScale(0)
   , mNewScale(0)
 {
   if (aEvent) {
     mEventIsInternal = false;
   }
   else {
     mEventIsInternal = true;
--- a/content/svg/content/src/SVGZoomEvent.h
+++ b/content/svg/content/src/SVGZoomEvent.h
@@ -1,38 +1,38 @@
 /* -*- Mode: C++; 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/. */
 
 #ifndef mozilla_dom_SVGZoomEvent_h
 #define mozilla_dom_SVGZoomEvent_h
 
+#include "DOMSVGPoint.h"
+#include "mozilla/dom/UIEvent.h"
+#include "mozilla/dom/SVGZoomEventBinding.h"
+#include "mozilla/EventForwards.h"
 #include "nsAutoPtr.h"
-#include "nsDOMUIEvent.h"
-#include "DOMSVGPoint.h"
-#include "mozilla/EventForwards.h"
-#include "mozilla/dom/SVGZoomEventBinding.h"
 
 class nsPresContext;
 
 namespace mozilla {
 
 class nsISVGPoint;
 
 namespace dom {
 
-class SVGZoomEvent MOZ_FINAL : public nsDOMUIEvent
+class SVGZoomEvent MOZ_FINAL : public UIEvent
 {
 public:
   SVGZoomEvent(EventTarget* aOwner, nsPresContext* aPresContext,
                WidgetGUIEvent* aEvent);
 
   // Forward to base class
-  NS_FORWARD_TO_NSDOMUIEVENT
+  NS_FORWARD_TO_UIEVENT
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
     return SVGZoomEventBinding::Wrap(aCx, aScope, this);
   }
 
   float PreviousScale() const
--- a/dom/base/nsDOMClassInfo.cpp
+++ b/dom/base/nsDOMClassInfo.cpp
@@ -131,17 +131,17 @@
 
 // Drag and drop
 #include "nsIDOMFile.h"
 #include "nsDOMBlobBuilder.h" // nsDOMMultipartFile
 
 #include "nsIEventListenerService.h"
 #include "nsIMessageManager.h"
 
-#include "nsDOMTouchEvent.h"
+#include "mozilla/dom/TouchEvent.h"
 
 #include "nsWrapperCacheInlines.h"
 #include "mozilla/dom/HTMLCollectionBinding.h"
 
 #include "nsIDOMMobileMessageManager.h"
 #include "nsIDOMMozSmsMessage.h"
 #include "nsIDOMMozMmsMessage.h"
 #include "nsIDOMSmsFilter.h"
@@ -863,27 +863,27 @@ nsDOMClassInfo::RegisterExternalClasses(
   DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindow)                                        \
   DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowB2G)                                     \
   DOM_CLASSINFO_MAP_ENTRY(nsIDOMJSWindow)                                      \
   DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)                                   \
   DOM_CLASSINFO_MAP_ENTRY(nsIInlineEventHandlers)                              \
   DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowPerformance)                             \
   DOM_CLASSINFO_MAP_ENTRY(nsIInterfaceRequestor)                               \
   DOM_CLASSINFO_MAP_CONDITIONAL_ENTRY(nsITouchEventReceiver,                   \
-                                      nsDOMTouchEvent::PrefEnabled())
+                                      TouchEvent::PrefEnabled())
 #else // !MOZ_B2G
 #define DOM_CLASSINFO_WINDOW_MAP_ENTRIES                                       \
   DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindow)                                        \
   DOM_CLASSINFO_MAP_ENTRY(nsIDOMJSWindow)                                      \
   DOM_CLASSINFO_MAP_ENTRY(nsIDOMEventTarget)                                   \
   DOM_CLASSINFO_MAP_ENTRY(nsIInlineEventHandlers)                              \
   DOM_CLASSINFO_MAP_ENTRY(nsIDOMWindowPerformance)                             \
   DOM_CLASSINFO_MAP_ENTRY(nsIInterfaceRequestor)                               \
   DOM_CLASSINFO_MAP_CONDITIONAL_ENTRY(nsITouchEventReceiver,                   \
-                                      nsDOMTouchEvent::PrefEnabled())
+                                      TouchEvent::PrefEnabled())
 #endif // MOZ_B2G
 
 nsresult
 nsDOMClassInfo::Init()
 {
   /* Errors that can trigger early returns are done first,
      otherwise nsDOMClassInfo is left in a half inited state. */
   static_assert(sizeof(uintptr_t) == sizeof(void*),
--- a/dom/base/nsDOMClassInfoID.h
+++ b/dom/base/nsDOMClassInfoID.h
@@ -59,31 +59,33 @@ DOMCI_CASTABLE_INTERFACE(nsIDocument, ns
 DOMCI_CASTABLE_INTERFACE(nsDocument, nsIDocument, 5, _extra)                  \
 DOMCI_CASTABLE_INTERFACE(nsGenericHTMLElement, nsIContent, 6, _extra)         \
 DOMCI_CASTABLE_INTERFACE(nsHTMLDocument, nsIDocument, 7, _extra)              \
 DOMCI_CASTABLE_INTERFACE(nsStyledElement, nsStyledElement, 8, _extra)         \
 DOMCI_CASTABLE_INTERFACE(nsSVGElement, nsIContent, 9, _extra)                 \
 /* NOTE: When removing the casts below, remove the nsDOMEventBase class */    \
 DOMCI_CASTABLE_NODECL_INTERFACE(mozilla::dom::MouseEvent,                     \
                                 nsDOMEventBase, 10, _extra)                   \
-DOMCI_CASTABLE_INTERFACE(nsDOMUIEvent, nsDOMEventBase, 11, _extra)            \
+DOMCI_CASTABLE_NODECL_INTERFACE(mozilla::dom::UIEvent,                        \
+                                nsDOMEventBase, 11, _extra)                   \
 DOMCI_CASTABLE_INTERFACE(nsGlobalWindow, nsIDOMEventTarget, 12, _extra)
 
 // Make sure all classes mentioned in DOMCI_CASTABLE_INTERFACES
 // have been declared.
 #define DOMCI_CASTABLE_NODECL_INTERFACE(_interface, _u1, _u2, _u3) /* Nothing */
 #define DOMCI_CASTABLE_INTERFACE(_interface, _u1, _u2, _u3) class _interface;
 DOMCI_CASTABLE_INTERFACES(unused)
 #undef DOMCI_CASTABLE_INTERFACE
 #undef DOMCI_CASTABLE_NODECL_INTERFACE
 namespace mozilla {
 namespace dom {
 class Element;
 class EventTarget;
 class MouseEvent;
+class UIEvent;
 } // namespace dom
 } // namespace mozilla
 
 #define DOMCI_CASTABLE_NODECL_INTERFACE DOMCI_CASTABLE_INTERFACE
 
 #ifdef MOZILLA_INTERNAL_API
 
 #define DOMCI_CLASS(_dom_class)                                               \
--- a/dom/base/nsJSEnvironment.cpp
+++ b/dom/base/nsJSEnvironment.cpp
@@ -716,29 +716,18 @@ static const char js_strict_option_str[]
 #ifdef DEBUG
 static const char js_strict_debug_option_str[] = JS_OPTIONS_DOT_STR "strict.debug";
 #endif
 static const char js_werror_option_str[] = JS_OPTIONS_DOT_STR "werror";
 #ifdef JS_GC_ZEAL
 static const char js_zeal_option_str[]        = JS_OPTIONS_DOT_STR "gczeal";
 static const char js_zeal_frequency_str[]     = JS_OPTIONS_DOT_STR "gczeal.frequency";
 #endif
-static const char js_typeinfer_content_str[]  = JS_OPTIONS_DOT_STR "typeinference.content";
-static const char js_typeinfer_chrome_str[]   = JS_OPTIONS_DOT_STR "typeinference.chrome";
 static const char js_memlog_option_str[]      = JS_OPTIONS_DOT_STR "mem.log";
 static const char js_memnotify_option_str[]   = JS_OPTIONS_DOT_STR "mem.notify";
-static const char js_asmjs_content_str[]      = JS_OPTIONS_DOT_STR "asmjs";
-static const char js_baselinejit_content_str[] = JS_OPTIONS_DOT_STR "baselinejit.content";
-static const char js_baselinejit_chrome_str[]  = JS_OPTIONS_DOT_STR "baselinejit.chrome";
-static const char js_baselinejit_eager_str[]  = JS_OPTIONS_DOT_STR "baselinejit.unsafe_eager_compilation";
-static const char js_ion_content_str[]        = JS_OPTIONS_DOT_STR "ion.content";
-static const char js_ion_chrome_str[]         = JS_OPTIONS_DOT_STR "ion.chrome";
-static const char js_ion_eager_str[]          = JS_OPTIONS_DOT_STR "ion.unsafe_eager_compilation";
-static const char js_parallel_parsing_str[]   = JS_OPTIONS_DOT_STR "parallel_parsing";
-static const char js_ion_parallel_compilation_str[] = JS_OPTIONS_DOT_STR "ion.parallel_compilation";
 
 void
 nsJSContext::JSOptionChangedCallback(const char *pref, void *data)
 {
   nsJSContext *context = reinterpret_cast<nsJSContext *>(data);
   JSContext *cx = context->mContext;
 
   sPostGCEventsToConsole = Preferences::GetBool(js_memlog_option_str);
@@ -751,69 +740,27 @@ nsJSContext::JSOptionChangedCallback(con
   // So ask for the member directly instead.
   nsIScriptGlobalObject *global = context->GetGlobalObjectRef();
 
   // XXX should we check for sysprin instead of a chrome window, to make
   // XXX components be covered by the chrome pref instead of the content one?
   nsCOMPtr<nsIDOMWindow> contentWindow(do_QueryInterface(global));
   nsCOMPtr<nsIDOMChromeWindow> chromeWindow(do_QueryInterface(global));
 
-  bool useTypeInference = Preferences::GetBool((chromeWindow || !contentWindow) ?
-                                               js_typeinfer_chrome_str :
-                                               js_typeinfer_content_str);
-  bool useBaselineJIT = Preferences::GetBool((chromeWindow || !contentWindow) ?
-                                               js_baselinejit_chrome_str :
-                                               js_baselinejit_content_str);
-  bool useBaselineJITEager = Preferences::GetBool(js_baselinejit_eager_str);
-  bool useIon = Preferences::GetBool((chromeWindow || !contentWindow) ?
-                                               js_ion_chrome_str :
-                                               js_ion_content_str);
-  bool useIonEager = Preferences::GetBool(js_ion_eager_str);
-  bool useAsmJS = Preferences::GetBool(js_asmjs_content_str);
-  bool parallelParsing = Preferences::GetBool(js_parallel_parsing_str);
-  bool parallelIonCompilation = Preferences::GetBool(js_ion_parallel_compilation_str);
-  nsCOMPtr<nsIXULRuntime> xr = do_GetService(XULRUNTIME_SERVICE_CONTRACTID);
-  if (xr) {
-    bool safeMode = false;
-    xr->GetInSafeMode(&safeMode);
-    if (safeMode) {
-      useTypeInference = false;
-      useBaselineJIT = false;
-      useBaselineJITEager = false;
-      useIon = false;
-      useIonEager = false;
-      useAsmJS = false;
-    }
-  }
-
-  JS::ContextOptionsRef(cx).setTypeInference(useTypeInference)
-                           .setBaseline(useBaselineJIT)
-                           .setIon(useIon)
-                           .setAsmJS(useAsmJS);
-
 #ifdef DEBUG
   // In debug builds, warnings are enabled in chrome context if
   // javascript.options.strict.debug is true
   if (Preferences::GetBool(js_strict_debug_option_str) &&
       (chromeWindow || !contentWindow)) {
     JS::ContextOptionsRef(cx).setExtraWarnings(true);
   }
 #endif
 
   JS::ContextOptionsRef(cx).setWerror(Preferences::GetBool(js_werror_option_str));
 
-  ::JS_SetParallelParsingEnabled(context->mContext, parallelParsing);
-  ::JS_SetParallelIonCompilationEnabled(context->mContext, parallelIonCompilation);
-
-  ::JS_SetGlobalJitCompilerOption(context->mContext, JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER,
-                                  (useBaselineJITEager ? 0 : -1));
-
-  ::JS_SetGlobalJitCompilerOption(context->mContext, JSJITCOMPILER_ION_USECOUNT_TRIGGER,
-                                  (useIonEager ? 0 : -1));
-
 #ifdef JS_GC_ZEAL
   int32_t zeal = Preferences::GetInt(js_zeal_option_str, -1);
   int32_t frequency = Preferences::GetInt(js_zeal_frequency_str, JS_DEFAULT_ZEAL_FREQ);
   if (zeal >= 0)
     ::JS_SetGCZeal(context->mContext, (uint8_t)zeal, frequency);
 #endif
 }
 
--- a/dom/base/nsPIDOMWindow.h
+++ b/dom/base/nsPIDOMWindow.h
@@ -335,20 +335,21 @@ public:
     return mOuterWindow && mOuterWindow->GetCurrentInnerWindow() == this;
   }
 
   // Returns true if the document of this window is the active document.  This
   // is not identical to IsCurrentInnerWindow() because document.open() will
   // keep the same document active but create a new window.
   bool HasActiveDocument()
   {
+    MOZ_ASSERT(IsInnerWindow());
     return IsCurrentInnerWindow() ||
-      (GetOuterWindow() &&
-       GetOuterWindow()->GetCurrentInnerWindow() &&
-       GetOuterWindow()->GetCurrentInnerWindow()->GetDoc() == mDoc);
+      (mOuterWindow &&
+       mOuterWindow->GetCurrentInnerWindow() &&
+       mOuterWindow->GetCurrentInnerWindow()->GetDoc() == mDoc);
   }
 
   bool IsOuterWindow() const
   {
     return !IsInnerWindow();
   }
 
   virtual bool WouldReuseInnerWindow(nsIDocument *aNewDocument) = 0;
--- a/dom/base/nsScreen.cpp
+++ b/dom/base/nsScreen.cpp
@@ -217,74 +217,16 @@ nsScreen::GetLockOrientationPermission()
         nsIPrincipal::APP_STATUS_INSTALLED) {
     return LOCK_ALLOWED;
   }
 
   // Other content must be full-screen in order to lock orientation.
   return doc->MozFullScreen() ? FULLSCREEN_LOCK_ALLOWED : LOCK_DENIED;
 }
 
-NS_IMETHODIMP
-nsScreen::MozLockOrientation(JS::Handle<JS::Value> aOrientation, JSContext* aCx,
-                             bool* aReturn)
-{
-  if (aOrientation.isObject()) {
-    JS::Rooted<JSObject*> seq(aCx, &aOrientation.toObject());
-    if (IsArrayLike(aCx, seq)) {
-      uint32_t length;
-      // JS_GetArrayLength actually works on all objects
-      if (!JS_GetArrayLength(aCx, seq, &length)) {
-        return NS_ERROR_FAILURE;
-      }
-
-      Sequence<nsString> orientations;
-      if (!orientations.SetCapacity(length)) {
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
-
-      for (uint32_t i = 0; i < length; ++i) {
-        JS::Rooted<JS::Value> temp(aCx);
-        if (!JS_GetElement(aCx, seq, i, &temp)) {
-          return NS_ERROR_FAILURE;
-        }
-
-        JS::Rooted<JSString*> jsString(aCx, JS::ToString(aCx, temp));
-        if (!jsString) {
-          return NS_ERROR_FAILURE;
-        }
-
-        nsDependentJSString str;
-        if (!str.init(aCx, jsString)) {
-          return NS_ERROR_FAILURE;
-        }
-
-        *orientations.AppendElement() = str;
-      }
-
-      ErrorResult rv;
-      *aReturn = MozLockOrientation(orientations, rv);
-      return rv.ErrorCode();
-    }
-  }
-
-  JS::Rooted<JSString*> jsString(aCx, JS::ToString(aCx, aOrientation));
-  if (!jsString) {
-    return NS_ERROR_FAILURE;
-  }
-
-  nsDependentJSString orientation;
-  if (!orientation.init(aCx, jsString)) {
-    return NS_ERROR_FAILURE;
-  }
-
-  ErrorResult rv;
-  *aReturn = MozLockOrientation(orientation, rv);
-  return rv.ErrorCode();
-}
-
 bool
 nsScreen::MozLockOrientation(const nsAString& aOrientation, ErrorResult& aRv)
 {
   nsString orientation(aOrientation);
   Sequence<nsString> orientations;
   if (!orientations.AppendElement(orientation)) {
     aRv.Throw(NS_ERROR_OUT_OF_MEMORY);
     return false;
@@ -360,23 +302,16 @@ nsScreen::MozLockOrientation(const Seque
 }
 
 void
 nsScreen::MozUnlockOrientation()
 {
   hal::UnlockScreenOrientation();
 }
 
-NS_IMETHODIMP
-nsScreen::SlowMozUnlockOrientation()
-{
-  MozUnlockOrientation();
-  return NS_OK;
-}
-
 bool
 nsScreen::IsDeviceSizePageSize()
 {
   nsPIDOMWindow* owner = GetOwner();
   if (owner) {
     nsIDocShell* docShell = owner->GetDocShell();
     if (docShell) {
       return docShell->GetDeviceSizeIsPageSize();
--- a/dom/bindings/BindingUtils.h
+++ b/dom/bindings/BindingUtils.h
@@ -259,22 +259,16 @@ UnwrapObject(JSObject* obj, U& value)
 inline bool
 IsNotDateOrRegExp(JSContext* cx, JS::Handle<JSObject*> obj)
 {
   MOZ_ASSERT(obj);
   return !JS_ObjectIsDate(cx, obj) && !JS_ObjectIsRegExp(cx, obj);
 }
 
 MOZ_ALWAYS_INLINE bool
-IsArrayLike(JSContext* cx, JS::Handle<JSObject*> obj)
-{
-  return IsNotDateOrRegExp(cx, obj);
-}
-
-MOZ_ALWAYS_INLINE bool
 IsObjectValueConvertibleToDictionary(JSContext* cx,
                                      JS::Handle<JS::Value> objVal)
 {
   JS::Rooted<JSObject*> obj(cx, &objVal.toObject());
   return IsNotDateOrRegExp(cx, obj);
 }
 
 MOZ_ALWAYS_INLINE bool
--- a/dom/bindings/Bindings.conf
+++ b/dom/bindings/Bindings.conf
@@ -92,20 +92,16 @@ DOMInterfaces = {
 'MozActivity': {
     'nativeType': 'mozilla::dom::Activity',
 },
 
 'AbstractWorker': {
     'concrete': False
 },
 
-'AnimationEvent': {
-    'nativeType': 'mozilla::dom::AnimationEvent',
-},
-
 'ArchiveReader': {
     'nativeType': 'mozilla::dom::file::ArchiveReader',
 },
 
 'ArchiveRequest': {
     'nativeType': 'mozilla::dom::file::ArchiveRequest',
 },
 
@@ -135,20 +131,16 @@ DOMInterfaces = {
         'channelInterpretation': 'channelInterpretationValue',
     },
 },
 
 'AudioProcessingEvent' : {
     'resultNotAddRefed': [ 'inputBuffer', 'outputBuffer' ],
 },
 
-'BeforeUnloadEvent': {
-    'nativeType': 'mozilla::dom::BeforeUnloadEvent',
-},
-
 'BarProp': {
     'headerFile': 'mozilla/dom/BarProps.h',
 },
 
 'BiquadFilterNode': {
     'resultNotAddRefed': [ 'frequency', 'detune', 'q', 'gain' ],
 },
 
@@ -228,28 +220,16 @@ DOMInterfaces = {
     'nativeType': 'mozilla::dom::workers::ChromeWorkerPrivate',
 },
 
 'DOMRectList': {
     'headerFile': 'mozilla/dom/DOMRect.h',
     'resultNotAddRefed': [ 'item' ]
 },
 
-'ClipboardEvent': {
-    'nativeType': 'mozilla::dom::ClipboardEvent',
-},
-
-'CommandEvent': {
-    'nativeType': 'mozilla::dom::CommandEvent',
-},
-
-'CompositionEvent': {
-    'nativeType': 'mozilla::dom::CompositionEvent',
-},
-
 'Console': {
     'implicitJSContext': [ 'trace', 'time', 'timeEnd' ],
 },
 
 'ConvolverNode': {
     'implicitJSContext': [ 'buffer' ],
     'resultNotAddRefed': [ 'buffer' ],
 },
@@ -298,20 +278,16 @@ DOMInterfaces = {
 'CSSValueList': {
     'nativeType': 'nsDOMCSSValueList'
 },
 
 'DataChannel': {
     'nativeType': 'nsDOMDataChannel',
 },
 
-'DataContainerEvent': {
-    'nativeType': 'mozilla::dom::DataContainerEvent',
-},
-
 'DedicatedWorkerGlobalScope': {
     'headerFile': 'mozilla/dom/WorkerScope.h',
     'workers': True,
 },
 
 'DelayNode': {
     'resultNotAddRefed': [ 'delayTime' ],
 },
@@ -847,24 +823,16 @@ DOMInterfaces = {
     'resultNotAddRefed': [ 'root', 'referenceNode' ],
 },
 
 'NodeList': {
     'nativeType': 'nsINodeList',
     'resultNotAddRefed': [ 'item' ]
 },
 
-'NotifyPaintEvent': {
-    'nativeType': 'nsDOMNotifyPaintEvent',
-},
-
-'NotifyAudioAvailableEvent': {
-    'nativeType': 'nsDOMNotifyAudioAvailableEvent',
-},
-
 'OfflineAudioCompletionEvent': {
     'resultNotAddRefed': [ 'renderedBuffer' ],
 },
 
 'OfflineAudioContext': {
     'nativeType': 'mozilla::dom::AudioContext',
     'resultNotAddRefed': [ 'destination', 'listener' ],
 },
@@ -953,20 +921,16 @@ DOMInterfaces = {
     'nativeType': 'nsDOMCSSRGBColor',
     'resultNotAddRefed': [ 'alpha', 'blue', 'green', 'red' ]
 },
 
 'Screen': {
     'nativeType': 'nsScreen',
 },
 
-'ScrollAreaEvent': {
-    'nativeType': 'nsDOMScrollAreaEvent',
-},
-
 'Selection': {
     'nativeType': 'mozilla::Selection',
     'resultNotAddRefed': [ 'anchorNode', 'focusNode', 'getRangeAt' ],
 },
 
 'ShadowRoot': {
     'resultNotAddRefed': [
         'styleSheets'
@@ -1242,50 +1206,33 @@ DOMInterfaces = {
 'TextEncoder': {
     'nativeOwnership': 'owned',
 },
 
 'TextMetrics': {
     'nativeOwnership': 'owned',
 },
 
-'TimeEvent': {
-    'nativeType': 'nsDOMTimeEvent',
-},
-
 'TimeRanges': {
     'wrapperCache': False
 },
 
-'TouchEvent': {
-    'nativeType': 'nsDOMTouchEvent',
-},
-
 'TouchList': {
-    'nativeType': 'nsDOMTouchList',
-    'headerFile': 'nsDOMTouchEvent.h',
-},
-
-'TransitionEvent': {
-    'nativeType': 'nsDOMTransitionEvent',
+    'headerFile': 'mozilla/dom/TouchEvent.h',
 },
 
 'TreeColumns': {
     'nativeType': 'nsTreeColumns',
 },
 
 'TreeWalker': {
     'wrapperCache': False,
     'resultNotAddRefed': [ 'root', 'currentNode' ],
 },
 
-'UIEvent': {
-    'nativeType': 'nsDOMUIEvent',
-},
-
 'UndoManager': {
     'implicitJSContext' : [ 'undo', 'redo', 'transact' ],
 },
 
 'URL' : [{
     'wrapperCache': False,
 },
 {
@@ -1473,20 +1420,16 @@ DOMInterfaces = {
     'nativeType': 'mozilla::WebGLVertexArray',
     'headerFile': 'WebGLVertexArray.h'
 },
 
 'WebSocket': {
     'headerFile': 'WebSocket.h',
 },
 
-'WheelEvent': {
-    'nativeType': 'mozilla::dom::WheelEvent',
-},
-
 'Window': {
     'nativeType': 'nsGlobalWindow',
     # When turning on Window, remember to drop the "'register': False"
     # from ChromeWindow.
     'hasXPConnectImpls': True,
     'register': False,
     'binaryNames': {
         'postMessage': 'postMessageMoz',
@@ -1574,20 +1517,16 @@ DOMInterfaces = {
 'XPathEvaluator': {
     'wrapperCache': False
 },
 
 'XULDocument': {
     'headerFile': 'XULDocument.h'
 },
 
-'XULCommandEvent': {
-    'nativeType': 'nsDOMXULCommandEvent',
-},
-
 'XULElement': {
     'nativeType': 'nsXULElement',
     'resultNotAddRefed': [ 'controllers', 'style' ]
 },
 
 ####################################
 # Test Interfaces of various sorts #
 ####################################
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -3100,41 +3100,45 @@ def getJSToNativeConversionInfo(type, de
         sequenceType = typeName.define()
         if nullable:
             typeName = CGTemplatedType("Nullable", typeName)
             arrayRef = "${declName}.SetValue()"
         else:
             arrayRef = "${declName}"
 
         # NOTE: Keep this in sync with variadic conversions as needed
-        templateBody = ("""JS::Rooted<JSObject*> seq(cx, &${val}.toObject());\n
-if (!IsArrayLike(cx, seq)) {
+        templateBody = ("""JS::ForOfIterator iter(cx);
+if (!iter.init(${val}, JS::ForOfIterator::AllowNonIterable)) {
 %s
 }
-uint32_t length;
-// JS_GetArrayLength actually works on all objects
-if (!JS_GetArrayLength(cx, seq, &length)) {
+if (!iter.valueIsIterable()) {
 %s
 }
 %s &arr = %s;
-if (!arr.SetCapacity(length)) {
-  JS_ReportOutOfMemory(cx);
-%s
-}
-for (uint32_t i = 0; i < length; ++i) {
-  JS::Rooted<JS::Value> temp(cx);
-  if (!JS_GetElement(cx, seq, i, &temp)) {
+JS::Rooted<JS::Value> temp(cx);
+while (true) {
+  bool done;
+  if (!iter.next(&temp, &done)) {
 %s
   }
-  %s& slot = *arr.AppendElement();
-""" % (CGIndenter(CGGeneric(notSequence)).define(),
-       exceptionCodeIndented.define(),
+  if (done) {
+    break;
+  }
+  %s* slotPtr = arr.AppendElement();
+  if (!slotPtr) {
+    JS_ReportOutOfMemory(cx);
+%s
+  }
+  %s& slot = *slotPtr;
+""" % (exceptionCodeIndented.define(),
+       CGIndenter(CGGeneric(notSequence)).define(),
        sequenceType,
        arrayRef,
-       exceptionCodeIndented.define(),
+       CGIndenter(exceptionCodeIndented).define(),
+       elementInfo.declType.define(),
        CGIndenter(exceptionCodeIndented).define(),
        elementInfo.declType.define()))
 
         templateBody += CGIndenter(CGGeneric(
                 string.Template(elementInfo.template).substitute(
                     {
                         "val": "temp",
                         "mutableVal": "&temp",
@@ -3191,22 +3195,17 @@ for (uint32_t i = 0; i < length; ++i) {
                 interfaceObject.append(CGGeneric("(failed = !%s.TrySetTo%s(cx, ${val}, ${mutableVal}, tryNext)) || !tryNext" % (unionArgumentObj, name)))
                 names.append(name)
             interfaceObject = CGWrapper(CGList(interfaceObject, " ||\n"), pre="done = ", post=";\n", reindent=True)
         else:
             interfaceObject = None
 
         arrayObjectMemberTypes = filter(lambda t: t.isArray() or t.isSequence(), memberTypes)
         if len(arrayObjectMemberTypes) > 0:
-            assert len(arrayObjectMemberTypes) == 1
-            memberType = arrayObjectMemberTypes[0]
-            name = memberType.name
-            arrayObject = CGGeneric("done = (failed = !%s.TrySetTo%s(cx, ${val}, ${mutableVal}, tryNext)) || !tryNext;" % (unionArgumentObj, name))
-            arrayObject = CGIfWrapper(arrayObject, "IsArrayLike(cx, argObj)")
-            names.append(name)
+            raise TypeError("Bug 767924: We don't support sequences in unions yet")
         else:
             arrayObject = None
 
         dateObjectMemberTypes = filter(lambda t: t.isDate(), memberTypes)
         if len(dateObjectMemberTypes) > 0:
             assert len(dateObjectMemberTypes) == 1
             memberType = dateObjectMemberTypes[0]
             name = memberType.name
--- a/dom/camera/DOMCameraControl.cpp
+++ b/dom/camera/DOMCameraControl.cpp
@@ -31,71 +31,42 @@
 #include "mozilla/dom/CameraCapabilitiesBinding.h"
 #include "mozilla/dom/BindingUtils.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::idl;
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMCameraControl)
-  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
   NS_INTERFACE_MAP_ENTRY(nsIDOMMediaStream)
 NS_INTERFACE_MAP_END_INHERITING(DOMMediaStream)
 
 NS_IMPL_ADDREF_INHERITED(nsDOMCameraControl, DOMMediaStream)
 NS_IMPL_RELEASE_INHERITED(nsDOMCameraControl, DOMMediaStream)
 
-NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMCameraControl)
-
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMCameraControl, DOMMediaStream)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mCapabilities)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mWindow)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mGetCameraOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mGetCameraOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mAutoFocusOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mAutoFocusOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mTakePictureOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mTakePictureOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mStartRecordingOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mStartRecordingOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mReleaseOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mReleaseOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mSetConfigurationOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mSetConfigurationOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mOnShutterCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mOnClosedCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mOnRecorderStateChangeCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK(mOnPreviewStateChangeCb)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMCameraControl, DOMMediaStream)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mCapabilities)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mWindow)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGetCameraOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mGetCameraOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAutoFocusOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mAutoFocusOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTakePictureOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mTakePictureOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStartRecordingOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mStartRecordingOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReleaseOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mReleaseOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSetConfigurationOnSuccessCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSetConfigurationOnErrorCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOnShutterCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOnClosedCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOnRecorderStateChangeCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mOnPreviewStateChangeCb)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(nsDOMCameraControl)
+NS_IMPL_CYCLE_COLLECTION_INHERITED_18(nsDOMCameraControl, DOMMediaStream,
+                                      mCapabilities,
+                                      mWindow,
+                                      mGetCameraOnSuccessCb,
+                                      mGetCameraOnErrorCb,
+                                      mAutoFocusOnSuccessCb,
+                                      mAutoFocusOnErrorCb,
+                                      mTakePictureOnSuccessCb,
+                                      mTakePictureOnErrorCb,
+                                      mStartRecordingOnSuccessCb,
+                                      mStartRecordingOnErrorCb,
+                                      mReleaseOnSuccessCb,
+                                      mReleaseOnErrorCb,
+                                      mSetConfigurationOnSuccessCb,
+                                      mSetConfigurationOnErrorCb,
+                                      mOnShutterCb,
+                                      mOnClosedCb,
+                                      mOnRecorderStateChangeCb,
+                                      mOnPreviewStateChangeCb)
 
 class mozilla::StartRecordingHelper : public nsIDOMEventListener
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMEVENTLISTENER
 
   StartRecordingHelper(nsDOMCameraControl* aDOMCameraControl)
--- a/dom/camera/DOMCameraControl.h
+++ b/dom/camera/DOMCameraControl.h
@@ -32,17 +32,17 @@ namespace dom {
 }
 class ErrorResult;
 class StartRecordingHelper;
 
 // Main camera control.
 class nsDOMCameraControl MOZ_FINAL : public DOMMediaStream
 {
 public:
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_INHERITED(nsDOMCameraControl, DOMMediaStream)
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMCameraControl, DOMMediaStream)
   NS_DECL_ISUPPORTS_INHERITED
 
   nsDOMCameraControl(uint32_t aCameraId,
                      const dom::CameraConfiguration& aInitialConfig,
                      dom::GetCameraCallback* aOnSuccess,
                      dom::CameraErrorCallback* aOnError,
                      nsPIDOMWindow* aWindow);
 
--- a/dom/contacts/tests/test_contacts_basics2.html
+++ b/dom/contacts/tests/test_contacts_basics2.html
@@ -676,22 +676,25 @@ var steps = [
     req = mozContacts.clear()
     req.onsuccess = function () {
       ok(true, "Deleted the database");
       next();
     }
     req.onerror = onFailure;
   },
   function() {
-    ok(true, "Test setting array properties to scalar values")
+    ok(true, "Test that after setting array properties to scalar values the property os not a non-array")
     const FIELDS = ["email","url","adr","tel","impp"];
     createResult1 = new mozContact();
     for (var prop of FIELDS) {
-      createResult1[prop] = {type: ["foo"]};
-      ok(Array.isArray(createResult1[prop]), prop + " is array");
+      try {
+        createResult1[prop] = {type: ["foo"]};
+      } catch (e) {}
+      ok(createResult1[prop] === null ||
+         Array.isArray(createResult1[prop]), prop + " is array");
     }
     next();
   },
   function() {
     ok(true, "Undefined properties of fields should be treated correctly");
     var c = new mozContact({
       adr: [{streetAddress: undefined}],
       email: [{value: undefined}],
--- a/dom/events/CompositionEvent.cpp
+++ b/dom/events/CompositionEvent.cpp
@@ -9,18 +9,18 @@
 #include "prtime.h"
 
 namespace mozilla {
 namespace dom {
 
 CompositionEvent::CompositionEvent(EventTarget* aOwner,
                                    nsPresContext* aPresContext,
                                    WidgetCompositionEvent* aEvent)
-  : nsDOMUIEvent(aOwner, aPresContext, aEvent ? aEvent :
-                 new WidgetCompositionEvent(false, 0, nullptr))
+  : UIEvent(aOwner, aPresContext,
+            aEvent ? aEvent : new WidgetCompositionEvent(false, 0, nullptr))
 {
   NS_ASSERTION(mEvent->eventStructType == NS_COMPOSITION_EVENT,
                "event type mismatch");
 
   if (aEvent) {
     mEventIsInternal = false;
   } else {
     mEventIsInternal = true;
@@ -31,22 +31,22 @@ CompositionEvent::CompositionEvent(Event
     //     when we sends compositionstart event.
     mEvent->mFlags.mCancelable = false;
   }
 
   mData = mEvent->AsCompositionEvent()->data;
   // TODO: Native event should have locale information.
 }
 
-NS_IMPL_ADDREF_INHERITED(CompositionEvent, nsDOMUIEvent)
-NS_IMPL_RELEASE_INHERITED(CompositionEvent, nsDOMUIEvent)
+NS_IMPL_ADDREF_INHERITED(CompositionEvent, UIEvent)
+NS_IMPL_RELEASE_INHERITED(CompositionEvent, UIEvent)
 
 NS_INTERFACE_MAP_BEGIN(CompositionEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMCompositionEvent)
-NS_INTERFACE_MAP_END_INHERITING(nsDOMUIEvent)
+NS_INTERFACE_MAP_END_INHERITING(UIEvent)
 
 NS_IMETHODIMP
 CompositionEvent::GetData(nsAString& aData)
 {
   aData = mData;
   return NS_OK;
 }
 
@@ -60,18 +60,17 @@ CompositionEvent::GetLocale(nsAString& a
 NS_IMETHODIMP
 CompositionEvent::InitCompositionEvent(const nsAString& aType,
                                        bool aCanBubble,
                                        bool aCancelable,
                                        nsIDOMWindow* aView,
                                        const nsAString& aData,
                                        const nsAString& aLocale)
 {
-  nsresult rv =
-    nsDOMUIEvent::InitUIEvent(aType, aCanBubble, aCancelable, aView, 0);
+  nsresult rv = UIEvent::InitUIEvent(aType, aCanBubble, aCancelable, aView, 0);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mData = aData;
   mLocale = aLocale;
   return NS_OK;
 }
 
 } // namespace dom
--- a/dom/events/CompositionEvent.h
+++ b/dom/events/CompositionEvent.h
@@ -2,34 +2,34 @@
 /* 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/. */
 
 #ifndef mozilla_dom_CompositionEvent_h_
 #define mozilla_dom_CompositionEvent_h_
 
-#include "nsDOMUIEvent.h"
+#include "mozilla/dom/CompositionEventBinding.h"
+#include "mozilla/dom/UIEvent.h"
+#include "mozilla/EventForwards.h"
 #include "nsIDOMCompositionEvent.h"
-#include "mozilla/dom/CompositionEventBinding.h"
-#include "mozilla/EventForwards.h"
 
 namespace mozilla {
 namespace dom {
 
-class CompositionEvent : public nsDOMUIEvent,
+class CompositionEvent : public UIEvent,
                          public nsIDOMCompositionEvent
 {
 public:
   CompositionEvent(EventTarget* aOwner,
                    nsPresContext* aPresContext,
                    WidgetCompositionEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
-  NS_FORWARD_TO_NSDOMUIEVENT
+  NS_FORWARD_TO_UIEVENT
   NS_DECL_NSIDOMCOMPOSITIONEVENT
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
     return CompositionEventBinding::Wrap(aCx, aScope, this);
   }
 
--- a/dom/events/DataTransfer.cpp
+++ b/dom/events/DataTransfer.cpp
@@ -315,17 +315,17 @@ DataTransfer::GetFiles(ErrorResult& aRv)
 
   return mFiles;
 }
 
 NS_IMETHODIMP
 DataTransfer::GetFiles(nsIDOMFileList** aFileList)
 {
   ErrorResult rv;
-  *aFileList = GetFiles(rv);
+  NS_IF_ADDREF(*aFileList = GetFiles(rv));
   return rv.ErrorCode();
 }
 
 already_AddRefed<DOMStringList>
 DataTransfer::Types()
 {
   nsRefPtr<DOMStringList> types = new DOMStringList();
   if (mItems.Length()) {
--- a/dom/events/DragEvent.cpp
+++ b/dom/events/DragEvent.cpp
@@ -82,17 +82,16 @@ DragEvent::InitDragEvent(const nsAString
                          bool aAltKey,
                          bool aShiftKey,
                          bool aMetaKey,
                          uint16_t aButton,
                          nsIDOMEventTarget* aRelatedTarget,
                          nsIDOMDataTransfer* aDataTransfer)
 {
   nsCOMPtr<DataTransfer> dataTransfer = do_QueryInterface(aDataTransfer);
-  NS_ENSURE_ARG(dataTransfer);
 
   nsresult rv =
     MouseEvent::InitMouseEvent(aType, aCanBubble, aCancelable, aView, aDetail,
                                aScreenX, aScreenY, aClientX, aClientY,
                                aCtrlKey, aAltKey, aShiftKey, aMetaKey, aButton,
                                aRelatedTarget);
   NS_ENSURE_SUCCESS(rv, rv);
 
--- a/dom/events/FocusEvent.cpp
+++ b/dom/events/FocusEvent.cpp
@@ -5,24 +5,23 @@
 
 #include "mozilla/dom/FocusEvent.h"
 #include "mozilla/ContentEvents.h"
 #include "prtime.h"
 
 namespace mozilla {
 namespace dom {
 
-NS_IMPL_ISUPPORTS_INHERITED1(FocusEvent, nsDOMUIEvent, nsIDOMFocusEvent)
+NS_IMPL_ISUPPORTS_INHERITED1(FocusEvent, UIEvent, nsIDOMFocusEvent)
 
 FocusEvent::FocusEvent(EventTarget* aOwner,
                        nsPresContext* aPresContext,
                        InternalFocusEvent* aEvent)
-  : nsDOMUIEvent(aOwner, aPresContext,
-                 aEvent ? aEvent :
-                          new InternalFocusEvent(false, NS_FOCUS_CONTENT))
+  : UIEvent(aOwner, aPresContext,
+            aEvent ? aEvent : new InternalFocusEvent(false, NS_FOCUS_CONTENT))
 {
   if (aEvent) {
     mEventIsInternal = false;
   } else {
     mEventIsInternal = true;
     mEvent->time = PR_Now();
   }
 }
@@ -45,17 +44,18 @@ FocusEvent::GetRelatedTarget()
 nsresult
 FocusEvent::InitFocusEvent(const nsAString& aType,
                            bool aCanBubble,
                            bool aCancelable,
                            nsIDOMWindow* aView,
                            int32_t aDetail,
                            EventTarget* aRelatedTarget)
 {
-  nsresult rv = nsDOMUIEvent::InitUIEvent(aType, aCanBubble, aCancelable, aView, aDetail);
+  nsresult rv =
+    UIEvent::InitUIEvent(aType, aCanBubble, aCancelable, aView, aDetail);
   NS_ENSURE_SUCCESS(rv, rv);
   mEvent->AsFocusEvent()->relatedTarget = aRelatedTarget;
   return NS_OK;
 }
 
 already_AddRefed<FocusEvent>
 FocusEvent::Constructor(const GlobalObject& aGlobal,
                         const nsAString& aType,
--- a/dom/events/FocusEvent.h
+++ b/dom/events/FocusEvent.h
@@ -1,32 +1,32 @@
 /* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 #ifndef mozilla_dom_FocusEvent_h_
 #define mozilla_dom_FocusEvent_h_
 
-#include "nsDOMUIEvent.h"
+#include "mozilla/dom/FocusEventBinding.h"
+#include "mozilla/dom/UIEvent.h"
+#include "mozilla/EventForwards.h"
 #include "nsIDOMFocusEvent.h"
-#include "mozilla/EventForwards.h"
-#include "mozilla/dom/FocusEventBinding.h"
 
 namespace mozilla {
 namespace dom {
 
-class FocusEvent : public nsDOMUIEvent,
+class FocusEvent : public UIEvent,
                    public nsIDOMFocusEvent
 {
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIDOMFOCUSEVENT
 
   // Forward to base class
-  NS_FORWARD_TO_NSDOMUIEVENT
+  NS_FORWARD_TO_UIEVENT
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
     return FocusEventBinding::Wrap(aCx, aScope, this);
   }
 
   FocusEvent(EventTarget* aOwner,
--- a/dom/events/KeyboardEvent.cpp
+++ b/dom/events/KeyboardEvent.cpp
@@ -8,37 +8,37 @@
 #include "prtime.h"
 
 namespace mozilla {
 namespace dom {
 
 KeyboardEvent::KeyboardEvent(EventTarget* aOwner,
                              nsPresContext* aPresContext,
                              WidgetKeyboardEvent* aEvent)
-  : nsDOMUIEvent(aOwner, aPresContext, aEvent ? aEvent :
-                 new WidgetKeyboardEvent(false, 0, nullptr))
+  : UIEvent(aOwner, aPresContext,
+            aEvent ? aEvent : new WidgetKeyboardEvent(false, 0, nullptr))
 {
   NS_ASSERTION(mEvent->eventStructType == NS_KEY_EVENT, "event type mismatch");
 
   if (aEvent) {
     mEventIsInternal = false;
   }
   else {
     mEventIsInternal = true;
     mEvent->time = PR_Now();
     mEvent->AsKeyboardEvent()->mKeyNameIndex = KEY_NAME_INDEX_USE_STRING;
   }
 }
 
-NS_IMPL_ADDREF_INHERITED(KeyboardEvent, nsDOMUIEvent)
-NS_IMPL_RELEASE_INHERITED(KeyboardEvent, nsDOMUIEvent)
+NS_IMPL_ADDREF_INHERITED(KeyboardEvent, UIEvent)
+NS_IMPL_RELEASE_INHERITED(KeyboardEvent, UIEvent)
 
 NS_INTERFACE_MAP_BEGIN(KeyboardEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMKeyEvent)
-NS_INTERFACE_MAP_END_INHERITING(nsDOMUIEvent)
+NS_INTERFACE_MAP_END_INHERITING(UIEvent)
 
 bool
 KeyboardEvent::AltKey()
 {
   return mEvent->AsKeyboardEvent()->IsAlt();
 }
 
 NS_IMETHODIMP
@@ -207,17 +207,17 @@ KeyboardEvent::InitKeyEvent(const nsAStr
                             nsIDOMWindow* aView,
                             bool aCtrlKey,
                             bool aAltKey,
                             bool aShiftKey,
                             bool aMetaKey,
                             uint32_t aKeyCode,
                             uint32_t aCharCode)
 {
-  nsresult rv = nsDOMUIEvent::InitUIEvent(aType, aCanBubble, aCancelable, aView, 0);
+  nsresult rv = UIEvent::InitUIEvent(aType, aCanBubble, aCancelable, aView, 0);
   NS_ENSURE_SUCCESS(rv, rv);
 
   WidgetKeyboardEvent* keyEvent = mEvent->AsKeyboardEvent();
   keyEvent->InitBasicModifiers(aCtrlKey, aAltKey, aShiftKey, aMetaKey);
   keyEvent->keyCode = aKeyCode;
   keyEvent->charCode = aCharCode;
 
   return NS_OK;
--- a/dom/events/KeyboardEvent.h
+++ b/dom/events/KeyboardEvent.h
@@ -1,39 +1,39 @@
 /* -*- Mode: C++; 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/. */
 
 #ifndef mozilla_dom_KeyboardEvent_h_
 #define mozilla_dom_KeyboardEvent_h_
 
+#include "mozilla/dom/UIEvent.h"
+#include "mozilla/dom/KeyboardEventBinding.h"
+#include "mozilla/EventForwards.h"
 #include "nsIDOMKeyEvent.h"
-#include "nsDOMUIEvent.h"
-#include "mozilla/EventForwards.h"
-#include "mozilla/dom/KeyboardEventBinding.h"
 
 namespace mozilla {
 namespace dom {
 
-class KeyboardEvent : public nsDOMUIEvent,
+class KeyboardEvent : public UIEvent,
                       public nsIDOMKeyEvent
 {
 public:
   KeyboardEvent(EventTarget* aOwner,
                 nsPresContext* aPresContext,
                 WidgetKeyboardEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMKeyEvent Interface
   NS_DECL_NSIDOMKEYEVENT
 
   // Forward to base class
-  NS_FORWARD_TO_NSDOMUIEVENT
+  NS_FORWARD_TO_UIEVENT
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
     return KeyboardEventBinding::Wrap(aCx, aScope, this);
   }
 
   bool AltKey();
--- a/dom/events/MouseEvent.cpp
+++ b/dom/events/MouseEvent.cpp
@@ -10,19 +10,19 @@
 #include "prtime.h"
 
 namespace mozilla {
 namespace dom {
 
 MouseEvent::MouseEvent(EventTarget* aOwner,
                        nsPresContext* aPresContext,
                        WidgetMouseEventBase* aEvent)
-  : nsDOMUIEvent(aOwner, aPresContext, aEvent ? aEvent :
-                 new WidgetMouseEvent(false, 0, nullptr,
-                                      WidgetMouseEvent::eReal))
+  : UIEvent(aOwner, aPresContext,
+            aEvent ? aEvent : new WidgetMouseEvent(false, 0, nullptr,
+                                                   WidgetMouseEvent::eReal))
 {
   // There's no way to make this class' ctor allocate an WidgetMouseScrollEvent.
   // It's not that important, though, since a scroll event is not a real
   // DOM event.
 
   WidgetMouseEvent* mouseEvent = mEvent->AsMouseEvent();
   if (aEvent) {
     mEventIsInternal = false;
@@ -36,22 +36,22 @@ MouseEvent::MouseEvent(EventTarget* aOwn
 
   if (mouseEvent) {
     MOZ_ASSERT(mouseEvent->reason != WidgetMouseEvent::eSynthesized,
                "Don't dispatch DOM events from synthesized mouse events");
     mDetail = mouseEvent->clickCount;
   }
 }
 
-NS_IMPL_ADDREF_INHERITED(MouseEvent, nsDOMUIEvent)
-NS_IMPL_RELEASE_INHERITED(MouseEvent, nsDOMUIEvent)
+NS_IMPL_ADDREF_INHERITED(MouseEvent, UIEvent)
+NS_IMPL_RELEASE_INHERITED(MouseEvent, UIEvent)
 
 NS_INTERFACE_MAP_BEGIN(MouseEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMMouseEvent)
-NS_INTERFACE_MAP_END_INHERITING(nsDOMUIEvent)
+NS_INTERFACE_MAP_END_INHERITING(UIEvent)
 
 NS_IMETHODIMP
 MouseEvent::InitMouseEvent(const nsAString& aType,
                            bool aCanBubble,
                            bool aCancelable,
                            nsIDOMWindow* aView,
                            int32_t aDetail,
                            int32_t aScreenX,
@@ -60,17 +60,18 @@ MouseEvent::InitMouseEvent(const nsAStri
                            int32_t aClientY, 
                            bool aCtrlKey,
                            bool aAltKey,
                            bool aShiftKey,
                            bool aMetaKey,
                            uint16_t aButton,
                            nsIDOMEventTarget* aRelatedTarget)
 {
-  nsresult rv = nsDOMUIEvent::InitUIEvent(aType, aCanBubble, aCancelable, aView, aDetail);
+  nsresult rv =
+    UIEvent::InitUIEvent(aType, aCanBubble, aCancelable, aView, aDetail);
   NS_ENSURE_SUCCESS(rv, rv);
 
   switch(mEvent->eventStructType) {
     case NS_MOUSE_EVENT:
     case NS_MOUSE_SCROLL_EVENT:
     case NS_WHEEL_EVENT:
     case NS_DRAG_EVENT:
     case NS_POINTER_EVENT:
--- a/dom/events/MouseEvent.h
+++ b/dom/events/MouseEvent.h
@@ -1,39 +1,39 @@
 /* -*- Mode: C++; 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/. */
 
 #ifndef mozilla_dom_MouseEvent_h_
 #define mozilla_dom_MouseEvent_h_
 
-#include "nsIDOMMouseEvent.h"
-#include "nsDOMUIEvent.h"
+#include "mozilla/dom/UIEvent.h"
 #include "mozilla/dom/MouseEventBinding.h"
 #include "mozilla/EventForwards.h"
+#include "nsIDOMMouseEvent.h"
 
 namespace mozilla {
 namespace dom {
 
-class MouseEvent : public nsDOMUIEvent,
+class MouseEvent : public UIEvent,
                    public nsIDOMMouseEvent
 {
 public:
   MouseEvent(EventTarget* aOwner,
              nsPresContext* aPresContext,
              WidgetMouseEventBase* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
 
   // nsIDOMMouseEvent Interface
   NS_DECL_NSIDOMMOUSEEVENT
 
   // Forward to base class
-  NS_FORWARD_TO_NSDOMUIEVENT
+  NS_FORWARD_TO_UIEVENT
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
     return MouseEventBinding::Wrap(aCx, aScope, this);
   }
 
   // Web IDL binding methods
@@ -116,11 +116,11 @@ protected:
                           const nsAString& aModifiersList);
 };
 
 } // namespace dom
 } // namespace mozilla
 
 #define NS_FORWARD_TO_MOUSEEVENT \
   NS_FORWARD_NSIDOMMOUSEEVENT(MouseEvent::) \
-  NS_FORWARD_TO_NSDOMUIEVENT
+  NS_FORWARD_TO_UIEVENT
 
 #endif // mozilla_dom_MouseEvent_h_
rename from dom/events/nsDOMNotifyAudioAvailableEvent.cpp
rename to dom/events/NotifyAudioAvailableEvent.cpp
--- a/dom/events/nsDOMNotifyAudioAvailableEvent.cpp
+++ b/dom/events/NotifyAudioAvailableEvent.cpp
@@ -1,77 +1,81 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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 "nsDOMNotifyAudioAvailableEvent.h"
-
+#include "mozilla/dom/NotifyAudioAvailableEvent.h"
+#include "mozilla/HoldDropJSObjects.h"
 #include "nsError.h"
-#include "mozilla/HoldDropJSObjects.h"
 #include "jsfriendapi.h"
 
-using namespace mozilla;
-using namespace mozilla::dom;
+namespace mozilla {
+namespace dom {
 
-nsDOMNotifyAudioAvailableEvent::nsDOMNotifyAudioAvailableEvent(EventTarget* aOwner,
-                                                               nsPresContext* aPresContext,
-                                                               WidgetEvent* aEvent,
-                                                               uint32_t aEventType,
-                                                               float* aFrameBuffer,
-                                                               uint32_t aFrameBufferLength,
-                                                               float aTime)
-  : nsDOMEvent(aOwner, aPresContext, aEvent),
-    mFrameBuffer(aFrameBuffer),
-    mFrameBufferLength(aFrameBufferLength),
-    mTime(aTime),
-    mCachedArray(nullptr),
-    mAllowAudioData(false)
+NotifyAudioAvailableEvent::NotifyAudioAvailableEvent(
+                             EventTarget* aOwner,
+                             nsPresContext* aPresContext,
+                             WidgetEvent* aEvent,
+                             uint32_t aEventType,
+                             float* aFrameBuffer,
+                             uint32_t aFrameBufferLength,
+                             float aTime)
+  : nsDOMEvent(aOwner, aPresContext, aEvent)
+  , mFrameBuffer(aFrameBuffer)
+  , mFrameBufferLength(aFrameBufferLength)
+  , mTime(aTime)
+  , mCachedArray(nullptr)
+  , mAllowAudioData(false)
 {
-  MOZ_COUNT_CTOR(nsDOMNotifyAudioAvailableEvent);
+  MOZ_COUNT_CTOR(NotifyAudioAvailableEvent);
   if (mEvent) {
     mEvent->message = aEventType;
   }
 }
 
-NS_IMPL_ADDREF_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent)
-NS_IMPL_RELEASE_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent)
+NS_IMPL_ADDREF_INHERITED(NotifyAudioAvailableEvent, nsDOMEvent)
+NS_IMPL_RELEASE_INHERITED(NotifyAudioAvailableEvent, nsDOMEvent)
 
-NS_IMPL_CYCLE_COLLECTION_CLASS(nsDOMNotifyAudioAvailableEvent)
+NS_IMPL_CYCLE_COLLECTION_CLASS(NotifyAudioAvailableEvent)
 
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent)
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(NotifyAudioAvailableEvent,
+                                                nsDOMEvent)
   if (tmp->mCachedArray) {
     tmp->mCachedArray = nullptr;
-    mozilla::DropJSObjects(tmp);
+    DropJSObjects(tmp);
   }
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(NotifyAudioAvailableEvent,
+                                                  nsDOMEvent)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
-NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(nsDOMNotifyAudioAvailableEvent, nsDOMEvent)
+NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(NotifyAudioAvailableEvent,
+                                               nsDOMEvent)
   NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mCachedArray)
 NS_IMPL_CYCLE_COLLECTION_TRACE_END
 
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMNotifyAudioAvailableEvent)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(NotifyAudioAvailableEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMNotifyAudioAvailableEvent)
 NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent)
 
-nsDOMNotifyAudioAvailableEvent::~nsDOMNotifyAudioAvailableEvent()
+NotifyAudioAvailableEvent::~NotifyAudioAvailableEvent()
 {
-  MOZ_COUNT_DTOR(nsDOMNotifyAudioAvailableEvent);
+  MOZ_COUNT_DTOR(NotifyAudioAvailableEvent);
   if (mCachedArray) {
     mCachedArray = nullptr;
     mozilla::DropJSObjects(this);
   }
 }
 
 NS_IMETHODIMP
-nsDOMNotifyAudioAvailableEvent::GetFrameBuffer(JSContext* aCx, JS::MutableHandle<JS::Value> aResult)
+NotifyAudioAvailableEvent::GetFrameBuffer(JSContext* aCx,
+                                          JS::MutableHandle<JS::Value> aResult)
 {
   if (!mAllowAudioData) {
     // Media is not same-origin, don't allow the data out.
     return NS_ERROR_DOM_SECURITY_ERR;
   }
 
   if (mCachedArray) {
     aResult.setObject(*mCachedArray);
@@ -81,37 +85,38 @@ nsDOMNotifyAudioAvailableEvent::GetFrame
   // Cache this array so we don't recreate on next call.
   mozilla::HoldJSObjects(this);
 
   mCachedArray = JS_NewFloat32Array(aCx, mFrameBufferLength);
   if (!mCachedArray) {
     mozilla::DropJSObjects(this);
     return NS_ERROR_FAILURE;
   }
-  memcpy(JS_GetFloat32ArrayData(mCachedArray), mFrameBuffer.get(), mFrameBufferLength * sizeof(float));
+  memcpy(JS_GetFloat32ArrayData(mCachedArray), mFrameBuffer.get(),
+         mFrameBufferLength * sizeof(float));
 
   aResult.setObject(*mCachedArray);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMNotifyAudioAvailableEvent::GetTime(float *aRetVal)
+NotifyAudioAvailableEvent::GetTime(float* aRetVal)
 {
   *aRetVal = Time();
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMNotifyAudioAvailableEvent::InitAudioAvailableEvent(const nsAString& aType,
-                                                        bool aCanBubble,
-                                                        bool aCancelable,
-                                                        float* aFrameBuffer,
-                                                        uint32_t aFrameBufferLength,
-                                                        float aTime,
-                                                        bool aAllowAudioData)
+NotifyAudioAvailableEvent::InitAudioAvailableEvent(const nsAString& aType,
+                                                   bool aCanBubble,
+                                                   bool aCancelable,
+                                                   float* aFrameBuffer,
+                                                   uint32_t aFrameBufferLength,
+                                                   float aTime,
+                                                   bool aAllowAudioData)
 {
   // Auto manage the memory which stores the frame buffer. This ensures
   // that if we exit due to some error, the memory will be freed. Otherwise,
   // the framebuffer's memory will be freed when this event is destroyed.
   nsAutoArrayPtr<float> frameBuffer(aFrameBuffer);
   nsresult rv = nsDOMEvent::InitEvent(aType, aCanBubble, aCancelable);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -119,24 +124,25 @@ nsDOMNotifyAudioAvailableEvent::InitAudi
   mFrameBufferLength = aFrameBufferLength;
   mTime = aTime;
   mAllowAudioData = aAllowAudioData;
   mCachedArray = nullptr;
   return NS_OK;
 }
 
 void
-nsDOMNotifyAudioAvailableEvent::InitAudioAvailableEvent(const nsAString& aType,
-                                                        bool aCanBubble,
-                                                        bool aCancelable,
-                                                        const Nullable<Sequence<float> >& aFrameBuffer,
-                                                        uint32_t aFrameBufferLength,
-                                                        float aTime,
-                                                        bool aAllowAudioData,
-                                                        ErrorResult& aRv)
+NotifyAudioAvailableEvent::InitAudioAvailableEvent(
+                             const nsAString& aType,
+                             bool aCanBubble,
+                             bool aCancelable,
+                             const Nullable<Sequence<float> >& aFrameBuffer,
+                             uint32_t aFrameBufferLength,
+                             float aTime,
+                             bool aAllowAudioData,
+                             ErrorResult& aRv)
 {
   if ((aFrameBuffer.IsNull() && aFrameBufferLength > 0) ||
       (!aFrameBuffer.IsNull() &&
        aFrameBuffer.Value().Length() < aFrameBufferLength)) {
     aRv = NS_ERROR_UNEXPECTED;
     return;
   }
 
@@ -148,22 +154,29 @@ nsDOMNotifyAudioAvailableEvent::InitAudi
   }
 
   aRv = InitAudioAvailableEvent(aType, aCanBubble, aCancelable,
                                 buffer.forget(),
                                 aFrameBufferLength,
                                 aTime, aAllowAudioData);
 }
 
-nsresult NS_NewDOMAudioAvailableEvent(nsIDOMEvent** aInstancePtrResult,
-                                      EventTarget* aOwner,
-                                      nsPresContext* aPresContext,
-                                      WidgetEvent* aEvent,
-                                      uint32_t aEventType,
-                                      float* aFrameBuffer,
-                                      uint32_t aFrameBufferLength,
-                                      float aTime)
+} // namespace dom
+} // namespace mozilla
+
+using namespace mozilla;
+using namespace mozilla::dom;
+
+nsresult
+NS_NewDOMAudioAvailableEvent(nsIDOMEvent** aInstancePtrResult,
+                             EventTarget* aOwner,
+                             nsPresContext* aPresContext,
+                             WidgetEvent* aEvent,
+                             uint32_t aEventType,
+                             float* aFrameBuffer,
+                             uint32_t aFrameBufferLength,
+                             float aTime)
 {
-  nsDOMNotifyAudioAvailableEvent* it =
-    new nsDOMNotifyAudioAvailableEvent(aOwner, aPresContext, aEvent, aEventType,
-                                       aFrameBuffer, aFrameBufferLength, aTime);
+  NotifyAudioAvailableEvent* it =
+    new NotifyAudioAvailableEvent(aOwner, aPresContext, aEvent, aEventType,
+                                  aFrameBuffer, aFrameBufferLength, aTime);
   return CallQueryInterface(it, aInstancePtrResult);
 }
rename from dom/events/nsDOMNotifyAudioAvailableEvent.h
rename to dom/events/NotifyAudioAvailableEvent.h
--- a/dom/events/nsDOMNotifyAudioAvailableEvent.h
+++ b/dom/events/NotifyAudioAvailableEvent.h
@@ -1,79 +1,78 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#ifndef nsDOMNotifyAudioAvailableEvent_h_
-#define nsDOMNotifyAudioAvailableEvent_h_
+#ifndef mozilla_dom_NotifyAudioAvailableEvent_h_
+#define mozilla_dom_NotifyAudioAvailableEvent_h_
 
 #include "nsIDOMNotifyAudioAvailableEvent.h"
 #include "nsDOMEvent.h"
 #include "nsCycleCollectionParticipant.h"
 #include "mozilla/dom/NotifyAudioAvailableEventBinding.h"
 
 class nsPresContext;
 
-class nsDOMNotifyAudioAvailableEvent : public nsDOMEvent,
-                                       public nsIDOMNotifyAudioAvailableEvent
+namespace mozilla {
+namespace dom {
+
+class NotifyAudioAvailableEvent : public nsDOMEvent,
+                                  public nsIDOMNotifyAudioAvailableEvent
 {
 public:
-  nsDOMNotifyAudioAvailableEvent(mozilla::dom::EventTarget* aOwner,
-                                 nsPresContext* aPresContext,
-                                 mozilla::WidgetEvent* aEvent,
-                                 uint32_t aEventType, float * aFrameBuffer,
-                                 uint32_t aFrameBufferLength, float aTime);
+  NotifyAudioAvailableEvent(EventTarget* aOwner,
+                            nsPresContext* aPresContext,
+                            WidgetEvent* aEvent,
+                            uint32_t aEventType,
+                            float* aFrameBuffer,
+                            uint32_t aFrameBufferLength,
+                            float aTime);
 
   NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_INHERITED(nsDOMNotifyAudioAvailableEvent,
-                                                         nsDOMEvent)
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_INHERITED(
+    NotifyAudioAvailableEvent, nsDOMEvent)
 
   NS_DECL_NSIDOMNOTIFYAUDIOAVAILABLEEVENT
   NS_FORWARD_NSIDOMEVENT(nsDOMEvent::)
 
-  nsresult NS_NewDOMAudioAvailableEvent(nsIDOMEvent** aInstancePtrResult,
-                                        mozilla::dom::EventTarget* aOwner,
-                                        nsPresContext* aPresContext,
-                                        mozilla::WidgetEvent* aEvent,
-                                        uint32_t aEventType,
-                                        float * aFrameBuffer,
-                                        uint32_t aFrameBufferLength,
-                                        float aTime);
-
-  ~nsDOMNotifyAudioAvailableEvent();
+  ~NotifyAudioAvailableEvent();
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
-    return mozilla::dom::NotifyAudioAvailableEventBinding::Wrap(aCx, aScope, this);
+    return NotifyAudioAvailableEventBinding::Wrap(aCx, aScope, this);
   }
 
-  JSObject* GetFrameBuffer(JSContext* aCx, mozilla::ErrorResult& aRv)
+  JSObject* GetFrameBuffer(JSContext* aCx, ErrorResult& aRv)
   {
     JS::Rooted<JS::Value> dummy(aCx);
     aRv = GetFrameBuffer(aCx, &dummy);
     return mCachedArray;
   }
 
   float Time()
   {
     return mTime;
   }
 
   void InitAudioAvailableEvent(const nsAString& aType,
                                bool aCanBubble,
                                bool aCancelable,
-                               const mozilla::dom::Nullable<mozilla::dom::Sequence<float> >& aFrameBuffer,
+                               const Nullable<Sequence<float> >& aFrameBuffer,
                                uint32_t aFrameBufferLength,
                                float aTime,
                                bool aAllowAudioData,
-                               mozilla::ErrorResult& aRv);
+                               ErrorResult& aRv);
 private:
   nsAutoArrayPtr<float> mFrameBuffer;
   uint32_t mFrameBufferLength;
   float mTime;
   JS::Heap<JSObject*> mCachedArray;
   bool mAllowAudioData;
 };
 
-#endif // nsDOMNotifyAudioAvailableEvent_h_
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_NotifyAudioAvailableEvent_h_
rename from dom/events/nsDOMNotifyPaintEvent.cpp
rename to dom/events/NotifyPaintEvent.cpp
--- a/dom/events/nsDOMNotifyPaintEvent.cpp
+++ b/dom/events/NotifyPaintEvent.cpp
@@ -1,88 +1,88 @@
 /* -*- Mode: C++; 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 "base/basictypes.h"
 #include "ipc/IPCMessageUtils.h"
+#include "mozilla/dom/DOMRect.h"
+#include "mozilla/dom/NotifyPaintEvent.h"
 #include "mozilla/GfxMessageUtils.h"
-#include "nsDOMNotifyPaintEvent.h"
 #include "nsContentUtils.h"
 #include "nsPaintRequest.h"
-#include "mozilla/dom/DOMRect.h"
 
-using namespace mozilla;
-using namespace mozilla::dom;
+namespace mozilla {
+namespace dom {
 
-nsDOMNotifyPaintEvent::nsDOMNotifyPaintEvent(mozilla::dom::EventTarget* aOwner,
-                                             nsPresContext* aPresContext,
-                                             WidgetEvent* aEvent,
-                                             uint32_t aEventType,
-                                             nsInvalidateRequestList* aInvalidateRequests)
+NotifyPaintEvent::NotifyPaintEvent(EventTarget* aOwner,
+                                   nsPresContext* aPresContext,
+                                   WidgetEvent* aEvent,
+                                   uint32_t aEventType,
+                                   nsInvalidateRequestList* aInvalidateRequests)
 : nsDOMEvent(aOwner, aPresContext, aEvent)
 {
   if (mEvent) {
     mEvent->message = aEventType;
   }
   if (aInvalidateRequests) {
     mInvalidateRequests.MoveElementsFrom(aInvalidateRequests->mRequests);
   }
 }
 
-NS_INTERFACE_MAP_BEGIN(nsDOMNotifyPaintEvent)
+NS_INTERFACE_MAP_BEGIN(NotifyPaintEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMNotifyPaintEvent)
 NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent)
 
-NS_IMPL_ADDREF_INHERITED(nsDOMNotifyPaintEvent, nsDOMEvent)
-NS_IMPL_RELEASE_INHERITED(nsDOMNotifyPaintEvent, nsDOMEvent)
+NS_IMPL_ADDREF_INHERITED(NotifyPaintEvent, nsDOMEvent)
+NS_IMPL_RELEASE_INHERITED(NotifyPaintEvent, nsDOMEvent)
 
 nsRegion
-nsDOMNotifyPaintEvent::GetRegion()
+NotifyPaintEvent::GetRegion()
 {
   nsRegion r;
   if (!nsContentUtils::IsCallerChrome()) {
     return r;
   }
   for (uint32_t i = 0; i < mInvalidateRequests.Length(); ++i) {
     r.Or(r, mInvalidateRequests[i].mRect);
     r.SimplifyOutward(10);
   }
   return r;
 }
 
 NS_IMETHODIMP
-nsDOMNotifyPaintEvent::GetBoundingClientRect(nsIDOMClientRect** aResult)
+NotifyPaintEvent::GetBoundingClientRect(nsIDOMClientRect** aResult)
 {
   *aResult = BoundingClientRect().get();
   return NS_OK;
 }
 
 already_AddRefed<DOMRect>
-nsDOMNotifyPaintEvent::BoundingClientRect()
+NotifyPaintEvent::BoundingClientRect()
 {
   nsRefPtr<DOMRect> rect = new DOMRect(ToSupports(this));
 
   if (mPresContext) {
     rect->SetLayoutRect(GetRegion().GetBounds());
   }
 
   return rect.forget();
 }
 
 NS_IMETHODIMP
-nsDOMNotifyPaintEvent::GetClientRects(nsIDOMClientRectList** aResult)
+NotifyPaintEvent::GetClientRects(nsIDOMClientRectList** aResult)
 {
   *aResult = ClientRects().get();
   return NS_OK;
 }
 
 already_AddRefed<DOMRectList>
-nsDOMNotifyPaintEvent::ClientRects()
+NotifyPaintEvent::ClientRects()
 {
   nsISupports* parent = ToSupports(this);
   nsRefPtr<DOMRectList> rectList = new DOMRectList(parent);
 
   nsRegion r = GetRegion();
   nsRegionRectIterator iter(r);
   for (const nsRect* rgnRect = iter.Next(); rgnRect; rgnRect = iter.Next()) {
     nsRefPtr<DOMRect> rect = new DOMRect(parent);
@@ -90,81 +90,86 @@ nsDOMNotifyPaintEvent::ClientRects()
     rect->SetLayoutRect(*rgnRect);
     rectList->Append(rect);
   }
 
   return rectList.forget();
 }
 
 NS_IMETHODIMP
-nsDOMNotifyPaintEvent::GetPaintRequests(nsISupports** aResult)
+NotifyPaintEvent::GetPaintRequests(nsISupports** aResult)
 {
   nsRefPtr<nsPaintRequestList> requests = PaintRequests();
   requests.forget(aResult);
   return NS_OK;
 }
 
 already_AddRefed<nsPaintRequestList>
-nsDOMNotifyPaintEvent::PaintRequests()
+NotifyPaintEvent::PaintRequests()
 {
   nsDOMEvent* parent = this;
   nsRefPtr<nsPaintRequestList> requests = new nsPaintRequestList(parent);
 
   if (nsContentUtils::IsCallerChrome()) {
     for (uint32_t i = 0; i < mInvalidateRequests.Length(); ++i) {
       nsRefPtr<nsPaintRequest> r = new nsPaintRequest(parent);
       r->SetRequest(mInvalidateRequests[i]);
       requests->Append(r);
     }
   }
 
   return requests.forget();
 }
 
 NS_IMETHODIMP_(void)
-nsDOMNotifyPaintEvent::Serialize(IPC::Message* aMsg,
-                                 bool aSerializeInterfaceType)
+NotifyPaintEvent::Serialize(IPC::Message* aMsg,
+                            bool aSerializeInterfaceType)
 {
   if (aSerializeInterfaceType) {
     IPC::WriteParam(aMsg, NS_LITERAL_STRING("notifypaintevent"));
   }
 
   nsDOMEvent::Serialize(aMsg, false);
 
   uint32_t length = mInvalidateRequests.Length();
   IPC::WriteParam(aMsg, length);
   for (uint32_t i = 0; i < length; ++i) {
     IPC::WriteParam(aMsg, mInvalidateRequests[i].mRect);
     IPC::WriteParam(aMsg, mInvalidateRequests[i].mFlags);
   }
 }
 
 NS_IMETHODIMP_(bool)
-nsDOMNotifyPaintEvent::Deserialize(const IPC::Message* aMsg, void** aIter)
+NotifyPaintEvent::Deserialize(const IPC::Message* aMsg, void** aIter)
 {
   NS_ENSURE_TRUE(nsDOMEvent::Deserialize(aMsg, aIter), false);
 
   uint32_t length = 0;
   NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &length), false);
   mInvalidateRequests.SetCapacity(length);
   for (uint32_t i = 0; i < length; ++i) {
     nsInvalidateRequestList::Request req;
     NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &req.mRect), false);
     NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &req.mFlags), false);
     mInvalidateRequests.AppendElement(req);
   }
 
   return true;
 }
 
-nsresult NS_NewDOMNotifyPaintEvent(nsIDOMEvent** aInstancePtrResult,
-                                   mozilla::dom::EventTarget* aOwner,
-                                   nsPresContext* aPresContext,
-                                   WidgetEvent* aEvent,
-                                   uint32_t aEventType,
-                                   nsInvalidateRequestList* aInvalidateRequests) 
+} // namespace dom
+} // namespace mozilla
+
+using namespace mozilla;
+using namespace mozilla::dom;
+
+nsresult
+NS_NewDOMNotifyPaintEvent(nsIDOMEvent** aInstancePtrResult,
+                          EventTarget* aOwner,
+                          nsPresContext* aPresContext,
+                          WidgetEvent* aEvent,
+                          uint32_t aEventType,
+                          nsInvalidateRequestList* aInvalidateRequests) 
 {
-  nsDOMNotifyPaintEvent* it =
-    new nsDOMNotifyPaintEvent(aOwner, aPresContext, aEvent, aEventType,
-                              aInvalidateRequests);
-
+  NotifyPaintEvent* it = new NotifyPaintEvent(aOwner, aPresContext, aEvent,
+                                              aEventType, aInvalidateRequests);
   return CallQueryInterface(it, aInstancePtrResult);
 }
rename from dom/events/nsDOMNotifyPaintEvent.h
rename to dom/events/NotifyPaintEvent.h
--- a/dom/events/nsDOMNotifyPaintEvent.h
+++ b/dom/events/NotifyPaintEvent.h
@@ -1,43 +1,40 @@
 /* -*- Mode: C++; 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/. */
 
-#ifndef nsDOMNotifyPaintEvent_h_
-#define nsDOMNotifyPaintEvent_h_
+#ifndef mozilla_dom_NotifyPaintEvent_h_
+#define mozilla_dom_NotifyPaintEvent_h_
 
 #include "mozilla/Attributes.h"
 #include "nsIDOMNotifyPaintEvent.h"
 #include "nsDOMEvent.h"
 #include "nsPresContext.h"
 #include "mozilla/dom/NotifyPaintEventBinding.h"
 
 class nsPaintRequestList;
 
 namespace mozilla {
 namespace dom {
+
 class DOMRect;
 class DOMRectList;
-}
-}
 
-class nsDOMNotifyPaintEvent : public nsDOMEvent,
-                              public nsIDOMNotifyPaintEvent
+class NotifyPaintEvent : public nsDOMEvent,
+                         public nsIDOMNotifyPaintEvent
 {
-  typedef mozilla::dom::DOMRect DOMRect;
-  typedef mozilla::dom::DOMRectList DOMRectList;
 
 public:
-  nsDOMNotifyPaintEvent(mozilla::dom::EventTarget* aOwner,
-                        nsPresContext*           aPresContext,
-                        mozilla::WidgetEvent*    aEvent,
-                        uint32_t                 aEventType,
-                        nsInvalidateRequestList* aInvalidateRequests);
+  NotifyPaintEvent(EventTarget* aOwner,
+                   nsPresContext* aPresContext,
+                   WidgetEvent* aEvent,
+                   uint32_t aEventType,
+                   nsInvalidateRequestList* aInvalidateRequests);
 
   NS_DECL_ISUPPORTS_INHERITED
 
   NS_DECL_NSIDOMNOTIFYPAINTEVENT
 
   // Forward to base class
   NS_FORWARD_TO_NSDOMEVENT_NO_SERIALIZATION_NO_DUPLICATION
   NS_IMETHOD DuplicatePrivateData() MOZ_OVERRIDE
@@ -45,23 +42,26 @@ public:
     return nsDOMEvent::DuplicatePrivateData();
   }
   NS_IMETHOD_(void) Serialize(IPC::Message* aMsg, bool aSerializeInterfaceType) MOZ_OVERRIDE;
   NS_IMETHOD_(bool) Deserialize(const IPC::Message* aMsg, void** aIter) MOZ_OVERRIDE;
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
-    return mozilla::dom::NotifyPaintEventBinding::Wrap(aCx, aScope, this);
+    return NotifyPaintEventBinding::Wrap(aCx, aScope, this);
   }
 
   already_AddRefed<DOMRectList> ClientRects();
 
   already_AddRefed<DOMRect> BoundingClientRect();
 
   already_AddRefed<nsPaintRequestList> PaintRequests();
 private:
   nsRegion GetRegion();
 
   nsTArray<nsInvalidateRequestList::Request> mInvalidateRequests;
 };
 
-#endif // nsDOMNotifyPaintEvent_h_
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_NotifyPaintEvent_h_
rename from dom/events/nsDOMScrollAreaEvent.cpp
rename to dom/events/ScrollAreaEvent.cpp
--- a/dom/events/nsDOMScrollAreaEvent.cpp
+++ b/dom/events/ScrollAreaEvent.cpp
@@ -1,102 +1,110 @@
 /* -*- Mode: C++; 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 "base/basictypes.h"
 #include "ipc/IPCMessageUtils.h"
+#include "mozilla/dom/DOMRect.h"
+#include "mozilla/dom/ScrollAreaEvent.h"
 #include "mozilla/ContentEvents.h"
 
-#include "nsDOMScrollAreaEvent.h"
-#include "mozilla/dom/DOMRect.h"
-
-using namespace mozilla;
+namespace mozilla {
+namespace dom {
 
-nsDOMScrollAreaEvent::nsDOMScrollAreaEvent(mozilla::dom::EventTarget* aOwner,
-                                           nsPresContext *aPresContext,
-                                           InternalScrollAreaEvent* aEvent)
-  : nsDOMUIEvent(aOwner, aPresContext, aEvent)
+ScrollAreaEvent::ScrollAreaEvent(EventTarget* aOwner,
+                                 nsPresContext* aPresContext,
+                                 InternalScrollAreaEvent* aEvent)
+  : UIEvent(aOwner, aPresContext, aEvent)
   , mClientArea(nullptr)
 {
   mClientArea.SetLayoutRect(aEvent ? aEvent->mArea : nsRect());
 }
 
-NS_IMPL_ADDREF_INHERITED(nsDOMScrollAreaEvent, nsDOMUIEvent)
-NS_IMPL_RELEASE_INHERITED(nsDOMScrollAreaEvent, nsDOMUIEvent)
+NS_IMPL_ADDREF_INHERITED(ScrollAreaEvent, UIEvent)
+NS_IMPL_RELEASE_INHERITED(ScrollAreaEvent, UIEvent)
 
-NS_INTERFACE_MAP_BEGIN(nsDOMScrollAreaEvent)
+NS_INTERFACE_MAP_BEGIN(ScrollAreaEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMScrollAreaEvent)
-NS_INTERFACE_MAP_END_INHERITING(nsDOMUIEvent)
+NS_INTERFACE_MAP_END_INHERITING(UIEvent)
 
 
-#define FORWARD_GETTER(_name)                                                   \
-  NS_IMETHODIMP                                                                 \
-  nsDOMScrollAreaEvent::Get ## _name(float* aResult)                            \
-  {                                                                             \
-    *aResult = _name();                                                         \
-    return NS_OK;                                                               \
+#define FORWARD_GETTER(_name)                                                  \
+  NS_IMETHODIMP                                                                \
+  ScrollAreaEvent::Get ## _name(float* aResult)                                \
+  {                                                                            \
+    *aResult = _name();                                                        \
+    return NS_OK;                                                              \
   }
 
 FORWARD_GETTER(X)
 FORWARD_GETTER(Y)
 FORWARD_GETTER(Width)
 FORWARD_GETTER(Height)
 
 NS_IMETHODIMP
-nsDOMScrollAreaEvent::InitScrollAreaEvent(const nsAString &aEventType,
-                                          bool aCanBubble,
-                                          bool aCancelable,
-                                          nsIDOMWindow *aView,
-                                          int32_t aDetail,
-                                          float aX, float aY,
-                                          float aWidth, float aHeight)
+ScrollAreaEvent::InitScrollAreaEvent(const nsAString& aEventType,
+                                     bool aCanBubble,
+                                     bool aCancelable,
+                                     nsIDOMWindow* aView,
+                                     int32_t aDetail,
+                                     float aX,
+                                     float aY,
+                                     float aWidth,
+                                     float aHeight)
 {
-  nsresult rv = nsDOMUIEvent::InitUIEvent(aEventType, aCanBubble, aCancelable, aView, aDetail);
+  nsresult rv =
+    UIEvent::InitUIEvent(aEventType, aCanBubble, aCancelable, aView, aDetail);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mClientArea.SetRect(aX, aY, aWidth, aHeight);
 
   return NS_OK;
 }
 
 NS_IMETHODIMP_(void)
-nsDOMScrollAreaEvent::Serialize(IPC::Message* aMsg,
-                                bool aSerializeInterfaceType)
+ScrollAreaEvent::Serialize(IPC::Message* aMsg,
+                           bool aSerializeInterfaceType)
 {
   if (aSerializeInterfaceType) {
     IPC::WriteParam(aMsg, NS_LITERAL_STRING("scrollareaevent"));
   }
 
   nsDOMEvent::Serialize(aMsg, false);
 
   IPC::WriteParam(aMsg, X());
   IPC::WriteParam(aMsg, Y());
   IPC::WriteParam(aMsg, Width());
   IPC::WriteParam(aMsg, Height());
 }
 
 NS_IMETHODIMP_(bool)
-nsDOMScrollAreaEvent::Deserialize(const IPC::Message* aMsg, void** aIter)
+ScrollAreaEvent::Deserialize(const IPC::Message* aMsg, void** aIter)
 {
   NS_ENSURE_TRUE(nsDOMEvent::Deserialize(aMsg, aIter), false);
 
   float x, y, width, height;
   NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &x), false);
   NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &y), false);
   NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &width), false);
   NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &height), false);
   mClientArea.SetRect(x, y, width, height);
 
   return true;
 }
 
+} // namespace dom
+} // namespace mozilla
+
+using namespace mozilla;
+using namespace mozilla::dom;
+
 nsresult
-NS_NewDOMScrollAreaEvent(nsIDOMEvent **aInstancePtrResult,
-                         mozilla::dom::EventTarget* aOwner,
-                         nsPresContext *aPresContext,
+NS_NewDOMScrollAreaEvent(nsIDOMEvent** aInstancePtrResult,
+                         EventTarget* aOwner,
+                         nsPresContext* aPresContext,
                          InternalScrollAreaEvent* aEvent)
 {
-  nsDOMScrollAreaEvent* ev =
-    new nsDOMScrollAreaEvent(aOwner, aPresContext, aEvent);
+  ScrollAreaEvent* ev = new ScrollAreaEvent(aOwner, aPresContext, aEvent);
   return CallQueryInterface(ev, aInstancePtrResult);
 }
rename from dom/events/nsDOMScrollAreaEvent.h
rename to dom/events/ScrollAreaEvent.h
--- a/dom/events/nsDOMScrollAreaEvent.h
+++ b/dom/events/ScrollAreaEvent.h
@@ -1,52 +1,52 @@
 /* -*- Mode: C++; 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/. */
 
-#ifndef nsDOMScrollAreaEvent_h__
-#define nsDOMScrollAreaEvent_h__
-
-#include "mozilla/Attributes.h"
-#include "mozilla/EventForwards.h"
-#include "nsIDOMScrollAreaEvent.h"
-#include "nsDOMUIEvent.h"
+#ifndef mozilla_dom_ScrollAreaEvent_h_
+#define mozilla_dom_ScrollAreaEvent_h_
 
 #include "mozilla/dom/DOMRect.h"
 #include "mozilla/dom/ScrollAreaEventBinding.h"
+#include "mozilla/dom/UIEvent.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/EventForwards.h"
+#include "nsIDOMScrollAreaEvent.h"
 
-class nsDOMScrollAreaEvent : public nsDOMUIEvent,
-                             public nsIDOMScrollAreaEvent
+namespace mozilla {
+namespace dom {
+
+class ScrollAreaEvent : public UIEvent,
+                        public nsIDOMScrollAreaEvent
 {
-  typedef mozilla::dom::DOMRect DOMRect;
-
 public:
-  nsDOMScrollAreaEvent(mozilla::dom::EventTarget* aOwner,
-                       nsPresContext *aPresContext,
-                       mozilla::InternalScrollAreaEvent* aEvent);
+  ScrollAreaEvent(EventTarget* aOwner,
+                  nsPresContext* aPresContext,
+                  InternalScrollAreaEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
 
   NS_DECL_NSIDOMSCROLLAREAEVENT
 
-  NS_FORWARD_NSIDOMUIEVENT(nsDOMUIEvent::)
+  NS_FORWARD_NSIDOMUIEVENT(UIEvent::)
 
   NS_FORWARD_TO_NSDOMEVENT_NO_SERIALIZATION_NO_DUPLICATION
   NS_IMETHOD DuplicatePrivateData()
   {
     return nsDOMEvent::DuplicatePrivateData();
   }
   NS_IMETHOD_(void) Serialize(IPC::Message* aMsg, bool aSerializeInterfaceType) MOZ_OVERRIDE;
   NS_IMETHOD_(bool) Deserialize(const IPC::Message* aMsg, void** aIter) MOZ_OVERRIDE;
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
-    return mozilla::dom::ScrollAreaEventBinding::Wrap(aCx, aScope, this);
+    return ScrollAreaEventBinding::Wrap(aCx, aScope, this);
   }
 
   float X() const
   {
     return mClientArea.Left();
   }
 
   float Y() const
@@ -66,19 +66,22 @@ public:
 
   void InitScrollAreaEvent(const nsAString& aType,
                            bool aCanBubble,
                            bool aCancelable,
                            nsIDOMWindow* aView,
                            int32_t aDetail,
                            float aX, float aY,
                            float aWidth, float aHeight,
-                           mozilla::ErrorResult& aRv)
+                           ErrorResult& aRv)
   {
     aRv = InitScrollAreaEvent(aType, aCanBubble, aCancelable, aView,
                               aDetail, aX, aY, aWidth, aHeight);
   }
 
 protected:
   DOMRect mClientArea;
 };
 
-#endif // nsDOMScrollAreaEvent_h__
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_ScrollAreaEvent_h_
--- a/dom/events/Touch.cpp
+++ b/dom/events/Touch.cpp
@@ -2,24 +2,24 @@
 /* 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 "mozilla/dom/Touch.h"
 
 #include "mozilla/dom/EventTarget.h"
 #include "mozilla/dom/TouchBinding.h"
+#include "mozilla/dom/TouchEvent.h"
 #include "nsContentUtils.h"
-#include "nsDOMTouchEvent.h"
 #include "nsIContent.h"
 
 namespace mozilla {
 namespace dom {
 
-Touch::Touch(mozilla::dom::EventTarget* aTarget,
+Touch::Touch(EventTarget* aTarget,
              int32_t aIdentifier,
              int32_t aPageX,
              int32_t aPageY,
              int32_t aScreenX,
              int32_t aScreenY,
              int32_t aClientX,
              int32_t aClientY,
              int32_t aRadiusX,
@@ -66,20 +66,21 @@ Touch::Touch(int32_t aIdentifier,
   mMessage = 0;
   nsJSContext::LikelyShortLivingObjectCreated();
 }
 
 Touch::~Touch()
 {
 }
 
- /* static */ bool
+// static
+bool
 Touch::PrefEnabled(JSContext* aCx, JSObject* aGlobal)
 {
-  return nsDOMTouchEvent::PrefEnabled(aCx, aGlobal);
+  return TouchEvent::PrefEnabled(aCx, aGlobal);
 }
 
 NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_1(Touch, mTarget)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Touch)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
@@ -112,31 +113,31 @@ Touch::InitializePoints(nsPresContext* a
     aPresContext, aEvent, LayoutDeviceIntPoint::FromUntyped(mRefPoint),
     mClientPoint);
   mScreenPoint = nsDOMEvent::GetScreenCoords(aPresContext, aEvent,
     LayoutDeviceIntPoint::FromUntyped(mRefPoint));
   mPointsInitialized = true;
 }
 
 void
-Touch::SetTarget(mozilla::dom::EventTarget* aTarget)
+Touch::SetTarget(EventTarget* aTarget)
 {
   mTarget = aTarget;
 }
 
 bool
 Touch::Equals(Touch* aTouch)
 {
   return mRefPoint == aTouch->mRefPoint &&
          mForce == aTouch->Force() &&
          mRotationAngle == aTouch->RotationAngle() &&
          mRadius.x == aTouch->RadiusX() &&
          mRadius.y == aTouch->RadiusY();
 }
 
-/* virtual */ JSObject*
+JSObject*
 Touch::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
   return TouchBinding::Wrap(aCx, aScope, this);
 }
 
 } // namespace dom
 } // namespace mozilla
--- a/dom/events/Touch.h
+++ b/dom/events/Touch.h
@@ -1,15 +1,15 @@
 /* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#ifndef mozilla_dom_Touch_h
-#define mozilla_dom_Touch_h
+#ifndef mozilla_dom_Touch_h_
+#define mozilla_dom_Touch_h_
 
 #include "mozilla/Attributes.h"
 #include "mozilla/EventForwards.h"
 #include "mozilla/MouseEvents.h"
 #include "nsWrapperCache.h"
 #include "nsAutoPtr.h"
 #include "Units.h"
 
@@ -22,17 +22,17 @@ class EventTarget;
 
 class Touch MOZ_FINAL : public nsISupports
                       , public nsWrapperCache
                       , public WidgetPointerHelper
 {
 public:
   static bool PrefEnabled(JSContext* aCx, JSObject* aGlobal);
 
-  Touch(mozilla::dom::EventTarget* aTarget,
+  Touch(EventTarget* aTarget,
         int32_t aIdentifier,
         int32_t aPageX,
         int32_t aPageY,
         int32_t aScreenX,
         int32_t aScreenY,
         int32_t aClientX,
         int32_t aClientY,
         int32_t aRadiusX,
@@ -47,17 +47,17 @@ public:
 
   ~Touch();
 
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Touch)
 
   void InitializePoints(nsPresContext* aPresContext, WidgetEvent* aEvent);
 
-  void SetTarget(mozilla::dom::EventTarget* aTarget);
+  void SetTarget(EventTarget* aTarget);
 
   bool Equals(Touch* aTouch);
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
   EventTarget* GetParentObject() { return mTarget; }
 
   // WebIDL
@@ -87,9 +87,9 @@ public:
   float mForce;
 protected:
   bool mPointsInitialized;
 };
 
 } // namespace dom
 } // namespace mozilla
 
-#endif // mozilla_dom_Touch_h
+#endif // mozilla_dom_Touch_h_
rename from dom/events/nsDOMTouchEvent.cpp
rename to dom/events/TouchEvent.cpp
--- a/dom/events/nsDOMTouchEvent.cpp
+++ b/dom/events/TouchEvent.cpp
@@ -1,207 +1,208 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "nsDOMTouchEvent.h"
-#include "nsContentUtils.h"
-#include "mozilla/Preferences.h"
+#include "mozilla/dom/TouchEvent.h"
 #include "mozilla/dom/Touch.h"
 #include "mozilla/dom/TouchListBinding.h"
+#include "mozilla/Preferences.h"
 #include "mozilla/TouchEvents.h"
+#include "nsContentUtils.h"
+
+namespace mozilla {
 
-using namespace mozilla;
-using namespace mozilla::dom;
+#ifdef XP_WIN
+namespace widget {
+extern int32_t IsTouchDeviceSupportPresent();
+} // namespace widget
+#endif // #ifdef XP_WIN
 
-// TouchList
+namespace dom {
 
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMTouchList)
+/******************************************************************************
+ * TouchList
+ *****************************************************************************/
+
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TouchList)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
-NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_2(nsDOMTouchList, mParent, mPoints)
+NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_2(TouchList, mParent, mPoints)
 
-NS_IMPL_CYCLE_COLLECTING_ADDREF(nsDOMTouchList)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(nsDOMTouchList)
+NS_IMPL_CYCLE_COLLECTING_ADDREF(TouchList)
+NS_IMPL_CYCLE_COLLECTING_RELEASE(TouchList)
 
-/* virtual */ JSObject*
-nsDOMTouchList::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
+JSObject*
+TouchList::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
   return TouchListBinding::Wrap(aCx, aScope, this);
 }
 
-/* static */ bool
-nsDOMTouchList::PrefEnabled(JSContext* aCx, JSObject* aGlobal)
+// static
+bool
+TouchList::PrefEnabled(JSContext* aCx, JSObject* aGlobal)
 {
-  return nsDOMTouchEvent::PrefEnabled(aCx, aGlobal);
+  return TouchEvent::PrefEnabled(aCx, aGlobal);
 }
 
 Touch*
-nsDOMTouchList::IdentifiedTouch(int32_t aIdentifier) const
+TouchList::IdentifiedTouch(int32_t aIdentifier) const
 {
   for (uint32_t i = 0; i < mPoints.Length(); ++i) {
     Touch* point = mPoints[i];
     if (point && point->Identifier() == aIdentifier) {
       return point;
     }
   }
   return nullptr;
 }
 
-// TouchEvent
+/******************************************************************************
+ * TouchEvent
+ *****************************************************************************/
 
-nsDOMTouchEvent::nsDOMTouchEvent(mozilla::dom::EventTarget* aOwner,
-                                 nsPresContext* aPresContext,
-                                 WidgetTouchEvent* aEvent)
-  : nsDOMUIEvent(aOwner, aPresContext,
-                 aEvent ? aEvent : new WidgetTouchEvent(false, 0, nullptr))
+TouchEvent::TouchEvent(EventTarget* aOwner,
+                       nsPresContext* aPresContext,
+                       WidgetTouchEvent* aEvent)
+  : UIEvent(aOwner, aPresContext,
+            aEvent ? aEvent : new WidgetTouchEvent(false, 0, nullptr))
 {
   if (aEvent) {
     mEventIsInternal = false;
 
     for (uint32_t i = 0; i < aEvent->touches.Length(); ++i) {
       Touch* touch = aEvent->touches[i];
       touch->InitializePoints(mPresContext, aEvent);
     }
   } else {
     mEventIsInternal = true;
     mEvent->time = PR_Now();
   }
 }
 
-NS_IMPL_CYCLE_COLLECTION_INHERITED_3(nsDOMTouchEvent, nsDOMUIEvent,
+NS_IMPL_CYCLE_COLLECTION_INHERITED_3(TouchEvent, UIEvent,
                                      mTouches,
                                      mTargetTouches,
                                      mChangedTouches)
 
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMTouchEvent)
-NS_INTERFACE_MAP_END_INHERITING(nsDOMUIEvent)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(TouchEvent)
+NS_INTERFACE_MAP_END_INHERITING(UIEvent)
 
-NS_IMPL_ADDREF_INHERITED(nsDOMTouchEvent, nsDOMUIEvent)
-NS_IMPL_RELEASE_INHERITED(nsDOMTouchEvent, nsDOMUIEvent)
-
+NS_IMPL_ADDREF_INHERITED(TouchEvent, UIEvent)
+NS_IMPL_RELEASE_INHERITED(TouchEvent, UIEvent)
 
 void
-nsDOMTouchEvent::InitTouchEvent(const nsAString& aType,
-                                bool aCanBubble,
-                                bool aCancelable,
-                                nsIDOMWindow* aView,
-                                int32_t aDetail,
-                                bool aCtrlKey,
-                                bool aAltKey,
-                                bool aShiftKey,
-                                bool aMetaKey,
-                                nsDOMTouchList* aTouches,
-                                nsDOMTouchList* aTargetTouches,
-                                nsDOMTouchList* aChangedTouches,
-                                mozilla::ErrorResult& aRv)
+TouchEvent::InitTouchEvent(const nsAString& aType,
+                           bool aCanBubble,
+                           bool aCancelable,
+                           nsIDOMWindow* aView,
+                           int32_t aDetail,
+                           bool aCtrlKey,
+                           bool aAltKey,
+                           bool aShiftKey,
+                           bool aMetaKey,
+                           TouchList* aTouches,
+                           TouchList* aTargetTouches,
+                           TouchList* aChangedTouches,
+                           ErrorResult& aRv)
 {
-  aRv = nsDOMUIEvent::InitUIEvent(aType,
-                                  aCanBubble,
-                                  aCancelable,
-                                  aView,
-                                  aDetail);
+  aRv = UIEvent::InitUIEvent(aType, aCanBubble, aCancelable, aView, aDetail);
   if (aRv.Failed()) {
     return;
   }
 
   mEvent->AsInputEvent()->InitBasicModifiers(aCtrlKey, aAltKey,
                                              aShiftKey, aMetaKey);
   mTouches = aTouches;
   mTargetTouches = aTargetTouches;
   mChangedTouches = aChangedTouches;
 }
 
-nsDOMTouchList*
-nsDOMTouchEvent::Touches()
+TouchList*
+TouchEvent::Touches()
 {
   if (!mTouches) {
     WidgetTouchEvent* touchEvent = mEvent->AsTouchEvent();
     if (mEvent->message == NS_TOUCH_END || mEvent->message == NS_TOUCH_CANCEL) {
       // for touchend events, remove any changed touches from the touches array
       nsTArray< nsRefPtr<Touch> > unchangedTouches;
       const nsTArray< nsRefPtr<Touch> >& touches = touchEvent->touches;
       for (uint32_t i = 0; i < touches.Length(); ++i) {
         if (!touches[i]->mChanged) {
           unchangedTouches.AppendElement(touches[i]);
         }
       }
-      mTouches = new nsDOMTouchList(ToSupports(this), unchangedTouches);
+      mTouches = new TouchList(ToSupports(this), unchangedTouches);
     } else {
-      mTouches = new nsDOMTouchList(ToSupports(this), touchEvent->touches);
+      mTouches = new TouchList(ToSupports(this), touchEvent->touches);
     }
   }
   return mTouches;
 }
 
-nsDOMTouchList*
-nsDOMTouchEvent::TargetTouches()
+TouchList*
+TouchEvent::TargetTouches()
 {
   if (!mTargetTouches) {
     nsTArray< nsRefPtr<Touch> > targetTouches;
     WidgetTouchEvent* touchEvent = mEvent->AsTouchEvent();
     const nsTArray< nsRefPtr<Touch> >& touches = touchEvent->touches;
     for (uint32_t i = 0; i < touches.Length(); ++i) {
       // for touchend/cancel events, don't append to the target list if this is a
       // touch that is ending
       if ((mEvent->message != NS_TOUCH_END &&
            mEvent->message != NS_TOUCH_CANCEL) || !touches[i]->mChanged) {
         if (touches[i]->mTarget == mEvent->originalTarget) {
           targetTouches.AppendElement(touches[i]);
         }
       }
     }
-    mTargetTouches = new nsDOMTouchList(ToSupports(this), targetTouches);
+    mTargetTouches = new TouchList(ToSupports(this), targetTouches);
   }
   return mTargetTouches;
 }
 
-nsDOMTouchList*
-nsDOMTouchEvent::ChangedTouches()
+TouchList*
+TouchEvent::ChangedTouches()
 {
   if (!mChangedTouches) {
     nsTArray< nsRefPtr<Touch> > changedTouches;
     WidgetTouchEvent* touchEvent = mEvent->AsTouchEvent();
     const nsTArray< nsRefPtr<Touch> >& touches = touchEvent->touches;
     for (uint32_t i = 0; i < touches.Length(); ++i) {
       if (touches[i]->mChanged) {
         changedTouches.AppendElement(touches[i]);
       }
     }
-    mChangedTouches = new nsDOMTouchList(ToSupports(this), changedTouches);
+    mChangedTouches = new TouchList(ToSupports(this), changedTouches);
   }
   return mChangedTouches;
 }
 
-#ifdef XP_WIN
-namespace mozilla {
-namespace widget {
-extern int32_t IsTouchDeviceSupportPresent();
-} }
-#endif
-
+// static
 bool
-nsDOMTouchEvent::PrefEnabled(JSContext* aCx, JSObject* aGlobal)
+TouchEvent::PrefEnabled(JSContext* aCx, JSObject* aGlobal)
 {
   bool prefValue = false;
   int32_t flag = 0;
   if (NS_SUCCEEDED(Preferences::GetInt("dom.w3c_touch_events.enabled",
                                         &flag))) {
     if (flag == 2) {
 #ifdef XP_WIN
       static bool sDidCheckTouchDeviceSupport = false;
       static bool sIsTouchDeviceSupportPresent = false;
       // On Windows we auto-detect based on device support.
       if (!sDidCheckTouchDeviceSupport) {
         sDidCheckTouchDeviceSupport = true;
-        sIsTouchDeviceSupportPresent = mozilla::widget::IsTouchDeviceSupportPresent();
+        sIsTouchDeviceSupportPresent = widget::IsTouchDeviceSupportPresent();
       }
       prefValue = sIsTouchDeviceSupportPresent;
 #else
       NS_WARNING("dom.w3c_touch_events.enabled=2 not implemented!");
       prefValue = false;
 #endif
     } else {
       prefValue = !!flag;
@@ -209,40 +210,46 @@ nsDOMTouchEvent::PrefEnabled(JSContext* 
   }
   if (prefValue) {
     nsContentUtils::InitializeTouchEventTable();
   }
   return prefValue;
 }
 
 bool
-nsDOMTouchEvent::AltKey()
+TouchEvent::AltKey()
 {
   return mEvent->AsTouchEvent()->IsAlt();
 }
 
 bool
-nsDOMTouchEvent::MetaKey()
+TouchEvent::MetaKey()
 {
   return mEvent->AsTouchEvent()->IsMeta();
 }
 
 bool
-nsDOMTouchEvent::CtrlKey()
+TouchEvent::CtrlKey()
 {
   return mEvent->AsTouchEvent()->IsControl();
 }
 
 bool
-nsDOMTouchEvent::ShiftKey()
+TouchEvent::ShiftKey()
 {
   return mEvent->AsTouchEvent()->IsShift();
 }
 
+} // namespace dom
+} // namespace mozilla
+
+using namespace mozilla;
+using namespace mozilla::dom;
+
 nsresult
 NS_NewDOMTouchEvent(nsIDOMEvent** aInstancePtrResult,
-                    mozilla::dom::EventTarget* aOwner,
+                    EventTarget* aOwner,
                     nsPresContext* aPresContext,
                     WidgetTouchEvent* aEvent)
 {
-  nsDOMTouchEvent* it = new nsDOMTouchEvent(aOwner, aPresContext, aEvent);
+  TouchEvent* it = new TouchEvent(aOwner, aPresContext, aEvent);
   return CallQueryInterface(it, aInstancePtrResult);
 }
rename from dom/events/nsDOMTouchEvent.h
rename to dom/events/TouchEvent.h
--- a/dom/events/nsDOMTouchEvent.h
+++ b/dom/events/TouchEvent.h
@@ -1,65 +1,66 @@
 /* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-#ifndef nsDOMTouchEvent_h_
-#define nsDOMTouchEvent_h_
+#ifndef mozilla_dom_TouchEvent_h_
+#define mozilla_dom_TouchEvent_h_
 
-#include "nsDOMUIEvent.h"
-#include "nsTArray.h"
+#include "mozilla/dom/Touch.h"
+#include "mozilla/dom/TouchEventBinding.h"
+#include "mozilla/dom/UIEvent.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/EventForwards.h"
 #include "nsJSEnvironment.h"
-#include "mozilla/dom/Touch.h"
-#include "mozilla/dom/TouchEventBinding.h"
+#include "nsTArray.h"
 #include "nsWrapperCache.h"
 
-
 class nsAString;
 
-class nsDOMTouchList MOZ_FINAL : public nsISupports
-                               , public nsWrapperCache
+namespace mozilla {
+namespace dom {
+
+class TouchList MOZ_FINAL : public nsISupports
+                          , public nsWrapperCache
 {
-  typedef mozilla::dom::Touch Touch;
-
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(nsDOMTouchList)
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(TouchList)
 
-  nsDOMTouchList(nsISupports* aParent)
+  TouchList(nsISupports* aParent)
     : mParent(aParent)
   {
     SetIsDOMBinding();
     nsJSContext::LikelyShortLivingObjectCreated();
   }
-  nsDOMTouchList(nsISupports* aParent,
-                 const nsTArray< nsRefPtr<Touch> >& aTouches)
+  TouchList(nsISupports* aParent,
+            const nsTArray<nsRefPtr<Touch> >& aTouches)
     : mParent(aParent)
     , mPoints(aTouches)
   {
     SetIsDOMBinding();
     nsJSContext::LikelyShortLivingObjectCreated();
   }
 
   void Append(Touch* aPoint)
   {
     mPoints.AppendElement(aPoint);
   }
 
-  virtual JSObject*
-  WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
+  virtual JSObject* WrapObject(JSContext* aCx,
+                               JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
 
   nsISupports* GetParentObject() const
   {
     return mParent;
   }
 
-  static bool PrefEnabled(JSContext* aCx = nullptr, JSObject* aGlobal = nullptr);
+  static bool PrefEnabled(JSContext* aCx = nullptr,
+                          JSObject* aGlobal = nullptr);
 
   uint32_t Length() const
   {
     return mPoints.Length();
   }
   Touch* Item(uint32_t aIndex) const
   {
     return mPoints.SafeElementAt(aIndex);
@@ -71,58 +72,62 @@ public:
       return nullptr;
     }
     return mPoints[aIndex];
   }
   Touch* IdentifiedTouch(int32_t aIdentifier) const;
 
 protected:
   nsCOMPtr<nsISupports> mParent;
-  nsTArray< nsRefPtr<Touch> > mPoints;
+  nsTArray<nsRefPtr<Touch> > mPoints;
 };
 
-class nsDOMTouchEvent : public nsDOMUIEvent
+class TouchEvent : public UIEvent
 {
 public:
-  nsDOMTouchEvent(mozilla::dom::EventTarget* aOwner,
-                  nsPresContext* aPresContext,
-                  mozilla::WidgetTouchEvent* aEvent);
+  TouchEvent(EventTarget* aOwner,
+             nsPresContext* aPresContext,
+             WidgetTouchEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMTouchEvent, nsDOMUIEvent)
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(TouchEvent, UIEvent)
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
-    return mozilla::dom::TouchEventBinding::Wrap(aCx, aScope, this);
+    return TouchEventBinding::Wrap(aCx, aScope, this);
   }
 
-  nsDOMTouchList* Touches();
-  nsDOMTouchList* TargetTouches();
-  nsDOMTouchList* ChangedTouches();
+  TouchList* Touches();
+  TouchList* TargetTouches();
+  TouchList* ChangedTouches();
 
   bool AltKey();
   bool MetaKey();
   bool CtrlKey();
   bool ShiftKey();
 
   void InitTouchEvent(const nsAString& aType,
                       bool aCanBubble,
                       bool aCancelable,
                       nsIDOMWindow* aView,
                       int32_t aDetail,
                       bool aCtrlKey,
                       bool aAltKey,
                       bool aShiftKey,
                       bool aMetaKey,
-                      nsDOMTouchList* aTouches,
-                      nsDOMTouchList* aTargetTouches,
-                      nsDOMTouchList* aChangedTouches,
-                      mozilla::ErrorResult& aRv);
+                      TouchList* aTouches,
+                      TouchList* aTargetTouches,
+                      TouchList* aChangedTouches,
+                      ErrorResult& aRv);
 
-  static bool PrefEnabled(JSContext* aCx = nullptr, JSObject* aGlobal = nullptr);
+  static bool PrefEnabled(JSContext* aCx = nullptr,
+                          JSObject* aGlobal = nullptr);
 protected:
-  nsRefPtr<nsDOMTouchList> mTouches;
-  nsRefPtr<nsDOMTouchList> mTargetTouches;
-  nsRefPtr<nsDOMTouchList> mChangedTouches;
+  nsRefPtr<TouchList> mTouches;
+  nsRefPtr<TouchList> mTargetTouches;
+  nsRefPtr<TouchList> mChangedTouches;
 };
 
-#endif /* !defined(nsDOMTouchEvent_h_) */
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_TouchEvent_h_
rename from dom/events/nsDOMTransitionEvent.cpp
rename to dom/events/TransitionEvent.cpp
--- a/dom/events/nsDOMTransitionEvent.cpp
+++ b/dom/events/TransitionEvent.cpp
@@ -1,92 +1,98 @@
 /* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
 /* 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 "nsDOMTransitionEvent.h"
+#include "mozilla/dom/TransitionEvent.h"
+#include "mozilla/ContentEvents.h"
 #include "prtime.h"
-#include "mozilla/ContentEvents.h"
 
-using namespace mozilla;
+namespace mozilla {
+namespace dom {
 
-nsDOMTransitionEvent::nsDOMTransitionEvent(mozilla::dom::EventTarget* aOwner,
-                                           nsPresContext *aPresContext,
-                                           InternalTransitionEvent* aEvent)
+TransitionEvent::TransitionEvent(EventTarget* aOwner,
+                                 nsPresContext* aPresContext,
+                                 InternalTransitionEvent* aEvent)
   : nsDOMEvent(aOwner, aPresContext,
                aEvent ? aEvent : new InternalTransitionEvent(false, 0))
 {
   if (aEvent) {
     mEventIsInternal = false;
   }
   else {
     mEventIsInternal = true;
     mEvent->time = PR_Now();
   }
 }
 
-NS_INTERFACE_MAP_BEGIN(nsDOMTransitionEvent)
+NS_INTERFACE_MAP_BEGIN(TransitionEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMTransitionEvent)
 NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent)
 
-NS_IMPL_ADDREF_INHERITED(nsDOMTransitionEvent, nsDOMEvent)
-NS_IMPL_RELEASE_INHERITED(nsDOMTransitionEvent, nsDOMEvent)
+NS_IMPL_ADDREF_INHERITED(TransitionEvent, nsDOMEvent)
+NS_IMPL_RELEASE_INHERITED(TransitionEvent, nsDOMEvent)
 
-//static
-already_AddRefed<nsDOMTransitionEvent>
-nsDOMTransitionEvent::Constructor(const mozilla::dom::GlobalObject& aGlobal,
-                                  const nsAString& aType,
-                                  const mozilla::dom::TransitionEventInit& aParam,
-                                  mozilla::ErrorResult& aRv)
+// static
+already_AddRefed<TransitionEvent>
+TransitionEvent::Constructor(const GlobalObject& aGlobal,
+                             const nsAString& aType,
+                             const TransitionEventInit& aParam,
+                             ErrorResult& aRv)
 {
-  nsCOMPtr<mozilla::dom::EventTarget> t = do_QueryInterface(aGlobal.GetAsSupports());
-  nsRefPtr<nsDOMTransitionEvent> e = new nsDOMTransitionEvent(t, nullptr, nullptr);
+  nsCOMPtr<EventTarget> t = do_QueryInterface(aGlobal.GetAsSupports());
+  nsRefPtr<TransitionEvent> e = new TransitionEvent(t, nullptr, nullptr);
   bool trusted = e->Init(t);
 
   aRv = e->InitEvent(aType, aParam.mBubbles, aParam.mCancelable);
 
   InternalTransitionEvent* internalEvent = e->mEvent->AsTransitionEvent();
   internalEvent->propertyName = aParam.mPropertyName;
   internalEvent->elapsedTime = aParam.mElapsedTime;
   internalEvent->pseudoElement = aParam.mPseudoElement;
 
   e->SetTrusted(trusted);
   return e.forget();
 }
 
 NS_IMETHODIMP
-nsDOMTransitionEvent::GetPropertyName(nsAString & aPropertyName)
+TransitionEvent::GetPropertyName(nsAString& aPropertyName)
 {
   aPropertyName = mEvent->AsTransitionEvent()->propertyName;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMTransitionEvent::GetElapsedTime(float *aElapsedTime)
+TransitionEvent::GetElapsedTime(float* aElapsedTime)
 {
   *aElapsedTime = ElapsedTime();
   return NS_OK;
 }
 
 float
-nsDOMTransitionEvent::ElapsedTime()
+TransitionEvent::ElapsedTime()
 {
   return mEvent->AsTransitionEvent()->elapsedTime;
 }
 
 NS_IMETHODIMP
-nsDOMTransitionEvent::GetPseudoElement(nsAString& aPseudoElement)
+TransitionEvent::GetPseudoElement(nsAString& aPseudoElement)
 {
   aPseudoElement = mEvent->AsTransitionEvent()->pseudoElement;
   return NS_OK;
 }
 
+} // namespace dom
+} // namespace mozilla
+
+using namespace mozilla;
+using namespace mozilla::dom;
+
 nsresult
-NS_NewDOMTransitionEvent(nsIDOMEvent **aInstancePtrResult,
-                         mozilla::dom::EventTarget* aOwner,
-                         nsPresContext *aPresContext,
+NS_NewDOMTransitionEvent(nsIDOMEvent** aInstancePtrResult,
+                         EventTarget* aOwner,
+                         nsPresContext* aPresContext,
                          InternalTransitionEvent* aEvent)
 {
-  nsDOMTransitionEvent *it =
-    new nsDOMTransitionEvent(aOwner, aPresContext, aEvent);
+  TransitionEvent *it = new TransitionEvent(aOwner, aPresContext, aEvent);
   return CallQueryInterface(it, aInstancePtrResult);
 }
rename from dom/events/nsDOMTransitionEvent.h
rename to dom/events/TransitionEvent.h
--- a/dom/events/nsDOMTransitionEvent.h
+++ b/dom/events/TransitionEvent.h
@@ -1,46 +1,52 @@
 /* vim: set shiftwidth=2 tabstop=8 autoindent cindent expandtab: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
-#ifndef nsDOMTransitionEvent_h_
-#define nsDOMTransitionEvent_h_
+#ifndef mozilla_dom_TransitionEvent_h_
+#define mozilla_dom_TransitionEvent_h_
 
 #include "nsDOMEvent.h"
 #include "nsIDOMTransitionEvent.h"
 #include "mozilla/EventForwards.h"
 #include "mozilla/dom/TransitionEventBinding.h"
 
 class nsAString;
 
-class nsDOMTransitionEvent : public nsDOMEvent,
-                             public nsIDOMTransitionEvent
+namespace mozilla {
+namespace dom {
+
+class TransitionEvent : public nsDOMEvent,
+                        public nsIDOMTransitionEvent
 {
 public:
-  nsDOMTransitionEvent(mozilla::dom::EventTarget* aOwner,
-                       nsPresContext *aPresContext,
-                       mozilla::InternalTransitionEvent* aEvent);
+  TransitionEvent(EventTarget* aOwner,
+                  nsPresContext* aPresContext,
+                  InternalTransitionEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
   NS_FORWARD_TO_NSDOMEVENT
   NS_DECL_NSIDOMTRANSITIONEVENT
 
-  static already_AddRefed<nsDOMTransitionEvent>
-  Constructor(const mozilla::dom::GlobalObject& aGlobal,
+  static already_AddRefed<TransitionEvent>
+  Constructor(const GlobalObject& aGlobal,
               const nsAString& aType,
-              const mozilla::dom::TransitionEventInit& aParam,
-              mozilla::ErrorResult& aRv);
+              const TransitionEventInit& aParam,
+              ErrorResult& aRv);
 
   virtual JSObject* WrapObject(JSContext* aCx,
-			       JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
+                               JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
-    return mozilla::dom::TransitionEventBinding::Wrap(aCx, aScope, this);
+    return TransitionEventBinding::Wrap(aCx, aScope, this);
   }
 
   // xpidl implementation
   // GetPropertyName(nsAString& aPropertyName)
   // GetPseudoElement(nsAString& aPreudoElement)
 
   float ElapsedTime();
 };
 
-#endif /* !defined(nsDOMTransitionEvent_h_) */
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_TransitionEvent_h_
rename from dom/events/nsDOMUIEvent.cpp
rename to dom/events/UIEvent.cpp
--- a/dom/events/nsDOMUIEvent.cpp
+++ b/dom/events/UIEvent.cpp
@@ -1,37 +1,42 @@
 /* -*- Mode: C++; 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 "base/basictypes.h"
 #include "ipc/IPCMessageUtils.h"
-#include "nsCOMPtr.h"
-#include "nsDOMUIEvent.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "nsIDOMWindow.h"
-#include "nsIDOMNode.h"
-#include "nsIContent.h"
-#include "nsContentUtils.h"
-#include "nsEventStateManager.h"
-#include "nsIFrame.h"
+#include "mozilla/dom/UIEvent.h"
 #include "mozilla/ArrayUtils.h"
 #include "mozilla/Assertions.h"
 #include "mozilla/ContentEvents.h"
 #include "mozilla/TextEvents.h"
+#include "nsCOMPtr.h"
+#include "nsContentUtils.h"
+#include "nsEventStateManager.h"
+#include "nsIContent.h"
+#include "nsIInterfaceRequestorUtils.h"
+#include "nsIDOMWindow.h"
+#include "nsIDOMNode.h"
+#include "nsIFrame.h"
 #include "prtime.h"
 
-using namespace mozilla;
+namespace mozilla {
+namespace dom {
 
-nsDOMUIEvent::nsDOMUIEvent(mozilla::dom::EventTarget* aOwner,
-                           nsPresContext* aPresContext, WidgetGUIEvent* aEvent)
+UIEvent::UIEvent(EventTarget* aOwner,
+                 nsPresContext* aPresContext,
+                 WidgetGUIEvent* aEvent)
   : nsDOMEvent(aOwner, aPresContext,
                aEvent ? aEvent : new InternalUIEvent(false, 0))
-  , mClientPoint(0, 0), mLayerPoint(0, 0), mPagePoint(0, 0), mMovementPoint(0, 0)
+  , mClientPoint(0, 0)
+  , mLayerPoint(0, 0)
+  , mPagePoint(0, 0)
+  , mMovementPoint(0, 0)
   , mIsPointerLocked(nsEventStateManager::sIsPointerLocked)
   , mLastClientPoint(nsEventStateManager::sLastClientPoint)
 {
   if (aEvent) {
     mEventIsInternal = false;
   }
   else {
     mEventIsInternal = true;
@@ -68,52 +73,52 @@ nsDOMUIEvent::nsDOMUIEvent(mozilla::dom:
     {
        nsCOMPtr<nsIDOMWindow> window = do_GetInterface(container);
        if (window)
           mView = do_QueryInterface(window);
     }
   }
 }
 
-//static
-already_AddRefed<nsDOMUIEvent>
-nsDOMUIEvent::Constructor(const mozilla::dom::GlobalObject& aGlobal,
-                          const nsAString& aType,
-                          const mozilla::dom::UIEventInit& aParam,
-                          mozilla::ErrorResult& aRv)
+// static
+already_AddRefed<UIEvent>
+UIEvent::Constructor(const GlobalObject& aGlobal,
+                     const nsAString& aType,
+                     const UIEventInit& aParam,
+                     ErrorResult& aRv)
 {
-  nsCOMPtr<mozilla::dom::EventTarget> t = do_QueryInterface(aGlobal.GetAsSupports());
-  nsRefPtr<nsDOMUIEvent> e = new nsDOMUIEvent(t, nullptr, nullptr);
+  nsCOMPtr<EventTarget> t = do_QueryInterface(aGlobal.GetAsSupports());
+  nsRefPtr<UIEvent> e = new UIEvent(t, nullptr, nullptr);
   bool trusted = e->Init(t);
   aRv = e->InitUIEvent(aType, aParam.mBubbles, aParam.mCancelable, aParam.mView,
                        aParam.mDetail);
   e->SetTrusted(trusted);
   return e.forget();
 }
 
-NS_IMPL_CYCLE_COLLECTION_INHERITED_1(nsDOMUIEvent, nsDOMEvent,
+NS_IMPL_CYCLE_COLLECTION_INHERITED_1(UIEvent, nsDOMEvent,
                                      mView)
 
-NS_IMPL_ADDREF_INHERITED(nsDOMUIEvent, nsDOMEvent)
-NS_IMPL_RELEASE_INHERITED(nsDOMUIEvent, nsDOMEvent)
+NS_IMPL_ADDREF_INHERITED(UIEvent, nsDOMEvent)
+NS_IMPL_RELEASE_INHERITED(UIEvent, nsDOMEvent)
 
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMUIEvent)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(UIEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMUIEvent)
 NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent)
 
 static nsIntPoint
 DevPixelsToCSSPixels(const LayoutDeviceIntPoint& aPoint,
                      nsPresContext* aContext)
 {
   return nsIntPoint(aContext->DevPixelsToIntCSSPixels(aPoint.x),
                     aContext->DevPixelsToIntCSSPixels(aPoint.y));
 }
 
 nsIntPoint
-nsDOMUIEvent::GetMovementPoint()
+UIEvent::GetMovementPoint()
 {
   if (mPrivateDataDuplicated) {
     return mMovementPoint;
   }
 
   if (!mEvent ||
       (mEvent->eventStructType != NS_MOUSE_EVENT &&
        mEvent->eventStructType != NS_MOUSE_SCROLL_EVENT &&
@@ -127,103 +132,102 @@ nsDOMUIEvent::GetMovementPoint()
 
   // Calculate the delta between the last screen point and the current one.
   nsIntPoint current = DevPixelsToCSSPixels(mEvent->refPoint, mPresContext);
   nsIntPoint last = DevPixelsToCSSPixels(mEvent->lastRefPoint, mPresContext);
   return current - last;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetView(nsIDOMWindow** aView)
+UIEvent::GetView(nsIDOMWindow** aView)
 {
   *aView = mView;
   NS_IF_ADDREF(*aView);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetDetail(int32_t* aDetail)
+UIEvent::GetDetail(int32_t* aDetail)
 {
   *aDetail = mDetail;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::InitUIEvent(const nsAString& typeArg,
-                          bool canBubbleArg,
-                          bool cancelableArg,
-                          nsIDOMWindow* viewArg,
-                          int32_t detailArg)
+UIEvent::InitUIEvent(const nsAString& typeArg,
+                     bool canBubbleArg,
+                     bool cancelableArg,
+                     nsIDOMWindow* viewArg,
+                     int32_t detailArg)
 {
   if (viewArg) {
     nsCOMPtr<nsPIDOMWindow> view = do_QueryInterface(viewArg);
     NS_ENSURE_TRUE(view, NS_ERROR_INVALID_ARG);
   }
   nsresult rv = nsDOMEvent::InitEvent(typeArg, canBubbleArg, cancelableArg);
   NS_ENSURE_SUCCESS(rv, rv);
   
   mDetail = detailArg;
   mView = viewArg;
 
   return NS_OK;
 }
 
-// ---- nsDOMNSUIEvent implementation -------------------
 NS_IMETHODIMP
-nsDOMUIEvent::GetPageX(int32_t* aPageX)
+UIEvent::GetPageX(int32_t* aPageX)
 {
   NS_ENSURE_ARG_POINTER(aPageX);
   *aPageX = PageX();
   return NS_OK;
 }
 
 int32_t
-nsDOMUIEvent::PageX() const
+UIEvent::PageX() const
 {
   if (mPrivateDataDuplicated) {
     return mPagePoint.x;
   }
 
   return nsDOMEvent::GetPageCoords(mPresContext,
                                    mEvent,
                                    mEvent->refPoint,
                                    mClientPoint).x;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetPageY(int32_t* aPageY)
+UIEvent::GetPageY(int32_t* aPageY)
 {
   NS_ENSURE_ARG_POINTER(aPageY);
   *aPageY = PageY();
   return NS_OK;
 }
 
 int32_t
-nsDOMUIEvent::PageY() const
+UIEvent::PageY() const
 {
   if (mPrivateDataDuplicated) {
     return mPagePoint.y;
   }
 
   return nsDOMEvent::GetPageCoords(mPresContext,
                                    mEvent,
                                    mEvent->refPoint,
                                    mClientPoint).y;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetWhich(uint32_t* aWhich)
+UIEvent::GetWhich(uint32_t* aWhich)
 {
   NS_ENSURE_ARG_POINTER(aWhich);
   *aWhich = Which();
   return NS_OK;
 }
 
 already_AddRefed<nsINode>
-nsDOMUIEvent::GetRangeParent()
+UIEvent::GetRangeParent()
 {
   nsIFrame* targetFrame = nullptr;
 
   if (mPresContext) {
     targetFrame = mPresContext->EventStateManager()->GetEventTarget();
   }
 
   if (targetFrame) {
@@ -238,69 +242,69 @@ nsDOMUIEvent::GetRangeParent()
       return parent.forget();
     }
   }
 
   return nullptr;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetRangeParent(nsIDOMNode** aRangeParent)
+UIEvent::GetRangeParent(nsIDOMNode** aRangeParent)
 {
   NS_ENSURE_ARG_POINTER(aRangeParent);
   *aRangeParent = nullptr;
   nsCOMPtr<nsINode> n = GetRangeParent();
   if (n) {
     CallQueryInterface(n, aRangeParent);
   }
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetRangeOffset(int32_t* aRangeOffset)
+UIEvent::GetRangeOffset(int32_t* aRangeOffset)
 {
   NS_ENSURE_ARG_POINTER(aRangeOffset);
   *aRangeOffset = RangeOffset();
   return NS_OK;
 }
 
 int32_t
-nsDOMUIEvent::RangeOffset() const
+UIEvent::RangeOffset() const
 {
   if (!mPresContext) {
     return 0;
   }
 
   nsIFrame* targetFrame = mPresContext->EventStateManager()->GetEventTarget();
   if (!targetFrame) {
     return 0;
   }
 
   nsPoint pt = nsLayoutUtils::GetEventCoordinatesRelativeTo(mEvent,
                                                             targetFrame);
   return targetFrame->GetContentOffsetsFromPoint(pt).offset;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetCancelBubble(bool* aCancelBubble)
+UIEvent::GetCancelBubble(bool* aCancelBubble)
 {
   NS_ENSURE_ARG_POINTER(aCancelBubble);
   *aCancelBubble = CancelBubble();
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::SetCancelBubble(bool aCancelBubble)
+UIEvent::SetCancelBubble(bool aCancelBubble)
 {
   mEvent->mFlags.mPropagationStopped = aCancelBubble;
   return NS_OK;
 }
 
 nsIntPoint
-nsDOMUIEvent::GetLayerPoint() const
+UIEvent::GetLayerPoint() const
 {
   if (!mEvent ||
       (mEvent->eventStructType != NS_MOUSE_EVENT &&
        mEvent->eventStructType != NS_MOUSE_SCROLL_EVENT &&
        mEvent->eventStructType != NS_WHEEL_EVENT &&
        mEvent->eventStructType != NS_POINTER_EVENT &&
        mEvent->eventStructType != NS_TOUCH_EVENT &&
        mEvent->eventStructType != NS_DRAG_EVENT &&
@@ -315,51 +319,51 @@ nsDOMUIEvent::GetLayerPoint() const
     return mLayerPoint;
   nsIFrame* layer = nsLayoutUtils::GetClosestLayer(targetFrame);
   nsPoint pt(nsLayoutUtils::GetEventCoordinatesRelativeTo(mEvent, layer));
   return nsIntPoint(nsPresContext::AppUnitsToIntCSSPixels(pt.x),
                     nsPresContext::AppUnitsToIntCSSPixels(pt.y));
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetLayerX(int32_t* aLayerX)
+UIEvent::GetLayerX(int32_t* aLayerX)
 {
   NS_ENSURE_ARG_POINTER(aLayerX);
   *aLayerX = GetLayerPoint().x;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetLayerY(int32_t* aLayerY)
+UIEvent::GetLayerY(int32_t* aLayerY)
 {
   NS_ENSURE_ARG_POINTER(aLayerY);
   *aLayerY = GetLayerPoint().y;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::GetIsChar(bool* aIsChar)
+UIEvent::GetIsChar(bool* aIsChar)
 {
   *aIsChar = IsChar();
   return NS_OK;
 }
 
 bool
-nsDOMUIEvent::IsChar() const
+UIEvent::IsChar() const
 {
   WidgetKeyboardEvent* keyEvent = mEvent->AsKeyboardEvent();
   if (keyEvent) {
     return keyEvent->isChar;
   }
   WidgetTextEvent* textEvent = mEvent->AsTextEvent();
   return textEvent ? textEvent->isChar : false;
 }
 
 NS_IMETHODIMP
-nsDOMUIEvent::DuplicatePrivateData()
+UIEvent::DuplicatePrivateData()
 {
   mClientPoint = nsDOMEvent::GetClientCoords(mPresContext,
                                              mEvent,
                                              mEvent->refPoint,
                                              mClientPoint);
   mMovementPoint = GetMovementPoint();
   mLayerPoint = GetLayerPoint();
   mPagePoint = nsDOMEvent::GetPageCoords(mPresContext,
@@ -373,95 +377,95 @@ nsDOMUIEvent::DuplicatePrivateData()
   nsresult rv = nsDOMEvent::DuplicatePrivateData();
   if (NS_SUCCEEDED(rv)) {
     mEvent->refPoint = LayoutDeviceIntPoint::FromUntyped(screenPoint);
   }
   return rv;
 }
 
 NS_IMETHODIMP_(void)
-nsDOMUIEvent::Serialize(IPC::Message* aMsg, bool aSerializeInterfaceType)
+UIEvent::Serialize(IPC::Message* aMsg, bool aSerializeInterfaceType)
 {
   if (aSerializeInterfaceType) {
     IPC::WriteParam(aMsg, NS_LITERAL_STRING("uievent"));
   }
 
   nsDOMEvent::Serialize(aMsg, false);
 
   int32_t detail = 0;
   GetDetail(&detail);
   IPC::WriteParam(aMsg, detail);
 }
 
 NS_IMETHODIMP_(bool)
-nsDOMUIEvent::Deserialize(const IPC::Message* aMsg, void** aIter)
+UIEvent::Deserialize(const IPC::Message* aMsg, void** aIter)
 {
   NS_ENSURE_TRUE(nsDOMEvent::Deserialize(aMsg, aIter), false);
   NS_ENSURE_TRUE(IPC::ReadParam(aMsg, aIter, &mDetail), false);
   return true;
 }
 
 // XXX Following struct and array are used only in
-//     nsDOMUIEvent::ComputeModifierState(), but if we define them in it,
+//     UIEvent::ComputeModifierState(), but if we define them in it,
 //     we fail to build on Mac at calling mozilla::ArrayLength().
-struct nsModifierPair
+struct ModifierPair
 {
-  mozilla::Modifier modifier;
+  Modifier modifier;
   const char* name;
 };
-static const nsModifierPair kPairs[] = {
+static const ModifierPair kPairs[] = {
   { MODIFIER_ALT,        NS_DOM_KEYNAME_ALT },
   { MODIFIER_ALTGRAPH,   NS_DOM_KEYNAME_ALTGRAPH },
   { MODIFIER_CAPSLOCK,   NS_DOM_KEYNAME_CAPSLOCK },
   { MODIFIER_CONTROL,    NS_DOM_KEYNAME_CONTROL },
   { MODIFIER_FN,         NS_DOM_KEYNAME_FN },
   { MODIFIER_META,       NS_DOM_KEYNAME_META },
   { MODIFIER_NUMLOCK,    NS_DOM_KEYNAME_NUMLOCK },
   { MODIFIER_SCROLLLOCK, NS_DOM_KEYNAME_SCROLLLOCK },
   { MODIFIER_SHIFT,      NS_DOM_KEYNAME_SHIFT },
   { MODIFIER_SYMBOLLOCK, NS_DOM_KEYNAME_SYMBOLLOCK },
   { MODIFIER_OS,         NS_DOM_KEYNAME_OS }
 };
 
-/* static */
-mozilla::Modifiers
-nsDOMUIEvent::ComputeModifierState(const nsAString& aModifiersList)
+// static
+Modifiers
+UIEvent::ComputeModifierState(const nsAString& aModifiersList)
 {
   if (aModifiersList.IsEmpty()) {
     return 0;
   }
 
   // Be careful about the performance.  If aModifiersList is too long,
   // parsing it needs too long time.
   // XXX Should we abort if aModifiersList is too long?
 
   Modifiers modifiers = 0;
 
   nsAString::const_iterator listStart, listEnd;
   aModifiersList.BeginReading(listStart);
   aModifiersList.EndReading(listEnd);
 
-  for (uint32_t i = 0; i < mozilla::ArrayLength(kPairs); i++) {
+  for (uint32_t i = 0; i < ArrayLength(kPairs); i++) {
     nsAString::const_iterator start(listStart), end(listEnd);
     if (!FindInReadable(NS_ConvertASCIItoUTF16(kPairs[i].name), start, end)) {
       continue;
     }
 
     if ((start != listStart && !NS_IsAsciiWhitespace(*(--start))) ||
         (end != listEnd && !NS_IsAsciiWhitespace(*(end)))) {
       continue;
     }
     modifiers |= kPairs[i].modifier;
   }
 
   return modifiers;
 }
 
 bool
-nsDOMUIEvent::GetModifierStateInternal(const nsAString& aKey)
+UIEvent::GetModifierStateInternal(const nsAString& aKey)
 {
   WidgetInputEvent* inputEvent = mEvent->AsInputEvent();
   MOZ_ASSERT(inputEvent, "mEvent must be WidgetInputEvent or derived class");
   if (aKey.EqualsLiteral(NS_DOM_KEYNAME_SHIFT)) {
     return inputEvent->IsShift();
   }
   if (aKey.EqualsLiteral(NS_DOM_KEYNAME_CONTROL)) {
     return inputEvent->IsControl();
@@ -494,17 +498,23 @@ nsDOMUIEvent::GetModifierStateInternal(c
     return inputEvent->IsScrollLocked();
   }
   if (aKey.EqualsLiteral(NS_DOM_KEYNAME_SYMBOLLOCK)) {
     return inputEvent->IsSymbolLocked();
   }
   return false;
 }
 
+} // namespace dom
+} // namespace mozilla
 
-nsresult NS_NewDOMUIEvent(nsIDOMEvent** aInstancePtrResult,
-                          mozilla::dom::EventTarget* aOwner,
-                          nsPresContext* aPresContext,
-                          WidgetGUIEvent* aEvent) 
+using namespace mozilla;
+using namespace mozilla::dom;
+
+nsresult
+NS_NewDOMUIEvent(nsIDOMEvent** aInstancePtrResult,
+                 EventTarget* aOwner,
+                 nsPresContext* aPresContext,
+                 WidgetGUIEvent* aEvent) 
 {
-  nsDOMUIEvent* it = new nsDOMUIEvent(aOwner, aPresContext, aEvent);
+  UIEvent* it = new UIEvent(aOwner, aPresContext, aEvent);
   return CallQueryInterface(it, aInstancePtrResult);
 }
rename from dom/events/nsDOMUIEvent.h
rename to dom/events/UIEvent.h
--- a/dom/events/nsDOMUIEvent.h
+++ b/dom/events/UIEvent.h
@@ -1,75 +1,77 @@
 /* -*- Mode: C++; 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/. */
 
-#ifndef nsDOMUIEvent_h
-#define nsDOMUIEvent_h
+#ifndef mozilla_dom_UIEvent_h_
+#define mozilla_dom_UIEvent_h_
 
 #include "mozilla/Attributes.h"
 #include "nsIDOMUIEvent.h"
 #include "nsDOMEvent.h"
 #include "nsLayoutUtils.h"
 #include "mozilla/dom/UIEventBinding.h"
 #include "nsPresContext.h"
 #include "nsDeviceContext.h"
 
 class nsINode;
 
-class nsDOMUIEvent : public nsDOMEvent,
-                     public nsIDOMUIEvent
+namespace mozilla {
+namespace dom {
+
+class UIEvent : public nsDOMEvent,
+                public nsIDOMUIEvent
 {
-  typedef mozilla::CSSIntPoint CSSIntPoint;
 public:
-  nsDOMUIEvent(mozilla::dom::EventTarget* aOwner,
-               nsPresContext* aPresContext,
-               mozilla::WidgetGUIEvent* aEvent);
+  UIEvent(EventTarget* aOwner,
+          nsPresContext* aPresContext,
+          WidgetGUIEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMUIEvent, nsDOMEvent)
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(UIEvent, nsDOMEvent)
 
   // nsIDOMUIEvent Interface
   NS_DECL_NSIDOMUIEVENT
-  
+
   // Forward to nsDOMEvent
   NS_FORWARD_TO_NSDOMEVENT_NO_SERIALIZATION_NO_DUPLICATION
   NS_IMETHOD DuplicatePrivateData() MOZ_OVERRIDE;
   NS_IMETHOD_(void) Serialize(IPC::Message* aMsg, bool aSerializeInterfaceType) MOZ_OVERRIDE;
   NS_IMETHOD_(bool) Deserialize(const IPC::Message* aMsg, void** aIter) MOZ_OVERRIDE;
 
-  static nsIntPoint
-  CalculateScreenPoint(nsPresContext* aPresContext,
-                       mozilla::WidgetEvent* aEvent)
+  static nsIntPoint CalculateScreenPoint(nsPresContext* aPresContext,
+                                         WidgetEvent* aEvent)
   {
     if (!aEvent ||
         (aEvent->eventStructType != NS_MOUSE_EVENT &&
          aEvent->eventStructType != NS_MOUSE_SCROLL_EVENT &&
          aEvent->eventStructType != NS_WHEEL_EVENT &&
          aEvent->eventStructType != NS_DRAG_EVENT &&
          aEvent->eventStructType != NS_POINTER_EVENT &&
          aEvent->eventStructType != NS_SIMPLE_GESTURE_EVENT)) {
       return nsIntPoint(0, 0);
     }
 
-    mozilla::WidgetGUIEvent* event = aEvent->AsGUIEvent();
+    WidgetGUIEvent* event = aEvent->AsGUIEvent();
     if (!event->widget) {
-      return mozilla::LayoutDeviceIntPoint::ToUntyped(aEvent->refPoint);
+      return LayoutDeviceIntPoint::ToUntyped(aEvent->refPoint);
     }
 
-    mozilla::LayoutDeviceIntPoint offset = aEvent->refPoint +
-      mozilla::LayoutDeviceIntPoint::FromUntyped(event->widget->WidgetToScreenOffset());
-    nscoord factor = aPresContext->DeviceContext()->UnscaledAppUnitsPerDevPixel();
+    LayoutDeviceIntPoint offset = aEvent->refPoint +
+      LayoutDeviceIntPoint::FromUntyped(event->widget->WidgetToScreenOffset());
+    nscoord factor =
+      aPresContext->DeviceContext()->UnscaledAppUnitsPerDevPixel();
     return nsIntPoint(nsPresContext::AppUnitsToIntCSSPixels(offset.x * factor),
                       nsPresContext::AppUnitsToIntCSSPixels(offset.y * factor));
   }
 
   static CSSIntPoint CalculateClientPoint(nsPresContext* aPresContext,
-                                          mozilla::WidgetEvent* aEvent,
+                                          WidgetEvent* aEvent,
                                           CSSIntPoint* aDefaultClientPoint)
   {
     if (!aEvent ||
         (aEvent->eventStructType != NS_MOUSE_EVENT &&
          aEvent->eventStructType != NS_MOUSE_SCROLL_EVENT &&
          aEvent->eventStructType != NS_WHEEL_EVENT &&
          aEvent->eventStructType != NS_DRAG_EVENT &&
          aEvent->eventStructType != NS_POINTER_EVENT &&
@@ -90,25 +92,25 @@ public:
       return CSSIntPoint(0, 0);
     }
     nsPoint pt =
       nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent, rootFrame);
 
     return CSSIntPoint::FromAppUnitsRounded(pt);
   }
 
-  static already_AddRefed<nsDOMUIEvent> Constructor(const mozilla::dom::GlobalObject& aGlobal,
-                                                    const nsAString& aType,
-                                                    const mozilla::dom::UIEventInit& aParam,
-                                                    mozilla::ErrorResult& aRv);
+  static already_AddRefed<UIEvent> Constructor(const GlobalObject& aGlobal,
+                                               const nsAString& aType,
+                                               const UIEventInit& aParam,
+                                               ErrorResult& aRv);
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
-    return mozilla::dom::UIEventBinding::Wrap(aCx, aScope, this);
+    return UIEventBinding::Wrap(aCx, aScope, this);
   }
 
   nsIDOMWindow* GetView() const
   {
     return mView;
   }
 
   int32_t Detail() const
@@ -159,32 +161,34 @@ protected:
   CSSIntPoint mClientPoint;
   // Screenpoint is mEvent->refPoint.
   nsIntPoint mLayerPoint;
   CSSIntPoint mPagePoint;
   nsIntPoint mMovementPoint;
   bool mIsPointerLocked;
   CSSIntPoint mLastClientPoint;
 
-  typedef mozilla::Modifiers Modifiers;
   static Modifiers ComputeModifierState(const nsAString& aModifiersList);
   bool GetModifierStateInternal(const nsAString& aKey);
 };
 
-#define NS_FORWARD_TO_NSDOMUIEVENT                          \
-  NS_FORWARD_NSIDOMUIEVENT(nsDOMUIEvent::)                  \
+} // namespace dom
+} // namespace mozilla
+
+#define NS_FORWARD_TO_UIEVENT                               \
+  NS_FORWARD_NSIDOMUIEVENT(UIEvent::)                       \
   NS_FORWARD_TO_NSDOMEVENT_NO_SERIALIZATION_NO_DUPLICATION  \
   NS_IMETHOD DuplicatePrivateData()                         \
   {                                                         \
-    return nsDOMUIEvent::DuplicatePrivateData();            \
+    return UIEvent::DuplicatePrivateData();                 \
   }                                                         \
   NS_IMETHOD_(void) Serialize(IPC::Message* aMsg,           \
                               bool aSerializeInterfaceType) \
   {                                                         \
-    nsDOMUIEvent::Serialize(aMsg, aSerializeInterfaceType); \
+    UIEvent::Serialize(aMsg, aSerializeInterfaceType);      \
   }                                                         \
   NS_IMETHOD_(bool) Deserialize(const IPC::Message* aMsg,   \
                                 void** aIter)               \
   {                                                         \
-    return nsDOMUIEvent::Deserialize(aMsg, aIter);          \
+    return UIEvent::Deserialize(aMsg, aIter);               \
   }
 
-#endif // nsDOMUIEvent_h
+#endif // mozilla_dom_UIEvent_h_
rename from dom/events/nsDOMXULCommandEvent.cpp
rename to dom/events/XULCommandEvent.cpp
--- a/dom/events/nsDOMXULCommandEvent.cpp
+++ b/dom/events/XULCommandEvent.cpp
@@ -1,130 +1,139 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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 "nsDOMXULCommandEvent.h"
+#include "mozilla/dom/XULCommandEvent.h"
 #include "prtime.h"
 
-using namespace mozilla;
+namespace mozilla {
+namespace dom {
 
-nsDOMXULCommandEvent::nsDOMXULCommandEvent(mozilla::dom::EventTarget* aOwner,
-                                           nsPresContext* aPresContext,
-                                           WidgetInputEvent* aEvent)
-  : nsDOMUIEvent(aOwner, aPresContext,
-                 aEvent ? aEvent : new WidgetInputEvent(false, 0, nullptr))
+XULCommandEvent::XULCommandEvent(EventTarget* aOwner,
+                                 nsPresContext* aPresContext,
+                                 WidgetInputEvent* aEvent)
+  : UIEvent(aOwner, aPresContext,
+            aEvent ? aEvent : new WidgetInputEvent(false, 0, nullptr))
 {
   if (aEvent) {
     mEventIsInternal = false;
   }
   else {
     mEventIsInternal = true;
     mEvent->time = PR_Now();
   }
 }
 
-NS_IMPL_ADDREF_INHERITED(nsDOMXULCommandEvent, nsDOMUIEvent)
-NS_IMPL_RELEASE_INHERITED(nsDOMXULCommandEvent, nsDOMUIEvent)
+NS_IMPL_ADDREF_INHERITED(XULCommandEvent, UIEvent)
+NS_IMPL_RELEASE_INHERITED(XULCommandEvent, UIEvent)
 
-NS_IMPL_CYCLE_COLLECTION_INHERITED_1(nsDOMXULCommandEvent, nsDOMUIEvent,
+NS_IMPL_CYCLE_COLLECTION_INHERITED_1(XULCommandEvent, UIEvent,
                                      mSourceEvent)
 
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMXULCommandEvent)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(XULCommandEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMXULCommandEvent)
-NS_INTERFACE_MAP_END_INHERITING(nsDOMUIEvent)
+NS_INTERFACE_MAP_END_INHERITING(UIEvent)
 
 bool
-nsDOMXULCommandEvent::AltKey()
+XULCommandEvent::AltKey()
 {
   return mEvent->AsInputEvent()->IsAlt();
 }
 
 NS_IMETHODIMP
-nsDOMXULCommandEvent::GetAltKey(bool* aIsDown)
+XULCommandEvent::GetAltKey(bool* aIsDown)
 {
   NS_ENSURE_ARG_POINTER(aIsDown);
   *aIsDown = AltKey();
   return NS_OK;
 }
 
 bool
-nsDOMXULCommandEvent::CtrlKey()
+XULCommandEvent::CtrlKey()
 {
   return mEvent->AsInputEvent()->IsControl();
 }
 
 NS_IMETHODIMP
-nsDOMXULCommandEvent::GetCtrlKey(bool* aIsDown)
+XULCommandEvent::GetCtrlKey(bool* aIsDown)
 {
   NS_ENSURE_ARG_POINTER(aIsDown);
   *aIsDown = CtrlKey();
   return NS_OK;
 }
 
 bool
-nsDOMXULCommandEvent::ShiftKey()
+XULCommandEvent::ShiftKey()
 {
   return mEvent->AsInputEvent()->IsShift();
 }
 
 NS_IMETHODIMP
-nsDOMXULCommandEvent::GetShiftKey(bool* aIsDown)
+XULCommandEvent::GetShiftKey(bool* aIsDown)
 {
   NS_ENSURE_ARG_POINTER(aIsDown);
   *aIsDown = ShiftKey();
   return NS_OK;
 }
 
 bool
-nsDOMXULCommandEvent::MetaKey()
+XULCommandEvent::MetaKey()
 {
   return mEvent->AsInputEvent()->IsMeta();
 }
 
 NS_IMETHODIMP
-nsDOMXULCommandEvent::GetMetaKey(bool* aIsDown)
+XULCommandEvent::GetMetaKey(bool* aIsDown)
 {
   NS_ENSURE_ARG_POINTER(aIsDown);
   *aIsDown = MetaKey();
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMXULCommandEvent::GetSourceEvent(nsIDOMEvent** aSourceEvent)
+XULCommandEvent::GetSourceEvent(nsIDOMEvent** aSourceEvent)
 {
   NS_ENSURE_ARG_POINTER(aSourceEvent);
   *aSourceEvent = GetSourceEvent().get();
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMXULCommandEvent::InitCommandEvent(const nsAString& aType,
-                                       bool aCanBubble, bool aCancelable,
-                                       nsIDOMWindow* aView,
-                                       int32_t aDetail,
-                                       bool aCtrlKey, bool aAltKey,
-                                       bool aShiftKey, bool aMetaKey,
-                                       nsIDOMEvent* aSourceEvent)
+XULCommandEvent::InitCommandEvent(const nsAString& aType,
+                                  bool aCanBubble,
+                                  bool aCancelable,
+                                  nsIDOMWindow* aView,
+                                  int32_t aDetail,
+                                  bool aCtrlKey,
+                                  bool aAltKey,
+                                  bool aShiftKey,
+                                  bool aMetaKey,
+                                  nsIDOMEvent* aSourceEvent)
 {
-  nsresult rv = nsDOMUIEvent::InitUIEvent(aType, aCanBubble, aCancelable,
-                                          aView, aDetail);
+  nsresult rv = UIEvent::InitUIEvent(aType, aCanBubble, aCancelable,
+                                     aView, aDetail);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mEvent->AsInputEvent()->InitBasicModifiers(aCtrlKey, aAltKey,
                                              aShiftKey, aMetaKey);
   mSourceEvent = aSourceEvent;
 
   return NS_OK;
 }
 
+} // namespace dom
+} // namespace mozilla
 
-nsresult NS_NewDOMXULCommandEvent(nsIDOMEvent** aInstancePtrResult,
-                                  mozilla::dom::EventTarget* aOwner,
-                                  nsPresContext* aPresContext,
-                                  WidgetInputEvent* aEvent) 
+using namespace mozilla;
+using namespace mozilla::dom;
+
+nsresult
+NS_NewDOMXULCommandEvent(nsIDOMEvent** aInstancePtrResult,
+                         EventTarget* aOwner,
+                         nsPresContext* aPresContext,
+                         WidgetInputEvent* aEvent) 
 {
-  nsDOMXULCommandEvent* it =
-    new nsDOMXULCommandEvent(aOwner, aPresContext, aEvent);
+  XULCommandEvent* it = new XULCommandEvent(aOwner, aPresContext, aEvent);
   return CallQueryInterface(it, aInstancePtrResult);
 }
rename from dom/events/nsDOMXULCommandEvent.h
rename to dom/events/XULCommandEvent.h
--- a/dom/events/nsDOMXULCommandEvent.h
+++ b/dom/events/XULCommandEvent.h
@@ -1,42 +1,45 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim:set ts=2 sw=2 sts=2 et cindent: */
 /* 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/. */
 
 // This class implements a XUL "command" event.  See nsIDOMXULCommandEvent.idl
 
-#ifndef nsDOMXULCommandEvent_h_
-#define nsDOMXULCommandEvent_h_
+#ifndef mozilla_dom_XULCommandEvent_h_
+#define mozilla_dom_XULCommandEvent_h_
 
-#include "nsDOMUIEvent.h"
+#include "mozilla/dom/UIEvent.h"
+#include "mozilla/dom/XULCommandEventBinding.h"
 #include "nsIDOMXULCommandEvent.h"
-#include "mozilla/dom/XULCommandEventBinding.h"
 
-class nsDOMXULCommandEvent : public nsDOMUIEvent,
-                             public nsIDOMXULCommandEvent
+namespace mozilla {
+namespace dom {
+
+class XULCommandEvent : public UIEvent,
+                        public nsIDOMXULCommandEvent
 {
 public:
-  nsDOMXULCommandEvent(mozilla::dom::EventTarget* aOwner,
-                       nsPresContext* aPresContext,
-                       mozilla::WidgetInputEvent* aEvent);
+  XULCommandEvent(EventTarget* aOwner,
+                  nsPresContext* aPresContext,
+                  WidgetInputEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMXULCommandEvent, nsDOMUIEvent)
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(XULCommandEvent, UIEvent)
   NS_DECL_NSIDOMXULCOMMANDEVENT
 
   // Forward our inherited virtual methods to the base class
-  NS_FORWARD_TO_NSDOMUIEVENT
+  NS_FORWARD_TO_UIEVENT
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
-    return mozilla::dom::XULCommandEventBinding::Wrap(aCx, aScope, this);
+    return XULCommandEventBinding::Wrap(aCx, aScope, this);
   }
 
   bool AltKey();
   bool CtrlKey();
   bool ShiftKey();
   bool MetaKey();
 
   already_AddRefed<nsDOMEvent> GetSourceEvent()
@@ -48,20 +51,23 @@ public:
 
   void InitCommandEvent(const nsAString& aType,
                         bool aCanBubble, bool aCancelable,
                         nsIDOMWindow* aView,
                         int32_t aDetail,
                         bool aCtrlKey, bool aAltKey,
                         bool aShiftKey, bool aMetaKey,
                         nsDOMEvent* aSourceEvent,
-                        mozilla::ErrorResult& aRv)
+                        ErrorResult& aRv)
   {
     aRv = InitCommandEvent(aType, aCanBubble, aCancelable, aView, aDetail,
                            aCtrlKey, aAltKey, aShiftKey, aMetaKey,
                            aSourceEvent);
   }
 
 protected:
   nsCOMPtr<nsIDOMEvent> mSourceEvent;
 };
 
-#endif  // nsDOMXULCommandEvent_h_
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_XULCommandEvent_h_
--- a/dom/events/moz.build
+++ b/dom/events/moz.build
@@ -13,18 +13,16 @@ XPIDL_SOURCES += [
 
 XPIDL_MODULE = 'content_events'
 
 EXPORTS += [
     'nsAsyncDOMEvent.h',
     'nsDOMEvent.h',
     'nsDOMEventTargetHelper.h',
     'nsDOMKeyNameList.h',
-    'nsDOMTouchEvent.h',
-    'nsDOMUIEvent.h',
     'nsEventDispatcher.h',
     'nsEventListenerManager.h',
     'nsEventNameList.h',
     'nsEventStateManager.h',
     'nsEventStates.h',
     'nsIJSEventListener.h',
     'nsIPrivateTextEvent.h',
     'nsIPrivateTextRange.h',
@@ -47,20 +45,27 @@ EXPORTS.mozilla.dom += [
     'DragEvent.h',
     'EventTarget.h',
     'FocusEvent.h',
     'KeyboardEvent.h',
     'MessageEvent.h',
     'MouseEvent.h',
     'MouseScrollEvent.h',
     'MutationEvent.h',
+    'NotifyAudioAvailableEvent.h',
+    'NotifyPaintEvent.h',
     'PointerEvent.h',
+    'ScrollAreaEvent.h',
     'SimpleGestureEvent.h',
     'Touch.h',
+    'TouchEvent.h',
+    'TransitionEvent.h',
+    'UIEvent.h',
     'WheelEvent.h',
+    'XULCommandEvent.h',
 ]
 
 if CONFIG['MOZ_WEBSPEECH']:
     EXPORTS.mozilla.dom += ['SpeechRecognitionError.h']
 
 UNIFIED_SOURCES += [
     'AnimationEvent.cpp',
     'BeforeUnloadEvent.cpp',
@@ -73,56 +78,56 @@ UNIFIED_SOURCES += [
     'DragEvent.cpp',
     'EventTarget.cpp',
     'FocusEvent.cpp',
     'KeyboardEvent.cpp',
     'MessageEvent.cpp',
     'MouseEvent.cpp',
     'MouseScrollEvent.cpp',
     'MutationEvent.cpp',
+    'NotifyAudioAvailableEvent.cpp',
     'nsAsyncDOMEvent.cpp',
     'nsContentEventHandler.cpp',
     'nsDOMEventTargetHelper.cpp',
-    'nsDOMNotifyAudioAvailableEvent.cpp',
     'nsDOMTextEvent.cpp',
-    'nsDOMTouchEvent.cpp',
-    'nsDOMTransitionEvent.cpp',
-    'nsDOMXULCommandEvent.cpp',
     'nsEventDispatcher.cpp',
     'nsEventListenerService.cpp',
     'nsIMEStateManager.cpp',
     'nsJSEventListener.cpp',
     'nsPaintRequest.cpp',
     'nsPrivateTextRange.cpp',
     'PointerEvent.cpp',
     'SimpleGestureEvent.cpp',
     'TextComposition.cpp',
     'Touch.cpp',
+    'TouchEvent.cpp',
+    'TransitionEvent.cpp',
     'WheelEvent.cpp',
+    'XULCommandEvent.cpp',
 ]
 
 SOURCES += [
     # nsDOMEvent.cpp should be built separately because it includes
     # ipc/IPCMessageUtils.h, which on Windows includes windows.h.
-    'nsDOMEvent.cpp',
+    'NotifyPaintEvent.cpp',
     # nsDOMEvent.cpp should be built separately because it includes
     # ipc/IPCMessageUtils.h, which on Windows includes windows.h.
-    'nsDOMNotifyPaintEvent.cpp',
-    # nsDOMEvent.cpp should be built separately because it includes
-    # ipc/IPCMessageUtils.h, which on Windows includes windows.h.
-    'nsDOMScrollAreaEvent.cpp',
-    # nsDOMEvent.cpp should be built separately because it includes
-    # ipc/IPCMessageUtils.h, which on Windows includes windows.h.
-    'nsDOMUIEvent.cpp',
+    'nsDOMEvent.cpp',
     # nsDOMEvent.cpp should be built separately because it includes
     # mozilla/HalSensor.h, which includes ipc/IPCMessageUtils.h, which
     # on Windows includes windows.h.
     'nsEventListenerManager.cpp',
     # nsEventStateManager.cpp should be built separately because of Mac OS X headers.
     'nsEventStateManager.cpp',
+    # nsDOMEvent.cpp should be built separately because it includes
+    # ipc/IPCMessageUtils.h, which on Windows includes windows.h.
+    'ScrollAreaEvent.cpp',
+    # nsDOMEvent.cpp should be built separately because it includes
+    # ipc/IPCMessageUtils.h, which on Windows includes windows.h.
+    'UIEvent.cpp',
 ]
 
 if CONFIG['MOZ_WEBSPEECH']:
     UNIFIED_SOURCES += ['SpeechRecognitionError.cpp']
 
 FAIL_ON_WARNINGS = True
 
 MSVC_ENABLE_PGO = True
--- a/dom/events/nsDOMTextEvent.cpp
+++ b/dom/events/nsDOMTextEvent.cpp
@@ -5,22 +5,23 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMTextEvent.h"
 #include "nsPrivateTextRange.h"
 #include "prtime.h"
 #include "mozilla/TextEvents.h"
 
 using namespace mozilla;
+using namespace mozilla::dom;
 
 nsDOMTextEvent::nsDOMTextEvent(mozilla::dom::EventTarget* aOwner,
                                nsPresContext* aPresContext,
                                WidgetTextEvent* aEvent)
-  : nsDOMUIEvent(aOwner, aPresContext,
-                 aEvent ? aEvent : new WidgetTextEvent(false, 0, nullptr))
+  : UIEvent(aOwner, aPresContext,
+            aEvent ? aEvent : new WidgetTextEvent(false, 0, nullptr))
 {
   NS_ASSERTION(mEvent->eventStructType == NS_TEXT_EVENT, "event type mismatch");
 
   if (aEvent) {
     mEventIsInternal = false;
   }
   else {
     mEventIsInternal = true;
@@ -48,22 +49,22 @@ nsDOMTextEvent::nsDOMTextEvent(mozilla::
 
       if (tempPrivateTextRange) {
         mTextRange->AppendTextRange(tempPrivateTextRange);
       }
     }
   }
 }
 
-NS_IMPL_ADDREF_INHERITED(nsDOMTextEvent, nsDOMUIEvent)
-NS_IMPL_RELEASE_INHERITED(nsDOMTextEvent, nsDOMUIEvent)
+NS_IMPL_ADDREF_INHERITED(nsDOMTextEvent, UIEvent)
+NS_IMPL_RELEASE_INHERITED(nsDOMTextEvent, UIEvent)
 
 NS_INTERFACE_MAP_BEGIN(nsDOMTextEvent)
   NS_INTERFACE_MAP_ENTRY(nsIPrivateTextEvent)
-NS_INTERFACE_MAP_END_INHERITING(nsDOMUIEvent)
+NS_INTERFACE_MAP_END_INHERITING(UIEvent)
 
 NS_METHOD nsDOMTextEvent::GetText(nsString& aText)
 {
   aText = mText;
   return NS_OK;
 }
 
 NS_METHOD_(already_AddRefed<nsIPrivateTextRangeList>) nsDOMTextEvent::GetInputRange()
--- a/dom/events/nsDOMTextEvent.h
+++ b/dom/events/nsDOMTextEvent.h
@@ -1,34 +1,36 @@
 /* -*- Mode: C++; 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/. */
 
 #ifndef nsDOMTextEvent_h__
 #define nsDOMTextEvent_h__
 
+#include "mozilla/dom/UIEvent.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/EventForwards.h"
-#include "nsDOMUIEvent.h"
 #include "nsIPrivateTextEvent.h"
 #include "nsPrivateTextRange.h"
 
-class nsDOMTextEvent : public nsDOMUIEvent,
+class nsDOMTextEvent : public mozilla::dom::UIEvent,
                        public nsIPrivateTextEvent
 {
+  typedef mozilla::dom::UIEvent UIEvent;
+
 public:
   nsDOMTextEvent(mozilla::dom::EventTarget* aOwner,
                  nsPresContext* aPresContext,
                  mozilla::WidgetTextEvent* aEvent);
 
   NS_DECL_ISUPPORTS_INHERITED
 
   // Forward to base class
-  NS_FORWARD_TO_NSDOMUIEVENT
+  NS_FORWARD_TO_UIEVENT
 
   // nsIPrivateTextEvent interface
   NS_IMETHOD GetText(nsString& aText) MOZ_OVERRIDE;
   NS_IMETHOD_(already_AddRefed<nsIPrivateTextRangeList>) GetInputRange() MOZ_OVERRIDE;
   
 protected:
   nsString mText;
   nsRefPtr<nsPrivateTextRangeList> mTextRange;
--- a/dom/events/nsEventDispatcher.cpp
+++ b/dom/events/nsEventDispatcher.cpp
@@ -9,21 +9,21 @@
 #include "nsEventListenerManager.h"
 #include "nsContentUtils.h"
 #include "nsError.h"
 #include <new>
 #include "nsIContent.h"
 #include "nsIDocument.h"
 #include "nsINode.h"
 #include "nsPIDOMWindow.h"
-#include "nsDOMTouchEvent.h"
 #include "GeckoProfiler.h"
 #include "GeneratedEvents.h"
 #include "mozilla/ContentEvents.h"
 #include "mozilla/dom/EventTarget.h"
+#include "mozilla/dom/TouchEvent.h"
 #include "mozilla/InternalMutationEvent.h"
 #include "mozilla/MiscEvents.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/TextEvents.h"
 #include "mozilla/TouchEvents.h"
 #include "mozilla/unused.h"
 
 using namespace mozilla;
@@ -813,17 +813,17 @@ nsEventDispatcher::CreateEvent(mozilla::
     return NS_NewDOMScrollAreaEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("popstateevent"))
     return NS_NewDOMPopStateEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("mozaudioavailableevent"))
     return NS_NewDOMAudioAvailableEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("closeevent"))
     return NS_NewDOMCloseEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("touchevent") &&
-      nsDOMTouchEvent::PrefEnabled())
+      TouchEvent::PrefEnabled())
     return NS_NewDOMTouchEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("hashchangeevent"))
     return NS_NewDOMHashChangeEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("customevent"))
     return NS_NewDOMCustomEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("mozsmsevent"))
     return NS_NewDOMMozSmsEvent(aDOMEvent, aOwner, aPresContext, nullptr);
   if (aEventType.LowerCaseEqualsLiteral("mozmmsevent"))
--- a/dom/events/nsEventStateManager.cpp
+++ b/dom/events/nsEventStateManager.cpp
@@ -6,16 +6,17 @@
 
 #include "mozilla/Attributes.h"
 #include "mozilla/MiscEvents.h"
 #include "mozilla/MathAlgorithms.h"
 #include "mozilla/MouseEvents.h"
 #include "mozilla/TextEvents.h"
 #include "mozilla/TouchEvents.h"
 #include "mozilla/dom/TabParent.h"
+#include "mozilla/dom/UIEvent.h"
 
 #include "nsCOMPtr.h"
 #include "nsEventStateManager.h"
 #include "nsFocusManager.h"
 #include "nsIMEStateManager.h"
 #include "nsContentEventHandler.h"
 #include "nsIContent.h"
 #include "nsINodeInfo.h"
@@ -45,17 +46,16 @@
 #include "nsIDOMXULElement.h"
 #include "nsIDOMKeyEvent.h"
 #include "nsIObserverService.h"
 #include "nsIDocShell.h"
 #include "nsIMarkupDocumentViewer.h"
 #include "nsIDOMWheelEvent.h"
 #include "nsIDOMDragEvent.h"
 #include "nsIDOMUIEvent.h"
-#include "nsDOMUIEvent.h"
 #include "nsIMozBrowserFrame.h"
 
 #include "nsSubDocumentFrame.h"
 #include "nsLayoutUtils.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsContentUtils.h"
 
@@ -1025,19 +1025,19 @@ nsEventStateManager::PreHandleEvent(nsPr
   // Store last known screenPoint and clientPoint so pointer lock
   // can use these values as constants.
   WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent();
   if (aEvent->mFlags.mIsTrusted &&
       ((mouseEvent && IsMouseEventReal(mouseEvent)) ||
        aEvent->eventStructType == NS_WHEEL_EVENT) &&
       !sIsPointerLocked) {
     sLastScreenPoint =
-      nsDOMUIEvent::CalculateScreenPoint(aPresContext, aEvent);
+      UIEvent::CalculateScreenPoint(aPresContext, aEvent);
     sLastClientPoint =
-      nsDOMUIEvent::CalculateClientPoint(aPresContext, aEvent, nullptr);
+      UIEvent::CalculateClientPoint(aPresContext, aEvent, nullptr);
   }
 
   // Do not take account NS_MOUSE_ENTER/EXIT so that loading a page
   // when user is not active doesn't change the state to active.
   if (aEvent->mFlags.mIsTrusted &&
       ((mouseEvent && IsMouseEventReal(mouseEvent) &&
         mouseEvent->message != NS_MOUSE_ENTER &&
         mouseEvent->message != NS_MOUSE_EXIT) ||
@@ -2332,19 +2332,19 @@ nsEventStateManager::DoDefaultDragStart(
     aDataTransfer->GetMozItemCount(&count);
   if (!count)
     return false;
 
   // Get the target being dragged, which may not be the same as the
   // target of the mouse event. If one wasn't set in the
   // aDataTransfer during the event handler, just use the original
   // target instead.
-  nsCOMPtr<Element> dragTarget = aDataTransfer->GetDragTarget();
+  nsCOMPtr<nsIContent> dragTarget = aDataTransfer->GetDragTarget();
   if (!dragTarget) {
-    dragTarget = do_QueryInterface(aDragTarget);
+    dragTarget = aDragTarget;
     if (!dragTarget)
       return false;
   }
 
   // check which drag effect should initially be used. If the effect was not
   // set, just use all actions, otherwise Windows won't allow a drop.
   uint32_t action;
   aDataTransfer->GetEffectAllowedInt(&action);
@@ -4327,17 +4327,17 @@ nsEventStateManager::NotifyMouseOver(Wid
 
   // Turn recursion protection back off
   wrapper->mFirstOverEventElement = nullptr;
 }
 
 // Returns the center point of the window's inner content area.
 // This is in widget coordinates, i.e. relative to the widget's top
 // left corner, not in screen coordinates, the same units that
-// nsDOMUIEvent::refPoint is in.
+// UIEvent::refPoint is in.
 //
 // XXX Hack alert: XXX
 // However, we do the computation in integer CSS pixels, NOT device pix,
 // in order to fudge around the one-pixel error in innerHeight in fullscreen
 // mode (see bug 799523 comment 35, and bug 729011). Using integer CSS pix
 // makes us throw away the fractional error that results, rather than having
 // it manifest as a potential one-device-pix discrepancy.
 static LayoutDeviceIntPoint
@@ -4381,17 +4381,17 @@ nsEventStateManager::GenerateMouseEnterE
 
   // Hold onto old target content through the event and reset after.
   nsCOMPtr<nsIContent> targetBeforeEvent = mCurrentTargetContent;
 
   switch(aMouseEvent->message) {
   case NS_MOUSE_MOVE:
     {
       // Mouse movement is reported on the MouseEvent.movement{X,Y} fields.
-      // Movement is calculated in nsDOMUIEvent::GetMovementPoint() as:
+      // Movement is calculated in UIEvent::GetMovementPoint() as:
       //   previous_mousemove_refPoint - current_mousemove_refPoint.
       if (sIsPointerLocked && aMouseEvent->widget) {
         // The pointer is locked. If the pointer is not located at the center of
         // the window, dispatch a synthetic mousemove to return the pointer there.
         // Doing this between "real" pointer moves gives the impression that the
         // (locked) pointer can continue moving and won't stop at the screen
         // boundary. We cancel the synthetic event so that we don't end up
         // dispatching the centering move event to content.
--- a/dom/events/test/test_bug822898.html
+++ b/dom/events/test/test_bug822898.html
@@ -193,16 +193,17 @@ function testOnPointerProperty()
 {
   iframeBody.onpointerdown = function (e) { gOnPointerPropHandled["pointerdown"] = true; }
   iframeBody.onpointerup = function (e) { gOnPointerPropHandled["pointerup"] = true; }
   iframeBody.onpointermove = function (e) { gOnPointerPropHandled["pointermove"] = true; }
   iframeBody.onpointerout = function (e) { gOnPointerPropHandled["pointerout"] = true; }
   iframeBody.onpointerover = function (e) { gOnPointerPropHandled["pointerover"] = true; }
   iframeBody.onpointerenter = function (e) { gOnPointerPropHandled["pointerenter"] = true; }
   iframeBody.onpointerleave = function (e) { gOnPointerPropHandled["pointerleave"] = true; }
+  iframeBody.onpointercancel = function (e) { gOnPointerPropHandled["pointercancel"] = true; }
 
   iframeBody.dispatchEvent(getDefaultArgEvent("pointerdown"));
   is(gOnPointerPropHandled['pointerdown'], true, "pointerdown property is performed");
 
   iframeBody.dispatchEvent(getDefaultArgEvent("pointerup"));
   is(gOnPointerPropHandled['pointerup'], true, "pointerup property is performed");
 
   iframeBody.dispatchEvent(getDefaultArgEvent("pointermove"));
@@ -215,16 +216,19 @@ function testOnPointerProperty()
   is(gOnPointerPropHandled['pointerover'], true, "pointerover property is performed");
 
   iframeBody.dispatchEvent(getDefaultArgEvent("pointerenter"));
   is(gOnPointerPropHandled['pointerenter'], true, "pointerenter property is performed");
 
   iframeBody.dispatchEvent(getDefaultArgEvent("pointerleave"));
   is(gOnPointerPropHandled['pointerleave'], true, "pointerleave property is performed");
 
+  iframeBody.dispatchEvent(getDefaultArgEvent("pointercancel"));
+  is(gOnPointerPropHandled['pointercancel'], true, "pointercancel property is performed");
+
   nextTest();
 }
 
 function testPointerEventCTORS()
 {
   // TODO: This should go to test_eventctors.html, when PointerEvents enabled by default
   var receivedEvent;
   iframeBody.addEventListener("hello", function(e) { receivedEvent = e; }, true);
--- a/dom/events/test/test_bug967796.html
+++ b/dom/events/test/test_bug967796.html
@@ -161,34 +161,34 @@ function runTests() {
 function penter(evt) {
   ++pointerentercount;
   evt.stopPropagation();
   if (expectedPointerEnterTargets.length) {
     var t = expectedPointerEnterTargets.shift();
     is(evt.target.id, t, "Wrong event target!");
   }
   is(evt.bubbles, false, evt.type + " should not bubble!");
-  is(evt.cancelable, true, evt.type + " is cancelable!");
+  is(evt.cancelable, false, evt.type + " is cancelable!");
   is(evt.target, evt.currentTarget, "Wrong event target!");
   ok(!evt.relatedTarget || evt.target.ownerDocument == evt.relatedTarget.ownerDocument,
      "Leaking nodes to another document?");
   if (checkRelatedTarget && evt.target.ownerDocument == document) {
     is(evt.relatedTarget, expectedRelatedEnter, "Wrong related target (pointerenter)");
   }
 }
 
 function pleave(evt) {
   ++pointerleavecount;
   evt.stopPropagation();
   if (expectedPointerLeaveTargets.length) {
     var t = expectedPointerLeaveTargets.shift();
     is(evt.target.id, t, "Wrong event target!");
   }
   is(evt.bubbles, false, evt.type + " should not bubble!");
-  is(evt.cancelable, true, evt.type + " is cancelable!");
+  is(evt.cancelable, false, evt.type + " is cancelable!");
   is(evt.target, evt.currentTarget, "Wrong event target!");
   ok(!evt.relatedTarget || evt.target.ownerDocument == evt.relatedTarget.ownerDocument,
      "Leaking nodes to another document?");
   if (checkRelatedTarget && evt.target.ownerDocument == document) {
     is(evt.relatedTarget, expectedRelatedLeave, "Wrong related target (pointerleave)");
   }
 }
 
--- a/dom/interfaces/base/nsIDOMScreen.idl
+++ b/dom/interfaces/base/nsIDOMScreen.idl
@@ -1,16 +1,16 @@
 /* -*- 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 "nsIDOMEventTarget.idl"
 
-[scriptable, builtinclass, uuid(bcdf4ce4-9785-4e31-a851-1d51ea16da20)]
+[scriptable, builtinclass, uuid(e732649a-4f78-4ded-abe1-dbdc36fd59d3)]
 interface nsIDOMScreen : nsIDOMEventTarget
 {
   readonly attribute long             top;
   readonly attribute long             left;
   readonly attribute long             width;
   readonly attribute long             height;
   readonly attribute long             pixelDepth;
   readonly attribute long             colorDepth;
@@ -21,41 +21,9 @@ interface nsIDOMScreen : nsIDOMEventTarg
 
   /**
    * Returns the current screen orientation.
    * Can be: landscape-primary, landscape-secondary,
    *         portrait-primary or portrait-secondary.
    */
   [binaryname(SlowMozOrientation)]
   readonly attribute DOMString       mozOrientation;
-
-  /**
-   * Lock the screen to the specified orientations(s).  This method returns true
-   * if the lock was acquired successfully, and false otherwise.
-   *
-   * The parameter can be a DOMString or an Array of DOMStrings.  If you pass a
-   * string, we lock the screen to that one orientation.  If you pass an Array,
-   * we ensure that the screen is always in one of the given orientations.
-   *
-   * Valid orientations are "portrait", "portrait-primary",
-   * "portrait-secondary", "landscape", "landscape-primary", and
-   * "landscape-secondary".
-   * These tokens are case-sensitive.
-   *
-   * If you pass a string that's not one of the valid orientations, or if you
-   * pass an array of orientations and any of the orientations in the array is
-   * not valid, we reject the lock and return false.
-   *
-   * The "-primary" orientations correspond to holding the device right-side up,
-   * while the "-secondary" orientations correspond to holding the device
-   * upside-down.	Locking the orientation in "portrait" is the same as locking
-   * the orientation in ['portrait-primary', 'portrait-secondary'], and the
-   * "landscape" orientation similarly corresponds to the set
-   * ['landscape-primary', 'landscape-secondary'].
-   */
-  [implicit_jscontext] boolean mozLockOrientation(in jsval orientation);
-
-  /**
-   * Unlock the screen orientation.
-   */
-  [binaryname(SlowMozUnlockOrientation)]
-  void mozUnlockOrientation();
 };
rename from dom/smil/nsDOMTimeEvent.cpp
rename to dom/smil/TimeEvent.cpp
--- a/dom/smil/nsDOMTimeEvent.cpp
+++ b/dom/smil/TimeEvent.cpp
@@ -1,23 +1,24 @@
 /* -*- Mode: C++; 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 "nsDOMTimeEvent.h"
+#include "mozilla/dom/TimeEvent.h"
+#include "mozilla/BasicEvents.h"
+#include "nsIInterfaceRequestorUtils.h"
 #include "nsPresContext.h"
-#include "nsIInterfaceRequestorUtils.h"
-#include "mozilla/BasicEvents.h"
 
-using namespace mozilla;
+namespace mozilla {
+namespace dom {
 
-nsDOMTimeEvent::nsDOMTimeEvent(mozilla::dom::EventTarget* aOwner,
-                               nsPresContext* aPresContext,
-                               WidgetEvent* aEvent)
+TimeEvent::TimeEvent(EventTarget* aOwner,
+                     nsPresContext* aPresContext,
+                     WidgetEvent* aEvent)
   : nsDOMEvent(aOwner, aPresContext,
                aEvent ? aEvent : new InternalUIEvent(false, 0)),
     mDetail(0)
 {
   SetIsDOMBinding();
   if (aEvent) {
     mEventIsInternal = false;
   } else {
@@ -38,56 +39,63 @@ nsDOMTimeEvent::nsDOMTimeEvent(mozilla::
       nsCOMPtr<nsIDOMWindow> window = do_GetInterface(container);
       if (window) {
         mView = do_QueryInterface(window);
       }
     }
   }
 }
 
-NS_IMPL_CYCLE_COLLECTION_INHERITED_1(nsDOMTimeEvent, nsDOMEvent,
+NS_IMPL_CYCLE_COLLECTION_INHERITED_1(TimeEvent, nsDOMEvent,
                                      mView)
 
-NS_IMPL_ADDREF_INHERITED(nsDOMTimeEvent, nsDOMEvent)
-NS_IMPL_RELEASE_INHERITED(nsDOMTimeEvent, nsDOMEvent)
+NS_IMPL_ADDREF_INHERITED(TimeEvent, nsDOMEvent)
+NS_IMPL_RELEASE_INHERITED(TimeEvent, nsDOMEvent)
 
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsDOMTimeEvent)
+NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(TimeEvent)
   NS_INTERFACE_MAP_ENTRY(nsIDOMTimeEvent)
 NS_INTERFACE_MAP_END_INHERITING(nsDOMEvent)
 
 NS_IMETHODIMP
-nsDOMTimeEvent::GetView(nsIDOMWindow** aView)
+TimeEvent::GetView(nsIDOMWindow** aView)
 {
   *aView = mView;
   NS_IF_ADDREF(*aView);
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMTimeEvent::GetDetail(int32_t* aDetail)
+TimeEvent::GetDetail(int32_t* aDetail)
 {
   *aDetail = mDetail;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsDOMTimeEvent::InitTimeEvent(const nsAString& aTypeArg,
-                              nsIDOMWindow* aViewArg,
-                              int32_t aDetailArg)
+TimeEvent::InitTimeEvent(const nsAString& aTypeArg,
+                         nsIDOMWindow* aViewArg,
+                         int32_t aDetailArg)
 {
   nsresult rv = nsDOMEvent::InitEvent(aTypeArg, false /*doesn't bubble*/,
                                                 false /*can't cancel*/);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mDetail = aDetailArg;
   mView = aViewArg;
 
   return NS_OK;
 }
 
-nsresult NS_NewDOMTimeEvent(nsIDOMEvent** aInstancePtrResult,
-                            mozilla::dom::EventTarget* aOwner,
-                            nsPresContext* aPresContext,
-                            WidgetEvent* aEvent)
+} // namespace dom
+} // namespace mozilla
+
+using namespace mozilla;
+using namespace mozilla::dom;
+
+nsresult
+NS_NewDOMTimeEvent(nsIDOMEvent** aInstancePtrResult,
+                   EventTarget* aOwner,
+                   nsPresContext* aPresContext,
+                   WidgetEvent* aEvent)
 {
-  nsDOMTimeEvent* it = new nsDOMTimeEvent(aOwner, aPresContext, aEvent);
+  TimeEvent* it = new TimeEvent(aOwner, aPresContext, aEvent);
   return CallQueryInterface(it, aInstancePtrResult);
 }
rename from dom/smil/nsDOMTimeEvent.h
rename to dom/smil/TimeEvent.h
--- a/dom/smil/nsDOMTimeEvent.h
+++ b/dom/smil/TimeEvent.h
@@ -1,58 +1,64 @@
 /* -*- Mode: C++; 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/. */
 
-#ifndef NS_DOMTIMEEVENT_H_
-#define NS_DOMTIMEEVENT_H_
+#ifndef mozilla_dom_TimeEvent_h_
+#define mozilla_dom_TimeEvent_h_
 
 #include "nsIDOMTimeEvent.h"
 #include "nsDOMEvent.h"
 #include "mozilla/dom/TimeEventBinding.h"
 
-class nsDOMTimeEvent MOZ_FINAL : public nsDOMEvent,
-                                 public nsIDOMTimeEvent
+namespace mozilla {
+namespace dom {
+
+class TimeEvent MOZ_FINAL : public nsDOMEvent,
+                            public nsIDOMTimeEvent
 {
 public:
-  nsDOMTimeEvent(mozilla::dom::EventTarget* aOwner,
-                 nsPresContext* aPresContext,
-                 mozilla::WidgetEvent* aEvent);
+  TimeEvent(EventTarget* aOwner,
+            nsPresContext* aPresContext,
+            WidgetEvent* aEvent);
 
   // nsISupports interface:
   NS_DECL_ISUPPORTS_INHERITED
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsDOMTimeEvent, nsDOMEvent)
+  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(TimeEvent, nsDOMEvent)
 
   // nsIDOMTimeEvent interface:
   NS_DECL_NSIDOMTIMEEVENT
 
   // Forward to base class
   NS_FORWARD_TO_NSDOMEVENT
 
   virtual JSObject* WrapObject(JSContext* aCx,
                                JS::Handle<JSObject*> aScope) MOZ_OVERRIDE
   {
-    return mozilla::dom::TimeEventBinding::Wrap(aCx, aScope, this);
+    return TimeEventBinding::Wrap(aCx, aScope, this);
   }
 
   int32_t Detail() const
   {
     return mDetail;
   }
 
   nsIDOMWindow* GetView() const
   {
     return mView;
   }
 
   void InitTimeEvent(const nsAString& aType, nsIDOMWindow* aView,
-                     int32_t aDetail, mozilla::ErrorResult& aRv)
+                     int32_t aDetail, ErrorResult& aRv)
   {
     aRv = InitTimeEvent(aType, aView, aDetail);
   }
 
 private:
   nsCOMPtr<nsIDOMWindow> mView;
   int32_t mDetail;
 };
 
-#endif // NS_DOMTIMEEVENT_H_
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_TimeEvent_h_
--- a/dom/smil/moz.build
+++ b/dom/smil/moz.build
@@ -2,17 +2,16 @@
 # vim: set filetype=python:
 # 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/.
 
 TEST_TOOL_DIRS += ['test']
 
 EXPORTS += [
-    'nsDOMTimeEvent.h',
     'nsISMILAttr.h',
     'nsISMILType.h',
     'nsSMILAnimationController.h',
     'nsSMILAnimationFunction.h',
     'nsSMILCompositorTable.h',
     'nsSMILCSSProperty.h',
     'nsSMILInstanceTime.h',
     'nsSMILInterval.h',
@@ -27,18 +26,21 @@ EXPORTS += [
     'nsSMILTimedElement.h',
     'nsSMILTimeValue.h',
     'nsSMILTimeValueSpec.h',
     'nsSMILTimeValueSpecParams.h',
     'nsSMILTypes.h',
     'nsSMILValue.h',
 ]
 
+EXPORTS.mozilla.dom += [
+    'TimeEvent.h',
+]
+
 UNIFIED_SOURCES += [
-    'nsDOMTimeEvent.cpp',
     'nsSMILAnimationController.cpp',
     'nsSMILAnimationFunction.cpp',
     'nsSMILCompositor.cpp',
     'nsSMILCSSProperty.cpp',
     'nsSMILCSSValueType.cpp',
     'nsSMILFloatType.cpp',
     'nsSMILInstanceTime.cpp',
     'nsSMILInterval.cpp',
@@ -52,16 +54,17 @@ UNIFIED_SOURCES += [
     'nsSMILTimedElement.cpp',
     'nsSMILTimeValue.cpp',
     'nsSMILTimeValueSpec.cpp',
     'nsSMILValue.cpp',
     'SMILBoolType.cpp',
     'SMILEnumType.cpp',
     'SMILIntegerType.cpp',
     'SMILStringType.cpp',
+    'TimeEvent.cpp',
 ]
 
 FAIL_ON_WARNINGS = True
 
 LOCAL_INCLUDES += [
     '/content/base/src',
     '/content/svg/content/src',
     '/dom/events',
--- a/dom/webidl/EventHandler.webidl
+++ b/dom/webidl/EventHandler.webidl
@@ -85,16 +85,18 @@ interface GlobalEventHandlers {
            attribute EventHandler onsubmit;
            attribute EventHandler onsuspend;
            attribute EventHandler ontimeupdate;
            attribute EventHandler onvolumechange;
            attribute EventHandler onwaiting;
 
            // Pointer events handlers
            [Pref="dom.w3c_pointer_events.enabled"]
+           attribute EventHandler onpointercancel;
+           [Pref="dom.w3c_pointer_events.enabled"]
            attribute EventHandler onpointerdown;
            [Pref="dom.w3c_pointer_events.enabled"]
            attribute EventHandler onpointerup;
            [Pref="dom.w3c_pointer_events.enabled"]
            attribute EventHandler onpointermove;
            [Pref="dom.w3c_pointer_events.enabled"]
            attribute EventHandler onpointerout;
            [Pref="dom.w3c_pointer_events.enabled"]
--- a/dom/webidl/TouchEvent.webidl
+++ b/dom/webidl/TouchEvent.webidl
@@ -1,17 +1,17 @@
 /* -*- 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/.
  */
 
 interface WindowProxy;
 
-[Func="nsDOMTouchEvent::PrefEnabled"]
+[Func="mozilla::dom::TouchEvent::PrefEnabled"]
 interface TouchEvent : UIEvent {
   readonly attribute TouchList touches;
   readonly attribute TouchList targetTouches;
   readonly attribute TouchList changedTouches;
 
   readonly attribute boolean altKey;
   readonly attribute boolean metaKey;
   readonly attribute boolean ctrlKey;
--- a/dom/webidl/TouchList.webidl
+++ b/dom/webidl/TouchList.webidl
@@ -5,17 +5,17 @@
  *
  * The origin of this IDL file is
  * https://dvcs.w3.org/hg/webevents/raw-file/v1/touchevents.html
  *
  * Copyright © 2012 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C
  * liability, trademark and document use rules apply.
  */
 
-[Func="nsDOMTouchList::PrefEnabled"]
+[Func="mozilla::dom::TouchList::PrefEnabled"]
 interface TouchList {
   [Pure]
   readonly attribute unsigned long length;
   getter Touch? item(unsigned long index);
 };
 
 /* Mozilla extension. */
 partial interface TouchList {
--- a/dom/workers/RuntimeService.cpp
+++ b/dom/workers/RuntimeService.cpp
@@ -143,17 +143,17 @@ static_assert(MAX_WORKERS_PER_DOMAIN >= 
 #endif
 
 #define PREF_WORKERS_LATEST_JS_VERSION "dom.workers.latestJSVersion"
 
 namespace {
 
 const uint32_t kNoIndex = uint32_t(-1);
 
-const JS::ContextOptions kRequiredJSContextOptions =
+const JS::ContextOptions kRequiredContextOptions =
   JS::ContextOptions().setDontReportUncaught(true)
                       .setNoScriptRval(true);
 
 uint32_t gMaxWorkersPerDomain = MAX_WORKERS_PER_DOMAIN;
 
 // Does not hold an owning reference.
 RuntimeService* gRuntimeService = nullptr;
 
@@ -295,17 +295,17 @@ GenerateSharedWorkerKey(const nsACString
     }
   }
 
   aKey.Append('|');
   aKey.Append(aScriptSpec);
 }
 
 void
-LoadJSContextOptions(const char* aPrefName, void* /* aClosure */)
+LoadRuntimeAndContextOptions(const char* aPrefName, void* /* aClosure */)
 {
   AssertIsOnMainThread();
 
   RuntimeService* rts = RuntimeService::GetService();
   if (!rts && !gRuntimeServiceDuringInit) {
     // May be shutting down, just bail.
     return;
   }
@@ -325,61 +325,57 @@ LoadJSContextOptions(const char* aPrefNa
 
 #ifdef JS_GC_ZEAL
   if (prefName.EqualsLiteral(PREF_JS_OPTIONS_PREFIX PREF_GCZEAL) ||
       prefName.EqualsLiteral(PREF_WORKERS_OPTIONS_PREFIX PREF_GCZEAL)) {
     return;
   }
 #endif
 
+  // Runtime options.
+  JS::RuntimeOptions runtimeOptions;
+  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("asmjs"))) {
+    runtimeOptions.setAsmJS(true);
+  }
+  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("typeinference"))) {
+    runtimeOptions.setTypeInference(true);
+  }
+  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("baselinejit"))) {
+    runtimeOptions.setBaseline(true);
+  }
+  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("ion"))) {
+    runtimeOptions.setIon(true);
+  }
+
   // Common options.
-  JS::ContextOptions commonOptions = kRequiredJSContextOptions;
+  JS::ContextOptions commonContextOptions = kRequiredContextOptions;
   if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("strict"))) {
-    commonOptions.setExtraWarnings(true);
+    commonContextOptions.setExtraWarnings(true);
   }
   if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("werror"))) {
-    commonOptions.setWerror(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("asmjs"))) {
-    commonOptions.setAsmJS(true);
+    commonContextOptions.setWerror(true);
   }
 
   // Content options.
-  JS::ContextOptions contentOptions = commonOptions;
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("baselinejit.content"))) {
-    contentOptions.setBaseline(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("ion.content"))) {
-    contentOptions.setIon(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("typeinference.content"))) {
-    contentOptions.setTypeInference(true);
-  }
+  JS::ContextOptions contentContextOptions = commonContextOptions;
 
   // Chrome options.
-  JS::ContextOptions chromeOptions = commonOptions;
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("baselinejit.chrome"))) {
-    chromeOptions.setBaseline(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("ion.chrome"))) {
-    chromeOptions.setIon(true);
-  }
-  if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("typeinference.chrome"))) {
-    chromeOptions.setTypeInference(true);
-  }
+  JS::ContextOptions chromeContextOptions = commonContextOptions;
 #ifdef DEBUG
   if (GetWorkerPref<bool>(NS_LITERAL_CSTRING("strict.debug"))) {
-    chromeOptions.setExtraWarnings(true);
+    chromeContextOptions.setExtraWarnings(true);
   }
 #endif
 
-  RuntimeService::SetDefaultJSContextOptions(contentOptions, chromeOptions);
+  RuntimeService::SetDefaultRuntimeAndContextOptions(runtimeOptions,
+                                                     contentContextOptions,
+                                                     chromeContextOptions);
 
   if (rts) {
-    rts->UpdateAllWorkerJSContextOptions();
+    rts->UpdateAllWorkerRuntimeAndContextOptions();
   }
 }
 
 #ifdef JS_GC_ZEAL
 void
 LoadGCZealOptions(const char* /* aPrefName */, void* /* aClosure */)
 {
   AssertIsOnMainThread();
@@ -766,16 +762,18 @@ JSContext*
 CreateJSContextForWorker(WorkerPrivate* aWorkerPrivate, JSRuntime* aRuntime)
 {
   aWorkerPrivate->AssertIsOnWorkerThread();
   NS_ASSERTION(!aWorkerPrivate->GetJSContext(), "Already has a context!");
 
   JSSettings settings;
   aWorkerPrivate->CopyJSSettings(settings);
 
+  JS::RuntimeOptionsRef(aRuntime) = settings.runtimeOptions;
+
   JSSettings::JSGCSettingsArray& gcSettings = settings.gcSettings;
 
   // This is the real place where we set the max memory for the runtime.
   for (uint32_t index = 0; index < ArrayLength(gcSettings); index++) {
     const JSSettings::JSGCSetting& setting = gcSettings[index];
     if (setting.IsSet()) {
       NS_ASSERTION(setting.value, "Can't handle 0 values!");
       JS_SetGCParameter(aRuntime, setting.key, setting.value);
@@ -1609,20 +1607,21 @@ nsresult
 RuntimeService::Init()
 {
   AssertIsOnMainThread();
 
   nsLayoutStatics::AddRef();
 
   // Initialize JSSettings.
   if (!sDefaultJSSettings.gcSettings[0].IsSet()) {
-    sDefaultJSSettings.chrome.contextOptions = kRequiredJSContextOptions;
+    sDefaultJSSettings.runtimeOptions = JS::RuntimeOptions();
+    sDefaultJSSettings.chrome.contextOptions = kRequiredContextOptions;
     sDefaultJSSettings.chrome.maxScriptRuntime = -1;
     sDefaultJSSettings.chrome.compartmentOptions.setVersion(JSVERSION_LATEST);
-    sDefaultJSSettings.content.contextOptions = kRequiredJSContextOptions;
+    sDefaultJSSettings.content.contextOptions = kRequiredContextOptions;
     sDefaultJSSettings.content.maxScriptRuntime = MAX_SCRIPT_RUN_TIME_SEC;
 #ifdef JS_GC_ZEAL
     sDefaultJSSettings.gcZealFrequency = JS_DEFAULT_ZEAL_FREQ;
     sDefaultJSSettings.gcZeal = 0;
 #endif
     SetDefaultJSGCSettings(JSGC_MAX_BYTES, WORKER_DEFAULT_RUNTIME_HEAPSIZE);
     SetDefaultJSGCSettings(JSGC_ALLOCATION_THRESHOLD,
                            WORKER_DEFAULT_ALLOCATION_THRESHOLD);
@@ -1687,23 +1686,23 @@ RuntimeService::Init()
                                         nullptr)) ||
 #endif
 #if DUMP_CONTROLLED_BY_PREF
       NS_FAILED(Preferences::RegisterCallbackAndCall(
                                   WorkerPrefChanged,
                                   PREF_DOM_WINDOW_DUMP_ENABLED,
                                   reinterpret_cast<void *>(WORKERPREF_DUMP))) ||
 #endif
-      NS_FAILED(Preferences::RegisterCallback(LoadJSContextOptions,
+      NS_FAILED(Preferences::RegisterCallback(LoadRuntimeAndContextOptions,
                                               PREF_JS_OPTIONS_PREFIX,
                                               nullptr)) ||
       NS_FAILED(Preferences::RegisterCallbackAndCall(
-                                                    LoadJSContextOptions,
-                                                    PREF_WORKERS_OPTIONS_PREFIX,
-                                                    nullptr)) ||
+                                                   LoadRuntimeAndContextOptions,
+                                                   PREF_WORKERS_OPTIONS_PREFIX,
+                                                   nullptr)) ||
       NS_FAILED(Preferences::RegisterCallbackAndCall(
                                                  JSVersionChanged,
                                                  PREF_WORKERS_LATEST_JS_VERSION,
                                                  nullptr))) {
     NS_WARNING("Failed to register pref callbacks!");
   }
 
   NS_ASSERTION(gRuntimeServiceDuringInit == this, "Should be 'this'!");
@@ -1840,20 +1839,20 @@ RuntimeService::Cleanup()
   }
 
   NS_ASSERTION(!mWindowMap.Count(), "All windows should have been released!");
 
   if (mObserved) {
     if (NS_FAILED(Preferences::UnregisterCallback(JSVersionChanged,
                                                   PREF_WORKERS_LATEST_JS_VERSION,
                                                   nullptr)) ||
-        NS_FAILED(Preferences::UnregisterCallback(LoadJSContextOptions,
+        NS_FAILED(Preferences::UnregisterCallback(LoadRuntimeAndContextOptions,
                                                   PREF_JS_OPTIONS_PREFIX,
                                                   nullptr)) ||
-        NS_FAILED(Preferences::UnregisterCallback(LoadJSContextOptions,
+        NS_FAILED(Preferences::UnregisterCallback(LoadRuntimeAndContextOptions,
                                                   PREF_WORKERS_OPTIONS_PREFIX,
                                                   nullptr)) ||
 #if DUMP_CONTROLLED_BY_PREF
         NS_FAILED(Preferences::UnregisterCallback(
                                   WorkerPrefChanged,
                                   PREF_DOM_WINDOW_DUMP_ENABLED,
                                   reinterpret_cast<void *>(WORKERPREF_DUMP))) ||
 #endif
@@ -2225,19 +2224,20 @@ RuntimeService::NoteIdleThread(WorkerThr
   // Schedule timer.
   MOZ_ALWAYS_TRUE(NS_SUCCEEDED(mIdleThreadTimer->InitWithFuncCallback(
                                                  ShutdownIdleThreads, nullptr,
                                                  IDLE_THREAD_TIMEOUT_SEC * 1000,
                                                  nsITimer::TYPE_ONE_SHOT)));
 }
 
 void
-RuntimeService::UpdateAllWorkerJSContextOptions()
+RuntimeService::UpdateAllWorkerRuntimeAndContextOptions()
 {
-  BROADCAST_ALL_WORKERS(UpdateJSContextOptions,
+  BROADCAST_ALL_WORKERS(UpdateRuntimeAndContextOptions,
+                        sDefaultJSSettings.runtimeOptions,
                         sDefaultJSSettings.content.contextOptions,
                         sDefaultJSSettings.chrome.contextOptions);
 }
 
 void
 RuntimeService::UpdateAllWorkerPreference(WorkerPreference aPref, bool aValue)
 {
   BROADCAST_ALL_WORKERS(UpdatePreference, aPref, aValue);
--- a/dom/workers/RuntimeService.h
+++ b/dom/workers/RuntimeService.h
@@ -169,26 +169,29 @@ public:
   static void
   GetDefaultPreferences(bool aPreferences[WORKERPREF_COUNT])
   {
     AssertIsOnMainThread();
     memcpy(aPreferences, sDefaultPreferences, WORKERPREF_COUNT * sizeof(bool));
   }
 
   static void
-  SetDefaultJSContextOptions(const JS::ContextOptions& aContentOptions,
-                             const JS::ContextOptions& aChromeOptions)
+  SetDefaultRuntimeAndContextOptions(
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions)
   {
     AssertIsOnMainThread();
-    sDefaultJSSettings.content.contextOptions = aContentOptions;
-    sDefaultJSSettings.chrome.contextOptions = aChromeOptions;
+    sDefaultJSSettings.runtimeOptions = aRuntimeOptions;
+    sDefaultJSSettings.content.contextOptions = aContentCxOptions;
+    sDefaultJSSettings.chrome.contextOptions = aChromeCxOptions;
   }
 
   void
-  UpdateAllWorkerJSContextOptions();
+  UpdateAllWorkerRuntimeAndContextOptions();
 
   void
   UpdateAllWorkerPreference(WorkerPreference aPref, bool aValue);
 
   static void
   SetDefaultJSGCSettings(JSGCParamKey aKey, uint32_t aValue)
   {
     AssertIsOnMainThread();
--- a/dom/workers/WorkerPrivate.cpp
+++ b/dom/workers/WorkerPrivate.cpp
@@ -1510,35 +1510,42 @@ private:
       mTimer->Cancel();
       mTimer = nullptr;
     }
 
     return true;
   }
 };
 
-class UpdateJSContextOptionsRunnable MOZ_FINAL : public WorkerControlRunnable
+class UpdateRuntimeAndContextOptionsRunnable MOZ_FINAL : public WorkerControlRunnable
 {
-  JS::ContextOptions mContentOptions;
-  JS::ContextOptions mChromeOptions;
+  JS::RuntimeOptions mRuntimeOptions;
+  JS::ContextOptions mContentCxOptions;
+  JS::ContextOptions mChromeCxOptions;
 
 public:
-  UpdateJSContextOptionsRunnable(WorkerPrivate* aWorkerPrivate,
-                                 const JS::ContextOptions& aContentOptions,
-                                 const JS::ContextOptions& aChromeOptions)
+  UpdateRuntimeAndContextOptionsRunnable(
+                                    WorkerPrivate* aWorkerPrivate,
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions)
   : WorkerControlRunnable(aWorkerPrivate, WorkerThreadUnchangedBusyCount),
-    mContentOptions(aContentOptions), mChromeOptions(aChromeOptions)
+    mRuntimeOptions(aRuntimeOptions),
+    mContentCxOptions(aContentCxOptions),
+    mChromeCxOptions(aChromeCxOptions)
   { }
 
 private:
   virtual bool
   WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) MOZ_OVERRIDE
   {
-    aWorkerPrivate->UpdateJSContextOptionsInternal(aCx, mContentOptions,
-                                                   mChromeOptions);
+    aWorkerPrivate->UpdateRuntimeAndContextOptionsInternal(aCx,
+                                                           mRuntimeOptions,
+                                                           mContentCxOptions,
+                                                           mChromeCxOptions);
     return true;
   }
 };
 
 class UpdatePreferenceRunnable MOZ_FINAL : public WorkerControlRunnable
 {
   WorkerPreference mPref;
   bool mValue;
@@ -2830,32 +2837,36 @@ WorkerPrivateParent<Derived>::GetInnerWi
   AssertIsOnMainThread();
   NS_ASSERTION(!mLoadInfo.mWindow || mLoadInfo.mWindow->IsInnerWindow(),
                "Outer window?");
   return mLoadInfo.mWindow ? mLoadInfo.mWindow->WindowID() : 0;
 }
 
 template <class Derived>
 void
-WorkerPrivateParent<Derived>::UpdateJSContextOptions(
-                                      JSContext* aCx,
-                                      const JS::ContextOptions& aContentOptions,
-                                      const JS::ContextOptions& aChromeOptions)
+WorkerPrivateParent<Derived>::UpdateRuntimeAndContextOptions(
+                                    JSContext* aCx,
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions)
 {
   AssertIsOnParentThread();
 
   {
     MutexAutoLock lock(mMutex);
-    mJSSettings.content.contextOptions = aContentOptions;
-    mJSSettings.chrome.contextOptions = aChromeOptions;
-  }
-
-  nsRefPtr<UpdateJSContextOptionsRunnable> runnable =
-    new UpdateJSContextOptionsRunnable(ParentAsWorkerPrivate(), aContentOptions,
-                                       aChromeOptions);
+    mJSSettings.runtimeOptions = aRuntimeOptions;
+    mJSSettings.content.contextOptions = aContentCxOptions;
+    mJSSettings.chrome.contextOptions = aChromeCxOptions;
+  }
+
+  nsRefPtr<UpdateRuntimeAndContextOptionsRunnable> runnable =
+    new UpdateRuntimeAndContextOptionsRunnable(ParentAsWorkerPrivate(),
+                                               aRuntimeOptions,
+                                               aContentCxOptions,
+                                               aChromeCxOptions);
   if (!runnable->Dispatch(aCx)) {
     NS_WARNING("Failed to update worker context options!");
     JS_ClearPendingException(aCx);
   }
 }
 
 template <class Derived>
 void
@@ -5483,27 +5494,31 @@ WorkerPrivate::RescheduleTimeoutTimer(JS
     JS_ReportError(aCx, "Failed to start timer!");
     return false;
   }
 
   return true;
 }
 
 void
-WorkerPrivate::UpdateJSContextOptionsInternal(JSContext* aCx,
-                                              const JS::ContextOptions& aContentOptions,
-                                              const JS::ContextOptions& aChromeOptions)
+WorkerPrivate::UpdateRuntimeAndContextOptionsInternal(
+                                    JSContext* aCx,
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions)
 {
   AssertIsOnWorkerThread();
 
-  JS::ContextOptionsRef(aCx) = IsChromeWorker() ? aChromeOptions : aContentOptions;
+  JS::RuntimeOptionsRef(aCx) = aRuntimeOptions;
+  JS::ContextOptionsRef(aCx) = IsChromeWorker() ? aChromeCxOptions : aContentCxOptions;
 
   for (uint32_t index = 0; index < mChildWorkers.Length(); index++) {
-    mChildWorkers[index]->UpdateJSContextOptions(aCx, aContentOptions,
-                                                 aChromeOptions);
+    mChildWorkers[index]->UpdateRuntimeAndContextOptions(aCx, aRuntimeOptions,
+                                                         aContentCxOptions,
+                                                         aChromeCxOptions);
   }
 }
 
 void
 WorkerPrivate::UpdatePreferenceInternal(JSContext* aCx, WorkerPreference aPref, bool aValue)
 {
   AssertIsOnWorkerThread();
   MOZ_ASSERT(aPref >= 0 && aPref < WORKERPREF_COUNT);
--- a/dom/workers/WorkerPrivate.h
+++ b/dom/workers/WorkerPrivate.h
@@ -384,18 +384,20 @@ public:
                                uint64_t aMessagePortSerial,
                                JSAutoStructuredCloneBuffer&& aBuffer,
                                nsTArray<nsCOMPtr<nsISupports>>& aClonedObjects);
 
   uint64_t
   GetInnerWindowId();
 
   void
-  UpdateJSContextOptions(JSContext* aCx, const JS::ContextOptions& aChromeOptions,
-                         const JS::ContextOptions& aContentOptions);
+  UpdateRuntimeAndContextOptions(JSContext* aCx,
+                                 const JS::RuntimeOptions& aRuntimeOptions,
+                                 const JS::ContextOptions& aContentCxOptions,
+                                 const JS::ContextOptions& aChromeCxOptions);
 
   void
   UpdatePreference(JSContext* aCx, WorkerPreference aPref, bool aValue);
 
   void
   UpdateJSWorkerMemoryParameter(JSContext* aCx, JSGCParamKey key,
                                 uint32_t value);
 
@@ -901,18 +903,21 @@ public:
   void
   CloseHandlerFinished()
   {
     AssertIsOnWorkerThread();
     mCloseHandlerFinished = true;
   }
 
   void
-  UpdateJSContextOptionsInternal(JSContext* aCx, const JS::ContextOptions& aContentOptions,
-                                 const JS::ContextOptions& aChromeOptions);
+  UpdateRuntimeAndContextOptionsInternal(
+                                    JSContext* aCx,
+                                    const JS::RuntimeOptions& aRuntimeOptions,
+                                    const JS::ContextOptions& aContentCxOptions,
+                                    const JS::ContextOptions& aChromeCxOptions);
 
   void
   UpdatePreferenceInternal(JSContext* aCx, WorkerPreference aPref, bool aValue);
 
   void
   UpdateJSWorkerMemoryParameterInternal(JSContext* aCx, JSGCParamKey key, uint32_t aValue);
 
   void
--- a/dom/workers/Workers.h
+++ b/dom/workers/Workers.h
@@ -102,16 +102,17 @@ struct JSSettings
     JSContentChromeSettings()
     : contextOptions(), compartmentOptions(), maxScriptRuntime(0)
     { }
   };
 
   JSContentChromeSettings chrome;
   JSContentChromeSettings content;
   JSGCSettingsArray gcSettings;
+  JS::RuntimeOptions runtimeOptions;
 
 #ifdef JS_GC_ZEAL
   uint8_t gcZeal;
   uint32_t gcZealFrequency;
 #endif
 
   JSSettings()
 #ifdef JS_GC_ZEAL
--- a/gfx/2d/DrawTargetD2D.cpp
+++ b/gfx/2d/DrawTargetD2D.cpp
@@ -1,13 +1,14 @@
 /* -*- 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 <initguid.h>
 #include "DrawTargetD2D.h"
 #include "SourceSurfaceD2D.h"
 #include "SourceSurfaceD2DTarget.h"
 #include "ShadersD2D.h"
 #include "PathD2D.h"
 #include "GradientStopsD2D.h"
 #include "ScaledFontDWrite.h"
 #include "ImageScaling.h"
--- a/js/jsd/jsd_xpc.cpp
+++ b/js/jsd/jsd_xpc.cpp
@@ -1650,39 +1650,31 @@ jsdContext::GetJSContext(JSContext **_rv
 
 #define JSOPTION_EXTRA_WARNINGS                 JS_BIT(0)
 #define JSOPTION_WERROR                         JS_BIT(1)
 #define JSOPTION_VAROBJFIX                      JS_BIT(2)
 #define JSOPTION_PRIVATE_IS_NSISUPPORTS         JS_BIT(3)
 #define JSOPTION_DONT_REPORT_UNCAUGHT           JS_BIT(8)
 #define JSOPTION_NO_DEFAULT_COMPARTMENT_OBJECT  JS_BIT(11)
 #define JSOPTION_NO_SCRIPT_RVAL                 JS_BIT(12)
-#define JSOPTION_BASELINE                       JS_BIT(14)
-#define JSOPTION_TYPE_INFERENCE                 JS_BIT(16)
 #define JSOPTION_STRICT_MODE                    JS_BIT(17)
-#define JSOPTION_ION                            JS_BIT(18)
-#define JSOPTION_ASMJS                          JS_BIT(19)
 #define JSOPTION_MASK                           JS_BITMASK(20)
 
 NS_IMETHODIMP
 jsdContext::GetOptions(uint32_t *_rval)
 {
     ASSERT_VALID_EPHEMERAL;
     *_rval = (JS::ContextOptionsRef(mJSCx).extraWarnings() ? JSOPTION_EXTRA_WARNINGS : 0)
            | (JS::ContextOptionsRef(mJSCx).werror() ? JSOPTION_WERROR : 0)
            | (JS::ContextOptionsRef(mJSCx).varObjFix() ? JSOPTION_VAROBJFIX : 0)
            | (JS::ContextOptionsRef(mJSCx).privateIsNSISupports() ? JSOPTION_PRIVATE_IS_NSISUPPORTS : 0)
            | (JS::ContextOptionsRef(mJSCx).dontReportUncaught() ? JSOPTION_DONT_REPORT_UNCAUGHT : 0)
            | (JS::ContextOptionsRef(mJSCx).noDefaultCompartmentObject() ? JSOPTION_NO_DEFAULT_COMPARTMENT_OBJECT : 0)
            | (JS::ContextOptionsRef(mJSCx).noScriptRval() ? JSOPTION_NO_SCRIPT_RVAL : 0)
-           | (JS::ContextOptionsRef(mJSCx).strictMode() ? JSOPTION_STRICT_MODE : 0)
-           | (JS::ContextOptionsRef(mJSCx).baseline() ? JSOPTION_BASELINE : 0)
-           | (JS::ContextOptionsRef(mJSCx).typeInference() ? JSOPTION_TYPE_INFERENCE : 0)
-           | (JS::ContextOptionsRef(mJSCx).ion() ? JSOPTION_ION : 0)
-           | (JS::ContextOptionsRef(mJSCx).asmJS() ? JSOPTION_ASMJS : 0);
+           | (JS::ContextOptionsRef(mJSCx).strictMode() ? JSOPTION_STRICT_MODE : 0);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 jsdContext::SetOptions(uint32_t options)
 {
     ASSERT_VALID_EPHEMERAL;
 
@@ -1693,21 +1685,17 @@ jsdContext::SetOptions(uint32_t options)
         return NS_ERROR_ILLEGAL_VALUE;
 
     JS::ContextOptionsRef(mJSCx).setExtraWarnings(options & JSOPTION_EXTRA_WARNINGS)
                                 .setWerror(options & JSOPTION_WERROR)
                                 .setVarObjFix(options & JSOPTION_VAROBJFIX)
                                 .setDontReportUncaught(options & JSOPTION_DONT_REPORT_UNCAUGHT)
                                 .setNoDefaultCompartmentObject(options & JSOPTION_NO_DEFAULT_COMPARTMENT_OBJECT)
                                 .setNoScriptRval(options & JSOPTION_NO_SCRIPT_RVAL)
-                                .setStrictMode(options & JSOPTION_STRICT_MODE)
-                                .setBaseline(options & JSOPTION_BASELINE)
-                                .setTypeInference(options & JSOPTION_TYPE_INFERENCE)
-                                .setIon(options & JSOPTION_ION)
-                                .setAsmJS(options & JSOPTION_ASMJS);
+                                .setStrictMode(options & JSOPTION_STRICT_MODE);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 jsdContext::GetPrivateData(nsISupports **_rval)
 {
     ASSERT_VALID_EPHEMERAL;
     if (JS::ContextOptionsRef(mJSCx).privateIsNSISupports()) 
--- a/js/src/builtin/TestingFunctions.cpp
+++ b/js/src/builtin/TestingFunctions.cpp
@@ -1155,35 +1155,35 @@ SetJitCompilerOption(JSContext *cx, unsi
         ReportUsageError(cx, callee, "First argument does not name a valid option (see jsapi.h).");
         return false;
     }
 
     int32_t number = args[1].toInt32();
     if (number < 0)
         number = -1;
 
-    JS_SetGlobalJitCompilerOption(cx, opt, uint32_t(number));
+    JS_SetGlobalJitCompilerOption(cx->runtime(), opt, uint32_t(number));
 
     args.rval().setUndefined();
     return true;
 }
 
 static bool
 GetJitCompilerOptions(JSContext *cx, unsigned argc, jsval *vp)
 {
     RootedObject info(cx, JS_NewObject(cx, nullptr, JS::NullPtr(), JS::NullPtr()));
     if (!info)
         return false;
 
     RootedValue value(cx);
 
-#define JIT_COMPILER_MATCH(key, string)                         \
-    opt = JSJITCOMPILER_ ## key;                                \
-    value.setInt32(JS_GetGlobalJitCompilerOption(cx, opt));     \
-    if (!JS_SetProperty(cx, info, string, value))               \
+#define JIT_COMPILER_MATCH(key, string)                                \
+    opt = JSJITCOMPILER_ ## key;                                       \
+    value.setInt32(JS_GetGlobalJitCompilerOption(cx->runtime(), opt)); \
+    if (!JS_SetProperty(cx, info, string, value))                      \
         return false;
 
     JSJitCompilerOption opt = JSJITCOMPILER_NOT_AN_OPTION;
     JIT_COMPILER_OPTIONS(JIT_COMPILER_MATCH);
 #undef JIT_COMPILER_MATCH
 
     *vp = ObjectValue(*info);
 
--- a/js/src/builtin/TypedObject.cpp
+++ b/js/src/builtin/TypedObject.cpp
@@ -889,18 +889,22 @@ StructMetaTypeDescr::layout(JSContext *c
                                      ObjectValue(*fieldOffsetsVec));
     }
 
     // Construct the fieldOffsets and fieldTypes objects:
     // fieldOffsets : { string: integer, ... }
     // fieldTypes : { string: Type, ... }
     RootedObject fieldOffsets(cx);
     fieldOffsets = NewObjectWithProto<JSObject>(cx, nullptr, nullptr, TenuredObject);
+    if (!fieldOffsets)
+        return false;
     RootedObject fieldTypes(cx);
     fieldTypes = NewObjectWithProto<JSObject>(cx, nullptr, nullptr, TenuredObject);
+    if (!fieldTypes)
+        return false;
     for (size_t i = 0; i < typeRepr->fieldCount(); i++) {
         const StructField &field = typeRepr->field(i);
         RootedId fieldId(cx, NameToId(field.propertyName));
 
         // fieldOffsets[id] = offset
         RootedValue offset(cx, NumberValue(field.offset));
         if (!JSObject::defineGeneric(cx, fieldOffsets, fieldId,
                                      offset, nullptr, nullptr,
--- a/js/src/builtin/TypedObject.h
+++ b/js/src/builtin/TypedObject.h
@@ -875,48 +875,65 @@ JS_FOR_EACH_REFERENCE_TYPE_REPR(JS_LOAD_
 
 inline bool
 IsTypedObjectClass(const Class *class_)
 {
     return class_ == &TransparentTypedObject::class_ ||
            class_ == &OpaqueTypedObject::class_;
 }
 
+inline bool
+IsSimpleTypeDescrClass(const Class* clasp)
+{
+    return clasp == &ScalarTypeDescr::class_ ||
+           clasp == &ReferenceTypeDescr::class_;
+}
+
+inline bool
+IsSizedTypeDescrClass(const Class* clasp)
+{
+    return IsSimpleTypeDescrClass(clasp) ||
+           clasp == &StructTypeDescr::class_ ||
+           clasp == &SizedArrayTypeDescr::class_ ||
+           clasp == &X4TypeDescr::class_;
+}
+
+inline bool
+IsTypeDescrClass(const Class* clasp)
+{
+    return IsSizedTypeDescrClass(clasp) ||
+           clasp == &UnsizedArrayTypeDescr::class_;
+}
+
 } // namespace js
 
 JSObject *
 js_InitTypedObjectModuleObject(JSContext *cx, JS::HandleObject obj);
 
 template <>
 inline bool
 JSObject::is<js::SimpleTypeDescr>() const
 {
-    return is<js::ScalarTypeDescr>() ||
-           is<js::ReferenceTypeDescr>();
+    return IsSimpleTypeDescrClass(getClass());
 }
 
 template <>
 inline bool
 JSObject::is<js::SizedTypeDescr>() const
 {
-    return is<js::SimpleTypeDescr>() ||
-           is<js::StructTypeDescr>() ||
-           is<js::SizedArrayTypeDescr>() ||
-           is<js::X4TypeDescr>();
+    return IsSizedTypeDescrClass(getClass());
 }
 
 template <>
 inline bool
 JSObject::is<js::TypeDescr>() const
 {
-    return is<js::SizedTypeDescr>() ||
-           is<js::UnsizedArrayTypeDescr>();
+    return IsTypeDescrClass(getClass());
 }
 
 template <>
 inline bool
 JSObject::is<js::TypedObject>() const
 {
     return IsTypedObjectClass(getClass());
 }
 
 #endif /* builtin_TypedObject_h */
-
--- a/js/src/ctypes/CTypes.cpp
+++ b/js/src/ctypes/CTypes.cpp
@@ -1442,17 +1442,17 @@ struct ConvertImpl<uint64_t, double> {
   }
 };
 #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
+#if defined(SPARC) || defined(__powerpc__)
 // Simulate x86 overflow behavior
 template<>
 struct ConvertImpl<uint64_t, double> {
   static MOZ_ALWAYS_INLINE uint64_t Convert(double d) {
     return d >= 0xffffffffffffffff ?
            0x8000000000000000 : uint64_t(d);
   }
 };
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/inlining/TypedObject-ObjectIsTypeDescr-multi.js
@@ -0,0 +1,38 @@
+/* -*- Mode: C++; tab-width: 8; 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/. */
+
+/* Used to verify that the JIT resolves the ObjectIsTypeDescr tests
+ * internal to Type.toSource().
+ *
+ * In this case the argument type is always a type descriptor object
+ * (though not a unique one), so ObjectIsTypeDescr resolves to true
+ * and there should be no exceptions.
+ *
+ * Load this into the js shell with IONFLAGS=logs, then exit and run
+ * iongraph.  You're looking for a smallish function within the
+ * "self-hosted" domain.  Look for a call to ObjectIsTypeDescr far
+ * down in the graph for pass00, with a call to DescrToSource in a
+ * subsequent block (all of this is at the mercy of the way the code
+ * is currently written).
+ */
+
+var T = TypedObject;
+var ST1 = new T.StructType({x:T.int32});
+var ST2 = new T.StructType({x:T.float64});
+
+function check(v) {
+    return v.toSource();
+}
+
+function test() {
+  var a = [ ST1, ST2 ];
+    for ( var i=0 ; i < 1000 ; i++ )
+	check(a[i%2]);
+    return check(a[0]);
+}
+
+print(test());
+
+
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/inlining/TypedObject-ObjectIsTypeDescr-unknown.js
@@ -0,0 +1,36 @@
+/* -*- Mode: C++; tab-width: 8; 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/. */
+
+/* Used to verify that the JIT resolves the ObjectIsTypeDescr tests
+ * internal to Type.toSource().
+ *
+ * In this case the argument type is never a type descriptor object,
+ * so ObjectIsTypeDescr resolves to false (and we have to catch
+ * exceptions).
+ *
+ * Load this into the js shell with IONFLAGS=logs, then exit and run
+ * iongraph.  You're looking for a smallish function within the
+ * "self-hosted" domain.  Look for a call to ObjectIsTypeDescr far
+ * down in the graph for pass00, with a call to DescrToSource in a
+ * subsequent block (all of this is at the mercy of the way the code
+ * is currently written).
+ */
+
+var T = TypedObject;
+var ST = new T.StructType({x:T.int32});
+
+function check(v) {
+    return v.toSource();
+}
+
+function test() {
+    var fake = { toSource: ST.toSource };
+    var a = [ ST, fake ];
+    for ( var i=0 ; i < 1000 ; i++ )
+	try { check(a[i%2]); } catch (e) {}
+    try { return check(a[0]); } catch (e) { return "Thrown" }
+}
+
+print(test());
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/inlining/TypedObject-ObjectIsTypeDescr-wrong-multi.js
@@ -0,0 +1,38 @@
+/* -*- Mode: C++; tab-width: 8; 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/. */
+
+/* Used to verify that the JIT resolves the ObjectIsTypeDescr tests
+ * internal to Type.toSource().
+ *
+ * In this case the argument type is never a type descriptor object
+ * (though not a unique non-type-descriptor), so ObjectIsTypeDescr
+ * resolves to false (and we have to catch exceptions).
+ *
+ * Load this into the js shell with IONFLAGS=logs, then exit and run
+ * iongraph.  You're looking for a smallish function within the
+ * "self-hosted" domain.  Look for a call to ObjectIsTypeDescr far
+ * down in the graph for pass00, with a call to DescrToSource in a
+ * subsequent block (all of this is at the mercy of the way the code
+ * is currently written).
+ */
+
+var T = TypedObject;
+var ST = new T.StructType({x:T.int32});
+
+function check(v) {
+    return v.toSource();
+}
+
+function test() {
+    var fake1 = { toSource: ST.toSource };
+    var fake2 = [];  fake2.toSource = ST.toSource;
+    var a = [ fake1, fake2 ];
+    for ( var i=0 ; i < 1000 ; i++ )
+	try { check(a[i%2]); } catch (e) {}
+    try { return check(a[0]); } catch (e) { return "Thrown" }
+}
+
+print(test());
+
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/inlining/TypedObject-ObjectIsTypeDescr-wrong.js
@@ -0,0 +1,36 @@
+/* -*- Mode: C++; tab-width: 8; 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/. */
+
+/* Used to verify that the JIT resolves the ObjectIsTypeDescr tests
+ * internal to Type.toSource().
+ *
+ * In this case the argument type is never a type descriptor object,
+ * so ObjectIsTypeDescr resolves to false (and we have to catch
+ * exceptions).
+ *
+ * Load this into the js shell with IONFLAGS=logs, then exit and run
+ * iongraph.  You're looking for a smallish function within the
+ * "self-hosted" domain.  Look for a call to ObjectIsTypeDescr far
+ * down in the graph for pass00, with a call to DescrToSource in a
+ * subsequent block (all of this is at the mercy of the way the code
+ * is currently written).
+ */
+
+var T = TypedObject;
+var ST = new T.StructType({x:T.int32});
+
+function check(v) {
+    return v.toSource();
+}
+
+function test() {
+    var fake = { toSource: ST.toSource };
+    for ( var i=0 ; i < 1000 ; i++ )
+	try { check(fake); } catch (e) {}
+    try { return check(fake); } catch (e) { return "Thrown" }
+}
+
+print(test());
+
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/ion/inlining/TypedObject-ObjectIsTypeDescr.js
@@ -0,0 +1,36 @@
+/* -*- Mode: C++; tab-width: 8; 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/. */
+
+/* Used to verify that the JIT resolves the ObjectIsTypeDescr tests
+ * internal to Type.toSource().
+ *
+ * In this case the argument type is always a type descriptor object,
+ * so ObjectIsTypeDescr resolves to true and there should be no
+ * exceptions.
+ *
+ * Load this into the js shell with IONFLAGS=logs, then exit and run
+ * iongraph.  You're looking for a smallish function within the
+ * "self-hosted" domain.  Look for a call to ObjectIsTypeDescr far
+ * down in the graph for pass00, with a call to DescrToSource in a
+ * subsequent block (all of this is at the mercy of the way the code
+ * is currently written).
+ */
+
+var T = TypedObject;
+var ST = new T.StructType({x:T.int32});
+
+function check(v) {
+    return v.toSource();
+}
+
+function test() {
+    for ( var i=0 ; i < 1000 ; i++ )
+	check(ST);
+    return check(ST);
+}
+
+print(test());
+
+
--- a/js/src/jit-test/tests/ion/testFloat32-correctness.js
+++ b/js/src/jit-test/tests/ion/testFloat32-correctness.js
@@ -225,16 +225,55 @@ function testFloorDouble() {
         assertFloat32(g, false);
 
         assertEq(f, g);
     }
 }
 test(setupFloor, testFloor);
 test(setupFloorDouble, testFloorDouble);
 
+function setupRound() {
+    f32[0] = -5.5;
+    f32[1] = -0.6;
+    f32[2] = 1.5;
+    f32[3] = 1;
+}
+function setupRoundDouble() {
+    f32[4] = NaN;
+    f32[5] = -0.49;          // rounded to -0
+    f32[6] = Infinity;
+    f32[7] = -Infinity;
+    f32[8] = Math.pow(2,31); // too big to fit into a int
+    f32[9] = -0;
+}
+function testRound() {
+    for (var i = 0; i < 4; ++i) {
+        var r32 = Math.round(f32[i]);
+        assertFloat32(r32, false); // r32 is an int32
+
+        var r64 = Math.round(-0 + f32[i]);
+        assertFloat32(r64, false);
+
+        assertEq(r32, r64);
+    }
+}
+function testRoundDouble() {
+    for (var i = 4; i < 10; ++i) {
+        var r32 = Math.fround(Math.round(f32[i]));
+        assertFloat32(r32, true);
+
+        var r64 = Math.round(-0 + f32[i]);
+        assertFloat32(r64, false);
+
+        assertEq(r32, r64);
+    }
+}
+test(setupRound, testRound);
+test(setupRoundDouble, testRoundDouble);
+
 function setupCeil() {
     f32[0] = -5.5;
     f32[1] = -1.5;
     f32[2] = 0;
     f32[3] = 1.5;
 }
 function setupCeilDouble() {
     f32[4] = NaN;
new file mode 100644
--- /dev/null
+++ b/js/src/jit-test/tests/self-hosting/bug957004.js
@@ -0,0 +1,3 @@
+// No result, just mustn't crash.
+Array.prototype.push(0);
+Array.prototype.indexOf();
--- a/js/src/jit/AsmJS.cpp
+++ b/js/src/jit/AsmJS.cpp
@@ -6947,13 +6947,13 @@ js::IsAsmJSCompilationAvailable(JSContex
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     // See EstablishPreconditions.
     bool available = cx->jitSupportsFloatingPoint() &&
                      cx->signalHandlersInstalled() &&
                      cx->gcSystemPageSize() == AsmJSPageSize &&
                      !cx->compartment()->debugMode() &&
-                     cx->compartment()->options().asmJS(cx);
+                     cx->runtime()->options().asmJS();
 
     args.rval().set(BooleanValue(available));
     return true;
 }
--- a/js/src/jit/BaselineJIT.h
+++ b/js/src/jit/BaselineJIT.h
@@ -307,17 +307,17 @@ struct BaselineScript
         JS_ASSERT(bytecodeTypeMapOffset_);
         return reinterpret_cast<uint32_t *>(reinterpret_cast<uint8_t *>(this) + bytecodeTypeMapOffset_);
     }
 };
 
 inline bool
 IsBaselineEnabled(JSContext *cx)
 {
-    return cx->compartment()->options().baseline(cx);
+    return cx->runtime()->options().baseline();
 }
 
 MethodStatus
 CanEnterBaselineMethod(JSContext *cx, RunState &state);
 
 MethodStatus
 CanEnterBaselineAtBranch(JSContext *cx, StackFrame *fp, bool newType);
 
--- a/js/src/jit/CodeGenerator.cpp
+++ b/js/src/jit/CodeGenerator.cpp
@@ -4300,18 +4300,19 @@ CodeGenerator::visitMathFunctionF(LMathF
     FloatRegister input = ToFloatRegister(ins->input());
     JS_ASSERT(ToFloatRegister(ins->output()) == ReturnFloatReg);
 
     masm.setupUnalignedABICall(1, temp);
     masm.passABIArg(input, MoveOp::FLOAT32);
 
     void *funptr = nullptr;
     switch (ins->mir()->function()) {
-      case MMathFunction::Floor: funptr = JS_FUNC_TO_DATA_PTR(void *, floorf); break;
-      case MMathFunction::Ceil:  funptr = JS_FUNC_TO_DATA_PTR(void *, ceilf);  break;
+      case MMathFunction::Floor: funptr = JS_FUNC_TO_DATA_PTR(void *, floorf);           break;
+      case MMathFunction::Round: funptr = JS_FUNC_TO_DATA_PTR(void *, math_roundf_impl); break;
+      case MMathFunction::Ceil:  funptr = JS_FUNC_TO_DATA_PTR(void *, ceilf);            break;
       default:
         MOZ_ASSUME_UNREACHABLE("Unknown or unsupported float32 math function");
     }
 
     masm.callWithABI(funptr, MoveOp::FLOAT32);
     return true;
 }
 
--- a/js/src/jit/Ion.h
+++ b/js/src/jit/Ion.h
@@ -154,18 +154,18 @@ CodeGenerator *CompileBackEnd(MIRGenerat
 
 void AttachFinishedCompilations(JSContext *cx);
 void FinishOffThreadBuilder(IonBuilder *builder);
 void StopAllOffThreadCompilations(JSCompartment *comp);
 
 static inline bool
 IsIonEnabled(JSContext *cx)
 {
-    return cx->compartment()->options().ion(cx) &&
-        cx->compartment()->options().baseline(cx) &&
+    return cx->runtime()->options().ion() &&
+        cx->runtime()->options().baseline() &&
         cx->typeInferenceEnabled();
 }
 
 inline bool
 IsIonInlinablePC(jsbytecode *pc) {
     // CALL, FUNCALL, FUNAPPLY, EVAL, NEW (Normal Callsites)
     // GETPROP, CALLPROP, and LENGTH. (Inlined Getters)
     // SETPROP, SETNAME, SETGNAME (Inlined Setters)
--- a/js/src/jit/IonBuilder.h
+++ b/js/src/jit/IonBuilder.h
@@ -672,16 +672,19 @@ class IonBuilder : public MIRGenerator
 
     // Slot intrinsics.
     InliningStatus inlineUnsafeSetReservedSlot(CallInfo &callInfo);
     InliningStatus inlineUnsafeGetReservedSlot(CallInfo &callInfo);
 
     // ForkJoin intrinsics
     InliningStatus inlineForkJoinGetSlice(CallInfo &callInfo);
 
+    // TypedObject intrinsics.
+    InliningStatus inlineObjectIsTypeDescr(CallInfo &callInfo);
+
     // Utility intrinsics.
     InliningStatus inlineIsCallable(CallInfo &callInfo);
     InliningStatus inlineHaveSameClass(CallInfo &callInfo);
     InliningStatus inlineToObject(CallInfo &callInfo);
     InliningStatus inlineDump(CallInfo &callInfo);
     InliningStatus inlineHasClass(CallInfo &callInfo, const Class *clasp);
 
     // Testing functions.
--- a/js/src/jit/LIR-Common.h
+++ b/js/src/jit/LIR-Common.h
@@ -4733,17 +4733,17 @@ class LFloorF : public LInstructionHelpe
   public:
     LIR_HEADER(FloorF)
 
     LFloorF(const LAllocation &num) {
         setOperand(0, num);
     }
 };
 
-// Round a number. Implements Math.round().
+// Round a double precision number. Implements Math.round().
 class LRound : public LInstructionHelper<1, 1, 1>
 {
   public:
     LIR_HEADER(Round)
 
     LRound(const LAllocation &num, const LDefinition &temp) {
         setOperand(0, num);
         setTemp(0, temp);
@@ -4752,16 +4752,35 @@ class LRound : public LInstructionHelper
     const LDefinition *temp() {
         return getTemp(0);
     }
     MRound *mir() const {
         return mir_->toRound();
     }
 };
 
+// Round a single precision number. Implements Math.round().
+class LRoundF : public LInstructionHelper<1, 1, 1>
+{
+  public:
+    LIR_HEADER(RoundF)
+
+    LRoundF(const LAllocation &num, const LDefinition &temp) {
+        setOperand(0, num);
+        setTemp(0, temp);
+    }
+
+    const LDefinition *temp() {
+        return getTemp(0);
+    }
+    MRound *mir() const {
+        return mir_->toRound();
+    }
+};
+
 // Load a function's call environment.
 class LFunctionEnvironment : public LInstructionHelper<1, 1, 0>
 {
   public:
     LIR_HEADER(FunctionEnvironment)
 
     LFunctionEnvironment(const LAllocation &function) {
         setOperand(0, function);
--- a/js/src/jit/LOpcodes.h
+++ b/js/src/jit/LOpcodes.h
@@ -256,16 +256,17 @@
     _(RunOncePrologue)              \
     _(Rest)                         \
     _(RestPar)                      \
     _(TypeOfV)                      \
     _(ToIdV)                        \
     _(Floor)                        \
     _(FloorF)                       \
     _(Round)                        \
+    _(RoundF)                       \
     _(In)                           \
     _(InArray)                      \
     _(InstanceOfO)                  \
     _(InstanceOfV)                  \
     _(CallInstanceOf)               \
     _(InterruptCheck)               \
     _(InterruptCheckImplicit)       \
     _(FunctionBoundary)             \
--- a/js/src/jit/Lowering.cpp
+++ b/js/src/jit/Lowering.cpp
@@ -1174,18 +1174,27 @@ LIRGenerator::visitFloor(MFloor *ins)
     if (!assignSnapshot(lir))
         return false;
     return define(lir, ins);
 }
 
 bool
 LIRGenerator::visitRound(MRound *ins)
 {
-    JS_ASSERT(ins->num()->type() == MIRType_Double);
-    LRound *lir = new(alloc()) LRound(useRegister(ins->num()), tempDouble());
+    MIRType type = ins->num()->type();
+    JS_ASSERT(IsFloatingPointType(type));
+
+    if (type == MIRType_Double) {
+        LRound *lir = new (alloc()) LRound(useRegister(ins->num()), tempDouble());
+        if (!assignSnapshot(lir))
+            return false;
+        return define(lir, ins);
+    }
+
+    LRoundF *lir = new (alloc()) LRoundF(useRegister(ins->num()), tempDouble());
     if (!assignSnapshot(lir))
         return false;
     return define(lir, ins);
 }
 
 bool
 LIRGenerator::visitMinMax(MMinMax *ins)
 {
--- a/js/src/jit/MCallOptimize.cpp
+++ b/js/src/jit/MCallOptimize.cpp
@@ -157,16 +157,18 @@ IonBuilder::inlineNativeCall(CallInfo &c
     if (native == intrinsic_ToObject)
         return inlineToObject(callInfo);
 
     // TypedObject intrinsics.
     if (native == intrinsic_ObjectIsTransparentTypedObject)
         return inlineHasClass(callInfo, &TransparentTypedObject::class_);
     if (native == intrinsic_ObjectIsOpaqueTypedObject)
         return inlineHasClass(callInfo, &OpaqueTypedObject::class_);
+    if (native == intrinsic_ObjectIsTypeDescr)
+        return inlineObjectIsTypeDescr(callInfo);
 
     // Testing Functions
     if (native == testingFunc_inParallelSection)
         return inlineForceSequentialOrInParallelSection(callInfo);
     if (native == testingFunc_bailout)
         return inlineBailout(callInfo);
     if (native == testingFunc_assertFloat32)
         return inlineAssertFloat32(callInfo);
@@ -668,25 +670,25 @@ IonBuilder::inlineMathRound(CallInfo &ca
 
     // Math.round(int(x)) == int(x)
     if (argType == MIRType_Int32 && returnType == MIRType_Int32) {
         callInfo.setImplicitlyUsedUnchecked();
         current->push(callInfo.getArg(0));
         return InliningStatus_Inlined;
     }
 
-    if (argType == MIRType_Double && returnType == MIRType_Int32) {
+    if (IsFloatingPointType(argType) && returnType == MIRType_Int32) {
         callInfo.setImplicitlyUsedUnchecked();
         MRound *ins = MRound::New(alloc(), callInfo.getArg(0));
         current->add(ins);
         current->push(ins);
         return InliningStatus_Inlined;
     }
 
-    if (argType == MIRType_Double && returnType == MIRType_Double) {
+    if (IsFloatingPointType(argType) && returnType == MIRType_Double) {
         callInfo.setImplicitlyUsedUnchecked();
         MMathFunction *ins = MMathFunction::New(alloc(), callInfo.getArg(0), MMathFunction::Round, nullptr);
         current->add(ins);
         current->push(ins);
         return InliningStatus_Inlined;
     }
 
     return InliningStatus_NotInlined;
@@ -1504,16 +1506,53 @@ IonBuilder::inlineHasClass(CallInfo &cal
         current->push(hasClass);
     }
 
     callInfo.setImplicitlyUsedUnchecked();
     return InliningStatus_Inlined;
 }
 
 IonBuilder::InliningStatus
+IonBuilder::inlineObjectIsTypeDescr(CallInfo &callInfo)
+{
+    if (callInfo.constructing() || callInfo.argc() != 1)
+        return InliningStatus_NotInlined;
+
+    if (callInfo.getArg(0)->type() != MIRType_Object)
+        return InliningStatus_NotInlined;
+    if (getInlineReturnType() != MIRType_Boolean)
+        return InliningStatus_NotInlined;
+
+    // The test is elaborate: in-line only if there is exact
+    // information.
+
+    types::TemporaryTypeSet *types = callInfo.getArg(0)->resultTypeSet();
+    if (!types)
+        return InliningStatus_NotInlined;
+
+    bool result = false;
+    switch (types->forAllClasses(IsTypeDescrClass)) {
+    case types::TemporaryTypeSet::ForAllResult::ALL_FALSE:
+    case types::TemporaryTypeSet::ForAllResult::EMPTY:
+        result = false;
+        break;
+    case types::TemporaryTypeSet::ForAllResult::ALL_TRUE:
+        result = true;
+        break;
+    case types::TemporaryTypeSet::ForAllResult::MIXED:
+        return InliningStatus_NotInlined;
+    }
+
+    pushConstant(BooleanValue(result));
+
+    callInfo.setImplicitlyUsedUnchecked();
+    return InliningStatus_Inlined;
+}
+
+IonBuilder::InliningStatus
 IonBuilder::inlineUnsafeSetReservedSlot(CallInfo &callInfo)
 {
     if (callInfo.argc() != 3 || callInfo.constructing())
         return InliningStatus_NotInlined;
     if (getInlineReturnType() != MIRType_Undefined)
         return InliningStatus_NotInlined;
     if (callInfo.getArg(0)->type() != MIRType_Object)
         return InliningStatus_NotInlined;
--- a/js/src/jit/MIR.cpp
+++ b/js/src/jit/MIR.cpp
@@ -805,16 +805,32 @@ MFloor::trySpecializeFloat32(TempAllocat
     }
 
     if (type() == MIRType_Double)
         setResultType(MIRType_Float32);
 
     setPolicyType(MIRType_Float32);
 }
 
+void
+MRound::trySpecializeFloat32(TempAllocator &alloc)
+{
+    // No need to look at the output, as it's an integer (unique way to have
+    // this instruction in IonBuilder::inlineMathRound)
+    JS_ASSERT(type() == MIRType_Int32);
+
+    if (!input()->canProduceFloat32()) {
+        if (input()->type() == MIRType_Float32)
+            ConvertDefinitionToDouble<0>(alloc, input(), this);
+        return;
+    }
+
+    setPolicyType(MIRType_Float32);
+}
+
 MTest *
 MTest::New(TempAllocator &alloc, MDefinition *ins, MBasicBlock *ifTrue, MBasicBlock *ifFalse)
 {
     return new(alloc) MTest(ins, ifTrue, ifFalse);
 }
 
 MCompare *
 MCompare::New(TempAllocator &alloc, MDefinition *left, MDefinition *right, JSOp op)
--- a/js/src/jit/MIR.h
+++ b/js/src/jit/MIR.h
@@ -3925,17 +3925,17 @@ class MMathFunction
         return true;
     }
 
     void printOpcode(FILE *fp) const;
 
     static const char *FunctionName(Function function);
 
     bool isFloat32Commutative() const {
-        return function_ == Floor || function_ == Ceil;
+        return function_ == Floor || function_ == Ceil || function_ == Round;
     }
     void trySpecializeFloat32(TempAllocator &alloc);
     void computeRange(TempAllocator &alloc);
 };
 
 class MAdd : public MBinaryArithInstruction
 {
     // Is this instruction really an int at heart?
@@ -8278,22 +8278,23 @@ class MFloor
         return true;
     }
 #endif
 };
 
 // Inlined version of Math.round().
 class MRound
   : public MUnaryInstruction,
-    public DoublePolicy<0>
+    public FloatingPointPolicy<0>
 {
     MRound(MDefinition *num)
       : MUnaryInstruction(num)
     {
         setResultType(MIRType_Int32);
+        setPolicyType(MIRType_Double);
         setMovable();
     }
 
   public:
     INSTRUCTION_HEADER(Round)
 
     static MRound *New(TempAllocator &alloc, MDefinition *num) {
         return new(alloc) MRound(num);
@@ -8303,16 +8304,26 @@ class MRound
         return getOperand(0);
     }
     AliasSet getAliasSet() const {
         return AliasSet::None();
     }
     TypePolicy *typePolicy() {
         return this;
     }
+
+    bool isFloat32Commutative() const {
+        return true;
+    }
+    void trySpecializeFloat32(TempAllocator &alloc);
+#ifdef DEBUG
+    bool isConsistentFloat32Use(MUse *use) const {
+        return true;
+    }
+#endif
 };
 
 class MIteratorStart
   : public MUnaryInstruction,
     public SingleObjectPolicy
 {
     uint8_t flags_;
 
--- a/js/src/jit/arm/CodeGenerator-arm.cpp
+++ b/js/src/jit/arm/CodeGenerator-arm.cpp
@@ -1239,16 +1239,31 @@ CodeGeneratorARM::visitRound(LRound *lir
     // Output is either correct, or clamped.  All -0 cases have been translated to a clamped
     // case.a
     masm.round(input, output, &bail, tmp);
     if (!bailoutFrom(&bail, lir->snapshot()))
         return false;
     return true;
 }
 
+bool
+CodeGeneratorARM::visitRoundF(LRoundF *lir)
+{
+    FloatRegister input = ToFloatRegister(lir->input());
+    Register output = ToRegister(lir->output());
+    FloatRegister tmp = ToFloatRegister(lir->temp());
+    Label bail;
+    // Output is either correct, or clamped.  All -0 cases have been translated to a clamped
+    // case.a
+    masm.roundf(input, output, &bail, tmp);
+    if (!bailoutFrom(&bail, lir->snapshot()))
+        return false;
+    return true;
+}
+
 void
 CodeGeneratorARM::emitRoundDouble(const FloatRegister &src, const Register &dest, Label *fail)
 {
     masm.ma_vcvt_F64_I32(src, ScratchFloatReg);
     masm.ma_vxfer(ScratchFloatReg, dest);
     masm.ma_cmp(dest, Imm32(0x7fffffff));
     masm.ma_cmp(dest, Imm32(0x80000000), Assembler::NotEqual);
     masm.ma_b(fail, Assembler::Equal);
--- a/js/src/jit/arm/CodeGenerator-arm.h
+++ b/js/src/jit/arm/CodeGenerator-arm.h
@@ -107,16 +107,17 @@ class CodeGeneratorARM : public CodeGene
     virtual bool visitNotD(LNotD *ins);
     virtual bool visitNotF(LNotF *ins);
 
     virtual bool visitMathD(LMathD *math);
     virtual bool visitMathF(LMathF *math);
     virtual bool visitFloor(LFloor *lir);
     virtual bool visitFloorF(LFloorF *lir);
     virtual bool visitRound(LRound *lir);
+    virtual bool visitRoundF(LRoundF *lir);
     virtual bool visitTruncateDToInt32(LTruncateDToInt32 *ins);
     virtual bool visitTruncateFToInt32(LTruncateFToInt32 *ins);
 
     // Out of line visitors.
     bool visitOutOfLineBailout(OutOfLineBailout *ool);
     bool visitOutOfLineTableSwitch(OutOfLineTableSwitch *ool);
 
   protected:
--- a/js/src/jit/arm/MacroAssembler-arm.cpp
+++ b/js/src/jit/arm/MacroAssembler-arm.cpp
@@ -4139,16 +4139,79 @@ MacroAssemblerARMCompat::round(FloatRegi
     // If the result looks non-negative, then this value didn't actually fit into
     // the int range, and special handling is required, or it was zero, which means
     // the result is actually -0.0 which also requires special handling.
     ma_b(bail, NotSigned);
 
     bind(&fin);
 }
 
+void
+MacroAssemblerARMCompat::roundf(FloatRegister input, Register output, Label *bail, FloatRegister tmp)
+{
+    Label handleZero;
+    Label handleNeg;
+    Label fin;
+    // Do a compare based on the original value, then do most other things based on the
+    // shifted value.
+    ma_vcmpz_f32(input);
+    // Adding 0.5 is technically incorrect!
+    // We want to add 0.5 to negative numbers, and 0.49999999999999999 to positive numbers.
+    ma_vimm_f32(0.5f, ScratchFloatReg);
+    // Since we already know the sign bit, flip all numbers to be positive, stored in tmp.
+    ma_vabs_f32(input, tmp);
+    // Add 0.5, storing the result into tmp.
+    ma_vadd_f32(ScratchFloatReg, tmp, tmp);
+    as_vmrs(pc);
+    ma_b(&handleZero, Assembler::Equal);
+    ma_b(&handleNeg, Assembler::Signed);
+    // NaN is always a bail condition, just bail directly.
+    ma_b(bail, Assembler::Overflow);
+
+    // The argument is a positive number, truncation is the path to glory;
+    // Since it is known to be > 0.0, explicitly convert to a larger range,
+    // then a value that rounds to INT_MAX is explicitly different from an
+    // argument that clamps to INT_MAX
+    ma_vcvt_F32_U32(tmp, ScratchFloatReg);
+    ma_vxfer(VFPRegister(ScratchFloatReg).uintOverlay(), output);
+    ma_mov(output, output, SetCond);
+    ma_b(bail, Signed);
+    ma_b(&fin);
+
+    bind(&handleZero);
+    // Move the top word of the double into the output reg, if it is non-zero,
+    // then the original value was -0.0
+    as_vxfer(output, InvalidReg, input, FloatToCore, Always, 1);
+    ma_cmp(output, Imm32(0));
+    ma_b(bail, NonZero);
+    ma_b(&fin);
+
+    bind(&handleNeg);
+    // Negative case, negate, then start dancing.  This number may be positive, since we added 0.5
+    ma_vcvt_F32_U32(tmp, ScratchFloatReg);
+    ma_vxfer(VFPRegister(ScratchFloatReg).uintOverlay(), output);
+
+    // -output is now a correctly rounded value, unless the original value was exactly
+    // halfway between two integers, at which point, it has been rounded away from zero, when
+    // it should be rounded towards \infty.
+    ma_vcvt_U32_F32(ScratchFloatReg, ScratchFloatReg);
+    compareFloat(ScratchFloatReg, tmp);
+    ma_sub(output, Imm32(1), output, NoSetCond, Equal);
+    // Negate the output.  Since INT_MIN < -INT_MAX, even after adding 1,
+    // the result will still be a negative number
+    ma_rsb(output, Imm32(0), output, SetCond);
+
+    // If the result looks non-negative, then this value didn't actually fit into
+    // the int range, and special handling is required, or it was zero, which means
+    // the result is actually -0.0 which also requires special handling.
+    ma_b(bail, NotSigned);
+
+    bind(&fin);
+}
+
 CodeOffsetJump
 MacroAssemblerARMCompat::jumpWithPatch(RepatchLabel *label, Condition cond)
 {
     ARMBuffer::PoolEntry pe;
     BufferOffset bo = as_BranchPool(0xdeadbeef, label, &pe, cond);
 
     // Fill in a new CodeOffset with both the load and the
     // pool entry that the instruction loads from.
--- a/js/src/jit/arm/MacroAssembler-arm.h
+++ b/js/src/jit/arm/MacroAssembler-arm.h
@@ -1436,16 +1436,17 @@ class MacroAssemblerARMCompat : public M
     void computeEffectiveAddress(const BaseIndex &address, Register dest) {
         ma_alu(address.base, lsl(address.index, address.scale), dest, op_add, NoSetCond);
         if (address.offset)
             ma_add(dest, Imm32(address.offset), dest, NoSetCond);
     }
     void floor(FloatRegister input, Register output, Label *handleNotAnInt);
     void floorf(FloatRegister input, Register output, Label *handleNotAnInt);
     void round(FloatRegister input, Register output, Label *handleNotAnInt, FloatRegister tmp);
+    void roundf(FloatRegister input, Register output, Label *handleNotAnInt, FloatRegister tmp);
 
     void clampCheck(Register r, Label *handleNotAnInt) {
         // check explicitly for r == INT_MIN || r == INT_MAX
         // this is the instruction sequence that gcc generated for this
         // operation.
         ma_sub(r, Imm32(0x80000001), ScratchRegister);
         ma_cmn(ScratchRegister, Imm32(3));
         ma_b(handleNotAnInt, Above);
--- a/js/src/jit/shared/CodeGenerator-x86-shared.cpp
+++ b/js/src/jit/shared/CodeGenerator-x86-shared.cpp
@@ -1662,16 +1662,103 @@ CodeGeneratorX86Shared::visitRound(LRoun
         }
     }
 
     masm.bind(&end);
     return true;
 }
 
 bool
+CodeGeneratorX86Shared::visitRoundF(LRoundF *lir)
+{
+    FloatRegister input = ToFloatRegister(lir->input());
+    FloatRegister temp = ToFloatRegister(lir->temp());
+    FloatRegister scratch = ScratchFloatReg;
+    Register output = ToRegister(lir->output());
+
+    Label negative, end;
+
+    // Load 0.5 in the temp register.
+    masm.loadConstantFloat32(0.5f, temp);
+
+    // Branch to a slow path for negative inputs. Doesn't catch NaN or -0.
+    masm.xorps(scratch, scratch);
+    masm.branchFloat(Assembler::DoubleLessThan, input, scratch, &negative);
+
+    // Bail on negative-zero.
+    Assembler::Condition bailCond = masm.testNegativeZeroFloat32(input, output);
+    if (!bailoutIf(bailCond, lir->snapshot()))
+        return false;
+
+    // Input is non-negative. Add 0.5 and truncate, rounding down. Note that we
+    // have to add the input to the temp register (which contains 0.5) because
+    // we're not allowed to modify the input register.
+    masm.addss(input, temp);
+
+    masm.cvttss2si(temp, output);
+    masm.cmp32(output, Imm32(INT_MIN));
+    if (!bailoutIf(Assembler::Equal, lir->snapshot()))
+        return false;
+
+    masm.jump(&end);
+
+
+    // Input is negative, but isn't -0.
+    masm.bind(&negative);
+
+    if (AssemblerX86Shared::HasSSE41()) {
+        // Add 0.5 and round toward -Infinity. The result is stored in the temp
+        // register (currently contains 0.5).
+        masm.addss(input, temp);
+        masm.roundss(temp, scratch, JSC::X86Assembler::RoundDown);
+
+        // Truncate.
+        masm.cvttss2si(scratch, output);
+        masm.cmp32(output, Imm32(INT_MIN));
+        if (!bailoutIf(Assembler::Equal, lir->snapshot()))
+            return false;
+
+        // If the result is positive zero, then the actual result is -0. Bail.
+        // Otherwise, the truncation will have produced the correct negative integer.
+        masm.testl(output, output);
+        if (!bailoutIf(Assembler::Zero, lir->snapshot()))
+            return false;
+
+    } else {
+        masm.addss(input, temp);
+        // Round toward -Infinity without the benefit of ROUNDSS.
+        {
+            // If input + 0.5 >= 0, input is a negative number >= -0.5 and the result is -0.
+            masm.compareFloat(Assembler::DoubleGreaterThanOrEqual, temp, scratch);
+            if (!bailoutIf(Assembler::DoubleGreaterThanOrEqual, lir->snapshot()))
+                return false;
+
+            // Truncate and round toward zero.
+            // This is off-by-one for everything but integer-valued inputs.
+            masm.cvttss2si(temp, output);
+            masm.cmp32(output, Imm32(INT_MIN));
+            if (!bailoutIf(Assembler::Equal, lir->snapshot()))
+                return false;
+
+            // Test whether the truncated double was integer-valued.
+            masm.convertInt32ToFloat32(output, scratch);
+            masm.branchFloat(Assembler::DoubleEqualOrUnordered, temp, scratch, &end);
+
+            // Input is not integer-valued, so we rounded off-by-one in the
+            // wrong direction. Correct by subtraction.
+            masm.subl(Imm32(1), output);
+            // Cannot overflow: output was already checked against INT_MIN.
+        }
+    }
+
+    masm.bind(&end);
+    return true;
+}
+
+bool
 CodeGeneratorX86Shared::visitGuardShape(LGuardShape *guard)
 {
     Register obj = ToRegister(guard->input());
     masm.cmpPtr(Operand(obj, JSObject::offsetOfShape()), ImmGCPtr(guard->mir()->shape()));
 
     return bailoutIf(Assembler::NotEqual, guard->snapshot());
 }
 
--- a/js/src/jit/shared/CodeGenerator-x86-shared.h
+++ b/js/src/jit/shared/CodeGenerator-x86-shared.h
@@ -110,16 +110,17 @@ class CodeGeneratorX86Shared : public Co
     virtual bool visitNotI(LNotI *comp);
     virtual bool visitNotD(LNotD *comp);
     virtual bool visitNotF(LNotF *comp);
     virtual bool visitMathD(LMathD *math);
     virtual bool visitMathF(LMathF *math);
     virtual bool visitFloor(LFloor *lir);
     virtual bool visitFloorF(LFloorF *lir);
     virtual bool visitRound(LRound *lir);
+    virtual bool visitRoundF(LRoundF *lir);
     virtual bool visitGuardShape(LGuardShape *guard);
     virtual bool visitGuardObjectType(LGuardObjectType *guard);
     virtual bool visitGuardClass(LGuardClass *guard);
     virtual bool visitEffectiveAddress(LEffectiveAddress *ins);
     virtual bool visitUDivOrMod(LUDivOrMod *ins);
     virtual bool visitAsmJSPassStackArg(LAsmJSPassStackArg *ins);
 
     bool visitForkJoinGetSlice(LForkJoinGetSlice *ins);
--- a/js/src/jsapi-tests/testFuncCallback.cpp
+++ b/js/src/jsapi-tests/testFuncCallback.cpp
@@ -128,14 +128,14 @@ BEGIN_TEST(testFuncCallback_bug507012)
 // Make sure that the method jit is enabled.
 // We'll probably want to test in all modes.
 virtual
 JSContext *createContext()
 {
     JSContext *cx = JSAPITest::createContext();
     if (!cx)
         return nullptr;
-    JS::ContextOptionsRef(cx).setBaseline(true)
+    JS::RuntimeOptionsRef(cx).setBaseline(true)
                              .setIon(true);
     return cx;
 }
 
 END_TEST(testFuncCallback_bug507012)
--- a/js/src/jsapi-tests/testProfileStrings.cpp
+++ b/js/src/jsapi-tests/testProfileStrings.cpp
@@ -136,17 +136,17 @@ BEGIN_TEST(testProfileStrings_isCalledWi
     }
     return true;
 }
 END_TEST(testProfileStrings_isCalledWithInterpreter)
 
 BEGIN_TEST(testProfileStrings_isCalledWithJIT)
 {
     CHECK(initialize(cx));
-    JS::ContextOptionsRef(cx).setBaseline(true)
+    JS::RuntimeOptionsRef(cx).setBaseline(true)
                              .setIon(true);
 
     EXEC("function g() { var p = new Prof(); p.test_fn(); }");
     EXEC("function f() { g(); }");
     EXEC("function e() { f(); }");
     EXEC("function d() { e(); }");
     EXEC("function c() { d(); }");
     EXEC("function b() { c(); }");
@@ -185,17 +185,17 @@ BEGIN_TEST(testProfileStrings_isCalledWi
     }
     return true;
 }
 END_TEST(testProfileStrings_isCalledWithJIT)
 
 BEGIN_TEST(testProfileStrings_isCalledWhenError)
 {
     CHECK(initialize(cx));
-    JS::ContextOptionsRef(cx).setBaseline(true)
+    JS::RuntimeOptionsRef(cx).setBaseline(true)
                              .setIon(true);
 
     EXEC("function check2() { throw 'a'; }");
 
     reset(cx);
     JS::ContextOptionsRef(cx).setDontReportUncaught(true);
     {
         JS::RootedValue rval(cx);
@@ -209,17 +209,17 @@ BEGIN_TEST(testProfileStrings_isCalledWh
     }
     return true;
 }
 END_TEST(testProfileStrings_isCalledWhenError)
 
 BEGIN_TEST(testProfileStrings_worksWhenEnabledOnTheFly)
 {
     CHECK(initialize(cx));
-    JS::ContextOptionsRef(cx).setBaseline(true)
+    JS::RuntimeOptionsRef(cx).setBaseline(true)
                              .setIon(true);
 
     EXEC("function b(p) { p.test_fn(); }");
     EXEC("function a() { var p = new Prof(); p.enable(); b(p); }");
     reset(cx);
     js::EnableRuntimeProfilingStack(cx->runtime(), false);
     {
         /* enable it in the middle of JS and make sure things check out */
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -878,16 +878,28 @@ JS_StringToVersion(const char *string)
     int i;
 
     for (i = 0; v2smap[i].string; i++)
         if (strcmp(v2smap[i].string, string) == 0)
             return v2smap[i].version;
     return JSVERSION_UNKNOWN;
 }
 
+JS_PUBLIC_API(JS::RuntimeOptions &)
+JS::RuntimeOptionsRef(JSRuntime *rt)
+{
+    return rt->options();
+}
+
+JS_PUBLIC_API(JS::RuntimeOptions &)
+JS::RuntimeOptionsRef(JSContext *cx)
+{
+    return cx->runtime()->options();
+}
+
 JS_PUBLIC_API(JS::ContextOptions &)
 JS::ContextOptionsRef(JSContext *cx)
 {
     return cx->options();
 }
 
 JS_PUBLIC_API(const char *)
 JS_GetImplementationVersion(void)
@@ -2450,46 +2462,16 @@ class AutoHoldZone
   private:
     bool *holdp;
     MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
 } /* anonymous namespace */
 
 bool
-JS::CompartmentOptions::baseline(JSContext *cx) const
-{
-    return baselineOverride_.get(cx->options().baseline());
-}
-
-bool
-JS::CompartmentOptions::typeInference(const ExclusiveContext *cx) const
-{
-    /* Unlike the other options that can be overriden on a per compartment
-     * basis, the default value for the typeInference option is stored on the
-     * compartment's type zone, rather than the current JSContext. Type zones
-     * copy this default value over from the current JSContext when they are
-     * created.
-     */
-    return typeInferenceOverride_.get(cx->compartment()->zone()->types.inferenceEnabled);
-}
-
-bool
-JS::CompartmentOptions::ion(JSContext *cx) const
-{
-    return ionOverride_.get(cx->options().ion());
-}
-
-bool
-JS::CompartmentOptions::asmJS(JSContext *cx) const
-{
-    return asmJSOverride_.get(cx->options().asmJS());
-}
-
-bool
 JS::CompartmentOptions::cloneSingletons(JSContext *cx) const
 {
     return cloneSingletonsOverride_.get(cx->options().cloneSingletons());
 }
 
 JS::CompartmentOptions &
 JS::CompartmentOptions::setZone(ZoneSpecifier spec)
 {
@@ -4450,17 +4432,17 @@ JS::CompileOptions::CompileOptions(JSCon
 {
     this->version = (version != JSVERSION_UNKNOWN) ? version : cx->findVersion();
 
     compileAndGo = false;
     noScriptRval = cx->options().noScriptRval();
     strictOption = cx->options().strictMode();
     extraWarningsOption = cx->options().extraWarnings();
     werrorOption = cx->options().werror();
-    asmJSOption = cx->options().asmJS();
+    asmJSOption = cx->runtime()->options().asmJS();
 }
 
 bool
 JS::CompileOptions::wrap(JSContext *cx, JSCompartment *compartment)
 {
     if (!compartment->wrap(cx, &elementRoot))
         return false;
     if (elementAttributeNameRoot) {
@@ -6026,33 +6008,33 @@ JS_SetGCZeal(JSContext *cx, uint8_t zeal
 JS_PUBLIC_API(void)
 JS_ScheduleGC(JSContext *cx, uint32_t count)
 {
     cx->runtime()->gcNextScheduled = count;
 }
 #endif
 
 JS_PUBLIC_API(void)
-JS_SetParallelParsingEnabled(JSContext *cx, bool enabled)
+JS_SetParallelParsingEnabled(JSRuntime *rt, bool enabled)
 {
 #ifdef JS_ION
-    cx->runtime()->setParallelParsingEnabled(enabled);
+    rt->setParallelParsingEnabled(enabled);
 #endif
 }
 
 JS_PUBLIC_API(void)
-JS_SetParallelIonCompilationEnabled(JSContext *cx, bool enabled)
+JS_SetParallelIonCompilationEnabled(JSRuntime *rt, bool enabled)
 {
 #ifdef JS_ION
-    cx->runtime()->setParallelIonCompilationEnabled(enabled);
+    rt->setParallelIonCompilationEnabled(enabled);
 #endif
 }
 
 JS_PUBLIC_API(void)
-JS_SetGlobalJitCompilerOption(JSContext *cx, JSJitCompilerOption opt, uint32_t value)
+JS_SetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt, uint32_t value)
 {
 #ifdef JS_ION
 
     switch (opt) {
       case JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER:
         if (value == uint32_t(-1)) {
             jit::JitOptions defaultValues;
             value = defaultValues.baselineUsesBeforeCompile;
@@ -6065,51 +6047,51 @@ JS_SetGlobalJitCompilerOption(JSContext 
             break;
         }
         jit::js_JitOptions.setUsesBeforeCompile(value);
         if (value == 0)
             jit::js_JitOptions.setEagerCompilation();
         break;
       case JSJITCOMPILER_ION_ENABLE:
         if (value == 1) {
-            JS::ContextOptionsRef(cx).setIon(true);
+            JS::RuntimeOptionsRef(rt).setIon(true);
             IonSpew(js::jit::IonSpew_Scripts, "Enable ion");
         } else if (value == 0) {
-            JS::ContextOptionsRef(cx).setIon(false);
+            JS::RuntimeOptionsRef(rt).setIon(false);
             IonSpew(js::jit::IonSpew_Scripts, "Disable ion");
         }
         break;
       case JSJITCOMPILER_BASELINE_ENABLE:
         if (value == 1) {
-            JS::ContextOptionsRef(cx).setBaseline(true);
+            JS::RuntimeOptionsRef(rt).setBaseline(true);
             IonSpew(js::jit::IonSpew_BaselineScripts, "Enable baseline");
         } else if (value == 0) {
-            JS::ContextOptionsRef(cx).setBaseline(false);
+            JS::RuntimeOptionsRef(rt).setBaseline(false);
             IonSpew(js::jit::IonSpew_BaselineScripts, "Disable baseline");
         }
         break;
       default:
         break;
     }
 #endif
 }
 
 JS_PUBLIC_API(int)
-JS_GetGlobalJitCompilerOption(JSContext *cx, JSJitCompilerOption opt)
+JS_GetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt)
 {
 #ifdef JS_ION
     switch (opt) {
       case JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER:
         return jit::js_JitOptions.baselineUsesBeforeCompile;
       case JSJITCOMPILER_ION_USECOUNT_TRIGGER:
         return jit::js_JitOptions.forcedDefaultIonUsesBeforeCompile;
       case JSJITCOMPILER_ION_ENABLE:
-        return JS::ContextOptionsRef(cx).ion();
+        return JS::RuntimeOptionsRef(rt).ion();
       case JSJITCOMPILER_BASELINE_ENABLE:
-        return JS::ContextOptionsRef(cx).baseline();
+        return JS::RuntimeOptionsRef(rt).baseline();
       default:
         break;
     }
 #endif
     return 0;
 }
 
 /************************************************************************/
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -1433,31 +1433,90 @@ JS_SetVersionForCompartment(JSCompartmen
 extern JS_PUBLIC_API(const char *)
 JS_VersionToString(JSVersion version);
 
 extern JS_PUBLIC_API(JSVersion)
 JS_StringToVersion(const char *string);
 
 namespace JS {
 
+class JS_PUBLIC_API(RuntimeOptions) {
+  public:
+    RuntimeOptions()
+      : baseline_(false),
+        typeInference_(false),
+        ion_(false),
+        asmJS_(false)
+    {
+    }
+
+    bool baseline() const { return baseline_; }
+    RuntimeOptions &setBaseline(bool flag) {
+        baseline_ = flag;
+        return *this;
+    }
+    RuntimeOptions &toggleBaseline() {
+        baseline_ = !baseline_;
+        return *this;
+    }
+
+    bool typeInference() const { return typeInference_; }
+    RuntimeOptions &setTypeInference(bool flag) {
+        typeInference_ = flag;
+        return *this;
+    }
+    RuntimeOptions &toggleTypeInference() {
+        typeInference_ = !typeInference_;
+        return *this;
+    }
+
+    bool ion() const { return ion_; }
+    RuntimeOptions &setIon(bool flag) {
+        ion_ = flag;
+        return *this;
+    }
+    RuntimeOptions &toggleIon() {
+        ion_ = !ion_;
+        return *this;
+    }
+
+    bool asmJS() const { return asmJS_; }
+    RuntimeOptions &setAsmJS(bool flag) {
+        asmJS_ = flag;
+        return *this;
+    }
+    RuntimeOptions &toggleAsmJS() {
+        asmJS_ = !asmJS_;
+        return *this;
+    }
+
+  private:
+    bool baseline_ : 1;
+    bool typeInference_ : 1;
+    bool ion_ : 1;
+    bool asmJS_ : 1;
+};
+
+JS_PUBLIC_API(RuntimeOptions &)
+RuntimeOptionsRef(JSRuntime *rt);
+
+JS_PUBLIC_API(RuntimeOptions &)
+RuntimeOptionsRef(JSContext *cx);
+
 class JS_PUBLIC_API(ContextOptions) {
   public:
     ContextOptions()
       : extraWarnings_(false),
         werror_(false),
         varObjFix_(false),
         privateIsNSISupports_(false),
         dontReportUncaught_(false),
         noDefaultCompartmentObject_(false),
         noScriptRval_(false),
         strictMode_(false),
-        baseline_(false),
-        typeInference_(false),
-        ion_(false),
-        asmJS_(false),
         cloneSingletons_(false)
     {
     }
 
     bool extraWarnings() const { return extraWarnings_; }
     ContextOptions &setExtraWarnings(bool flag) {
         extraWarnings_ = flag;
         return *this;
@@ -1532,56 +1591,16 @@ class JS_PUBLIC_API(ContextOptions) {
         strictMode_ = flag;
         return *this;
     }
     ContextOptions &toggleStrictMode() {
         strictMode_ = !strictMode_;
         return *this;
     }
 
-    bool baseline() const { return baseline_; }
-    ContextOptions &setBaseline(bool flag) {
-        baseline_ = flag;
-        return *this;
-    }
-    ContextOptions &toggleBaseline() {
-        baseline_ = !baseline_;
-        return *this;
-    }
-
-    bool typeInference() const { return typeInference_; }
-    ContextOptions &setTypeInference(bool flag) {
-        typeInference_ = flag;
-        return *this;
-    }
-    ContextOptions &toggleTypeInference() {
-        typeInference_ = !typeInference_;
-        return *this;
-    }
-
-    bool ion() const { return ion_; }
-    ContextOptions &setIon(bool flag) {
-        ion_ = flag;
-        return *this;
-    }
-    ContextOptions &toggleIon() {
-        ion_ = !ion_;
-        return *this;
-    }
-
-    bool asmJS() const { return asmJS_; }
-    ContextOptions &setAsmJS(bool flag) {
-        asmJS_ = flag;
-        return *this;
-    }
-    ContextOptions &toggleAsmJS() {
-        asmJS_ = !asmJS_;
-        return *this;
-    }
-
     bool cloneSingletons() const { return cloneSingletons_; }
     ContextOptions &setCloneSingletons(bool flag) {
         cloneSingletons_ = flag;
         return *this;
     }
     ContextOptions &toggleCloneSingletons() {
         cloneSingletons_ = !cloneSingletons_;
         return *this;
@@ -1591,20 +1610,16 @@ class JS_PUBLIC_API(ContextOptions) {
     bool extraWarnings_ : 1;
     bool werror_ : 1;
     bool varObjFix_ : 1;
     bool privateIsNSISupports_ : 1;
     bool dontReportUncaught_ : 1;
     bool noDefaultCompartmentObject_ : 1;
     bool noScriptRval_ : 1;
     bool strictMode_ : 1;
-    bool baseline_ : 1;
-    bool typeInference_ : 1;
-    bool ion_ : 1;
-    bool asmJS_ : 1;
     bool cloneSingletons_ : 1;
 };
 
 JS_PUBLIC_API(ContextOptions &)
 ContextOptionsRef(JSContext *cx);
 
 class JS_PUBLIC_API(AutoSaveContextOptions) {
   public:
@@ -2641,28 +2656,16 @@ class JS_PUBLIC_API(CompartmentOptions)
     // allowed if this flag is set.  The invisibleToDebugger flag must also be
     // set for such compartments.
     bool mergeable() const { return mergeable_; }
     CompartmentOptions &setMergeable(bool flag) {
         mergeable_ = flag;
         return *this;
     }
 
-    bool baseline(JSContext *cx) const;
-    Override &baselineOverride() { return baselineOverride_; }
-
-    bool typeInference(const js::ExclusiveContext *cx) const;
-    Override &typeInferenceOverride() { return typeInferenceOverride_; }
-
-    bool ion(JSContext *cx) const;
-    Override &ionOverride() { return ionOverride_; }
-
-    bool asmJS(JSContext *cx) const;
-    Override &asmJSOverride() { return asmJSOverride_; }
-
     bool cloneSingletons(JSContext *cx) const;
     Override &cloneSingletonsOverride() { return cloneSingletonsOverride_; }
 
     void *zonePointer() const {
         JS_ASSERT(uintptr_t(zone_.pointer) > uintptr_t(JS::SystemZone));
         return zone_.pointer;
     }
     ZoneSpecifier zoneSpecifier() const { return zone_.spec; }
@@ -2675,20 +2678,16 @@ class JS_PUBLIC_API(CompartmentOptions)
     bool getSingletonsAsTemplates() const {
         return singletonsAsTemplates_;
     };
 
   private:
     JSVersion version_;
     bool invisibleToDebugger_;
     bool mergeable_;
-    Override baselineOverride_;
-    Override typeInferenceOverride_;
-    Override ionOverride_;
-    Override asmJSOverride_;
     Override cloneSingletonsOverride_;
     union {
         ZoneSpecifier spec;
         void *pointer; // js::Zone* is not exposed in the API.
     } zone_;
 
     // To XDR singletons, we need to ensure that all singletons are all used as
     // templates, by making JSOP_OBJECT return a clone of the JSScript
@@ -4713,20 +4712,20 @@ JS_NewObjectForConstructor(JSContext *cx
 extern JS_PUBLIC_API(void)
 JS_SetGCZeal(JSContext *cx, uint8_t zeal, uint32_t frequency);
 
 extern JS_PUBLIC_API(void)
 JS_ScheduleGC(JSContext *cx, uint32_t count);
 #endif
 
 extern JS_PUBLIC_API(void)
-JS_SetParallelParsingEnabled(JSContext *cx, bool enabled);
+JS_SetParallelParsingEnabled(JSRuntime *rt, bool enabled);
 
 extern JS_PUBLIC_API(void)
-JS_SetParallelIonCompilationEnabled(JSContext *cx, bool enabled);
+JS_SetParallelIonCompilationEnabled(JSRuntime *rt, bool enabled);
 
 #define JIT_COMPILER_OPTIONS(Register)                             \
   Register(BASELINE_USECOUNT_TRIGGER, "baseline.usecount.trigger") \
   Register(ION_USECOUNT_TRIGGER, "ion.usecount.trigger")           \
   Register(ION_ENABLE, "ion.enable")                               \
   Register(BASELINE_ENABLE, "baseline.enable")
 
 typedef enum JSJitCompilerOption {
@@ -4735,19 +4734,19 @@ typedef enum JSJitCompilerOption {
 
     JIT_COMPILER_OPTIONS(JIT_COMPILER_DECLARE)
 #undef JIT_COMPILER_DECLARE
 
     JSJITCOMPILER_NOT_AN_OPTION
 } JSJitCompilerOption;
 
 extern JS_PUBLIC_API(void)
-JS_SetGlobalJitCompilerOption(JSContext *cx, JSJitCompilerOption opt, uint32_t value);
+JS_SetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt, uint32_t value);
 extern JS_PUBLIC_API(int)
-JS_GetGlobalJitCompilerOption(JSContext *cx, JSJitCompilerOption opt);
+JS_GetGlobalJitCompilerOption(JSRuntime *rt, JSJitCompilerOption opt);
 
 /*
  * Convert a uint32_t index into a jsid.
  */
 extern JS_PUBLIC_API(bool)
 JS_IndexToId(JSContext *cx, uint32_t index, JS::MutableHandleId);
 
 /*
--- a/js/src/jscntxt.h
+++ b/js/src/jscntxt.h
@@ -1031,16 +1031,17 @@ bool intrinsic_IsPackedArray(JSContext *
 
 bool intrinsic_ShouldForceSequential(JSContext *cx, unsigned argc, Value *vp);
 bool intrinsic_NewParallelArray(JSContext *cx, unsigned argc, Value *vp);
 bool intrinsic_ForkJoinGetSlice(JSContext *cx, unsigned argc, Value *vp);
 bool intrinsic_InParallelSection(JSContext *cx, unsigned argc, Value *vp);
 
 bool intrinsic_ObjectIsTransparentTypedObject(JSContext *cx, unsigned argc, Value *vp);
 bool intrinsic_ObjectIsOpaqueTypedObject(JSContext *cx, unsigned argc, Value *vp);
+bool intrinsic_ObjectIsTypeDescr(JSContext *cx, unsigned argc, Value *vp);
 
 class AutoLockForExclusiveAccess
 {
 #ifdef JS_THREADSAFE
     JSRuntime *runtime;
 
     void init(JSRuntime *rt) {
         runtime = rt;
--- a/js/src/jscompartment.h
+++ b/js/src/jscompartment.h
@@ -516,17 +516,17 @@ class js::AutoDebugModeInvalidation
     }
 };
 
 namespace js {
 
 inline bool
 ExclusiveContext::typeInferenceEnabled() const
 {
-    return compartment_->options().typeInference(this);
+    return zone()->types.inferenceEnabled;
 }
 
 inline js::Handle<js::GlobalObject*>
 ExclusiveContext::global() const
 {
     /*
      * It's safe to use |unsafeGet()| here because any compartment that is
      * on-stack will be marked automatically, so there's no need for a read
--- a/js/src/jsinfer.cpp
+++ b/js/src/jsinfer.cpp
@@ -1693,16 +1693,47 @@ TemporaryTypeSet::getKnownClass()
         if (clasp && clasp != nclasp)
             return nullptr;
         clasp = nclasp;
     }
 
     return clasp;
 }
 
+TemporaryTypeSet::ForAllResult
+TemporaryTypeSet::forAllClasses(bool (*func)(const Class* clasp))
+{
+    if (unknownObject())
+        return ForAllResult::MIXED;
+
+    unsigned count = getObjectCount();
+    if (count == 0)
+        return ForAllResult::EMPTY;
+
+    bool true_results = false;
+    bool false_results = false;
+    for (unsigned i = 0; i < count; i++) {
+        const Class *clasp = getObjectClass(i);
+        if (!clasp)
+            return ForAllResult::MIXED;
+        if (func(clasp)) {
+            true_results = true;
+            if (false_results) return ForAllResult::MIXED;
+        }
+        else {
+            false_results = true;
+            if (true_results) return ForAllResult::MIXED;
+        }
+    }
+
+    JS_ASSERT(true_results != false_results);
+
+    return true_results ? ForAllResult::ALL_TRUE : ForAllResult::ALL_FALSE;
+}
+
 int
 TemporaryTypeSet::getTypedArrayType()
 {
     const Class *clasp = getKnownClass();
 
     if (clasp && IsTypedArrayClass(clasp))
         return clasp - &TypedArrayObject::classes[0];
     return ScalarTypeDescr::TYPE_MAX;
@@ -1826,17 +1857,17 @@ TypeCompartment::TypeCompartment()
 {
     PodZero(this);
 }
 
 void
 TypeZone::init(JSContext *cx)
 {
     if (!cx ||
-        !cx->options().typeInference() ||
+        !cx->runtime()->options().typeInference() ||
         !cx->runtime()->jitSupportsFloatingPoint)
     {
         return;
     }
 
     inferenceEnabled = true;
 }
 
--- a/js/src/jsinfer.h
+++ b/js/src/jsinfer.h
@@ -668,16 +668,31 @@ class TemporaryTypeSet : public TypeSet
     }
 
     /* Whether the type set contains objects with any of a set of flags. */
     bool hasObjectFlags(CompilerConstraintList *constraints, TypeObjectFlags flags);
 
     /* Get the class shared by all objects in this set, or nullptr. */
     const Class *getKnownClass();
 
+    /* Result returned from forAllClasses */
+    enum ForAllResult {
+        EMPTY=1,                // Set empty
+        ALL_TRUE,               // Set not empty and predicate returned true for all classes
+        ALL_FALSE,              // Set not empty and predicate returned false for all classes
+        MIXED,                  // Set not empty and predicate returned false for some classes
+                                // and true for others, or set contains an unknown or non-object
+                                // type
+    };
+
+    /* Apply func to the members of the set and return an appropriate result.
+     * The iteration may end early if the result becomes known early.
+     */
+    ForAllResult forAllClasses(bool (*func)(const Class *clasp));
+
     /* Get the prototype shared by all objects in this set, or nullptr. */
     JSObject *getCommonPrototype();
 
     /* Get the typed array type of all objects in this set, or TypedArrayObject::TYPE_MAX. */
     int getTypedArrayType();
 
     /* Whether all objects have JSCLASS_IS_DOMJSCLASS set. */
     bool isDOMClass();
--- a/js/src/jsmath.cpp
+++ b/js/src/jsmath.cpp
@@ -33,24 +33,24 @@
 #include "jsobjinlines.h"
 
 using namespace js;
 
 using mozilla::Abs;
 using mozilla::NumberEqualsInt32;
 using mozilla::NumberIsInt32;
 using mozilla::ExponentComponent;
+using mozilla::FloatingPoint;
 using mozilla::IsFinite;
 using mozilla::IsInfinite;
 using mozilla::IsNaN;
 using mozilla::IsNegative;
 using mozilla::IsNegativeZero;
 using mozilla::PositiveInfinity;
 using mozilla::NegativeInfinity;
-using mozilla::SpecificNaN;
 using JS::ToNumber;
 using JS::GenericNaN;
 
 static const JSConstDoubleSpec math_constants[] = {
     {M_E,       "E",            0, {0,0,0}},
     {M_LOG2E,   "LOG2E",        0, {0,0,0}},
     {M_LOG10E,  "LOG10E",       0, {0,0,0}},
     {M_LN2,     "LN2",          0, {0,0,0}},
@@ -740,27 +740,41 @@ js_math_random(JSContext *cx, unsigned a
     double z = random_nextDouble(cx);
     args.rval().setDouble(z);
     return true;
 }
 
 double
 js::math_round_impl(double x)
 {
-    int32_t i;
-    if (NumberIsInt32(x, &i))
-        return double(i);
+    int32_t ignored;
+    if (NumberIsInt32(x, &ignored))
+        return x;
 
     /* Some numbers are so big that adding 0.5 would give the wrong number. */
-    if (ExponentComponent(x) >= 52)
+    if (ExponentComponent(x) >= int_fast16_t(FloatingPoint<double>::ExponentShift))
         return x;
 
     return js_copysign(floor(x + 0.5), x);
 }
 
+float
+js::math_roundf_impl(float x)
+{
+    int32_t ignored;
+    if (NumberIsInt32(x, &ignored))
+        return x;
+
+    /* Some numbers are so big that adding 0.5 would give the wrong number. */
+    if (ExponentComponent(x) >= int_fast16_t(FloatingPoint<float>::ExponentShift))
+        return x;
+
+    return js_copysign(floorf(x + 0.5f), x);
+}
+
 bool /* ES5 15.8.2.15. */
 js::math_round(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
     if (args.length() == 0) {
         args.rval().setNaN();
         return true;
--- a/js/src/jsmath.h
+++ b/js/src/jsmath.h
@@ -260,16 +260,19 @@ extern double
 math_floor_impl(double x);
 
 extern bool
 math_round(JSContext *cx, unsigned argc, Value *vp);
 
 extern double
 math_round_impl(double x);
 
+extern float
+math_roundf_impl(float x);
+
 extern double
 powi(double x, int y);
 
 extern double
 ecmaPow(double x, double y);
 
 extern bool
 math_imul(JSContext *cx, unsigned argc, Value *vp);
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -113,21 +113,17 @@ static size_t gMaxStackSize = 128 * size
  * Limit the timeout to 30 minutes to prevent an overflow on platfoms
  * that represent the time internally in microseconds using 32-bit int.
  */
 static double MAX_TIMEOUT_INTERVAL = 1800.0;
 static double gTimeoutInterval = -1.0;
 static volatile bool gTimedOut = false;
 static JS::Value gTimeoutFunc;
 
-static bool enableTypeInference = true;
 static bool enableDisassemblyDumps = false;
-static bool enableIon = true;
-static bool enableBaseline = true;
-static bool enableAsmJS = true;
 
 static bool printTiming = false;
 static const char *jsCacheDir = nullptr;
 static const char *jsCacheAsmJSPath = nullptr;
 static bool jsCachingEnabled = true;
 mozilla::Atomic<bool> jsCacheOpened(false);
 
 static bool
@@ -647,31 +643,32 @@ ResolvePath(JSContext *cx, HandleString 
     return JS_NewStringCopyZ(cx, buffer);
 }
 
 static bool
 Options(JSContext *cx, unsigned argc, jsval *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
 
-    JS::ContextOptions oldOptions = JS::ContextOptionsRef(cx);
+    JS::RuntimeOptions oldRuntimeOptions = JS::RuntimeOptionsRef(cx);
+    JS::ContextOptions oldContextOptions = JS::ContextOptionsRef(cx);
     for (unsigned i = 0; i < args.length(); i++) {
         JSString *str = JS::ToString(cx, args[i]);
         if (!str)
             return false;
         args[i].setString(str);
 
         JSAutoByteString opt(cx, str);
         if (!opt)
             return false;
 
         if (strcmp(opt.ptr(), "strict") == 0)
             JS::ContextOptionsRef(cx).toggleExtraWarnings();
         else if (strcmp(opt.ptr(), "typeinfer") == 0)
-            JS::ContextOptionsRef(cx).toggleTypeInference();
+            JS::RuntimeOptionsRef(cx).toggleTypeInference();
         else if (strcmp(opt.ptr(), "werror") == 0)
             JS::ContextOptionsRef(cx).toggleWerror();
         else if (strcmp(opt.ptr(), "strict_mode") == 0)
             JS::ContextOptionsRef(cx).toggleStrictMode();
         else {
             char* msg = JS_sprintf_append(nullptr,
                                           "unknown option name '%s'."
                                           " The valid names are strict,"
@@ -685,29 +682,29 @@ Options(JSContext *cx, unsigned argc, js
             JS_ReportError(cx, msg);
             free(msg);
             return false;
         }
     }
 
     char *names = strdup("");
     bool found = false;
-    if (!names && oldOptions.extraWarnings()) {
+    if (!names && oldContextOptions.extraWarnings()) {
         names = JS_sprintf_append(names, "%s%s", found ? "," : "", "strict");
         found = true;
     }
-    if (!names && oldOptions.typeInference()) {
+    if (!names && oldRuntimeOptions.typeInference()) {
         names = JS_sprintf_append(names, "%s%s", found ? "," : "", "typeinfer");
         found = true;
     }
-    if (!names && oldOptions.werror()) {
+    if (!names && oldContextOptions.werror()) {
         names = JS_sprintf_append(names, "%s%s", found ? "," : "", "werror");
         found = true;
     }
-    if (!names && oldOptions.strictMode()) {
+    if (!names && oldContextOptions.strictMode()) {
         names = JS_sprintf_append(names, "%s%s", found ? "," : "", "strict_mode");
         found = true;
     }
     if (!names) {
         JS_ReportOutOfMemory(cx);
         return false;
     }
 
@@ -5480,24 +5477,16 @@ NewContext(JSRuntime *rt)
     JSShellContextData *data = NewContextData();
     if (!data) {
         DestroyContext(cx, false);
         return nullptr;
     }
 
     JS_SetContextPrivate(cx, data);
     JS_SetErrorReporter(cx, my_ErrorReporter);
-    if (enableTypeInference)
-        JS::ContextOptionsRef(cx).toggleTypeInference();
-    if (enableIon)
-        JS::ContextOptionsRef(cx).toggleIon();
-    if (enableBaseline)
-        JS::ContextOptionsRef(cx).toggleBaseline();
-    if (enableAsmJS)
-        JS::ContextOptionsRef(cx).toggleAsmJS();
     return cx;
 }
 
 static void
 DestroyContext(JSContext *cx, bool withGC)
 {
     JSShellContextData *data = GetContextData(cx);
     JS_SetContextPrivate(cx, nullptr);
@@ -5589,202 +5578,37 @@ BindScriptArgs(JSContext *cx, JSObject *
 
     return true;
 }
 
 // This function is currently only called from "#if defined(JS_ION)" chunks,
 // so we're guarding the function definition with an #ifdef, too, to avoid
 // build warning for unused function in non-ion-enabled builds:
 #if defined(JS_ION)
-static int
+static bool
 OptionFailure(const char *option, const char *str)
 {
     fprintf(stderr, "Unrecognized option for %s: %s\n", option, str);
-    return EXIT_FAILURE;
+    return false;
 }
 #endif /* JS_ION */
 
 static int
 ProcessArgs(JSContext *cx, JSObject *obj_, OptionParser *op)
 {
     RootedObject obj(cx, obj_);
 
-    if (op->getBoolOption('c'))
-        compileOnly = true;
-
-    if (op->getBoolOption('w'))
-        reportWarnings = true;
-    else if (op->getBoolOption('W'))
-        reportWarnings = false;
-
     if (op->getBoolOption('s'))
         JS::ContextOptionsRef(cx).toggleExtraWarnings();
 
     if (op->getBoolOption('d')) {
         JS_SetRuntimeDebugMode(JS_GetRuntime(cx), true);
         JS_SetDebugMode(cx, true);
     }
 
-    jsCacheDir = op->getStringOption("js-cache");
-    if (jsCacheDir) {
-        if (op->getBoolOption("js-cache-per-process"))
-            jsCacheDir = JS_smprintf("%s/%u", jsCacheDir, (unsigned)getpid());
-        jsCacheAsmJSPath = JS_smprintf("%s/asmjs.cache", jsCacheDir);
-    }
-
-    if (op->getBoolOption('b'))
-        printTiming = true;
-
-    if (op->getBoolOption('D')) {
-        cx->runtime()->profilingScripts = true;
-        enableDisassemblyDumps = true;
-    }
-
-#ifdef JS_THREADSAFE
-    int32_t threadCount = op->getIntOption("thread-count");
-    if (threadCount >= 0)
-        SetFakeCPUCount(threadCount);
-#endif /* JS_THREADSAFE */
-
-#if defined(JS_ION)
-    if (op->getBoolOption("no-ion")) {
-        enableIon = false;
-        JS::ContextOptionsRef(cx).toggleIon();
-    }
-    if (op->getBoolOption("no-asmjs")) {
-        enableAsmJS = false;
-        JS::ContextOptionsRef(cx).toggleAsmJS();
-    }
-
-    if (op->getBoolOption("no-baseline")) {
-        enableBaseline = false;
-        JS::ContextOptionsRef(cx).toggleBaseline();
-    }
-
-    if (const char *str = op->getStringOption("ion-gvn")) {
-        if (strcmp(str, "off") == 0) {
-            jit::js_JitOptions.disableGvn = true;
-        } else if (strcmp(str, "pessimistic") == 0) {
-            jit::js_JitOptions.forceGvnKind = true;
-            jit::js_JitOptions.forcedGvnKind = jit::GVN_Pessimistic;
-        } else if (strcmp(str, "optimistic") == 0) {
-            jit::js_JitOptions.forceGvnKind = true;
-            jit::js_JitOptions.forcedGvnKind = jit::GVN_Optimistic;
-        } else {
-            return OptionFailure("ion-gvn", str);
-        }
-    }
-
-    if (const char *str = op->getStringOption("ion-licm")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.disableLicm = false;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.disableLicm = true;
-        else
-            return OptionFailure("ion-licm", str);
-    }
-
-    if (const char *str = op->getStringOption("ion-edgecase-analysis")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.disableEdgeCaseAnalysis = false;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.disableEdgeCaseAnalysis = true;
-        else
-            return OptionFailure("ion-edgecase-analysis", str);
-    }
-
-     if (const char *str = op->getStringOption("ion-range-analysis")) {
-         if (strcmp(str, "on") == 0)
-             jit::js_JitOptions.disableRangeAnalysis = false;
-         else if (strcmp(str, "off") == 0)
-             jit::js_JitOptions.disableRangeAnalysis = true;
-         else
-             return OptionFailure("ion-range-analysis", str);
-     }
-
-    if (op->getBoolOption("ion-check-range-analysis"))
-        jit::js_JitOptions.checkRangeAnalysis = true;
-
-    if (const char *str = op->getStringOption("ion-inlining")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.disableInlining = false;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.disableInlining = true;
-        else
-            return OptionFailure("ion-inlining", str);
-    }
-
-    if (const char *str = op->getStringOption("ion-osr")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.osr = true;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.osr = false;
-        else
-            return OptionFailure("ion-osr", str);
-    }
-
-    if (const char *str = op->getStringOption("ion-limit-script-size")) {
-        if (strcmp(str, "on") == 0)
-            jit::js_JitOptions.limitScriptSize = true;
-        else if (strcmp(str, "off") == 0)
-            jit::js_JitOptions.limitScriptSize = false;
-        else
-            return OptionFailure("ion-limit-script-size", str);
-    }
-
-    int32_t useCount = op->getIntOption("ion-uses-before-compile");
-    if (useCount >= 0)
-        jit::js_JitOptions.setUsesBeforeCompile(useCount);
-
-    useCount = op->getIntOption("baseline-uses-before-compile");
-    if (useCount >= 0)
-        jit::js_JitOptions.baselineUsesBeforeCompile = useCount;
-
-    if (op->getBoolOption("baseline-eager"))
-        jit::js_JitOptions.baselineUsesBeforeCompile = 0;
-
-    if (const char *str = op->getStringOption("ion-regalloc")) {
-        if (strcmp(str, "lsra") == 0) {
-            jit::js_JitOptions.forceRegisterAllocator = true;
-            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_LSRA;
-        } else if (strcmp(str, "backtracking") == 0) {
-            jit::js_JitOptions.forceRegisterAllocator = true;
-            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_Backtracking;
-        } else if (strcmp(str, "stupid") == 0) {
-            jit::js_JitOptions.forceRegisterAllocator = true;
-            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_Stupid;
-        } else {
-            return OptionFailure("ion-regalloc", str);
-        }
-    }
-
-    if (op->getBoolOption("ion-eager"))
-        jit::js_JitOptions.setEagerCompilation();
-
-    if (op->getBoolOption("ion-compile-try-catch"))
-        jit::js_JitOptions.compileTryCatch = true;
-
-    bool parallelCompilation = true;
-    if (const char *str = op->getStringOption("ion-parallel-compile")) {
-        if (strcmp(str, "off") == 0)
-            parallelCompilation = false;
-        else if (strcmp(str, "on") != 0)
-            return OptionFailure("ion-parallel-compile", str);
-    }
-#ifdef JS_THREADSAFE
-    cx->runtime()->setParallelIonCompilationEnabled(parallelCompilation);
-#endif
-
-#endif /* JS_ION */
-
-#ifdef DEBUG
-    if (op->getBoolOption("dump-entrained-variables"))
-        dumpEntrainedVariables = true;
-#endif
-
     /* |scriptArgs| gets bound on the global before any code is run. */
     if (!BindScriptArgs(cx, obj, op))
         return EXIT_FAILURE;
 
     MultiStringRange filePaths = op->getMultiStringOption('f');
     MultiStringRange codeChunks = op->getMultiStringOption('e');
 
     if (filePaths.empty() && codeChunks.empty() && !op->getStringArg("script")) {
@@ -5818,30 +5642,201 @@ ProcessArgs(JSContext *cx, JSObject *obj
     }
 
     if (op->getBoolOption('i'))
         Process(cx, obj, nullptr, true);
 
     return gExitCode ? gExitCode : EXIT_SUCCESS;
 }
 
+static bool
+SetRuntimeOptions(JSRuntime *rt, const OptionParser &op)
+{
+#if defined(JS_ION)
+    bool enableBaseline = !op.getBoolOption("no-baseline");
+    bool enableIon = !op.getBoolOption("no-ion");
+    bool enableTypeInference = !op.getBoolOption("no-ti");
+    bool enableAsmJS = !op.getBoolOption("no-asmjs");
+
+    JS::RuntimeOptionsRef(rt).setBaseline(enableBaseline)
+                             .setIon(enableIon)
+                             .setTypeInference(enableTypeInference)
+                             .setAsmJS(enableAsmJS);
+
+    if (const char *str = op.getStringOption("ion-gvn")) {
+        if (strcmp(str, "off") == 0) {
+            jit::js_JitOptions.disableGvn = true;
+        } else if (strcmp(str, "pessimistic") == 0) {
+            jit::js_JitOptions.forceGvnKind = true;
+            jit::js_JitOptions.forcedGvnKind = jit::GVN_Pessimistic;
+        } else if (strcmp(str, "optimistic") == 0) {
+            jit::js_JitOptions.forceGvnKind = true;
+            jit::js_JitOptions.forcedGvnKind = jit::GVN_Optimistic;
+        } else {
+            return OptionFailure("ion-gvn", str);
+        }
+    }
+
+    if (const char *str = op.getStringOption("ion-licm")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.disableLicm = false;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.disableLicm = true;
+        else
+            return OptionFailure("ion-licm", str);
+    }
+
+    if (const char *str = op.getStringOption("ion-edgecase-analysis")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.disableEdgeCaseAnalysis = false;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.disableEdgeCaseAnalysis = true;
+        else
+            return OptionFailure("ion-edgecase-analysis", str);
+    }
+
+     if (const char *str = op.getStringOption("ion-range-analysis")) {
+         if (strcmp(str, "on") == 0)
+             jit::js_JitOptions.disableRangeAnalysis = false;
+         else if (strcmp(str, "off") == 0)
+             jit::js_JitOptions.disableRangeAnalysis = true;
+         else
+             return OptionFailure("ion-range-analysis", str);
+     }
+
+    if (op.getBoolOption("ion-check-range-analysis"))
+        jit::js_JitOptions.checkRangeAnalysis = true;
+
+    if (const char *str = op.getStringOption("ion-inlining")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.disableInlining = false;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.disableInlining = true;
+        else
+            return OptionFailure("ion-inlining", str);
+    }
+
+    if (const char *str = op.getStringOption("ion-osr")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.osr = true;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.osr = false;
+        else
+            return OptionFailure("ion-osr", str);
+    }
+
+    if (const char *str = op.getStringOption("ion-limit-script-size")) {
+        if (strcmp(str, "on") == 0)
+            jit::js_JitOptions.limitScriptSize = true;
+        else if (strcmp(str, "off") == 0)
+            jit::js_JitOptions.limitScriptSize = false;
+        else
+            return OptionFailure("ion-limit-script-size", str);
+    }
+
+    int32_t useCount = op.getIntOption("ion-uses-before-compile");
+    if (useCount >= 0)
+        jit::js_JitOptions.setUsesBeforeCompile(useCount);
+
+    useCount = op.getIntOption("baseline-uses-before-compile");
+    if (useCount >= 0)
+        jit::js_JitOptions.baselineUsesBeforeCompile = useCount;
+
+    if (op.getBoolOption("baseline-eager"))
+        jit::js_JitOptions.baselineUsesBeforeCompile = 0;
+
+    if (const char *str = op.getStringOption("ion-regalloc")) {
+        if (strcmp(str, "lsra") == 0) {
+            jit::js_JitOptions.forceRegisterAllocator = true;
+            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_LSRA;
+        } else if (strcmp(str, "backtracking") == 0) {
+            jit::js_JitOptions.forceRegisterAllocator = true;
+            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_Backtracking;
+        } else if (strcmp(str, "stupid") == 0) {
+            jit::js_JitOptions.forceRegisterAllocator = true;
+            jit::js_JitOptions.forcedRegisterAllocator = jit::RegisterAllocator_Stupid;
+        } else {
+            return OptionFailure("ion-regalloc", str);
+        }
+    }
+
+    if (op.getBoolOption("ion-eager"))
+        jit::js_JitOptions.setEagerCompilation();
+
+    if (op.getBoolOption("ion-compile-try-catch"))
+        jit::js_JitOptions.compileTryCatch = true;
+
+    bool parallelCompilation = true;
+    if (const char *str = op.getStringOption("ion-parallel-compile")) {
+        if (strcmp(str, "off") == 0)
+            parallelCompilation = false;
+        else if (strcmp(str, "on") != 0)
+            return OptionFailure("ion-parallel-compile", str);
+    }
+#ifdef JS_THREADSAFE
+    rt->setParallelIonCompilationEnabled(parallelCompilation);
+#endif
+
+#if defined(JS_CODEGEN_X86) && defined(DEBUG)
+    if (op.getBoolOption("no-fpu"))
+        JSC::MacroAssembler::SetFloatingPointDisabled();
+#endif
+
+#if (defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)) && defined(DEBUG)
+    if (op.getBoolOption("no-sse3")) {
+        JSC::MacroAssembler::SetSSE3Disabled();
+        PropagateFlagToNestedShells("--no-sse3");
+    }
+    if (op.getBoolOption("no-sse4")) {
+        JSC::MacroAssembler::SetSSE4Disabled();
+        PropagateFlagToNestedShells("--no-sse4");
+    }
+#endif
+
+#endif // JS_ION
+
+#ifdef JS_ARM_SIMULATOR
+    if (op.getBoolOption("arm-sim-icache-checks"))
+        jit::Simulator::ICacheCheckingEnabled = true;
+
+    int32_t stopAt = op.getIntOption("arm-sim-stop-at");
+    if (stopAt >= 0)
+        jit::Simulator::StopSimAt = stopAt;
+#endif
+
+    reportWarnings = op.getBoolOption('w');
+    compileOnly = op.getBoolOption('c');
+    printTiming = op.getBoolOption('b');
+    rt->profilingScripts = enableDisassemblyDumps = op.getBoolOption('D');
+
+    jsCacheDir = op.getStringOption("js-cache");
+    if (jsCacheDir) {
+        if (op.getBoolOption("js-cache-per-process"))
+            jsCacheDir = JS_smprintf("%s/%u", jsCacheDir, (unsigned)getpid());
+        jsCacheAsmJSPath = JS_smprintf("%s/asmjs.cache", jsCacheDir);
+    }
+
+#ifdef JS_THREADSAFE
+    int32_t threadCount = op.getIntOption("thread-count");
+    if (threadCount >= 0)
+        SetFakeCPUCount(threadCount);
+#endif /* JS_THREADSAFE */
+
+#ifdef DEBUG
+    dumpEntrainedVariables = op.getBoolOption("dump-entrained-variables");
+#endif
+
+    return true;
+}
+
 static int
 Shell(JSContext *cx, OptionParser *op, char **envp)
 {
     JSAutoRequest ar(cx);
 
-    /*
-     * First check to see if type inference is enabled. These flags
-     * must be set on the compartment when it is constructed.
-     */
-    if (op->getBoolOption("no-ti")) {
-        enableTypeInference = false;
-        JS::ContextOptionsRef(cx).toggleTypeInference();
-    }
-
     if (op->getBoolOption("fuzzing-safe"))
         fuzzingSafe = true;
     else
         fuzzingSafe = (getenv("MOZ_FUZZING_SAFE") && getenv("MOZ_FUZZING_SAFE")[0] != '0');
 
     RootedObject glob(cx);
     JS::CompartmentOptions options;
     options.setVersion(JSVERSION_LATEST);
@@ -6047,53 +6042,31 @@ main(int argc, char **argv, char **envp)
     if (op.getHelpOption())
         return EXIT_SUCCESS;
 
 #ifdef DEBUG
     /*
      * Process OOM options as early as possible so that we can observe as many
      * allocations as possible.
      */
-    if (op.getBoolOption('O'))
-        OOM_printAllocationCount = true;
-
-#if defined(JS_CODEGEN_X86) && defined(JS_ION)
-    if (op.getBoolOption("no-fpu"))
-        JSC::MacroAssembler::SetFloatingPointDisabled();
-#endif
-
-#if (defined(JS_CODEGEN_X86) || defined(JS_CODEGEN_X64)) && defined(JS_ION)
-    if (op.getBoolOption("no-sse3")) {
-        JSC::MacroAssembler::SetSSE3Disabled();
-        PropagateFlagToNestedShells("--no-sse3");
-    }
-    if (op.getBoolOption("no-sse4")) {
-        JSC::MacroAssembler::SetSSE4Disabled();
-        PropagateFlagToNestedShells("--no-sse4");
-    }
-#endif
-#endif
-
-#ifdef JS_ARM_SIMULATOR
-    if (op.getBoolOption("arm-sim-icache-checks"))
-        jit::Simulator::ICacheCheckingEnabled = true;
-
-    int32_t stopAt = op.getIntOption("arm-sim-stop-at");
-    if (stopAt >= 0)
-        jit::Simulator::StopSimAt = stopAt;
+    OOM_printAllocationCount = op.getBoolOption('O');
 #endif
 
     // Start the engine.
     if (!JS_Init())
         return 1;
 
     /* Use the same parameters as the browser in xpcjsruntime.cpp. */
     rt = JS_NewRuntime(32L * 1024L * 1024L, JS_USE_HELPER_THREADS);
     if (!rt)
         return 1;
+
+    if (!SetRuntimeOptions(rt, op))
+        return 1;
+
     gTimeoutFunc = NullValue();
     if (!JS_AddNamedValueRootRT(rt, &gTimeoutFunc, "gTimeoutFunc"))
         return 1;
 
     JS_SetGCParameter(rt, JSGC_MAX_BYTES, 0xffffffff);
 #ifdef JSGC_GENERATIONAL
     Maybe<JS::AutoDisableGenerationalGC> noggc;
     if (op.getBoolOption("no-ggc"))
--- a/js/src/vm/Runtime.h
+++ b/js/src/vm/Runtime.h
@@ -1689,16 +1689,17 @@ struct JSRuntime : public JS::shadow::Ru
         TriggerCallbackAnyThreadForkJoin
     };
 
     void triggerOperationCallback(OperationCallbackTrigger trigger);
 
     void addSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf, JS::RuntimeSizes *runtime);
 
   private:
+    JS::RuntimeOptions options_;
 
     JSUseHelperThreads useHelperThreads_;
 
     // Settings for how helper threads can be used.
     bool parallelIonCompilationEnabled_;
     bool parallelParsingEnabled_;
 
     // True iff this is a DOM Worker runtime.
@@ -1736,16 +1737,23 @@ struct JSRuntime : public JS::shadow::Ru
 
     void setIsWorkerRuntime() {
         isWorkerRuntime_ = true;
     }
     bool isWorkerRuntime() const {
         return isWorkerRuntime_;
     }
 
+    const JS::RuntimeOptions &options() const {
+        return options_;
+    }
+    JS::RuntimeOptions &options() {
+        return options_;
+    }
+
 #ifdef DEBUG
   public:
     js::AutoEnterPolicy *enteredPolicy;
 #endif
 
     /* See comment for JS::SetLargeAllocationFailureCallback in jsapi.h. */
     JS::LargeAllocationFailureCallback largeAllocationFailureCallback;
     /* See comment for JS::SetOutOfMemoryCallback in jsapi.h. */
--- a/js/src/vm/SelfHosting.cpp
+++ b/js/src/vm/SelfHosting.cpp
@@ -477,17 +477,17 @@ js::intrinsic_HaveSameClass(JSContext *c
 bool
 js::intrinsic_IsPackedArray(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     JS_ASSERT(args.length() == 1);
     JS_ASSERT(args[0].isObject());
 
     JSObject *obj = &args[0].toObject();
-    bool isPacked = obj->is<ArrayObject>() &&
+    bool isPacked = obj->is<ArrayObject>() && !obj->hasLazyType() &&
                     !obj->type()->hasAllFlags(types::OBJECT_FLAG_NON_PACKED) &&
                     obj->getDenseInitializedLength() == obj->as<ArrayObject>().length();
 
     args.rval().setBoolean(isPacked);
     return true;
 }
 
 static bool
@@ -630,16 +630,22 @@ js::intrinsic_ObjectIsTransparentTypedOb
 }
 
 bool
 js::intrinsic_ObjectIsOpaqueTypedObject(JSContext *cx, unsigned argc, Value *vp)
 {
     return js::ObjectIsOpaqueTypedObject(cx, argc, vp);
 }
 
+bool
+js::intrinsic_ObjectIsTypeDescr(JSContext *cx, unsigned argc, Value *vp)
+{
+    return js::ObjectIsTypeDescr(cx, argc, vp);
+}
+
 /**
  * Returns the default locale as a well-formed, but not necessarily canonicalized,
  * BCP-47 language tag.
  */
 static bool
 intrinsic_RuntimeDefaultLocale(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
@@ -707,17 +713,17 @@ static const JSFunctionSpec intrinsic_fu
           3, 0),
     JS_FNINFO("AttachTypedObject",
               JSNativeThreadSafeWrapper<js::AttachTypedObject>,
               &js::AttachTypedObjectJitInfo, 5, 0),
     JS_FNINFO("SetTypedObjectOffset",
               JSNativeThreadSafeWrapper<js::SetTypedObjectOffset>,
               &js::SetTypedObjectOffsetJitInfo, 2, 0),
     JS_FNINFO("ObjectIsTypeDescr",
-              JSNativeThreadSafeWrapper<js::ObjectIsTypeDescr>,
+              intrinsic_ObjectIsTypeDescr,
               &js::ObjectIsTypeDescrJitInfo, 5, 0),
     JS_FNINFO("ObjectIsTransparentTypedObject",
               intrinsic_ObjectIsTransparentTypedObject,
               &js::ObjectIsTransparentTypedObjectJitInfo, 5, 0),
     JS_FNINFO("TypedObjectIsAttached",
               JSNativeThreadSafeWrapper<js::TypedObjectIsAttached>,
               &js::TypedObjectIsAttachedJitInfo, 1, 0),
     JS_FNINFO("ObjectIsOpaqueTypedObject",
--- a/js/xpconnect/src/XPCComponents.cpp
+++ b/js/xpconnect/src/XPCComponents.cpp
@@ -3240,36 +3240,51 @@ nsXPCComponents_Utils::Dispatch(HandleVa
                                                    getter_AddRefs(run));
     NS_ENSURE_SUCCESS(rv, rv);
     MOZ_ASSERT(run);
 
     // Dispatch.
     return NS_DispatchToMainThread(run);
 }
 
-#define GENERATE_JSOPTION_GETTER_SETTER(_attr, _getter, _setter)    \
-    NS_IMETHODIMP                                                   \
-    nsXPCComponents_Utils::Get## _attr(JSContext* cx, bool* aValue) \
-    {                                                               \
-        *aValue = ContextOptionsRef(cx)._getter();                  \
-        return NS_OK;                                               \
-    }                                                               \
-    NS_IMETHODIMP                                                   \
-    nsXPCComponents_Utils::Set## _attr(JSContext* cx, bool aValue)  \
-    {                                                               \
-        ContextOptionsRef(cx)._setter(aValue);                      \
-        return NS_OK;                                               \
+#define GENERATE_JSCONTEXTOPTION_GETTER_SETTER(_attr, _getter, _setter) \
+    NS_IMETHODIMP                                                       \
+    nsXPCComponents_Utils::Get## _attr(JSContext* cx, bool* aValue)     \
+    {                                                                   \
+        *aValue = ContextOptionsRef(cx)._getter();                      \
+        return NS_OK;                                                   \
+    }                                                                   \
+    NS_IMETHODIMP                                                       \
+    nsXPCComponents_Utils::Set## _attr(JSContext* cx, bool aValue)      \
+    {                                                                   \
+        ContextOptionsRef(cx)._setter(aValue);                          \
+        return NS_OK;                                                   \
     }
 
-GENERATE_JSOPTION_GETTER_SETTER(Strict, extraWarnings, setExtraWarnings)
-GENERATE_JSOPTION_GETTER_SETTER(Werror, werror, setWerror)
-GENERATE_JSOPTION_GETTER_SETTER(Strict_mode, strictMode, setStrictMode)
-GENERATE_JSOPTION_GETTER_SETTER(Ion, ion, setIon)
-
-#undef GENERATE_JSOPTION_GETTER_SETTER
+#define GENERATE_JSRUNTIMEOPTION_GETTER_SETTER(_attr, _getter, _setter) \
+    NS_IMETHODIMP                                                       \
+    nsXPCComponents_Utils::Get## _attr(JSContext* cx, bool* aValue)     \
+    {                                                                   \
+        *aValue = RuntimeOptionsRef(cx)._getter();                      \
+        return NS_OK;                                                   \
+    }                                                                   \
+    NS_IMETHODIMP                                                       \
+    nsXPCComponents_Utils::Set## _attr(JSContext* cx, bool aValue)      \
+    {                                                                   \
+        RuntimeOptionsRef(cx)._setter(aValue);                          \
+        return NS_OK;                                                   \
+    }
+
+GENERATE_JSCONTEXTOPTION_GETTER_SETTER(Strict, extraWarnings, setExtraWarnings)
+GENERATE_JSCONTEXTOPTION_GETTER_SETTER(Werror, werror, setWerror)
+GENERATE_JSCONTEXTOPTION_GETTER_SETTER(Strict_mode, strictMode, setStrictMode)
+GENERATE_JSRUNTIMEOPTION_GETTER_SETTER(Ion, ion, setIon)
+
+#undef GENERATE_JSCONTEXTOPTION_GETTER_SETTER
+#undef GENERATE_JSRUNTIMEOPTION_GETTER_SETTER
 
 NS_IMETHODIMP
 nsXPCComponents_Utils::SetGCZeal(int32_t aValue, JSContext* cx)
 {
 #ifdef JS_GC_ZEAL
     JS_SetGCZeal(cx, uint8_t(aValue), JS_DEFAULT_ZEAL_FREQ);
 #endif
     return NS_OK;
--- a/js/xpconnect/src/XPCJSRuntime.cpp
+++ b/js/xpconnect/src/XPCJSRuntime.cpp
@@ -41,16 +41,17 @@
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/WindowBinding.h"
 #include "mozilla/Attributes.h"
 #include "AccessCheck.h"
 #include "nsGlobalWindow.h"
 #include "nsAboutProtocolUtils.h"
 
 #include "GeckoProfiler.h"
+#include "nsIXULRuntime.h"
 #include "nsJSPrincipals.h"
 
 #ifdef MOZ_CRASHREPORTER
 #include "nsExceptionHandler.h"
 #endif
 
 using namespace mozilla;
 using namespace xpc;
@@ -1493,16 +1494,55 @@ void XPCJSRuntime::SystemIsBeingShutDown
 {
     DOM_ClearInterfaces();
 
     if (mDetachedWrappedNativeProtoMap)
         mDetachedWrappedNativeProtoMap->
             Enumerate(DetachedWrappedNativeProtoShutdownMarker, nullptr);
 }
 
+#define JS_OPTIONS_DOT_STR "javascript.options."
+
+static void
+ReloadPrefsCallback(const char *pref, void *data)
+{
+    XPCJSRuntime *runtime = reinterpret_cast<XPCJSRuntime *>(data);
+    JSRuntime *rt = runtime->Runtime();
+
+    bool safeMode = false;
+    nsCOMPtr<nsIXULRuntime> xr = do_GetService("@mozilla.org/xre/runtime;1");
+    if (xr) {
+        xr->GetInSafeMode(&safeMode);
+    }
+
+    bool useBaseline = Preferences::GetBool(JS_OPTIONS_DOT_STR "baselinejit") && !safeMode;
+    bool useTypeInference = Preferences::GetBool(JS_OPTIONS_DOT_STR "typeinference") && !safeMode;
+    bool useIon = Preferences::GetBool(JS_OPTIONS_DOT_STR "ion") && !safeMode;
+    bool useAsmJS = Preferences::GetBool(JS_OPTIONS_DOT_STR "asmjs") && !safeMode;
+
+    bool parallelParsing = Preferences::GetBool(JS_OPTIONS_DOT_STR "parallel_parsing");
+    bool parallelIonCompilation = Preferences::GetBool(JS_OPTIONS_DOT_STR
+                                                       "ion.parallel_compilation");
+    bool useBaselineEager = Preferences::GetBool(JS_OPTIONS_DOT_STR
+                                                 "baselinejit.unsafe_eager_compilation");
+    bool useIonEager = Preferences::GetBool(JS_OPTIONS_DOT_STR "ion.unsafe_eager_compilation");
+
+    JS::RuntimeOptionsRef(rt).setBaseline(useBaseline)
+                             .setTypeInference(useTypeInference)
+                             .setIon(useIon)
+                           .  setAsmJS(useAsmJS);
+
+    JS_SetParallelParsingEnabled(rt, parallelParsing);
+    JS_SetParallelIonCompilationEnabled(rt, parallelIonCompilation);
+    JS_SetGlobalJitCompilerOption(rt, JSJITCOMPILER_BASELINE_USECOUNT_TRIGGER,
+                                  useBaselineEager ? 0 : -1);
+    JS_SetGlobalJitCompilerOption(rt, JSJITCOMPILER_ION_USECOUNT_TRIGGER,
+                                  useIonEager ? 0 : -1);
+}
+
 XPCJSRuntime::~XPCJSRuntime()
 {
     // This destructor runs before ~CycleCollectedJSRuntime, which does the
     // actual JS_DestroyRuntime() call. But destroying the runtime triggers
     // one final GC, which can call back into the runtime with various
     // callback if we aren't careful. Null out the relevant callbacks.
     js::SetActivityCallback(Runtime(), nullptr, nullptr);
     JS_SetFinalizeCallback(Runtime(), nullptr);
@@ -1578,16 +1618,18 @@ XPCJSRuntime::~XPCJSRuntime()
         stack->sampleRuntime(nullptr);
 #endif
 
 #ifdef DEBUG
     for (uint32_t i = 0; i < XPCCCX_STRING_CACHE_SIZE; ++i) {
         MOZ_ASSERT(mScratchStrings[i].empty(), "Short lived string still in use");
     }
 #endif
+
+    Preferences::UnregisterCallback(ReloadPrefsCallback, JS_OPTIONS_DOT_STR, this);
 }
 
 static void
 GetCompartmentName(JSCompartment *c, nsCString &name, bool replaceSlashes)
 {
     if (js::IsAtomsCompartment(c)) {
         name.AssignLiteral("atoms");
     } else if (JSPrincipals *principals = JS_GetCompartmentPrincipals(c)) {
@@ -3131,16 +3173,20 @@ XPCJSRuntime::XPCJSRuntime(nsXPConnect* 
     RegisterJSMainRuntimeCompartmentsUserDistinguishedAmount(JSMainRuntimeCompartmentsUserDistinguishedAmount);
     mozilla::RegisterJSSizeOfTab(JSSizeOfTab);
 
     // Install a JavaScript 'debugger' keyword handler in debug builds only
 #ifdef DEBUG
     if (!JS_GetGlobalDebugHooks(runtime)->debuggerHandler)
         xpc_InstallJSDebuggerKeywordHandler(runtime);
 #endif
+
+    // Watch for the JS boolean options.
+    ReloadPrefsCallback(nullptr, this);
+    Preferences::RegisterCallback(ReloadPrefsCallback, JS_OPTIONS_DOT_STR, this);
 }
 
 // static
 XPCJSRuntime*
 XPCJSRuntime::newXPCJSRuntime(nsXPConnect* aXPConnect)
 {
     NS_PRECONDITION(aXPConnect,"bad param");
 
--- a/js/xpconnect/src/XPCShellImpl.cpp
+++ b/js/xpconnect/src/XPCShellImpl.cpp
@@ -1034,21 +1034,21 @@ ProcessArgsForCompartment(JSContext *cx,
                 return;
             break;
         case 'S':
             ContextOptionsRef(cx).toggleWerror();
         case 's':
             ContextOptionsRef(cx).toggleExtraWarnings();
             break;
         case 'I':
-            ContextOptionsRef(cx).toggleIon()
+            RuntimeOptionsRef(cx).toggleIon()
                                  .toggleAsmJS();
             break;
         case 'n':
-            ContextOptionsRef(cx).toggleTypeInference();
+            RuntimeOptionsRef(cx).toggleTypeInference();
             break;
         }
     }
 }
 
 static int
 ProcessArgs(JSContext *cx, JS::Handle<JSObject*> obj, char **argv, int argc, XPCShellDirProvider* aDirProvider)
 {
@@ -1482,19 +1482,16 @@ XRE_XPCShellMain(int argc, char **argv, 
         JS_SetOperationCallback(rt, XPCShellOperationCallback);
 
         cx = JS_NewContext(rt, 8192);
         if (!cx) {
             printf("JS_NewContext failed!\n");
             return 1;
         }
 
-        // Ion not enabled yet here because of bug 931861.
-        JS::ContextOptionsRef(cx).setBaseline(true);
-
         argc--;
         argv++;
         ProcessArgsForCompartment(cx, argv, argc);
 
         nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
         if (!xpc) {
             printf("failed to get nsXPConnect service!\n");
             return 1;
--- a/js/xpconnect/src/nsDOMQS.h
+++ b/js/xpconnect/src/nsDOMQS.h
@@ -12,17 +12,17 @@
 #include "mozilla/dom/HTMLImageElement.h"
 #include "mozilla/dom/HTMLOptionElement.h"
 #include "HTMLOptGroupElement.h"
 #include "mozilla/dom/HTMLVideoElement.h"
 #include "nsHTMLDocument.h"
 #include "nsICSSDeclaration.h"
 #include "nsSVGElement.h"
 #include "nsDOMEvent.h"
-#include "nsDOMUIEvent.h"
+#include "mozilla/dom/UIEvent.h"
 #include "mozilla/dom/MouseEvent.h"
 #include "mozilla/dom/EventTargetBinding.h"
 #include "mozilla/dom/NodeBinding.h"
 #include "mozilla/dom/ElementBinding.h"
 #include "mozilla/dom/HTMLElementBinding.h"
 #include "mozilla/dom/DocumentBinding.h"
 #include "mozilla/dom/SVGElementBinding.h"
 #include "mozilla/dom/HTMLDocumentBinding.h"
@@ -53,17 +53,17 @@ NEW_BINDING(mozilla::dom::EventTarget, E
 NEW_BINDING(nsINode, Node);
 NEW_BINDING(mozilla::dom::Element, Element);
 NEW_BINDING(nsGenericHTMLElement, HTMLElement);
 NEW_BINDING(nsIDocument, Document);
 NEW_BINDING(nsDocument, Document);
 NEW_BINDING(nsHTMLDocument, HTMLDocument);
 NEW_BINDING(nsSVGElement, SVGElement);
 NEW_BINDING(nsDOMEvent, Event);
-NEW_BINDING(nsDOMUIEvent, UIEvent);
+NEW_BINDING(mozilla::dom::UIEvent, UIEvent);
 NEW_BINDING(mozilla::dom::MouseEvent, MouseEvent);
 
 #define DEFINE_UNWRAP_CAST(_interface, _base, _bit)                           \
 template <>                                                                   \
 MOZ_ALWAYS_INLINE bool                                                        \
 xpc_qsUnwrapThis<_interface>(JSContext *cx,                                   \
                              JS::HandleObject obj,                            \
                              _interface **ppThis,                             \
--- a/js/xpconnect/src/nsXPConnect.cpp
+++ b/js/xpconnect/src/nsXPConnect.cpp
@@ -356,75 +356,32 @@ TraceXPCGlobal(JSTracer *trc, JSObject *
         return;
     }
 #endif
 
     if (js::GetObjectClass(obj)->flags & JSCLASS_DOM_GLOBAL)
         mozilla::dom::TraceProtoAndIfaceCache(trc, obj);
 }
 
-#ifdef DEBUG
-#include "mozilla/Preferences.h"
-#include "nsIXULRuntime.h"
-static void
-CheckTypeInference(JSContext *cx, const JSClass *clasp, nsIPrincipal *principal)
-{
-    // Check that the global class isn't whitelisted.
-    if (strcmp(clasp->name, "Sandbox") ||
-        strcmp(clasp->name, "nsXBLPrototypeScript compilation scope") ||
-        strcmp(clasp->name, "nsXULPrototypeScript compilation scope"))
-        return;
-
-    // Check that the pref is on.
-    if (!mozilla::Preferences::GetBool("javascript.options.typeinference"))
-        return;
-
-    // Check that we're not chrome.
-    bool isSystem;
-    nsIScriptSecurityManager* ssm;
-    ssm = XPCWrapper::GetSecurityManager();
-    if (NS_FAILED(ssm->IsSystemPrincipal(principal, &isSystem)) || !isSystem)
-        return;
-
-    // Check that safe mode isn't on.
-    bool safeMode;
-    nsCOMPtr<nsIXULRuntime> xr = do_GetService("@mozilla.org/xre/runtime;1");
-    if (!xr) {
-        NS_WARNING("Couldn't get XUL runtime!");
-        return;
-    }
-    if (NS_FAILED(xr->GetInSafeMode(&safeMode)) || safeMode)
-        return;
-
-    // Finally, do the damn assert.
-    MOZ_ASSERT(ContextOptionsRef(cx).typeInference());
-}
-#else
-#define CheckTypeInference(cx, clasp, principal) {}
-#endif
-
 namespace xpc {
 
 JSObject*
 CreateGlobalObject(JSContext *cx, const JSClass *clasp, nsIPrincipal *principal,
                    JS::CompartmentOptions& aOptions)
 {
-    // Make sure that Type Inference is enabled for everything non-chrome.
-    // Sandboxes and compilation scopes are exceptions. See bug 744034.
-    CheckTypeInference(cx, clasp, principal);
-
     MOZ_ASSERT(NS_IsMainThread(), "using a principal off the main thread?");
     MOZ_ASSERT(principal);
 
     RootedObject global(cx,
                         JS_NewGlobalObject(cx, clasp, nsJSPrincipals::get(principal),
                                            JS::DontFireOnNewGlobalHook, aOptions));
     if (!global)
         return nullptr;
     JSAutoCompartment ac(cx, global);
+
     // The constructor automatically attaches the scope to the compartment private
     // of |global|.
     (void) new XPCWrappedNativeScope(cx, global);
 
 #ifdef DEBUG
     // Verify that the right trace hook is called. Note that this doesn't
     // work right for wrapped globals, since the tracing situation there is
     // more complicated. Manual inspection shows that they do the right thing.
--- a/layout/base/tests/bug970964_inner.html
+++ b/layout/base/tests/bug970964_inner.html
@@ -129,16 +129,18 @@ function runTests() {
   d0.onpointerdown = function(e) {
     pointerDownTriggered = 1;
     is(mouseDownTriggered, 0, "Pointer event must be triggered before mouse event!");
     is(touchDownTriggered, 0, "Pointer event must be triggered before touch event!");
   };
   d0.addEventListener("pointercancel", function(ev) {
     d0.removeEventListener("pointercancel", arguments.callee, false);
     is(ev.pointerId, 0, "Correct default pointerId");
+    is(ev.bubbles, true, "bubbles should be true");
+    is(ev.cancelable, false, "pointercancel cancelable should be false ");
     pointerCancelTriggered = 1;
     is(touchCancelTriggered, 0, "Pointer event must be triggered before touch event!");
   }, false);
 
   // Test pointer event generated from mouse event
   synthesizeMouse(d1, 3, 3, { type: "mousemove"});
   synthesizeMouse(d1, 3, 3, { type: "mousedown"});
   synthesizeMouse(d1, 3, 3, { type: "mouseup"});
@@ -154,16 +156,18 @@ function runTests() {
   // Test Touch to Pointer Cancel
   sendTouchEvent(cwu, "touchcancel", event1, 0);
 
   // Check Pointer enter/leave from mouse generated event
   var mouseEnterTriggered = 0;
   var pointerEnterTriggered = 0;
   d2.onpointerenter = function(e) {
     pointerEnterTriggered = 1;
+    is(e.bubbles, false, "bubbles should be false");
+    is(e.cancelable, false, "cancelable should be false");
     is(mouseEnterTriggered, 0, "Pointer event must be triggered before mouse event!");
   };
   d2.onmouseenter = function(e) {
     mouseEnterTriggered = 1;
     is(pointerEnterTriggered , 1, "Mouse event must be triggered after pointer event!");
   };
   synthesizeMouse(d2, 3, 3, { type: "mousemove"});
   d2.onmouseenter = function(e) {}
@@ -184,36 +188,48 @@ function runTests() {
       ++mousePointerEnterLeaveCount;
     } else if (pointerType == "touch") {
       ++touchPointerEnterLeaveCount;
     }
   };
 
   d1.onpointerenter = function(e) {
     ++d1enterCount;
+    is(e.bubbles, false, "bubbles should be false");
+    is(e.cancelable, false, "cancelable should be false");
     checkPointerType(e.pointerType);
   };
   d2.onpointerenter = function(e) {
     ++d2enterCount;
+    is(e.bubbles, false, "bubbles should be false");
+    is(e.cancelable, false, "cancelable should be false");
     checkPointerType(e.pointerType);
   };
   d3.onpointerenter = function(e) {
     ++d3enterCount;
+    is(e.bubbles, false, "bubbles should be false");
+    is(e.cancelable, false, "cancelable should be false");
     checkPointerType(e.pointerType);
   };
   d1.onpointerleave = function(e) {
     ++d1leaveCount;
+    is(e.bubbles, false, "bubbles should be false");
+    is(e.cancelable, false, "cancelable should be false");
     checkPointerType(e.pointerType);
   };
   d2.onpointerleave = function(e) {
     ++d2leaveCount;
+    is(e.bubbles, false, "bubbles should be false");
+    is(e.cancelable, false, "cancelable should be false");
     checkPointerType(e.pointerType);
   };
   d3.onpointerleave = function(e) {
     ++d3leaveCount;
+    is(e.bubbles, false, "bubbles should be false");
+    is(e.cancelable, false, "cancelable should be false");
     checkPointerType(e.pointerType);
   };
 
   synthesizeMouse(d1, 3, 3, { type: "mousemove"});
   sendTouchEvent(cwu, "touchmove", getTouchEventForTarget(d3, cwu, 3), 0);
   is(touchPointerEnterLeaveCount, 1, "Wrong touch enterLeave count for!");
   is(mousePointerEnterLeaveCount, 2, "Wrong mouse enterLeave count for!");
 
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -2024,30 +2024,38 @@ nsIFrame::BuildDisplayListForStackingCon
     if (Preserves3DChildren()) {
       WrapPreserve3DList(this, aBuilder, &resultList);
     } else {
       resultList.AppendNewToTop(
         new (aBuilder) nsDisplayTransform(aBuilder, this, &resultList));
     }
   }
 
+  /* If adding both a nsDisplayBlendContainer and a nsDisplayMixBlendMode to the
+   * same list, the nsDisplayBlendContainer should be added first. This only
+   * happens when the element creating this stacking context has mix-blend-mode
+   * and also contains a child which has mix-blend-mode.
+   * The nsDisplayBlendContainer must be added to the list first, so it does not
+   * isolate the containing element blending as well.
+   */
+
+  if (aBuilder->ContainsBlendMode()) {
+      resultList.AppendNewToTop(
+        new (aBuilder) nsDisplayBlendContainer(aBuilder, this, &resultList));
+  }
+
   /* If there's blending, wrap up the list in a blend-mode item. Note
    * that opacity can be applied before blending as the blend color is
    * not affected by foreground opacity (only background alpha).
    */
 
   if (useBlendMode && !resultList.IsEmpty()) {
     resultList.AppendNewToTop(
         new (aBuilder) nsDisplayMixBlendMode(aBuilder, this, &resultList));
   }
-  
-  if (aBuilder->ContainsBlendMode()) {
-      resultList.AppendNewToTop(
-        new (aBuilder) nsDisplayBlendContainer(aBuilder, this, &resultList));
-  }
 
   CreateOwnLayerIfNeeded(aBuilder, &resultList);
 
   aList->AppendToTop(&resultList);
 }
 
 static nsDisplayItem*
 WrapInWrapList(nsDisplayListBuilder* aBuilder,
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-blending/mix-blend-mode-nested-976533-ref.html
@@ -0,0 +1,47 @@
+<!DOCTYPE HTML>
+<head>
+	<style>
+		.parent {
+		  width: 200px;
+		  height: 200px;
+		  position: absolute;
+		  z-index: 1;
+			background-color: #00ff00;
+		}
+
+		.intermediate {
+			width: 100px;
+		  height: 100px;
+		  margin-left:50px;
+		  background-color: #ffffff;
+		}
+
+		.child {
+		  width: 100px;
+		  height: 100px;
+		  margin-left:50px;
+		  background-color: #00ffff;
+		}
+
+		.grandchild {
+			width: 50px;
+			height: 100px;
+			margin-left: 50px;
+			background-color: #0000ff;
+		}
+
+		body {
+			margin:0px;
+		}
+
+	</style>
+</head>
+<body>
+	<div class="parent">
+		<div class="intermediate">
+	    <div class="child">
+	    	<div class="grandchild"></div>
+	    </div>
+    </div>
+	</div>
+</body>
new file mode 100644
--- /dev/null
+++ b/layout/reftests/css-blending/mix-blend-mode-nested-976533.html
@@ -0,0 +1,45 @@
+<!DOCTYPE HTML>
+<head>
+	<style>
+		.parent {
+		  width: 200px;
+		  height: 200px;
+		  position: absolute;
+		  z-index: 1;
+			background-color: #00ff00;
+		}
+
+		.intermediate {
+			width: 100px;
+		  height: 100px;
+		  margin-left:50px;
+		  background-color: #ff00ff;
+		  mix-blend-mode: difference;
+		}
+
+		.child {
+		  width: 100px;
+		  height: 100px;
+		  margin-left:50px;
+		  background-color: #00ffff;
+		  mix-blend-mode: multiply;
+		}
+
+		body {
+			margin:0px;
+		}
+	</style>
+	<!-- Blending should happen as follows:
+				First, the child element should blend with the intermediate element, with
+				the multiply operator. Is should not blend with the parent directly.
+				Then, group formed by the blended child and the intermediate element should
+				blend with the parent as a single layer.
+	 -->
+</head>
+<body>
+	<div class="parent">
+		<div class="intermediate">
+	    <div class="child"></div>
+    </div>
+	</div>
+</body>
--- a/layout/reftests/css-blending/reftest.list
+++ b/layout/reftests/css-blending/reftest.list
@@ -37,16 +37,18 @@ fuzzy-if(azureQuartz,1,1600) fuzzy-if(d2
 
 fuzzy-if(azureQuartz,2,40000) fuzzy-if(azureSkia||d2d||gtk2Widget,1,40000) pref(layout.css.background-blend-mode.enabled,true) == background-blending-image-color-959674.html background-blending-image-color-959674-ref.html
 
 #fuzzy due to inconsistencies in rounded rect cliping between parent and child; may be related to antialiasing. Between platforms, the max difference is the same, and the number of different pixels is either 36 or 37. (Win, Mac and Lin)
 fuzzy(64,37) pref(layout.css.mix-blend-mode.enabled,true) == mix-blend-mode-952051.html mix-blend-mode-952051-ref.html
 
 pref(layout.css.mix-blend-mode.enabled,true) == mix-blend-mode-child-of-blended-has-opacity.html mix-blend-mode-child-of-blended-has-opacity-ref.html
 
+pref(layout.css.mix-blend-mode.enabled,true) == mix-blend-mode-nested-976533.html mix-blend-mode-nested-976533-ref.html
+
 # Test plan 5.3.1 Blending between the background layers and the background color for an element with background-blend-mode
 # Test 9
 pref(layout.css.background-blend-mode.enabled,true) == background-blending-image-color-svg-as-data-uri.html background-blending-image-color-ref.html
 # Test 10
 pref(layout.css.background-blend-mode.enabled,true) == background-blending-image-color-gif.html background-blending-image-color-gif-ref.html
 pref(layout.css.background-blend-mode.enabled,true) == background-blending-image-color-transform3d.html background-blending-image-color-ref.html
 
 # Test plan 5.3.2 Background layers do not blend with content outside the background (or behind the element) - tests 2 and 3
--- a/memory/mozalloc/VolatileBufferFallback.cpp
+++ b/memory/mozalloc/VolatileBufferFallback.cpp
@@ -1,14 +1,15 @@
 /* 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 "VolatileBuffer.h"
 #include "mozilla/Assertions.h"
+#include "mozilla/NullPtr.h"
 #include "mozilla/mozalloc.h"
 
 #ifdef MOZ_MEMORY
 int posix_memalign(void** memptr, size_t alignment, size_t size);
 #endif
 
 namespace mozilla {
 
--- a/modules/libpref/src/init/all.js
+++ b/modules/libpref/src/init/all.js
@@ -735,25 +735,22 @@ pref("dom.event.clipboardevents.enabled"
 
 pref("dom.webcomponents.enabled",           false);
 
 pref("javascript.enabled",                  true);
 pref("javascript.options.strict",           false);
 #ifdef DEBUG
 pref("javascript.options.strict.debug",     true);
 #endif
-pref("javascript.options.baselinejit.content", true);
-pref("javascript.options.baselinejit.chrome",  true);
-pref("javascript.options.ion.content",      true);
-pref("javascript.options.ion.chrome",       true);
+pref("javascript.options.baselinejit",      true);
+pref("javascript.options.ion",              true);
 pref("javascript.options.asmjs",            true);
 pref("javascript.options.parallel_parsing", true);
 pref("javascript.options.ion.parallel_compilation", true);
-pref("javascript.options.typeinference.content", true);
-pref("javascript.options.typeinference.chrome", true);
+pref("javascript.options.typeinference",    true);
 // This preference limits the memory usage of javascript.
 // If you want to change these values for your device,
 // please find Bug 417052 comment 17 and Bug 456721
 // Comment 32 and Bug 613551.
 pref("javascript.options.mem.high_water_mark", 128);
 pref("javascript.options.mem.max", -1);
 pref("javascript.options.mem.gc_per_compartment", true);
 pref("javascript.options.mem.gc_incremental", true);
--- a/mozilla-config.h.in
+++ b/mozilla-config.h.in
@@ -45,10 +45,20 @@
  * HUNSPELL_STATIC is defined in extensions/spellcheck/hunspell/src/Makefile.in,
  * unless --enable-system-hunspell is defined.
  */
 #if defined(HUNSPELL_STATIC)
 #include "hunspell_alloc_hooks.h"
 #include "hunspell_fopen_hooks.h"
 #endif
 
+/*
+ * Force-include sdkdecls.h for building the chromium sandbox code.
+ *
+ * CHROMIUM_SANDBOX_BUILD is defined in security/sandbox/moz.build.
+ * Note that this include path relies on the LOCAL_INCLUDES in that file.
+ */
+#if defined(CHROMIUM_SANDBOX_BUILD) && defined(XP_WIN)
+#include "base/shim/sdkdecls.h"
+#endif
+
 #endif /* _MOZILLA_CONFIG_H_ */
 
--- a/profile/dirserviceprovider/src/nsProfileLock.cpp
+++ b/profile/dirserviceprovider/src/nsProfileLock.cpp
@@ -629,17 +629,17 @@ nsresult nsProfileLock::Unlock(bool aFat
             // handler.  The problem is that a call to free() might be the
             // cause of this fatal signal.  If so, calling free() might cause
             // us to wait on the malloc implementation's lock.  We're already
             // holding this lock, so we'll deadlock. See bug 522332.
             if (!aFatalSignal)
                 free(mPidLockFileName);
             mPidLockFileName = nullptr;
         }
-        else if (mLockFileDesc != -1)
+        if (mLockFileDesc != -1)
         {
             close(mLockFileDesc);
             mLockFileDesc = -1;
             // Don't remove it
         }
 #endif
 
         mHaveLock = false;
--- a/security/sandbox/Makefile.in
+++ b/security/sandbox/Makefile.in
@@ -1,18 +1,10 @@
 # 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/.
 
 ifeq ($(OS_ARCH),WINNT)
-EXTRA_SDK_DECLS = $(topsrcdir)/security/sandbox/chromium/base/shim/sdkdecls.h
-
-ifdef _MSC_VER
-OS_CXXFLAGS += -FI $(EXTRA_SDK_DECLS)
-else
-OS_CXXFLAGS += -include $(EXTRA_SDK_DECLS)
-endif
-
 STL_FLAGS =
 MOZ_GLUE_LDFLAGS =
 endif
 
 include $(topsrcdir)/config/rules.mk
--- a/security/sandbox/moz.build
+++ b/security/sandbox/moz.build
@@ -116,15 +116,15 @@ elif CONFIG['OS_ARCH'] == 'WINNT':
         'win/src/target_services.cc',
         'win/src/win2k_threadpool.cc',
         'win/src/win_utils.cc',
         'win/src/window.cc',
         'win/src/Wow64.cc',
     ]
 
     for var in ('UNICODE', '_UNICODE', 'NS_NO_XPCOM', 'SANDBOX_EXPORTS',
-                'NOMINMAX', '_CRT_RAND_S'):
+                'NOMINMAX', '_CRT_RAND_S', 'CHROMIUM_SANDBOX_BUILD'):
         DEFINES[var] = True
 
     LOCAL_INCLUDES += ['/security/sandbox/chromium/base/shim']
     LOCAL_INCLUDES += ['/security/sandbox/chromium']
     LOCAL_INCLUDES += ['/security']
     LOCAL_INCLUDES += ['/nsprpub']
--- a/testing/mochitest/runtests.py
+++ b/testing/mochitest/runtests.py
@@ -147,17 +147,17 @@ class MochitestServer(object):
     # get testing environment
     env = environment(xrePath=self._xrePath)
     env["XPCOM_DEBUG_BREAK"] = "warn"
 
     # When running with an ASan build, our xpcshell server will also be ASan-enabled,
     # thus consuming too much resources when running together with the browser on
     # the test slaves. Try to limit the amount of resources by disabling certain
     # features.
-    env["ASAN_OPTIONS"] = "quarantine_size=1:redzone=32"
+    env["ASAN_OPTIONS"] = "quarantine_size=1:redzone=32:malloc_context_size=5"
 
     if mozinfo.isWin:
       env["PATH"] = env["PATH"] + ";" + str(self._xrePath)
 
     args = ["-g", self._xrePath,
             "-v", "170",
             "-f", self._httpdPath + "/httpd.js",
             "-e", """const _PROFILE_PATH = '%(profile)s'; const _SERVER_PORT = '%(port)s'; const _SERVER_ADDR = '%(server)s'; const _TEST_PREFIX = %(testPrefix)s; const _DISPLAY_RESULTS = %(displayResults)s;""" %
--- a/testing/mozbase/mozcrash/mozcrash/mozcrash.py
+++ b/testing/mozbase/mozcrash/mozcrash/mozcrash.py
@@ -156,26 +156,29 @@ def check_for_crashes(dump_directory, sy
                 mozfile.remove(extra)
     finally:
         if remove_symbols:
             mozfile.remove(symbols_path)
 
     return True
 
 
-def check_for_java_exception(logcat):
+def check_for_java_exception(logcat, quiet=False):
     """
     Print a summary of a fatal Java exception, if present in the provided
     logcat output.
 
     Example:
     PROCESS-CRASH | java-exception | java.lang.NullPointerException at org.mozilla.gecko.GeckoApp$21.run(GeckoApp.java:1833)
 
     `logcat` should be a list of strings.
 
+    If `quiet` is set, no PROCESS-CRASH message will be printed to stdout if a
+    crash is detected.
+
     Returns True if a fatal Java exception was found, False otherwise.
     """
     found_exception = False
 
     for i, line in enumerate(logcat):
         # Logs will be of form:
         #
         # 01-30 20:15:41.937 E/GeckoAppShell( 1703): >>> REPORTING UNCAUGHT EXCEPTION FROM THREAD 9 ("GeckoBackgroundThread")
@@ -189,14 +192,15 @@ def check_for_java_exception(logcat):
             if len(logcat) >= i + 3:
                 logre = re.compile(r".*\): \t?(.*)")
                 m = logre.search(logcat[i+1])
                 if m and m.group(1):
                     exception_type = m.group(1)
                 m = logre.search(logcat[i+2])
                 if m and m.group(1):
                     exception_location = m.group(1)
-                print "PROCESS-CRASH | java-exception | %s %s" % (exception_type, exception_location)
+                if not quiet:
+                    print "PROCESS-CRASH | java-exception | %s %s" % (exception_type, exception_location)
             else:
                 print "Automation Error: Logcat is truncated!"
             break
 
     return found_exception
--- a/testing/mozbase/mozcrash/tests/test.py
+++ b/testing/mozbase/mozcrash/tests/test.py
@@ -182,37 +182,37 @@ class TestJavaException(unittest.TestCas
                        "01-30 20:15:41.937 E/GeckoAppShell( 1703): java.lang.NullPointerException",
                        "01-30 20:15:41.937 E/GeckoAppShell( 1703):    at org.mozilla.gecko.GeckoApp$21.run(GeckoApp.java:1833)",
                        "01-30 20:15:41.937 E/GeckoAppShell( 1703):    at android.os.Handler.handleCallback(Handler.java:587)"]
 
        def test_uncaught_exception(self):
                """
                Test for an exception which should be caught
                """
-               self.assert_(mozcrash.check_for_java_exception(self.test_log))
+               self.assert_(mozcrash.check_for_java_exception(self.test_log, quiet=True))
 
        def test_fatal_exception(self):
                """
                Test for an exception which should be caught
                """
                fatal_log = list(self.test_log)
                fatal_log[0] = "01-30 20:15:41.937 E/GeckoAppShell( 1703): >>> FATAL EXCEPTION FROM THREAD 9 (\"GeckoBackgroundThread\")"
-               self.assert_(mozcrash.check_for_java_exception(fatal_log))
+               self.assert_(mozcrash.check_for_java_exception(fatal_log, quiet=True))
 
        def test_truncated_exception(self):
                """
                Test for an exception which should be caught which
                was truncated
                """
                truncated_log = list(self.test_log)
                truncated_log[0], truncated_log[1] = truncated_log[1], truncated_log[0]
-               self.assert_(mozcrash.check_for_java_exception(truncated_log))
+               self.assert_(mozcrash.check_for_java_exception(truncated_log, quiet=True))
 
        def test_unchecked_exception(self):
                """
                Test for an exception which should not be caught
                """
                passable_log = list(self.test_log)
                passable_log[0] = "01-30 20:15:41.937 E/GeckoAppShell( 1703): >>> NOT-SO-BAD EXCEPTION FROM THREAD 9 (\"GeckoBackgroundThread\")"
-               self.assert_(not mozcrash.check_for_java_exception(passable_log))
+               self.assert_(not mozcrash.check_for_java_exception(passable_log, quiet=True))
 
 if __name__ == '__main__':
     unittest.main()
--- a/tools/mercurial/hgsetup/config.py
+++ b/tools/mercurial/hgsetup/config.py
@@ -116,27 +116,28 @@ class MercurialConfig(object):
         if 'diff' not in self._c:
             self._c['diff'] = {}
 
         d = self._c['diff']
         d['git'] = 1
         d['showfunc'] = 1
         d['unified'] = 8
 
-    def autocommit_mq(self, value=True):
+    def have_mqext_autocommit_mq(self):
+        if 'mqext' not in self._c:
+            return False
+        v = self._c['mqext'].get('mqcommit')
+        return v == 'auto' or v == 'yes'
+
+    def ensure_mqext_autocommit_mq(self):
+        if self.have_mqext_autocommit_mq():
+            return
         if 'mqext' not in self._c:
             self._c['mqext'] = {}
-
-        if value:
-            self._c['mqext']['mqcommit'] = 'auto'
-        else:
-            try:
-                del self._c['mqext']['mqcommit']
-            except KeyError:
-                pass
+        self._c['mqext']['mqcommit'] = 'auto'
 
     def have_qnew_currentuser_default(self):
         if 'defaults' not in self._c:
             return False
         d = self._c['defaults']
         if 'qnew' not in d:
             return False
         argv = d['qnew'].split(' ')
--- a/tools/mercurial/hgsetup/wizard.py
+++ b/tools/mercurial/hgsetup/wizard.py
@@ -164,19 +164,21 @@ class MercurialSetupWizard(object):
 
             if 'mqext' in c.extensions:
                 self.update_mercurial_repo(
                     hg,
                     'https://bitbucket.org/sfink/mqext',
                     os.path.join(self.ext_dir, 'mqext'),
                     'default',
                     'Ensuring mqext extension is up to date...')
+
+            if 'mqext' in c.extensions and not c.have_mqext_autocommit_mq():
                 if self._prompt_yn('Would you like to configure mqext to '
                     'automatically commit changes as you modify patches'):
-                    c.autocommit_mq(True)
+                    c.ensure_mqext_autocommit_mq()
                     print('Configured mqext to auto-commit.\n')
 
             self.prompt_external_extension(c, 'qimportbz', QIMPORTBZ_INFO)
 
             if not c.have_qnew_currentuser_default():
                 print(QNEWCURRENTUSER_INFO)
                 if self._prompt_yn('Would you like qnew to set patch author by '
                                    'default'):
--- a/widget/MouseEvents.h
+++ b/widget/MouseEvents.h
@@ -571,16 +571,22 @@ public:
   }
 
   void UpdateFlags()
   {
     switch (message) {
       case NS_POINTER_ENTER:
       case NS_POINTER_LEAVE:
         mFlags.mBubbles = false;
+        mFlags.mCancelable = false;
+        break;
+      case NS_POINTER_CANCEL:
+      case NS_POINTER_GOT_CAPTURE:
+      case NS_POINTER_LOST_CAPTURE:
+        mFlags.mCancelable = false;
         break;
       default:
         break;
     }
   }
 
   virtual WidgetEvent* Duplicate() const MOZ_OVERRIDE
   {
--- a/widget/TouchEvents.h
+++ b/widget/TouchEvents.h
@@ -144,23 +144,25 @@ public:
 
   WidgetTouchEvent(const WidgetTouchEvent& aOther) :
     WidgetInputEvent(aOther.mFlags.mIsTrusted, aOther.message, aOther.widget,
                      NS_TOUCH_EVENT)
   {
     modifiers = aOther.modifiers;
     time = aOther.time;
     touches.AppendElements(aOther.touches);
+    mFlags.mCancelable = message != NS_TOUCH_CANCEL;
     MOZ_COUNT_CTOR(WidgetTouchEvent);
   }
 
   WidgetTouchEvent(bool aIsTrusted, uint32_t aMessage, nsIWidget* aWidget) :
     WidgetInputEvent(aIsTrusted, aMessage, aWidget, NS_TOUCH_EVENT)
   {
     MOZ_COUNT_CTOR(WidgetTouchEvent);
+    mFlags.mCancelable = message != NS_TOUCH_CANCEL;
   }
 
   virtual ~WidgetTouchEvent()
   {
     MOZ_COUNT_DTOR(WidgetTouchEvent);
   }
 
   virtual WidgetEvent* Duplicate() const MOZ_OVERRIDE
--- a/widget/android/nsAppShell.cpp
+++ b/widget/android/nsAppShell.cpp
@@ -14,17 +14,16 @@
 #include "nsWindow.h"
 #include "nsThreadUtils.h"
 #include "nsICommandLineRunner.h"
 #include "nsIObserverService.h"
 #include "nsIAppStartup.h"
 #include "nsIGeolocationProvider.h"
 #include "nsCacheService.h"
 #include "nsIDOMEventListener.h"
-#include "nsDOMNotifyPaintEvent.h"
 #include "nsIDOMClientRectList.h"
 #include "nsIDOMClientRect.h"
 #include "nsIDOMWakeLockListener.h"
 #include "nsIPowerManagerService.h"
 #include "nsFrameManager.h"
 #include "nsINetworkLinkService.h"
 
 #include "mozilla/Services.h"
--- a/widget/windows/nsLookAndFeel.cpp
+++ b/widget/windows/nsLookAndFeel.cpp
@@ -66,17 +66,17 @@ static nsresult GetColorFromTheme(nsUXTh
 static int32_t GetSystemParam(long flag, int32_t def)
 {
     DWORD value; 
     return ::SystemParametersInfo(flag, 0, &value, 0) ? value : def;
 }
 
 namespace mozilla {
 namespace widget {
-// This is in use here and in nsDOMTouchEvent.cpp
+// This is in use here and in dom/events/TouchEvent.cpp
 int32_t IsTouchDeviceSupportPresent()
 {
   int32_t touchCapabilities;
   touchCapabilities = ::GetSystemMetrics(SM_DIGITIZER);
   return ((touchCapabilities & NID_READY) && 
           (touchCapabilities & (NID_EXTERNAL_TOUCH | NID_INTEGRATED_TOUCH)));
 }
 } }
--- a/xpcom/base/nsCycleCollector.cpp
+++ b/xpcom/base/nsCycleCollector.cpp
@@ -215,23 +215,16 @@ using namespace mozilla;
 //
 // MOZ_CC_RUN_DURING_SHUTDOWN: In non-DEBUG or builds, if this is set,
 // run cycle collections at shutdown.
 //
 // MOZ_CC_LOG_DIRECTORY: The directory in which logs are placed (such as
 // logs from MOZ_CC_LOG_ALL and MOZ_CC_LOG_SHUTDOWN, or other uses
 // of nsICycleCollectorListener)
 
-MOZ_NEVER_INLINE void
-CC_AbortIfNull(void *ptr)
-{
-    if (!ptr)
-        MOZ_CRASH();
-}
-
 // Various parameters of this collector can be tuned using environment
 // variables.
 
 struct nsCycleCollectorParams
 {
     bool mLogAll;
     bool mLogShutdown;
     bool mAllTracesAtShutdown;
@@ -1227,17 +1220,19 @@ class GraphWalker
 {
 private:
     Visitor mVisitor;
 
     void DoWalk(nsDeque &aQueue);
 
     void CheckedPush(nsDeque &aQueue, PtrInfo *pi)
     {
-        CC_AbortIfNull(pi);
+        if (!pi) {
+            MOZ_CRASH();
+        }
         if (!aQueue.Push(pi, fallible_t())) {
             mVisitor.Failed();
         }
     }
 
 public:
     void Walk(PtrInfo *s0);
     void WalkFromRoots(GCGraph &aGraph);
@@ -1313,17 +1308,16 @@ GraphWalker<Visitor>::WalkFromRoots(GCGr
 template <class Visitor>
 MOZ_NEVER_INLINE void
 GraphWalker<Visitor>::DoWalk(nsDeque &aQueue)
 {
     // Use a aQueue to match the breadth-first traversal used when we
     // built the graph, for hopefully-better locality.
     while (aQueue.GetSize() > 0) {
         PtrInfo *pi = static_cast<PtrInfo*>(aQueue.PopFront());
-        CC_AbortIfNull(pi);
 
         if (pi->mParticipant && mVisitor.ShouldVisitNode(pi)) {
             mVisitor.VisitNode(pi);
             for (EdgePool::Iterator child = pi->FirstChild(),
                                 child_end = pi->LastChild();
                  child != child_end; ++child) {
                 CheckedPush(aQueue, *child);
             }
@@ -2531,17 +2525,20 @@ nsCycleCollector::MarkRoots(SliceBudget 
     AutoRestore<bool> ar(mScanInProgress);
     MOZ_ASSERT(!mScanInProgress);
     mScanInProgress = true;
     MOZ_ASSERT(mIncrementalPhase == GraphBuildingPhase);
     MOZ_ASSERT(mCurrNode);
 
     while (!aBudget.isOverBudget() && !mCurrNode->IsDone()) {
         PtrInfo *pi = mCurrNode->GetNext();
-        CC_AbortIfNull(pi);
+        if (!pi) {
+            MOZ_CRASH();
+        }
+
         // We need to call the builder's Traverse() method on deleted nodes, to
         // set their firstChild() that may be read by a prior non-deleted
         // neighbor.
         mBuilder->Traverse(pi);
         if (mCurrNode->AtBlockEnd()) {
             mBuilder->SetLastChild();
         }
         aBudget.step(kStep);
--- a/xpcom/glue/nsCycleCollectionParticipant.h
+++ b/xpcom/glue/nsCycleCollectionParticipant.h
@@ -1211,11 +1211,248 @@ static NS_CYCLE_COLLECTION_INNERCLASS NS
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f7)                                        \
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f8)                                        \
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f9)                                        \
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f10)                                       \
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f11)                                       \
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f12)                                       \
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
+#define NS_IMPL_CYCLE_COLLECTION_INHERITED_13(_class, _base, _f1, _f2, _f3, _f4, _f5, _f6, _f7, _f8, _f9, _f10, _f11, _f12, _f13) \
+ NS_IMPL_CYCLE_COLLECTION_CLASS(_class)                                        \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(_class, _base)                \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f1)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f2)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f3)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f4)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f5)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f6)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f7)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f8)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f9)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f10)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f11)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f12)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f13)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_END                                           \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(_class, _base)              \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f1)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f2)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f3)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f4)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f5)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f6)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f7)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f8)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f9)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f10)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f11)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f12)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f13)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+#define NS_IMPL_CYCLE_COLLECTION_INHERITED_14(_class, _base, _f1, _f2, _f3, _f4, _f5, \
+                                              _f6, _f7, _f8, _f9, _f10, _f11, _f12, _f13, _f14) \
+ NS_IMPL_CYCLE_COLLECTION_CLASS(_class)                                        \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(_class, _base)                \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f1)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f2)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f3)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f4)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f5)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f6)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f7)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f8)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f9)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f10)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f11)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f12)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f13)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f14)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_END                                           \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(_class, _base)              \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f1)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f2)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f3)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f4)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f5)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f6)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f7)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f8)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f9)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f10)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f11)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f12)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f13)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f14)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+#define NS_IMPL_CYCLE_COLLECTION_INHERITED_15(_class, _base, _f1, _f2, _f3, _f4, _f5, \
+                                              _f6, _f7, _f8, _f9, _f10, _f11, _f12, _f13, _f14, \
+                                              _f15)                            \
+ NS_IMPL_CYCLE_COLLECTION_CLASS(_class)                                        \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(_class, _base)                \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f1)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f2)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f3)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f4)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f5)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f6)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f7)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f8)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f9)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f10)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f11)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f12)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f13)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f14)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f15)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_END                                           \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(_class, _base)              \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f1)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f2)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f3)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f4)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f5)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f6)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f7)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f8)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f9)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f10)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f11)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f12)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f13)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f14)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f15)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+#define NS_IMPL_CYCLE_COLLECTION_INHERITED_16(_class, _base, _f1, _f2, _f3, _f4, _f5, \
+                                              _f6, _f7, _f8, _f9, _f10, _f11, _f12, _f13, _f14, \
+                                              _f15, _f16)                      \
+ NS_IMPL_CYCLE_COLLECTION_CLASS(_class)                                        \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(_class, _base)                \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f1)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f2)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f3)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f4)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f5)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f6)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f7)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f8)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f9)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f10)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f11)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f12)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f13)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f14)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f15)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f16)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_END                                           \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(_class, _base)              \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f1)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f2)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f3)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f4)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f5)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f6)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f7)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f8)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f9)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f10)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f11)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f12)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f13)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f14)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f15)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f16)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+#define NS_IMPL_CYCLE_COLLECTION_INHERITED_17(_class, _base, _f1, _f2, _f3, _f4, _f5, \
+                                              _f6, _f7, _f8, _f9, _f10, _f11, _f12, _f13, _f14, \
+                                              _f15, _f16, _f17)                \
+ NS_IMPL_CYCLE_COLLECTION_CLASS(_class)                                        \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(_class, _base)                \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f1)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f2)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f3)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f4)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f5)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f6)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f7)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f8)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f9)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f10)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f11)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f12)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f13)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f14)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f15)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f16)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f17)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_END                                           \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(_class, _base)              \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f1)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f2)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f3)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f4)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f5)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f6)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f7)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f8)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f9)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f10)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f11)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f12)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f13)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f14)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f15)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f16)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f17)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
+#define NS_IMPL_CYCLE_COLLECTION_INHERITED_18(_class, _base, _f1, _f2, _f3, _f4, _f5, \
+                                              _f6, _f7, _f8, _f9, _f10, _f11, _f12, _f13, _f14, \
+                                              _f15, _f16, _f17, _f18)          \
+ NS_IMPL_CYCLE_COLLECTION_CLASS(_class)                                        \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(_class, _base)                \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f1)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f2)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f3)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f4)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f5)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f6)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f7)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f8)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f9)                                          \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f10)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f11)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f12)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f13)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f14)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f15)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f16)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f17)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK(_f18)                                         \
+ NS_IMPL_CYCLE_COLLECTION_UNLINK_END                                           \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(_class, _base)              \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f1)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f2)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f3)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f4)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f5)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f6)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f7)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f8)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f9)                                        \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f10)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f11)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f12)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f13)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f14)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f15)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f16)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f17)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE(_f18)                                       \
+ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
+
 #define NS_CYCLE_COLLECTION_NOTE_EDGE_NAME CycleCollectionNoteEdgeName
 
 #endif // nsCycleCollectionParticipant_h__