Merge from Chromium at DEPS revision 224184

This commit was generated by merge_to_master.py.

Change-Id: I6aa2623a399e683ff92335749916c23088d1fbd8
diff --git a/Source/core/accessibility/AXObjectCache.cpp b/Source/core/accessibility/AXObjectCache.cpp
index 526c600..ad15a32 100644
--- a/Source/core/accessibility/AXObjectCache.cpp
+++ b/Source/core/accessibility/AXObjectCache.cpp
@@ -99,12 +99,18 @@
     }
 }
 
+void AXComputedObjectAttributeCache::clear()
+{
+    m_idMapping.clear();
+}
+
 bool AXObjectCache::gAccessibilityEnabled = false;
 
 AXObjectCache::AXObjectCache(const Document* doc)
     : m_notificationPostTimer(this, &AXObjectCache::notificationPostTimerFired)
 {
     m_document = const_cast<Document*>(doc);
+    m_computedObjectAttributeCache = AXComputedObjectAttributeCache::create();
 }
 
 AXObjectCache::~AXObjectCache()
@@ -651,7 +657,7 @@
     if (!renderer)
         return;
 
-    stopCachingComputedObjectAttributes();
+    m_computedObjectAttributeCache->clear();
 
     // Get an accessibility object that already exists. One should not be created here
     // because a render update may be in progress and creating an AX object can re-trigger a layout
@@ -672,7 +678,7 @@
     if (!node)
         return;
 
-    stopCachingComputedObjectAttributes();
+    m_computedObjectAttributeCache->clear();
 
     // Get an accessibility object that already exists. One should not be created here
     // because a render update may be in progress and creating an AX object can re-trigger a layout
@@ -690,7 +696,7 @@
 
 void AXObjectCache::postNotification(AccessibilityObject* object, Document* document, AXNotification notification, bool postToElement, PostType postType)
 {
-    stopCachingComputedObjectAttributes();
+    m_computedObjectAttributeCache->clear();
 
     if (object && !postToElement)
         object = object->observableObject();
@@ -735,7 +741,7 @@
 
     // We don't want to create a scroll view from this method, only update an existing one.
     if (AccessibilityObject* scrollViewObject = get(view)) {
-        stopCachingComputedObjectAttributes();
+        m_computedObjectAttributeCache->clear();
         scrollViewObject->updateChildrenIfNecessary();
     }
 }
@@ -754,10 +760,9 @@
 
 void AXObjectCache::handleAriaRoleChanged(Node* node)
 {
-    stopCachingComputedObjectAttributes();
-
     if (AccessibilityObject* obj = getOrCreate(node)) {
         obj->updateAccessibilityRole();
+        m_computedObjectAttributeCache->clear();
         obj->notifyIfIgnoredValueChanged();
     }
 }
@@ -807,14 +812,14 @@
 
 void AXObjectCache::startCachingComputedObjectAttributesUntilTreeMutates()
 {
-    if (!m_computedObjectAttributeCache)
-        m_computedObjectAttributeCache = AXComputedObjectAttributeCache::create();
+    // FIXME: no longer needed. When Chromium no longer calls
+    // WebAXObject::startCachingComputedObjectAttributesUntilTreeMutates,
+    // delete this function and the WebAXObject interfaces.
 }
 
 void AXObjectCache::stopCachingComputedObjectAttributes()
 {
-    if (m_computedObjectAttributeCache)
-        m_computedObjectAttributeCache.clear();
+    // FIXME: no longer needed (see above).
 }
 
 VisiblePosition AXObjectCache::visiblePositionForTextMarkerData(TextMarkerData& textMarkerData)
diff --git a/Source/core/accessibility/AXObjectCache.h b/Source/core/accessibility/AXObjectCache.h
index 3e37eb9..52caa5c 100644
--- a/Source/core/accessibility/AXObjectCache.h
+++ b/Source/core/accessibility/AXObjectCache.h
@@ -58,6 +58,8 @@
     AccessibilityObjectInclusion getIgnored(AXID) const;
     void setIgnored(AXID, AccessibilityObjectInclusion);
 
+    void clear();
+
 private:
     AXComputedObjectAttributeCache() { }
 
diff --git a/Source/core/animation/AnimatableNumber.cpp b/Source/core/animation/AnimatableNumber.cpp
index f57a829..415fc8b 100644
--- a/Source/core/animation/AnimatableNumber.cpp
+++ b/Source/core/animation/AnimatableNumber.cpp
@@ -81,9 +81,9 @@
     return value->isCalculationValue();
 }
 
-PassRefPtr<CSSValue> AnimatableNumber::toCSSValue(CalculationPermittedValueRange calcRange) const
+PassRefPtr<CSSValue> AnimatableNumber::toCSSValue(NumberRange range) const
 {
-    return toCSSPrimitiveValue(calcRange);
+    return toCSSPrimitiveValue(range);
 }
 
 double AnimatableNumber::toDouble() const
@@ -92,14 +92,16 @@
     return m_number;
 }
 
-Length AnimatableNumber::toLength(const RenderStyle* style, const RenderStyle* rootStyle, double zoom, CalculationPermittedValueRange calcRange) const
+Length AnimatableNumber::toLength(const RenderStyle* style, const RenderStyle* rootStyle, double zoom, NumberRange range) const
 {
-    // Avoid creating a CSSValue in the common cases
-    if (m_unitType == UnitTypeLength)
-        return Length(m_number, Fixed);
-    if (m_unitType == UnitTypePercentage)
-        return Length(m_number, Percent);
-    return toCSSPrimitiveValue(calcRange)->convertToLength<AnyConversion>(style, rootStyle, zoom);
+    if (!m_isCalc) {
+        // Avoid creating a CSSValue in the common cases
+        if (m_unitType == UnitTypeLength)
+            return Length(clampedNumber(range) * zoom, Fixed);
+        if (m_unitType == UnitTypePercentage)
+            return Length(clampedNumber(range), Percent);
+    }
+    return toCSSPrimitiveValue(range)->convertToLength<AnyConversion>(style, rootStyle, zoom);
 }
 
 PassRefPtr<AnimatableValue> AnimatableNumber::interpolateTo(const AnimatableValue* value, double fraction) const
@@ -124,17 +126,27 @@
 {
     if (m_isCalc)
         return m_calcExpression;
-    return CSSCalcValue::createExpressionNode(toCSSPrimitiveValue(CalculationRangeAll), m_number == trunc(m_number));
+    return CSSCalcValue::createExpressionNode(toCSSPrimitiveValue(AllValues), m_number == trunc(m_number));
 }
 
-PassRefPtr<CSSPrimitiveValue> AnimatableNumber::toCSSPrimitiveValue(CalculationPermittedValueRange calcRange) const
+static bool isCompatibleWithRange(const CSSPrimitiveValue* primitiveValue, NumberRange range)
+{
+    ASSERT(primitiveValue);
+    if (range == AllValues)
+        return true;
+    if (primitiveValue->isCalculated())
+        return primitiveValue->cssCalcValue()->permittedValueRange() == CalculationRangeNonNegative;
+    return primitiveValue->getDoubleValue() >= 0;
+}
+
+PassRefPtr<CSSPrimitiveValue> AnimatableNumber::toCSSPrimitiveValue(NumberRange range) const
 {
     ASSERT(m_unitType != UnitTypeInvalid);
-    if (!m_cachedCSSPrimitiveValue || !isCompatibleWithCalcRange(m_cachedCSSPrimitiveValue.get(), calcRange)) {
+    if (!m_cachedCSSPrimitiveValue || !isCompatibleWithRange(m_cachedCSSPrimitiveValue.get(), range)) {
         if (m_isCalc)
-            m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(CSSCalcValue::create(m_calcExpression, calcRange));
+            m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(CSSCalcValue::create(m_calcExpression, range == AllValues ? CalculationRangeAll : CalculationRangeNonNegative));
         else
-            m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(m_number, static_cast<CSSPrimitiveValue::UnitTypes>(numberTypeToPrimitiveUnit(m_unitType)));
+            m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(clampedNumber(range), static_cast<CSSPrimitiveValue::UnitTypes>(numberTypeToPrimitiveUnit(m_unitType)));
     }
     return m_cachedCSSPrimitiveValue;
 }
@@ -150,12 +162,6 @@
     return AnimatableNumber::create(m_number * factor, m_unitType);
 }
 
-bool AnimatableNumber::isCompatibleWithCalcRange(const CSSPrimitiveValue* primitiveValue, CalculationPermittedValueRange& calcRange)
-{
-    ASSERT(primitiveValue);
-    return !primitiveValue->isCalculated() || primitiveValue->cssCalcValue()->permittedValueRange() == calcRange;
-}
-
 AnimatableNumber::NumberUnitType AnimatableNumber::primitiveUnitToNumberType(unsigned short primitiveUnit)
 {
     switch (primitiveUnit) {
diff --git a/Source/core/animation/AnimatableNumber.h b/Source/core/animation/AnimatableNumber.h
index 30b2d54..9da6a7d 100644
--- a/Source/core/animation/AnimatableNumber.h
+++ b/Source/core/animation/AnimatableNumber.h
@@ -34,10 +34,14 @@
 #include "core/animation/AnimatableValue.h"
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/platform/CalculationValue.h"
 
 namespace WebCore {
 
+enum NumberRange {
+    AllValues,
+    NonNegativeValues,
+};
+
 // Handles animation of CSSPrimitiveValues that can be represented by doubles including CSSCalcValue.
 // See primitiveUnitToNumberType() for the list of supported units (with the exception of calc).
 // If created from a CSSPrimitiveValue this class will cache it to be returned in toCSSValue().
@@ -68,9 +72,9 @@
     {
         return adoptRef(new AnimatableNumber(number, unitType, cssPrimitiveValue));
     }
-    PassRefPtr<CSSValue> toCSSValue(CalculationPermittedValueRange = CalculationRangeAll) const;
+    PassRefPtr<CSSValue> toCSSValue(NumberRange = AllValues) const;
     double toDouble() const;
-    Length toLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, double zoom, CalculationPermittedValueRange = CalculationRangeAll) const;
+    Length toLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, double zoom, NumberRange = AllValues) const;
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
@@ -101,11 +105,15 @@
     }
     static PassRefPtr<AnimatableNumber> create(const AnimatableNumber* leftAddend, const AnimatableNumber* rightAddend);
 
-    PassRefPtr<CSSPrimitiveValue> toCSSPrimitiveValue(CalculationPermittedValueRange) const;
+    PassRefPtr<CSSPrimitiveValue> toCSSPrimitiveValue(NumberRange) const;
     PassRefPtr<CSSCalcExpressionNode> toCSSCalcExpressionNode() const;
 
     PassRefPtr<AnimatableNumber> scale(double) const;
-    static bool isCompatibleWithCalcRange(const CSSPrimitiveValue*, CalculationPermittedValueRange&);
+    double clampedNumber(NumberRange range) const
+    {
+        ASSERT(!m_isCalc);
+        return (range == NonNegativeValues && m_number <= 0) ? 0 : m_number;
+    }
     static NumberUnitType primitiveUnitToNumberType(unsigned short primitiveUnit);
     static unsigned short numberTypeToPrimitiveUnit(NumberUnitType numberType);
 
diff --git a/Source/core/animation/AnimatableNumberTest.cpp b/Source/core/animation/AnimatableNumberTest.cpp
index 2399d03..4872919 100644
--- a/Source/core/animation/AnimatableNumberTest.cpp
+++ b/Source/core/animation/AnimatableNumberTest.cpp
@@ -34,6 +34,8 @@
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/platform/CalculationValue.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/style/StyleInheritedData.h"
 #include "wtf/MathExtras.h"
 
 #include <gtest/gtest.h>
@@ -46,6 +48,7 @@
 protected:
     virtual void SetUp()
     {
+        style = RenderStyle::createDefaultStyle();
     }
 
     PassRefPtr<AnimatableNumber> create(double value)
@@ -58,6 +61,11 @@
         return AnimatableNumber::create(CSSPrimitiveValue::create(value, type).get());
     }
 
+    PassRefPtr<AnimatableNumber> create(double valueLeft, CSSPrimitiveValue::UnitTypes typeLeft, double valueRight, CSSPrimitiveValue::UnitTypes typeRight)
+    {
+        return AnimatableNumber::create(createCalc(valueLeft, typeLeft, valueRight, typeRight).get());
+    }
+
     PassRefPtr<CSSCalcValue> createCalc(double valueLeft, CSSPrimitiveValue::UnitTypes typeLeft, double valueRight, CSSPrimitiveValue::UnitTypes typeRight)
     {
         return CSSCalcValue::create(CSSCalcValue::createExpressionNode(
@@ -83,6 +91,8 @@
     {
         return toAnimatableNumber(AnimatableValue::add(numberA, numberB).get())->toCSSValue()->equals(*cssValueExpected);
     }
+
+    RefPtr<RenderStyle> style;
 };
 
 TEST_F(AnimatableNumberTest, CanCreateFrom)
@@ -191,6 +201,52 @@
         createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_IN).get()));
 }
 
+TEST_F(AnimatableNumberTest, ToLength)
+{
+    EXPECT_EQ(Length(-5, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 1));
+    EXPECT_EQ(Length(-15, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 3));
+    EXPECT_EQ(Length(0, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 1, NonNegativeValues));
+    EXPECT_EQ(Length(0, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 3, NonNegativeValues));
+
+    EXPECT_EQ(Length(-5, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 1));
+    EXPECT_EQ(Length(-5, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 3));
+    EXPECT_EQ(Length(0, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 1, NonNegativeValues));
+    EXPECT_EQ(Length(0, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 3, NonNegativeValues));
+
+    EXPECT_EQ(
+        Length(CalculationValue::create(
+            adoptPtr(new CalcExpressionBinaryOperation(
+                adoptPtr(new CalcExpressionNumber(-5)),
+                adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
+                CalcAdd)),
+            CalculationRangeAll)),
+        create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 1));
+    EXPECT_EQ(
+        Length(CalculationValue::create(
+            adoptPtr(new CalcExpressionBinaryOperation(
+                adoptPtr(new CalcExpressionNumber(-15)),
+                adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
+                CalcAdd)),
+            CalculationRangeAll)),
+        create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 3));
+    EXPECT_EQ(
+        Length(CalculationValue::create(
+            adoptPtr(new CalcExpressionBinaryOperation(
+                adoptPtr(new CalcExpressionNumber(-5)),
+                adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
+                CalcAdd)),
+            CalculationRangeNonNegative)),
+        create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 1, NonNegativeValues));
+    EXPECT_EQ(
+        Length(CalculationValue::create(
+            adoptPtr(new CalcExpressionBinaryOperation(
+                adoptPtr(new CalcExpressionNumber(-15)),
+                adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
+                CalcAdd)),
+            CalculationRangeNonNegative)),
+        create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 3, NonNegativeValues));
+}
+
 TEST_F(AnimatableNumberTest, Interpolate)
 {
     RefPtr<AnimatableNumber> from10 = create(10);
diff --git a/Source/core/animation/AnimatableValue.h b/Source/core/animation/AnimatableValue.h
index bfaa571..3c16593 100644
--- a/Source/core/animation/AnimatableValue.h
+++ b/Source/core/animation/AnimatableValue.h
@@ -36,8 +36,6 @@
 
 namespace WebCore {
 
-class CSSValue;
-
 class AnimatableValue : public RefCounted<AnimatableValue> {
 public:
     virtual ~AnimatableValue() { }
diff --git a/Source/core/animation/KeyframeAnimationEffect.cpp b/Source/core/animation/KeyframeAnimationEffect.cpp
index a9cc771..7c70831 100644
--- a/Source/core/animation/KeyframeAnimationEffect.cpp
+++ b/Source/core/animation/KeyframeAnimationEffect.cpp
@@ -140,6 +140,16 @@
     return properties;
 }
 
+PassRefPtr<Keyframe> Keyframe::cloneWithOffset(double offset) const
+{
+    RefPtr<Keyframe> clone = Keyframe::create();
+    clone->setOffset(offset);
+    clone->setComposite(m_composite);
+    for (PropertyValueMap::const_iterator iter = m_propertyValues.begin(); iter != m_propertyValues.end(); ++iter)
+        clone->setPropertyValue(iter->key, iter->value.get());
+    return clone.release();
+}
+
 
 KeyframeAnimationEffect::KeyframeAnimationEffect(const KeyframeVector& keyframes)
     : m_keyframes(keyframes)
diff --git a/Source/core/animation/KeyframeAnimationEffect.h b/Source/core/animation/KeyframeAnimationEffect.h
index fccd2c7..d826c1d 100644
--- a/Source/core/animation/KeyframeAnimationEffect.h
+++ b/Source/core/animation/KeyframeAnimationEffect.h
@@ -62,6 +62,7 @@
     void setPropertyValue(CSSPropertyID, const AnimatableValue*);
     const AnimatableValue* propertyValue(CSSPropertyID) const;
     PropertySet properties() const;
+    PassRefPtr<Keyframe> cloneWithOffset(double offset) const;
 private:
     Keyframe();
     double m_offset;
diff --git a/Source/core/animation/css/CSSAnimatableValueFactory.cpp b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
index 14933d0..bf22b53 100644
--- a/Source/core/animation/css/CSSAnimatableValueFactory.cpp
+++ b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
@@ -226,6 +226,8 @@
         return createFromLength(style->width(), style);
     case CSSPropertyVisibility:
         return AnimatableVisibility::create(style->visibility());
+    case CSSPropertyZIndex:
+        return createFromDouble(style->zIndex());
     default:
         RELEASE_ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Create AnimatableValue from render style: %s", getPropertyNameString(property).utf8().data());
         ASSERT_NOT_REACHED();
diff --git a/Source/core/animation/css/CSSAnimations.cpp b/Source/core/animation/css/CSSAnimations.cpp
index ce36831..9d4ef7b 100644
--- a/Source/core/animation/css/CSSAnimations.cpp
+++ b/Source/core/animation/css/CSSAnimations.cpp
@@ -65,7 +65,8 @@
 
 namespace WebCore {
 
-void timingFromAnimationData(const CSSAnimationData* animationData, Timing& timing)
+// Returns the default timing function.
+const PassRefPtr<TimingFunction> timingFromAnimationData(const CSSAnimationData* animationData, Timing& timing)
 {
     if (animationData->isDelaySet())
         timing.startDelay = animationData->delay();
@@ -79,16 +80,6 @@
         else
             timing.iterationCount = animationData->iterationCount();
     }
-    // For CSS animations, timing functions apply to individual keyframes, not
-    // to the complete animation.
-    // FIXME: Until chained timing functions are implemented, we simply apply
-    // the default timing function to the complete animation.
-    if (animationData->isTimingFunctionSet()) {
-        if (animationData->timingFunction()->type() != TimingFunction::LinearFunction)
-            timing.timingFunction = animationData->timingFunction();
-    } else {
-        timing.timingFunction = CSSAnimationData::initialAnimationTimingFunction();
-    }
     if (animationData->isFillModeSet()) {
         switch (animationData->fillMode()) {
         case AnimationFillModeForwards:
@@ -125,6 +116,7 @@
             ASSERT_NOT_REACHED();
         }
     }
+    return animationData->isTimingFunctionSet() ? animationData->timingFunction() : CSSAnimationData::initialAnimationTimingFunction();
 }
 
 CSSAnimationUpdateScope::CSSAnimationUpdateScope(Element* target)
@@ -186,11 +178,11 @@
                 }
             }
 
+            Timing timing;
+            RefPtr<TimingFunction> defaultTimingFunction = timingFromAnimationData(animationData, timing);
             KeyframeAnimationEffect::KeyframeVector keyframes;
-            resolver->resolveKeyframes(element, style, animationName.impl(), keyframes);
+            resolver->resolveKeyframes(element, style, animationName, defaultTimingFunction.get(), keyframes, timing.timingFunction);
             if (!keyframes.isEmpty()) {
-                Timing timing;
-                timingFromAnimationData(animationData, timing);
                 if (!update)
                     update = adoptPtr(new CSSAnimationUpdate());
                 // FIXME: crbug.com/268791 - Keyframes are already normalized, perhaps there should be a flag on KeyframeAnimationEffect to skip normalization.
diff --git a/Source/core/core.gyp b/Source/core/core.gyp
index ebfc56c..f515299 100644
--- a/Source/core/core.gyp
+++ b/Source/core/core.gyp
@@ -327,7 +327,6 @@
         }],
         ['OS=="win"', {
           'defines': [
-            'WEBCORE_NAVIGATOR_PLATFORM="Win32"',
             '__PRETTY_FUNCTION__=__FUNCTION__',
           ],
           # In generated bindings code: 'switch contains default but no case'.
@@ -397,7 +396,6 @@
       ],
       'direct_dependent_settings': {
         'defines': [
-          'WEBCORE_NAVIGATOR_VENDOR="Google Inc."',
           'WEBKIT_IMPLEMENTATION=1',
           'INSIDE_WEBKIT',
         ],
@@ -456,9 +454,6 @@
         ['OS=="mac"', {
           'direct_dependent_settings': {
             'defines': [
-              # Match Safari and Mozilla on Mac x86.
-              'WEBCORE_NAVIGATOR_PLATFORM="MacIntel"',
-
               # Chromium's version of WebCore includes the following Objective-C
               # classes. The system-provided WebCore framework may also provide
               # these classes. Because of the nature of Objective-C binding
@@ -512,8 +507,6 @@
         ['OS=="win"', {
           'direct_dependent_settings': {
             'defines': [
-              # Match Safari and Mozilla on Windows.
-              'WEBCORE_NAVIGATOR_PLATFORM="Win32"',
               '__PRETTY_FUNCTION__=__FUNCTION__',
             ],
           },
diff --git a/Source/core/core.gypi b/Source/core/core.gypi
index 8a1c624..f506b1d 100644
--- a/Source/core/core.gypi
+++ b/Source/core/core.gypi
@@ -1,6 +1,6 @@
 {
     'variables': {
-        'deprecated_perl_core_idl_files': [
+        'core_idl_files': [
             'css/CSS.idl',
             'css/CSSCharsetRule.idl',
             'css/CSSFontFaceLoadEvent.idl',
@@ -26,9 +26,12 @@
             'css/CSSViewportRule.idl',
             'css/CSSVariablesMap.idl',
             'css/Counter.idl',
-            'css/FontLoader.idl',
+            'css/FontFaceSet.idl',
+            'css/FontFace.idl',
             'css/MediaList.idl',
             'css/MediaQueryList.idl',
+            'css/RGBColor.idl',
+            'css/Rect.idl',
             'css/StyleMedia.idl',
             'css/StyleSheet.idl',
             'css/StyleSheetList.idl',
@@ -44,6 +47,7 @@
             'dom/BeforeUnloadEvent.idl',
             'dom/CDATASection.idl',
             'dom/CharacterData.idl',
+            'dom/ChildNode.idl',
             'dom/ClientRect.idl',
             'dom/ClientRectList.idl',
             'dom/Clipboard.idl',
@@ -61,6 +65,7 @@
             'dom/DataTransferItemList.idl',
             'dom/Document.idl',
             'dom/DocumentFragment.idl',
+            'dom/DocumentFullscreen.idl',
             'dom/DocumentType.idl',
             'dom/Element.idl',
             'dom/Entity.idl',
@@ -92,8 +97,10 @@
             'dom/Promise.idl',
             'dom/PromiseResolver.idl',
             'dom/Range.idl',
+            'dom/RequestAnimationFrameCallback.idl',
             'dom/ResourceProgressEvent.idl',
             'dom/SecurityPolicyViolationEvent.idl',
+            'dom/StringCallback.idl',
             'dom/Text.idl',
             'dom/TextEvent.idl',
             'dom/Touch.idl',
@@ -199,17 +206,25 @@
             'html/TimeRanges.idl',
             'html/URL.idl',
             'html/ValidityState.idl',
+            'html/VoidCallback.idl',
             'html/canvas/ANGLEInstancedArrays.idl',
             'html/canvas/CanvasGradient.idl',
+            'html/canvas/CanvasPattern.idl',
             'html/canvas/CanvasRenderingContext.idl',
             'html/canvas/CanvasRenderingContext2D.idl',
             'html/canvas/Canvas2DContextAttributes.idl',
+            'html/canvas/EXTFragDepth.idl',
             'html/canvas/EXTTextureFilterAnisotropic.idl',
+            'html/canvas/OESElementIndexUint.idl',
             'html/canvas/OESStandardDerivatives.idl',
+            'html/canvas/OESTextureFloat.idl',
+            'html/canvas/OESTextureFloatLinear.idl',
             'html/canvas/OESTextureHalfFloat.idl',
+            'html/canvas/OESTextureHalfFloatLinear.idl',
             'html/canvas/OESVertexArrayObject.idl',
             'html/canvas/Path.idl',
             'html/canvas/WebGLActiveInfo.idl',
+            'html/canvas/WebGLBuffer.idl',
             'html/canvas/WebGLCompressedTextureATC.idl',
             'html/canvas/WebGLCompressedTexturePVRTC.idl',
             'html/canvas/WebGLCompressedTextureS3TC.idl',
@@ -219,9 +234,16 @@
             'html/canvas/WebGLDebugShaders.idl',
             'html/canvas/WebGLDepthTexture.idl',
             'html/canvas/WebGLDrawBuffers.idl',
+            'html/canvas/WebGLFramebuffer.idl',
             'html/canvas/WebGLLoseContext.idl',
+            'html/canvas/WebGLProgram.idl',
+            'html/canvas/WebGLRenderbuffer.idl',
             'html/canvas/WebGLRenderingContext.idl',
+            'html/canvas/WebGLShader.idl',
             'html/canvas/WebGLShaderPrecisionFormat.idl',
+            'html/canvas/WebGLTexture.idl',
+            'html/canvas/WebGLUniformLocation.idl',
+            'html/canvas/WebGLVertexArrayObjectOES.idl',
             'html/ime/Composition.idl',
             'html/ime/InputMethodContext.idl',
             'html/shadow/HTMLContentElement.idl',
@@ -238,6 +260,7 @@
             'inspector/InspectorOverlayHost.idl',
             'inspector/JavaScriptCallFrame.idl',
             'loader/appcache/ApplicationCache.idl',
+            'page/PerformanceNavigation.idl',
             'page/BarProp.idl',
             'page/ConsoleBase.idl',
             'page/Console.idl',
@@ -245,6 +268,7 @@
             'page/History.idl',
             'page/ImageBitmap.idl',
             'page/Location.idl',
+            'page/MemoryInfo.idl',
             'page/Navigator.idl',
             'page/NavigatorID.idl',
             'page/NavigatorOnLine.idl',
@@ -263,6 +287,9 @@
             'page/SpeechInputResultList.idl',
             'page/WebKitPoint.idl',
             'page/Window.idl',
+            'page/WindowBase64.idl',
+            'page/WindowPagePopup.idl',
+            'page/WindowTimers.idl',
             'page/WorkerNavigator.idl',
             'plugins/MimeType.idl',
             'plugins/MimeTypeArray.idl',
@@ -270,6 +297,7 @@
             'plugins/PluginArray.idl',
             'storage/Storage.idl',
             'storage/StorageEvent.idl',
+            'workers/AbstractWorker.idl',
             'workers/DedicatedWorkerGlobalScope.idl',
             'workers/SharedWorker.idl',
             'workers/SharedWorkerGlobalScope.idl',
@@ -278,6 +306,7 @@
             'workers/WorkerConsole.idl',
             'workers/WorkerLocation.idl',
             'xml/DOMParser.idl',
+            'xml/DocumentXPathEvaluator.idl',
             'xml/XMLHttpRequest.idl',
             'xml/XMLHttpRequestEventTarget.idl',
             'xml/XMLHttpRequestProgressEvent.idl',
@@ -289,37 +318,7 @@
             'xml/XPathResult.idl',
             'xml/XSLTProcessor.idl',
         ],
-        'python_core_idl_files': [
-            'css/RGBColor.idl',
-            'css/Rect.idl',
-            'dom/ChildNode.idl',
-            'dom/DocumentFullscreen.idl',
-            'dom/RequestAnimationFrameCallback.idl',
-            'dom/StringCallback.idl',
-            'html/VoidCallback.idl',
-            'html/canvas/CanvasPattern.idl',
-            'html/canvas/EXTFragDepth.idl',
-            'html/canvas/OESElementIndexUint.idl',
-            'html/canvas/OESTextureFloat.idl',
-            'html/canvas/OESTextureFloatLinear.idl',
-            'html/canvas/OESTextureHalfFloatLinear.idl',
-            'html/canvas/WebGLBuffer.idl',
-            'html/canvas/WebGLFramebuffer.idl',
-            'html/canvas/WebGLProgram.idl',
-            'html/canvas/WebGLRenderbuffer.idl',
-            'html/canvas/WebGLShader.idl',
-            'html/canvas/WebGLTexture.idl',
-            'html/canvas/WebGLUniformLocation.idl',
-            'html/canvas/WebGLVertexArrayObjectOES.idl',
-            'page/MemoryInfo.idl',
-            'page/PerformanceNavigation.idl',
-            'page/WindowBase64.idl',
-            'page/WindowPagePopup.idl',
-            'page/WindowTimers.idl',
-            'workers/AbstractWorker.idl',
-            'xml/DocumentXPathEvaluator.idl',
-        ],
-        'deprecated_perl_svg_idl_files': [
+        'svg_idl_files': [
             'svg/SVGAElement.idl',
             'svg/SVGAltGlyphDefElement.idl',
             'svg/SVGAltGlyphElement.idl',
@@ -354,6 +353,7 @@
             'svg/SVGElementInstance.idl',
             'svg/SVGElementInstanceList.idl',
             'svg/SVGEllipseElement.idl',
+            'svg/SVGExternalResourcesRequired.idl',
             'svg/SVGFEBlendElement.idl',
             'svg/SVGFEColorMatrixElement.idl',
             'svg/SVGFEComponentTransferElement.idl',
@@ -380,6 +380,8 @@
             'svg/SVGFETileElement.idl',
             'svg/SVGFETurbulenceElement.idl',
             'svg/SVGFilterElement.idl',
+            'svg/SVGFilterPrimitiveStandardAttributes.idl',
+            'svg/SVGFitToViewBox.idl',
             'svg/SVGFontElement.idl',
             'svg/SVGFontFaceElement.idl',
             'svg/SVGFontFaceFormatElement.idl',
@@ -448,6 +450,7 @@
             'svg/SVGSwitchElement.idl',
             'svg/SVGSymbolElement.idl',
             'svg/SVGTSpanElement.idl',
+            'svg/SVGTests.idl',
             'svg/SVGTextContentElement.idl',
             'svg/SVGTextElement.idl',
             'svg/SVGTextPathElement.idl',
@@ -455,20 +458,14 @@
             'svg/SVGTitleElement.idl',
             'svg/SVGTransform.idl',
             'svg/SVGTransformList.idl',
+            'svg/SVGURIReference.idl',
             'svg/SVGUnitTypes.idl',
             'svg/SVGUseElement.idl',
             'svg/SVGVKernElement.idl',
             'svg/SVGViewElement.idl',
             'svg/SVGViewSpec.idl',
-            'svg/SVGZoomEvent.idl',
-        ],
-        'python_svg_idl_files': [
-            'svg/SVGExternalResourcesRequired.idl',
-            'svg/SVGFilterPrimitiveStandardAttributes.idl',
-            'svg/SVGFitToViewBox.idl',
-            'svg/SVGTests.idl',
-            'svg/SVGURIReference.idl',
             'svg/SVGZoomAndPan.idl',
+            'svg/SVGZoomEvent.idl',
         ],
         'webcore_files': [
             'Init.cpp',
@@ -689,10 +686,12 @@
             'css/DocumentRuleSets.h',
             'css/ElementRuleCollector.cpp',
             'css/ElementRuleCollector.h',
+            'css/FontFaceSet.h',
+            'css/FontFaceSet.cpp',
+            'css/FontFace.cpp',
+            'css/FontFace.h',
             'css/FontFeatureValue.cpp',
             'css/FontFeatureValue.h',
-            'css/FontLoader.h',
-            'css/FontLoader.cpp',
             'css/FontSize.cpp',
             'css/FontSize.h',
             'css/FontValue.cpp',
@@ -1215,7 +1214,6 @@
             'page/MouseEventWithHitTestResults.h',
             'page/Navigator.cpp',
             'page/Navigator.h',
-            'page/NavigatorBase.cpp',
             'page/NavigatorBase.h',
             'page/NavigatorID.cpp',
             'page/NavigatorID.h',
@@ -1311,17 +1309,19 @@
             'plugins/DOMPlugin.h',
             'plugins/DOMPluginArray.cpp',
             'plugins/DOMPluginArray.h',
-            'plugins/IFrameShimSupport.cpp',
-            'plugins/IFrameShimSupport.h',
             'plugins/PluginData.cpp',
             'plugins/PluginData.h',
             'plugins/PluginListBuilder.cpp',
             'plugins/PluginListBuilder.h',
+            'plugins/PluginOcclusionSupport.cpp',
+            'plugins/PluginOcclusionSupport.h',
             'plugins/PluginView.h',
             'rendering/AutoTableLayout.cpp',
             'rendering/AutoTableLayout.h',
             'rendering/BidiRun.cpp',
             'rendering/BidiRun.h',
+            'rendering/ClipRect.cpp',
+            'rendering/ClipRect.h',
             'rendering/CompositingReasons.h',
             'rendering/CounterNode.cpp',
             'rendering/CounterNode.h',
@@ -1354,6 +1354,8 @@
             'rendering/LayoutIndicator.cpp',
             'rendering/LayoutIndicator.h',
             'rendering/LayoutRepainter.cpp',
+            'rendering/LineWidth.cpp',
+            'rendering/LineWidth.h',
             'rendering/PartialLayoutState.h',
             'rendering/Pagination.cpp',
             'rendering/Pagination.h',
@@ -1522,6 +1524,8 @@
             'rendering/RenderWidget.cpp',
             'rendering/RenderWordBreak.cpp',
             'rendering/RenderWordBreak.h',
+            'rendering/RenderingConfiguration.cpp',
+            'rendering/RenderingConfiguration.h',
             'rendering/RenderingNodeProxy.cpp',
             'rendering/RenderingNodeProxy.h',
             'rendering/RootInlineBox.cpp',
@@ -1942,7 +1946,6 @@
             'dom/NodeTraversal.cpp',
             'dom/NodeTraversal.h',
             'dom/NodeWithIndex.h',
-            'dom/Notation.cpp',
             'dom/Notation.h',
             'dom/OverflowEvent.cpp',
             'dom/OverflowEvent.h',
@@ -1997,10 +2000,10 @@
             'dom/StringCallback.h',
             'dom/StyleElement.cpp',
             'dom/StyleElement.h',
+            'dom/StyleEngine.cpp',
+            'dom/StyleEngine.h',
             'dom/StyleSheetCollection.cpp',
             'dom/StyleSheetCollection.h',
-            'dom/StyleSheetCollections.cpp',
-            'dom/StyleSheetCollections.h',
             'dom/StyleSheetScopingNodeList.cpp',
             'dom/StyleSheetScopingNodeList.h',
             'dom/TagNodeList.cpp',
@@ -2012,6 +2015,8 @@
             'dom/TextLinkColors.h',
             'dom/Touch.cpp',
             'dom/Touch.h',
+            'dom/TouchController.cpp',
+            'dom/TouchController.h',
             'dom/TouchEvent.cpp',
             'dom/TouchEvent.h',
             'dom/TouchList.cpp',
@@ -3714,20 +3719,18 @@
             'svg/properties/SVGAnimatedPathSegListPropertyTearOff.h',
             'svg/properties/SVGPathSegListPropertyTearOff.cpp',
         ],
-        'deprecated_perl_webcore_test_support_idl_files': [
+        'webcore_test_support_idl_files': [
           'testing/GCObservation.idl',
           'testing/Internals.idl',
           'testing/InternalProfilers.idl',
           'testing/InternalSettings.idl',
           'testing/LayerRect.idl',
           'testing/LayerRectList.idl',
+          'testing/MallocStatistics.idl',
           'testing/TypeConversions.idl',
           '<(SHARED_INTERMEDIATE_DIR)/blink/InternalSettingsGenerated.idl',
           '<(SHARED_INTERMEDIATE_DIR)/blink/InternalRuntimeFlags.idl',
         ],
-        'python_webcore_test_support_idl_files': [
-          'testing/MallocStatistics.idl',
-        ],
         'webcore_test_support_files': [
             'testing/v8/WebCoreTestSupport.cpp',
             'testing/v8/WebCoreTestSupport.h',
@@ -3858,6 +3861,10 @@
             'tests/TreeTestHelpers.h',
         ],
         'scripts_for_in_files': [
+            # jinja2/__init__.py contains version string, so sufficient as
+            # dependency for whole jinja2 package
+            '<(DEPTH)/third_party/jinja2/__init__.py',
+            '<(DEPTH)/third_party/markupsafe/__init__.py',  # jinja2 dep
             'scripts/in_file.py',
             'scripts/in_generator.py',
             'scripts/license.py',
diff --git a/Source/core/css/CSSComputedStyleDeclaration.cpp b/Source/core/css/CSSComputedStyleDeclaration.cpp
index dd2e82d..9be152f 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -999,10 +999,8 @@
 
 static PassRefPtr<CSSValue> valueForGridTrackBreadth(const GridLength& trackBreadth, const RenderStyle* style, RenderView* renderView)
 {
-    if (!trackBreadth.isLength()) {
-        String flex = String::number(trackBreadth.flex()) + "fr";
-        return cssValuePool().createValue(flex, CSSPrimitiveValue::CSS_DIMENSION);
-    }
+    if (!trackBreadth.isLength())
+        return cssValuePool().createValue(trackBreadth.flex(), CSSPrimitiveValue::CSS_FR);
 
     const Length& trackBreadthLength = trackBreadth.length();
     if (trackBreadthLength.isAuto())
diff --git a/Source/core/css/CSSFontFace.cpp b/Source/core/css/CSSFontFace.cpp
index efb19e2..c667aaa 100644
--- a/Source/core/css/CSSFontFace.cpp
+++ b/Source/core/css/CSSFontFace.cpp
@@ -29,7 +29,7 @@
 #include "core/css/CSSFontFaceSource.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSSegmentedFontFace.h"
-#include "core/css/FontLoader.h"
+#include "core/css/FontFaceSet.h"
 #include "core/dom/Document.h"
 #include "core/platform/graphics/SimpleFontData.h"
 
@@ -67,6 +67,18 @@
     m_segmentedFontFace = segmentedFontFace;
 }
 
+void CSSFontFace::beginLoadingFontSoon(FontResource* resource)
+{
+    if (!m_segmentedFontFace)
+        return;
+
+    CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
+    fontSelector->beginLoadingFontSoon(resource);
+
+    if (loadStatus() == FontFace::Unloaded)
+        setLoadStatus(FontFace::Loading);
+}
+
 void CSSFontFace::fontLoaded(CSSFontFaceSource* source)
 {
     if (source != m_activeSource)
@@ -81,11 +93,11 @@
     CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
     fontSelector->fontLoaded();
 
-    if (fontSelector->document() && m_loadState == Loading) {
+    if (fontSelector->document() && loadStatus() == FontFace::Loading) {
         if (source->ensureFontData())
-            setLoadState(Loaded);
+            setLoadStatus(FontFace::Loaded);
         else if (!isValid())
-            setLoadState(Error);
+            setLoadStatus(FontFace::Error);
     }
 
     m_segmentedFontFace->fontLoaded(this);
@@ -100,27 +112,28 @@
     ASSERT(m_segmentedFontFace);
     CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
 
-    if (m_loadState == NotLoaded)
-        setLoadState(Loading);
-
     size_t size = m_sources.size();
     for (size_t i = 0; i < size; ++i) {
         if (RefPtr<SimpleFontData> result = m_sources[i]->getFontData(fontDescription, syntheticBold, syntheticItalic, fontSelector)) {
             m_activeSource = m_sources[i].get();
-            if (m_loadState == Loading && m_sources[i]->isLoaded())
-                setLoadState(Loaded);
+            if (loadStatus() == FontFace::Unloaded && (m_sources[i]->isLoading() || m_sources[i]->isLoaded()))
+                setLoadStatus(FontFace::Loading);
+            if (loadStatus() == FontFace::Loading && m_sources[i]->isLoaded())
+                setLoadStatus(FontFace::Loaded);
             return result.release();
         }
     }
 
-    if (m_loadState == Loading)
-        setLoadState(Error);
+    if (loadStatus() == FontFace::Unloaded)
+        setLoadStatus(FontFace::Loading);
+    if (loadStatus() == FontFace::Loading)
+        setLoadStatus(FontFace::Error);
     return 0;
 }
 
 void CSSFontFace::willUseFontData(const FontDescription& fontDescription)
 {
-    if (m_loadState != NotLoaded)
+    if (loadStatus() != FontFace::Unloaded)
         return;
 
     ASSERT(m_segmentedFontFace);
@@ -136,23 +149,24 @@
     }
 }
 
-void CSSFontFace::setLoadState(LoadState newState)
+void CSSFontFace::setLoadStatus(FontFace::LoadStatus newStatus)
 {
-    m_loadState = newState;
+    ASSERT(m_fontFace);
+    m_fontFace->setLoadStatus(newStatus);
 
     Document* document = m_segmentedFontFace->fontSelector()->document();
     if (!document)
         return;
 
-    switch (newState) {
-    case Loading:
-        document->fontloader()->beginFontLoading(m_rule.get());
+    switch (newStatus) {
+    case FontFace::Loading:
+        document->fonts()->beginFontLoading(m_fontFace.get());
         break;
-    case Loaded:
-        document->fontloader()->fontLoaded(m_rule.get());
+    case FontFace::Loaded:
+        document->fonts()->fontLoaded(m_fontFace.get());
         break;
-    case Error:
-        document->fontloader()->loadError(m_rule.get(), m_activeSource);
+    case FontFace::Error:
+        document->fonts()->loadError(m_fontFace.get());
         break;
     default:
         break;
diff --git a/Source/core/css/CSSFontFace.h b/Source/core/css/CSSFontFace.h
index 1b40b34..7ada75e 100644
--- a/Source/core/css/CSSFontFace.h
+++ b/Source/core/css/CSSFontFace.h
@@ -26,8 +26,8 @@
 #ifndef CSSFontFace_h
 #define CSSFontFace_h
 
-#include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSFontFaceSource.h"
+#include "core/css/FontFace.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
@@ -37,14 +37,18 @@
 
 class CSSSegmentedFontFace;
 class FontDescription;
+class FontResource;
 class SimpleFontData;
 
+// FIXME: Can this be a subclass of FontFace?
 class CSSFontFace : public RefCounted<CSSFontFace> {
 public:
-    static PassRefPtr<CSSFontFace> create(PassRefPtr<CSSFontFaceRule> rule, bool isLocalFallback = false) { return adoptRef(new CSSFontFace(rule, isLocalFallback)); }
+    static PassRefPtr<CSSFontFace> create(PassRefPtr<FontFace> fontFace) { return adoptRef(new CSSFontFace(fontFace)); }
 
     struct UnicodeRange;
 
+    FontFace* fontFace() const { return m_fontFace.get(); }
+
     void addRange(UChar32 from, UChar32 to) { m_ranges.append(UnicodeRange(from, to)); }
     const Vector<UnicodeRange>& ranges() const { return m_ranges; }
 
@@ -56,6 +60,7 @@
 
     void addSource(PassOwnPtr<CSSFontFaceSource>);
 
+    void beginLoadingFontSoon(FontResource*);
     void fontLoaded(CSSFontFaceSource*);
 
     PassRefPtr<SimpleFontData> getFontData(const FontDescription&, bool syntheticBold, bool syntheticItalic);
@@ -79,27 +84,23 @@
     bool hasSVGFontFaceSource() const;
 #endif
 
-    enum LoadState { NotLoaded, Loading, Loaded, Error };
-    LoadState loadState() const { return m_loadState; }
+    FontFace::LoadStatus loadStatus() const { return m_fontFace ? m_fontFace->loadStatus() : FontFace::Loaded; }
     void willUseFontData(const FontDescription&);
 
 private:
-    CSSFontFace(PassRefPtr<CSSFontFaceRule> rule, bool isLocalFallback)
+    CSSFontFace(PassRefPtr<FontFace> fontFace)
         : m_segmentedFontFace(0)
         , m_activeSource(0)
-        , m_loadState(isLocalFallback ? Loaded : NotLoaded)
-        , m_rule(rule)
+        , m_fontFace(fontFace)
     {
-        UNUSED_PARAM(rule);
     }
-    void setLoadState(LoadState);
+    void setLoadStatus(FontFace::LoadStatus);
 
     Vector<UnicodeRange> m_ranges;
     CSSSegmentedFontFace* m_segmentedFontFace;
     Vector<OwnPtr<CSSFontFaceSource> > m_sources;
     CSSFontFaceSource* m_activeSource;
-    LoadState m_loadState;
-    RefPtr<CSSFontFaceRule> m_rule;
+    RefPtr<FontFace> m_fontFace;
 };
 
 }
diff --git a/Source/core/css/CSSFontFaceLoadEvent.cpp b/Source/core/css/CSSFontFaceLoadEvent.cpp
index 80ca0c9..58a5e4f 100644
--- a/Source/core/css/CSSFontFaceLoadEvent.cpp
+++ b/Source/core/css/CSSFontFaceLoadEvent.cpp
@@ -38,18 +38,16 @@
     ScriptWrappable::init(this);
 }
 
-CSSFontFaceLoadEvent::CSSFontFaceLoadEvent(const AtomicString& type, PassRefPtr<CSSFontFaceRule> fontface, PassRefPtr<DOMError> error)
+CSSFontFaceLoadEvent::CSSFontFaceLoadEvent(const AtomicString& type, const FontFaceArray& fontfaces)
     : Event(type, false, false)
-    , m_fontface(fontface)
-    , m_error(error)
+    , m_fontfaces(fontfaces)
 {
     ScriptWrappable::init(this);
 }
 
 CSSFontFaceLoadEvent::CSSFontFaceLoadEvent(const AtomicString& type, const CSSFontFaceLoadEventInit& initializer)
     : Event(type, initializer)
-    , m_fontface(initializer.fontface)
-    , m_error(initializer.error)
+    , m_fontfaces(initializer.fontfaces)
 {
     ScriptWrappable::init(this);
 }
diff --git a/Source/core/css/CSSFontFaceLoadEvent.h b/Source/core/css/CSSFontFaceLoadEvent.h
index c2aca89..84b674c 100644
--- a/Source/core/css/CSSFontFaceLoadEvent.h
+++ b/Source/core/css/CSSFontFaceLoadEvent.h
@@ -31,7 +31,7 @@
 #ifndef CSSFontFaceLoadEvent_h
 #define CSSFontFaceLoadEvent_h
 
-#include "core/css/CSSFontFaceRule.h"
+#include "core/css/FontFace.h"
 #include "core/dom/DOMError.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
@@ -41,8 +41,7 @@
 namespace WebCore {
 
 struct CSSFontFaceLoadEventInit : public EventInit {
-    RefPtr<CSSFontFaceRule> fontface;
-    RefPtr<DOMError> error;
+    FontFaceArray fontfaces;
 };
 
 class CSSFontFaceLoadEvent : public Event {
@@ -57,30 +56,23 @@
         return adoptRef<CSSFontFaceLoadEvent>(new CSSFontFaceLoadEvent(type, initializer));
     }
 
-    static PassRefPtr<CSSFontFaceLoadEvent> createForFontFaceRule(const AtomicString& type, PassRefPtr<CSSFontFaceRule> rule)
+    static PassRefPtr<CSSFontFaceLoadEvent> createForFontFaces(const AtomicString& type, const FontFaceArray& fontfaces = FontFaceArray())
     {
-        return adoptRef<CSSFontFaceLoadEvent>(new CSSFontFaceLoadEvent(type, rule, 0));
-    }
-
-    static PassRefPtr<CSSFontFaceLoadEvent> createForError(PassRefPtr<CSSFontFaceRule> rule, PassRefPtr<DOMError> error)
-    {
-        return adoptRef<CSSFontFaceLoadEvent>(new CSSFontFaceLoadEvent(eventNames().errorEvent, rule, error));
+        return adoptRef<CSSFontFaceLoadEvent>(new CSSFontFaceLoadEvent(type, fontfaces));
     }
 
     virtual ~CSSFontFaceLoadEvent();
 
-    CSSFontFaceRule* fontface() const { return m_fontface.get(); }
-    DOMError* error() const { return m_error.get(); }
+    FontFaceArray fontfaces() const { return m_fontfaces; }
 
     virtual const AtomicString& interfaceName() const;
 
 private:
     CSSFontFaceLoadEvent();
-    CSSFontFaceLoadEvent(const AtomicString&, PassRefPtr<CSSFontFaceRule>, PassRefPtr<DOMError>);
+    CSSFontFaceLoadEvent(const AtomicString&, const FontFaceArray&);
     CSSFontFaceLoadEvent(const AtomicString&, const CSSFontFaceLoadEventInit&);
 
-    RefPtr<CSSFontFaceRule> m_fontface;
-    RefPtr<DOMError> m_error;
+    FontFaceArray m_fontfaces;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSFontFaceLoadEvent.idl b/Source/core/css/CSSFontFaceLoadEvent.idl
index 7a1b32b..7ab2522 100644
--- a/Source/core/css/CSSFontFaceLoadEvent.idl
+++ b/Source/core/css/CSSFontFaceLoadEvent.idl
@@ -28,11 +28,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+// FIXME: Make this constructable from Javascript
 [
     NoInterfaceObject,
     EnabledAtRuntime=FontLoadEvents,
-    ConstructorTemplate=Event
 ] interface CSSFontFaceLoadEvent : Event {
-    [InitializedByEventConstructor] readonly attribute CSSFontFaceRule fontface;
-    [InitializedByEventConstructor] readonly attribute DOMError error;
+    readonly attribute FontFace[] fontfaces;
 };
diff --git a/Source/core/css/CSSFontFaceRule.h b/Source/core/css/CSSFontFaceRule.h
index a042e8f..1be5c3a 100644
--- a/Source/core/css/CSSFontFaceRule.h
+++ b/Source/core/css/CSSFontFaceRule.h
@@ -42,6 +42,8 @@
 
     CSSStyleDeclaration* style() const;
 
+    StyleRuleFontFace* styleRule() const { return m_fontFaceRule.get(); }
+
 private:
     CSSFontFaceRule(StyleRuleFontFace*, CSSStyleSheet* parent);
 
@@ -49,6 +51,12 @@
     mutable RefPtr<StyleRuleCSSStyleDeclaration> m_propertiesCSSOMWrapper;
 };
 
+inline CSSFontFaceRule* toCSSFontFaceRule(CSSRule* rule)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(rule->type() == CSSRule::FONT_FACE_RULE);
+    return static_cast<CSSFontFaceRule*>(rule);
+}
+
 } // namespace WebCore
 
 #endif // CSSFontFaceRule_h
diff --git a/Source/core/css/CSSFontFaceSource.cpp b/Source/core/css/CSSFontFaceSource.cpp
index 264c496..911f28e 100644
--- a/Source/core/css/CSSFontFaceSource.cpp
+++ b/Source/core/css/CSSFontFaceSource.cpp
@@ -68,6 +68,10 @@
     if (m_fontDataTable.isEmpty())
         return;
 
+    for (FontDataTable::iterator it = m_fontDataTable.begin(); it != m_fontDataTable.end(); ++it) {
+        if (SimpleFontData* fontData = it->value.get())
+            fontData->clearCSSFontFaceSource();
+    }
     m_fontDataTable.clear();
 }
 
@@ -82,6 +86,13 @@
     return true;
 }
 
+bool CSSFontFaceSource::isLoading() const
+{
+    if (m_font)
+        return !m_font->stillNeedsLoad() && !m_font->isLoaded();
+    return false;
+}
+
 bool CSSFontFaceSource::isLoaded() const
 {
     if (m_font)
@@ -193,14 +204,11 @@
 #endif
         }
     } else {
-        // Kick off the load. Do it soon rather than now, because we may be in the middle of layout,
-        // and the loader may invoke arbitrary delegate or event handler code.
-        fontSelector->beginLoadingFontSoon(m_font.get());
-
         // This temporary font is not retained and should not be returned.
         FontCachePurgePreventer fontCachePurgePreventer;
         SimpleFontData* temporaryFont = fontCache()->getNonRetainedLastResortFallbackFont(fontDescription);
         fontData = SimpleFontData::create(temporaryFont->platformData(), true, true);
+        fontData->setCSSFontFaceSource(this);
     }
 
     return fontData; // No release, because fontData is a reference to a RefPtr that is held in the m_fontDataTable.
@@ -254,6 +262,13 @@
         m_font->willUseFontData();
 }
 
+void CSSFontFaceSource::beginLoadingFontSoon()
+{
+    ASSERT(m_face);
+    ASSERT(m_font);
+    m_face->beginLoadingFontSoon(m_font.get());
+}
+
 void CSSFontFaceSource::FontLoadHistograms::loadStarted()
 {
     if (!m_loadStartTime)
diff --git a/Source/core/css/CSSFontFaceSource.h b/Source/core/css/CSSFontFaceSource.h
index 6414ae6..6cdabfd 100644
--- a/Source/core/css/CSSFontFaceSource.h
+++ b/Source/core/css/CSSFontFaceSource.h
@@ -51,6 +51,7 @@
     virtual ~CSSFontFaceSource();
 
     bool isLocal() const;
+    bool isLoading() const;
     bool isLoaded() const;
     bool isValid() const;
 
@@ -76,8 +77,11 @@
     bool ensureFontData();
     bool isLocalFontAvailable(const FontDescription&);
     void willUseFontData();
+    void beginLoadingFontSoon();
 
 private:
+    typedef HashMap<unsigned, RefPtr<SimpleFontData> > FontDataTable; // The hash key is composed of size synthetic styles.
+
     class FontLoadHistograms {
     public:
         FontLoadHistograms() : m_loadStartTime(0) { }
@@ -95,7 +99,7 @@
     AtomicString m_string; // URI for remote, built-in font name for local.
     ResourcePtr<FontResource> m_font; // For remote fonts, a pointer to our cached resource.
     CSSFontFace* m_face; // Our owning font face.
-    HashMap<unsigned, RefPtr<SimpleFontData> > m_fontDataTable; // The hash key is composed of size synthetic styles.
+    FontDataTable m_fontDataTable;
     FontLoadHistograms m_histograms;
 
 #if ENABLE(SVG_FONTS)
diff --git a/Source/core/css/CSSFontFaceSrcValue.h b/Source/core/css/CSSFontFaceSrcValue.h
index 9129f1c..992448e 100644
--- a/Source/core/css/CSSFontFaceSrcValue.h
+++ b/Source/core/css/CSSFontFaceSrcValue.h
@@ -95,6 +95,12 @@
 #endif
 };
 
+inline CSSFontFaceSrcValue* toCSSFontFaceSrcValue(CSSValue* value)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isFontFaceSrcValue());
+    return static_cast<CSSFontFaceSrcValue*>(value);
+}
+
 }
 
 #endif
diff --git a/Source/core/css/CSSFontSelector.cpp b/Source/core/css/CSSFontSelector.cpp
index b608878..bfe6bfe 100644
--- a/Source/core/css/CSSFontSelector.cpp
+++ b/Source/core/css/CSSFontSelector.cpp
@@ -27,20 +27,13 @@
 #include "config.h"
 #include "core/css/CSSFontSelector.h"
 
-#include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
 #include "FontFamilyNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSFontFace.h"
 #include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSFontFaceSource.h"
-#include "core/css/CSSFontFaceSrcValue.h"
-#include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSSegmentedFontFace.h"
-#include "core/css/CSSUnicodeRangeValue.h"
 #include "core/css/CSSValueList.h"
-#include "core/css/StylePropertySet.h"
-#include "core/css/StyleRule.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/fetch/FontResource.h"
@@ -50,7 +43,6 @@
 #include "core/page/Settings.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/SimpleFontData.h"
-#include "core/svg/SVGFontFaceElement.h"
 #include "wtf/text/AtomicString.h"
 
 using namespace std;
@@ -83,224 +75,32 @@
 
 void CSSFontSelector::addFontFaceRule(const StyleRuleFontFace* fontFaceRule)
 {
-    // Obtain the font-family property and the src property.  Both must be defined.
-    const StylePropertySet* style = fontFaceRule->properties();
-    RefPtr<CSSValue> fontFamily = style->getPropertyCSSValue(CSSPropertyFontFamily);
-    RefPtr<CSSValue> src = style->getPropertyCSSValue(CSSPropertySrc);
-    RefPtr<CSSValue> unicodeRange = style->getPropertyCSSValue(CSSPropertyUnicodeRange);
-    if (!fontFamily || !src || !fontFamily->isValueList() || !src->isValueList() || (unicodeRange && !unicodeRange->isValueList()))
+    RefPtr<FontFace> fontFace = FontFace::create(fontFaceRule);
+    if (!fontFace || fontFace->family().isEmpty())
         return;
 
-    // The font-family descriptor has to have exactly one family name.
-    CSSValueList* familyList = toCSSValueList(fontFamily.get());
-    if (familyList->length() != 1)
+    unsigned traitsMask = fontFace->traitsMask();
+    if (!traitsMask)
         return;
 
-    CSSValueList* srcList = toCSSValueList(src.get());
-    if (!srcList->length())
+    RefPtr<CSSFontFace> cssFontFace = fontFace->createCSSFontFace(m_document);
+    if (!cssFontFace || !cssFontFace->isValid())
         return;
 
-    CSSValueList* rangeList = toCSSValueList(unicodeRange.get());
-
-    unsigned traitsMask = 0;
-
-    if (RefPtr<CSSValue> fontStyle = style->getPropertyCSSValue(CSSPropertyFontStyle)) {
-        if (!fontStyle->isPrimitiveValue())
-            return;
-
-        switch (toCSSPrimitiveValue(fontStyle.get())->getValueID()) {
-        case CSSValueNormal:
-            traitsMask |= FontStyleNormalMask;
-            break;
-        case CSSValueItalic:
-        case CSSValueOblique:
-            traitsMask |= FontStyleItalicMask;
-            break;
-        default:
-            break;
-        }
-    } else
-        traitsMask |= FontStyleNormalMask;
-
-    if (RefPtr<CSSValue> fontWeight = style->getPropertyCSSValue(CSSPropertyFontWeight)) {
-        if (!fontWeight->isPrimitiveValue())
-            return;
-
-        switch (toCSSPrimitiveValue(fontWeight.get())->getValueID()) {
-        case CSSValueBold:
-        case CSSValue700:
-            traitsMask |= FontWeight700Mask;
-            break;
-        case CSSValueNormal:
-        case CSSValue400:
-            traitsMask |= FontWeight400Mask;
-            break;
-        case CSSValue900:
-            traitsMask |= FontWeight900Mask;
-            break;
-        case CSSValue800:
-            traitsMask |= FontWeight800Mask;
-            break;
-        case CSSValue600:
-            traitsMask |= FontWeight600Mask;
-            break;
-        case CSSValue500:
-            traitsMask |= FontWeight500Mask;
-            break;
-        case CSSValue300:
-            traitsMask |= FontWeight300Mask;
-            break;
-        case CSSValue200:
-            traitsMask |= FontWeight200Mask;
-            break;
-        case CSSValue100:
-            traitsMask |= FontWeight100Mask;
-            break;
-        default:
-            break;
-        }
-    } else
-        traitsMask |= FontWeight400Mask;
-
-    if (RefPtr<CSSValue> fontVariant = style->getPropertyCSSValue(CSSPropertyFontVariant)) {
-        // font-variant descriptor can be a value list.
-        if (fontVariant->isPrimitiveValue()) {
-            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
-            list->append(fontVariant);
-            fontVariant = list;
-        } else if (!fontVariant->isValueList())
-            return;
-
-        CSSValueList* variantList = toCSSValueList(fontVariant.get());
-        unsigned numVariants = variantList->length();
-        if (!numVariants)
-            return;
-
-        for (unsigned i = 0; i < numVariants; ++i) {
-            switch (toCSSPrimitiveValue(variantList->itemWithoutBoundsCheck(i))->getValueID()) {
-                case CSSValueNormal:
-                    traitsMask |= FontVariantNormalMask;
-                    break;
-                case CSSValueSmallCaps:
-                    traitsMask |= FontVariantSmallCapsMask;
-                    break;
-                default:
-                    break;
-            }
-        }
-    } else {
-        traitsMask |= FontVariantNormalMask;
-    }
-
-    // Each item in the src property's list is a single CSSFontFaceSource. Put them all into a CSSFontFace.
-    RefPtr<CSSFontFace> fontFace;
-
-    int srcLength = srcList->length();
-
-    bool foundSVGFont = false;
-
-    for (int i = 0; i < srcLength; i++) {
-        // An item in the list either specifies a string (local font name) or a URL (remote font to download).
-        CSSFontFaceSrcValue* item = static_cast<CSSFontFaceSrcValue*>(srcList->itemWithoutBoundsCheck(i));
-        OwnPtr<CSSFontFaceSource> source;
-
-#if ENABLE(SVG_FONTS)
-        foundSVGFont = item->isSVGFontFaceSrc() || item->svgFontFaceElement();
-#endif
-        if (!item->isLocal()) {
-            Settings* settings = m_document ? m_document->frame() ? m_document->frame()->settings() : 0 : 0;
-            bool allowDownloading = foundSVGFont || (settings && settings->downloadableBinaryFontsEnabled());
-            if (allowDownloading && item->isSupportedFormat() && m_document) {
-                FontResource* fetched = item->fetch(m_document);
-                if (fetched) {
-                    source = adoptPtr(new CSSFontFaceSource(item->resource(), fetched));
-#if ENABLE(SVG_FONTS)
-                    if (foundSVGFont)
-                        source->setHasExternalSVGFont(true);
-#endif
-                }
-            }
-        } else {
-            source = adoptPtr(new CSSFontFaceSource(item->resource()));
-        }
-
-        if (!fontFace) {
-            RefPtr<CSSFontFaceRule> rule;
-            // FIXME: https://bugs.webkit.org/show_bug.cgi?id=112116 - This CSSFontFaceRule has no parent.
-            if (RuntimeEnabledFeatures::fontLoadEventsEnabled())
-                rule = static_pointer_cast<CSSFontFaceRule>(fontFaceRule->createCSSOMWrapper());
-            fontFace = CSSFontFace::create(rule);
-        }
-
-        if (source) {
-#if ENABLE(SVG_FONTS)
-            source->setSVGFontFaceElement(item->svgFontFaceElement());
-#endif
-            fontFace->addSource(source.release());
-        }
-    }
-
-    ASSERT(fontFace);
-
-    if (fontFace && !fontFace->isValid())
-        return;
-
-    if (rangeList) {
-        unsigned numRanges = rangeList->length();
-        for (unsigned i = 0; i < numRanges; i++) {
-            CSSUnicodeRangeValue* range = static_cast<CSSUnicodeRangeValue*>(rangeList->itemWithoutBoundsCheck(i));
-            fontFace->addRange(range->from(), range->to());
-        }
-    }
-
-    CSSPrimitiveValue* familyValue = toCSSPrimitiveValue(familyList->itemWithoutBoundsCheck(0));
-    String familyName;
-    if (familyValue->isString()) {
-        familyName = familyValue->getStringValue();
-    } else if (familyValue->isValueID()) {
-        // We need to use the raw text for all the generic family types, since @font-face is a way of actually
-        // defining what font to use for those types.
-        switch (familyValue->getValueID()) {
-        case CSSValueSerif:
-            familyName =  serifFamily;
-            break;
-        case CSSValueSansSerif:
-            familyName =  sansSerifFamily;
-            break;
-        case CSSValueCursive:
-            familyName =  cursiveFamily;
-            break;
-        case CSSValueFantasy:
-            familyName =  fantasyFamily;
-            break;
-        case CSSValueMonospace:
-            familyName =  monospaceFamily;
-            break;
-        case CSSValueWebkitPictograph:
-            familyName =  pictographFamily;
-            break;
-        default:
-            break;
-        }
-    }
-
-    if (familyName.isEmpty())
-        return;
-
-    OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >& familyFontFaces = m_fontFaces.add(familyName, nullptr).iterator->value;
+    OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >& familyFontFaces = m_fontFaces.add(fontFace->family(), nullptr).iterator->value;
     if (!familyFontFaces) {
         familyFontFaces = adoptPtr(new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >);
 
-        ASSERT(!m_locallyInstalledFontFaces.contains(familyName));
+        ASSERT(!m_locallyInstalledFontFaces.contains(fontFace->family()));
 
         Vector<unsigned> locallyInstalledFontsTraitsMasks;
-        fontCache()->getTraitsInFamily(familyName, locallyInstalledFontsTraitsMasks);
+        fontCache()->getTraitsInFamily(fontFace->family(), locallyInstalledFontsTraitsMasks);
         if (unsigned numLocallyInstalledFaces = locallyInstalledFontsTraitsMasks.size()) {
             OwnPtr<Vector<RefPtr<CSSSegmentedFontFace> > > familyLocallyInstalledFaces = adoptPtr(new Vector<RefPtr<CSSSegmentedFontFace> >);
 
             for (unsigned i = 0; i < numLocallyInstalledFaces; ++i) {
                 RefPtr<CSSFontFace> locallyInstalledFontFace = CSSFontFace::create(0);
-                locallyInstalledFontFace->addSource(adoptPtr(new CSSFontFaceSource(familyName)));
+                locallyInstalledFontFace->addSource(adoptPtr(new CSSFontFaceSource(fontFace->family())));
                 ASSERT(locallyInstalledFontFace->isValid());
 
                 RefPtr<CSSSegmentedFontFace> segmentedFontFace = CSSSegmentedFontFace::create(this, static_cast<FontTraitsMask>(locallyInstalledFontsTraitsMasks[i]), true);
@@ -308,7 +108,7 @@
                 familyLocallyInstalledFaces->append(segmentedFontFace);
             }
 
-            m_locallyInstalledFontFaces.set(familyName, familyLocallyInstalledFaces.release());
+            m_locallyInstalledFontFaces.set(fontFace->family(), familyLocallyInstalledFaces.release());
         }
     }
 
@@ -316,7 +116,7 @@
     if (!segmentedFontFace)
         segmentedFontFace = CSSSegmentedFontFace::create(this, static_cast<FontTraitsMask>(traitsMask), false);
 
-    segmentedFontFace->appendFontFace(fontFace);
+    segmentedFontFace->appendFontFace(cssFontFace);
 
     ++m_version;
 }
diff --git a/Source/core/css/CSSGrammar.y.in b/Source/core/css/CSSGrammar.y.in
index d437fb6..da016a2 100644
--- a/Source/core/css/CSSGrammar.y.in
+++ b/Source/core/css/CSSGrammar.y.in
@@ -1382,6 +1382,8 @@
 
 pseudo_page:
     ':' IDENT {
+        if ($2.isFunction())
+            YYERROR;
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PagePseudoClass);
         parser->tokenToLowerCase($2);
@@ -1393,6 +1395,8 @@
 
 pseudo:
     ':' error_location IDENT {
+        if ($3.isFunction())
+            YYERROR;
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         parser->tokenToLowerCase($3);
@@ -1404,6 +1408,8 @@
         }
     }
     | ':' ':' error_location IDENT {
+        if ($4.isFunction())
+            YYERROR;
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoElement);
         parser->tokenToLowerCase($4);
diff --git a/Source/core/css/CSSImportRule.h b/Source/core/css/CSSImportRule.h
index a4ccaf4..b16e943 100644
--- a/Source/core/css/CSSImportRule.h
+++ b/Source/core/css/CSSImportRule.h
@@ -53,6 +53,12 @@
     mutable RefPtr<CSSStyleSheet> m_styleSheetCSSOMWrapper;
 };
 
+inline CSSImportRule* toCSSImportRule(CSSRule* rule)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(rule->type() == CSSRule::IMPORT_RULE);
+    return static_cast<CSSImportRule*>(rule);
+}
+
 } // namespace WebCore
 
 #endif // CSSImportRule_h
diff --git a/Source/core/css/CSSParser-in.cpp b/Source/core/css/CSSParser-in.cpp
index 873c347..889de86 100644
--- a/Source/core/css/CSSParser-in.cpp
+++ b/Source/core/css/CSSParser-in.cpp
@@ -543,7 +543,8 @@
 {
     ASSERT(!string.isEmpty());
     bool acceptsNegativeNumbers;
-    if (!isSimpleLengthPropertyID(propertyId, acceptsNegativeNumbers))
+    // In ViewportMode, width and height are shorthands, not simple length values.
+    if (cssParserMode == ViewportMode || !isSimpleLengthPropertyID(propertyId, acceptsNegativeNumbers))
         return false;
 
     unsigned length = string.length();
@@ -1208,7 +1209,8 @@
 {
     // FIXME: Check RuntimeCSSEnabled::isPropertyEnabled or isValueEnabledForProperty.
 
-    if (m_useCounter)
+    // We don't count the UA style sheet in our statistics.
+    if (m_context.mode != UASheetMode && m_useCounter)
         m_useCounter->count(propertyID);
 
     setStyleSheet(contextStyleSheet);
@@ -1218,7 +1220,10 @@
     m_id = propertyID;
     m_important = important;
 
-    cssyyparse(this);
+    {
+        StyleDeclarationScope scope(this, declaration);
+        cssyyparse(this);
+    }
 
     m_rule = 0;
     m_id = CSSPropertyInvalid;
@@ -1333,7 +1338,12 @@
         m_sourceDataHandler->endRuleHeader(1);
         m_sourceDataHandler->startRuleBody(0);
     }
-    cssyyparse(this);
+
+    {
+        StyleDeclarationScope scope(this, declaration);
+        cssyyparse(this);
+    }
+
     m_rule = 0;
 
     bool ok = false;
@@ -1400,7 +1410,9 @@
     if (unusedEntries)
         results.remove(0, unusedEntries);
 
-    return ImmutableStylePropertySet::create(results.data(), results.size(), m_context.mode);
+    CSSParserMode mode = inViewport() ? ViewportMode : m_context.mode;
+
+    return ImmutableStylePropertySet::create(results.data(), results.size(), mode);
 }
 
 void CSSParser::addPropertyWithPrefixingVariant(CSSPropertyID propId, PassRefPtr<CSSValue> value, bool important, bool implicit)
@@ -1681,7 +1693,8 @@
     if (m_context.mode != UASheetMode && isInternalProperty(propId))
         return false;
 
-    if (m_useCounter)
+    // We don't count the UA style sheet in our statistics.
+    if (m_context.mode != UASheetMode && m_useCounter)
         m_useCounter->count(propId);
 
     if (!m_valueList)
@@ -1910,15 +1923,14 @@
             if (image)
                 list->append(CSSCursorImageValue::create(image, hasHotSpot, hotSpot));
 
-            if ((inStrictMode() && !value) || (value && !(value->unit == CSSParserValue::Operator && value->iValue == ',')))
+            if (!value || !(value->unit == CSSParserValue::Operator && value->iValue == ','))
                 return false;
             value = m_valueList->next(); // comma
         }
         if (list) {
-            if (!value) { // no value after url list (MSIE 5 compatibility)
-                if (list->length() != 1)
-                    return false;
-            } else if (inQuirksMode() && value->id == CSSValueHand) // MSIE 5 compatibility :/
+            if (!value)
+                return false;
+            if (inQuirksMode() && value->id == CSSValueHand) // MSIE 5 compatibility :/
                 list->append(cssValuePool().createIdentifierValue(CSSValuePointer));
             else if ((value->id >= CSSValueAuto && value->id <= CSSValueWebkitGrabbing) || value->id == CSSValueCopy || value->id == CSSValueNone)
                 list->append(cssValuePool().createIdentifierValue(value->id));
diff --git a/Source/core/css/CSSParser.h b/Source/core/css/CSSParser.h
index 275e55d..6d0e270 100644
--- a/Source/core/css/CSSParser.h
+++ b/Source/core/css/CSSParser.h
@@ -34,6 +34,7 @@
 #include "core/css/CSSPropertySourceData.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/MediaQuery.h"
+#include "core/css/StylePropertySet.h"
 #include "core/page/UseCounter.h"
 #include "core/platform/graphics/Color.h"
 #include "wtf/HashSet.h"
@@ -459,6 +460,30 @@
         WebCore::CSSParser* m_parser;
     };
 
+    class StyleDeclarationScope {
+        WTF_MAKE_NONCOPYABLE(StyleDeclarationScope);
+    public:
+        StyleDeclarationScope(CSSParser* parser, const StylePropertySet* declaration)
+            : m_parser(parser)
+            , m_mode(declaration->cssParserMode())
+        {
+            if (m_mode == ViewportMode) {
+                ASSERT(!m_parser->inViewport());
+                m_parser->markViewportRuleBodyStart();
+            }
+        }
+
+        ~StyleDeclarationScope()
+        {
+            if (m_mode == ViewportMode)
+                m_parser->markViewportRuleBodyEnd();
+        }
+
+    private:
+        CSSParser* m_parser;
+        CSSParserMode m_mode;
+    };
+
     bool is8BitSource() const { return m_is8BitSource; }
 
     template <typename SourceCharacterType>
@@ -536,7 +561,7 @@
 
     void setStyleSheet(StyleSheetContents* styleSheet) { m_styleSheet = styleSheet; }
 
-    inline bool inStrictMode() const { return m_context.mode == CSSStrictMode || m_context.mode == SVGAttributeMode; }
+    inline bool inStrictMode() const { return isStrictParserMode(m_context.mode); }
     inline bool inQuirksMode() const { return m_context.mode == CSSQuirksMode; }
 
     KURL completeURL(const String& url) const;
diff --git a/Source/core/css/CSSParserMode.h b/Source/core/css/CSSParserMode.h
index 075d2e2..6a40a5f 100644
--- a/Source/core/css/CSSParserMode.h
+++ b/Source/core/css/CSSParserMode.h
@@ -44,7 +44,10 @@
     SVGAttributeMode,
     // User agent style sheet should always be in strict mode. Enables internal
     // only properties and values.
-    UASheetMode
+    UASheetMode,
+    // Parsing @viewport descriptors. Always strict. Set as mode on StylePropertySet
+    // to make sure CSSOM modifications use CSSParser::parseViewportProperty.
+    ViewportMode
 };
 
 inline CSSParserMode strictToCSSParserMode(bool inStrictMode)
@@ -54,7 +57,7 @@
 
 inline bool isStrictParserMode(CSSParserMode cssParserMode)
 {
-    return cssParserMode == CSSStrictMode || cssParserMode == SVGAttributeMode || cssParserMode == UASheetMode;
+    return cssParserMode != CSSQuirksMode;
 }
 
 struct CSSParserContext {
diff --git a/Source/core/css/CSSParserValues.h b/Source/core/css/CSSParserValues.h
index 87deccb..0aafa37 100644
--- a/Source/core/css/CSSParserValues.h
+++ b/Source/core/css/CSSParserValues.h
@@ -121,6 +121,8 @@
 
     AtomicString atomicSubstring(unsigned position, unsigned length) const;
 
+    bool isFunction() const { return length() > 0 && (*this)[length() - 1] == '('; }
+
     union {
         const LChar* characters8;
         const UChar* characters16;
diff --git a/Source/core/css/CSSPrimitiveValue.cpp b/Source/core/css/CSSPrimitiveValue.cpp
index a77565b..9a5741e 100644
--- a/Source/core/css/CSSPrimitiveValue.cpp
+++ b/Source/core/css/CSSPrimitiveValue.cpp
@@ -988,7 +988,8 @@
             text = formatNumber(m_value.num, "turn");
             break;
         case CSS_DIMENSION:
-            text = m_value.string;
+            // FIXME: We currently don't handle CSS_DIMENSION properly as we don't store
+            // the actual dimension, just the numeric value as a string.
             break;
         case CSS_STRING:
             text = formattingFlag == AlwaysQuoteCSSString ? quoteCSSString(m_value.string) : quoteCSSStringIfNeeded(m_value.string);
diff --git a/Source/core/css/CSSSegmentedFontFace.cpp b/Source/core/css/CSSSegmentedFontFace.cpp
index 515d6f6..60bc3c5 100644
--- a/Source/core/css/CSSSegmentedFontFace.cpp
+++ b/Source/core/css/CSSSegmentedFontFace.cpp
@@ -92,14 +92,9 @@
     m_fontFaces.append(fontFace);
 }
 
-static void appendFontDataWithInvalidUnicodeRangeIfLoading(SegmentedFontData* newFontData, PassRefPtr<SimpleFontData> prpFaceFontData, const Vector<CSSFontFace::UnicodeRange>& ranges)
+static void appendFontData(SegmentedFontData* newFontData, PassRefPtr<SimpleFontData> prpFaceFontData, const Vector<CSSFontFace::UnicodeRange>& ranges)
 {
     RefPtr<SimpleFontData> faceFontData = prpFaceFontData;
-    if (faceFontData->isLoading()) {
-        newFontData->appendRange(FontDataRange(0, 0, faceFontData));
-        return;
-    }
-
     unsigned numRanges = ranges.size();
     if (!numRanges) {
         newFontData->appendRange(FontDataRange(0, 0x7FFFFFFF, faceFontData));
@@ -136,7 +131,7 @@
             continue;
         if (RefPtr<SimpleFontData> faceFontData = m_fontFaces[i]->getFontData(fontDescription, syntheticBold, syntheticItalic)) {
             ASSERT(!faceFontData->isSegmented());
-            appendFontDataWithInvalidUnicodeRangeIfLoading(fontData.get(), faceFontData.release(), m_fontFaces[i]->ranges());
+            appendFontData(fontData.get(), faceFontData.release(), m_fontFaces[i]->ranges());
         }
     }
     if (fontData->numRanges())
@@ -159,7 +154,7 @@
 {
     unsigned size = m_fontFaces.size();
     for (unsigned i = 0; i < size; i++) {
-        if (m_fontFaces[i]->loadState() == CSSFontFace::Loading)
+        if (m_fontFaces[i]->loadStatus() == FontFace::Loading)
             return true;
     }
     return false;
@@ -176,7 +171,7 @@
 {
     unsigned size = m_fontFaces.size();
     for (unsigned i = 0; i < size; i++) {
-        if (m_fontFaces[i]->loadState() != CSSFontFace::Loaded)
+        if (m_fontFaces[i]->loadStatus() != FontFace::Loaded)
             return false;
     }
     return true;
@@ -184,7 +179,10 @@
 
 void CSSSegmentedFontFace::loadFont(const FontDescription& fontDescription, PassRefPtr<LoadFontCallback> callback)
 {
-    getFontData(fontDescription); // Kick off the load.
+    RefPtr<SegmentedFontData> fontData = toSegmentedFontData(getFontData(fontDescription).get());
+    unsigned numRanges = fontData->numRanges();
+    for (unsigned i = 0; i < numRanges; i++)
+        fontData->rangeAt(i).fontData()->beginLoadIfNeeded();
 
     if (callback) {
         if (isLoading())
@@ -196,4 +194,16 @@
     }
 }
 
+Vector<RefPtr<FontFace> > CSSSegmentedFontFace::fontFaces() const
+{
+    Vector<RefPtr<FontFace> > fontFaces;
+    unsigned size = m_fontFaces.size();
+    for (unsigned i = 0; i < size; i++) {
+        RefPtr<FontFace> face = m_fontFaces[i]->fontFace();
+        if (face)
+            fontFaces.append(face);
+    }
+    return fontFaces;
+}
+
 }
diff --git a/Source/core/css/CSSSegmentedFontFace.h b/Source/core/css/CSSSegmentedFontFace.h
index 214a052..a9a624d 100644
--- a/Source/core/css/CSSSegmentedFontFace.h
+++ b/Source/core/css/CSSSegmentedFontFace.h
@@ -38,6 +38,7 @@
 class CSSFontSelector;
 class FontData;
 class FontDescription;
+class FontFace;
 class SegmentedFontData;
 
 class CSSSegmentedFontFace : public RefCounted<CSSSegmentedFontFace> {
@@ -68,6 +69,7 @@
 
     bool checkFont() const;
     void loadFont(const FontDescription&, PassRefPtr<LoadFontCallback> loadCallback);
+    Vector<RefPtr<FontFace> > fontFaces() const;
     void willUseFontData(const FontDescription&);
 
 private:
diff --git a/Source/core/css/CSSSelector.cpp b/Source/core/css/CSSSelector.cpp
index 3874329..a0cc26e 100644
--- a/Source/core/css/CSSSelector.cpp
+++ b/Source/core/css/CSSSelector.cpp
@@ -103,10 +103,12 @@
     case Contain:
     case Begin:
     case End:
-        // FIXME: PsuedoAny should base the specificity on the sub-selectors.
+        // FIXME: PseudoAny should base the specificity on the sub-selectors.
         // See http://lists.w3.org/Archives/Public/www-style/2010Sep/0530.html
-        if (pseudoType() == PseudoNot && selectorList())
+        if (pseudoType() == PseudoNot) {
+            ASSERT(selectorList());
             return selectorList()->first()->specificityForOneSelector();
+        }
         return 0x100;
     case Tag:
         return (tagQName().localName() != starAtom) ? 1 : 0;
@@ -127,7 +129,7 @@
         case Tag:
             s += tagQName().localName() == starAtom ? 0 : 4;
             break;
-        case PseudoClass:
+        case PagePseudoClass:
             switch (component->pseudoType()) {
             case PseudoFirstPage:
                 s += 2;
@@ -627,8 +629,8 @@
 
             switch (cs->pseudoType()) {
             case PseudoNot:
-                if (const CSSSelectorList* selectorList = cs->selectorList())
-                    str.append(selectorList->first()->selectorText());
+                ASSERT(cs->selectorList());
+                str.append(cs->selectorList()->first()->selectorText());
                 str.append(')');
                 break;
             case PseudoLang:
diff --git a/Source/core/css/CSSStyleRule.h b/Source/core/css/CSSStyleRule.h
index b9f148b..f608a2f 100644
--- a/Source/core/css/CSSStyleRule.h
+++ b/Source/core/css/CSSStyleRule.h
@@ -57,6 +57,12 @@
     mutable RefPtr<StyleRuleCSSStyleDeclaration> m_propertiesCSSOMWrapper;
 };
 
+inline CSSStyleRule* toCSSStyleRule(CSSRule* rule)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(rule->type() == CSSRule::STYLE_RULE);
+    return static_cast<CSSStyleRule*>(rule);
+}
+
 } // namespace WebCore
 
 #endif // CSSStyleRule_h
diff --git a/Source/core/css/CSSUnicodeRangeValue.cpp b/Source/core/css/CSSUnicodeRangeValue.cpp
index ab482a5..967df4e 100644
--- a/Source/core/css/CSSUnicodeRangeValue.cpp
+++ b/Source/core/css/CSSUnicodeRangeValue.cpp
@@ -32,9 +32,9 @@
 
 String CSSUnicodeRangeValue::customCssText() const
 {
-    String result;
-    // FIXME: Implement.
-    return result;
+    if (m_from == m_to)
+        return String::format("U+%X", m_from);
+    return String::format("U+%X-%X", m_from, m_to);
 }
 
 bool CSSUnicodeRangeValue::equals(const CSSUnicodeRangeValue& other) const
diff --git a/Source/core/css/CSSValue.h b/Source/core/css/CSSValue.h
index 27f6467..a92bc86 100644
--- a/Source/core/css/CSSValue.h
+++ b/Source/core/css/CSSValue.h
@@ -74,6 +74,7 @@
     bool isCursorImageValue() const { return m_classType == CursorImageClass; }
     bool isFontFeatureValue() const { return m_classType == FontFeatureClass; }
     bool isFontValue() const { return m_classType == FontClass; }
+    bool isFontFaceSrcValue() const { return m_classType == FontFaceSrcClass; }
     bool isFunctionValue() const { return m_classType == FunctionClass; }
     bool isImageGeneratorValue() const { return m_classType >= CanvasClass && m_classType <= RadialGradientClass; }
     bool isGradientValue() const { return m_classType >= LinearGradientClass && m_classType <= RadialGradientClass; }
diff --git a/Source/core/css/CSSValueList.cpp b/Source/core/css/CSSValueList.cpp
index 26ab9c0..1a18bc9 100644
--- a/Source/core/css/CSSValueList.cpp
+++ b/Source/core/css/CSSValueList.cpp
@@ -127,7 +127,9 @@
 
 bool CSSValueList::equals(const CSSValueList& other) const
 {
-    return m_valueListSeparator == other.m_valueListSeparator && compareCSSValueVector<CSSValue>(m_values, other.m_values);
+    // FIXME: the explicit Vector conversion copies into a temporary and is
+    // wasteful.
+    return m_valueListSeparator == other.m_valueListSeparator && compareCSSValueVector<CSSValue>(Vector<RefPtr<CSSValue> >(m_values), Vector<RefPtr<CSSValue> >(other.m_values));
 }
 
 bool CSSValueList::equals(const CSSValue& other) const
diff --git a/Source/core/css/DocumentRuleSets.cpp b/Source/core/css/DocumentRuleSets.cpp
index 9a595b4..298d23d 100644
--- a/Source/core/css/DocumentRuleSets.cpp
+++ b/Source/core/css/DocumentRuleSets.cpp
@@ -34,7 +34,7 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/MatchRequest.h"
 #include "core/css/resolver/StyleResolver.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 
 namespace WebCore {
 
@@ -74,7 +74,7 @@
 {
 }
 
-void DocumentRuleSets::initUserStyle(StyleSheetCollections* styleSheetCollection, const MediaQueryEvaluator& medium, StyleResolver& resolver)
+void DocumentRuleSets::initUserStyle(StyleEngine* styleSheetCollection, const MediaQueryEvaluator& medium, StyleResolver& resolver)
 {
     OwnPtr<RuleSet> tempUserStyle = RuleSet::create();
     if (CSSStyleSheet* pageUserSheet = styleSheetCollection->pageUserSheet())
diff --git a/Source/core/css/DocumentRuleSets.h b/Source/core/css/DocumentRuleSets.h
index 7ef6674..4434ec5 100644
--- a/Source/core/css/DocumentRuleSets.h
+++ b/Source/core/css/DocumentRuleSets.h
@@ -38,7 +38,7 @@
 class MatchRequest;
 class MediaQueryEvaluator;
 class RuleSet;
-class StyleSheetCollections;
+class StyleEngine;
 
 class ShadowDistributedRules {
 public:
@@ -60,7 +60,7 @@
     ~DocumentRuleSets();
     RuleSet* userStyle() const { return m_userStyle.get(); }
 
-    void initUserStyle(StyleSheetCollections*, const MediaQueryEvaluator&, StyleResolver&);
+    void initUserStyle(StyleEngine*, const MediaQueryEvaluator&, StyleResolver&);
     void resetAuthorStyle();
     void collectFeaturesTo(RuleFeatureSet&, bool isViewSource);
 
diff --git a/Source/core/css/FontFace.cpp b/Source/core/css/FontFace.cpp
new file mode 100644
index 0000000..d1d3896
--- /dev/null
+++ b/Source/core/css/FontFace.cpp
@@ -0,0 +1,456 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/FontFace.h"
+
+#include "CSSPropertyNames.h"
+#include "CSSValueKeywords.h"
+#include "FontFamilyNames.h"
+#include "bindings/v8/Dictionary.h"
+#include "bindings/v8/ExceptionState.h"
+#include "core/css/CSSFontFace.h"
+#include "core/css/CSSFontFaceSrcValue.h"
+#include "core/css/CSSParser.h"
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSUnicodeRangeValue.h"
+#include "core/css/CSSValueList.h"
+#include "core/css/StylePropertySet.h"
+#include "core/css/StyleRule.h"
+#include "core/dom/Document.h"
+#include "core/page/Frame.h"
+#include "core/page/Settings.h"
+#include "core/platform/graphics/FontTraitsMask.h"
+#include "core/svg/SVGFontFaceElement.h"
+
+namespace WebCore {
+
+static PassRefPtr<CSSValue> parseCSSValue(const String& s, CSSPropertyID propertyID)
+{
+    if (s.isEmpty())
+        return 0;
+    RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
+    CSSParser::parseValue(parsedStyle.get(), propertyID, s, true, CSSStrictMode, 0);
+    return parsedStyle->getPropertyCSSValue(propertyID);
+}
+
+PassRefPtr<FontFace> FontFace::create(const String& family, const String& source, const Dictionary& descriptors, ExceptionState& es)
+{
+    RefPtr<CSSValue> src = parseCSSValue(source, CSSPropertySrc);
+    if (!src || !src->isValueList()) {
+        es.throwDOMException(SyntaxError);
+        return 0;
+    }
+
+    RefPtr<FontFace> fontFace = adoptRef<FontFace>(new FontFace(src));
+    fontFace->setFamily(family, es);
+    if (es.hadException())
+        return 0;
+
+    String value;
+    if (descriptors.get("style", value)) {
+        fontFace->setStyle(value, es);
+        if (es.hadException())
+            return 0;
+    }
+    if (descriptors.get("weight", value)) {
+        fontFace->setWeight(value, es);
+        if (es.hadException())
+            return 0;
+    }
+    if (descriptors.get("stretch", value)) {
+        fontFace->setStretch(value, es);
+        if (es.hadException())
+            return 0;
+    }
+    if (descriptors.get("unicodeRange", value)) {
+        fontFace->setUnicodeRange(value, es);
+        if (es.hadException())
+            return 0;
+    }
+    if (descriptors.get("variant", value)) {
+        fontFace->setVariant(value, es);
+        if (es.hadException())
+            return 0;
+    }
+    if (descriptors.get("featureSettings", value)) {
+        fontFace->setFeatureSettings(value, es);
+        if (es.hadException())
+            return 0;
+    }
+
+    return fontFace;
+}
+
+PassRefPtr<FontFace> FontFace::create(const StyleRuleFontFace* fontFaceRule)
+{
+    const StylePropertySet* properties = fontFaceRule->properties();
+
+    // Obtain the font-family property and the src property. Both must be defined.
+    RefPtr<CSSValue> family = properties->getPropertyCSSValue(CSSPropertyFontFamily);
+    if (!family || !family->isValueList())
+        return 0;
+    RefPtr<CSSValue> src = properties->getPropertyCSSValue(CSSPropertySrc);
+    if (!src || !src->isValueList())
+        return 0;
+
+    RefPtr<FontFace> fontFace = adoptRef<FontFace>(new FontFace(src));
+
+    if (fontFace->setFamilyValue(toCSSValueList(family.get()))
+        && fontFace->setPropertyFromStyle(properties, CSSPropertyFontStyle)
+        && fontFace->setPropertyFromStyle(properties, CSSPropertyFontWeight)
+        && fontFace->setPropertyFromStyle(properties, CSSPropertyFontStretch)
+        && fontFace->setPropertyFromStyle(properties, CSSPropertyUnicodeRange)
+        && fontFace->setPropertyFromStyle(properties, CSSPropertyFontVariant)
+        && fontFace->setPropertyFromStyle(properties, CSSPropertyWebkitFontFeatureSettings))
+        return fontFace;
+    return 0;
+}
+
+FontFace::FontFace(PassRefPtr<CSSValue> src)
+    : m_src(src)
+    , m_status(Unloaded)
+{
+}
+
+FontFace::~FontFace()
+{
+}
+
+String FontFace::style() const
+{
+    return m_style ? m_style->cssText() : "normal";
+}
+
+String FontFace::weight() const
+{
+    return m_weight ? m_weight->cssText() : "normal";
+}
+
+String FontFace::stretch() const
+{
+    return m_stretch ? m_stretch->cssText() : "normal";
+}
+
+String FontFace::unicodeRange() const
+{
+    return m_unicodeRange ? m_unicodeRange->cssText() : "U+0-10FFFF";
+}
+
+String FontFace::variant() const
+{
+    return m_variant ? m_variant->cssText() : "normal";
+}
+
+String FontFace::featureSettings() const
+{
+    return m_featureSettings ? m_featureSettings->cssText() : "normal";
+}
+
+void FontFace::setStyle(const String& s, ExceptionState& es)
+{
+    setPropertyFromString(s, CSSPropertyFontStyle, es);
+}
+
+void FontFace::setWeight(const String& s, ExceptionState& es)
+{
+    setPropertyFromString(s, CSSPropertyFontWeight, es);
+}
+
+void FontFace::setStretch(const String& s, ExceptionState& es)
+{
+    setPropertyFromString(s, CSSPropertyFontStretch, es);
+}
+
+void FontFace::setUnicodeRange(const String& s, ExceptionState& es)
+{
+    setPropertyFromString(s, CSSPropertyUnicodeRange, es);
+}
+
+void FontFace::setVariant(const String& s, ExceptionState& es)
+{
+    setPropertyFromString(s, CSSPropertyFontVariant, es);
+}
+
+void FontFace::setFeatureSettings(const String& s, ExceptionState& es)
+{
+    setPropertyFromString(s, CSSPropertyWebkitFontFeatureSettings, es);
+}
+
+void FontFace::setPropertyFromString(const String& s, CSSPropertyID propertyID, ExceptionState& es)
+{
+    RefPtr<CSSValue> value = parseCSSValue(s, propertyID);
+    if (!value || !setPropertyValue(value, propertyID))
+        es.throwDOMException(SyntaxError);
+}
+
+bool FontFace::setPropertyFromStyle(const StylePropertySet* properties, CSSPropertyID propertyID)
+{
+    return setPropertyValue(properties->getPropertyCSSValue(propertyID), propertyID);
+}
+
+bool FontFace::setPropertyValue(PassRefPtr<CSSValue> value, CSSPropertyID propertyID)
+{
+    switch (propertyID) {
+    case CSSPropertyFontStyle:
+        m_style = value;
+        break;
+    case CSSPropertyFontWeight:
+        m_weight = value;
+        break;
+    case CSSPropertyFontStretch:
+        m_stretch = value;
+        break;
+    case CSSPropertyUnicodeRange:
+        if (value && !value->isValueList())
+            return false;
+        m_unicodeRange = value;
+        break;
+    case CSSPropertyFontVariant:
+        m_variant = value;
+        break;
+    case CSSPropertyWebkitFontFeatureSettings:
+        m_featureSettings = value;
+        break;
+    default:
+        ASSERT_NOT_REACHED();
+        return false;
+    }
+    return true;
+}
+
+bool FontFace::setFamilyValue(CSSValueList* familyList)
+{
+    // The font-family descriptor has to have exactly one family name.
+    if (familyList->length() != 1)
+        return false;
+
+    CSSPrimitiveValue* familyValue = toCSSPrimitiveValue(familyList->itemWithoutBoundsCheck(0));
+    String family;
+    if (familyValue->isString()) {
+        family = familyValue->getStringValue();
+    } else if (familyValue->isValueID()) {
+        // We need to use the raw text for all the generic family types, since @font-face is a way of actually
+        // defining what font to use for those types.
+        switch (familyValue->getValueID()) {
+        case CSSValueSerif:
+            family =  FontFamilyNames::serifFamily;
+            break;
+        case CSSValueSansSerif:
+            family =  FontFamilyNames::sansSerifFamily;
+            break;
+        case CSSValueCursive:
+            family =  FontFamilyNames::cursiveFamily;
+            break;
+        case CSSValueFantasy:
+            family =  FontFamilyNames::fantasyFamily;
+            break;
+        case CSSValueMonospace:
+            family =  FontFamilyNames::monospaceFamily;
+            break;
+        case CSSValueWebkitPictograph:
+            family =  FontFamilyNames::pictographFamily;
+            break;
+        default:
+            return false;
+        }
+    }
+    m_family = family;
+    return true;
+}
+
+String FontFace::status() const
+{
+    switch (m_status) {
+    case Unloaded:
+        return "unloaded";
+    case Loading:
+        return "loading";
+    case Loaded:
+        return "loaded";
+    case Error:
+        return "error";
+    default:
+        ASSERT_NOT_REACHED();
+    }
+    return emptyString();
+}
+
+unsigned FontFace::traitsMask() const
+{
+    unsigned traitsMask = 0;
+
+    if (m_style) {
+        if (!m_style->isPrimitiveValue())
+            return 0;
+
+        switch (toCSSPrimitiveValue(m_style.get())->getValueID()) {
+        case CSSValueNormal:
+            traitsMask |= FontStyleNormalMask;
+            break;
+        case CSSValueItalic:
+        case CSSValueOblique:
+            traitsMask |= FontStyleItalicMask;
+            break;
+        default:
+            break;
+        }
+    } else {
+        traitsMask |= FontStyleNormalMask;
+    }
+
+    if (m_weight) {
+        if (!m_weight->isPrimitiveValue())
+            return 0;
+
+        switch (toCSSPrimitiveValue(m_weight.get())->getValueID()) {
+        case CSSValueBold:
+        case CSSValue700:
+            traitsMask |= FontWeight700Mask;
+            break;
+        case CSSValueNormal:
+        case CSSValue400:
+            traitsMask |= FontWeight400Mask;
+            break;
+        case CSSValue900:
+            traitsMask |= FontWeight900Mask;
+            break;
+        case CSSValue800:
+            traitsMask |= FontWeight800Mask;
+            break;
+        case CSSValue600:
+            traitsMask |= FontWeight600Mask;
+            break;
+        case CSSValue500:
+            traitsMask |= FontWeight500Mask;
+            break;
+        case CSSValue300:
+            traitsMask |= FontWeight300Mask;
+            break;
+        case CSSValue200:
+            traitsMask |= FontWeight200Mask;
+            break;
+        case CSSValue100:
+            traitsMask |= FontWeight100Mask;
+            break;
+        default:
+            break;
+        }
+    } else {
+        traitsMask |= FontWeight400Mask;
+    }
+
+    if (RefPtr<CSSValue> fontVariant = m_variant) {
+        // font-variant descriptor can be a value list.
+        if (fontVariant->isPrimitiveValue()) {
+            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            list->append(fontVariant);
+            fontVariant = list;
+        } else if (!fontVariant->isValueList()) {
+            return 0;
+        }
+
+        CSSValueList* variantList = toCSSValueList(fontVariant.get());
+        unsigned numVariants = variantList->length();
+        if (!numVariants)
+            return 0;
+
+        for (unsigned i = 0; i < numVariants; ++i) {
+            switch (toCSSPrimitiveValue(variantList->itemWithoutBoundsCheck(i))->getValueID()) {
+            case CSSValueNormal:
+                traitsMask |= FontVariantNormalMask;
+                break;
+            case CSSValueSmallCaps:
+                traitsMask |= FontVariantSmallCapsMask;
+                break;
+            default:
+                break;
+            }
+        }
+    } else {
+        traitsMask |= FontVariantNormalMask;
+    }
+    return traitsMask;
+}
+
+PassRefPtr<CSSFontFace> FontFace::createCSSFontFace(Document* document)
+{
+    RefPtr<CSSFontFace> cssFontFace = CSSFontFace::create(this);
+
+    // Each item in the src property's list is a single CSSFontFaceSource. Put them all into a CSSFontFace.
+    CSSValueList* srcList = toCSSValueList(m_src.get());
+    int srcLength = srcList->length();
+
+    bool foundSVGFont = false;
+
+    for (int i = 0; i < srcLength; i++) {
+        // An item in the list either specifies a string (local font name) or a URL (remote font to download).
+        CSSFontFaceSrcValue* item = static_cast<CSSFontFaceSrcValue*>(srcList->itemWithoutBoundsCheck(i));
+        OwnPtr<CSSFontFaceSource> source;
+
+#if ENABLE(SVG_FONTS)
+        foundSVGFont = item->isSVGFontFaceSrc() || item->svgFontFaceElement();
+#endif
+        if (!item->isLocal()) {
+            Settings* settings = document ? document->frame() ? document->frame()->settings() : 0 : 0;
+            bool allowDownloading = foundSVGFont || (settings && settings->downloadableBinaryFontsEnabled());
+            if (allowDownloading && item->isSupportedFormat() && document) {
+                FontResource* fetched = item->fetch(document);
+                if (fetched) {
+                    source = adoptPtr(new CSSFontFaceSource(item->resource(), fetched));
+#if ENABLE(SVG_FONTS)
+                    if (foundSVGFont)
+                        source->setHasExternalSVGFont(true);
+#endif
+                }
+            }
+        } else {
+            source = adoptPtr(new CSSFontFaceSource(item->resource()));
+        }
+
+        if (source) {
+#if ENABLE(SVG_FONTS)
+            source->setSVGFontFaceElement(item->svgFontFaceElement());
+#endif
+            cssFontFace->addSource(source.release());
+        }
+    }
+
+    if (CSSValueList* rangeList = toCSSValueList(m_unicodeRange.get())) {
+        unsigned numRanges = rangeList->length();
+        for (unsigned i = 0; i < numRanges; i++) {
+            CSSUnicodeRangeValue* range = static_cast<CSSUnicodeRangeValue*>(rangeList->itemWithoutBoundsCheck(i));
+            cssFontFace->addRange(range->from(), range->to());
+        }
+    }
+    return cssFontFace;
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/FontFace.h b/Source/core/css/FontFace.h
new file mode 100644
index 0000000..69c5094
--- /dev/null
+++ b/Source/core/css/FontFace.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef FontFace_h
+#define FontFace_h
+
+#include "CSSPropertyNames.h"
+#include "core/css/CSSValue.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class CSSFontFace;
+class CSSValueList;
+class Dictionary;
+class Document;
+class ExceptionState;
+class StylePropertySet;
+class StyleRuleFontFace;
+
+class FontFace : public RefCounted<FontFace> {
+public:
+    enum LoadStatus { Unloaded, Loading, Loaded, Error };
+
+    static PassRefPtr<FontFace> create(const String& family, const String& source, const Dictionary&, ExceptionState&);
+    static PassRefPtr<FontFace> create(const StyleRuleFontFace*);
+
+    ~FontFace();
+
+    String family() const { return m_family; }
+    String style() const;
+    String weight() const;
+    String stretch() const;
+    String unicodeRange() const;
+    String variant() const;
+    String featureSettings() const;
+
+    // FIXME: Changing these attributes should affect font matching.
+    void setFamily(const String& s, ExceptionState&) { m_family = s; }
+    void setStyle(const String&, ExceptionState&);
+    void setWeight(const String&, ExceptionState&);
+    void setStretch(const String&, ExceptionState&);
+    void setUnicodeRange(const String&, ExceptionState&);
+    void setVariant(const String&, ExceptionState&);
+    void setFeatureSettings(const String&, ExceptionState&);
+
+    String status() const;
+
+    LoadStatus loadStatus() const { return m_status; }
+    void setLoadStatus(LoadStatus status) { m_status = status; }
+    unsigned traitsMask() const;
+    PassRefPtr<CSSFontFace> createCSSFontFace(Document*);
+
+private:
+    FontFace(PassRefPtr<CSSValue> source);
+
+    void setPropertyFromString(const String&, CSSPropertyID, ExceptionState&);
+    bool setPropertyFromStyle(const StylePropertySet*, CSSPropertyID);
+    bool setPropertyValue(PassRefPtr<CSSValue>, CSSPropertyID);
+    bool setFamilyValue(CSSValueList*);
+
+    String m_family;
+    RefPtr<CSSValue> m_src;
+    RefPtr<CSSValue> m_style;
+    RefPtr<CSSValue> m_weight;
+    RefPtr<CSSValue> m_stretch;
+    RefPtr<CSSValue> m_unicodeRange;
+    RefPtr<CSSValue> m_variant;
+    RefPtr<CSSValue> m_featureSettings;
+    LoadStatus m_status;
+};
+
+typedef Vector<RefPtr<FontFace> > FontFaceArray;
+
+} // namespace WebCore
+
+#endif // FontFace_h
diff --git a/Source/core/css/FontLoader.idl b/Source/core/css/FontFace.idl
similarity index 68%
copy from Source/core/css/FontLoader.idl
copy to Source/core/css/FontFace.idl
index ff4e533..a66872b 100644
--- a/Source/core/css/FontLoader.idl
+++ b/Source/core/css/FontFace.idl
@@ -28,21 +28,30 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+enum FontFaceLoadStatus {
+    "unloaded",
+    "loading",
+    "loaded",
+    "error"
+};
+
 [
-    NoInterfaceObject,
     EnabledAtRuntime=FontLoadEvents,
-    ActiveDOMObject,
-    GenerateIsReachable=document
-] interface FontLoader : EventTarget {
+    Constructor(DOMString family, DOMString source, Dictionary descriptors),
+    ConstructorRaisesException
+] interface FontFace {
 
-    attribute EventHandler onloading;
-    attribute EventHandler onloadingdone;
-    attribute EventHandler onloadstart;
-    attribute EventHandler onload;
-    attribute EventHandler onerror;
+    [SetterRaisesException] attribute DOMString family;
+    [SetterRaisesException] attribute DOMString style;
+    [SetterRaisesException] attribute DOMString weight;
+    [SetterRaisesException] attribute DOMString stretch;
+    [SetterRaisesException] attribute DOMString unicodeRange;
+    [SetterRaisesException] attribute DOMString variant;
+    [SetterRaisesException] attribute DOMString featureSettings;
 
-    boolean checkFont(DOMString font, [Default=NullString] optional DOMString text);
-    void loadFont(Dictionary params);
-    void notifyWhenFontsReady(VoidCallback callback);
-    readonly attribute boolean loading;
+    readonly attribute FontFaceLoadStatus status;
+
+    // FIXME: Implement them
+    //  void load();
+    //  Promise ready();
 };
diff --git a/Source/core/css/FontFaceSet.cpp b/Source/core/css/FontFaceSet.cpp
new file mode 100644
index 0000000..c9838d2
--- /dev/null
+++ b/Source/core/css/FontFaceSet.cpp
@@ -0,0 +1,451 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/FontFaceSet.h"
+
+#include "RuntimeEnabledFeatures.h"
+#include "V8FontFaceSet.h"
+#include "bindings/v8/Dictionary.h"
+#include "bindings/v8/ScriptPromiseResolver.h"
+#include "bindings/v8/ScriptScope.h"
+#include "bindings/v8/ScriptState.h"
+#include "core/css/CSSFontFaceLoadEvent.h"
+#include "core/css/CSSFontFaceSource.h"
+#include "core/css/CSSFontSelector.h"
+#include "core/css/CSSParser.h"
+#include "core/css/CSSSegmentedFontFace.h"
+#include "core/css/StylePropertySet.h"
+#include "core/css/resolver/StyleResolver.h"
+#include "core/dom/Document.h"
+#include "core/page/FrameView.h"
+#include "core/platform/HistogramSupport.h"
+
+namespace WebCore {
+
+static const int defaultFontSize = 10;
+static const char* const defaultFontFamily = "sans-serif";
+
+class LoadFontPromiseResolver : public CSSSegmentedFontFace::LoadFontCallback {
+public:
+    static PassRefPtr<LoadFontPromiseResolver> create(const FontFamily& family, ScriptExecutionContext* context)
+    {
+        int numFamilies = 0;
+        for (const FontFamily* f = &family; f; f = f->next())
+            numFamilies++;
+        return adoptRef<LoadFontPromiseResolver>(new LoadFontPromiseResolver(numFamilies, context));
+    }
+
+    virtual void notifyLoaded(CSSSegmentedFontFace*) OVERRIDE;
+    virtual void notifyError(CSSSegmentedFontFace*) OVERRIDE;
+    void loaded(Document*);
+    void error(Document*);
+    void resolve();
+
+    ScriptPromise promise()
+    {
+        ScriptPromise promise = m_resolver->promise();
+        m_resolver->detachPromise();
+        return promise;
+    }
+
+private:
+    LoadFontPromiseResolver(int numLoading, ScriptExecutionContext* context)
+        : m_numLoading(numLoading)
+        , m_errorOccured(false)
+        , m_scriptState(ScriptState::current())
+        , m_resolver(ScriptPromiseResolver::create(context))
+    { }
+
+    int m_numLoading;
+    bool m_errorOccured;
+    ScriptState* m_scriptState;
+    RefPtr<ScriptPromiseResolver> m_resolver;
+};
+
+void LoadFontPromiseResolver::loaded(Document* document)
+{
+    m_numLoading--;
+    if (m_numLoading || !document)
+        return;
+
+    document->fonts()->scheduleResolve(this);
+}
+
+void LoadFontPromiseResolver::error(Document* document)
+{
+    m_errorOccured = true;
+    loaded(document);
+}
+
+void LoadFontPromiseResolver::notifyLoaded(CSSSegmentedFontFace* face)
+{
+    loaded(face->fontSelector()->document());
+}
+
+void LoadFontPromiseResolver::notifyError(CSSSegmentedFontFace* face)
+{
+    error(face->fontSelector()->document());
+}
+
+void LoadFontPromiseResolver::resolve()
+{
+    ScriptScope scope(m_scriptState);
+    if (m_errorOccured)
+        m_resolver->reject(ScriptValue::createNull());
+    else
+        m_resolver->fulfill(ScriptValue::createNull());
+}
+
+class FontsReadyPromiseResolver {
+public:
+    static PassOwnPtr<FontsReadyPromiseResolver> create(ScriptExecutionContext* context)
+    {
+        return adoptPtr(new FontsReadyPromiseResolver(context));
+    }
+
+    void call(PassRefPtr<FontFaceSet> fontFaceSet)
+    {
+        ScriptScope scope(m_scriptState);
+        m_resolver->fulfill(fontFaceSet);
+    }
+
+    ScriptPromise promise()
+    {
+        ScriptPromise promise = m_resolver->promise();
+        m_resolver->detachPromise();
+        return promise;
+    }
+
+private:
+    FontsReadyPromiseResolver(ScriptExecutionContext* context)
+        : m_scriptState(ScriptState::current())
+        , m_resolver(ScriptPromiseResolver::create(context))
+    { }
+    ScriptState* m_scriptState;
+    RefPtr<ScriptPromiseResolver> m_resolver;
+};
+
+FontFaceSet::FontFaceSet(Document* document)
+    : ActiveDOMObject(document)
+    , m_loadingCount(0)
+    , m_shouldFireDoneEvent(false)
+    , m_timer(this, &FontFaceSet::timerFired)
+{
+    suspendIfNeeded();
+}
+
+FontFaceSet::~FontFaceSet()
+{
+}
+
+Document* FontFaceSet::document() const
+{
+    return toDocument(scriptExecutionContext());
+}
+
+EventTargetData* FontFaceSet::eventTargetData()
+{
+    return &m_eventTargetData;
+}
+
+EventTargetData* FontFaceSet::ensureEventTargetData()
+{
+    return &m_eventTargetData;
+}
+
+const AtomicString& FontFaceSet::interfaceName() const
+{
+    return eventNames().interfaceForFontFaceSet;
+}
+
+ScriptExecutionContext* FontFaceSet::scriptExecutionContext() const
+{
+    return ActiveDOMObject::scriptExecutionContext();
+}
+
+AtomicString FontFaceSet::status() const
+{
+    DEFINE_STATIC_LOCAL(AtomicString, loading, ("loading", AtomicString::ConstructFromLiteral));
+    DEFINE_STATIC_LOCAL(AtomicString, loaded, ("loaded", AtomicString::ConstructFromLiteral));
+    return (m_loadingCount > 0 || m_shouldFireDoneEvent) ? loading : loaded;
+}
+
+void FontFaceSet::didLayout()
+{
+    Document* d = document();
+    if (d->page() && d->page()->mainFrame() == d->frame())
+        m_histogram.record();
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
+    if (m_loadingCount || (!m_shouldFireDoneEvent && m_readyResolvers.isEmpty()))
+        return;
+    if (!m_timer.isActive())
+        m_timer.startOneShot(0);
+}
+
+void FontFaceSet::timerFired(Timer<FontFaceSet>*)
+{
+    firePendingEvents();
+    resolvePendingLoadPromises();
+    fireDoneEventIfPossible();
+}
+
+void FontFaceSet::scheduleEvent(PassRefPtr<Event> event)
+{
+    m_pendingEvents.append(event);
+    if (!m_timer.isActive())
+        m_timer.startOneShot(0);
+}
+
+void FontFaceSet::firePendingEvents()
+{
+    if (m_pendingEvents.isEmpty())
+        return;
+
+    Vector<RefPtr<Event> > pendingEvents;
+    m_pendingEvents.swap(pendingEvents);
+    for (size_t index = 0; index < pendingEvents.size(); ++index)
+        dispatchEvent(pendingEvents[index].release());
+}
+
+void FontFaceSet::scheduleResolve(LoadFontPromiseResolver* resolver)
+{
+    m_pendingLoadResolvers.append(resolver);
+    if (!m_timer.isActive())
+        m_timer.startOneShot(0);
+}
+
+void FontFaceSet::resolvePendingLoadPromises()
+{
+    if (m_pendingLoadResolvers.isEmpty())
+        return;
+
+    Vector<RefPtr<LoadFontPromiseResolver> > resolvers;
+    m_pendingLoadResolvers.swap(resolvers);
+    for (size_t index = 0; index < resolvers.size(); ++index)
+        resolvers[index]->resolve();
+}
+
+void FontFaceSet::beginFontLoading(FontFace* fontFace)
+{
+    m_histogram.incrementCount();
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
+
+    ++m_loadingCount;
+    if (m_loadingCount == 1 && !m_shouldFireDoneEvent)
+        scheduleEvent(CSSFontFaceLoadEvent::createForFontFaces(eventNames().loadingEvent));
+    m_shouldFireDoneEvent = false;
+}
+
+void FontFaceSet::fontLoaded(FontFace* fontFace)
+{
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
+    m_loadedFonts.append(fontFace);
+    queueDoneEvent(fontFace);
+}
+
+void FontFaceSet::loadError(FontFace* fontFace)
+{
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
+    m_failedFonts.append(fontFace);
+    queueDoneEvent(fontFace);
+}
+
+void FontFaceSet::queueDoneEvent(FontFace* fontFace)
+{
+    ASSERT(m_loadingCount > 0);
+    --m_loadingCount;
+    if (!m_loadingCount) {
+        ASSERT(!m_shouldFireDoneEvent);
+        m_shouldFireDoneEvent = true;
+        if (!m_timer.isActive())
+            m_timer.startOneShot(0);
+    }
+}
+
+ScriptPromise FontFaceSet::ready()
+{
+    OwnPtr<FontsReadyPromiseResolver> resolver = FontsReadyPromiseResolver::create(scriptExecutionContext());
+    ScriptPromise promise = resolver->promise();
+    m_readyResolvers.append(resolver.release());
+    if (!m_timer.isActive())
+        m_timer.startOneShot(0);
+    return promise;
+}
+
+void FontFaceSet::fireDoneEventIfPossible()
+{
+    if (!m_pendingEvents.isEmpty() || !m_pendingLoadResolvers.isEmpty())
+        return;
+    if (m_loadingCount || (!m_shouldFireDoneEvent && m_readyResolvers.isEmpty()))
+        return;
+
+    // If the layout was invalidated in between when we thought layout
+    // was updated and when we're ready to fire the event, just wait
+    // until after the next layout before firing events.
+    Document* d = document();
+    if (!d->view() || d->view()->needsLayout())
+        return;
+
+    if (m_shouldFireDoneEvent) {
+        m_shouldFireDoneEvent = false;
+        RefPtr<CSSFontFaceLoadEvent> doneEvent;
+        RefPtr<CSSFontFaceLoadEvent> errorEvent;
+        doneEvent = CSSFontFaceLoadEvent::createForFontFaces(eventNames().loadingdoneEvent, m_loadedFonts);
+        m_loadedFonts.clear();
+        if (!m_failedFonts.isEmpty()) {
+            errorEvent = CSSFontFaceLoadEvent::createForFontFaces(eventNames().loadingerrorEvent, m_failedFonts);
+            m_failedFonts.clear();
+        }
+        dispatchEvent(doneEvent);
+        if (errorEvent)
+            dispatchEvent(errorEvent);
+    }
+
+    if (!m_readyResolvers.isEmpty()) {
+        Vector<OwnPtr<FontsReadyPromiseResolver> > resolvers;
+        m_readyResolvers.swap(resolvers);
+        for (size_t index = 0; index < resolvers.size(); ++index)
+            resolvers[index]->call(this);
+    }
+}
+
+Vector<RefPtr<FontFace> > FontFaceSet::match(const String& fontString, const String&, ExceptionState& es)
+{
+    // FIXME: The second parameter (text) is ignored.
+    Vector<RefPtr<FontFace> > matchedFonts;
+
+    Font font;
+    if (!resolveFontStyle(fontString, font)) {
+        es.throwDOMException(SyntaxError);
+        return matchedFonts;
+    }
+
+    for (const FontFamily* f = &font.family(); f; f = f->next()) {
+        CSSSegmentedFontFace* face = document()->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
+        if (face)
+            matchedFonts.append(face->fontFaces());
+    }
+    return matchedFonts;
+}
+
+ScriptPromise FontFaceSet::load(const String& fontString, const String&, ExceptionState& es)
+{
+    // FIXME: The second parameter (text) is ignored.
+    Font font;
+    if (!resolveFontStyle(fontString, font)) {
+        es.throwDOMException(SyntaxError);
+        return ScriptPromise();
+    }
+
+    Document* d = document();
+    RefPtr<LoadFontPromiseResolver> resolver = LoadFontPromiseResolver::create(font.family(), scriptExecutionContext());
+    for (const FontFamily* f = &font.family(); f; f = f->next()) {
+        CSSSegmentedFontFace* face = d->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
+        if (!face) {
+            resolver->error(d);
+            continue;
+        }
+        face->loadFont(font.fontDescription(), resolver);
+    }
+    return resolver->promise();
+}
+
+bool FontFaceSet::check(const String& fontString, const String&, ExceptionState& es)
+{
+    // FIXME: The second parameter (text) is ignored.
+    Font font;
+    if (!resolveFontStyle(fontString, font)) {
+        es.throwDOMException(SyntaxError);
+        return false;
+    }
+
+    for (const FontFamily* f = &font.family(); f; f = f->next()) {
+        CSSSegmentedFontFace* face = document()->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
+        if (!face || !face->checkFont())
+            return false;
+    }
+    return true;
+}
+
+bool FontFaceSet::resolveFontStyle(const String& fontString, Font& font)
+{
+    if (fontString.isEmpty())
+        return false;
+
+    // Interpret fontString in the same way as the 'font' attribute of CanvasRenderingContext2D.
+    RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
+    CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, CSSStrictMode, 0);
+    if (parsedStyle->isEmpty())
+        return false;
+
+    String fontValue = parsedStyle->getPropertyValue(CSSPropertyFont);
+    if (fontValue == "inherit" || fontValue == "initial")
+        return false;
+
+    RefPtr<RenderStyle> style = RenderStyle::create();
+
+    FontFamily fontFamily;
+    fontFamily.setFamily(defaultFontFamily);
+
+    FontDescription defaultFontDescription;
+    defaultFontDescription.setFamily(fontFamily);
+    defaultFontDescription.setSpecifiedSize(defaultFontSize);
+    defaultFontDescription.setComputedSize(defaultFontSize);
+
+    style->setFontDescription(defaultFontDescription);
+
+    style->font().update(style->font().fontSelector());
+
+    // Now map the font property longhands into the style.
+    CSSPropertyValue properties[] = {
+        CSSPropertyValue(CSSPropertyFontFamily, *parsedStyle),
+        CSSPropertyValue(CSSPropertyFontStyle, *parsedStyle),
+        CSSPropertyValue(CSSPropertyFontVariant, *parsedStyle),
+        CSSPropertyValue(CSSPropertyFontWeight, *parsedStyle),
+        CSSPropertyValue(CSSPropertyFontSize, *parsedStyle),
+        CSSPropertyValue(CSSPropertyLineHeight, *parsedStyle),
+    };
+    StyleResolver* styleResolver = document()->styleResolver();
+    styleResolver->applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), style.get());
+
+    font = style->font();
+    font.update(styleResolver->fontSelector());
+    return true;
+}
+
+void FontFaceSet::FontLoadHistogram::record()
+{
+    if (m_recorded)
+        return;
+    m_recorded = true;
+    HistogramSupport::histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
+}
+
+} // namespace WebCore
diff --git a/Source/core/css/FontLoader.h b/Source/core/css/FontFaceSet.h
similarity index 64%
rename from Source/core/css/FontLoader.h
rename to Source/core/css/FontFaceSet.h
index c67a407..fdc2b3a 100644
--- a/Source/core/css/FontLoader.h
+++ b/Source/core/css/FontFaceSet.h
@@ -23,63 +23,70 @@
  * DAMAGE.
  */
 
-#ifndef FontLoader_h
-#define FontLoader_h
+#ifndef FontFaceSet_h
+#define FontFaceSet_h
 
+#include "bindings/v8/ScriptPromise.h"
+#include "core/css/FontFace.h"
 #include "core/dom/ActiveDOMObject.h"
 #include "core/dom/EventListener.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/EventTarget.h"
-#include "core/html/VoidCallback.h"
 #include "core/platform/Timer.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
+// Mac OS X 10.6 SDK defines check() macro that interfares with our check() method
+#ifdef check
+#undef check
+#endif
+
 namespace WebCore {
 
-class FontResource;
-class CSSFontFaceRule;
 class CSSFontFaceSource;
 class Dictionary;
 class Document;
 class Event;
+class ExceptionState;
 class Font;
+class FontResource;
+class FontsReadyPromiseResolver;
+class LoadFontPromiseResolver;
 class ScriptExecutionContext;
 
-class FontLoader : public RefCounted<FontLoader>, public ActiveDOMObject, public EventTarget {
+class FontFaceSet : public RefCounted<FontFaceSet>, public ActiveDOMObject, public EventTarget {
 public:
-    static PassRefPtr<FontLoader> create(Document* document)
+    static PassRefPtr<FontFaceSet> create(Document* document)
     {
-        return adoptRef<FontLoader>(new FontLoader(document));
+        return adoptRef<FontFaceSet>(new FontFaceSet(document));
     }
-    virtual ~FontLoader();
+    virtual ~FontFaceSet();
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(loading);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(loadingdone);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
-    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
+    DEFINE_ATTRIBUTE_EVENT_LISTENER(loadingerror);
 
-    bool checkFont(const String&, const String&);
-    void loadFont(const Dictionary&);
-    void notifyWhenFontsReady(PassRefPtr<VoidCallback>);
+    Vector<RefPtr<FontFace> > match(const String& font, const String& text, ExceptionState&);
+    bool check(const String& font, const String& text, ExceptionState&);
+    ScriptPromise load(const String& font, const String& text, ExceptionState&);
+    ScriptPromise ready();
 
-    bool loading() const { return m_loadingCount > 0 || m_pendingDoneEvent; }
+    AtomicString status() const;
 
     virtual ScriptExecutionContext* scriptExecutionContext() const;
     virtual const AtomicString& interfaceName() const;
 
-    using RefCounted<FontLoader>::ref;
-    using RefCounted<FontLoader>::deref;
+    using RefCounted<FontFaceSet>::ref;
+    using RefCounted<FontFaceSet>::deref;
 
     Document* document() const;
 
     void didLayout();
-    void beginFontLoading(CSSFontFaceRule*);
-    void fontLoaded(CSSFontFaceRule*);
-    void loadError(CSSFontFaceRule*, CSSFontFaceSource*);
-    void scheduleCallback(PassRefPtr<VoidCallback>);
+    void beginFontLoading(FontFace*);
+    void fontLoaded(FontFace*);
+    void loadError(FontFace*);
+    void scheduleResolve(LoadFontPromiseResolver*);
 
 private:
     class FontLoadHistogram {
@@ -93,7 +100,7 @@
         bool m_recorded;
     };
 
-    FontLoader(Document*);
+    FontFaceSet(Document*);
 
     virtual void refEventTarget() { ref(); }
     virtual void derefEventTarget() { deref(); }
@@ -101,23 +108,25 @@
     virtual EventTargetData* ensureEventTargetData();
 
     void scheduleEvent(PassRefPtr<Event>);
-    void queueDoneEvent(CSSFontFaceRule* rule);
+    void queueDoneEvent(FontFace*);
     void firePendingEvents();
-    void firePendingCallbacks();
+    void resolvePendingLoadPromises();
     void fireDoneEventIfPossible();
     bool resolveFontStyle(const String&, Font&);
-    void timerFired(Timer<FontLoader>*);
+    void timerFired(Timer<FontFaceSet>*);
 
     EventTargetData m_eventTargetData;
     unsigned m_loadingCount;
     Vector<RefPtr<Event> > m_pendingEvents;
-    Vector<RefPtr<VoidCallback> > m_pendingCallbacks;
-    Vector<RefPtr<VoidCallback> > m_fontsReadyCallbacks;
-    RefPtr<Event> m_pendingDoneEvent;
-    Timer<FontLoader> m_timer;
+    Vector<RefPtr<LoadFontPromiseResolver> > m_pendingLoadResolvers;
+    Vector<OwnPtr<FontsReadyPromiseResolver> > m_readyResolvers;
+    FontFaceArray m_loadedFonts;
+    FontFaceArray m_failedFonts;
+    bool m_shouldFireDoneEvent;
+    Timer<FontFaceSet> m_timer;
     FontLoadHistogram m_histogram;
 };
 
 } // namespace WebCore
 
-#endif // FontLoader_h
+#endif // FontFaceSet_h
diff --git a/Source/core/css/FontLoader.idl b/Source/core/css/FontFaceSet.idl
similarity index 75%
rename from Source/core/css/FontLoader.idl
rename to Source/core/css/FontFaceSet.idl
index ff4e533..9fe5d56 100644
--- a/Source/core/css/FontLoader.idl
+++ b/Source/core/css/FontFaceSet.idl
@@ -28,21 +28,23 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+enum FontFaceSetLoadStatus { "loading", "loaded" };
+
 [
     NoInterfaceObject,
     EnabledAtRuntime=FontLoadEvents,
     ActiveDOMObject,
     GenerateIsReachable=document
-] interface FontLoader : EventTarget {
+] interface FontFaceSet : EventTarget {
 
     attribute EventHandler onloading;
     attribute EventHandler onloadingdone;
-    attribute EventHandler onloadstart;
-    attribute EventHandler onload;
-    attribute EventHandler onerror;
+    attribute EventHandler onloadingerror;
 
-    boolean checkFont(DOMString font, [Default=NullString] optional DOMString text);
-    void loadFont(Dictionary params);
-    void notifyWhenFontsReady(VoidCallback callback);
-    readonly attribute boolean loading;
+    [RaisesException] sequence<FontFace> match(DOMString font, [Default=NullString] optional DOMString text);
+    [RaisesException] boolean check(DOMString font, [Default=NullString] optional DOMString text);
+    [EnabledAtRuntime=Promise, RaisesException] Promise load(DOMString font, [Default=NullString] optional DOMString text);
+    [EnabledAtRuntime=Promise] Promise ready();
+
+    readonly attribute FontFaceSetLoadStatus status;
 };
diff --git a/Source/core/css/FontLoader.cpp b/Source/core/css/FontLoader.cpp
deleted file mode 100644
index 4e0609c..0000000
--- a/Source/core/css/FontLoader.cpp
+++ /dev/null
@@ -1,372 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- * DAMAGE.
- */
-
-#include "config.h"
-#include "core/css/FontLoader.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "bindings/v8/Dictionary.h"
-#include "core/css/CSSFontFaceLoadEvent.h"
-#include "core/css/CSSFontFaceSource.h"
-#include "core/css/CSSFontSelector.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSSegmentedFontFace.h"
-#include "core/css/StylePropertySet.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/DOMException.h"
-#include "core/dom/Document.h"
-#include "core/page/FrameView.h"
-#include "core/platform/HistogramSupport.h"
-
-namespace WebCore {
-
-static const int defaultFontSize = 10;
-static const char* const defaultFontFamily = "sans-serif";
-
-class LoadFontCallback : public CSSSegmentedFontFace::LoadFontCallback {
-public:
-    static PassRefPtr<LoadFontCallback> create(int numLoading, PassRefPtr<VoidCallback> loadCallback, PassRefPtr<VoidCallback> errorCallback)
-    {
-        return adoptRef<LoadFontCallback>(new LoadFontCallback(numLoading, loadCallback, errorCallback));
-    }
-
-    static PassRefPtr<LoadFontCallback> createFromParams(const Dictionary& params, const FontFamily& family)
-    {
-        RefPtr<VoidCallback> onsuccess;
-        RefPtr<VoidCallback> onerror;
-        params.get("onsuccess", onsuccess);
-        params.get("onerror", onerror);
-        if (!onsuccess && !onerror)
-            return 0;
-        int numFamilies = 0;
-        for (const FontFamily* f = &family; f; f = f->next())
-            numFamilies++;
-        return LoadFontCallback::create(numFamilies, onsuccess, onerror);
-    }
-
-    virtual void notifyLoaded(CSSSegmentedFontFace*) OVERRIDE;
-    virtual void notifyError(CSSSegmentedFontFace*) OVERRIDE;
-    void loaded(Document*);
-    void error(Document*);
-private:
-    LoadFontCallback(int numLoading, PassRefPtr<VoidCallback> loadCallback, PassRefPtr<VoidCallback> errorCallback)
-        : m_numLoading(numLoading)
-        , m_errorOccured(false)
-        , m_loadCallback(loadCallback)
-        , m_errorCallback(errorCallback)
-    { }
-
-    int m_numLoading;
-    bool m_errorOccured;
-    RefPtr<VoidCallback> m_loadCallback;
-    RefPtr<VoidCallback> m_errorCallback;
-};
-
-void LoadFontCallback::loaded(Document* document)
-{
-    m_numLoading--;
-    if (m_numLoading || !document)
-        return;
-
-    if (m_errorOccured) {
-        if (m_errorCallback)
-            document->fontloader()->scheduleCallback(m_errorCallback.release());
-    } else {
-        if (m_loadCallback)
-            document->fontloader()->scheduleCallback(m_loadCallback.release());
-    }
-}
-
-void LoadFontCallback::error(Document* document)
-{
-    m_errorOccured = true;
-    loaded(document);
-}
-
-void LoadFontCallback::notifyLoaded(CSSSegmentedFontFace* face)
-{
-    loaded(face->fontSelector()->document());
-}
-
-void LoadFontCallback::notifyError(CSSSegmentedFontFace* face)
-{
-    error(face->fontSelector()->document());
-}
-
-FontLoader::FontLoader(Document* document)
-    : ActiveDOMObject(document)
-    , m_loadingCount(0)
-    , m_timer(this, &FontLoader::timerFired)
-{
-    suspendIfNeeded();
-}
-
-FontLoader::~FontLoader()
-{
-}
-
-Document* FontLoader::document() const
-{
-    return toDocument(scriptExecutionContext());
-}
-
-EventTargetData* FontLoader::eventTargetData()
-{
-    return &m_eventTargetData;
-}
-
-EventTargetData* FontLoader::ensureEventTargetData()
-{
-    return &m_eventTargetData;
-}
-
-const AtomicString& FontLoader::interfaceName() const
-{
-    return eventNames().interfaceForFontLoader;
-}
-
-ScriptExecutionContext* FontLoader::scriptExecutionContext() const
-{
-    return ActiveDOMObject::scriptExecutionContext();
-}
-
-void FontLoader::didLayout()
-{
-    Document* d = document();
-    if (d->page() && d->page()->mainFrame() == d->frame())
-        m_histogram.record();
-    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
-        return;
-    if (m_loadingCount || (!m_pendingDoneEvent && m_fontsReadyCallbacks.isEmpty()))
-        return;
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
-}
-
-void FontLoader::timerFired(Timer<FontLoader>*)
-{
-    firePendingEvents();
-    firePendingCallbacks();
-    fireDoneEventIfPossible();
-}
-
-void FontLoader::scheduleEvent(PassRefPtr<Event> event)
-{
-    m_pendingEvents.append(event);
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
-}
-
-void FontLoader::firePendingEvents()
-{
-    if (m_pendingEvents.isEmpty())
-        return;
-
-    Vector<RefPtr<Event> > pendingEvents;
-    m_pendingEvents.swap(pendingEvents);
-    for (size_t index = 0; index < pendingEvents.size(); ++index)
-        dispatchEvent(pendingEvents[index].release());
-}
-
-void FontLoader::scheduleCallback(PassRefPtr<VoidCallback> callback)
-{
-    m_pendingCallbacks.append(callback);
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
-}
-
-void FontLoader::firePendingCallbacks()
-{
-    if (m_pendingCallbacks.isEmpty())
-        return;
-
-    Vector<RefPtr<VoidCallback> > pendingCallbacks;
-    m_pendingCallbacks.swap(pendingCallbacks);
-    for (size_t index = 0; index < pendingCallbacks.size(); ++index)
-        pendingCallbacks[index]->handleEvent();
-}
-
-void FontLoader::beginFontLoading(CSSFontFaceRule* rule)
-{
-    m_histogram.incrementCount();
-    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
-        return;
-
-    ++m_loadingCount;
-    if (m_loadingCount == 1 && !m_pendingDoneEvent)
-        scheduleEvent(CSSFontFaceLoadEvent::createForFontFaceRule(eventNames().loadingEvent, rule));
-    scheduleEvent(CSSFontFaceLoadEvent::createForFontFaceRule(eventNames().loadstartEvent, rule));
-    m_pendingDoneEvent.clear();
-}
-
-void FontLoader::fontLoaded(CSSFontFaceRule* rule)
-{
-    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
-        return;
-    scheduleEvent(CSSFontFaceLoadEvent::createForFontFaceRule(eventNames().loadEvent, rule));
-    queueDoneEvent(rule);
-}
-
-void FontLoader::loadError(CSSFontFaceRule* rule, CSSFontFaceSource* source)
-{
-    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
-        return;
-    // FIXME: We should report NetworkError in case of timeout, etc.
-    String errorName = (source && source->isDecodeError()) ? "InvalidFontDataError" : DOMException::getErrorName(NotFoundError);
-    scheduleEvent(CSSFontFaceLoadEvent::createForError(rule, DOMError::create(errorName)));
-    queueDoneEvent(rule);
-}
-
-void FontLoader::queueDoneEvent(CSSFontFaceRule* rule)
-{
-    ASSERT(m_loadingCount > 0);
-    --m_loadingCount;
-    if (!m_loadingCount) {
-        ASSERT(!m_pendingDoneEvent);
-        m_pendingDoneEvent = CSSFontFaceLoadEvent::createForFontFaceRule(eventNames().loadingdoneEvent, rule);
-    }
-}
-
-void FontLoader::notifyWhenFontsReady(PassRefPtr<VoidCallback> callback)
-{
-    m_fontsReadyCallbacks.append(callback);
-    if (!m_timer.isActive())
-        m_timer.startOneShot(0);
-}
-
-void FontLoader::fireDoneEventIfPossible()
-{
-    if (!m_pendingEvents.isEmpty() || !m_pendingCallbacks.isEmpty())
-        return;
-    if (m_loadingCount || (!m_pendingDoneEvent && m_fontsReadyCallbacks.isEmpty()))
-        return;
-
-    // If the layout was invalidated in between when we thought layout
-    // was updated and when we're ready to fire the event, just wait
-    // until after the next layout before firing events.
-    Document* d = document();
-    if (!d->view() || d->view()->needsLayout())
-        return;
-
-    if (m_pendingDoneEvent)
-        dispatchEvent(m_pendingDoneEvent.release());
-
-    if (!m_fontsReadyCallbacks.isEmpty()) {
-        Vector<RefPtr<VoidCallback> > callbacks;
-        m_fontsReadyCallbacks.swap(callbacks);
-        for (size_t index = 0; index < callbacks.size(); ++index)
-            callbacks[index]->handleEvent();
-    }
-}
-
-void FontLoader::loadFont(const Dictionary& params)
-{
-    // FIXME: The text member of params is ignored.
-    String fontString;
-    if (!params.get("font", fontString))
-        return;
-    Font font;
-    if (!resolveFontStyle(fontString, font))
-        return;
-    RefPtr<LoadFontCallback> callback = LoadFontCallback::createFromParams(params, font.family());
-
-    for (const FontFamily* f = &font.family(); f; f = f->next()) {
-        Document* d = document();
-        CSSSegmentedFontFace* face = d->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
-        if (!face) {
-            if (callback)
-                callback->error(d);
-            continue;
-        }
-        face->loadFont(font.fontDescription(), callback);
-    }
-}
-
-bool FontLoader::checkFont(const String& fontString, const String&)
-{
-    // FIXME: The second parameter (text) is ignored.
-    Font font;
-    if (!resolveFontStyle(fontString, font))
-        return false;
-    for (const FontFamily* f = &font.family(); f; f = f->next()) {
-        CSSSegmentedFontFace* face = document()->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
-        if (!face || !face->checkFont())
-            return false;
-    }
-    return true;
-}
-
-bool FontLoader::resolveFontStyle(const String& fontString, Font& font)
-{
-    // Interpret fontString in the same way as the 'font' attribute of CanvasRenderingContext2D.
-    RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
-    CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, CSSStrictMode, 0);
-    if (parsedStyle->isEmpty())
-        return false;
-
-    String fontValue = parsedStyle->getPropertyValue(CSSPropertyFont);
-    if (fontValue == "inherit" || fontValue == "initial")
-        return false;
-
-    RefPtr<RenderStyle> style = RenderStyle::create();
-
-    FontFamily fontFamily;
-    fontFamily.setFamily(defaultFontFamily);
-
-    FontDescription defaultFontDescription;
-    defaultFontDescription.setFamily(fontFamily);
-    defaultFontDescription.setSpecifiedSize(defaultFontSize);
-    defaultFontDescription.setComputedSize(defaultFontSize);
-
-    style->setFontDescription(defaultFontDescription);
-
-    style->font().update(style->font().fontSelector());
-
-    // Now map the font property longhands into the style.
-    CSSPropertyValue properties[] = {
-        CSSPropertyValue(CSSPropertyFontFamily, *parsedStyle),
-        CSSPropertyValue(CSSPropertyFontStyle, *parsedStyle),
-        CSSPropertyValue(CSSPropertyFontVariant, *parsedStyle),
-        CSSPropertyValue(CSSPropertyFontWeight, *parsedStyle),
-        CSSPropertyValue(CSSPropertyFontSize, *parsedStyle),
-        CSSPropertyValue(CSSPropertyLineHeight, *parsedStyle),
-    };
-    StyleResolver* styleResolver = document()->styleResolver();
-    styleResolver->applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), style.get());
-
-    font = style->font();
-    font.update(styleResolver->fontSelector());
-    return true;
-}
-
-void FontLoader::FontLoadHistogram::record()
-{
-    if (m_recorded)
-        return;
-    m_recorded = true;
-    HistogramSupport::histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
-}
-
-} // namespace WebCore
diff --git a/Source/core/css/InspectorCSSOMWrappers.cpp b/Source/core/css/InspectorCSSOMWrappers.cpp
index 7cdd0f7..595d22c 100644
--- a/Source/core/css/InspectorCSSOMWrappers.cpp
+++ b/Source/core/css/InspectorCSSOMWrappers.cpp
@@ -39,7 +39,7 @@
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/CSSSupportsRule.h"
 #include "core/css/StyleSheetContents.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 
 namespace WebCore {
 
@@ -103,7 +103,7 @@
         collect(sheets[i].get());
 }
 
-void InspectorCSSOMWrappers::collectFromStyleSheetCollections(StyleSheetCollections* styleSheetCollection)
+void InspectorCSSOMWrappers::collectFromStyleEngine(StyleEngine* styleSheetCollection)
 {
     collectFromStyleSheets(styleSheetCollection->activeAuthorStyleSheets());
     collect(styleSheetCollection->pageUserSheet());
@@ -111,7 +111,7 @@
     collectFromStyleSheets(styleSheetCollection->documentUserStyleSheets());
 }
 
-CSSStyleRule* InspectorCSSOMWrappers::getWrapperForRuleInSheets(StyleRule* rule, StyleSheetCollections* styleSheetCollection)
+CSSStyleRule* InspectorCSSOMWrappers::getWrapperForRuleInSheets(StyleRule* rule, StyleEngine* styleSheetCollection)
 {
     if (m_styleRuleToCSSOMWrapperMap.isEmpty()) {
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::simpleDefaultStyleSheet);
@@ -121,7 +121,7 @@
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::mediaControlsStyleSheet);
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::fullscreenStyleSheet);
 
-        collectFromStyleSheetCollections(styleSheetCollection);
+        collectFromStyleEngine(styleSheetCollection);
     }
     return m_styleRuleToCSSOMWrapperMap.get(rule);
 }
diff --git a/Source/core/css/InspectorCSSOMWrappers.h b/Source/core/css/InspectorCSSOMWrappers.h
index f97eea4..fda8789 100644
--- a/Source/core/css/InspectorCSSOMWrappers.h
+++ b/Source/core/css/InspectorCSSOMWrappers.h
@@ -33,14 +33,14 @@
 class CSSStyleRule;
 class CSSStyleSheet;
 class StyleRule;
-class StyleSheetCollections;
+class StyleEngine;
 class StyleSheetContents;
 
 class InspectorCSSOMWrappers {
 public:
     // WARNING. This will construct CSSOM wrappers for all style rules and cache them in a map for significant memory cost.
     // It is here to support inspector. Don't use for any regular engine functions.
-    CSSStyleRule* getWrapperForRuleInSheets(StyleRule*, StyleSheetCollections*);
+    CSSStyleRule* getWrapperForRuleInSheets(StyleRule*, StyleEngine*);
     void collectFromStyleSheetIfNeeded(CSSStyleSheet*);
     void reset();
 
@@ -50,7 +50,7 @@
 
     void collectFromStyleSheetContents(HashSet<RefPtr<CSSStyleSheet> >& sheetWrapperSet, StyleSheetContents*);
     void collectFromStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&);
-    void collectFromStyleSheetCollections(StyleSheetCollections*);
+    void collectFromStyleEngine(StyleEngine*);
 
     HashMap<StyleRule*, RefPtr<CSSStyleRule> > m_styleRuleToCSSOMWrapperMap;
     HashSet<RefPtr<CSSStyleSheet> > m_styleSheetCSSOMWrapperSet;
diff --git a/Source/core/css/LengthFunctions.cpp b/Source/core/css/LengthFunctions.cpp
index 28c98de..3a91ce2 100644
--- a/Source/core/css/LengthFunctions.cpp
+++ b/Source/core/css/LengthFunctions.cpp
@@ -53,25 +53,13 @@
     case Calculated:
         return length.nonNanCalculatedValue(maximumValue);
     case ViewportPercentageWidth:
-        if (renderView)
-            return static_cast<LayoutUnit>(renderView->viewportSize().width() * length.viewportPercentageLength() / 100.0f);
-        return 0;
+        return renderView ? renderView->viewportPercentageWidth(length.viewportPercentageLength()) : LayoutUnit(0);
     case ViewportPercentageHeight:
-        if (renderView)
-            return static_cast<LayoutUnit>(renderView->viewportSize().height() * length.viewportPercentageLength() / 100.0f);
-        return 0;
+        return renderView ? renderView->viewportPercentageHeight(length.viewportPercentageLength()) : LayoutUnit(0);
     case ViewportPercentageMin:
-        if (renderView) {
-            IntSize viewportSize = renderView->viewportSize();
-            return static_cast<LayoutUnit>(std::min(viewportSize.width(), viewportSize.height()) * length.viewportPercentageLength() / 100.0f);
-        }
-        return 0;
+        return renderView ? renderView->viewportPercentageMin(length.viewportPercentageLength()) : LayoutUnit(0);
     case ViewportPercentageMax:
-        if (renderView) {
-            IntSize viewportSize = renderView->viewportSize();
-            return static_cast<LayoutUnit>(std::max(viewportSize.width(), viewportSize.height()) * length.viewportPercentageLength() / 100.0f);
-        }
-        return 0;
+        return renderView ? renderView->viewportPercentageMax(length.viewportPercentageLength()) : LayoutUnit(0);
     case FillAvailable:
     case Auto:
         return 0;
@@ -132,25 +120,13 @@
     case Calculated:
         return length.nonNanCalculatedValue(maximumValue);
     case ViewportPercentageWidth:
-        if (renderView)
-            return static_cast<int>(renderView->viewportSize().width() * length.viewportPercentageLength() / 100.0f);
-        return 0;
+        return renderView ? static_cast<int>(renderView->viewportPercentageWidth(length.viewportPercentageLength())) : 0;
     case ViewportPercentageHeight:
-        if (renderView)
-            return static_cast<int>(renderView->viewportSize().height() * length.viewportPercentageLength() / 100.0f);
-        return 0;
+        return renderView ? static_cast<int>(renderView->viewportPercentageHeight(length.viewportPercentageLength())) : 0;
     case ViewportPercentageMin:
-        if (renderView) {
-            IntSize viewportSize = renderView->viewportSize();
-            return static_cast<int>(std::min(viewportSize.width(), viewportSize.height()) * length.viewportPercentageLength() / 100.0f);
-        }
-        return 0;
+        return renderView ? static_cast<int>(renderView->viewportPercentageMin(length.viewportPercentageLength())) : 0;
     case ViewportPercentageMax:
-        if (renderView) {
-            IntSize viewportSize = renderView->viewportSize();
-            return static_cast<int>(std::max(viewportSize.width(), viewportSize.height()) * length.viewportPercentageLength() / 100.0f);
-        }
-        return 0;
+        return renderView ? static_cast<int>(renderView->viewportPercentageMax(length.viewportPercentageLength())) : 0;
     case Relative:
     case Intrinsic:
     case MinIntrinsic:
diff --git a/Source/core/css/MediaQueryListListener.cpp b/Source/core/css/MediaQueryListListener.cpp
index 36bf5c4..494883e 100644
--- a/Source/core/css/MediaQueryListListener.cpp
+++ b/Source/core/css/MediaQueryListListener.cpp
@@ -35,7 +35,7 @@
         return; // JS may not be enabled.
 
     v8::Context::Scope scope(context);
-    callback.appendArgument(toV8(query, v8::Handle<v8::Object>(), context->GetIsolate()));
+    callback.appendArgument(ScriptValue(toV8(query, v8::Handle<v8::Object>(), context->GetIsolate()), context->GetIsolate()));
     callback.call();
 }
 
diff --git a/Source/core/css/SelectorChecker.cpp b/Source/core/css/SelectorChecker.cpp
index d6d28b8..6837ffd 100644
--- a/Source/core/css/SelectorChecker.cpp
+++ b/Source/core/css/SelectorChecker.cpp
@@ -154,7 +154,7 @@
 
             PseudoId pseudoId = CSSSelector::pseudoId(context.selector->pseudoType());
             if (pseudoId == FIRST_LETTER)
-                context.element->document().styleSheetCollections()->setUsesFirstLetterRules(true);
+                context.element->document().styleEngine()->setUsesFirstLetterRules(true);
             if (pseudoId != NOPSEUDO && m_mode != SharingRules)
                 dynamicPseudo = pseudoId;
         }
@@ -413,15 +413,10 @@
     if (selector->m_match == CSSSelector::PseudoClass) {
         // Handle :not up front.
         if (selector->pseudoType() == CSSSelector::PseudoNot) {
-            const CSSSelectorList* selectorList = selector->selectorList();
-
-            // FIXME: We probably should fix the parser and make it never produce :not rules with missing selector list.
-            if (!selectorList)
-                return false;
-
             SelectorCheckingContext subContext(context);
             subContext.isSubSelector = true;
-            for (subContext.selector = selectorList->first(); subContext.selector; subContext.selector = subContext.selector->tagHistory()) {
+            ASSERT(selector->selectorList());
+            for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = subContext.selector->tagHistory()) {
                 // :not cannot nest. I don't really know why this is a
                 // restriction in CSS3, but it is, so let's honor it.
                 // the parser enforces that this never occurs
@@ -466,7 +461,7 @@
                     element->setStyleAffectedByEmpty();
                     if (context.elementStyle)
                         context.elementStyle->setEmptyState(result);
-                    else if (element->renderStyle() && (element->document().styleSheetCollections()->usesSiblingRules() || element->renderStyle()->unique()))
+                    else if (element->renderStyle() && (element->document().styleEngine()->usesSiblingRules() || element->renderStyle()->unique()))
                         element->renderStyle()->setEmptyState(result);
                 }
                 return result;
@@ -609,6 +604,7 @@
                 SelectorCheckingContext subContext(context);
                 subContext.isSubSelector = true;
                 PseudoId ignoreDynamicPseudo = NOPSEUDO;
+                ASSERT(selector->selectorList());
                 for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(subContext.selector)) {
                     if (match(subContext, ignoreDynamicPseudo, siblingTraversalStrategy) == SelectorMatches)
                         return true;
@@ -946,11 +942,8 @@
         case CSSSelector::PseudoNot:
             {
                 // :not(:visited) is equivalent to :link. Parser enforces that :not can't nest.
-                const CSSSelectorList* selectorList = selector->selectorList();
-                if (!selectorList)
-                    break;
-
-                for (const CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = subSelector->tagHistory()) {
+                ASSERT(selector->selectorList());
+                for (const CSSSelector* subSelector = selector->selectorList()->first(); subSelector; subSelector = subSelector->tagHistory()) {
                     CSSSelector::PseudoType subType = subSelector->pseudoType();
                     if (subType == CSSSelector::PseudoVisited)
                         linkMatchType &= ~SelectorChecker::MatchVisited;
diff --git a/Source/core/css/StylePropertySet.cpp b/Source/core/css/StylePropertySet.cpp
index 3f84e58..8df65b8 100644
--- a/Source/core/css/StylePropertySet.cpp
+++ b/Source/core/css/StylePropertySet.cpp
@@ -80,7 +80,7 @@
 {
     StylePropertyMetadata* metadataArray = const_cast<StylePropertyMetadata*>(this->metadataArray());
     CSSValue** valueArray = const_cast<CSSValue**>(this->valueArray());
-    for (unsigned i = 0; i < length; ++i) {
+    for (unsigned i = 0; i < m_arraySize; ++i) {
         metadataArray[i] = properties[i].metadata();
         valueArray[i] = properties[i].value();
         valueArray[i]->ref();
@@ -342,7 +342,7 @@
     parser.parseDeclaration(this, styleDeclaration, 0, contextStyleSheet);
 }
 
-void MutableStylePropertySet::addParsedProperties(const Vector<CSSProperty>& properties)
+void MutableStylePropertySet::addParsedProperties(const Vector<CSSProperty, 256>& properties)
 {
     m_propertyVector.reserveCapacity(m_propertyVector.size() + properties.size());
     for (unsigned i = 0; i < properties.size(); ++i)
diff --git a/Source/core/css/StylePropertySet.h b/Source/core/css/StylePropertySet.h
index 7d8be4f..8e9c913 100644
--- a/Source/core/css/StylePropertySet.h
+++ b/Source/core/css/StylePropertySet.h
@@ -124,6 +124,9 @@
     bool propertyMatches(CSSPropertyID, const CSSValue*) const;
 
 protected:
+
+    enum { MaxArraySize = (1 << 28) - 1 };
+
     StylePropertySet(CSSParserMode cssParserMode)
         : m_cssParserMode(cssParserMode)
         , m_isMutable(true)
@@ -133,12 +136,12 @@
     StylePropertySet(CSSParserMode cssParserMode, unsigned immutableArraySize)
         : m_cssParserMode(cssParserMode)
         , m_isMutable(false)
-        , m_arraySize(immutableArraySize)
+        , m_arraySize(std::min(immutableArraySize, unsigned(MaxArraySize)))
     { }
 
-    unsigned m_cssParserMode : 2;
+    unsigned m_cssParserMode : 3;
     mutable unsigned m_isMutable : 1;
-    unsigned m_arraySize : 29;
+    unsigned m_arraySize : 28;
 
     friend class PropertySetCSSStyleDeclaration;
 };
@@ -177,7 +180,7 @@
     unsigned propertyCount() const { return m_propertyVector.size(); }
     PropertySetCSSStyleDeclaration* cssStyleDeclaration();
 
-    void addParsedProperties(const Vector<CSSProperty>&);
+    void addParsedProperties(const Vector<CSSProperty, 256>&);
     void addParsedProperty(const CSSProperty&);
 
     // These expand shorthand properties into multiple properties.
diff --git a/Source/core/css/StyleSheetList.cpp b/Source/core/css/StyleSheetList.cpp
index a792adb..b773deb 100644
--- a/Source/core/css/StyleSheetList.cpp
+++ b/Source/core/css/StyleSheetList.cpp
@@ -23,7 +23,7 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/html/HTMLStyleElement.h"
 #include "wtf/text/WTFString.h"
 
@@ -44,12 +44,12 @@
 {
     if (!m_document)
         return m_detachedStyleSheets;
-    return m_document->styleSheetCollections()->styleSheetsForStyleSheetList();
+    return m_document->styleEngine()->styleSheetsForStyleSheetList();
 }
 
 void StyleSheetList::detachFromDocument()
 {
-    m_detachedStyleSheets = m_document->styleSheetCollections()->styleSheetsForStyleSheetList();
+    m_detachedStyleSheets = m_document->styleEngine()->styleSheetsForStyleSheetList();
     m_document = 0;
 }
 
diff --git a/Source/core/css/resolver/AnimatedStyleBuilder.cpp b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
index f1388f8..bc86494 100644
--- a/Source/core/css/resolver/AnimatedStyleBuilder.cpp
+++ b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
@@ -61,21 +61,6 @@
     return cssPrimitiveValue->convertToLength<AnyConversion>(style, state.rootElementStyle(), style->effectiveZoom());
 }
 
-unsigned animatableValueToUnsigned(const AnimatableValue* value)
-{
-    return clampTo<unsigned>(round(toAnimatableNumber(value)->toDouble()));
-}
-
-unsigned short animatableValueToUnsignedShort(const AnimatableValue* value)
-{
-    return clampTo<unsigned short>(round(toAnimatableNumber(value)->toDouble()));
-}
-
-int animatableValueToInt(const AnimatableValue* value)
-{
-    return clampTo<int>(round(toAnimatableNumber(value)->toDouble()));
-}
-
 template<typename T> T animatableValueRoundClampTo(const AnimatableValue* value)
 {
     COMPILE_ASSERT(WTF::IsInteger<T>::value, ShouldUseIntegralTypeTWhenRoundingValues);
@@ -160,12 +145,12 @@
     case CSSPropertyHeight:
         style->setHeight(animatableValueToLength(value, state));
         return;
-    case CSSPropertyListStyleImage:
-        style->setListStyleImage(toAnimatableImage(value)->toStyleImage());
-        return;
     case CSSPropertyLeft:
         style->setLeft(animatableValueToLength(value, state));
         return;
+    case CSSPropertyListStyleImage:
+        style->setListStyleImage(toAnimatableImage(value)->toStyleImage());
+        return;
     case CSSPropertyMarginBottom:
         style->setMarginBottom(animatableValueToLength(value, state));
         return;
@@ -198,7 +183,7 @@
         style->setVisitedLinkOutlineColor(toAnimatableColor(value)->visitedLinkColor());
         return;
     case CSSPropertyOutlineOffset:
-        style->setOutlineOffset(animatableValueToInt(value));
+        style->setOutlineOffset(animatableValueRoundClampTo<int>(value));
         return;
     case CSSPropertyOutlineWidth:
         style->setOutlineWidth(animatableValueRoundClampTo<unsigned short>(value));
@@ -268,6 +253,9 @@
     case CSSPropertyVisibility:
         style->setVisibility(toAnimatableVisibility(value)->visibility());
         return;
+    case CSSPropertyZIndex:
+        style->setZIndex(animatableValueRoundClampTo<int>(value));
+        return;
     default:
         RELEASE_ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Unable to apply AnimatableValue to RenderStyle: %s", getPropertyNameString(property).utf8().data());
         ASSERT_NOT_REACHED();
diff --git a/Source/core/css/resolver/StyleBuilderCustom.cpp b/Source/core/css/resolver/StyleBuilderCustom.cpp
index a29932a..ec034c7 100644
--- a/Source/core/css/resolver/StyleBuilderCustom.cpp
+++ b/Source/core/css/resolver/StyleBuilderCustom.cpp
@@ -937,7 +937,7 @@
 
     if (primitiveValue->isFlex()) {
         // Fractional unit.
-        workingLength.setFlex(primitiveValue->getFloatValue());
+        workingLength.setFlex(primitiveValue->getDoubleValue());
         return true;
     }
 
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index cefc546..63748e5 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -64,7 +64,7 @@
 #include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/ViewportStyleResolver.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -136,7 +136,7 @@
 
     m_styleTree.clear();
 
-    StyleSheetCollections* styleSheetCollection = document.styleSheetCollections();
+    StyleEngine* styleSheetCollection = document.styleEngine();
     m_ruleSets.initUserStyle(styleSheetCollection, *m_medium, *this);
 
 #if ENABLE(SVG_FONTS)
@@ -833,36 +833,41 @@
     }
 }
 
-void StyleResolver::resolveKeyframes(const Element* element, const RenderStyle* style, const StringImpl* name, KeyframeAnimationEffect::KeyframeVector& keyframes)
+void StyleResolver::resolveKeyframes(const Element* element, const RenderStyle* style, const AtomicString& name, TimingFunction* defaultTimingFunction, KeyframeAnimationEffect::KeyframeVector& keyframes, RefPtr<TimingFunction>& timingFunction)
 {
     ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
-    const StyleRuleKeyframes* keyframesRule = matchScopedKeyframesRule(element, name);
+    const StyleRuleKeyframes* keyframesRule = matchScopedKeyframesRule(element, name.impl());
     if (!keyframesRule)
         return;
 
     // Construct and populate the style for each keyframe
+    HashMap<double, RefPtr<TimingFunction> > timingFunctions;
     const Vector<RefPtr<StyleKeyframe> >& styleKeyframes = keyframesRule->keyframes();
     for (size_t i = 0; i < styleKeyframes.size(); ++i) {
         const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
         RefPtr<RenderStyle> keyframeStyle = styleForKeyframe(0, style, styleKeyframe);
+        RefPtr<Keyframe> keyframe = Keyframe::create();
         const Vector<double>& offsets = styleKeyframe->keys();
-        RefPtr<Keyframe> firstOffsetKeyframe;
-        for (size_t j = 0; j < offsets.size(); ++j) {
-            RefPtr<Keyframe> keyframe = Keyframe::create();
-            keyframe->setOffset(offsets[j]);
-            const StylePropertySet* properties = styleKeyframe->properties();
-            for (unsigned k = 0; k < properties->propertyCount(); k++) {
-                CSSPropertyID property = properties->propertyAt(k).id();
-                // FIXME: Build the correct chained timing function when this property is specified.
-                if (property == CSSPropertyWebkitAnimationTimingFunction || property == CSSPropertyAnimationTimingFunction)
-                    continue;
-                if (!CSSAnimations::isAnimatableProperty(property))
-                    continue;
-                keyframe->setPropertyValue(property, firstOffsetKeyframe ? firstOffsetKeyframe->propertyValue(property) : CSSAnimatableValueFactory::create(property, keyframeStyle.get()).get());
+        ASSERT(!offsets.isEmpty());
+        keyframe->setOffset(offsets[0]);
+        TimingFunction* timingFunction = defaultTimingFunction;
+        const StylePropertySet* properties = styleKeyframe->properties();
+        for (unsigned j = 0; j < properties->propertyCount(); j++) {
+            CSSPropertyID property = properties->propertyAt(j).id();
+            if (property == CSSPropertyWebkitAnimationTimingFunction || property == CSSPropertyAnimationTimingFunction) {
+                // FIXME: This sometimes gets the wrong timing function. See crbug.com/288540.
+
+                timingFunction = KeyframeValue::timingFunction(keyframeStyle.get(), name);
+            } else if (CSSAnimations::isAnimatableProperty(property)) {
+                keyframe->setPropertyValue(property, CSSAnimatableValueFactory::create(property, keyframeStyle.get()).get());
             }
-            if (!firstOffsetKeyframe)
-                firstOffsetKeyframe = keyframe;
-            keyframes.append(keyframe);
+        }
+        keyframes.append(keyframe);
+        // The last keyframe specified at a given offset is used.
+        timingFunctions.set(offsets[0], timingFunction);
+        for (size_t j = 1; j < offsets.size(); ++j) {
+            keyframes.append(keyframe->cloneWithOffset(offsets[j]));
+            timingFunctions.set(offsets[j], timingFunction);
         }
     }
 
@@ -880,14 +885,7 @@
     }
     keyframes.shrink(targetIndex + 1);
 
-    HashSet<CSSPropertyID> allProperties;
-    for (size_t i = 0; i < keyframes.size(); i++) {
-        const HashSet<CSSPropertyID> keyframeProperties = keyframes[i]->properties();
-        for (HashSet<CSSPropertyID>::const_iterator iter = keyframeProperties.begin(); iter != keyframeProperties.end(); ++iter)
-            allProperties.add(*iter);
-    }
-
-    // Snapshot current property values for 0% and 100% if missing.
+    // Add 0% and 100% keyframes if absent.
     RefPtr<Keyframe> startKeyframe = keyframes[0];
     if (startKeyframe->offset()) {
         startKeyframe = Keyframe::create();
@@ -900,6 +898,43 @@
         endKeyframe->setOffset(1);
         keyframes.append(endKeyframe);
     }
+    ASSERT(keyframes.size() >= 2);
+    ASSERT(!keyframes.first()->offset());
+    ASSERT(keyframes.last()->offset() == 1);
+
+    // Generate the chained timing function. Note that timing functions apply
+    // from the keyframe in which they're specified to the next keyframe.
+    // FIXME: Handle keyframe sets where some keyframes don't specify all
+    // properties. In this case, timing functions apply between the keyframes
+    // which specify a particular property, so we'll need a separate chained
+    // timing function (and therefore animation) for each property. See
+    // LayoutTests/animations/missing-keyframe-properties-timing-function.html
+    if (!timingFunctions.contains(0))
+        timingFunctions.set(0, defaultTimingFunction);
+    bool isTimingFunctionLinearThroughout = true;
+    RefPtr<ChainedTimingFunction> chainedTimingFunction = ChainedTimingFunction::create();
+    for (size_t i = 0; i < keyframes.size() - 1; ++i) {
+        double lowerBound = keyframes[i]->offset();
+        ASSERT(lowerBound >=0 && lowerBound < 1);
+        double upperBound = keyframes[i + 1]->offset();
+        ASSERT(upperBound > 0 && upperBound <= 1);
+        TimingFunction* timingFunction = timingFunctions.get(lowerBound);
+        ASSERT(timingFunction);
+        isTimingFunctionLinearThroughout &= timingFunction->type() == TimingFunction::LinearFunction;
+        chainedTimingFunction->appendSegment(upperBound, timingFunction);
+    }
+    if (isTimingFunctionLinearThroughout)
+        timingFunction = LinearTimingFunction::create();
+    else
+        timingFunction = chainedTimingFunction;
+
+    // Snapshot current property values for 0% and 100% if missing.
+    HashSet<CSSPropertyID> allProperties;
+    for (size_t i = 0; i < keyframes.size(); i++) {
+        const HashSet<CSSPropertyID>& keyframeProperties = keyframes[i]->properties();
+        for (HashSet<CSSPropertyID>::const_iterator iter = keyframeProperties.begin(); iter != keyframeProperties.end(); ++iter)
+            allProperties.add(*iter);
+    }
     const HashSet<CSSPropertyID>& startKeyframeProperties = startKeyframe->properties();
     const HashSet<CSSPropertyID>& endKeyframeProperties = endKeyframe->properties();
     bool missingStartValues = startKeyframeProperties.size() < allProperties.size();
@@ -918,6 +953,8 @@
         if (endNeedsValue)
             endKeyframe->setPropertyValue(property, snapshotValue.get());
     }
+    ASSERT(startKeyframe->properties().size() == allProperties.size());
+    ASSERT(endKeyframe->properties().size() == allProperties.size());
 }
 
 PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* e, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle)
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index 5d9ae8e..16cf401 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -195,7 +195,7 @@
     // The body of calculateCSSAnimationUpdate can move to CSSAnimations.cpp and take just const element, const style,
     // and const ScopedStyleTree
     void calculateCSSAnimationUpdate(StyleResolverState&);
-    void resolveKeyframes(const Element*, const RenderStyle*, const StringImpl* animationName, KeyframeAnimationEffect::KeyframeVector&);
+    void resolveKeyframes(const Element*, const RenderStyle*, const AtomicString& animationName, TimingFunction* defaultTimingFunction, KeyframeAnimationEffect::KeyframeVector&, RefPtr<TimingFunction>&);
     void keyframeStylesForAnimation(Element*, const RenderStyle*, KeyframeList&);
     const StyleRuleKeyframes* matchScopedKeyframesRule(const Element*, const StringImpl* animationName);
     PassRefPtr<RenderStyle> styleForKeyframe(Element*, const RenderStyle*, const StyleKeyframe*);
diff --git a/Source/core/css/resolver/StyleResolverState.h b/Source/core/css/resolver/StyleResolverState.h
index 5f2deda..6bf00dc 100644
--- a/Source/core/css/resolver/StyleResolverState.h
+++ b/Source/core/css/resolver/StyleResolverState.h
@@ -46,7 +46,7 @@
     StyleResolverState(Document&, Element*, RenderStyle* parentStyle = 0, RenderRegion* regionForStyling = 0);
     ~StyleResolverState();
 
-    // In FontLoader and CanvasRenderingContext2D, we don't have an element to grab the document from.
+    // In FontFaceSet and CanvasRenderingContext2D, we don't have an element to grab the document from.
     // This is why we have to store the document separately.
     Document& document() const { return m_document; }
     // These are all just pass-through methods to ElementResolveContext.
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index 0d20c05..440ca96 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -24,6 +24,7 @@
 #include "core/dom/Attr.h"
 
 #include "XMLNSNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Element.h"
@@ -97,9 +98,13 @@
     if (es.hadException())
         return;
 
-    if ((prefix == xmlnsAtom && namespaceURI() != XMLNSNames::xmlnsNamespaceURI)
-        || static_cast<Attr*>(this)->qualifiedName() == xmlnsAtom) {
-        es.throwDOMException(NamespaceError);
+    if (prefix == xmlnsAtom && namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
+        es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + xmlnsAtom + "' may not be used on the namespace '" + namespaceURI() + "'."));
+        return;
+    }
+
+    if (static_cast<Attr*>(this)->qualifiedName() == xmlnsAtom) {
+        es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + prefix + "' may not be used as a namespace prefix for attributes whose qualified name is '" + xmlnsAtom + "'."));
         return;
     }
 
diff --git a/Source/core/dom/CharacterData.cpp b/Source/core/dom/CharacterData.cpp
index ecf9f6c..9d6f9c7 100644
--- a/Source/core/dom/CharacterData.cpp
+++ b/Source/core/dom/CharacterData.cpp
@@ -22,6 +22,7 @@
 #include "config.h"
 #include "core/dom/CharacterData.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
 #include "core/dom/EventNames.h"
@@ -55,13 +56,13 @@
     unsigned oldLength = length();
 
     setDataAndUpdate(nonNullData, 0, oldLength, nonNullData.length());
-    document().textRemoved(this, 0, oldLength);
+    document().didRemoveText(this, 0, oldLength);
 }
 
 String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& es)
 {
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError);
+        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("substringData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
         return String();
     }
 
@@ -120,7 +121,7 @@
 void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es, RecalcStyleBehavior recalcStyleBehavior)
 {
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError);
+        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
         return;
     }
 
@@ -129,13 +130,13 @@
 
     setDataAndUpdate(newStr, offset, 0, data.length(), recalcStyleBehavior);
 
-    document().textInserted(this, offset, data.length());
+    document().didInsertText(this, offset, data.length());
 }
 
 void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es, RecalcStyleBehavior recalcStyleBehavior)
 {
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError);
+        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
         return;
     }
 
@@ -150,13 +151,13 @@
 
     setDataAndUpdate(newStr, offset, count, 0, recalcStyleBehavior);
 
-    document().textRemoved(this, offset, realCount);
+    document().didRemoveText(this, offset, realCount);
 }
 
 void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& es)
 {
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError);
+        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("replaceData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
         return;
     }
 
@@ -173,8 +174,8 @@
     setDataAndUpdate(newStr, offset, count, data.length());
 
     // update the markers for spell checking and grammar checking
-    document().textRemoved(this, offset, realCount);
-    document().textInserted(this, offset, data.length());
+    document().didRemoveText(this, offset, realCount);
+    document().didInsertText(this, offset, data.length());
 }
 
 String CharacterData::nodeValue() const
@@ -205,7 +206,7 @@
         toProcessingInstruction(this)->checkStyleSheet();
 
     if (document().frame())
-        document().frame()->selection().textWasReplaced(this, offsetOfReplacedData, oldLength, newLength);
+        document().frame()->selection().didUpdateCharacterData(this, offsetOfReplacedData, oldLength, newLength);
 
     document().incDOMTreeVersion();
     didModifyData(oldData);
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index d04d081..7417915 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -47,7 +47,7 @@
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSStyleDeclaration.h"
 #include "core/css/CSSStyleSheet.h"
-#include "core/css/FontLoader.h"
+#include "core/css/FontFaceSet.h"
 #include "core/css/MediaQueryMatcher.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleSheetContents.h"
@@ -94,7 +94,7 @@
 #include "core/dom/ScriptRunner.h"
 #include "core/dom/ScriptedAnimationController.h"
 #include "core/dom/SelectorQuery.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/dom/TouchList.h"
 #include "core/dom/TransformSource.h"
 #include "core/dom/TreeWalker.h"
@@ -156,7 +156,6 @@
 #include "core/page/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/DateComponents.h"
-#include "core/platform/HistogramSupport.h"
 #include "core/platform/Language.h"
 #include "core/platform/ScrollbarTheme.h"
 #include "core/platform/Timer.h"
@@ -405,7 +404,7 @@
     , m_domTreeVersion(++s_globalTreeVersion)
     , m_listenerTypes(0)
     , m_mutationObserverTypes(0)
-    , m_styleSheetCollections(StyleSheetCollections::create(*this))
+    , m_styleEngine(StyleEngine::create(*this))
     , m_visitedLinkState(VisitedLinkState::create(this))
     , m_visuallyOrdered(false)
     , m_readyState(Complete)
@@ -462,7 +461,7 @@
 #endif
     , m_timeline(DocumentTimeline::create(this))
     , m_templateDocumentHost(0)
-    , m_fontloader(0)
+    , m_fonts(0)
     , m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
 {
     ScriptWrappable::init(this);
@@ -494,16 +493,6 @@
     InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
 }
 
-static void histogramMutationEventUsage(const unsigned short& listenerTypes)
-{
-    HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMSubtreeModified", static_cast<bool>(listenerTypes & Document::DOMSUBTREEMODIFIED_LISTENER), 2);
-    HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInserted", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTED_LISTENER), 2);
-    HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemoved", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVED_LISTENER), 2);
-    HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeRemovedFromDocument", static_cast<bool>(listenerTypes & Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER), 2);
-    HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMNodeInsertedIntoDocument", static_cast<bool>(listenerTypes & Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER), 2);
-    HistogramSupport::histogramEnumeration("DOMAPI.PerDocumentMutationEventUsage.DOMCharacterDataModified", static_cast<bool>(listenerTypes & Document::DOMCHARACTERDATAMODIFIED_LISTENER), 2);
-}
-
 static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
 {
     if (!owner)
@@ -525,13 +514,10 @@
     if (m_templateDocument)
         m_templateDocument->setTemplateDocumentHost(0); // balanced in templateDocument().
 
-    if (Document* ownerDocument = this->ownerDocument())
-        ownerDocument->didRemoveEventTargetNode(this);
+    lifecycleNotifier()->notifyDocumentBeingDestroyed();
 
     m_scriptRunner.clear();
 
-    histogramMutationEventUsage(m_listenerTypes);
-
     removeAllEventListeners();
 
     // Currently we believe that Document can never outlive the parser.
@@ -556,7 +542,7 @@
         m_import = 0;
     }
 
-    m_styleSheetCollections.clear();
+    m_styleEngine.clear();
 
     if (m_elemSheet)
         m_elemSheet->clearOwnerNode();
@@ -630,11 +616,6 @@
     lifecycleNotifier()->notifyDocumentWasDisposed();
 }
 
-Element* Document::getElementById(const AtomicString& id) const
-{
-    return TreeScope::getElementById(id);
-}
-
 SelectorQueryCache* Document::selectorQueryCache()
 {
     if (!m_selectorQueryCache)
@@ -658,8 +639,8 @@
     selectorQueryCache()->invalidate();
     if (inQuirksMode() != wasInQuirksMode) {
         // All user stylesheets have to reparse using the different mode.
-        m_styleSheetCollections->clearPageUserSheet();
-        m_styleSheetCollections->invalidateInjectedStyleSheetCache();
+        m_styleEngine->clearPageUserSheet();
+        m_styleEngine->invalidateInjectedStyleSheetCache();
     }
 }
 
@@ -1708,13 +1689,13 @@
     // re-attaching our containing iframe, which when asked HTMLFrameElementBase::isURLAllowed
     // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
 
-    if (m_styleSheetCollections->needsUpdateActiveStylesheetsOnStyleRecalc())
-        m_styleSheetCollections->updateActiveStyleSheets(FullStyleUpdate);
+    if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
+        m_styleEngine->updateActiveStyleSheets(FullStyleUpdate);
 
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
 
     if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
-        m_styleSheetCollections->setUsesRemUnit(true);
+        m_styleEngine->setUsesRemUnit(true);
 
     m_inStyleRecalc = true;
     {
@@ -1760,15 +1741,15 @@
         unscheduleStyleRecalc();
 
         // FIXME: SVG <use> element can schedule a recalc in the middle of an already running one.
-        // See StyleSheetCollections::updateActiveStyleSheets.
-        if (m_styleSheetCollections->needsUpdateActiveStylesheetsOnStyleRecalc())
+        // See StyleEngine::updateActiveStyleSheets.
+        if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
             setNeedsStyleRecalc();
 
         m_inStyleRecalc = false;
 
         // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
         if (m_styleResolver) {
-            m_styleSheetCollections->resetCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
+            m_styleEngine->resetCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
             m_styleResolver->clearStyleSharingList();
         }
 
@@ -1990,7 +1971,7 @@
     if (Settings* docSettings = settings())
         matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
     m_styleResolver = adoptPtr(new StyleResolver(*this, matchAuthorAndUserStyles));
-    m_styleSheetCollections->combineCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
+    m_styleEngine->combineCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
 }
 
 void Document::clearStyleResolver()
@@ -2061,9 +2042,6 @@
     if (render)
         render->destroy();
 
-    if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
-        parentDocument()->didRemoveEventTargetNode(this);
-
     // This is required, as our Frame might delete itself as soon as it detaches
     // us. However, this violates Node::detach() semantics, as it's never
     // possible to re-attach. Eventually Document::detach() should be renamed,
@@ -2831,7 +2809,7 @@
 
 void Document::seamlessParentUpdatedStylesheets()
 {
-    m_styleSheetCollections->didModifySeamlessParentStyleSheet();
+    m_styleEngine->didModifySeamlessParentStyleSheet();
     styleResolverChanged(RecalcStyleImmediately);
 }
 
@@ -2907,8 +2885,8 @@
     // For more info, see the test at:
     // http://www.hixie.ch/tests/evil/css/import/main/preferred.html
     // -dwh
-    m_styleSheetCollections->setSelectedStylesheetSetName(content);
-    m_styleSheetCollections->setPreferredStylesheetSetName(content);
+    m_styleEngine->setSelectedStylesheetSetName(content);
+    m_styleEngine->setPreferredStylesheetSetName(content);
     styleResolverChanged(RecalcStyleDeferred);
 }
 
@@ -3282,17 +3260,17 @@
 
 String Document::preferredStylesheetSet() const
 {
-    return m_styleSheetCollections->preferredStylesheetSetName();
+    return m_styleEngine->preferredStylesheetSetName();
 }
 
 String Document::selectedStylesheetSet() const
 {
-    return m_styleSheetCollections->selectedStylesheetSetName();
+    return m_styleEngine->selectedStylesheetSetName();
 }
 
 void Document::setSelectedStylesheetSet(const String& aString)
 {
-    m_styleSheetCollections->setSelectedStylesheetSetName(aString);
+    m_styleEngine->setSelectedStylesheetSetName(aString);
     styleResolverChanged(RecalcStyleDeferred);
 }
 
@@ -3312,9 +3290,9 @@
     }
     m_didCalculateStyleResolver = true;
 
-    bool needsRecalc = m_styleSheetCollections->updateActiveStyleSheets(updateMode);
+    bool needsRecalc = m_styleEngine->updateActiveStyleSheets(updateMode);
 
-    if (didLayoutWithPendingStylesheets() && !m_styleSheetCollections->hasPendingSheets()) {
+    if (didLayoutWithPendingStylesheets() && !m_styleEngine->hasPendingSheets()) {
         // We need to manually repaint because we avoid doing all repaints in layout or style
         // recalc while sheets are still loading to avoid FOUC.
         m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
@@ -3668,24 +3646,24 @@
     }
 }
 
-void Document::textInserted(Node* text, unsigned offset, unsigned length)
+void Document::didInsertText(Node* text, unsigned offset, unsigned length)
 {
     if (!m_ranges.isEmpty()) {
         HashSet<Range*>::const_iterator end = m_ranges.end();
         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
-            (*it)->textInserted(text, offset, length);
+            (*it)->didInsertText(text, offset, length);
     }
 
     // Update the markers for spelling and grammar checking.
     m_markers->shiftMarkers(text, offset, length);
 }
 
-void Document::textRemoved(Node* text, unsigned offset, unsigned length)
+void Document::didRemoveText(Node* text, unsigned offset, unsigned length)
 {
     if (!m_ranges.isEmpty()) {
         HashSet<Range*>::const_iterator end = m_ranges.end();
         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
-            (*it)->textRemoved(text, offset, length);
+            (*it)->didRemoveText(text, offset, length);
     }
 
     // Update the markers for spelling and grammar checking.
@@ -3693,28 +3671,28 @@
     m_markers->shiftMarkers(text, offset + length, 0 - length);
 }
 
-void Document::textNodesMerged(Text* oldNode, unsigned offset)
+void Document::didMergeTextNodes(Text* oldNode, unsigned offset)
 {
     if (!m_ranges.isEmpty()) {
         NodeWithIndex oldNodeWithIndex(oldNode);
         HashSet<Range*>::const_iterator end = m_ranges.end();
         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
-            (*it)->textNodesMerged(oldNodeWithIndex, offset);
+            (*it)->didMergeTextNodes(oldNodeWithIndex, offset);
     }
 
     // FIXME: This should update markers for spelling and grammar checking.
 }
 
-void Document::textNodeSplit(Text* oldNode)
+void Document::didSplitTextNode(Text* oldNode)
 {
     if (!m_ranges.isEmpty()) {
         HashSet<Range*>::const_iterator end = m_ranges.end();
         for (HashSet<Range*>::const_iterator it = m_ranges.begin(); it != end; ++it)
-            (*it)->textNodeSplit(oldNode);
+            (*it)->didSplitTextNode(oldNode);
     }
 
     if (m_frame)
-        m_frame->selection().textNodeSplit(*oldNode);
+        m_frame->selection().didSplitTextNode(*oldNode);
 
     // FIXME: This should update markers for spelling and grammar checking.
 }
@@ -3783,32 +3761,39 @@
 
 void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
 {
-    if (eventType == eventNames().DOMSubtreeModifiedEvent)
+    if (eventType == eventNames().DOMSubtreeModifiedEvent) {
+        UseCounter::count(this, UseCounter::DOMSubtreeModifiedEvent);
         addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
-    else if (eventType == eventNames().DOMNodeInsertedEvent)
+    } else if (eventType == eventNames().DOMNodeInsertedEvent) {
+        UseCounter::count(this, UseCounter::DOMNodeInsertedEvent);
         addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
-    else if (eventType == eventNames().DOMNodeRemovedEvent)
+    } else if (eventType == eventNames().DOMNodeRemovedEvent) {
+        UseCounter::count(this, UseCounter::DOMNodeRemovedEvent);
         addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
-    else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent)
+    } else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent) {
+        UseCounter::count(this, UseCounter::DOMNodeRemovedFromDocumentEvent);
         addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
-    else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent)
+    } else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent) {
+        UseCounter::count(this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
         addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
-    else if (eventType == eventNames().DOMCharacterDataModifiedEvent)
+    } else if (eventType == eventNames().DOMCharacterDataModifiedEvent) {
+        UseCounter::count(this, UseCounter::DOMCharacterDataModifiedEvent);
         addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
-    else if (eventType == eventNames().overflowchangedEvent)
+    } else if (eventType == eventNames().overflowchangedEvent) {
         addListenerType(OVERFLOWCHANGED_LISTENER);
-    else if (eventType == eventNames().webkitAnimationStartEvent || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == eventNames().animationstartEvent))
+    } else if (eventType == eventNames().webkitAnimationStartEvent || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == eventNames().animationstartEvent)) {
         addListenerType(ANIMATIONSTART_LISTENER);
-    else if (eventType == eventNames().webkitAnimationEndEvent || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == eventNames().animationendEvent))
+    } else if (eventType == eventNames().webkitAnimationEndEvent || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == eventNames().animationendEvent)) {
         addListenerType(ANIMATIONEND_LISTENER);
-    else if (eventType == eventNames().webkitAnimationIterationEvent || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == eventNames().animationiterationEvent))
+    } else if (eventType == eventNames().webkitAnimationIterationEvent || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == eventNames().animationiterationEvent)) {
         addListenerType(ANIMATIONITERATION_LISTENER);
-    else if (eventType == eventNames().webkitTransitionEndEvent || eventType == eventNames().transitionendEvent)
+    } else if (eventType == eventNames().webkitTransitionEndEvent || eventType == eventNames().transitionendEvent) {
         addListenerType(TRANSITIONEND_LISTENER);
-    else if (eventType == eventNames().beforeloadEvent)
+    } else if (eventType == eventNames().beforeloadEvent) {
         addListenerType(BEFORELOAD_LISTENER);
-    else if (eventType == eventNames().scrollEvent)
+    } else if (eventType == eventNames().scrollEvent) {
         addListenerType(SCROLL_LISTENER);
+    }
 }
 
 CSSStyleDeclaration* Document::getOverrideStyle(Element*, const String&)
@@ -5056,58 +5041,9 @@
     return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
 }
 
-void Document::didAddTouchEventHandler(Node* handler)
+PassRefPtr<TouchList> Document::createTouchList(Vector<RefPtr<Touch> >& touches) const
 {
-    if (!m_touchEventTargets.get())
-        m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
-    m_touchEventTargets->add(handler);
-    if (Document* parent = parentDocument()) {
-        parent->didAddTouchEventHandler(this);
-        return;
-    }
-    if (Page* page = this->page()) {
-        if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
-            scrollingCoordinator->touchEventTargetRectsDidChange(this);
-        if (m_touchEventTargets->size() == 1)
-            page->chrome().client().needTouchEvents(true);
-    }
-}
-
-void Document::didRemoveTouchEventHandler(Node* handler)
-{
-    if (!m_touchEventTargets.get())
-        return;
-    ASSERT(m_touchEventTargets->contains(handler));
-    m_touchEventTargets->remove(handler);
-    if (Document* parent = parentDocument()) {
-        parent->didRemoveTouchEventHandler(this);
-        return;
-    }
-
-    Page* page = this->page();
-    if (!page)
-        return;
-    if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
-        scrollingCoordinator->touchEventTargetRectsDidChange(this);
-    if (m_touchEventTargets->size())
-        return;
-    for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
-        if (frame->document() && frame->document()->hasTouchEventHandlers())
-            return;
-    }
-    page->chrome().client().needTouchEvents(false);
-}
-
-void Document::didRemoveEventTargetNode(Node* handler)
-{
-    if (m_touchEventTargets && !m_touchEventTargets->isEmpty()) {
-        if (handler == this)
-            m_touchEventTargets->clear();
-        else
-            m_touchEventTargets->removeAll(handler);
-        if (m_touchEventTargets->isEmpty() && parentDocument())
-            parentDocument()->didRemoveEventTargetNode(this);
-    }
+    return TouchList::create(touches);
 }
 
 void Document::resetLastHandledUserGestureTimestamp()
@@ -5148,13 +5084,6 @@
     return loader;
 }
 
-IntSize Document::viewportSize() const
-{
-    if (!view())
-        return IntSize();
-    return view()->visibleContentRect(ScrollableArea::IncludeScrollbars).size();
-}
-
 IntSize Document::initialViewportSize() const
 {
     if (!view())
@@ -5384,7 +5313,7 @@
 
 bool Document::haveStylesheetsLoaded() const
 {
-    return !m_styleSheetCollections->hasPendingSheets() || m_ignorePendingStylesheets;
+    return !m_styleEngine->hasPendingSheets() || m_ignorePendingStylesheets;
 }
 
 Locale& Document::getCachedLocale(const AtomicString& locale)
@@ -5416,11 +5345,11 @@
     return *m_templateDocument.get();
 }
 
-PassRefPtr<FontLoader> Document::fontloader()
+PassRefPtr<FontFaceSet> Document::fonts()
 {
-    if (!m_fontloader)
-        m_fontloader = FontLoader::create(this);
-    return m_fontloader;
+    if (!m_fonts)
+        m_fonts = FontFaceSet::create(this);
+    return m_fonts;
 }
 
 void Document::didAssociateFormControl(Element* element)
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index 1d0be02..0e46a60 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -49,7 +49,6 @@
 #include "weborigin/ReferrerPolicy.h"
 #include "core/platform/Timer.h"
 #include "core/rendering/HitTestRequest.h"
-#include "wtf/Deque.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
@@ -146,7 +145,7 @@
 class Settings;
 class StyleResolver;
 class StyleSheet;
-class StyleSheetCollections;
+class StyleEngine;
 class StyleSheetContents;
 class StyleSheetList;
 class Text;
@@ -161,7 +160,7 @@
 
 struct AnnotatedRegionValue;
 
-class FontLoader;
+class FontFaceSet;
 
 typedef int ExceptionCode;
 
@@ -192,8 +191,6 @@
 };
 const int numNodeListInvalidationTypes = InvalidateOnAnyAttrChange + 1;
 
-typedef HashCountedSet<Node*> TouchEventTargetSet;
-
 enum DocumentClass {
     DefaultDocumentClass = 0,
     HTMLDocumentClass = 1,
@@ -223,8 +220,6 @@
     using ContainerNode::ref;
     using ContainerNode::deref;
 
-    Element* getElementById(const AtomicString& id) const;
-
     virtual bool canContainRangeEndPoint() const { return true; }
 
     SelectorQueryCache* selectorQueryCache();
@@ -443,7 +438,7 @@
     // This is a DOM function.
     StyleSheetList* styleSheets();
 
-    StyleSheetCollections* styleSheetCollections() { return m_styleSheetCollections.get(); }
+    StyleEngine* styleEngine() { return m_styleEngine.get(); }
 
     bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
     void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
@@ -700,10 +695,10 @@
     void nodeWillBeRemoved(Node*);
     bool canReplaceChild(Node* newChild, Node* oldChild);
 
-    void textInserted(Node*, unsigned offset, unsigned length);
-    void textRemoved(Node*, unsigned offset, unsigned length);
-    void textNodesMerged(Text* oldNode, unsigned offset);
-    void textNodeSplit(Text* oldNode);
+    void didInsertText(Node*, unsigned offset, unsigned length);
+    void didRemoveText(Node*, unsigned offset, unsigned length);
+    void didMergeTextNodes(Text* oldNode, unsigned offset);
+    void didSplitTextNode(Text* oldNode);
 
     void setDOMWindow(DOMWindow* domWindow) { m_domWindow = domWindow; }
     DOMWindow* domWindow() const { return m_domWindow; }
@@ -974,6 +969,7 @@
     bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
 
     PassRefPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const;
+    PassRefPtr<TouchList> createTouchList(Vector<RefPtr<Touch> >&) const;
 
     const DocumentTiming* timing() const { return &m_documentTiming; }
 
@@ -989,21 +985,11 @@
     double lastHandledUserGestureTimestamp() const { return m_lastHandledUserGestureTimestamp; }
     void resetLastHandledUserGestureTimestamp();
 
-    bool hasTouchEventHandlers() const { return (m_touchEventTargets.get()) ? m_touchEventTargets->size() : false; }
-
-    void didAddTouchEventHandler(Node*);
-    void didRemoveTouchEventHandler(Node*);
-
-    void didRemoveEventTargetNode(Node*);
-
-    const TouchEventTargetSet* touchEventTargets() const { return m_touchEventTargets.get(); }
-
     bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
 
     void suspendScheduledTasks(ActiveDOMObject::ReasonForSuspension);
     void resumeScheduledTasks();
 
-    IntSize viewportSize() const;
     IntSize initialViewportSize() const;
 
     Prerenderer* prerenderer() { return m_prerenderer.get(); }
@@ -1063,7 +1049,7 @@
     virtual DOMWindow* executingWindow() OVERRIDE { return domWindow(); }
     virtual void userEventWasHandled() OVERRIDE { resetLastHandledUserGestureTimestamp(); }
 
-    PassRefPtr<FontLoader> fontloader();
+    PassRefPtr<FontFaceSet> fonts();
     DocumentLifecycleNotifier* lifecycleNotifier();
 
     enum HttpRefreshType {
@@ -1231,7 +1217,7 @@
 
     MutationObserverOptions m_mutationObserverTypes;
 
-    OwnPtr<StyleSheetCollections> m_styleSheetCollections;
+    OwnPtr<StyleEngine> m_styleEngine;
     RefPtr<StyleSheetList> m_styleSheetList;
 
     OwnPtr<FormController> m_formController;
@@ -1347,8 +1333,6 @@
     bool m_writeRecursionIsTooDeep;
     unsigned m_writeRecursionDepth;
 
-    OwnPtr<TouchEventTargetSet> m_touchEventTargets;
-
     double m_lastHandledUserGestureTimestamp;
 
     RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
@@ -1385,7 +1369,7 @@
     RefPtr<Document> m_templateDocument;
     Document* m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
 
-    RefPtr<FontLoader> m_fontloader;
+    RefPtr<FontFaceSet> m_fonts;
 
     Timer<Document> m_didAssociateFormControlsTimer;
     HashSet<RefPtr<Element> > m_associatedFormControls;
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index f2fba14..a18606d 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -167,7 +167,7 @@
 
     [EnabledAtRuntime=CSSRegions] WebKitNamedFlowCollection webkitGetNamedFlows();
 
-    [EnabledAtRuntime=FontLoadEvents] readonly attribute FontLoader fontloader;
+    [EnabledAtRuntime=FontLoadEvents] readonly attribute FontFaceSet fonts;
 
     // Event handler DOM attributes
     [NotEnumerable] attribute EventHandler onabort;
@@ -259,7 +259,7 @@
                                                [Default=Undefined] optional long webkitRadiusY,
                                                [Default=Undefined] optional float webkitRotationAngle,
                                                [Default=Undefined] optional float webkitForce);
-    [EnabledAtRuntime=Touch, Custom, RaisesException] TouchList createTouchList();
+    [EnabledAtRuntime=Touch] TouchList createTouchList(Touch... touches);
 
     [DeprecateAs=PrefixedDocumentRegister, EnabledAtRuntime=CustomElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor webkitRegister(DOMString name, optional Dictionary options);
     [EnabledAtRuntime=CustomElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor register(DOMString name, optional Dictionary options);
diff --git a/Source/core/dom/DocumentLifecycleObserver.h b/Source/core/dom/DocumentLifecycleObserver.h
index 27f1a68..6838e68 100644
--- a/Source/core/dom/DocumentLifecycleObserver.h
+++ b/Source/core/dom/DocumentLifecycleObserver.h
@@ -42,6 +42,7 @@
     virtual ~DocumentLifecycleObserver();
     virtual void documentWasDetached() { }
     virtual void documentWasDisposed() { }
+    virtual void documentBeingDestroyed() { }
 };
 
 class DocumentLifecycleNotifier : public ContextLifecycleNotifier {
@@ -50,6 +51,7 @@
 
     void notifyDocumentWasDetached();
     void notifyDocumentWasDisposed();
+    void notifyDocumentBeingDestroyed();
 
     virtual void addObserver(LifecycleObserver*) OVERRIDE;
     virtual void removeObserver(LifecycleObserver*) OVERRIDE;
@@ -80,6 +82,13 @@
         (*i)->documentWasDisposed();
 }
 
+inline void DocumentLifecycleNotifier::notifyDocumentBeingDestroyed()
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDocumentObservers);
+    for (DocumentObserverSet::iterator i = m_documentObservers.begin(); i != m_documentObservers.end(); ++i)
+        (*i)->documentBeingDestroyed();
+}
+
 } // namespace WebCore
 
 #endif // DocumentLifecycleObserver_h
diff --git a/Source/core/dom/DocumentStyleSheetCollection.cpp b/Source/core/dom/DocumentStyleSheetCollection.cpp
index 8055751..c4e18a9 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -34,7 +34,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/ProcessingInstruction.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/html/HTMLStyleElement.h"
@@ -51,7 +51,7 @@
     ASSERT(treeScope.rootNode() == &treeScope.rootNode()->document());
 }
 
-void DocumentStyleSheetCollection::collectStyleSheets(StyleSheetCollections* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
+void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
 {
     if (document()->settings() && !document()->settings()->authorAndUserStylesEnabled())
         return;
@@ -100,7 +100,7 @@
                 if (!sheet)
                     title = nullAtom;
             } else if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag)) {
-                sheet = static_cast<SVGStyleElement*>(n)->sheet();
+                sheet = toSVGStyleElement(n)->sheet();
             } else {
                 sheet = toHTMLStyleElement(n)->sheet();
             }
@@ -143,10 +143,10 @@
     HTMLIFrameElement* seamlessParentIFrame = document->seamlessParentIFrame();
     if (!seamlessParentIFrame)
         return;
-    sheets.append(seamlessParentIFrame->document().styleSheetCollections()->activeAuthorStyleSheets());
+    sheets.append(seamlessParentIFrame->document().styleEngine()->activeAuthorStyleSheets());
 }
 
-bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleSheetCollections* collections, StyleResolverUpdateMode updateMode)
+bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleEngine* collections, StyleResolverUpdateMode updateMode)
 {
     Vector<RefPtr<StyleSheet> > styleSheets;
     Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index 9f035f0..1a039fb 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -35,7 +35,7 @@
 class CSSStyleSheet;
 class StyleSheet;
 class StyleSheetCollection;
-class StyleSheetCollections;
+class StyleEngine;
 class TreeScope;
 
 class DocumentStyleSheetCollection FINAL : public StyleSheetCollection {
@@ -43,10 +43,10 @@
 public:
     explicit DocumentStyleSheetCollection(TreeScope&);
 
-    bool updateActiveStyleSheets(StyleSheetCollections*, StyleResolverUpdateMode);
+    bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
 
 private:
-    void collectStyleSheets(StyleSheetCollections*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
+    void collectStyleSheets(StyleEngine*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
 };
 
 }
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index 02518c5..1b732d9 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -1502,7 +1502,7 @@
 
     // If "rem" units are used anywhere in the document, and if the document element's font size changes, then go ahead and force font updating
     // all the way down the tree. This is simpler than having to maintain a cache of objects (and such font size changes should be rare anyway).
-    if (document().styleSheetCollections()->usesRemUnits() && document().documentElement() == this && oldStyle && newStyle && oldStyle->fontSize() != newStyle->fontSize()) {
+    if (document().styleEngine()->usesRemUnits() && document().documentElement() == this && oldStyle && newStyle && oldStyle->fontSize() != newStyle->fontSize()) {
         // Cached RenderStyles may depend on the re units.
         document().styleResolver()->invalidateMatchedPropertiesCache();
         return Force;
@@ -2464,15 +2464,24 @@
 
 void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
 {
+    if (needsPseudoElement(pseudoId))
+        createPseudoElement(pseudoId);
+}
+
+bool Element::needsPseudoElement(PseudoId pseudoId) const
+{
     if (pseudoId == BACKDROP && !isInTopLayer())
-        return;
-
+        return false;
     if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
-        return;
-
+        return false;
     if (!renderer()->canHaveGeneratedChildren())
-        return;
+        return false;
+    return true;
+}
 
+void Element::createPseudoElement(PseudoId pseudoId)
+{
+    ASSERT(needsPseudoElement(pseudoId));
     ASSERT(!isPseudoElement());
     RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
     if (pseudoId == BACKDROP)
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index 25c434b..a1bf613 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -703,7 +703,10 @@
     void rebuildPresentationAttributeStyle();
 
     void updatePseudoElement(PseudoId, StyleRecalcChange);
-    void createPseudoElementIfNeeded(PseudoId);
+
+    inline void createPseudoElementIfNeeded(PseudoId);
+    inline bool needsPseudoElement(PseudoId) const;
+    void createPseudoElement(PseudoId);
 
     // FIXME: Everyone should allow author shadows.
     virtual bool areAuthorShadowsAllowed() const { return true; }
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index 3de2173..55df834 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -124,10 +124,10 @@
 
     // Mozilla version
     const unsigned short ALLOW_KEYBOARD_INPUT = 1;
-    [EnabledAtRuntime=Fullscreen] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
+    [EnabledAtRuntime=Fullscreen, PerWorldBindings, ActivityLog=Access] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
 
     // W3C version
-    [EnabledAtRuntime=Fullscreen] void webkitRequestFullscreen();
+    [EnabledAtRuntime=Fullscreen, PerWorldBindings, ActivityLog=Access] void webkitRequestFullscreen();
 
     void webkitRequestPointerLock();
 
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index 7371c7a..f483681 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -30,6 +30,7 @@
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/html/ClassList.h"
 #include "core/html/ime/InputMethodContext.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "core/rendering/style/StyleInheritedData.h"
 #include "wtf/OwnPtr.h"
 
@@ -227,8 +228,9 @@
     ASSERT(!m_backdrop);
 }
 
-inline void ElementRareData::setPseudoElement(PseudoId pseudoId, PassRefPtr<PseudoElement> element)
+inline void ElementRareData::setPseudoElement(PseudoId pseudoId, PassRefPtr<PseudoElement> prpElement)
 {
+    RefPtr<PseudoElement> element = prpElement;
     switch (pseudoId) {
     case BEFORE:
         releasePseudoElement(m_generatedBefore.get());
@@ -245,6 +247,7 @@
     default:
         ASSERT_NOT_REACHED();
     }
+    InspectorInstrumentation::pseudoElementCreated(element.get());
 }
 
 inline PseudoElement* ElementRareData::pseudoElement(PseudoId pseudoId) const
@@ -266,6 +269,8 @@
     if (!element)
         return;
 
+    InspectorInstrumentation::pseudoElementDestroyed(element);
+
     if (element->attached())
         element->detach();
 
diff --git a/Source/core/dom/Entity.h b/Source/core/dom/Entity.h
index 31e042a..ee46c2c 100644
--- a/Source/core/dom/Entity.h
+++ b/Source/core/dom/Entity.h
@@ -26,13 +26,7 @@
 
 namespace WebCore {
 
-// FIXME: This abstract class is only here so that the JavaScript and bindings can continue to be compiled.
 class Entity : public ContainerNode {
-public:
-    String publicId() const { ASSERT_NOT_REACHED(); return String(); }
-    String systemId() const { ASSERT_NOT_REACHED(); return String(); }
-    String notationName() const { ASSERT_NOT_REACHED(); return String(); }
-
 private:
     Entity() : ContainerNode(0)
     {
diff --git a/Source/core/dom/Entity.idl b/Source/core/dom/Entity.idl
index 12b9234..151572f 100644
--- a/Source/core/dom/Entity.idl
+++ b/Source/core/dom/Entity.idl
@@ -16,10 +16,10 @@
  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  * Boston, MA 02110-1301, USA.
  */
-[
-] interface Entity : Node {
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString publicId;
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString systemId;
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString notationName;
+
+// FIXME: Remove Entity interface. We never create Entity objects. We have this
+// interface to provide window.Entity.
+interface Entity : Node {
+    // We don't need to provide any attributes.
 };
 
diff --git a/Source/core/dom/EventNames.h b/Source/core/dom/EventNames.h
index 1633336..225727d 100644
--- a/Source/core/dom/EventNames.h
+++ b/Source/core/dom/EventNames.h
@@ -89,6 +89,7 @@
     macro(load) \
     macro(loading) \
     macro(loadingdone) \
+    macro(loadingerror) \
     macro(loadstart) \
     macro(message) \
     macro(midimessage) \
diff --git a/Source/core/dom/EventTargetFactory.in b/Source/core/dom/EventTargetFactory.in
index 5227c79..9ead7d2 100644
--- a/Source/core/dom/EventTargetFactory.in
+++ b/Source/core/dom/EventTargetFactory.in
@@ -1,6 +1,6 @@
 namespace="EventTarget"
 
-core/css/FontLoader
+core/css/FontFaceSet
 core/dom/MessagePort
 core/dom/Node
 core/dom/WebKitNamedFlow ImplementedAs=NamedFlow
diff --git a/Source/core/dom/KeyboardEvent.cpp b/Source/core/dom/KeyboardEvent.cpp
index 4dc27d7..b20d77a 100644
--- a/Source/core/dom/KeyboardEvent.cpp
+++ b/Source/core/dom/KeyboardEvent.cpp
@@ -70,7 +70,6 @@
     if (key.isKeypad())
         return KeyboardEvent::DOM_KEY_LOCATION_NUMPAD;
 
-    // FIXME: Support DOM_KEY_LOCATION_MOBILE & DOM_KEY_LOCATION_JOYSTICK (crbug.com/265446).
     switch (key.windowsVirtualKeyCode()) {
     case VK_LCONTROL:
     case VK_LSHIFT:
diff --git a/Source/core/dom/KeyboardEvent.h b/Source/core/dom/KeyboardEvent.h
index 274e2c7..3cbeb06 100644
--- a/Source/core/dom/KeyboardEvent.h
+++ b/Source/core/dom/KeyboardEvent.h
@@ -51,9 +51,6 @@
         DOM_KEY_LOCATION_LEFT       = 0x01,
         DOM_KEY_LOCATION_RIGHT      = 0x02,
         DOM_KEY_LOCATION_NUMPAD     = 0x03
-        // FIXME: The following values are not supported yet (crbug.com/265446)
-        // DOM_KEY_LOCATION_MOBILE     = 0x04,
-        // DOM_KEY_LOCATION_JOYSTICK   = 0x05
     };
 
     static PassRefPtr<KeyboardEvent> create()
diff --git a/Source/core/dom/KeyboardEvent.idl b/Source/core/dom/KeyboardEvent.idl
index 81b2c17..62dd799 100644
--- a/Source/core/dom/KeyboardEvent.idl
+++ b/Source/core/dom/KeyboardEvent.idl
@@ -25,10 +25,6 @@
     const unsigned long DOM_KEY_LOCATION_LEFT     = 0x01;
     const unsigned long DOM_KEY_LOCATION_RIGHT    = 0x02;
     const unsigned long DOM_KEY_LOCATION_NUMPAD   = 0x03;
-    // FIXME: The following constants are defined in the specification but
-    // not yet supported (crbug.com/265446).
-    // const unsigned long DOM_KEY_LOCATION_MOBILE   = 0x04;
-    // const unsigned long DOM_KEY_LOCATION_JOYSTICK = 0x05;
 
     [InitializedByEventConstructor] readonly attribute DOMString        keyIdentifier;
     [InitializedByEventConstructor] readonly attribute unsigned long    location;
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 0e3d2cb..f6a2d3e 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -27,6 +27,7 @@
 
 #include "HTMLNames.h"
 #include "XMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/accessibility/AXObjectCache.h"
@@ -62,6 +63,7 @@
 #include "core/dom/TemplateContentDocumentFragment.h"
 #include "core/dom/Text.h"
 #include "core/dom/TextEvent.h"
+#include "core/dom/TouchController.h"
 #include "core/dom/TouchEvent.h"
 #include "core/dom/TreeScopeAdopter.h"
 #include "core/dom/UIEvent.h"
@@ -310,7 +312,7 @@
 {
     if (hasEventTargetData()) {
         if (document)
-            document->didRemoveEventTargetNode(this);
+            TouchController::from(document)->didRemoveEventTargetNode(document, this);
         clearEventTargetData();
     }
 
@@ -538,7 +540,7 @@
             // Both non-empty text nodes. Merge them.
             unsigned offset = text->length();
             text->appendData(nextText->data());
-            document().textNodesMerged(nextText.get(), offset);
+            document().didMergeTextNodes(nextText.get(), offset);
             nextText->remove(IGNORE_EXCEPTION);
         }
 
@@ -897,9 +899,13 @@
     // FIXME: Raise NamespaceError if prefix is malformed per the Namespaces in XML specification.
 
     const AtomicString& nodeNamespaceURI = namespaceURI();
-    if ((nodeNamespaceURI.isEmpty() && !prefix.isEmpty())
-        || (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI)) {
-        es.throwDOMException(NamespaceError);
+    if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
+        es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "No namespace is set, so a namespace prefix may not be set."));
+        return;
+    }
+
+    if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
+        es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'."));
         return;
     }
     // Attribute-specific checks are in Attr::setPrefix().
@@ -2065,23 +2071,25 @@
             cache->remove(this);
 
     const EventListenerVector& mousewheelListeners = getEventListeners(eventNames().mousewheelEvent);
-    WheelController* oldController = WheelController::from(oldDocument);
-    WheelController* newController = WheelController::from(&document());
+    WheelController* oldWheelController = WheelController::from(oldDocument);
+    WheelController* newWheelController = WheelController::from(&document());
     for (size_t i = 0; i < mousewheelListeners.size(); ++i) {
-        oldController->didRemoveWheelEventHandler(oldDocument);
-        newController->didAddWheelEventHandler(&document());
+        oldWheelController->didRemoveWheelEventHandler(oldDocument);
+        newWheelController->didAddWheelEventHandler(&document());
     }
 
     const EventListenerVector& wheelListeners = getEventListeners(eventNames().wheelEvent);
     for (size_t i = 0; i < wheelListeners.size(); ++i) {
-        oldController->didRemoveWheelEventHandler(oldDocument);
-        newController->didAddWheelEventHandler(&document());
+        oldWheelController->didRemoveWheelEventHandler(oldDocument);
+        newWheelController->didAddWheelEventHandler(&document());
     }
 
-    if (const TouchEventTargetSet* touchHandlers = oldDocument ? oldDocument->touchEventTargets() : 0) {
+    TouchController* oldTouchController = TouchController::from(oldDocument);
+    if (const TouchEventTargetSet* touchHandlers = oldDocument ? oldTouchController->touchEventTargets() : 0) {
+        TouchController* newTouchController = TouchController::from(&document());
         while (touchHandlers->contains(this)) {
-            oldDocument->didRemoveTouchEventHandler(this);
-            document().didAddTouchEventHandler(this);
+            oldTouchController->didRemoveTouchEventHandler(oldDocument, this);
+            newTouchController->didAddTouchEventHandler(&document(), this);
         }
     }
 
@@ -2108,7 +2116,7 @@
     if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
         WheelController::from(&document)->didAddWheelEventHandler(&document);
     else if (eventNames().isTouchEventType(eventType))
-        document.didAddTouchEventHandler(targetNode);
+        TouchController::from(&document)->didAddTouchEventHandler(&document, targetNode);
 
     return true;
 }
@@ -2129,7 +2137,7 @@
     if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
         WheelController::from(&document)->didAddWheelEventHandler(&document);
     else if (eventNames().isTouchEventType(eventType))
-        document.didRemoveTouchEventHandler(targetNode);
+        TouchController::from(&document)->didRemoveTouchEventHandler(&document, targetNode);
 
     return true;
 }
diff --git a/Source/core/dom/NodeRenderingContext.cpp b/Source/core/dom/NodeRenderingContext.cpp
index da6f56f..236ac4f 100644
--- a/Source/core/dom/NodeRenderingContext.cpp
+++ b/Source/core/dom/NodeRenderingContext.cpp
@@ -43,15 +43,6 @@
 
 namespace WebCore {
 
-NodeRenderingContext::NodeRenderingContext(Node* node, RenderStyle* style)
-    : m_node(node)
-    , m_renderingParent(0)
-    , m_style(style)
-    , m_parentFlowRenderer(0)
-{
-    m_renderingParent = NodeRenderingTraversal::parent(node, &m_parentDetails);
-}
-
 static bool isRendererReparented(const RenderObject* renderer)
 {
     if (!renderer->node()->isElementNode())
diff --git a/Source/core/dom/NodeRenderingContext.h b/Source/core/dom/NodeRenderingContext.h
index c31bb1f..ac2bab3 100644
--- a/Source/core/dom/NodeRenderingContext.h
+++ b/Source/core/dom/NodeRenderingContext.h
@@ -40,7 +40,14 @@
 
 class NodeRenderingContext {
 public:
-    NodeRenderingContext(Node*, RenderStyle* = 0);
+    explicit NodeRenderingContext(Node* node, RenderStyle* style = 0)
+        : m_node(node)
+        , m_renderingParent(0)
+        , m_style(style)
+        , m_parentFlowRenderer(0)
+    {
+        m_renderingParent = NodeRenderingTraversal::parent(node, &m_parentDetails);
+    }
 
     void createRendererForTextIfNeeded();
     void createRendererForElementIfNeeded();
diff --git a/Source/core/dom/Notation.cpp b/Source/core/dom/Notation.cpp
deleted file mode 100644
index e635eab..0000000
--- a/Source/core/dom/Notation.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2000 Peter Kelly (pmk@post.com)
- * Copyright (C) 2006, 2009 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/Notation.h"
-
-namespace WebCore {
-
-Notation::Notation(TreeScope* treeScope, const String& name, const String& publicId, const String& systemId)
-    : ContainerNode(treeScope)
-    , m_name(name)
-    , m_publicId(publicId)
-    , m_systemId(systemId)
-{
-    ASSERT_NOT_REACHED();
-    ScriptWrappable::init(this);
-}
-
-String Notation::nodeName() const
-{
-    return m_name;
-}
-
-Node::NodeType Notation::nodeType() const
-{
-    return NOTATION_NODE;
-}
-
-PassRefPtr<Node> Notation::cloneNode(bool /*deep*/)
-{
-    // Spec says cloning Notation nodes is "implementation dependent". We do not support it.
-    return 0;
-}
-
-bool Notation::childTypeAllowed(NodeType) const
-{
-    return false;
-}
-
-} // namespace
diff --git a/Source/core/dom/Notation.h b/Source/core/dom/Notation.h
index 0d59e02..30401f2 100644
--- a/Source/core/dom/Notation.h
+++ b/Source/core/dom/Notation.h
@@ -26,26 +26,15 @@
 
 namespace WebCore {
 
-// FIXME: This class is never instantiated. Maybe it should be removed.
-
-class Notation FINAL : public ContainerNode {
-public:
-    const String& publicId() const { return m_publicId; }
-    const String& systemId() const { return m_systemId; }
-
+class Notation : public ContainerNode {
 private:
-    Notation(TreeScope*, const String& name, const String& publicId, const String& systemId);
-
-    virtual String nodeName() const;
-    virtual NodeType nodeType() const;
-    virtual PassRefPtr<Node> cloneNode(bool deep = true);
-    virtual bool childTypeAllowed(NodeType) const;
-
-    String m_name;
-    String m_publicId;
-    String m_systemId;
+    Notation(TreeScope* treeScope) : ContainerNode(treeScope)
+    {
+        ASSERT_NOT_REACHED();
+        ScriptWrappable::init(this);
+    }
 };
 
-} //namespace
+} // namespace WebCore
 
 #endif
diff --git a/Source/core/dom/Notation.idl b/Source/core/dom/Notation.idl
index 4ac628f..5ad13ec 100644
--- a/Source/core/dom/Notation.idl
+++ b/Source/core/dom/Notation.idl
@@ -17,8 +17,9 @@
  * Boston, MA 02110-1301, USA.
  */
 
+// FIXME: Remove Notation interface. We never create Notation objects. We have
+// this interface to provide window.Notation.
 interface Notation : Node {
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString publicId;
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString systemId;
+    // We don't need to provide any attributes.
 };
 
diff --git a/Source/core/dom/ProcessingInstruction.cpp b/Source/core/dom/ProcessingInstruction.cpp
index 94ee37e..be736e8 100644
--- a/Source/core/dom/ProcessingInstruction.cpp
+++ b/Source/core/dom/ProcessingInstruction.cpp
@@ -26,7 +26,7 @@
 #include "core/css/MediaList.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/fetch/CSSStyleSheetResource.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ResourceFetcher.h"
@@ -63,7 +63,7 @@
         m_resource->removeClient(this);
 
     if (inDocument())
-        document().styleSheetCollections()->removeStyleSheetCandidateNode(this);
+        document().styleEngine()->removeStyleSheetCandidateNode(this);
 }
 
 String ProcessingInstruction::nodeName() const
@@ -133,7 +133,7 @@
                 return;
 
             m_loading = true;
-            document().styleSheetCollections()->addPendingSheet();
+            document().styleEngine()->addPendingSheet();
             FetchRequest request(ResourceRequest(document().completeURL(href)), FetchInitiatorTypeNames::processinginstruction);
             if (m_isXSL)
                 m_resource = document().fetcher()->fetchXSLStyleSheet(request);
@@ -151,7 +151,7 @@
             else {
                 // The request may have been denied if (for example) the stylesheet is local and the document is remote.
                 m_loading = false;
-                document().styleSheetCollections()->removePendingSheet(this);
+                document().styleEngine()->removePendingSheet(this);
             }
         }
     }
@@ -169,7 +169,7 @@
 bool ProcessingInstruction::sheetLoaded()
 {
     if (!isLoading()) {
-        document().styleSheetCollections()->removePendingSheet(this);
+        document().styleEngine()->removePendingSheet(this);
         return true;
     }
     return false;
@@ -248,7 +248,7 @@
     CharacterData::insertedInto(insertionPoint);
     if (!insertionPoint->inDocument())
         return InsertionDone;
-    document().styleSheetCollections()->addStyleSheetCandidateNode(this, m_createdByParser);
+    document().styleEngine()->addStyleSheetCandidateNode(this, m_createdByParser);
     checkStyleSheet();
     return InsertionDone;
 }
@@ -259,7 +259,7 @@
     if (!insertionPoint->inDocument())
         return;
 
-    document().styleSheetCollections()->removeStyleSheetCandidateNode(this);
+    document().styleEngine()->removeStyleSheetCandidateNode(this);
 
     RefPtr<StyleSheet> removedSheet = m_sheet;
 
diff --git a/Source/core/dom/Range.cpp b/Source/core/dom/Range.cpp
index 7767ffd..a6a6d7d 100644
--- a/Source/core/dom/Range.cpp
+++ b/Source/core/dom/Range.cpp
@@ -1726,7 +1726,7 @@
     boundary.setOffset(boundaryOffset + length);
 }
 
-void Range::textInserted(Node* text, unsigned offset, unsigned length)
+void Range::didInsertText(Node* text, unsigned offset, unsigned length)
 {
     ASSERT(text);
     ASSERT(&text->document() == m_ownerDocument);
@@ -1747,7 +1747,7 @@
         boundary.setOffset(boundaryOffset - length);
 }
 
-void Range::textRemoved(Node* text, unsigned offset, unsigned length)
+void Range::didRemoveText(Node* text, unsigned offset, unsigned length)
 {
     ASSERT(text);
     ASSERT(&text->document() == m_ownerDocument);
@@ -1763,7 +1763,7 @@
         boundary.set(oldNode.node()->previousSibling(), offset, 0);
 }
 
-void Range::textNodesMerged(NodeWithIndex& oldNode, unsigned offset)
+void Range::didMergeTextNodes(NodeWithIndex& oldNode, unsigned offset)
 {
     ASSERT(oldNode.node());
     ASSERT(&oldNode.node()->document() == m_ownerDocument);
@@ -1775,7 +1775,7 @@
     boundaryTextNodesMerged(m_end, oldNode, offset);
 }
 
-static inline void boundaryTextNodesSplit(RangeBoundaryPoint& boundary, Text* oldNode)
+static inline void boundaryTextNodeSplit(RangeBoundaryPoint& boundary, Text* oldNode)
 {
     if (boundary.container() != oldNode)
         return;
@@ -1785,7 +1785,7 @@
     boundary.set(oldNode->nextSibling(), boundaryOffset - oldNode->length(), 0);
 }
 
-void Range::textNodeSplit(Text* oldNode)
+void Range::didSplitTextNode(Text* oldNode)
 {
     ASSERT(oldNode);
     ASSERT(&oldNode->document() == m_ownerDocument);
@@ -1793,8 +1793,8 @@
     ASSERT(oldNode->isTextNode());
     ASSERT(oldNode->nextSibling());
     ASSERT(oldNode->nextSibling()->isTextNode());
-    boundaryTextNodesSplit(m_start, oldNode);
-    boundaryTextNodesSplit(m_end, oldNode);
+    boundaryTextNodeSplit(m_start, oldNode);
+    boundaryTextNodeSplit(m_end, oldNode);
 }
 
 void Range::expand(const String& unit, ExceptionState& es)
diff --git a/Source/core/dom/Range.h b/Source/core/dom/Range.h
index 736b7a8..8850144 100644
--- a/Source/core/dom/Range.h
+++ b/Source/core/dom/Range.h
@@ -132,10 +132,10 @@
     void nodeChildrenWillBeRemoved(ContainerNode*);
     void nodeWillBeRemoved(Node*);
 
-    void textInserted(Node*, unsigned offset, unsigned length);
-    void textRemoved(Node*, unsigned offset, unsigned length);
-    void textNodesMerged(NodeWithIndex& oldNode, unsigned offset);
-    void textNodeSplit(Text* oldNode);
+    void didInsertText(Node*, unsigned offset, unsigned length);
+    void didRemoveText(Node*, unsigned offset, unsigned length);
+    void didMergeTextNodes(NodeWithIndex& oldNode, unsigned offset);
+    void didSplitTextNode(Text* oldNode);
 
     // Expand range to a unit (word or sentence or block or document) boundary.
     // Please refer to https://bugs.webkit.org/show_bug.cgi?id=27632 comment #5
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
index a0d7c84..a952d05 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
@@ -32,7 +32,7 @@
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLStyleElement.h"
 #include "core/page/Settings.h"
@@ -46,7 +46,7 @@
 {
 }
 
-void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleSheetCollections* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
+void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleEngine* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
 {
     if (document()->settings() && !document()->settings()->authorAndUserStylesEnabled())
         return;
@@ -94,7 +94,7 @@
     }
 }
 
-bool ShadowTreeStyleSheetCollection::updateActiveStyleSheets(StyleSheetCollections* collections, StyleResolverUpdateMode updateMode)
+bool ShadowTreeStyleSheetCollection::updateActiveStyleSheets(StyleEngine* collections, StyleResolverUpdateMode updateMode)
 {
     Vector<RefPtr<StyleSheet> > styleSheets;
     Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.h b/Source/core/dom/ShadowTreeStyleSheetCollection.h
index a849d68..253ad63 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.h
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.h
@@ -36,17 +36,17 @@
 class ShadowRoot;
 class StyleSheet;
 class StyleSheetCollection;
-class StyleSheetCollections;
+class StyleEngine;
 
 class ShadowTreeStyleSheetCollection FINAL : public StyleSheetCollection {
     WTF_MAKE_NONCOPYABLE(ShadowTreeStyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
 public:
     explicit ShadowTreeStyleSheetCollection(ShadowRoot&);
 
-    bool updateActiveStyleSheets(StyleSheetCollections*, StyleResolverUpdateMode);
+    bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
 
 private:
-    void collectStyleSheets(StyleSheetCollections*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
+    void collectStyleSheets(StyleEngine*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
 };
 
 }
diff --git a/Source/core/dom/StyleElement.cpp b/Source/core/dom/StyleElement.cpp
index 8f8a151..cd1d2f4 100644
--- a/Source/core/dom/StyleElement.cpp
+++ b/Source/core/dom/StyleElement.cpp
@@ -27,7 +27,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/ScriptableDocumentParser.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/html/HTMLStyleElement.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "wtf/text/StringBuilder.h"
@@ -58,7 +58,7 @@
 void StyleElement::processStyleSheet(Document& document, Element* element)
 {
     ASSERT(element);
-    document.styleSheetCollections()->addStyleSheetCandidateNode(element, m_createdByParser);
+    document.styleEngine()->addStyleSheetCandidateNode(element, m_createdByParser);
     if (m_createdByParser)
         return;
 
@@ -68,7 +68,7 @@
 void StyleElement::removedFromDocument(Document& document, Element* element, ContainerNode* scopingNode)
 {
     ASSERT(element);
-    document.styleSheetCollections()->removeStyleSheetCandidateNode(element, scopingNode);
+    document.styleEngine()->removeStyleSheetCandidateNode(element, scopingNode);
 
     RefPtr<StyleSheet> removedSheet = m_sheet;
 
@@ -86,7 +86,7 @@
         m_sheet->clearOwnerNode();
 
     if (element->inDocument())
-        document.styleSheetCollections()->removeStyleSheetCandidateNode(element, isHTMLStyleElement(element) ? toHTMLStyleElement(element)->scopingNode() :  0);
+        document.styleEngine()->removeStyleSheetCandidateNode(element, isHTMLStyleElement(element) ? toHTMLStyleElement(element)->scopingNode() :  0);
 }
 
 void StyleElement::childrenChanged(Element* element)
@@ -125,7 +125,7 @@
     Document& document = e->document();
     if (m_sheet) {
         if (m_sheet->isLoading())
-            document.styleSheetCollections()->removePendingSheet(e);
+            document.styleEngine()->removePendingSheet(e);
         clearSheet();
     }
 
@@ -137,7 +137,7 @@
         MediaQueryEvaluator screenEval("screen", true);
         MediaQueryEvaluator printEval("print", true);
         if (screenEval.eval(mediaQueries.get()) || printEval.eval(mediaQueries.get())) {
-            document.styleSheetCollections()->addPendingSheet();
+            document.styleEngine()->addPendingSheet();
             m_loading = true;
 
             TextPosition startPosition = m_startPosition == TextPosition::belowRangePosition() ? TextPosition::minimumPosition() : m_startPosition;
@@ -166,13 +166,13 @@
     if (isLoading())
         return false;
 
-    document.styleSheetCollections()->removePendingSheet(m_sheet->ownerNode());
+    document.styleEngine()->removePendingSheet(m_sheet->ownerNode());
     return true;
 }
 
 void StyleElement::startLoadingDynamicSheet(Document& document)
 {
-    document.styleSheetCollections()->addPendingSheet();
+    document.styleEngine()->addPendingSheet();
 }
 
 }
diff --git a/Source/core/dom/StyleSheetCollections.cpp b/Source/core/dom/StyleEngine.cpp
similarity index 86%
rename from Source/core/dom/StyleSheetCollections.cpp
rename to Source/core/dom/StyleEngine.cpp
index 665c240..94a218b 100644
--- a/Source/core/dom/StyleSheetCollections.cpp
+++ b/Source/core/dom/StyleEngine.cpp
@@ -26,7 +26,7 @@
  */
 
 #include "config.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 
 #include "HTMLNames.h"
 #include "SVGNames.h"
@@ -52,7 +52,7 @@
 
 using namespace HTMLNames;
 
-StyleSheetCollections::StyleSheetCollections(Document& document)
+StyleEngine::StyleEngine(Document& document)
     : m_document(document)
     , m_pendingStylesheets(0)
     , m_injectedStyleSheetCacheValid(false)
@@ -67,7 +67,7 @@
 {
 }
 
-StyleSheetCollections::~StyleSheetCollections()
+StyleEngine::~StyleEngine()
 {
     if (m_pageUserSheet)
         m_pageUserSheet->clearOwnerNode();
@@ -81,7 +81,7 @@
         m_authorStyleSheets[i]->clearOwnerNode();
 }
 
-void StyleSheetCollections::insertTreeScopeInDocumentOrder(TreeScopeSet& treeScopes, TreeScope* treeScope)
+void StyleEngine::insertTreeScopeInDocumentOrder(TreeScopeSet& treeScopes, TreeScope* treeScope)
 {
     if (treeScopes.isEmpty()) {
         treeScopes.add(treeScope);
@@ -108,7 +108,7 @@
     treeScopes.insertBefore(followingTreeScope, treeScope);
 }
 
-StyleSheetCollection* StyleSheetCollections::ensureStyleSheetCollectionFor(TreeScope& treeScope)
+StyleSheetCollection* StyleEngine::ensureStyleSheetCollectionFor(TreeScope& treeScope)
 {
     if (&treeScope == &m_document)
         return &m_documentStyleSheetCollection;
@@ -119,7 +119,7 @@
     return result.iterator->value.get();
 }
 
-StyleSheetCollection* StyleSheetCollections::styleSheetCollectionFor(TreeScope& treeScope)
+StyleSheetCollection* StyleEngine::styleSheetCollectionFor(TreeScope& treeScope)
 {
     if (&treeScope == &m_document)
         return &m_documentStyleSheetCollection;
@@ -130,17 +130,17 @@
     return it->value.get();
 }
 
-const Vector<RefPtr<StyleSheet> >& StyleSheetCollections::styleSheetsForStyleSheetList()
+const Vector<RefPtr<StyleSheet> >& StyleEngine::styleSheetsForStyleSheetList()
 {
     return m_documentStyleSheetCollection.styleSheetsForStyleSheetList();
 }
 
-const Vector<RefPtr<CSSStyleSheet> >& StyleSheetCollections::activeAuthorStyleSheets() const
+const Vector<RefPtr<CSSStyleSheet> >& StyleEngine::activeAuthorStyleSheets() const
 {
     return m_documentStyleSheetCollection.activeAuthorStyleSheets();
 }
 
-void StyleSheetCollections::getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const
+void StyleEngine::getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const
 {
     activeAuthorStyleSheets.append(&m_documentStyleSheetCollection.activeAuthorStyleSheets());
 
@@ -153,20 +153,20 @@
     }
 }
 
-void StyleSheetCollections::combineCSSFeatureFlags(const RuleFeatureSet& features)
+void StyleEngine::combineCSSFeatureFlags(const RuleFeatureSet& features)
 {
     // Delay resetting the flags until after next style recalc since unapplying the style may not work without these set (this is true at least with before/after).
     m_usesSiblingRules = m_usesSiblingRules || features.usesSiblingRules();
     m_usesFirstLineRules = m_usesFirstLineRules || features.usesFirstLineRules();
 }
 
-void StyleSheetCollections::resetCSSFeatureFlags(const RuleFeatureSet& features)
+void StyleEngine::resetCSSFeatureFlags(const RuleFeatureSet& features)
 {
     m_usesSiblingRules = features.usesSiblingRules();
     m_usesFirstLineRules = features.usesFirstLineRules();
 }
 
-CSSStyleSheet* StyleSheetCollections::pageUserSheet()
+CSSStyleSheet* StyleEngine::pageUserSheet()
 {
     if (m_pageUserSheet)
         return m_pageUserSheet.get();
@@ -186,7 +186,7 @@
     return m_pageUserSheet.get();
 }
 
-void StyleSheetCollections::clearPageUserSheet()
+void StyleEngine::clearPageUserSheet()
 {
     if (m_pageUserSheet) {
         RefPtr<StyleSheet> removedSheet = m_pageUserSheet;
@@ -195,7 +195,7 @@
     }
 }
 
-void StyleSheetCollections::updatePageUserSheet()
+void StyleEngine::updatePageUserSheet()
 {
     clearPageUserSheet();
     // FIXME: Why is this immediately and not defer?
@@ -203,19 +203,19 @@
         m_document.addedStyleSheet(addedSheet, RecalcStyleImmediately);
 }
 
-const Vector<RefPtr<CSSStyleSheet> >& StyleSheetCollections::injectedUserStyleSheets() const
+const Vector<RefPtr<CSSStyleSheet> >& StyleEngine::injectedUserStyleSheets() const
 {
     updateInjectedStyleSheetCache();
     return m_injectedUserStyleSheets;
 }
 
-const Vector<RefPtr<CSSStyleSheet> >& StyleSheetCollections::injectedAuthorStyleSheets() const
+const Vector<RefPtr<CSSStyleSheet> >& StyleEngine::injectedAuthorStyleSheets() const
 {
     updateInjectedStyleSheetCache();
     return m_injectedAuthorStyleSheets;
 }
 
-void StyleSheetCollections::updateInjectedStyleSheetCache() const
+void StyleEngine::updateInjectedStyleSheetCache() const
 {
     if (m_injectedStyleSheetCacheValid)
         return;
@@ -246,7 +246,7 @@
     }
 }
 
-void StyleSheetCollections::invalidateInjectedStyleSheetCache()
+void StyleEngine::invalidateInjectedStyleSheetCache()
 {
     m_injectedStyleSheetCacheValid = false;
     m_needsDocumentStyleSheetsUpdate = true;
@@ -255,7 +255,7 @@
     m_document.styleResolverChanged(RecalcStyleDeferred);
 }
 
-void StyleSheetCollections::addAuthorSheet(PassRefPtr<StyleSheetContents> authorSheet)
+void StyleEngine::addAuthorSheet(PassRefPtr<StyleSheetContents> authorSheet)
 {
     ASSERT(!authorSheet->isUserStyleSheet());
     m_authorStyleSheets.append(CSSStyleSheet::create(authorSheet, &m_document));
@@ -263,7 +263,7 @@
     m_needsDocumentStyleSheetsUpdate = true;
 }
 
-void StyleSheetCollections::addUserSheet(PassRefPtr<StyleSheetContents> userSheet)
+void StyleEngine::addUserSheet(PassRefPtr<StyleSheetContents> userSheet)
 {
     ASSERT(userSheet->isUserStyleSheet());
     m_userStyleSheets.append(CSSStyleSheet::create(userSheet, &m_document));
@@ -272,7 +272,7 @@
 }
 
 // This method is called whenever a top-level stylesheet has finished loading.
-void StyleSheetCollections::removePendingSheet(Node* styleSheetCandidateNode, RemovePendingSheetNotificationType notification)
+void StyleEngine::removePendingSheet(Node* styleSheetCandidateNode, RemovePendingSheetNotificationType notification)
 {
     // Make sure we knew this sheet was pending, and that our count isn't out of sync.
     ASSERT(m_pendingStylesheets > 0);
@@ -298,7 +298,7 @@
     m_document.didRemoveAllPendingStylesheet();
 }
 
-void StyleSheetCollections::addStyleSheetCandidateNode(Node* node, bool createdByParser)
+void StyleEngine::addStyleSheetCandidateNode(Node* node, bool createdByParser)
 {
     if (!node->inDocument())
         return;
@@ -319,7 +319,7 @@
     m_dirtyTreeScopes.add(&treeScope);
 }
 
-void StyleSheetCollections::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
+void StyleEngine::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
 {
     TreeScope& treeScope = scopingNode ? scopingNode->treeScope() : m_document;
     ASSERT(isHTMLStyleElement(node) || &treeScope == &m_document);
@@ -336,7 +336,7 @@
     m_activeTreeScopes.remove(&treeScope);
 }
 
-void StyleSheetCollections::modifiedStyleSheetCandidateNode(Node* node)
+void StyleEngine::modifiedStyleSheetCandidateNode(Node* node)
 {
     if (!node->inDocument())
         return;
@@ -350,12 +350,12 @@
     m_dirtyTreeScopes.add(&treeScope);
 }
 
-bool StyleSheetCollections::shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode updateMode)
+bool StyleEngine::shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode updateMode)
 {
     return !m_dirtyTreeScopes.isEmpty() || updateMode == FullStyleUpdate;
 }
 
-bool StyleSheetCollections::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
+bool StyleEngine::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
 {
     if (m_document.inStyleRecalc()) {
         // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
@@ -408,7 +408,7 @@
     return requiresFullStyleRecalc;
 }
 
-void StyleSheetCollections::activeStyleSheetsUpdatedForInspector()
+void StyleEngine::activeStyleSheetsUpdatedForInspector()
 {
     if (m_activeTreeScopes.isEmpty()) {
         InspectorInstrumentation::activeStyleSheetsUpdated(&m_document, m_documentStyleSheetCollection.styleSheetsForStyleSheetList());
@@ -431,12 +431,12 @@
     InspectorInstrumentation::activeStyleSheetsUpdated(&m_document, activeStyleSheets);
 }
 
-void StyleSheetCollections::didRemoveShadowRoot(ShadowRoot* shadowRoot)
+void StyleEngine::didRemoveShadowRoot(ShadowRoot* shadowRoot)
 {
     m_styleSheetCollectionMap.remove(shadowRoot);
 }
 
-void StyleSheetCollections::appendActiveAuthorStyleSheets(StyleResolver* styleResolver)
+void StyleEngine::appendActiveAuthorStyleSheets(StyleResolver* styleResolver)
 {
     ASSERT(styleResolver);
 
diff --git a/Source/core/dom/StyleSheetCollections.h b/Source/core/dom/StyleEngine.h
similarity index 95%
rename from Source/core/dom/StyleSheetCollections.h
rename to Source/core/dom/StyleEngine.h
index 978d1b0..98d2bae 100644
--- a/Source/core/dom/StyleSheetCollections.h
+++ b/Source/core/dom/StyleEngine.h
@@ -25,8 +25,8 @@
  *
  */
 
-#ifndef StyleSheetCollections_h
-#define StyleSheetCollections_h
+#ifndef StyleEngine_h
+#define StyleEngine_h
 
 #include "core/dom/Document.h"
 #include "core/dom/DocumentOrderedList.h"
@@ -48,12 +48,12 @@
 class StyleSheetContents;
 class StyleSheetList;
 
-class StyleSheetCollections {
+class StyleEngine {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<StyleSheetCollections> create(Document& document) { return adoptPtr(new StyleSheetCollections(document)); }
+    static PassOwnPtr<StyleEngine> create(Document& document) { return adoptPtr(new StyleEngine(document)); }
 
-    ~StyleSheetCollections();
+    ~StyleEngine();
 
     const Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList();
     const Vector<RefPtr<CSSStyleSheet> >& activeAuthorStyleSheets() const;
@@ -112,7 +112,7 @@
     void getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const;
 
 private:
-    StyleSheetCollections(Document&);
+    StyleEngine(Document&);
 
     StyleSheetCollection* ensureStyleSheetCollectionFor(TreeScope&);
     StyleSheetCollection* styleSheetCollectionFor(TreeScope&);
diff --git a/Source/core/dom/StyleSheetCollection.cpp b/Source/core/dom/StyleSheetCollection.cpp
index 1edd2b8..6f807b9 100644
--- a/Source/core/dom/StyleSheetCollection.cpp
+++ b/Source/core/dom/StyleSheetCollection.cpp
@@ -33,7 +33,7 @@
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/html/HTMLStyleElement.h"
 #include "core/page/Settings.h"
 
diff --git a/Source/core/dom/StyleSheetCollection.h b/Source/core/dom/StyleSheetCollection.h
index 0a89677..6519617 100644
--- a/Source/core/dom/StyleSheetCollection.h
+++ b/Source/core/dom/StyleSheetCollection.h
@@ -43,7 +43,7 @@
 
 class ContainerNode;
 class CSSStyleSheet;
-class StyleSheetCollections;
+class StyleEngine;
 class Node;
 class StyleSheet;
 class StyleSheetContents;
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index 90446f1..744c15d 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -77,7 +77,7 @@
         toRenderText(renderer())->setTextWithOffset(dataImpl(), 0, oldStr.length());
 
     if (parentNode())
-        document().textNodeSplit(this);
+        document().didSplitTextNode(this);
 
     return newText.release();
 }
diff --git a/Source/core/dom/TouchController.cpp b/Source/core/dom/TouchController.cpp
new file mode 100644
index 0000000..ce730d2
--- /dev/null
+++ b/Source/core/dom/TouchController.cpp
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2013 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/TouchController.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/EventNames.h"
+#include "core/dom/TouchEvent.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
+#include "core/page/Frame.h"
+#include "core/page/Page.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
+
+namespace WebCore {
+
+TouchController::TouchController(Document* document)
+    : DOMWindowLifecycleObserver(document->domWindow())
+    , DocumentLifecycleObserver(document)
+{
+}
+
+TouchController::~TouchController()
+{
+}
+
+const char* TouchController::supplementName()
+{
+    return "TouchController";
+}
+
+TouchController* TouchController::from(Document* document)
+{
+    TouchController* controller = static_cast<TouchController*>(Supplement<ScriptExecutionContext>::from(document, supplementName()));
+    if (!controller) {
+        controller = new TouchController(document);
+        Supplement<ScriptExecutionContext>::provideTo(document, supplementName(), adoptPtr(controller));
+    }
+    return controller;
+}
+
+void TouchController::didAddTouchEventHandler(Document* document, Node* handler)
+{
+    if (!m_touchEventTargets)
+        m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
+    m_touchEventTargets->add(handler);
+    if (Document* parent = document->parentDocument()) {
+        TouchController::from(parent)->didAddTouchEventHandler(parent, document);
+        return;
+    }
+    if (Page* page = document->page()) {
+        if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+            scrollingCoordinator->touchEventTargetRectsDidChange(document);
+        if (m_touchEventTargets->size() == 1)
+            page->chrome().client().needTouchEvents(true);
+    }
+}
+
+void TouchController::didRemoveTouchEventHandler(Document* document, Node* handler)
+{
+    if (!m_touchEventTargets)
+        return;
+    ASSERT(m_touchEventTargets->contains(handler));
+    m_touchEventTargets->remove(handler);
+    if (Document* parent = document->parentDocument()) {
+        TouchController::from(parent)->didRemoveTouchEventHandler(parent, document);
+        return;
+    }
+
+    Page* page = document->page();
+    if (!page)
+        return;
+    if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+        scrollingCoordinator->touchEventTargetRectsDidChange(document);
+    if (m_touchEventTargets->size())
+        return;
+    for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+        if (frame->document() && TouchController::from(frame->document())->hasTouchEventHandlers())
+            return;
+    }
+    page->chrome().client().needTouchEvents(false);
+}
+
+void TouchController::didRemoveEventTargetNode(Document* document, Node* handler)
+{
+    if (m_touchEventTargets && !m_touchEventTargets->isEmpty()) {
+        if (handler == document)
+            m_touchEventTargets->clear();
+        else
+            m_touchEventTargets->removeAll(handler);
+        Document* parent = document->parentDocument();
+        if (m_touchEventTargets->isEmpty() && parent)
+            TouchController::from(parent)->didRemoveEventTargetNode(parent, document);
+    }
+}
+
+void TouchController::didAddEventListener(DOMWindow* window, const AtomicString& eventType)
+{
+    if (eventNames().isTouchEventType(eventType)) {
+        Document* document = window->document();
+        didAddTouchEventHandler(document, document);
+    }
+}
+
+void TouchController::didRemoveEventListener(DOMWindow* window, const AtomicString& eventType)
+{
+    if (eventNames().isTouchEventType(eventType)) {
+        Document* document = window->document();
+        didRemoveTouchEventHandler(document, document);
+    }
+}
+
+void TouchController::didRemoveAllEventListeners(DOMWindow* window)
+{
+    if (Document* document = window->document())
+        didRemoveEventTargetNode(document, document);
+}
+
+void TouchController::documentWasDetached()
+{
+    Document* document = static_cast<Document*>(scriptExecutionContext());
+    Document* parentDocument = document->parentDocument();
+
+    if (parentDocument) {
+        TouchController* parentController = TouchController::from(parentDocument);
+        if (parentController->hasTouchEventHandlers())
+            parentController->didRemoveEventTargetNode(parentDocument, document);
+    }
+}
+
+void TouchController::documentBeingDestroyed()
+{
+    Document* document = static_cast<Document*>(scriptExecutionContext());
+
+    if (Document* ownerDocument = document->ownerDocument())
+        TouchController::from(ownerDocument)->didRemoveEventTargetNode(ownerDocument, document);
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/TouchController.h b/Source/core/dom/TouchController.h
new file mode 100644
index 0000000..24d1ae1
--- /dev/null
+++ b/Source/core/dom/TouchController.h
@@ -0,0 +1,76 @@
+/*
+* Copyright (C) 2013 Google, Inc. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+*  * Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+*  * Redistributions in binary form must reproduce the above copyright
+*    notice, this list of conditions and the following disclaimer in the
+*    documentation and/or other materials provided with the distribution.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef TouchController_h
+#define TouchController_h
+
+#include "core/dom/DocumentLifecycleObserver.h"
+#include "core/dom/Event.h"
+#include "core/dom/Node.h"
+#include "core/page/DOMWindowLifecycleObserver.h"
+#include "core/platform/Supplementable.h"
+#include "wtf/HashSet.h"
+
+namespace WebCore {
+
+typedef HashCountedSet<Node*> TouchEventTargetSet;
+
+class Document;
+class DOMWindow;
+
+class TouchController : public Supplement<ScriptExecutionContext>, public DOMWindowLifecycleObserver, public DocumentLifecycleObserver {
+
+public:
+    virtual ~TouchController();
+
+    static const char* supplementName();
+    static TouchController* from(Document*);
+
+    bool hasTouchEventHandlers() const { return m_touchEventTargets ? m_touchEventTargets->size() : false; }
+
+    void didAddTouchEventHandler(Document*, Node*);
+    void didRemoveTouchEventHandler(Document*, Node*);
+    void didRemoveEventTargetNode(Document*, Node*);
+
+    const TouchEventTargetSet* touchEventTargets() const { return m_touchEventTargets.get(); }
+
+    // Inherited from DOMWindowLifecycleObserver
+    virtual void didAddEventListener(DOMWindow*, const AtomicString&) OVERRIDE;
+    virtual void didRemoveEventListener(DOMWindow*, const AtomicString&) OVERRIDE;
+    virtual void didRemoveAllEventListeners(DOMWindow*) OVERRIDE;
+
+    // Inherited from DocumentLifecycleObserver
+    virtual void documentWasDetached() OVERRIDE;
+    virtual void documentBeingDestroyed() OVERRIDE;
+
+private:
+    explicit TouchController(Document*);
+
+    OwnPtr<TouchEventTargetSet> m_touchEventTargets;
+};
+
+} // namespace WebCore
+
+#endif // TouchController_h
diff --git a/Source/core/dom/TouchList.h b/Source/core/dom/TouchList.h
index 74a712c..6d5f2bf 100644
--- a/Source/core/dom/TouchList.h
+++ b/Source/core/dom/TouchList.h
@@ -40,6 +40,11 @@
         return adoptRef(new TouchList);
     }
 
+    static PassRefPtr<TouchList> create(Vector<RefPtr<Touch> >& touches)
+    {
+        return adoptRef(new TouchList(touches));
+    }
+
     unsigned length() const { return m_values.size(); }
 
     Touch* item(unsigned);
@@ -53,6 +58,12 @@
         ScriptWrappable::init(this);
     }
 
+    TouchList(Vector<RefPtr<Touch> >& touches)
+    {
+        m_values.swap(touches);
+        ScriptWrappable::init(this);
+    }
+
     Vector<RefPtr<Touch> > m_values;
 };
 
diff --git a/Source/core/dom/UserGestureIndicator.cpp b/Source/core/dom/UserGestureIndicator.cpp
index 68e3feb..b52b871 100644
--- a/Source/core/dom/UserGestureIndicator.cpp
+++ b/Source/core/dom/UserGestureIndicator.cpp
@@ -135,17 +135,17 @@
 {
     if (token) {
         static_cast<GestureToken*>(token.get())->resetTimestamp();
-        if (static_cast<GestureToken*>(token.get())->hasGestures()) {
-            if (!s_topmostIndicator) {
-                s_topmostIndicator = this;
-                m_token = token;
-            } else {
-                m_token = s_topmostIndicator->currentToken();
+        if (!s_topmostIndicator) {
+            s_topmostIndicator = this;
+            m_token = token;
+        } else {
+            m_token = s_topmostIndicator->currentToken();
+            if (static_cast<GestureToken*>(token.get())->hasGestures()) {
                 static_cast<GestureToken*>(m_token.get())->addGesture();
                 static_cast<GestureToken*>(token.get())->consumeGesture();
             }
-            s_state = DefinitelyProcessingUserGesture;
         }
+        s_state = DefinitelyProcessingUserGesture;
     }
 
     ASSERT(isDefinite(s_state));
diff --git a/Source/core/dom/shadow/ContentDistribution.h b/Source/core/dom/shadow/ContentDistribution.h
index 2fd8fc1..65a221d 100644
--- a/Source/core/dom/shadow/ContentDistribution.h
+++ b/Source/core/dom/shadow/ContentDistribution.h
@@ -40,6 +40,8 @@
 
 class ContentDistribution {
 public:
+    ContentDistribution() { m_nodes.reserveInitialCapacity(32); }
+
     PassRefPtr<Node> first() const { return m_nodes.first(); }
     PassRefPtr<Node> last() const { return m_nodes.last(); }
     PassRefPtr<Node> at(size_t index) const { return m_nodes.at(index); }
@@ -49,6 +51,7 @@
 
     void append(PassRefPtr<Node>);
     void clear() { m_nodes.clear(); m_indices.clear(); }
+    void shrinkToFit() { m_nodes.shrinkToFit(); }
 
     bool contains(const Node* node) const { return m_indices.contains(node); }
     size_t find(const Node*) const;
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 455ad32..bebad50 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -194,15 +194,16 @@
 void ElementShadow::distribute()
 {
     Vector<Node*> pool;
+    pool.reserveInitialCapacity(32);
     for (Node* node = host()->firstChild(); node; node = node->nextSibling())
         populate(node, pool);
 
     host()->setNeedsStyleRecalc();
 
-    Vector<bool> distributed(pool.size());
-    distributed.fill(false);
+    Vector<bool> distributed;
+    distributed.fill(false, pool.size());
 
-    Vector<HTMLShadowElement*, 8> activeShadowInsertionPoints;
+    Vector<HTMLShadowElement*, 32> activeShadowInsertionPoints;
     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
         HTMLShadowElement* firstActiveShadowInsertionPoint = 0;
 
@@ -282,8 +283,9 @@
             InsertionPoint* innerInsertionPoint = toInsertionPoint(node);
             if (innerInsertionPoint->hasDistribution()) {
                 for (size_t i = 0; i < innerInsertionPoint->size(); ++i) {
-                    distribution.append(innerInsertionPoint->at(i));
-                    m_nodeToInsertionPoint.add(innerInsertionPoint->at(i), insertionPoint);
+                    Node* nodeToAdd = innerInsertionPoint->at(i);
+                    distribution.append(nodeToAdd);
+                    m_nodeToInsertionPoint.add(nodeToAdd, insertionPoint);
                 }
             } else {
                 for (Node* child = innerInsertionPoint->firstChild(); child; child = child->nextSibling()) {
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
index 4c2b26d..7d05daa 100644
--- a/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -92,6 +92,7 @@
         distribution.at(j)->lazyReattachIfAttached();
 
     m_distribution.swap(distribution);
+    m_distribution.shrinkToFit();
 }
 
 void InsertionPoint::attach(const AttachContext& context)
@@ -146,8 +147,9 @@
     document().updateDistributionForNodeIfNeeded(this);
 
     Vector<RefPtr<Node> > nodes;
+    nodes.reserveInitialCapacity(m_distribution.size());
     for (size_t i = 0; i < m_distribution.size(); ++i)
-        nodes.append(m_distribution.at(i));
+        nodes.uncheckedAppend(m_distribution.at(i));
 
     return StaticNodeList::adopt(nodes);
 }
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index fa21b00..bb0f5a1 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -31,7 +31,7 @@
 #include "bindings/v8/ExceptionState.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ElementTraversal.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/InsertionPoint.h"
@@ -80,7 +80,7 @@
     ASSERT(!m_prev);
     ASSERT(!m_next);
 
-    documentInternal()->styleSheetCollections()->didRemoveShadowRoot(this);
+    documentInternal()->styleEngine()->didRemoveShadowRoot(this);
 
     // We cannot let ContainerNode destructor call willBeDeletedFrom()
     // for this ShadowRoot instance because TreeScope destructor
diff --git a/Source/core/editing/CompositeEditCommand.cpp b/Source/core/editing/CompositeEditCommand.cpp
index 3da087c..85ffd92 100644
--- a/Source/core/editing/CompositeEditCommand.cpp
+++ b/Source/core/editing/CompositeEditCommand.cpp
@@ -680,12 +680,18 @@
 
     VisiblePosition visiblePos(position);
     VisiblePosition previousVisiblePos(visiblePos.previous());
-    Position previous(previousVisiblePos.deepEquivalent());
+    replaceCollapsibleWhitespaceWithNonBreakingSpaceIfNeeded(previousVisiblePos);
+    replaceCollapsibleWhitespaceWithNonBreakingSpaceIfNeeded(visiblePos);
+}
 
-    if (isCollapsibleWhitespace(previousVisiblePos.characterAfter()) && previous.deprecatedNode()->isTextNode() && !previous.deprecatedNode()->hasTagName(brTag))
-        replaceTextInNodePreservingMarkers(toText(previous.deprecatedNode()), previous.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
-    if (isCollapsibleWhitespace(visiblePos.characterAfter()) && position.deprecatedNode()->isTextNode() && !position.deprecatedNode()->hasTagName(brTag))
-        replaceTextInNodePreservingMarkers(toText(position.deprecatedNode()), position.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
+void CompositeEditCommand::replaceCollapsibleWhitespaceWithNonBreakingSpaceIfNeeded(const VisiblePosition& visiblePosition)
+{
+    if (!isCollapsibleWhitespace(visiblePosition.characterAfter()))
+        return;
+    Position pos = visiblePosition.deepEquivalent().downstream();
+    if (!pos.containerNode() || !pos.containerNode()->isTextNode() || pos.containerNode()->hasTagName(brTag))
+        return;
+    replaceTextInNodePreservingMarkers(pos.containerText(), pos.offsetInContainerNode(), 1, nonBreakingSpaceString());
 }
 
 void CompositeEditCommand::rebalanceWhitespace()
diff --git a/Source/core/editing/CompositeEditCommand.h b/Source/core/editing/CompositeEditCommand.h
index cef79bb..8032544 100644
--- a/Source/core/editing/CompositeEditCommand.h
+++ b/Source/core/editing/CompositeEditCommand.h
@@ -112,6 +112,7 @@
     void rebalanceWhitespaceAt(const Position&);
     void rebalanceWhitespaceOnTextSubstring(PassRefPtr<Text>, int startOffset, int endOffset);
     void prepareWhitespaceAtPositionForSplit(Position&);
+    void replaceCollapsibleWhitespaceWithNonBreakingSpaceIfNeeded(const VisiblePosition&);
     bool canRebalance(const Position&) const;
     bool shouldRebalanceLeadingWhitespaceFor(const String&) const;
     void removeCSSProperty(PassRefPtr<Element>, CSSPropertyID);
diff --git a/Source/core/editing/DeleteSelectionCommand.cpp b/Source/core/editing/DeleteSelectionCommand.cpp
index 164437e..adf8e06 100644
--- a/Source/core/editing/DeleteSelectionCommand.cpp
+++ b/Source/core/editing/DeleteSelectionCommand.cpp
@@ -704,8 +704,11 @@
 
 void DeleteSelectionCommand::calculateTypingStyleAfterDelete()
 {
-    if (!m_typingStyle)
+    // Clearing any previously set typing style and doing an early return.
+    if (!m_typingStyle) {
+        document().frame()->selection().clearTypingStyle();
         return;
+    }
 
     // Compute the difference between the style before the delete and the style now
     // after the delete has been done. Set this style on the frame, so other editing
diff --git a/Source/core/editing/Editor.cpp b/Source/core/editing/Editor.cpp
index 8b8c495..16a9e01 100644
--- a/Source/core/editing/Editor.cpp
+++ b/Source/core/editing/Editor.cpp
@@ -427,7 +427,9 @@
         return;
 
     RefPtr<Range> rangeToCheck = Range::create(*m_frame->document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
-    m_spellCheckRequester->requestCheckingFor(SpellCheckRequest::create(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
+    TextCheckingParagraph textToCheck(rangeToCheck, rangeToCheck);
+    bool asynchronous = true;
+    chunkAndMarkAllMisspellingsAndBadGrammar(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), textToCheck, asynchronous);
 }
 
 void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace)
@@ -1535,6 +1537,13 @@
 
     Range* rangeToCheck = shouldMarkGrammar ? grammarRange : spellingRange;
     TextCheckingParagraph fullParagraphToCheck(rangeToCheck);
+
+    bool asynchronous = m_frame && m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled();
+    chunkAndMarkAllMisspellingsAndBadGrammar(textCheckingOptions, fullParagraphToCheck, asynchronous);
+}
+
+void Editor::chunkAndMarkAllMisspellingsAndBadGrammar(TextCheckingTypeMask textCheckingOptions, const TextCheckingParagraph& fullParagraphToCheck, bool asynchronous)
+{
     if (fullParagraphToCheck.isRangeEmpty() || fullParagraphToCheck.isEmpty())
         return;
 
@@ -1544,13 +1553,11 @@
     int end = fullParagraphToCheck.checkingEnd();
     start = std::min(start, end);
     end = std::max(start, end);
-    bool asynchronous = m_frame && m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled();
     const int kNumChunksToCheck = asynchronous ? (end - start + kChunkSize - 1) / (kChunkSize) : 1;
     int currentChunkStart = start;
-    RefPtr<Range> checkRange = asynchronous ? fullParagraphToCheck.paragraphRange() : rangeToCheck;
-    RefPtr<Range> paragraphRange = fullParagraphToCheck.paragraphRange();
+    RefPtr<Range> checkRange = fullParagraphToCheck.checkingRange();
     if (kNumChunksToCheck == 1 && asynchronous) {
-        markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), paragraphRange.get(), asynchronous, 0);
+        markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), checkRange.get(), asynchronous, 0);
         return;
     }
 
@@ -1558,10 +1565,9 @@
         checkRange = fullParagraphToCheck.subrange(currentChunkStart, kChunkSize);
         setStart(checkRange.get(), startOfSentence(checkRange->startPosition()));
         setEnd(checkRange.get(), endOfSentence(checkRange->endPosition()));
-        paragraphRange = checkRange;
 
         int checkingLength = 0;
-        markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), paragraphRange.get(), asynchronous, iter, &checkingLength);
+        markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), checkRange.get(), asynchronous, iter, &checkingLength);
         currentChunkStart += checkingLength;
     }
 }
diff --git a/Source/core/editing/Editor.h b/Source/core/editing/Editor.h
index d0b419d..bca72bb 100644
--- a/Source/core/editing/Editor.h
+++ b/Source/core/editing/Editor.h
@@ -59,8 +59,9 @@
 class StylePropertySet;
 class Text;
 class TextCheckerClient;
-class TextEvent;
+class TextCheckingParagraph;
 struct TextCheckingResult;
+class TextEvent;
 
 enum EditorCommandSource { CommandFromMenuOrKeyBinding, CommandFromDOM, CommandFromDOMWithUserInterface };
 enum EditorParagraphSeparator { EditorParagraphSeparatorIsDiv, EditorParagraphSeparatorIsP };
@@ -339,7 +340,8 @@
 
     bool unifiedTextCheckerEnabled() const;
 
-    void markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingMask, Range* checkingRange, Range* paragraphRange, bool asynchronous, int requestNumber, int* checkingLength = 0);
+    void chunkAndMarkAllMisspellingsAndBadGrammar(TextCheckingTypeMask textCheckingOptions, const TextCheckingParagraph& fullParagraphToCheck, bool asynchronous);
+    void markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* checkingRange, Range* paragraphRange, bool asynchronous, int requestNumber, int* checkingLength = 0);
 };
 
 inline void Editor::setStartNewKillRingSequence(bool flag)
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index 7e82d30..f9d1816 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -417,7 +417,7 @@
     return highest->nodeType() == Node::DOCUMENT_FRAGMENT_NODE && !highest->isShadowRoot();
 }
 
-void FrameSelection::textWasReplaced(CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)
+void FrameSelection::didUpdateCharacterData(CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)
 {
     // The fragment check is a performance optimization. See http://trac.webkit.org/changeset/30062.
     if (isNone() || !node || nodeIsDetachedFromDocument(*node))
@@ -443,7 +443,7 @@
     return Position(toText(oldNode.nextSibling()), positionOffset - oldLength);
 }
 
-void FrameSelection::textNodeSplit(const Text& oldNode)
+void FrameSelection::didSplitTextNode(const Text& oldNode)
 {
     if (isNone() || nodeIsDetachedFromDocument(oldNode))
         return;
diff --git a/Source/core/editing/FrameSelection.h b/Source/core/editing/FrameSelection.h
index 91b8bde..feb16e0 100644
--- a/Source/core/editing/FrameSelection.h
+++ b/Source/core/editing/FrameSelection.h
@@ -155,8 +155,8 @@
     void debugRenderer(RenderObject*, bool selected) const;
 
     void nodeWillBeRemoved(Node*);
-    void textWasReplaced(CharacterData*, unsigned offset, unsigned oldLength, unsigned newLength);
-    void textNodeSplit(const Text& oldNode);
+    void didUpdateCharacterData(CharacterData*, unsigned offset, unsigned oldLength, unsigned newLength);
+    void didSplitTextNode(const Text& oldNode);
 
     void setCaretVisible(bool caretIsVisible) { setCaretVisibility(caretIsVisible ? Visible : Hidden); }
     bool recomputeCaretRect();
diff --git a/Source/core/editing/SpellCheckRequester.cpp b/Source/core/editing/SpellCheckRequester.cpp
index 5bc37bf..023cf34 100644
--- a/Source/core/editing/SpellCheckRequester.cpp
+++ b/Source/core/editing/SpellCheckRequester.cpp
@@ -62,7 +62,7 @@
 }
 
 // static
-PassRefPtr<SpellCheckRequest> SpellCheckRequest::create(TextCheckingTypeMask textCheckingOptions, TextCheckingProcessType processType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange, int requestNubmer)
+PassRefPtr<SpellCheckRequest> SpellCheckRequest::create(TextCheckingTypeMask textCheckingOptions, TextCheckingProcessType processType, PassRefPtr<Range> checkingRange, PassRefPtr<Range> paragraphRange, int requestNumber)
 {
     ASSERT(checkingRange);
     ASSERT(paragraphRange);
@@ -79,7 +79,7 @@
         offsets[i] = markers[i]->startOffset();
     }
 
-    return adoptRef(new SpellCheckRequest(checkingRange, paragraphRange, text, textCheckingOptions, processType, hashes, offsets, requestNubmer));
+    return adoptRef(new SpellCheckRequest(checkingRange, paragraphRange, text, textCheckingOptions, processType, hashes, offsets, requestNumber));
 }
 
 const TextCheckingRequestData& SpellCheckRequest::data() const
diff --git a/Source/core/editing/TextCheckingHelper.h b/Source/core/editing/TextCheckingHelper.h
index b67e217..cd1bc09 100644
--- a/Source/core/editing/TextCheckingHelper.h
+++ b/Source/core/editing/TextCheckingHelper.h
@@ -59,10 +59,10 @@
 
     bool checkingRangeCovers(int location, int length) const { return location < checkingEnd() && location + length > checkingStart(); }
     PassRefPtr<Range> paragraphRange() const;
+    PassRefPtr<Range> checkingRange() const { return m_checkingRange; }
 
 private:
     void invalidateParagraphRangeValues();
-    PassRefPtr<Range> checkingRange() const { return m_checkingRange; }
     PassRefPtr<Range> offsetAsRange() const;
 
     RefPtr<Range> m_checkingRange;
diff --git a/Source/core/fetch/Resource.cpp b/Source/core/fetch/Resource.cpp
index 0a38f04..e6e2114 100644
--- a/Source/core/fetch/Resource.cpp
+++ b/Source/core/fetch/Resource.cpp
@@ -278,7 +278,13 @@
 
 double Resource::freshnessLifetime() const
 {
-    // Cache non-http resources liberally
+#if !OS(ANDROID)
+    // On desktop, local files should be reloaded in case they change.
+    if (m_response.url().isLocalFile())
+        return 0;
+#endif
+
+    // Cache other non-http resources liberally.
     if (!m_response.url().protocolIsInHTTPFamily())
         return std::numeric_limits<double>::max();
 
diff --git a/Source/core/fetch/Resource.h b/Source/core/fetch/Resource.h
index 6d5526b..bd9c37f 100644
--- a/Source/core/fetch/Resource.h
+++ b/Source/core/fetch/Resource.h
@@ -70,7 +70,8 @@
         LinkSubresource,
         TextTrack,
         Shader,
-        ImportResource
+        ImportResource,
+        NumberOfTypes,
     };
 
     enum Status {
diff --git a/Source/core/fetch/ResourceFetcher.cpp b/Source/core/fetch/ResourceFetcher.cpp
index 6059672..9652049 100644
--- a/Source/core/fetch/ResourceFetcher.cpp
+++ b/Source/core/fetch/ResourceFetcher.cpp
@@ -59,6 +59,7 @@
 #include "core/page/Performance.h"
 #include "core/page/ResourceTimingInfo.h"
 #include "core/page/Settings.h"
+#include "core/platform/HistogramSupport.h"
 #include "core/platform/Logging.h"
 #include "core/platform/chromium/TraceEvent.h"
 #include "public/platform/Platform.h"
@@ -72,7 +73,16 @@
 
 namespace WebCore {
 
-static Resource* createResource(Resource::Type type, const ResourceRequest& request, const String& charset)
+namespace {
+
+enum ActionUponResourceRequest {
+    LoadResource,
+    RevalidateResource,
+    UseResourceFromCache,
+    NumberOfResourceRequestActions,
+};
+
+Resource* createResource(Resource::Type type, const ResourceRequest& request, const String& charset)
 {
     switch (type) {
     case Resource::Image:
@@ -100,13 +110,15 @@
         return new ShaderResource(request);
     case Resource::ImportResource:
         return new RawResource(request, type);
+    case Resource::NumberOfTypes:
+        ASSERT_NOT_REACHED();
     }
 
     ASSERT_NOT_REACHED();
     return 0;
 }
 
-static ResourceLoadPriority loadPriority(Resource::Type type, const FetchRequest& request)
+ResourceLoadPriority loadPriority(Resource::Type type, const FetchRequest& request)
 {
     if (request.priority() != ResourceLoadPriorityUnresolved)
         return request.priority();
@@ -135,12 +147,14 @@
         return ResourceLoadPriorityLow;
     case Resource::Shader:
         return ResourceLoadPriorityMedium;
+    case Resource::NumberOfTypes:
+        ASSERT_NOT_REACHED();
     }
     ASSERT_NOT_REACHED();
     return ResourceLoadPriorityUnresolved;
 }
 
-static Resource* resourceFromDataURIRequest(const ResourceRequest& request)
+Resource* resourceFromDataURIRequest(const ResourceRequest& request)
 {
     const KURL& url = request.url();
     ASSERT(url.protocolIsData());
@@ -161,6 +175,8 @@
     return resource;
 }
 
+} // namespace
+
 ResourceFetcher::ResourceFetcher(DocumentLoader* documentLoader)
     : m_document(0)
     , m_documentLoader(documentLoader)
@@ -357,6 +373,8 @@
             // These cannot affect the current document.
             treatment = TreatAsAlwaysAllowedContent;
             break;
+        case Resource::NumberOfTypes:
+            ASSERT_NOT_REACHED();
         }
     }
     if (treatment == TreatAsActiveContent) {
@@ -417,6 +435,8 @@
             return false;
         }
         break;
+    case Resource::NumberOfTypes:
+        ASSERT_NOT_REACHED();
     }
 
     switch (type) {
@@ -464,6 +484,8 @@
         if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowMediaFromSource(url))
             return false;
         break;
+    case Resource::NumberOfTypes:
+        ASSERT_NOT_REACHED();
     }
 
     // Last of all, check for insecure content. We do this last so that when
@@ -541,13 +563,27 @@
         // Fall through
     case Load:
         resource = loadResource(type, request, request.charset());
+        HistogramSupport::histogramEnumeration(
+            "WebCore.ResourceFetcher.ActionUponResourceRequest", LoadResource,
+            NumberOfResourceRequestActions);
         break;
     case Revalidate:
         resource = revalidateResource(request, resource.get());
+        HistogramSupport::histogramEnumeration(
+            "WebCore.ResourceFetcher.ActionUponResourceRequest", RevalidateResource,
+            NumberOfResourceRequestActions);
         break;
     case Use:
         resource->updateForAccess();
         notifyLoadedFromMemoryCache(resource.get());
+        HistogramSupport::histogramEnumeration(
+            "WebCore.ResourceFetcher.ActionUponResourceRequest", UseResourceFromCache,
+            NumberOfResourceRequestActions);
+        HistogramSupport::histogramEnumeration(
+            "WebCore.ResourceFetcher.ResourceHasClientUponCacheHit", resource->hasClients(), 2);
+        HistogramSupport::histogramEnumeration(
+            "WebCore.ResourceFetcher.ResourceTypeUponCacheHit", resource->type(),
+            Resource::NumberOfTypes);
         break;
     }
 
@@ -947,12 +983,12 @@
                 initiatorDocument = document()->parentDocument();
             ASSERT(initiatorDocument);
             RefPtr<ResourceTimingInfo> info = it->value;
+            m_resourceTimingInfoMap.remove(it);
             info->setInitialRequest(resource->resourceRequest());
             info->setFinalResponse(resource->response());
             info->setLoadFinishTime(resource->loadFinishTime());
             if (DOMWindow* initiatorWindow = initiatorDocument->domWindow())
                 initiatorWindow->performance()->addResourceTiming(*info, initiatorDocument);
-            m_resourceTimingInfoMap.remove(it);
         }
     }
 
@@ -1006,7 +1042,7 @@
     unsigned long identifier = createUniqueIdentifier();
     context().dispatchDidLoadResourceFromMemoryCache(request, resource->response());
     // FIXME: If willSendRequest changes the request, we don't respect it.
-    willSendRequest(resource, request, ResourceResponse(), resource->options());
+    willSendRequest(identifier, request, ResourceResponse(), resource->options());
     InspectorInstrumentation::markResourceAsCached(frame()->page(), identifier);
     context().sendRemainingDelegateMessages(m_documentLoader, identifier, resource->response(), 0, resource->encodedSize(), 0, ResourceError());
 }
@@ -1151,12 +1187,12 @@
     context().dispatchDidFail(m_documentLoader, resource->identifier(), error);
 }
 
-void ResourceFetcher::willSendRequest(const Resource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse, const ResourceLoaderOptions& options)
+void ResourceFetcher::willSendRequest(unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse, const ResourceLoaderOptions& options)
 {
     if (options.sendLoadCallbacks == SendCallbacks)
-        context().dispatchWillSendRequest(m_documentLoader, resource->identifier(), request, redirectResponse, options.initiatorInfo);
+        context().dispatchWillSendRequest(m_documentLoader, identifier, request, redirectResponse, options.initiatorInfo);
     else
-        InspectorInstrumentation::willSendRequest(frame(), resource->identifier(), m_documentLoader, request, redirectResponse, options.initiatorInfo);
+        InspectorInstrumentation::willSendRequest(frame(), identifier, m_documentLoader, request, redirectResponse, options.initiatorInfo);
 }
 
 void ResourceFetcher::didReceiveResponse(const Resource* resource, const ResourceResponse& response, const ResourceLoaderOptions& options)
diff --git a/Source/core/fetch/ResourceFetcher.h b/Source/core/fetch/ResourceFetcher.h
index 5f1b975..d6cc106 100644
--- a/Source/core/fetch/ResourceFetcher.h
+++ b/Source/core/fetch/ResourceFetcher.h
@@ -147,7 +147,7 @@
     virtual void didFinishLoading(const Resource*, double finishTime, const ResourceLoaderOptions&) OVERRIDE;
     virtual void didChangeLoadingPriority(const Resource*, ResourceLoadPriority) OVERRIDE;
     virtual void didFailLoading(const Resource*, const ResourceError&, const ResourceLoaderOptions&) OVERRIDE;
-    virtual void willSendRequest(const Resource*, ResourceRequest&, const ResourceResponse& redirectResponse, const ResourceLoaderOptions&) OVERRIDE;
+    virtual void willSendRequest(unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const ResourceLoaderOptions&) OVERRIDE;
     virtual void didReceiveResponse(const Resource*, const ResourceResponse&, const ResourceLoaderOptions&) OVERRIDE;
     virtual void didReceiveData(const Resource*, const char* data, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) OVERRIDE;
     virtual void subresourceLoaderFinishedLoadingOnePart(ResourceLoader*) OVERRIDE;
diff --git a/Source/core/fetch/ResourceLoader.cpp b/Source/core/fetch/ResourceLoader.cpp
index 6bea1e8..be3b720 100644
--- a/Source/core/fetch/ResourceLoader.cpp
+++ b/Source/core/fetch/ResourceLoader.cpp
@@ -116,7 +116,7 @@
 void ResourceLoader::init(const ResourceRequest& passedRequest)
 {
     ResourceRequest request(passedRequest);
-    m_host->willSendRequest(m_resource, request, ResourceResponse(), m_options);
+    m_host->willSendRequest(m_resource->identifier(), request, ResourceResponse(), m_options);
     request.setReportLoadTiming(true);
     ASSERT(m_state != Terminated);
     ASSERT(!request.isNull());
@@ -254,7 +254,7 @@
     if (request.isNull() || m_state == Terminated)
         return;
 
-    m_host->willSendRequest(m_resource, request, redirectResponse, m_options);
+    m_host->willSendRequest(m_resource->identifier(), request, redirectResponse, m_options);
     request.setReportLoadTiming(true);
     ASSERT(!request.isNull());
     m_request = request;
diff --git a/Source/core/fetch/ResourceLoaderHost.h b/Source/core/fetch/ResourceLoaderHost.h
index 5860b96..888ccc5 100644
--- a/Source/core/fetch/ResourceLoaderHost.h
+++ b/Source/core/fetch/ResourceLoaderHost.h
@@ -60,7 +60,7 @@
     virtual void didChangeLoadingPriority(const Resource*, ResourceLoadPriority) = 0;
     virtual void didFailLoading(const Resource*, const ResourceError&, const ResourceLoaderOptions&) = 0;
 
-    virtual void willSendRequest(const Resource*, ResourceRequest&, const ResourceResponse& redirectResponse, const ResourceLoaderOptions&) = 0;
+    virtual void willSendRequest(unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const ResourceLoaderOptions&) = 0;
     virtual void didReceiveResponse(const Resource*, const ResourceResponse&, const ResourceLoaderOptions&) = 0;
     virtual void didReceiveData(const Resource*, const char* data, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) = 0;
 
diff --git a/Source/core/generate_test_support_idls.target.darwin-arm.mk b/Source/core/generate_test_support_idls.target.darwin-arm.mk
index f0ea789..c45c6cb 100644
--- a/Source/core/generate_test_support_idls.target.darwin-arm.mk
+++ b/Source/core/generate_test_support_idls.target.darwin-arm.mk
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_internal_runtime_flags.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
diff --git a/Source/core/generate_test_support_idls.target.darwin-mips.mk b/Source/core/generate_test_support_idls.target.darwin-mips.mk
index f0ea789..c45c6cb 100644
--- a/Source/core/generate_test_support_idls.target.darwin-mips.mk
+++ b/Source/core/generate_test_support_idls.target.darwin-mips.mk
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_internal_runtime_flags.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
diff --git a/Source/core/generate_test_support_idls.target.darwin-x86.mk b/Source/core/generate_test_support_idls.target.darwin-x86.mk
index f0ea789..c45c6cb 100644
--- a/Source/core/generate_test_support_idls.target.darwin-x86.mk
+++ b/Source/core/generate_test_support_idls.target.darwin-x86.mk
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_internal_runtime_flags.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
diff --git a/Source/core/generate_test_support_idls.target.linux-arm.mk b/Source/core/generate_test_support_idls.target.linux-arm.mk
index f0ea789..c45c6cb 100644
--- a/Source/core/generate_test_support_idls.target.linux-arm.mk
+++ b/Source/core/generate_test_support_idls.target.linux-arm.mk
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_internal_runtime_flags.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
diff --git a/Source/core/generate_test_support_idls.target.linux-mips.mk b/Source/core/generate_test_support_idls.target.linux-mips.mk
index f0ea789..c45c6cb 100644
--- a/Source/core/generate_test_support_idls.target.linux-mips.mk
+++ b/Source/core/generate_test_support_idls.target.linux-mips.mk
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_internal_runtime_flags.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
diff --git a/Source/core/generate_test_support_idls.target.linux-x86.mk b/Source/core/generate_test_support_idls.target.linux-x86.mk
index f0ea789..c45c6cb 100644
--- a/Source/core/generate_test_support_idls.target.linux-x86.mk
+++ b/Source/core/generate_test_support_idls.target.linux-x86.mk
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InternalRuntimeFlags.idl: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_generate_test_support_idls_target_InternalRuntimeFlags ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_internal_runtime_flags.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
diff --git a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
index 39eab63..d97ebb7 100644
--- a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
@@ -44,7 +44,7 @@
 
 void BaseChooserOnlyDateAndTimeInputType::handleDOMActivateEvent(Event*)
 {
-    if (element()->isDisabledOrReadOnly() || !element()->renderer() || !ScriptController::processingUserGesture())
+    if (element()->isDisabledOrReadOnly() || !element()->renderer() || !ScriptController::processingUserGesture() || element()->hasAuthorShadowRoot())
         return;
 
     if (m_dateTimeChooser)
diff --git a/Source/core/html/EmailInputType.cpp b/Source/core/html/EmailInputType.cpp
index eea1fc3..ef19641 100644
--- a/Source/core/html/EmailInputType.cpp
+++ b/Source/core/html/EmailInputType.cpp
@@ -29,7 +29,7 @@
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/platform/LocalizedStrings.h"
+#include "core/platform/text/PlatformLocale.h"
 #include "core/platform/text/RegularExpression.h"
 #include "public/platform/Platform.h"
 #include "wtf/PassOwnPtr.h"
@@ -38,6 +38,10 @@
 
 namespace WebCore {
 
+using WebKit::WebLocalizedString;
+
+// http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
+static const char localPartCharacters[] = "abcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+/=?^_`{|}~.-";
 static const char emailPattern[] =
     "[a-z0-9!#$%&'*+/=?^_`{|}~.-]+" // local part
     "@"
@@ -91,6 +95,30 @@
     return builder.toString();
 }
 
+static bool isInvalidLocalPartCharacter(UChar ch)
+{
+    if (!isASCII(ch))
+        return true;
+    DEFINE_STATIC_LOCAL(const String, validCharacters, (localPartCharacters));
+    return validCharacters.find(toASCIILower(ch)) == notFound;
+}
+
+static bool isInvalidDomainCharacter(UChar ch)
+{
+    if (!isASCII(ch))
+        return true;
+    return !isASCIILower(ch) && !isASCIIUpper(ch) && !isASCIIDigit(ch) && ch != '.' && ch != '-';
+}
+
+static bool checkValidDotUsage(const String& domain)
+{
+    if (domain.isEmpty())
+        return true;
+    if (domain[0] == '.' || domain[domain.length() - 1] == '.')
+        return false;
+    return domain.find("..") == notFound;
+}
+
 static bool isValidEmailAddress(const String& address)
 {
     int addressLength = address.length();
@@ -120,19 +148,29 @@
     return InputTypeNames::email();
 }
 
-bool EmailInputType::typeMismatchFor(const String& value) const
+// The return value is an invalid email address string if the specified string
+// contains an invalid email address. Otherwise, null string is returned.
+// If an empty string is returned, it means empty address is specified.
+// e.g. "foo@example.com,,bar@example.com" for multiple case.
+String EmailInputType::findInvalidAddress(const String& value) const
 {
     if (value.isEmpty())
-        return false;
+        return String();
     if (!element()->multiple())
-        return !isValidEmailAddress(value);
+        return isValidEmailAddress(value) ? String() : value;
     Vector<String> addresses;
     value.split(',', true, addresses);
     for (unsigned i = 0; i < addresses.size(); ++i) {
-        if (!isValidEmailAddress(stripLeadingAndTrailingHTMLSpaces(addresses[i])))
-            return true;
+        String stripped = stripLeadingAndTrailingHTMLSpaces(addresses[i]);
+        if (!isValidEmailAddress(stripped))
+            return stripped;
     }
-    return false;
+    return String();
+}
+
+bool EmailInputType::typeMismatchFor(const String& value) const
+{
+    return !findInvalidAddress(value).isNull();
 }
 
 bool EmailInputType::typeMismatch() const
@@ -142,7 +180,41 @@
 
 String EmailInputType::typeMismatchText() const
 {
-    return element()->multiple() ? validationMessageTypeMismatchForMultipleEmailText() : validationMessageTypeMismatchForEmailText();
+    String invalidAddress = findInvalidAddress(element()->value());
+    ASSERT(!invalidAddress.isNull());
+    if (invalidAddress.isEmpty())
+        return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmailEmpty);
+    String atSign = String("@");
+    size_t atIndex = invalidAddress.find('@');
+    if (atIndex == notFound)
+        return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmailNoAtSign, atSign, invalidAddress);
+    // We check validity against an ASCII value because of difficulty to check
+    // invalid characters. However we should show Unicode value.
+    String unicodeAddress = convertEmailAddressToUnicode(invalidAddress);
+    String localPart = invalidAddress.left(atIndex);
+    String domain = invalidAddress.substring(atIndex + 1);
+    if (localPart.isEmpty())
+        return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmailEmptyLocal, atSign, unicodeAddress);
+    if (domain.isEmpty())
+        return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmailEmptyDomain, atSign, unicodeAddress);
+    size_t invalidCharIndex = localPart.find(isInvalidLocalPartCharacter);
+    if (invalidCharIndex != notFound) {
+        unsigned charLength = U_IS_LEAD(localPart[invalidCharIndex]) ? 2 : 1;
+        return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmailInvalidLocal, atSign, localPart.substring(invalidCharIndex, charLength));
+    }
+    invalidCharIndex = domain.find(isInvalidDomainCharacter);
+    if (invalidCharIndex != notFound) {
+        unsigned charLength = U_IS_LEAD(domain[invalidCharIndex]) ? 2 : 1;
+        return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmailInvalidDomain, atSign, domain.substring(invalidCharIndex, charLength));
+    }
+    if (!checkValidDotUsage(domain)) {
+        size_t atIndexInUnicode = unicodeAddress.find('@');
+        ASSERT(atIndexInUnicode != notFound);
+        return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmailInvalidDots, String("."), unicodeAddress.substring(atIndexInUnicode + 1));
+    }
+    if (element()->multiple())
+        return locale().queryString(WebLocalizedString::ValidationTypeMismatchForMultipleEmail);
+    return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmail);
 }
 
 bool EmailInputType::isEmailField() const
diff --git a/Source/core/html/EmailInputType.h b/Source/core/html/EmailInputType.h
index 139bac2..e2e0eae 100644
--- a/Source/core/html/EmailInputType.h
+++ b/Source/core/html/EmailInputType.h
@@ -52,6 +52,7 @@
     virtual String convertFromVisibleValue(const String&) const OVERRIDE;
     virtual String visibleValue() const OVERRIDE;
     String convertEmailAddressToUnicode(const String&) const;
+    String findInvalidAddress(const String&) const;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/FormController.cpp b/Source/core/html/FormController.cpp
index 8da69a8..b68b2fb 100644
--- a/Source/core/html/FormController.cpp
+++ b/Source/core/html/FormController.cpp
@@ -25,6 +25,7 @@
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/platform/FileChooser.h"
+#include "wtf/Deque.h"
 #include "wtf/HashTableDeletedValueType.h"
 #include "wtf/text/StringBuilder.h"
 
diff --git a/Source/core/html/HTMLAllCollection.cpp b/Source/core/html/HTMLAllCollection.cpp
index a7f5b64..5fc4b8b 100644
--- a/Source/core/html/HTMLAllCollection.cpp
+++ b/Source/core/html/HTMLAllCollection.cpp
@@ -84,4 +84,9 @@
     returnValue0 = NamedNodesCollection::create(namedItems);
 }
 
+PassRefPtr<NodeList> HTMLAllCollection::tags(const String& name)
+{
+    return ownerNode()->getElementsByTagName(name);
+}
+
 } // namespace WebCore
diff --git a/Source/core/html/HTMLAllCollection.h b/Source/core/html/HTMLAllCollection.h
index 3c41251..bf6cddf 100644
--- a/Source/core/html/HTMLAllCollection.h
+++ b/Source/core/html/HTMLAllCollection.h
@@ -37,6 +37,7 @@
 
     Node* namedItemWithIndex(const AtomicString& name, unsigned index) const;
     void anonymousNamedGetter(const AtomicString& name, bool&, RefPtr<NodeList>&, bool&, RefPtr<Node>&);
+    PassRefPtr<NodeList> tags(const String&);
 
 private:
     HTMLAllCollection(Node*, CollectionType);
diff --git a/Source/core/html/HTMLAllCollection.idl b/Source/core/html/HTMLAllCollection.idl
index 5eae2ee..9f87dd4 100644
--- a/Source/core/html/HTMLAllCollection.idl
+++ b/Source/core/html/HTMLAllCollection.idl
@@ -35,6 +35,6 @@
     [ImplementedAs=anonymousNamedGetter, NotEnumerable] getter (NodeList or Node)(DOMString name);
     [Custom] Node namedItem(DOMString name);
     // FIXME: This should return an HTMLAllCollection.
-    NodeList tags(DOMString name);
+    [MeasureAs=DocumentAllTags] NodeList tags(DOMString name);
 };
 
diff --git a/Source/core/html/HTMLAnchorElement.cpp b/Source/core/html/HTMLAnchorElement.cpp
index 5fa5a2b..43ee0a1 100644
--- a/Source/core/html/HTMLAnchorElement.cpp
+++ b/Source/core/html/HTMLAnchorElement.cpp
@@ -163,6 +163,9 @@
 
 bool HTMLAnchorElement::isKeyboardFocusable() const
 {
+    if (isFocusable() && Element::supportsFocus())
+        return HTMLElement::isKeyboardFocusable();
+
     if (isLink()) {
         Page* page = document().page();
         if (!page)
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index b75b296..280951c 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -502,6 +502,7 @@
     if (!m_imageBuffer)
         return;
     setExternallyAllocatedMemory(4 * width() * height());
+    m_imageBuffer->context()->setShouldClampToSourceRect(false);
     m_imageBuffer->context()->setImageInterpolationQuality(DefaultInterpolationQuality);
     if (document().settings() && !document().settings()->antialiased2dCanvasEnabled())
         m_imageBuffer->context()->setShouldAntialias(false);
diff --git a/Source/core/html/HTMLCollection.cpp b/Source/core/html/HTMLCollection.cpp
index a68e894..f891743 100644
--- a/Source/core/html/HTMLCollection.cpp
+++ b/Source/core/html/HTMLCollection.cpp
@@ -676,11 +676,6 @@
         result.append(nameResults->at(i));
 }
 
-PassRefPtr<NodeList> HTMLCollection::tags(const String& name)
-{
-    return ownerNode()->getElementsByTagName(name);
-}
-
 void HTMLCollection::append(NodeCacheMap& map, const AtomicString& key, Element* element)
 {
     OwnPtr<Vector<Element*> >& vector = map.add(key.impl(), nullptr).iterator->value;
diff --git a/Source/core/html/HTMLCollection.h b/Source/core/html/HTMLCollection.h
index 585cd9e..4ff5e71 100644
--- a/Source/core/html/HTMLCollection.h
+++ b/Source/core/html/HTMLCollection.h
@@ -38,7 +38,6 @@
 
     // DOM API
     virtual Node* namedItem(const AtomicString& name) const;
-    PassRefPtr<NodeList> tags(const String&);
 
     // Non-DOM API
     virtual bool hasNamedItem(const AtomicString& name) const;
diff --git a/Source/core/html/HTMLInputElement.cpp b/Source/core/html/HTMLInputElement.cpp
index d5766b5..875d3ca 100644
--- a/Source/core/html/HTMLInputElement.cpp
+++ b/Source/core/html/HTMLInputElement.cpp
@@ -43,6 +43,7 @@
 #include "core/dom/KeyboardEvent.h"
 #include "core/dom/MouseEvent.h"
 #include "core/dom/ScopedEventQueue.h"
+#include "core/dom/TouchController.h"
 #include "core/dom/TouchEvent.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/InsertionPoint.h"
@@ -163,7 +164,7 @@
     if (isRadioButton())
         document().formController()->checkedRadioButtons().removeButton(this);
     if (m_hasTouchEventHandler)
-        document().didRemoveEventTargetNode(this);
+        TouchController::from(&document())->didRemoveEventTargetNode(&document(), this);
 }
 
 const AtomicString& HTMLInputElement::name() const
@@ -186,9 +187,9 @@
     return m_inputType->innerTextElement();
 }
 
-HTMLElement* HTMLInputElement::innerBlockElement() const
+HTMLElement* HTMLInputElement::editingViewPortElement() const
 {
-    return m_inputType->innerBlockElement();
+    return m_inputType->editingViewPortElement();
 }
 
 HTMLElement* HTMLInputElement::passwordGeneratorButtonElement() const
@@ -196,11 +197,6 @@
     return m_inputType->passwordGeneratorButtonElement();
 }
 
-HTMLElement* HTMLInputElement::placeholderElement() const
-{
-    return m_inputType->placeholderElement();
-}
-
 bool HTMLInputElement::shouldAutocomplete() const
 {
     if (m_autocomplete != Uninitialized)
@@ -448,10 +444,11 @@
 
     bool hasTouchEventHandler = m_inputTypeView->hasTouchEventHandler();
     if (hasTouchEventHandler != m_hasTouchEventHandler) {
+        TouchController* controller = TouchController::from(&document());
         if (hasTouchEventHandler)
-            document().didAddTouchEventHandler(this);
+            controller->didAddTouchEventHandler(&document(), this);
         else
-            document().didRemoveTouchEventHandler(this);
+            controller->didRemoveTouchEventHandler(&document(), this);
         m_hasTouchEventHandler = hasTouchEventHandler;
     }
 
@@ -1162,7 +1159,7 @@
     // on the element, or presses enter while it is the active element. JavaScript code wishing to activate the element
     // must dispatch a DOMActivate event - a click event will not do the job.
     if (evt->type() == eventNames().DOMActivateEvent) {
-        m_inputTypeView->handleDOMActivateEvent(evt);
+        m_inputType->handleDOMActivateEvent(evt);
         if (evt->defaultHandled())
             return;
     }
@@ -1476,11 +1473,11 @@
         if (isRadioButton())
             oldDocument->formController()->checkedRadioButtons().removeButton(this);
         if (m_hasTouchEventHandler)
-            oldDocument->didRemoveEventTargetNode(this);
+            TouchController::from(oldDocument)->didRemoveEventTargetNode(oldDocument, this);
     }
 
     if (m_hasTouchEventHandler)
-        document().didAddTouchEventHandler(this);
+        TouchController::from(&document())->didAddTouchEventHandler(&document(), this);
 
     HTMLTextFormControlElement::didMoveToNewDocument(oldDocument);
 }
diff --git a/Source/core/html/HTMLInputElement.h b/Source/core/html/HTMLInputElement.h
index 684508f..b1de3a9 100644
--- a/Source/core/html/HTMLInputElement.h
+++ b/Source/core/html/HTMLInputElement.h
@@ -121,9 +121,8 @@
 
     HTMLElement* containerElement() const;
     virtual HTMLElement* innerTextElement() const;
-    HTMLElement* innerBlockElement() const;
+    HTMLElement* editingViewPortElement() const;
     HTMLElement* passwordGeneratorButtonElement() const;
-    virtual HTMLElement* placeholderElement() const;
 
     bool checked() const { return m_isChecked; }
     void setChecked(bool, TextFieldEventBehavior = DispatchNoEvent);
diff --git a/Source/core/html/HTMLLinkElement.cpp b/Source/core/html/HTMLLinkElement.cpp
index cbc8b9a..e41bf00 100644
--- a/Source/core/html/HTMLLinkElement.cpp
+++ b/Source/core/html/HTMLLinkElement.cpp
@@ -36,7 +36,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventSender.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/fetch/CSSStyleSheetResource.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ResourceFetcher.h"
@@ -80,7 +80,7 @@
     m_link.clear();
 
     if (inDocument())
-        document().styleSheetCollections()->removeStyleSheetCandidateNode(this);
+        document().styleEngine()->removeStyleSheetCandidateNode(this);
 
     linkLoadEventSender().cancelEvent(this);
 }
@@ -198,7 +198,7 @@
     if (m_isInShadowTree)
         return InsertionDone;
 
-    document().styleSheetCollections()->addStyleSheetCandidateNode(this, m_createdByParser);
+    document().styleEngine()->addStyleSheetCandidateNode(this, m_createdByParser);
 
     process();
     return InsertionDone;
@@ -216,7 +216,7 @@
         ASSERT(!linkStyle() || !linkStyle()->hasSheet());
         return;
     }
-    document().styleSheetCollections()->removeStyleSheetCandidateNode(this);
+    document().styleEngine()->removeStyleSheetCandidateNode(this);
 
     RefPtr<StyleSheet> removedSheet = sheet();
 
@@ -496,7 +496,7 @@
 
     if (m_pendingSheetType == NonBlocking)
         return;
-    m_owner->document().styleSheetCollections()->addPendingSheet();
+    m_owner->document().styleEngine()->addPendingSheet();
 }
 
 void LinkStyle::removePendingSheet(RemovePendingSheetNotificationType notification)
@@ -507,8 +507,8 @@
     if (type == None)
         return;
     if (type == NonBlocking) {
-        // Tell StyleSheetCollections to re-compute styleSheets of this m_owner's treescope.
-        m_owner->document().styleSheetCollections()->modifiedStyleSheetCandidateNode(m_owner);
+        // Tell StyleEngine to re-compute styleSheets of this m_owner's treescope.
+        m_owner->document().styleEngine()->modifiedStyleSheetCandidateNode(m_owner);
         // Document::removePendingSheet() triggers the style selector recalc for blocking sheets.
         // FIXME: We don't have enough knowledge at this point to know if we're adding or removing a sheet
         // so we can't call addedStyleSheet() or removedStyleSheet().
@@ -516,10 +516,10 @@
         return;
     }
 
-    m_owner->document().styleSheetCollections()->removePendingSheet(m_owner,
+    m_owner->document().styleEngine()->removePendingSheet(m_owner,
         notification == RemovePendingSheetNotifyImmediately
-        ? StyleSheetCollections::RemovePendingSheetNotifyImmediately
-        : StyleSheetCollections::RemovePendingSheetNotifyLater);
+        ? StyleEngine::RemovePendingSheetNotifyImmediately
+        : StyleEngine::RemovePendingSheetNotifyLater);
 }
 
 void LinkStyle::setDisabledState(bool disabled)
diff --git a/Source/core/html/HTMLMediaElement.cpp b/Source/core/html/HTMLMediaElement.cpp
index 587f75a..950ce40 100644
--- a/Source/core/html/HTMLMediaElement.cpp
+++ b/Source/core/html/HTMLMediaElement.cpp
@@ -346,11 +346,20 @@
     // us to dispatch an abort event, which would result in a crash.
     // See http://crbug.com/233654 for more details.
     m_completelyLoaded = true;
+
+    // Destroying the player may cause a resource load to be canceled,
+    // which could result in Document::dispatchWindowLoadEvent() being
+    // called via ResourceFetch::didLoadResource() then
+    // FrameLoader::loadDone(). To prevent load event dispatching during
+    // object destruction, we use Document::incrementLoadEventDelayCount().
+    // See http://crbug.com/275223 for more details.
+    document().incrementLoadEventDelayCount();
     m_player.clear();
 #if ENABLE(WEB_AUDIO)
     if (audioSourceProvider())
         audioSourceProvider()->setClient(0);
 #endif
+    document().decrementLoadEventDelayCount();
 }
 
 void HTMLMediaElement::didMoveToNewDocument(Document* oldDocument)
diff --git a/Source/core/html/HTMLQuoteElement.cpp b/Source/core/html/HTMLQuoteElement.cpp
index 47f1cd9..ff18c60 100644
--- a/Source/core/html/HTMLQuoteElement.cpp
+++ b/Source/core/html/HTMLQuoteElement.cpp
@@ -25,7 +25,7 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/HTMLStyleElement.cpp b/Source/core/html/HTMLStyleElement.cpp
index ee324da..259ddc3 100644
--- a/Source/core/html/HTMLStyleElement.cpp
+++ b/Source/core/html/HTMLStyleElement.cpp
@@ -31,7 +31,7 @@
 #include "core/dom/Document.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventSender.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/dom/shadow/ShadowRoot.h"
 
 namespace WebCore {
@@ -102,10 +102,10 @@
             scopingNode = containingShadowRoot();
             unregisterWithScopingNode(scopingNode);
         }
-        document().styleSheetCollections()->removeStyleSheetCandidateNode(this, scopingNode);
+        document().styleEngine()->removeStyleSheetCandidateNode(this, scopingNode);
         registerWithScopingNode(true);
 
-        document().styleSheetCollections()->addStyleSheetCandidateNode(this, false);
+        document().styleEngine()->addStyleSheetCandidateNode(this, false);
         document().modifiedStyleSheet(sheet());
         return;
     }
@@ -115,7 +115,7 @@
     if (m_scopedStyleRegistrationState != RegisteredAsScoped)
         return;
 
-    document().styleSheetCollections()->removeStyleSheetCandidateNode(this, parentNode());
+    document().styleEngine()->removeStyleSheetCandidateNode(this, parentNode());
     unregisterWithScopingNode(parentNode());
 
     // As any <style> in a shadow tree is treated as "scoped",
@@ -123,7 +123,7 @@
     if (isInShadowTree())
         registerWithScopingNode(false);
 
-    document().styleSheetCollections()->addStyleSheetCandidateNode(this, false);
+    document().styleEngine()->addStyleSheetCandidateNode(this, false);
     document().modifiedStyleSheet(sheet());
 }
 
diff --git a/Source/core/html/HTMLTextAreaElement.cpp b/Source/core/html/HTMLTextAreaElement.cpp
index 3ef62fe..d2ac02f 100644
--- a/Source/core/html/HTMLTextAreaElement.cpp
+++ b/Source/core/html/HTMLTextAreaElement.cpp
@@ -42,6 +42,7 @@
 #include "core/editing/TextIterator.h"
 #include "core/html/FormController.h"
 #include "core/html/FormDataList.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/html/shadow/TextControlInnerElements.h"
 #include "core/page/Frame.h"
 #include "core/platform/LocalizedStrings.h"
@@ -84,7 +85,6 @@
     , m_rows(defaultRows)
     , m_cols(defaultCols)
     , m_wrap(SoftWrap)
-    , m_placeholder(0)
     , m_isDirty(false)
     , m_wasModifiedByUser(false)
 {
@@ -514,11 +514,6 @@
     return true;
 }
 
-HTMLElement* HTMLTextAreaElement::placeholderElement() const
-{
-    return m_placeholder;
-}
-
 bool HTMLTextAreaElement::matchesReadOnlyPseudoClass() const
 {
     return isReadOnly();
@@ -531,21 +526,21 @@
 
 void HTMLTextAreaElement::updatePlaceholderText()
 {
+    HTMLElement* placeholder = placeholderElement();
     String placeholderText = strippedPlaceholder();
     if (placeholderText.isEmpty()) {
-        if (m_placeholder) {
-            userAgentShadowRoot()->removeChild(m_placeholder);
-            m_placeholder = 0;
-        }
+        if (placeholder)
+            userAgentShadowRoot()->removeChild(placeholder);
         return;
     }
-    if (!m_placeholder) {
-        RefPtr<HTMLDivElement> placeholder = HTMLDivElement::create(document());
-        m_placeholder = placeholder.get();
-        m_placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
-        userAgentShadowRoot()->insertBefore(m_placeholder, innerTextElement()->nextSibling());
+    if (!placeholder) {
+        RefPtr<HTMLDivElement> newElement = HTMLDivElement::create(document());
+        placeholder = newElement.get();
+        placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+        placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
+        userAgentShadowRoot()->insertBefore(placeholder, innerTextElement()->nextSibling());
     }
-    m_placeholder->setTextContent(placeholderText, ASSERT_NO_EXCEPTION);
+    placeholder->setTextContent(placeholderText, ASSERT_NO_EXCEPTION);
 }
 
 }
diff --git a/Source/core/html/HTMLTextAreaElement.h b/Source/core/html/HTMLTextAreaElement.h
index 80d2f29..7a35eb6 100644
--- a/Source/core/html/HTMLTextAreaElement.h
+++ b/Source/core/html/HTMLTextAreaElement.h
@@ -78,7 +78,6 @@
     void setValueCommon(const String&);
 
     virtual bool supportsPlaceholder() const { return true; }
-    virtual HTMLElement* placeholderElement() const;
     virtual void updatePlaceholderText();
     virtual bool isEmptyValue() const { return value().isEmpty(); }
 
@@ -124,7 +123,6 @@
     int m_rows;
     int m_cols;
     WrapMethod m_wrap;
-    HTMLElement* m_placeholder;
     mutable String m_value;
     mutable bool m_isDirty;
     mutable bool m_wasModifiedByUser;
diff --git a/Source/core/html/HTMLTextFormControlElement.cpp b/Source/core/html/HTMLTextFormControlElement.cpp
index acbd7cd..4887402 100644
--- a/Source/core/html/HTMLTextFormControlElement.cpp
+++ b/Source/core/html/HTMLTextFormControlElement.cpp
@@ -34,9 +34,11 @@
 #include "core/dom/EventNames.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Text.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/TextIterator.h"
 #include "core/html/HTMLBRElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
 #include "core/page/Frame.h"
 #include "core/page/UseCounter.h"
 #include "core/rendering/RenderBlock.h"
@@ -143,6 +145,11 @@
         && (!renderer() || renderer()->style()->visibility() == VISIBLE);
 }
 
+HTMLElement* HTMLTextFormControlElement::placeholderElement() const
+{
+    return toHTMLElement(userAgentShadowRoot()->getElementById(ShadowElementNames::placeholder()));
+}
+
 void HTMLTextFormControlElement::updatePlaceholderVisibility(bool placeholderValueChanged)
 {
     if (!supportsPlaceholder())
diff --git a/Source/core/html/HTMLTextFormControlElement.h b/Source/core/html/HTMLTextFormControlElement.h
index 4c9e1ec..66562b6 100644
--- a/Source/core/html/HTMLTextFormControlElement.h
+++ b/Source/core/html/HTMLTextFormControlElement.h
@@ -53,7 +53,7 @@
     virtual bool supportsPlaceholder() const = 0;
     String strippedPlaceholder() const;
     bool placeholderShouldBeVisible() const;
-    virtual HTMLElement* placeholderElement() const = 0;
+    HTMLElement* placeholderElement() const;
     void updatePlaceholderVisibility(bool);
 
     VisiblePosition visiblePositionForIndex(int) const;
diff --git a/Source/core/html/HTMLVideoElement.idl b/Source/core/html/HTMLVideoElement.idl
index 31dd2bc..2b2ab0d 100644
--- a/Source/core/html/HTMLVideoElement.idl
+++ b/Source/core/html/HTMLVideoElement.idl
@@ -35,11 +35,11 @@
     readonly attribute boolean webkitSupportsFullscreen;
     readonly attribute boolean webkitDisplayingFullscreen;
 
-    [RaisesException] void webkitEnterFullscreen();
+    [RaisesException, PerWorldBindings, ActivityLog=Access] void webkitEnterFullscreen();
     void webkitExitFullscreen();
 
     // Note the different capitalization of the "S" in FullScreen.
-    [RaisesException] void webkitEnterFullScreen();
+    [RaisesException, PerWorldBindings, ActivityLog=Access] void webkitEnterFullScreen();
     void webkitExitFullScreen();
 
     // The number of frames that have been decoded and made available for
diff --git a/Source/core/html/HTMLViewSourceDocument.cpp b/Source/core/html/HTMLViewSourceDocument.cpp
index b5b8cef..e5dd879 100644
--- a/Source/core/html/HTMLViewSourceDocument.cpp
+++ b/Source/core/html/HTMLViewSourceDocument.cpp
@@ -26,7 +26,7 @@
 #include "core/html/HTMLViewSourceDocument.h"
 
 #include "HTMLNames.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/dom/Text.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLBRElement.h"
diff --git a/Source/core/html/InputType.cpp b/Source/core/html/InputType.cpp
index 8f41d58..fb9d10c 100644
--- a/Source/core/html/InputType.cpp
+++ b/Source/core/html/InputType.cpp
@@ -65,11 +65,13 @@
 #include "core/html/shadow/HTMLShadowElement.h"
 #include "core/page/Page.h"
 #include "core/platform/LocalizedStrings.h"
+#include "core/platform/text/PlatformLocale.h"
 #include "core/platform/text/TextBreakIterator.h"
 #include "core/rendering/RenderTheme.h"
 
 namespace WebCore {
 
+using WebKit::WebLocalizedString;
 using namespace HTMLNames;
 using namespace std;
 
@@ -389,8 +391,16 @@
         return validationMessageRangeOverflowText(serialize(stepRange.maximum()));
 
     if (stepRange.stepMismatch(numericValue)) {
-        const String stepString = stepRange.hasStep() ? serializeForNumberType(stepRange.step() / stepRange.stepScaleFactor()) : emptyString();
-        return validationMessageStepMismatchText(serialize(stepRange.stepBase()), stepString);
+        ASSERT(stepRange.hasStep());
+        Decimal candidate1 = stepRange.clampValue(numericValue);
+        String localizedCandidate1 = localizeValue(serialize(candidate1));
+        Decimal candidate2 = candidate1 < numericValue ? candidate1 + stepRange.step() : candidate1 - stepRange.step();
+        if (!candidate2.isFinite() || candidate2 < stepRange.minimum() || candidate2 > stepRange.maximum())
+            return locale().queryString(WebLocalizedString::ValidationStepMismatchCloseToLimit, localizedCandidate1);
+        String localizedCandidate2 = localizeValue(serialize(candidate2));
+        if (candidate1 < candidate2)
+            return locale().queryString(WebLocalizedString::ValidationStepMismatch, localizedCandidate1, localizedCandidate2);
+        return locale().queryString(WebLocalizedString::ValidationStepMismatch, localizedCandidate2, localizedCandidate1);
     }
 
     return emptyString();
@@ -460,6 +470,11 @@
     return 0;
 }
 
+Locale& InputType::locale() const
+{
+    return element()->locale();
+}
+
 bool InputType::canSetStringValue() const
 {
     return true;
@@ -520,11 +535,6 @@
     return false;
 }
 
-HTMLElement* InputType::placeholderElement() const
-{
-    return 0;
-}
-
 bool InputType::rendererIsNeeded()
 {
     return true;
@@ -780,6 +790,10 @@
     return Decimal::nan();
 }
 
+void InputType::handleDOMActivateEvent(Event*)
+{
+}
+
 bool InputType::supportsIndeterminateAppearance() const
 {
     return false;
diff --git a/Source/core/html/InputType.h b/Source/core/html/InputType.h
index b19742e..bba7052 100644
--- a/Source/core/html/InputType.h
+++ b/Source/core/html/InputType.h
@@ -168,10 +168,9 @@
     virtual void destroyShadowSubtree();
 
     virtual HTMLElement* containerElement() const { return 0; }
-    virtual HTMLElement* innerBlockElement() const { return 0; }
+    virtual HTMLElement* editingViewPortElement() const { return 0; }
     virtual HTMLElement* innerTextElement() const { return 0; }
     virtual HTMLElement* passwordGeneratorButtonElement() const { return 0; }
-    virtual HTMLElement* placeholderElement() const;
 
     // Miscellaneous functions
 
@@ -203,6 +202,7 @@
     virtual void updatePlaceholderText();
     virtual String defaultToolTip() const;
     virtual Decimal findClosestTickMarkValue(const Decimal&);
+    virtual void handleDOMActivateEvent(Event*);
 
     // Parses the specified string for the type, and return
     // the Decimal value for the parsing result if the parsing
@@ -241,6 +241,7 @@
 protected:
     InputType(HTMLInputElement* element) : InputTypeView(element) { }
     Chrome* chrome() const;
+    Locale& locale() const;
     Decimal parseToNumberOrNaN(const String&) const;
     void observeFeatureIfVisible(UseCounter::Feature) const;
 
diff --git a/Source/core/html/SearchInputType.cpp b/Source/core/html/SearchInputType.cpp
index 5aab992..bd6f952 100644
--- a/Source/core/html/SearchInputType.cpp
+++ b/Source/core/html/SearchInputType.cpp
@@ -91,12 +91,12 @@
 {
     TextFieldInputType::createShadowSubtree();
     HTMLElement* container = containerElement();
-    HTMLElement* textWrapper = innerBlockElement();
+    HTMLElement* viewPort = editingViewPortElement();
     ASSERT(container);
-    ASSERT(textWrapper);
+    ASSERT(viewPort);
 
-    container->insertBefore(SearchFieldDecorationElement::create(element()->document()), textWrapper);
-    container->insertBefore(SearchFieldCancelButtonElement::create(element()->document()), textWrapper->nextSibling());
+    container->insertBefore(SearchFieldDecorationElement::create(element()->document()), viewPort);
+    container->insertBefore(SearchFieldCancelButtonElement::create(element()->document()), viewPort->nextSibling());
 }
 
 void SearchInputType::handleKeydownEvent(KeyboardEvent* event)
diff --git a/Source/core/html/TextFieldInputType.cpp b/Source/core/html/TextFieldInputType.cpp
index a599562..7915237 100644
--- a/Source/core/html/TextFieldInputType.cpp
+++ b/Source/core/html/TextFieldInputType.cpp
@@ -240,7 +240,7 @@
     ASSERT(element()->shadow());
 
     ASSERT(!m_innerText);
-    ASSERT(!m_innerBlock);
+    ASSERT(!m_editingViewPort);
 
     Document& document = element()->document();
     bool shouldHaveSpinButton = this->shouldHaveSpinButton();
@@ -257,9 +257,9 @@
     m_container->setPart(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
     shadowRoot->appendChild(m_container);
 
-    m_innerBlock = TextControlInnerElement::create(document);
-    m_innerBlock->appendChild(m_innerText);
-    m_container->appendChild(m_innerBlock);
+    m_editingViewPort = EditingViewPortElement::create(document);
+    m_editingViewPort->appendChild(m_innerText);
+    m_container->appendChild(m_editingViewPort);
 
 #if ENABLE(INPUT_SPEECH)
     if (element()->isSpeechEnabled())
@@ -275,9 +275,9 @@
     return m_container.get();
 }
 
-HTMLElement* TextFieldInputType::innerBlockElement() const
+HTMLElement* TextFieldInputType::editingViewPortElement() const
 {
-    return m_innerBlock.get();
+    return m_editingViewPort.get();
 }
 
 HTMLElement* TextFieldInputType::innerTextElement() const
@@ -286,17 +286,11 @@
     return m_innerText.get();
 }
 
-HTMLElement* TextFieldInputType::placeholderElement() const
-{
-    return m_placeholder.get();
-}
-
 void TextFieldInputType::destroyShadowSubtree()
 {
     InputType::destroyShadowSubtree();
     m_innerText.clear();
-    m_placeholder.clear();
-    m_innerBlock.clear();
+    m_editingViewPort.clear();
     if (SpinButtonElement* spinButton = spinButtonElement())
         spinButton->removeSpinButtonOwner();
     m_container.clear();
@@ -404,20 +398,21 @@
 {
     if (!supportsPlaceholder())
         return;
+    HTMLElement* placeholder = element()->placeholderElement();
     String placeholderText = element()->strippedPlaceholder();
     if (placeholderText.isEmpty()) {
-        if (m_placeholder) {
-            m_placeholder->parentNode()->removeChild(m_placeholder.get());
-            m_placeholder.clear();
-        }
+        if (placeholder)
+            placeholder->remove(ASSERT_NO_EXCEPTION);
         return;
     }
-    if (!m_placeholder) {
-        m_placeholder = HTMLDivElement::create(element()->document());
-        m_placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
-        element()->userAgentShadowRoot()->insertBefore(m_placeholder, m_container ? m_container->nextSibling() : innerTextElement()->nextSibling());
+    if (!placeholder) {
+        RefPtr<HTMLElement> newElement = HTMLDivElement::create(element()->document());
+        placeholder = newElement.get();
+        placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+        placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
+        element()->userAgentShadowRoot()->insertBefore(placeholder, m_container ? m_container->nextSibling() : innerTextElement()->nextSibling());
     }
-    m_placeholder->setTextContent(placeholderText, ASSERT_NO_EXCEPTION);
+    placeholder->setTextContent(placeholderText, ASSERT_NO_EXCEPTION);
 }
 
 bool TextFieldInputType::appendFormData(FormDataList& list, bool multipart) const
diff --git a/Source/core/html/TextFieldInputType.h b/Source/core/html/TextFieldInputType.h
index 793958b..9ac5445 100644
--- a/Source/core/html/TextFieldInputType.h
+++ b/Source/core/html/TextFieldInputType.h
@@ -49,7 +49,7 @@
     void handleKeydownEventForSpinButton(KeyboardEvent*);
 
     virtual HTMLElement* containerElement() const OVERRIDE;
-    virtual HTMLElement* innerBlockElement() const OVERRIDE;
+    virtual HTMLElement* editingViewPortElement() const OVERRIDE;
     virtual HTMLElement* innerTextElement() const OVERRIDE;
 
 protected:
@@ -84,7 +84,6 @@
     virtual bool shouldUseInputMethod() const OVERRIDE;
     virtual String sanitizeValue(const String&) const OVERRIDE;
     virtual bool shouldRespectListAttribute() OVERRIDE;
-    virtual HTMLElement* placeholderElement() const OVERRIDE;
     virtual void updatePlaceholderText() OVERRIDE;
     virtual bool appendFormData(FormDataList&, bool multipart) const OVERRIDE;
     virtual void subtreeHasChanged() OVERRIDE;
@@ -99,9 +98,8 @@
     SpinButtonElement* spinButtonElement() const;
 
     RefPtr<HTMLElement> m_container;
-    RefPtr<HTMLElement> m_innerBlock;
+    RefPtr<HTMLElement> m_editingViewPort;
     RefPtr<HTMLElement> m_innerText;
-    RefPtr<HTMLElement> m_placeholder;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index 968cac2..3225ecd 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -742,17 +742,7 @@
     if (!std::isfinite(m11) | !std::isfinite(m21) | !std::isfinite(dx) | !std::isfinite(m12) | !std::isfinite(m22) | !std::isfinite(dy))
         return;
 
-    AffineTransform ctm = state().m_transform;
-    if (!ctm.isInvertible())
-        return;
-
-    realizeSaves();
-
-    c->setCTM(canvas()->baseTransform());
-    modifiableState().m_transform = AffineTransform();
-    m_path.transform(ctm);
-
-    modifiableState().m_invertibleCTM = true;
+    resetTransform();
     transform(m11, m12, m21, m22, dx, dy);
 }
 
@@ -2059,6 +2049,8 @@
     StyleResolver* styleResolver = canvas()->styleResolver();
     styleResolver->applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), newStyle.get());
 
+    if (state().m_realizedFont)
+        state().m_font.fontSelector()->unregisterForInvalidationCallbacks(&modifiableState());
     modifiableState().m_font = newStyle->font();
     modifiableState().m_font.update(styleResolver->fontSelector());
     modifiableState().m_realizedFont = true;
diff --git a/Source/core/html/canvas/WebGLFramebuffer.cpp b/Source/core/html/canvas/WebGLFramebuffer.cpp
index ea0352a..d73eeac 100644
--- a/Source/core/html/canvas/WebGLFramebuffer.cpp
+++ b/Source/core/html/canvas/WebGLFramebuffer.cpp
@@ -46,14 +46,14 @@
 
     private:
         WebGLRenderbufferAttachment(WebGLRenderbuffer*);
-        virtual GC3Dsizei getWidth() const;
-        virtual GC3Dsizei getHeight() const;
-        virtual GC3Denum getFormat() const;
-        virtual GC3Denum getType() const;
-        virtual WebGLSharedObject* getObject() const;
+        virtual GC3Dsizei width() const;
+        virtual GC3Dsizei height() const;
+        virtual GC3Denum format() const;
+        virtual GC3Denum type() const;
+        virtual WebGLSharedObject* object() const;
         virtual bool isSharedObject(WebGLSharedObject*) const;
-        virtual bool isValid() const;
-        virtual bool isInitialized() const;
+        virtual bool valid() const;
+        virtual bool initialized() const;
         virtual void setInitialized();
         virtual void onDetached(GraphicsContext3D*);
         virtual void attach(GraphicsContext3D*, GC3Denum attachment);
@@ -74,28 +74,28 @@
     {
     }
 
-    GC3Dsizei WebGLRenderbufferAttachment::getWidth() const
+    GC3Dsizei WebGLRenderbufferAttachment::width() const
     {
-        return m_renderbuffer->getWidth();
+        return m_renderbuffer->width();
     }
 
-    GC3Dsizei WebGLRenderbufferAttachment::getHeight() const
+    GC3Dsizei WebGLRenderbufferAttachment::height() const
     {
-        return m_renderbuffer->getHeight();
+        return m_renderbuffer->height();
     }
 
-    GC3Denum WebGLRenderbufferAttachment::getFormat() const
+    GC3Denum WebGLRenderbufferAttachment::format() const
     {
-        GC3Denum format = m_renderbuffer->getInternalFormat();
+        GC3Denum format = m_renderbuffer->internalFormat();
         if (format == GraphicsContext3D::DEPTH_STENCIL
             && m_renderbuffer->emulatedStencilBuffer()
-            && m_renderbuffer->emulatedStencilBuffer()->getInternalFormat() != GraphicsContext3D::STENCIL_INDEX8) {
+            && m_renderbuffer->emulatedStencilBuffer()->internalFormat() != GraphicsContext3D::STENCIL_INDEX8) {
             return 0;
         }
         return format;
     }
 
-    WebGLSharedObject* WebGLRenderbufferAttachment::getObject() const
+    WebGLSharedObject* WebGLRenderbufferAttachment::object() const
     {
         return m_renderbuffer->object() ? m_renderbuffer.get() : 0;
     }
@@ -105,14 +105,14 @@
         return object == m_renderbuffer;
     }
 
-    bool WebGLRenderbufferAttachment::isValid() const
+    bool WebGLRenderbufferAttachment::valid() const
     {
         return m_renderbuffer->object();
     }
 
-    bool WebGLRenderbufferAttachment::isInitialized() const
+    bool WebGLRenderbufferAttachment::initialized() const
     {
-        return m_renderbuffer->object() && m_renderbuffer->isInitialized();
+        return m_renderbuffer->object() && m_renderbuffer->initialized();
     }
 
     void WebGLRenderbufferAttachment::setInitialized()
@@ -146,7 +146,7 @@
             context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, attachment, GraphicsContext3D::RENDERBUFFER, 0);
     }
 
-    GC3Denum WebGLRenderbufferAttachment::getType() const
+    GC3Denum WebGLRenderbufferAttachment::type() const
     {
         notImplemented();
         return 0;
@@ -158,14 +158,14 @@
 
     private:
         WebGLTextureAttachment(WebGLTexture*, GC3Denum target, GC3Dint level);
-        virtual GC3Dsizei getWidth() const;
-        virtual GC3Dsizei getHeight() const;
-        virtual GC3Denum getFormat() const;
-        virtual GC3Denum getType() const;
-        virtual WebGLSharedObject* getObject() const;
+        virtual GC3Dsizei width() const;
+        virtual GC3Dsizei height() const;
+        virtual GC3Denum format() const;
+        virtual GC3Denum type() const;
+        virtual WebGLSharedObject* object() const;
         virtual bool isSharedObject(WebGLSharedObject*) const;
-        virtual bool isValid() const;
-        virtual bool isInitialized() const;
+        virtual bool valid() const;
+        virtual bool initialized() const;
         virtual void setInitialized();
         virtual void onDetached(GraphicsContext3D*);
         virtual void attach(GraphicsContext3D*, GC3Denum attachment);
@@ -190,22 +190,22 @@
     {
     }
 
-    GC3Dsizei WebGLTextureAttachment::getWidth() const
+    GC3Dsizei WebGLTextureAttachment::width() const
     {
         return m_texture->getWidth(m_target, m_level);
     }
 
-    GC3Dsizei WebGLTextureAttachment::getHeight() const
+    GC3Dsizei WebGLTextureAttachment::height() const
     {
         return m_texture->getHeight(m_target, m_level);
     }
 
-    GC3Denum WebGLTextureAttachment::getFormat() const
+    GC3Denum WebGLTextureAttachment::format() const
     {
         return m_texture->getInternalFormat(m_target, m_level);
     }
 
-    WebGLSharedObject* WebGLTextureAttachment::getObject() const
+    WebGLSharedObject* WebGLTextureAttachment::object() const
     {
         return m_texture->object() ? m_texture.get() : 0;
     }
@@ -215,12 +215,12 @@
         return object == m_texture;
     }
 
-    bool WebGLTextureAttachment::isValid() const
+    bool WebGLTextureAttachment::valid() const
     {
         return m_texture->object();
     }
 
-    bool WebGLTextureAttachment::isInitialized() const
+    bool WebGLTextureAttachment::initialized() const
     {
         // Textures are assumed to be initialized.
         return true;
@@ -251,7 +251,7 @@
             context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, attachment, m_target, 0, m_level);
     }
 
-    GC3Denum WebGLTextureAttachment::getType() const
+    GC3Denum WebGLTextureAttachment::type() const
     {
         return m_texture->getType(m_target, m_level);
     }
@@ -335,16 +335,16 @@
     if (!object())
         return 0;
     WebGLAttachment* attachmentObject = getAttachment(attachment);
-    return attachmentObject ? attachmentObject->getObject() : 0;
+    return attachmentObject ? attachmentObject->object() : 0;
 }
 
 bool WebGLFramebuffer::isAttachmentComplete(WebGLAttachment* attachedObject, GC3Denum attachment, const char** reason) const
 {
-    ASSERT(attachedObject && attachedObject->isValid());
+    ASSERT(attachedObject && attachedObject->valid());
     ASSERT(reason);
 
-    GC3Denum internalformat = attachedObject->getFormat();
-    WebGLSharedObject* object = attachedObject->getObject();
+    GC3Denum internalformat = attachedObject->format();
+    WebGLSharedObject* object = attachedObject->object();
     ASSERT(object && (object->isTexture() || object->isRenderbuffer()));
 
     if (attachment == GraphicsContext3D::DEPTH_ATTACHMENT) {
@@ -354,7 +354,7 @@
                 return false;
             }
         } else if (object->isTexture()) {
-            GC3Denum type = attachedObject->getType();
+            GC3Denum type = attachedObject->type();
             if (!(context()->m_webglDepthTexture && internalformat == GraphicsContext3D::DEPTH_COMPONENT
                 && (type == GraphicsContext3D::UNSIGNED_SHORT || type == GraphicsContext3D::UNSIGNED_INT))) {
                 *reason = "the attached texture is not a depth texture";
@@ -377,7 +377,7 @@
                 return false;
             }
         } else if (object->isTexture()) {
-            GC3Denum type = attachedObject->getType();
+            GC3Denum type = attachedObject->type();
             if (!(context()->m_webglDepthTexture && internalformat == GraphicsContext3D::DEPTH_STENCIL
                 && type == GraphicsContext3D::UNSIGNED_INT_24_8)) {
                 *reason = "the attached texture is not a DEPTH_STENCIL texture";
@@ -393,7 +393,7 @@
                 return false;
             }
         } else if (object->isTexture()) {
-            GC3Denum type = attachedObject->getType();
+            GC3Denum type = attachedObject->type();
             if (internalformat != GraphicsContext3D::RGBA && internalformat != GraphicsContext3D::RGB) {
                 *reason = "the internalformat of the attached texture is not color-renderable";
                 return false;
@@ -417,7 +417,7 @@
         return false;
     }
 
-    if (!attachedObject->getWidth() || !attachedObject->getHeight()) {
+    if (!attachedObject->width() || !attachedObject->height()) {
         *reason = "attachment has a 0 dimension";
         return false;
     }
@@ -480,7 +480,7 @@
     }
 }
 
-GC3Dsizei WebGLFramebuffer::getColorBufferWidth() const
+GC3Dsizei WebGLFramebuffer::colorBufferWidth() const
 {
     if (!object())
         return 0;
@@ -488,10 +488,10 @@
     if (!attachment)
         return 0;
 
-    return attachment->getWidth();
+    return attachment->width();
 }
 
-GC3Dsizei WebGLFramebuffer::getColorBufferHeight() const
+GC3Dsizei WebGLFramebuffer::colorBufferHeight() const
 {
     if (!object())
         return 0;
@@ -499,17 +499,17 @@
     if (!attachment)
         return 0;
 
-    return attachment->getHeight();
+    return attachment->height();
 }
 
-GC3Denum WebGLFramebuffer::getColorBufferFormat() const
+GC3Denum WebGLFramebuffer::colorBufferFormat() const
 {
     if (!object())
         return 0;
     WebGLAttachment* attachment = getAttachment(GraphicsContext3D::COLOR_ATTACHMENT0);
     if (!attachment)
         return 0;
-    return attachment->getFormat();
+    return attachment->format();
 }
 
 GC3Denum WebGLFramebuffer::checkStatus(const char** reason) const
@@ -523,11 +523,11 @@
         WebGLAttachment* attachment = it->value.get();
         if (!isAttachmentComplete(attachment, it->key, reason))
             return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
-        if (!attachment->isValid()) {
+        if (!attachment->valid()) {
             *reason = "attachment is not valid";
             return GraphicsContext3D::FRAMEBUFFER_UNSUPPORTED;
         }
-        if (!attachment->getFormat()) {
+        if (!attachment->format()) {
             *reason = "attachment is an unsupported format";
             return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
         }
@@ -543,10 +543,10 @@
             break;
         }
         if (!count) {
-            width = attachment->getWidth();
-            height = attachment->getHeight();
+            width = attachment->width();
+            height = attachment->height();
         } else {
-            if (width != attachment->getWidth() || height != attachment->getHeight()) {
+            if (width != attachment->width() || height != attachment->height()) {
                 *reason = "attachments do not have the same dimensions";
                 return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
             }
@@ -581,7 +581,7 @@
     WebGLAttachment* attachment = getAttachment(GraphicsContext3D::STENCIL_ATTACHMENT);
     if (!attachment)
         attachment = getAttachment(GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT);
-    return attachment && attachment->isValid();
+    return attachment && attachment->valid();
 }
 
 void WebGLFramebuffer::deleteObjectImpl(GraphicsContext3D* context3d, Platform3DObject object)
diff --git a/Source/core/html/canvas/WebGLFramebuffer.h b/Source/core/html/canvas/WebGLFramebuffer.h
index 7b6edba..86e2aeb 100644
--- a/Source/core/html/canvas/WebGLFramebuffer.h
+++ b/Source/core/html/canvas/WebGLFramebuffer.h
@@ -43,18 +43,18 @@
     public:
         virtual ~WebGLAttachment();
 
-        virtual GC3Dsizei getWidth() const = 0;
-        virtual GC3Dsizei getHeight() const = 0;
-        virtual GC3Denum getFormat() const = 0;
-        // For texture attachment, getType() returns the type of the attached texture.
+        virtual GC3Dsizei width() const = 0;
+        virtual GC3Dsizei height() const = 0;
+        virtual GC3Denum format() const = 0;
+        // For texture attachment, type() returns the type of the attached texture.
         // For renderbuffer attachment, the type of the renderbuffer may vary with GL implementation.
-        // To avoid confusion, it would be better to not implement getType() for renderbuffer attachment and
-        // we should always use the internalformat of the renderbuffer and avoid using getType() API.
-        virtual GC3Denum getType() const = 0;
-        virtual WebGLSharedObject* getObject() const = 0;
+        // To avoid confusion, it would be better to not implement type() for renderbuffer attachment and
+        // we should always use the internalformat of the renderbuffer and avoid using type() API.
+        virtual GC3Denum type() const = 0;
+        virtual WebGLSharedObject* object() const = 0;
         virtual bool isSharedObject(WebGLSharedObject*) const = 0;
-        virtual bool isValid() const = 0;
-        virtual bool isInitialized() const = 0;
+        virtual bool valid() const = 0;
+        virtual bool initialized() const = 0;
         virtual void setInitialized() = 0;
         virtual void onDetached(GraphicsContext3D*) = 0;
         virtual void attach(GraphicsContext3D*, GC3Denum attachment) = 0;
@@ -76,9 +76,9 @@
     void removeAttachmentFromBoundFramebuffer(GC3Denum);
     WebGLSharedObject* getAttachmentObject(GC3Denum) const;
 
-    GC3Denum getColorBufferFormat() const;
-    GC3Dsizei getColorBufferWidth() const;
-    GC3Dsizei getColorBufferHeight() const;
+    GC3Denum colorBufferFormat() const;
+    GC3Dsizei colorBufferWidth() const;
+    GC3Dsizei colorBufferHeight() const;
 
     // This should always be called before drawArray, drawElements, clear,
     // readPixels, copyTexImage2D, copyTexSubImage2D if this framebuffer is
diff --git a/Source/core/html/canvas/WebGLProgram.cpp b/Source/core/html/canvas/WebGLProgram.cpp
index 804ed3b..f3001c5 100644
--- a/Source/core/html/canvas/WebGLProgram.cpp
+++ b/Source/core/html/canvas/WebGLProgram.cpp
@@ -88,7 +88,7 @@
     return false;
 }
 
-bool WebGLProgram::getLinkStatus()
+bool WebGLProgram::linkStatus()
 {
     cacheInfoIfNeeded();
     return m_linkStatus;
@@ -122,7 +122,7 @@
 {
     if (!shader || !shader->object())
         return false;
-    switch (shader->getType()) {
+    switch (shader->type()) {
     case GraphicsContext3D::VERTEX_SHADER:
         if (m_vertexShader)
             return false;
@@ -142,7 +142,7 @@
 {
     if (!shader || !shader->object())
         return false;
-    switch (shader->getType()) {
+    switch (shader->type()) {
     case GraphicsContext3D::VERTEX_SHADER:
         if (m_vertexShader != shader)
             return false;
diff --git a/Source/core/html/canvas/WebGLProgram.h b/Source/core/html/canvas/WebGLProgram.h
index 3b0203e..5ba00e7 100644
--- a/Source/core/html/canvas/WebGLProgram.h
+++ b/Source/core/html/canvas/WebGLProgram.h
@@ -45,10 +45,10 @@
 
     bool isUsingVertexAttrib0();
 
-    bool getLinkStatus();
+    bool linkStatus();
     void setLinkStatus(bool);
 
-    unsigned getLinkCount() const { return m_linkCount; }
+    unsigned linkCount() const { return m_linkCount; }
 
     // This is to be called everytime after the program is successfully linked.
     // We don't deal with integer overflow here, assuming in reality a program
diff --git a/Source/core/html/canvas/WebGLRenderbuffer.h b/Source/core/html/canvas/WebGLRenderbuffer.h
index 45c011a..95688a2 100644
--- a/Source/core/html/canvas/WebGLRenderbuffer.h
+++ b/Source/core/html/canvas/WebGLRenderbuffer.h
@@ -43,17 +43,17 @@
         m_internalFormat = internalformat;
         m_initialized = false;
     }
-    GC3Denum getInternalFormat() const { return m_internalFormat; }
+    GC3Denum internalFormat() const { return m_internalFormat; }
 
     void setSize(GC3Dsizei width, GC3Dsizei height)
     {
         m_width = width;
         m_height = height;
     }
-    GC3Dsizei getWidth() const { return m_width; }
-    GC3Dsizei getHeight() const { return m_height; }
+    GC3Dsizei width() const { return m_width; }
+    GC3Dsizei height() const { return m_height; }
 
-    bool isInitialized() const { return m_initialized; }
+    bool initialized() const { return m_initialized; }
     void setInitialized() { m_initialized = true; }
 
     bool hasEverBeenBound() const { return object() && m_hasEverBeenBound; }
diff --git a/Source/core/html/canvas/WebGLRenderingContext.cpp b/Source/core/html/canvas/WebGLRenderingContext.cpp
index a706605..6ae694c 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -103,26 +103,48 @@
 
 void WebGLRenderingContext::forciblyLoseOldestContext(const String& reason)
 {
-    if (activeContexts().size()) {
-        WebGLRenderingContext* oldestActiveContext = activeContexts().first();
-        activeContexts().remove(0);
+    size_t candidateID = oldestContextIndex();
+    if (candidateID >= activeContexts().size())
+        return;
 
-        oldestActiveContext->printWarningToConsole(reason);
-        InspectorInstrumentation::didFireWebGLWarning(oldestActiveContext->canvas());
+    WebGLRenderingContext* candidate = activeContexts()[candidateID];
 
-        // This will call deactivateContext once the context has actually been lost.
-        oldestActiveContext->forceLostContext(WebGLRenderingContext::SyntheticLostContext);
+    activeContexts().remove(candidateID);
+
+    candidate->printWarningToConsole(reason);
+    InspectorInstrumentation::didFireWebGLWarning(candidate->canvas());
+
+    // This will call deactivateContext once the context has actually been lost.
+    candidate->forceLostContext(WebGLRenderingContext::SyntheticLostContext);
+}
+
+size_t WebGLRenderingContext::oldestContextIndex()
+{
+    if (!activeContexts().size())
+        return maxGLActiveContexts;
+
+    WebGLRenderingContext* candidate = activeContexts().first();
+    size_t candidateID = 0;
+    for (size_t ii = 1; ii < activeContexts().size(); ++ii) {
+        WebGLRenderingContext* context = activeContexts()[ii];
+        if (context->graphicsContext3D() && candidate->graphicsContext3D() && context->graphicsContext3D()->lastFlushID() < candidate->graphicsContext3D()->lastFlushID()) {
+            candidate = context;
+            candidateID = ii;
+        }
     }
+
+    return candidateID;
 }
 
 IntSize WebGLRenderingContext::oldestContextSize()
 {
     IntSize size;
 
-    if (activeContexts().size()) {
-        WebGLRenderingContext* oldestActiveContext = activeContexts().first();
-        size.setWidth(oldestActiveContext->drawingBufferWidth());
-        size.setHeight(oldestActiveContext->drawingBufferHeight());
+    size_t candidateID = oldestContextIndex();
+    if (candidateID < activeContexts().size()) {
+        WebGLRenderingContext* candidate = activeContexts()[candidateID];
+        size.setWidth(candidate->drawingBufferWidth());
+        size.setHeight(candidate->drawingBufferHeight());
     }
 
     return size;
@@ -2070,7 +2092,7 @@
         return -1;
     if (isPrefixReserved(name))
         return -1;
-    if (!program->getLinkStatus()) {
+    if (!program->linkStatus()) {
         synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getAttribLocation", "program not linked");
         return 0;
     }
@@ -2469,7 +2491,7 @@
         m_context->getProgramiv(objectOrZero(program), pname, &value);
         return WebGLGetInfo(static_cast<bool>(value));
     case GraphicsContext3D::LINK_STATUS:
-        return WebGLGetInfo(program->getLinkStatus());
+        return WebGLGetInfo(program->linkStatus());
     case GraphicsContext3D::ATTACHED_SHADERS:
     case GraphicsContext3D::ACTIVE_ATTRIBUTES:
     case GraphicsContext3D::ACTIVE_UNIFORMS:
@@ -2524,7 +2546,7 @@
         }
         return WebGLGetInfo(value);
     case GraphicsContext3D::RENDERBUFFER_INTERNAL_FORMAT:
-        return WebGLGetInfo(m_renderbufferBinding->getInternalFormat());
+        return WebGLGetInfo(m_renderbufferBinding->internalFormat());
     default:
         synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getRenderbufferParameter", "invalid parameter name");
         return WebGLGetInfo();
@@ -2597,7 +2619,7 @@
         return String();
     if (!validateWebGLObject("getShaderSource", shader))
         return "";
-    return ensureNotNull(shader->getSource());
+    return ensureNotNull(shader->source());
 }
 
 Vector<String> WebGLRenderingContext::getSupportedExtensions()
@@ -2799,7 +2821,7 @@
         return 0;
     if (isPrefixReserved(name))
         return 0;
-    if (!program->getLinkStatus()) {
+    if (!program->linkStatus()) {
         synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getUniformLocation", "program not linked");
         return 0;
     }
@@ -3942,7 +3964,7 @@
         return;
     if (deleted)
         program = 0;
-    if (program && !program->getLinkStatus()) {
+    if (program && !program->linkStatus()) {
         synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "useProgram", "program not valid");
         return;
     }
@@ -4373,7 +4395,7 @@
 GC3Denum WebGLRenderingContext::getBoundFramebufferColorFormat()
 {
     if (m_framebufferBinding && m_framebufferBinding->object())
-        return m_framebufferBinding->getColorBufferFormat();
+        return m_framebufferBinding->colorBufferFormat();
     if (m_attributes.alpha)
         return GraphicsContext3D::RGBA;
     return GraphicsContext3D::RGB;
@@ -4382,14 +4404,14 @@
 int WebGLRenderingContext::getBoundFramebufferWidth()
 {
     if (m_framebufferBinding && m_framebufferBinding->object())
-        return m_framebufferBinding->getColorBufferWidth();
+        return m_framebufferBinding->colorBufferWidth();
     return m_drawingBuffer->size().width();
 }
 
 int WebGLRenderingContext::getBoundFramebufferHeight()
 {
     if (m_framebufferBinding && m_framebufferBinding->object())
-        return m_framebufferBinding->getColorBufferHeight();
+        return m_framebufferBinding->colorBufferHeight();
     return m_drawingBuffer->size().height();
 }
 
diff --git a/Source/core/html/canvas/WebGLRenderingContext.h b/Source/core/html/canvas/WebGLRenderingContext.h
index 386bb37..1d5fb82 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.h
+++ b/Source/core/html/canvas/WebGLRenderingContext.h
@@ -905,6 +905,9 @@
     static void deactivateContext(WebGLRenderingContext*, bool addToInactiveList);
     static void willDestroyContext(WebGLRenderingContext*);
     static void forciblyLoseOldestContext(const String& reason);
+    // Return the least recently used context's position in the active context vector.
+    // If the vector is empty, return the maximum allowed active context number.
+    static size_t oldestContextIndex();
     static IntSize oldestContextSize();
 };
 
diff --git a/Source/core/html/canvas/WebGLShader.h b/Source/core/html/canvas/WebGLShader.h
index e5864a7..6c776af 100644
--- a/Source/core/html/canvas/WebGLShader.h
+++ b/Source/core/html/canvas/WebGLShader.h
@@ -38,8 +38,8 @@
 
     static PassRefPtr<WebGLShader> create(WebGLRenderingContext*, GC3Denum);
 
-    GC3Denum getType() const { return m_type; }
-    const String& getSource() const { return m_source; }
+    GC3Denum type() const { return m_type; }
+    const String& source() const { return m_source; }
 
     void setSource(const String& source) { m_source = source; }
 
diff --git a/Source/core/html/canvas/WebGLUniformLocation.cpp b/Source/core/html/canvas/WebGLUniformLocation.cpp
index b87877b..2790c7e 100644
--- a/Source/core/html/canvas/WebGLUniformLocation.cpp
+++ b/Source/core/html/canvas/WebGLUniformLocation.cpp
@@ -41,14 +41,14 @@
 {
     ASSERT(m_program);
     ScriptWrappable::init(this);
-    m_linkCount = m_program->getLinkCount();
+    m_linkCount = m_program->linkCount();
 }
 
 WebGLProgram* WebGLUniformLocation::program() const
 {
     // If the program has been linked again, then this UniformLocation is no
     // longer valid.
-    if (m_program->getLinkCount() != m_linkCount)
+    if (m_program->linkCount() != m_linkCount)
         return 0;
     return m_program.get();
 }
@@ -57,7 +57,7 @@
 {
     // If the program has been linked again, then this UniformLocation is no
     // longer valid.
-    ASSERT(m_program->getLinkCount() == m_linkCount);
+    ASSERT(m_program->linkCount() == m_linkCount);
     return m_location;
 }
 
diff --git a/Source/core/html/forms/InputTypeView.cpp b/Source/core/html/forms/InputTypeView.cpp
index bbc1ba0..99e778b 100644
--- a/Source/core/html/forms/InputTypeView.cpp
+++ b/Source/core/html/forms/InputTypeView.cpp
@@ -57,10 +57,6 @@
 {
 }
 
-void InputTypeView::handleDOMActivateEvent(Event*)
-{
-}
-
 void InputTypeView::handleKeydownEvent(KeyboardEvent*)
 {
 }
diff --git a/Source/core/html/forms/InputTypeView.h b/Source/core/html/forms/InputTypeView.h
index 9614ade..2b880d0 100644
--- a/Source/core/html/forms/InputTypeView.h
+++ b/Source/core/html/forms/InputTypeView.h
@@ -78,7 +78,6 @@
     virtual void handleMouseDownEvent(MouseEvent*);
     virtual PassOwnPtr<ClickHandlingState> willDispatchClick();
     virtual void didDispatchClick(Event*, const ClickHandlingState&);
-    virtual void handleDOMActivateEvent(Event*);
     virtual void handleKeydownEvent(KeyboardEvent*);
     virtual void handleKeypressEvent(KeyboardEvent*);
     virtual void handleKeyupEvent(KeyboardEvent*);
diff --git a/Source/core/html/ime/Composition.cpp b/Source/core/html/ime/Composition.cpp
index cf313ad..9b40000 100644
--- a/Source/core/html/ime/Composition.cpp
+++ b/Source/core/html/ime/Composition.cpp
@@ -31,43 +31,27 @@
 #include "config.h"
 #include "core/html/ime/Composition.h"
 
-#include "core/html/ime/InputMethodContext.h"
-
 namespace WebCore {
 
 Composition::~Composition()
 {
 }
 
-PassRefPtr<Composition> Composition::create(InputMethodContext* context)
+PassRefPtr<Composition> Composition::create()
 {
-    return adoptRef(new Composition(context));
+    return adoptRef(new Composition());
 }
 
-Composition::Composition(InputMethodContext* context)
-    : m_inputMethodContext(context)
+Composition::Composition()
+    : m_selectionStart(0)
+    , m_selectionEnd(0)
 {
     ScriptWrappable::init(this);
 }
 
-String Composition::text() const
-{
-    return m_inputMethodContext->compositionText();
-}
-
-int Composition::selectionStart() const
-{
-    return m_inputMethodContext->selectionStart();
-}
-
-int Composition::selectionEnd() const
-{
-    return m_inputMethodContext->selectionEnd();
-}
-
 const Vector<unsigned>& Composition::getSegments() const
 {
-    return m_inputMethodContext->segments();
+    return m_segments;
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/ime/Composition.h b/Source/core/html/ime/Composition.h
index 0069969..a180c86 100644
--- a/Source/core/html/ime/Composition.h
+++ b/Source/core/html/ime/Composition.h
@@ -39,22 +39,29 @@
 
 namespace WebCore {
 
-class InputMethodContext;
-
 class Composition : public RefCounted<Composition>, public ScriptWrappable {
 public:
-    static PassRefPtr<Composition> create(InputMethodContext*);
+    static PassRefPtr<Composition> create();
     ~Composition();
 
-    String text() const;
-    int selectionStart() const;
-    int selectionEnd() const;
+    String text() const { return m_text; }
+    void setText(const String& text) { m_text = text; }
+
+    int selectionStart() const { return m_selectionStart; }
+    void setSelectionStart(int selectionStart) { selectionStart = m_selectionStart; }
+
+    int selectionEnd() const { return m_selectionEnd; }
+    void setSelectionEnd(int selectionEnd) { selectionEnd = m_selectionEnd; }
+
     const Vector<unsigned>& getSegments() const;
 
 private:
-    explicit Composition(InputMethodContext*);
+    Composition();
 
-    InputMethodContext* m_inputMethodContext;
+    String m_text;
+    int m_selectionStart;
+    int m_selectionEnd;
+    Vector<unsigned> m_segments;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/ime/InputMethodContext.cpp b/Source/core/html/ime/InputMethodContext.cpp
index 2ffdda0..8756006 100644
--- a/Source/core/html/ime/InputMethodContext.cpp
+++ b/Source/core/html/ime/InputMethodContext.cpp
@@ -31,7 +31,6 @@
 #include "config.h"
 #include "core/html/ime/InputMethodContext.h"
 
-#include "core/dom/Text.h"
 #include "core/editing/InputMethodController.h"
 #include "core/html/ime/Composition.h"
 #include "core/page/Frame.h"
@@ -44,7 +43,7 @@
 }
 
 InputMethodContext::InputMethodContext(HTMLElement* element)
-    : m_composition(Composition::create(this))
+    : m_composition(0)
     , m_element(element)
 {
     ScriptWrappable::init(this);
@@ -56,6 +55,8 @@
 
 Composition* InputMethodContext::composition() const
 {
+    // FIXME: Implement this. This should lazily update the composition object
+    // here.
     return m_composition.get();
 }
 
@@ -72,8 +73,15 @@
 
 void InputMethodContext::confirmComposition()
 {
-    if (hasFocus())
-        inputMethodController().confirmCompositionAndResetState();
+    Frame* frame = m_element->document().frame();
+    if (!frame)
+        return;
+
+    const Element* element = frame->document()->focusedElement();
+    if (!element || !element->isHTMLElement() || m_element != toHTMLElement(element))
+        return;
+
+    frame->inputMethodController().confirmCompositionAndResetState();
 }
 
 void InputMethodContext::setCaretRectangle(Node* anchor, int x, int y, int w, int h)
@@ -86,81 +94,4 @@
     // FIXME: Implement this.
 }
 
-bool InputMethodContext::hasFocus() const
-{
-    Frame* frame = m_element->document().frame();
-    if (!frame)
-        return false;
-
-    const Element* element = frame->document()->focusedElement();
-    return element && element->isHTMLElement() && m_element == toHTMLElement(element);
-}
-
-String InputMethodContext::compositionText() const
-{
-    if (!hasFocus())
-        return emptyString();
-
-    Text* text = inputMethodController().compositionNode();
-    return text ? text->wholeText() : emptyString();
-}
-
-CompositionUnderline InputMethodContext::selectedSegment() const
-{
-    CompositionUnderline underline;
-    if (!hasFocus())
-        return underline;
-
-    const InputMethodController& controller = inputMethodController();
-    if (!controller.hasComposition())
-        return underline;
-
-    Vector<CompositionUnderline> underlines = controller.customCompositionUnderlines();
-    for (size_t i = 0; i < underlines.size(); ++i) {
-        if (underlines[i].thick)
-            return underlines[i];
-    }
-
-    // When no underline information is available while composition exists,
-    // build a CompositionUnderline whose element is the whole composition.
-    underline.endOffset = controller.compositionEnd() - controller.compositionStart();
-    return underline;
-
-}
-
-int InputMethodContext::selectionStart() const
-{
-    return selectedSegment().startOffset;
-}
-
-int InputMethodContext::selectionEnd() const
-{
-    return selectedSegment().endOffset;
-}
-
-const Vector<unsigned>& InputMethodContext::segments()
-{
-    m_segments.clear();
-    if (!hasFocus())
-        return m_segments;
-    const InputMethodController& controller = inputMethodController();
-    if (!controller.hasComposition())
-        return m_segments;
-
-    Vector<CompositionUnderline> underlines = controller.customCompositionUnderlines();
-    if (!underlines.size()) {
-        m_segments.append(0);
-    } else {
-        for (size_t i = 0; i < underlines.size(); ++i)
-            m_segments.append(underlines[i].startOffset);
-    }
-
-    return m_segments;
-}
-
-InputMethodController& InputMethodContext::inputMethodController() const
-{
-    return m_element->document().frame()->inputMethodController();
-}
-
 } // namespace WebCore
diff --git a/Source/core/html/ime/InputMethodContext.h b/Source/core/html/ime/InputMethodContext.h
index 21999ad..e75be39 100644
--- a/Source/core/html/ime/InputMethodContext.h
+++ b/Source/core/html/ime/InputMethodContext.h
@@ -32,7 +32,6 @@
 #define InputMethodContext_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/editing/CompositionUnderline.h"
 #include "core/html/HTMLElement.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefPtr.h"
@@ -41,7 +40,6 @@
 namespace WebCore {
 
 class Composition;
-class InputMethodController;
 class Node;
 
 class InputMethodContext : public ScriptWrappable {
@@ -59,19 +57,9 @@
     void setCaretRectangle(Node* anchor, int x, int y, int w, int h);
     void setExclusionRectangle(Node* anchor, int x, int y, int w, int h);
 
-    String compositionText() const;
-    int selectionStart() const;
-    int selectionEnd() const;
-    const Vector<unsigned>& segments();
-
 private:
     InputMethodContext(HTMLElement*);
-    bool hasFocus() const;
-    CompositionUnderline selectedSegment() const;
-    InputMethodController& inputMethodController() const;
-
     RefPtr<Composition> m_composition;
-    Vector<unsigned> m_segments;
     HTMLElement* m_element;
 };
 
diff --git a/Source/core/html/parser/XSSAuditor.cpp b/Source/core/html/parser/XSSAuditor.cpp
index ccae51c..a7646ac 100644
--- a/Source/core/html/parser/XSSAuditor.cpp
+++ b/Source/core/html/parser/XSSAuditor.cpp
@@ -353,8 +353,8 @@
         didBlockScript |= filterEmbedToken(request);
     else if (hasName(request.token, appletTag))
         didBlockScript |= filterAppletToken(request);
-    else if (hasName(request.token, iframeTag))
-        didBlockScript |= filterIframeToken(request);
+    else if (hasName(request.token, iframeTag) || hasName(request.token, frameTag))
+        didBlockScript |= filterFrameToken(request);
     else if (hasName(request.token, metaTag))
         didBlockScript |= filterMetaToken(request);
     else if (hasName(request.token, baseTag))
@@ -460,10 +460,10 @@
     return didBlockScript;
 }
 
-bool XSSAuditor::filterIframeToken(const FilterTokenRequest& request)
+bool XSSAuditor::filterFrameToken(const FilterTokenRequest& request)
 {
     ASSERT(request.token.type() == HTMLToken::StartTag);
-    ASSERT(hasName(request.token, iframeTag));
+    ASSERT(hasName(request.token, iframeTag) || hasName(request.token, frameTag));
 
     bool didBlockScript = false;
     if (isContainedInRequest(decodedSnippetForName(request))) {
diff --git a/Source/core/html/parser/XSSAuditor.h b/Source/core/html/parser/XSSAuditor.h
index 25e326f..5249479 100644
--- a/Source/core/html/parser/XSSAuditor.h
+++ b/Source/core/html/parser/XSSAuditor.h
@@ -86,7 +86,7 @@
     bool filterParamToken(const FilterTokenRequest&);
     bool filterEmbedToken(const FilterTokenRequest&);
     bool filterAppletToken(const FilterTokenRequest&);
-    bool filterIframeToken(const FilterTokenRequest&);
+    bool filterFrameToken(const FilterTokenRequest&);
     bool filterMetaToken(const FilterTokenRequest&);
     bool filterBaseToken(const FilterTokenRequest&);
     bool filterFormToken(const FilterTokenRequest&);
diff --git a/Source/core/html/shadow/ShadowElementNames.cpp b/Source/core/html/shadow/ShadowElementNames.cpp
index 1c5421a..c62c6a7 100644
--- a/Source/core/html/shadow/ShadowElementNames.cpp
+++ b/Source/core/html/shadow/ShadowElementNames.cpp
@@ -59,6 +59,12 @@
     return name;
 }
 
+const AtomicString& placeholder()
+{
+    DEFINE_STATIC_LOCAL(AtomicString, name, ("placeholder", AtomicString::ConstructFromLiteral));
+    return name;
+}
+
 const AtomicString& searchDecoration()
 {
     DEFINE_STATIC_LOCAL(AtomicString, name, ("decoration", AtomicString::ConstructFromLiteral));
diff --git a/Source/core/html/shadow/ShadowElementNames.h b/Source/core/html/shadow/ShadowElementNames.h
index 6b5e54d..b3ef3cb 100644
--- a/Source/core/html/shadow/ShadowElementNames.h
+++ b/Source/core/html/shadow/ShadowElementNames.h
@@ -41,6 +41,7 @@
 const AtomicString& spinButton();
 const AtomicString& clearButton();
 const AtomicString& pickerIndicator();
+const AtomicString& placeholder();
 const AtomicString& searchDecoration();
 const AtomicString& sliderThumb();
 const AtomicString& sliderTrack();
diff --git a/Source/core/html/shadow/TextControlInnerElements.cpp b/Source/core/html/shadow/TextControlInnerElements.cpp
index fa833fe..90de6f9 100644
--- a/Source/core/html/shadow/TextControlInnerElements.cpp
+++ b/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -63,36 +63,38 @@
     return new RenderTextControlInnerContainer(this);
 }
 
-TextControlInnerElement::TextControlInnerElement(Document& document)
+// ---------------------------
+
+EditingViewPortElement::EditingViewPortElement(Document& document)
     : HTMLDivElement(divTag, document)
 {
     setHasCustomStyleCallbacks();
 }
 
-PassRefPtr<TextControlInnerElement> TextControlInnerElement::create(Document& document)
+PassRefPtr<EditingViewPortElement> EditingViewPortElement::create(Document& document)
 {
-    return adoptRef(new TextControlInnerElement(document));
+    return adoptRef(new EditingViewPortElement(document));
 }
 
-PassRefPtr<RenderStyle> TextControlInnerElement::customStyleForRenderer()
+PassRefPtr<RenderStyle> EditingViewPortElement::customStyleForRenderer()
 {
     // FXIME: Move these styles to html.css.
 
-    RefPtr<RenderStyle> innerBlockStyle = RenderStyle::create();
-    innerBlockStyle->inheritFrom(shadowHost()->renderStyle());
+    RefPtr<RenderStyle> style = RenderStyle::create();
+    style->inheritFrom(shadowHost()->renderStyle());
 
-    innerBlockStyle->setFlexGrow(1);
+    style->setFlexGrow(1);
     // min-width: 0; is needed for correct shrinking.
     // FIXME: Remove this line when https://bugs.webkit.org/show_bug.cgi?id=111790 is fixed.
-    innerBlockStyle->setMinWidth(Length(0, Fixed));
-    innerBlockStyle->setDisplay(BLOCK);
-    innerBlockStyle->setDirection(LTR);
+    style->setMinWidth(Length(0, Fixed));
+    style->setDisplay(BLOCK);
+    style->setDirection(LTR);
 
     // We don't want the shadow dom to be editable, so we set this block to
     // read-only in case the input itself is editable.
-    innerBlockStyle->setUserModify(READ_ONLY);
+    style->setUserModify(READ_ONLY);
 
-    return innerBlockStyle.release();
+    return style.release();
 }
 
 // ---------------------------
diff --git a/Source/core/html/shadow/TextControlInnerElements.h b/Source/core/html/shadow/TextControlInnerElements.h
index 1966330..5843c4d 100644
--- a/Source/core/html/shadow/TextControlInnerElements.h
+++ b/Source/core/html/shadow/TextControlInnerElements.h
@@ -43,12 +43,12 @@
     virtual RenderObject* createRenderer(RenderStyle*);
 };
 
-class TextControlInnerElement FINAL : public HTMLDivElement {
+class EditingViewPortElement FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<TextControlInnerElement> create(Document&);
+    static PassRefPtr<EditingViewPortElement> create(Document&);
 
 protected:
-    TextControlInnerElement(Document&);
+    EditingViewPortElement(Document&);
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
 
 private:
diff --git a/Source/core/html/track/WebVTTTokenizer.cpp b/Source/core/html/track/WebVTTTokenizer.cpp
index b2c30e7..f290cb6 100644
--- a/Source/core/html/track/WebVTTTokenizer.cpp
+++ b/Source/core/html/track/WebVTTTokenizer.cpp
@@ -83,8 +83,10 @@
             m_buffer.append(static_cast<LChar>(cc));
             WEBVTT_ADVANCE_TO(EscapeState);
         } else if (cc == '<') {
+            // FIXME: the explicit Vector conversion copies into a temporary
+            // and is wasteful.
             if (m_token->type() == WebVTTTokenTypes::Uninitialized
-                || vectorEqualsString<UChar>(m_token->characters(), emptyString()))
+                || vectorEqualsString<UChar>(Vector<UChar, 32>(m_token->characters()), emptyString()))
                 WEBVTT_ADVANCE_TO(TagState);
             else
                 return emitAndResumeIn(source, WebVTTTokenizerState::TagState);
diff --git a/Source/core/inspector/ConsoleAPITypes.h b/Source/core/inspector/ConsoleAPITypes.h
index 11f65ec..b36cdfe 100644
--- a/Source/core/inspector/ConsoleAPITypes.h
+++ b/Source/core/inspector/ConsoleAPITypes.h
@@ -38,7 +38,6 @@
     EndGroupMessageType,
     ClearMessageType,
     AssertMessageType,
-    TimingMessageType,
     ProfileMessageType,
     ProfileEndMessageType
 };
diff --git a/Source/core/inspector/ConsoleMessage.cpp b/Source/core/inspector/ConsoleMessage.cpp
index 7ce1741..0de574d 100644
--- a/Source/core/inspector/ConsoleMessage.cpp
+++ b/Source/core/inspector/ConsoleMessage.cpp
@@ -171,7 +171,6 @@
     case StartGroupCollapsedMessageType: return TypeBuilder::Console::ConsoleMessage::Type::StartGroupCollapsed;
     case EndGroupMessageType: return TypeBuilder::Console::ConsoleMessage::Type::EndGroup;
     case AssertMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Assert;
-    case TimingMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Timing;
     case ProfileMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Profile;
     case ProfileEndMessageType: return TypeBuilder::Console::ConsoleMessage::Type::ProfileEnd;
     }
diff --git a/Source/core/inspector/InspectorCSSAgent.cpp b/Source/core/inspector/InspectorCSSAgent.cpp
index e680633..fdace37 100644
--- a/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/Source/core/inspector/InspectorCSSAgent.cpp
@@ -977,13 +977,18 @@
     if (!element)
         return;
 
+    Element* originalElement = element;
+    PseudoId elementPseudoId = element->pseudoId();
+    if (elementPseudoId)
+        element = element->parentOrShadowHostElement();
+
     // Matched rules.
     StyleResolver* styleResolver = element->ownerDocument()->styleResolver();
-    RefPtr<CSSRuleList> matchedRules = styleResolver->styleRulesForElement(element, StyleResolver::AllCSSRules);
-    matchedCSSRules = buildArrayForMatchedRuleList(matchedRules.get(), styleResolver, element);
+    RefPtr<CSSRuleList> matchedRules = styleResolver->pseudoStyleRulesForElement(element, elementPseudoId, StyleResolver::AllCSSRules);
+    matchedCSSRules = buildArrayForMatchedRuleList(matchedRules.get(), styleResolver, originalElement);
 
     // Pseudo elements.
-    if (!includePseudo || *includePseudo) {
+    if (!elementPseudoId && (!includePseudo || *includePseudo)) {
         RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PseudoIdMatches> > pseudoElements = TypeBuilder::Array<TypeBuilder::CSS::PseudoIdMatches>::create();
         for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; pseudoId < AFTER_LAST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
             RefPtr<CSSRuleList> matchedRules = styleResolver->pseudoStyleRulesForElement(element, pseudoId, StyleResolver::AllCSSRules);
@@ -999,7 +1004,7 @@
     }
 
     // Inherited styles.
-    if (!includeInherited || *includeInherited) {
+    if (!elementPseudoId && (!includeInherited || *includeInherited)) {
         RefPtr<TypeBuilder::Array<TypeBuilder::CSS::InheritedStyleEntry> > entries = TypeBuilder::Array<TypeBuilder::CSS::InheritedStyleEntry>::create();
         Element* parentElement = element->parentElement();
         while (parentElement) {
@@ -1587,7 +1592,7 @@
     // Since the inspector wants to walk the parent chain, we construct the full wrappers here.
     // FIXME: This could be factored better. StyleResolver::styleRulesForElement should return a StyleRule vector, not a CSSRuleList.
     if (!rule->parentStyleSheet()) {
-        rule = styleResolver->inspectorCSSOMWrappers().getWrapperForRuleInSheets(rule->styleRule(), styleResolver->document().styleSheetCollections());
+        rule = styleResolver->inspectorCSSOMWrappers().getWrapperForRuleInSheets(rule->styleRule(), styleResolver->document().styleEngine());
         if (!rule)
             return 0;
     }
@@ -1614,6 +1619,18 @@
     return result.release();
 }
 
+static inline bool matchesPseudoElement(const CSSSelector* selector, PseudoId elementPseudoId)
+{
+    // According to http://www.w3.org/TR/css3-selectors/#pseudo-elements, "Only one pseudo-element may appear per selector."
+    // As such, check the last selector in the tag history.
+    for (; !selector->isLastInTagHistory(); ++selector) { }
+    PseudoId selectorPseudoId = selector->matchesPseudoElement() ? CSSSelector::pseudoId(selector->pseudoType()) : NOPSEUDO;
+
+    // FIXME: This only covers the case of matching pseudo-element selectors against PseudoElements.
+    // We should come up with a solution for matching pseudo-element selectors against ordinary Elements, too.
+    return selectorPseudoId == elementPseudoId;
+}
+
 PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > InspectorCSSAgent::buildArrayForMatchedRuleList(CSSRuleList* ruleList, StyleResolver* styleResolver, Element* element)
 {
     RefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > result = TypeBuilder::Array<TypeBuilder::CSS::RuleMatch>::create();
@@ -1628,15 +1645,20 @@
         RefPtr<TypeBuilder::Array<int> > matchingSelectors = TypeBuilder::Array<int>::create();
         const CSSSelectorList& selectorList = rule->styleRule()->selectorList();
         long index = 0;
+        PseudoId elementPseudoId = element->pseudoId();
         for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector)) {
-            bool matched = element->webkitMatchesSelector(selector->selectorText(), IGNORE_EXCEPTION);
+            const CSSSelector* firstTagHistorySelector = selector;
+            bool matched = false;
+            if (elementPseudoId)
+                matched = matchesPseudoElement(selector, elementPseudoId); // Modifies |selector|.
+            matched |= element->webkitMatchesSelector(firstTagHistorySelector->selectorText(), IGNORE_EXCEPTION);
             if (matched)
                 matchingSelectors->addItem(index);
             ++index;
         }
         RefPtr<TypeBuilder::CSS::RuleMatch> match = TypeBuilder::CSS::RuleMatch::create()
-            .setRule(ruleObject)
-            .setMatchingSelectors(matchingSelectors);
+            .setRule(ruleObject.release())
+            .setMatchingSelectors(matchingSelectors.release());
         result->addItem(match);
     }
 
diff --git a/Source/core/inspector/InspectorConsoleAgent.cpp b/Source/core/inspector/InspectorConsoleAgent.cpp
index 67b9261..8ad03e4 100644
--- a/Source/core/inspector/InspectorConsoleAgent.cpp
+++ b/Source/core/inspector/InspectorConsoleAgent.cpp
@@ -35,6 +35,7 @@
 #include "core/inspector/InjectedScriptHost.h"
 #include "core/inspector/InjectedScriptManager.h"
 #include "core/inspector/InspectorState.h"
+#include "core/inspector/InspectorTimelineAgent.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/inspector/ScriptArguments.h"
 #include "core/inspector/ScriptCallFrame.h"
@@ -62,8 +63,9 @@
 
 int InspectorConsoleAgent::s_enabledAgentCount = 0;
 
-InspectorConsoleAgent::InspectorConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
+InspectorConsoleAgent::InspectorConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorTimelineAgent* timelineAgent, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
     : InspectorBaseAgent<InspectorConsoleAgent>("Console", instrumentingAgents, state)
+    , m_timelineAgent(timelineAgent)
     , m_injectedScriptManager(injectedScriptManager)
     , m_frontend(0)
     , m_previousMessage(0)
@@ -191,7 +193,7 @@
     return result;
 }
 
-void InspectorConsoleAgent::startConsoleTiming(ScriptExecutionContext*, const String& title)
+void InspectorConsoleAgent::consoleTime(ScriptExecutionContext*, const String& title)
 {
     // Follow Firebug's behavior of requiring a title that is not null or
     // undefined for timing functions
@@ -201,7 +203,7 @@
     m_times.add(title, monotonicallyIncreasingTime());
 }
 
-void InspectorConsoleAgent::stopConsoleTiming(ScriptExecutionContext*, const String& title, PassRefPtr<ScriptCallStack> callStack)
+void InspectorConsoleAgent::consoleTimeEnd(ScriptExecutionContext*, const String& title, ScriptState* state)
 {
     // Follow Firebug's behavior of requiring a title that is not null or
     // undefined for timing functions
@@ -217,8 +219,17 @@
 
     double elapsed = monotonicallyIncreasingTime() - startTime;
     String message = title + String::format(": %.3fms", elapsed * 1000);
-    const ScriptCallFrame& lastCaller = callStack->at(0);
-    addMessageToConsole(ConsoleAPIMessageSource, TimingMessageType, DebugMessageLevel, message, lastCaller.sourceURL(), lastCaller.lineNumber(), lastCaller.columnNumber());
+    addMessageToConsole(ConsoleAPIMessageSource, LogMessageType, DebugMessageLevel, message, String(), 0, 0, state);
+}
+
+void InspectorConsoleAgent::consoleTimeline(ScriptExecutionContext* context, const String& title, ScriptState* state)
+{
+    m_timelineAgent->consoleTimeline(context, title, state);
+}
+
+void InspectorConsoleAgent::consoleTimelineEnd(ScriptExecutionContext* context, const String& title, ScriptState* state)
+{
+    m_timelineAgent->consoleTimelineEnd(context, title, state);
 }
 
 void InspectorConsoleAgent::consoleCount(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
diff --git a/Source/core/inspector/InspectorConsoleAgent.h b/Source/core/inspector/InspectorConsoleAgent.h
index 388a97a..a76b1b6 100644
--- a/Source/core/inspector/InspectorConsoleAgent.h
+++ b/Source/core/inspector/InspectorConsoleAgent.h
@@ -45,6 +45,7 @@
 class Frame;
 class InspectorFrontend;
 class InjectedScriptManager;
+class InspectorTimelineAgent;
 class InstrumentingAgents;
 class ResourceError;
 class ResourceLoader;
@@ -59,7 +60,7 @@
 class InspectorConsoleAgent : public InspectorBaseAgent<InspectorConsoleAgent>, public InspectorBackendDispatcher::ConsoleCommandHandler {
     WTF_MAKE_NONCOPYABLE(InspectorConsoleAgent);
 public:
-    InspectorConsoleAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*);
+    InspectorConsoleAgent(InstrumentingAgents*, InspectorTimelineAgent*, InspectorCompositeState*, InjectedScriptManager*);
     virtual ~InspectorConsoleAgent();
 
     virtual void enable(ErrorString*);
@@ -80,8 +81,11 @@
 
     Vector<unsigned> consoleMessageArgumentCounts();
 
-    void startConsoleTiming(ScriptExecutionContext*, const String& title);
-    void stopConsoleTiming(ScriptExecutionContext*, const String& title, PassRefPtr<ScriptCallStack>);
+    void consoleTime(ScriptExecutionContext*, const String& title);
+    void consoleTimeEnd(ScriptExecutionContext*, const String& title, ScriptState*);
+    void consoleTimeline(ScriptExecutionContext*, const String& title, ScriptState*);
+    void consoleTimelineEnd(ScriptExecutionContext*, const String& title, ScriptState*);
+
     void consoleCount(ScriptState*, PassRefPtr<ScriptArguments>);
 
     void frameWindowDiscarded(DOMWindow*);
@@ -101,6 +105,7 @@
 protected:
     void addConsoleMessage(PassOwnPtr<ConsoleMessage>);
 
+    InspectorTimelineAgent* m_timelineAgent;
     InjectedScriptManager* m_injectedScriptManager;
     InspectorFrontend::Console* m_frontend;
     ConsoleMessage* m_previousMessage;
diff --git a/Source/core/inspector/InspectorController.cpp b/Source/core/inspector/InspectorController.cpp
index fdb31a5..0d78760 100644
--- a/Source/core/inspector/InspectorController.cpp
+++ b/Source/core/inspector/InspectorController.cpp
@@ -117,7 +117,7 @@
 
     m_agents.append(PageRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), pageScriptDebugServer, page, pageAgent));
 
-    OwnPtr<InspectorConsoleAgent> consoleAgentPtr(PageConsoleAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), domAgent));
+    OwnPtr<InspectorConsoleAgent> consoleAgentPtr(PageConsoleAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), domAgent, m_timelineAgent));
     InspectorConsoleAgent* consoleAgent = consoleAgentPtr.get();
     m_agents.append(consoleAgentPtr.release());
 
diff --git a/Source/core/inspector/InspectorDOMAgent.cpp b/Source/core/inspector/InspectorDOMAgent.cpp
index 80b35fe..7426d72 100644
--- a/Source/core/inspector/InspectorDOMAgent.cpp
+++ b/Source/core/inspector/InspectorDOMAgent.cpp
@@ -48,6 +48,7 @@
 #include "core/dom/Node.h"
 #include "core/dom/NodeList.h"
 #include "core/dom/NodeTraversal.h"
+#include "core/dom/PseudoElement.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -359,6 +360,14 @@
     for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
         unbind(root, nodesMap);
 
+    if (node->isElementNode()) {
+        Element* element = toElement(node);
+        if (element->pseudoElement(BEFORE))
+            unbind(element->pseudoElement(BEFORE), nodesMap);
+        if (element->pseudoElement(AFTER))
+            unbind(element->pseudoElement(AFTER), nodesMap);
+    }
+
     nodesMap->remove(node);
     if (m_domListener)
         m_domListener->didRemoveDOMNode(node);
@@ -418,7 +427,12 @@
         return 0;
 
     if (node->isInShadowTree()) {
-        *errorString = "Can not edit nodes from shadow trees";
+        *errorString = "Cannot edit nodes from shadow trees";
+        return 0;
+    }
+
+    if (node->isPseudoElement()) {
+        *errorString = "Cannot edit pseudo elements";
         return 0;
     }
 
@@ -432,9 +446,15 @@
         return 0;
 
     if (element->isInShadowTree()) {
-        *errorString = "Can not edit elements from shadow trees";
+        *errorString = "Cannot edit elements from shadow trees";
         return 0;
     }
+
+    if (element->isPseudoElement()) {
+        *errorString = "Cannot edit pseudo elements";
+        return 0;
+    }
+
     return element;
 }
 
@@ -732,7 +752,7 @@
 
     ContainerNode* parentNode = node->parentNode();
     if (!parentNode) {
-        *errorString = "Can not remove detached node";
+        *errorString = "Cannot remove detached node";
         return;
     }
 
@@ -1480,6 +1500,23 @@
             value->setTemplateContent(buildObjectForNode(toHTMLTemplateElement(element)->content(), 0, nodesMap));
             forcePushChildren = true;
         }
+
+        switch (element->pseudoId()) {
+        case BEFORE:
+            value->setPseudoType(TypeBuilder::DOM::PseudoType::Before);
+            break;
+        case AFTER:
+            value->setPseudoType(TypeBuilder::DOM::PseudoType::After);
+            break;
+        default: {
+            RefPtr<TypeBuilder::Array<TypeBuilder::DOM::Node> > pseudoElements = buildArrayForPseudoElements(element, nodesMap);
+            if (pseudoElements) {
+                value->setPseudoElements(pseudoElements.release());
+                forcePushChildren = true;
+            }
+            break;
+        }
+        }
     } else if (node->isDocumentNode()) {
         Document* document = toDocument(node);
         value->setDocumentURL(documentURLString(document));
@@ -1589,6 +1626,19 @@
     return value.release();
 }
 
+PassRefPtr<TypeBuilder::Array<TypeBuilder::DOM::Node> > InspectorDOMAgent::buildArrayForPseudoElements(Element* element, NodeToIdMap* nodesMap)
+{
+    if (!element->pseudoElement(BEFORE) && !element->pseudoElement(AFTER))
+        return 0;
+
+    RefPtr<TypeBuilder::Array<TypeBuilder::DOM::Node> > pseudoElements = TypeBuilder::Array<TypeBuilder::DOM::Node>::create();
+    if (element->pseudoElement(BEFORE))
+        pseudoElements->addItem(buildObjectForNode(element->pseudoElement(BEFORE), 0, nodesMap));
+    if (element->pseudoElement(AFTER))
+        pseudoElements->addItem(buildObjectForNode(element->pseudoElement(AFTER), 0, nodesMap));
+    return pseudoElements.release();
+}
+
 Node* InspectorDOMAgent::innerFirstChild(Node* node)
 {
     node = node->firstChild();
@@ -1813,8 +1863,11 @@
         return;
 
     int hostId = m_documentNodeToIdMap.get(host);
-    if (hostId)
-        m_frontend->shadowRootPushed(hostId, buildObjectForNode(root, 0, &m_documentNodeToIdMap));
+    if (!hostId)
+        return;
+
+    pushChildNodesToFrontend(hostId, 1);
+    m_frontend->shadowRootPushed(hostId, buildObjectForNode(root, 0, &m_documentNodeToIdMap));
 }
 
 void InspectorDOMAgent::willPopShadowRoot(Element* host, ShadowRoot* root)
@@ -1844,6 +1897,35 @@
     setDocument(document);
 }
 
+void InspectorDOMAgent::pseudoElementCreated(PseudoElement* pseudoElement)
+{
+    Element* parent = pseudoElement->parentOrShadowHostElement();
+    if (!parent)
+        return;
+    int parentId = m_documentNodeToIdMap.get(parent);
+    if (!parentId)
+        return;
+
+    pushChildNodesToFrontend(parentId, 1);
+    m_frontend->pseudoElementAdded(parentId, buildObjectForNode(pseudoElement, 0, &m_documentNodeToIdMap));
+}
+
+void InspectorDOMAgent::pseudoElementDestroyed(PseudoElement* pseudoElement)
+{
+    int pseudoElementId = m_documentNodeToIdMap.get(pseudoElement);
+    if (!pseudoElementId)
+        return;
+
+    // If a PseudoElement is bound, its parent element must be bound, too.
+    Element* parent = pseudoElement->parentOrShadowHostElement();
+    ASSERT(parent);
+    int parentId = m_documentNodeToIdMap.get(parent);
+    ASSERT(parentId);
+
+    unbind(pseudoElement, &m_documentNodeToIdMap);
+    m_frontend->pseudoElementRemoved(parentId, pseudoElementId);
+}
+
 Node* InspectorDOMAgent::nodeForPath(const String& path)
 {
     // The path is of form "1,HTML,2,BODY,1,DIV"
diff --git a/Source/core/inspector/InspectorDOMAgent.h b/Source/core/inspector/InspectorDOMAgent.h
index ed92ab3..b70b4b0 100644
--- a/Source/core/inspector/InspectorDOMAgent.h
+++ b/Source/core/inspector/InspectorDOMAgent.h
@@ -172,6 +172,8 @@
     void didPushShadowRoot(Element* host, ShadowRoot*);
     void willPopShadowRoot(Element* host, ShadowRoot*);
     void frameDocumentUpdated(Frame*);
+    void pseudoElementCreated(PseudoElement*);
+    void pseudoElementDestroyed(PseudoElement*);
 
     int pushNodeToFrontend(ErrorString*, int documentNodeId, Node*);
     Node* nodeForId(int nodeId);
@@ -234,6 +236,7 @@
     PassRefPtr<TypeBuilder::Array<String> > buildArrayForElementAttributes(Element*);
     PassRefPtr<TypeBuilder::Array<TypeBuilder::DOM::Node> > buildArrayForContainerChildren(Node* container, int depth, NodeToIdMap* nodesMap);
     PassRefPtr<TypeBuilder::DOM::EventListener> buildObjectForEventListener(const RegisteredEventListener&, const AtomicString& eventType, Node*, const String* objectGroupId);
+    PassRefPtr<TypeBuilder::Array<TypeBuilder::DOM::Node> > buildArrayForPseudoElements(Element*, NodeToIdMap* nodesMap);
 
     Node* nodeForPath(const String& path);
 
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.cpp b/Source/core/inspector/InspectorIndexedDBAgent.cpp
index bd5a454..b6c1bde 100644
--- a/Source/core/inspector/InspectorIndexedDBAgent.cpp
+++ b/Source/core/inspector/InspectorIndexedDBAgent.cpp
@@ -618,7 +618,7 @@
         return;
 
     // FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
-    v8::HandleScope handleScope(frame->script()->isolate());
+    v8::HandleScope handleScope(toIsolate(frame));
     v8::Handle<v8::Context> context = document->frame()->script()->mainWorldContext();
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
@@ -643,7 +643,7 @@
         return;
 
     // FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
-    v8::HandleScope handleScope(frame->script()->isolate());
+    v8::HandleScope handleScope(toIsolate(frame));
     v8::Handle<v8::Context> context = document->frame()->script()->mainWorldContext();
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
@@ -671,7 +671,7 @@
     }
 
     // FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
-    v8::HandleScope handleScope(frame->script()->isolate());
+    v8::HandleScope handleScope(toIsolate(frame));
     v8::Handle<v8::Context> context = document->frame()->script()->mainWorldContext();
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
@@ -775,7 +775,7 @@
         return;
 
     // FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
-    v8::HandleScope handleScope(frame->script()->isolate());
+    v8::HandleScope handleScope(toIsolate(frame));
     v8::Handle<v8::Context> context = document->frame()->script()->mainWorldContext();
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
diff --git a/Source/core/inspector/InspectorInstrumentation.idl b/Source/core/inspector/InspectorInstrumentation.idl
index b706ee5..eadbef4 100644
--- a/Source/core/inspector/InspectorInstrumentation.idl
+++ b/Source/core/inspector/InspectorInstrumentation.idl
@@ -61,6 +61,9 @@
 */
 
 interface InspectorInstrumentation {
+
+#include "core/dom/PseudoElement.h"
+
     [Page, Inspector, PageDebugger, PageRuntime]
     void didClearWindowObjectInWorld([Keep] Frame*, DOMWrapperWorld*);
 
@@ -434,6 +437,12 @@
 
     [LayerTree]
     void layerTreeDidChange(Page*);
+
+    [DOM, Inline=FastReturn]
+    void pseudoElementCreated([Keep] PseudoElement*);
+
+    [DOM, Inline=FastReturn]
+    void pseudoElementDestroyed([Keep] PseudoElement*);
 }
 
 interface InspectorConsoleInstrumentation {
@@ -458,16 +467,19 @@
     void consoleCount(ScriptExecutionContext* context, ScriptState* state, PassRefPtr<ScriptArguments> arguments);
 
     [Timeline, Console]
-    void startConsoleTiming([Keep] ScriptExecutionContext* context, const String& title);
+    void consoleTime([Keep] ScriptExecutionContext* context, const String& title);
 
     [Console, Timeline]
-    void stopConsoleTiming([Keep] ScriptExecutionContext* context, const String& title, PassRefPtr<ScriptCallStack> stack);
+    void consoleTimeEnd([Keep] ScriptExecutionContext* context, const String& title, ScriptState* state);
 
     [Timeline, Inline=FastReturn]
-    void consoleTimeStamp([Keep] ScriptExecutionContext* context, PassRefPtr<ScriptArguments> arguments);
+    void consoleTimeStamp([Keep] ScriptExecutionContext* context, const String& title);
 
-    [Profiler]
-    void addStartProfilingMessageToConsole(ScriptExecutionContext* context, const String& title, unsigned lineNumber, const String& sourceURL);
+    [Console, Inline=FastReturn]
+    void consoleTimeline([Keep] ScriptExecutionContext* context, const String& title, ScriptState* state);
+
+    [Console, Inline=FastReturn]
+    void consoleTimelineEnd([Keep] ScriptExecutionContext* context, const String& title, ScriptState* state);
 
     [Profiler]
     void addProfile(ScriptExecutionContext* context, PassRefPtr<ScriptProfile> profile, PassRefPtr<ScriptCallStack> callStack);
diff --git a/Source/core/inspector/InspectorOverlay.cpp b/Source/core/inspector/InspectorOverlay.cpp
index e970566..cb81f13 100644
--- a/Source/core/inspector/InspectorOverlay.cpp
+++ b/Source/core/inspector/InspectorOverlay.cpp
@@ -633,7 +633,7 @@
     DocumentWriter* writer = loader->activeDocumentLoader()->beginWriting("text/html", "UTF-8");
     writer->addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
     loader->activeDocumentLoader()->endWriting(writer);
-    v8::Isolate* isolate = frame->script()->isolate();
+    v8::Isolate* isolate = toIsolate(frame.get());
     v8::HandleScope handleScope(isolate);
     v8::Handle<v8::Context> frameContext = frame->script()->currentWorldContext();
     v8::Context::Scope contextScope(frameContext);
diff --git a/Source/core/inspector/InspectorProfilerAgent.cpp b/Source/core/inspector/InspectorProfilerAgent.cpp
index 4af9715..e842474 100644
--- a/Source/core/inspector/InspectorProfilerAgent.cpp
+++ b/Source/core/inspector/InspectorProfilerAgent.cpp
@@ -101,13 +101,6 @@
     m_consoleAgent->addMessageToConsole(ConsoleAPIMessageSource, ProfileEndMessageType, DebugMessageLevel, message, sourceURL, lineNumber);
 }
 
-void InspectorProfilerAgent::addStartProfilingMessageToConsole(const String& title, unsigned lineNumber, const String& sourceURL)
-{
-    if (!m_frontend)
-        return;
-    m_consoleAgent->addMessageToConsole(ConsoleAPIMessageSource, ProfileMessageType, DebugMessageLevel, title, sourceURL, lineNumber);
-}
-
 PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::createProfileHeader(const ScriptProfile& profile)
 {
     return TypeBuilder::Profiler::ProfileHeader::create()
@@ -227,7 +220,6 @@
     m_recordingCPUProfile = true;
     String title = getCurrentUserInitiatedProfileName(true);
     ScriptProfiler::start(title);
-    addStartProfilingMessageToConsole(title, 0, String());
     toggleRecordButton(true);
     m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, true);
 }
diff --git a/Source/core/inspector/InspectorProfilerAgent.h b/Source/core/inspector/InspectorProfilerAgent.h
index 3308c1e..42fe08b 100644
--- a/Source/core/inspector/InspectorProfilerAgent.h
+++ b/Source/core/inspector/InspectorProfilerAgent.h
@@ -57,7 +57,6 @@
 
     void addProfile(PassRefPtr<ScriptProfile> prpProfile, PassRefPtr<ScriptCallStack>);
     void addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile>, unsigned lineNumber, const String& sourceURL);
-    void addStartProfilingMessageToConsole(const String& title, unsigned lineNumber, const String& sourceURL);
     virtual void clearProfiles(ErrorString*);
 
     virtual void enable(ErrorString*);
diff --git a/Source/core/inspector/InspectorTimelineAgent.cpp b/Source/core/inspector/InspectorTimelineAgent.cpp
index 96b6414..8ccb28e 100644
--- a/Source/core/inspector/InspectorTimelineAgent.cpp
+++ b/Source/core/inspector/InspectorTimelineAgent.cpp
@@ -48,6 +48,7 @@
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
+#include "core/page/PageConsole.h"
 #include "core/platform/MemoryUsageSupport.h"
 #include "core/platform/chromium/TraceEvent.h"
 #include "core/platform/network/ResourceRequest.h"
@@ -60,7 +61,9 @@
 namespace WebCore {
 
 namespace TimelineAgentState {
-static const char timelineAgentEnabled[] = "timelineAgentEnabled";
+static const char enabled[] = "enabled";
+static const char started[] = "started";
+static const char startedFromProtocol[] = "startedFromProtocol";
 static const char timelineMaxCallStackDepth[] = "timelineMaxCallStackDepth";
 static const char includeDomCounters[] = "includeDomCounters";
 static const char includeNativeMemoryStatistics[] = "includeNativeMemoryStatistics";
@@ -189,25 +192,44 @@
 {
     ErrorString error;
     stop(&error);
+    disable(&error);
     releaseNodeIds();
     m_frontend = 0;
 }
 
 void InspectorTimelineAgent::restore()
 {
-    if (m_state->getBoolean(TimelineAgentState::timelineAgentEnabled)) {
-        m_maxCallStackDepth = m_state->getLong(TimelineAgentState::timelineMaxCallStackDepth);
-        ErrorString error;
-        bool includeDomCounters = m_state->getBoolean(TimelineAgentState::includeDomCounters);
-        bool includeNativeMemoryStatistics = m_state->getBoolean(TimelineAgentState::includeNativeMemoryStatistics);
-        start(&error, &m_maxCallStackDepth, &includeDomCounters, &includeNativeMemoryStatistics);
+    if (m_state->getBoolean(TimelineAgentState::startedFromProtocol)) {
+        innerStart();
+    } else if (isStarted()) {
+        // Timeline was started from console.timeline, it is not restored.
+        // Tell front-end timline is no longer collecting.
+        m_state->setBoolean(TimelineAgentState::started, false);
+        bool fromConsole = true;
+        m_frontend->stopped(&fromConsole);
     }
 }
 
-void InspectorTimelineAgent::start(ErrorString*, const int* maxCallStackDepth, const bool* includeDomCounters, const bool* includeNativeMemoryStatistics)
+void InspectorTimelineAgent::enable(ErrorString*)
+{
+    m_state->setBoolean(TimelineAgentState::enabled, true);
+}
+
+void InspectorTimelineAgent::disable(ErrorString*)
+{
+    m_state->setBoolean(TimelineAgentState::enabled, false);
+}
+
+void InspectorTimelineAgent::start(ErrorString* errorString, const int* maxCallStackDepth, const bool* includeDomCounters, const bool* includeNativeMemoryStatistics)
 {
     if (!m_frontend)
         return;
+    m_state->setBoolean(TimelineAgentState::startedFromProtocol, true);
+
+    if (isStarted()) {
+        *errorString = "Timeline is already started";
+        return;
+    }
 
     releaseNodeIds();
     if (maxCallStackDepth && *maxCallStackDepth >= 0)
@@ -217,19 +239,40 @@
     m_state->setLong(TimelineAgentState::timelineMaxCallStackDepth, m_maxCallStackDepth);
     m_state->setBoolean(TimelineAgentState::includeDomCounters, includeDomCounters && *includeDomCounters);
     m_state->setBoolean(TimelineAgentState::includeNativeMemoryStatistics, includeNativeMemoryStatistics && *includeNativeMemoryStatistics);
-    m_timeConverter.reset();
 
+    innerStart();
+    bool fromConsole = false;
+    m_frontend->started(&fromConsole);
+}
+
+bool InspectorTimelineAgent::isStarted()
+{
+    return m_state->getBoolean(TimelineAgentState::started);
+}
+
+void InspectorTimelineAgent::innerStart()
+{
+    m_state->setBoolean(TimelineAgentState::started, true);
+    m_timeConverter.reset();
     m_instrumentingAgents->setInspectorTimelineAgent(this);
     ScriptGCEvent::addEventListener(this);
-    m_state->setBoolean(TimelineAgentState::timelineAgentEnabled, true);
     if (m_client && m_pageAgent)
         m_traceEventProcessor = adoptRef(new TimelineTraceEventProcessor(m_weakFactory.createWeakPtr(), m_client));
 }
 
-void InspectorTimelineAgent::stop(ErrorString*)
+void InspectorTimelineAgent::stop(ErrorString* errorString)
 {
-    if (!m_state->getBoolean(TimelineAgentState::timelineAgentEnabled))
+    m_state->setBoolean(TimelineAgentState::startedFromProtocol, false);
+    if (!isStarted()) {
+        *errorString = "Timeline was not started";
         return;
+    }
+    innerStop(false);
+}
+
+void InspectorTimelineAgent::innerStop(bool fromConsole)
+{
+    m_state->setBoolean(TimelineAgentState::started, false);
 
     if (m_traceEventProcessor) {
         m_traceEventProcessor->shutdown();
@@ -242,7 +285,13 @@
     clearRecordStack();
     m_gcEvents.clear();
 
-    m_state->setBoolean(TimelineAgentState::timelineAgentEnabled, false);
+    for (size_t i = 0; i < m_consoleTimelines.size(); ++i) {
+        String message = String::format("Timeline '%s' terminated.", m_consoleTimelines[i].utf8().data());
+        page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message);
+    }
+    m_consoleTimelines.clear();
+
+    m_frontend->stopped(&fromConsole);
 }
 
 void InspectorTimelineAgent::didBeginFrame()
@@ -566,23 +615,56 @@
     didFinishLoadingResource(identifier, true, 0, loader->frame());
 }
 
-void InspectorTimelineAgent::consoleTimeStamp(ScriptExecutionContext* context, PassRefPtr<ScriptArguments> arguments)
+void InspectorTimelineAgent::consoleTimeStamp(ScriptExecutionContext* context, const String& title)
 {
-    String message;
-    arguments->getFirstArgumentAsString(message);
-    appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeStamp, true, frameForScriptExecutionContext(context));
+    appendRecord(TimelineRecordFactory::createTimeStampData(title), TimelineRecordType::TimeStamp, true, frameForScriptExecutionContext(context));
 }
 
-void InspectorTimelineAgent::startConsoleTiming(ScriptExecutionContext* context, const String& message)
+void InspectorTimelineAgent::consoleTime(ScriptExecutionContext* context, const String& message)
 {
     appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::Time, true, frameForScriptExecutionContext(context));
 }
 
-void InspectorTimelineAgent::stopConsoleTiming(ScriptExecutionContext* context, const String& message, PassRefPtr<ScriptCallStack> stack)
+void InspectorTimelineAgent::consoleTimeEnd(ScriptExecutionContext* context, const String& message, ScriptState*)
 {
     appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeEnd, true, frameForScriptExecutionContext(context));
 }
 
+void InspectorTimelineAgent::consoleTimeline(ScriptExecutionContext* context, const String& title, ScriptState* state)
+{
+    if (!m_state->getBoolean(TimelineAgentState::enabled))
+        return;
+
+    String message = String::format("Timeline '%s' started.", title.utf8().data());
+    page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
+    m_consoleTimelines.append(title);
+    if (!isStarted()) {
+        innerStart();
+        bool fromConsole = true;
+        m_frontend->started(&fromConsole);
+    }
+    appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeStamp, true, frameForScriptExecutionContext(context));
+}
+
+void InspectorTimelineAgent::consoleTimelineEnd(ScriptExecutionContext* context, const String& title, ScriptState* state)
+{
+    if (!m_state->getBoolean(TimelineAgentState::enabled))
+        return;
+
+    size_t index = m_consoleTimelines.find(title);
+    if (index == notFound) {
+        String message = String::format("Timeline '%s' was not started.", title.utf8().data());
+        page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
+        return;
+    }
+
+    String message = String::format("Timeline '%s' finished.", title.utf8().data());
+    appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeStamp, true, frameForScriptExecutionContext(context));
+    m_consoleTimelines.remove(index);
+    if (!m_consoleTimelines.size() && isStarted() && !m_state->getBoolean(TimelineAgentState::startedFromProtocol))
+        innerStop(true);
+    page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
+}
 
 void InspectorTimelineAgent::domContentLoadedEventFired(Frame* frame)
 {
diff --git a/Source/core/inspector/InspectorTimelineAgent.h b/Source/core/inspector/InspectorTimelineAgent.h
index 769f34f..425090e 100644
--- a/Source/core/inspector/InspectorTimelineAgent.h
+++ b/Source/core/inspector/InspectorTimelineAgent.h
@@ -71,6 +71,7 @@
 class ScriptArguments;
 class ScriptCallStack;
 class ScriptExecutionContext;
+class ScriptState;
 class TimelineTraceEventProcessor;
 class WebSocketHandshakeRequest;
 class WebSocketHandshakeResponse;
@@ -117,6 +118,8 @@
     virtual void clearFrontend();
     virtual void restore();
 
+    virtual void enable(ErrorString*);
+    virtual void disable(ErrorString*);
     virtual void start(ErrorString*, const int* maxCallStackDepth, const bool* includeDomCounters, const bool* includeNativeMemoryStatistics);
     virtual void stop(ErrorString*);
 
@@ -175,12 +178,14 @@
     bool willEvaluateScript(Frame*, const String&, int);
     void didEvaluateScript();
 
-    void consoleTimeStamp(ScriptExecutionContext*, PassRefPtr<ScriptArguments>);
+    void consoleTimeStamp(ScriptExecutionContext*, const String& title);
     void domContentLoadedEventFired(Frame*);
     void loadEventFired(Frame*);
 
-    void startConsoleTiming(ScriptExecutionContext*, const String&);
-    void stopConsoleTiming(ScriptExecutionContext*, const String&, PassRefPtr<ScriptCallStack>);
+    void consoleTime(ScriptExecutionContext*, const String&);
+    void consoleTimeEnd(ScriptExecutionContext*, const String&, ScriptState*);
+    void consoleTimeline(ScriptExecutionContext*, const String& title, ScriptState*);
+    void consoleTimelineEnd(ScriptExecutionContext*, const String& title, ScriptState*);
 
     void didScheduleResourceRequest(Document*, const String& url);
     void willSendRequest(unsigned long, DocumentLoader*, const ResourceRequest&, const ResourceResponse&, const FetchInitiatorInfo&);
@@ -259,6 +264,10 @@
     double timestamp();
     Page* page();
 
+    bool isStarted();
+    void innerStart();
+    void innerStop(bool fromConsole);
+
     InspectorPageAgent* m_pageAgent;
     InspectorMemoryAgent* m_memoryAgent;
     InspectorDOMAgent* m_domAgent;
@@ -291,6 +300,7 @@
     unsigned m_styleRecalcElementCounter;
     int m_layerTreeId;
     RenderImage* m_imageBeingPainted;
+    Vector<String> m_consoleTimelines;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/JavaScriptCallFrame.cpp b/Source/core/inspector/JavaScriptCallFrame.cpp
index d82e8af..abc5d83 100644
--- a/Source/core/inspector/JavaScriptCallFrame.cpp
+++ b/Source/core/inspector/JavaScriptCallFrame.cpp
@@ -36,9 +36,9 @@
 namespace WebCore {
 
 JavaScriptCallFrame::JavaScriptCallFrame(v8::Handle<v8::Context> debuggerContext, v8::Handle<v8::Object> callFrame)
-    : m_debuggerContext(debuggerContext)
-    , m_callFrame(callFrame)
-    , m_isolate(v8::Isolate::GetCurrent())
+    : m_isolate(v8::Isolate::GetCurrent())
+    , m_debuggerContext(m_isolate, debuggerContext)
+    , m_callFrame(m_isolate, callFrame)
 {
     ScriptWrappable::init(this);
 }
@@ -150,7 +150,7 @@
     v8::Handle<v8::Object> callFrame = m_callFrame.newLocal(m_isolate);
     v8::Handle<v8::Function> setVariableValueFunction = v8::Handle<v8::Function>::Cast(callFrame->Get(v8::String::NewSymbol("setVariableValue")));
     v8::Handle<v8::Value> argv[] = {
-        v8::Handle<v8::Value>(v8::Integer::New(scopeNumber)),
+        v8::Handle<v8::Value>(v8::Integer::New(scopeNumber, m_isolate)),
         v8String(variableName, m_isolate),
         newValue
     };
diff --git a/Source/core/inspector/JavaScriptCallFrame.h b/Source/core/inspector/JavaScriptCallFrame.h
index af95698..62aec90 100644
--- a/Source/core/inspector/JavaScriptCallFrame.h
+++ b/Source/core/inspector/JavaScriptCallFrame.h
@@ -67,10 +67,10 @@
 private:
     JavaScriptCallFrame(v8::Handle<v8::Context> debuggerContext, v8::Handle<v8::Object> callFrame);
 
+    v8::Isolate* m_isolate;
     RefPtr<JavaScriptCallFrame> m_caller;
     ScopedPersistent<v8::Context> m_debuggerContext;
     ScopedPersistent<v8::Object> m_callFrame;
-    v8::Isolate* m_isolate;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/PageConsoleAgent.cpp b/Source/core/inspector/PageConsoleAgent.cpp
index e5edadf..8418b37 100644
--- a/Source/core/inspector/PageConsoleAgent.cpp
+++ b/Source/core/inspector/PageConsoleAgent.cpp
@@ -39,8 +39,8 @@
 
 namespace WebCore {
 
-PageConsoleAgent::PageConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, InspectorDOMAgent* domAgent)
-    : InspectorConsoleAgent(instrumentingAgents, state, injectedScriptManager)
+PageConsoleAgent::PageConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, InspectorDOMAgent* domAgent, InspectorTimelineAgent* timelineAgent)
+    : InspectorConsoleAgent(instrumentingAgents, timelineAgent, state, injectedScriptManager)
     , m_inspectorDOMAgent(domAgent)
 {
 }
diff --git a/Source/core/inspector/PageConsoleAgent.h b/Source/core/inspector/PageConsoleAgent.h
index ed9f713..4cca695 100644
--- a/Source/core/inspector/PageConsoleAgent.h
+++ b/Source/core/inspector/PageConsoleAgent.h
@@ -41,16 +41,16 @@
 class PageConsoleAgent : public InspectorConsoleAgent {
     WTF_MAKE_NONCOPYABLE(PageConsoleAgent);
 public:
-    static PassOwnPtr<PageConsoleAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, InspectorDOMAgent* domAgent)
+    static PassOwnPtr<PageConsoleAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, InspectorDOMAgent* domAgent, InspectorTimelineAgent* timelineAgent)
     {
-        return adoptPtr(new PageConsoleAgent(instrumentingAgents, state, injectedScriptManager, domAgent));
+        return adoptPtr(new PageConsoleAgent(instrumentingAgents, state, injectedScriptManager, domAgent, timelineAgent));
     }
     virtual ~PageConsoleAgent();
 
     virtual bool isWorkerAgent() OVERRIDE { return false; }
 
 private:
-    PageConsoleAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, InspectorDOMAgent*);
+    PageConsoleAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, InspectorDOMAgent*, InspectorTimelineAgent*);
     virtual void clearMessages(ErrorString*);
     virtual void addInspectedNode(ErrorString*, int nodeId);
 
diff --git a/Source/core/inspector/ScriptArguments.cpp b/Source/core/inspector/ScriptArguments.cpp
index 175f4eb..6c5ac58 100644
--- a/Source/core/inspector/ScriptArguments.cpp
+++ b/Source/core/inspector/ScriptArguments.cpp
@@ -77,7 +77,7 @@
         return false;
     }
 
-    result = value.toString(globalState());
+    result = value.toString();
     return true;
 }
 
diff --git a/Source/core/inspector/WorkerConsoleAgent.cpp b/Source/core/inspector/WorkerConsoleAgent.cpp
index 2dda5ba..f6b912a 100644
--- a/Source/core/inspector/WorkerConsoleAgent.cpp
+++ b/Source/core/inspector/WorkerConsoleAgent.cpp
@@ -34,8 +34,8 @@
 
 namespace WebCore {
 
-WorkerConsoleAgent::WorkerConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
-    : InspectorConsoleAgent(instrumentingAgents, state, injectedScriptManager)
+WorkerConsoleAgent::WorkerConsoleAgent(InstrumentingAgents* instrumentingAgents, InspectorTimelineAgent* timelineAgent, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
+    : InspectorConsoleAgent(instrumentingAgents, timelineAgent, state, injectedScriptManager)
 {
 }
 
diff --git a/Source/core/inspector/WorkerConsoleAgent.h b/Source/core/inspector/WorkerConsoleAgent.h
index 24f72eb..e886da7 100644
--- a/Source/core/inspector/WorkerConsoleAgent.h
+++ b/Source/core/inspector/WorkerConsoleAgent.h
@@ -39,16 +39,16 @@
 class WorkerConsoleAgent : public InspectorConsoleAgent {
     WTF_MAKE_NONCOPYABLE(WorkerConsoleAgent);
 public:
-    static PassOwnPtr<WorkerConsoleAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
+    static PassOwnPtr<WorkerConsoleAgent> create(InstrumentingAgents* instrumentingAgents, InspectorTimelineAgent* timelineAgent, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager)
     {
-        return adoptPtr(new WorkerConsoleAgent(instrumentingAgents, state, injectedScriptManager));
+        return adoptPtr(new WorkerConsoleAgent(instrumentingAgents, timelineAgent, state, injectedScriptManager));
     }
     virtual ~WorkerConsoleAgent();
 
     virtual bool isWorkerAgent() OVERRIDE { return true; }
 
 private:
-    WorkerConsoleAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*);
+    WorkerConsoleAgent(InstrumentingAgents*, InspectorTimelineAgent*, InspectorCompositeState*, InjectedScriptManager*);
     virtual void addInspectedNode(ErrorString*, int nodeId);
 };
 
diff --git a/Source/core/inspector/WorkerInspectorController.cpp b/Source/core/inspector/WorkerInspectorController.cpp
index a1b200f..6761fd7 100644
--- a/Source/core/inspector/WorkerInspectorController.cpp
+++ b/Source/core/inspector/WorkerInspectorController.cpp
@@ -97,12 +97,13 @@
 {
     m_agents.append(WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), m_debugServer.get(), workerGlobalScope));
 
-    OwnPtr<InspectorConsoleAgent> consoleAgent = WorkerConsoleAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get());
+    OwnPtr<InspectorTimelineAgent> timelineAgent = InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, 0, 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0);
+    OwnPtr<InspectorConsoleAgent> consoleAgent = WorkerConsoleAgent::create(m_instrumentingAgents.get(), timelineAgent.get(), m_state.get(), m_injectedScriptManager.get());
     m_agents.append(WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_debugServer.get(), workerGlobalScope, m_injectedScriptManager.get()));
 
     m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent.get(), m_state.get(), m_injectedScriptManager.get()));
     m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()));
-    m_agents.append(InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, 0, 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0));
+    m_agents.append(timelineAgent.release());
     m_agents.append(consoleAgent.release());
 
     m_injectedScriptManager->injectedScriptHost()->init(m_instrumentingAgents.get(), m_debugServer.get());
diff --git a/Source/core/loader/DocumentLoader.cpp b/Source/core/loader/DocumentLoader.cpp
index 29bea9b..11f05e2 100644
--- a/Source/core/loader/DocumentLoader.cpp
+++ b/Source/core/loader/DocumentLoader.cpp
@@ -609,7 +609,7 @@
 
     // If we are sending data to MediaDocument, we should stop here
     // and cancel the request.
-    if (m_frame->document()->isMediaDocument())
+    if (m_frame && m_frame->document()->isMediaDocument())
         cancelMainResourceLoad(ResourceError::cancelledError(m_request.url()));
 }
 
diff --git a/Source/core/loader/EmptyClients.h b/Source/core/loader/EmptyClients.h
index ab07244..5e9e860 100644
--- a/Source/core/loader/EmptyClients.h
+++ b/Source/core/loader/EmptyClients.h
@@ -248,6 +248,7 @@
     virtual WebKit::WebCookieJar* cookieJar() const { return 0; }
 
     virtual void didRequestAutocomplete(PassRefPtr<FormState>) OVERRIDE;
+    virtual WebKit::WebNavigationControllerRegistry* navigationControllerRegistry() OVERRIDE { return 0; }
 };
 
 class EmptyTextCheckerClient : public TextCheckerClient {
diff --git a/Source/core/loader/FrameLoader.cpp b/Source/core/loader/FrameLoader.cpp
index c4c0412..2f6869d 100644
--- a/Source/core/loader/FrameLoader.cpp
+++ b/Source/core/loader/FrameLoader.cpp
@@ -726,7 +726,7 @@
     if (!prepareRequestForThisFrame(request))
         return;
 
-    Frame* targetFrame = findFrameForNavigation(request.frameName(), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
+    RefPtr<Frame> targetFrame = findFrameForNavigation(request.frameName(), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
     if (targetFrame && targetFrame != m_frame) {
         request.setFrameName("_self");
         targetFrame->loader()->load(request);
@@ -737,7 +737,7 @@
 
     FrameLoadType newLoadType = determineFrameLoadType(request);
     NavigationAction action(request.resourceRequest(), newLoadType, request.formState(), request.triggeringEvent());
-    if (shouldOpenInNewWindow(targetFrame, request, action)) {
+    if (shouldOpenInNewWindow(targetFrame.get(), request, action)) {
         TemporaryChange<bool> changeOpener(m_suppressOpenerInNewFrame, request.shouldSendReferrer() == NeverSendReferrer);
         checkNewWindowPolicyAndContinue(request.formState(), request.frameName(), action);
         return;
diff --git a/Source/core/loader/FrameLoaderClient.h b/Source/core/loader/FrameLoaderClient.h
index 668a6cb..1031918 100644
--- a/Source/core/loader/FrameLoaderClient.h
+++ b/Source/core/loader/FrameLoaderClient.h
@@ -47,6 +47,7 @@
 
 namespace WebKit {
 class WebCookieJar;
+class WebNavigationControllerRegistry;
 }
 
 namespace WebCore {
@@ -214,6 +215,8 @@
         virtual void dispatchWillInsertBody() { }
 
         virtual void dispatchDidChangeResourcePriority(unsigned long /*identifier*/, ResourceLoadPriority) { }
+
+        virtual WebKit::WebNavigationControllerRegistry* navigationControllerRegistry() = 0;
     };
 
 } // namespace WebCore
diff --git a/Source/core/loader/Prerenderer.cpp b/Source/core/loader/Prerenderer.cpp
index 1360d78..75f454d 100644
--- a/Source/core/loader/Prerenderer.cpp
+++ b/Source/core/loader/Prerenderer.cpp
@@ -83,6 +83,7 @@
         client()->willAddPrerender(prerenderHandle.get());
     prerenderHandle->add();
 
+    // FIXME: This handle isn't released until page unload, but it may be canceled before then. It should be released in that case.
     m_activeHandles.append(prerenderHandle);
     return prerenderHandle;
 }
diff --git a/Source/core/make_derived_sources.target.darwin-arm.mk b/Source/core/make_derived_sources.target.darwin-arm.mk
index e58ed01..d1a02c2 100644
--- a/Source/core/make_derived_sources.target.darwin-arm.mk
+++ b/Source/core/make_derived_sources.target.darwin-arm.mk
@@ -59,7 +59,7 @@
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_RuntimeEnabledFeatures ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -70,7 +70,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -81,7 +81,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -92,7 +92,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -104,7 +104,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -155,7 +155,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -167,7 +167,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py dom/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -287,7 +287,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../core/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
@@ -442,7 +442,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -524,7 +524,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
diff --git a/Source/core/make_derived_sources.target.darwin-mips.mk b/Source/core/make_derived_sources.target.darwin-mips.mk
index 09ee9a1..e0e4ff8 100644
--- a/Source/core/make_derived_sources.target.darwin-mips.mk
+++ b/Source/core/make_derived_sources.target.darwin-mips.mk
@@ -59,7 +59,7 @@
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_RuntimeEnabledFeatures ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -70,7 +70,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -81,7 +81,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -92,7 +92,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -104,7 +104,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -155,7 +155,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -167,7 +167,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py dom/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -287,7 +287,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../core/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
@@ -442,7 +442,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -524,7 +524,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
diff --git a/Source/core/make_derived_sources.target.darwin-x86.mk b/Source/core/make_derived_sources.target.darwin-x86.mk
index 78c16a0..e382447 100644
--- a/Source/core/make_derived_sources.target.darwin-x86.mk
+++ b/Source/core/make_derived_sources.target.darwin-x86.mk
@@ -59,7 +59,7 @@
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_RuntimeEnabledFeatures ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -70,7 +70,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -81,7 +81,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -92,7 +92,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -104,7 +104,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -155,7 +155,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -167,7 +167,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py dom/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -287,7 +287,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../core/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
@@ -444,7 +444,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -529,7 +529,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
diff --git a/Source/core/make_derived_sources.target.linux-arm.mk b/Source/core/make_derived_sources.target.linux-arm.mk
index e58ed01..d1a02c2 100644
--- a/Source/core/make_derived_sources.target.linux-arm.mk
+++ b/Source/core/make_derived_sources.target.linux-arm.mk
@@ -59,7 +59,7 @@
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_RuntimeEnabledFeatures ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -70,7 +70,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -81,7 +81,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -92,7 +92,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -104,7 +104,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -155,7 +155,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -167,7 +167,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py dom/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -287,7 +287,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../core/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
@@ -442,7 +442,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -524,7 +524,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
diff --git a/Source/core/make_derived_sources.target.linux-mips.mk b/Source/core/make_derived_sources.target.linux-mips.mk
index 09ee9a1..e0e4ff8 100644
--- a/Source/core/make_derived_sources.target.linux-mips.mk
+++ b/Source/core/make_derived_sources.target.linux-mips.mk
@@ -59,7 +59,7 @@
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_RuntimeEnabledFeatures ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -70,7 +70,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -81,7 +81,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -92,7 +92,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -104,7 +104,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -155,7 +155,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -167,7 +167,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py dom/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -287,7 +287,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../core/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
@@ -442,7 +442,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -524,7 +524,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
diff --git a/Source/core/make_derived_sources.target.linux-x86.mk b/Source/core/make_derived_sources.target.linux-x86.mk
index 78c16a0..e382447 100644
--- a/Source/core/make_derived_sources.target.linux-x86.mk
+++ b/Source/core/make_derived_sources.target.linux-x86.mk
@@ -59,7 +59,7 @@
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/RuntimeEnabledFeatures.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_runtime_features.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_RuntimeEnabledFeatures ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_runtime_features.py page/RuntimeEnabledFeatures.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -70,7 +70,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -81,7 +81,7 @@
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StylePropertyShorthand.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_shorthands.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSShorthands.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StylePropertyShorthand ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_shorthands.py css/CSSShorthands.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -92,7 +92,7 @@
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/StyleBuilder.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_style_builder.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSProperties.in $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_StyleBuilder ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_style_builder.py css/CSSProperties.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -104,7 +104,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/blink" --defines "\"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\""
 
@@ -155,7 +155,7 @@
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/Event.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(gyp_shared_intermediate_dir)/blink/EventInterfaces.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/blink/EventInterfaces.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -167,7 +167,7 @@
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/EventTargetHeaders.h: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_utilities.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventTargetFactory ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/make_event_factory.py dom/EventTargetFactory.in --output_dir "$(gyp_shared_intermediate_dir)/blink"
 
@@ -287,7 +287,7 @@
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp: $(LOCAL_PATH)/third_party/jinja2/__init__.py $(LOCAL_PATH)/third_party/markupsafe/__init__.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_token_matcher.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSParser-in.cpp $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MakeTokenMatcher ($@)"
 	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python ../core/scripts/make_token_matcher.py ../core/css/CSSParser-in.cpp "$(gyp_shared_intermediate_dir)/blink/CSSParser.cpp"
 
@@ -444,7 +444,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -529,7 +529,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
diff --git a/Source/core/page/ConsoleBase.cpp b/Source/core/page/ConsoleBase.cpp
index e1eaa9e..a889446 100644
--- a/Source/core/page/ConsoleBase.cpp
+++ b/Source/core/page/ConsoleBase.cpp
@@ -111,9 +111,9 @@
     InspectorInstrumentation::consoleCount(context(), state, arguments);
 }
 
-void ConsoleBase::markTimeline(PassRefPtr<ScriptArguments> arguments)
+void ConsoleBase::markTimeline(const String& title)
 {
-    InspectorInstrumentation::consoleTimeStamp(context(), arguments);
+    InspectorInstrumentation::consoleTimeStamp(context(), title);
 }
 
 void ConsoleBase::profile(ScriptState* state, const String& title)
@@ -131,10 +131,7 @@
         resolvedTitle = InspectorInstrumentation::getCurrentUserInitiatedProfileName(context, true);
 
     ScriptProfiler::start(resolvedTitle);
-
-    RefPtr<ScriptCallStack> callStack(createScriptCallStack(state, 1));
-    const ScriptCallFrame& lastCaller = callStack->at(0);
-    InspectorInstrumentation::addStartProfilingMessageToConsole(context, resolvedTitle, lastCaller.lineNumber(), lastCaller.sourceURL());
+    InspectorInstrumentation::addMessageToConsole(context, ConsoleAPIMessageSource, ProfileMessageType, DebugMessageLevel, resolvedTitle, String(), 0, 0, state);
 }
 
 void ConsoleBase::profileEnd(ScriptState* state, const String& title)
@@ -154,23 +151,31 @@
     InspectorInstrumentation::addProfile(context, profile, callStack);
 }
 
-
 void ConsoleBase::time(const String& title)
 {
-    InspectorInstrumentation::startConsoleTiming(context(), title);
+    InspectorInstrumentation::consoleTime(context(), title);
     TRACE_EVENT_COPY_ASYNC_BEGIN0("webkit.console", title.utf8().data(), this);
 }
 
 void ConsoleBase::timeEnd(ScriptState* state, const String& title)
 {
     TRACE_EVENT_COPY_ASYNC_END0("webkit.console", title.utf8().data(), this);
-    RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(state));
-    InspectorInstrumentation::stopConsoleTiming(context(), title, callStack.release());
+    InspectorInstrumentation::consoleTimeEnd(context(), title, state);
 }
 
-void ConsoleBase::timeStamp(PassRefPtr<ScriptArguments> arguments)
+void ConsoleBase::timeStamp(const String& title)
 {
-    InspectorInstrumentation::consoleTimeStamp(context(), arguments);
+    InspectorInstrumentation::consoleTimeStamp(context(), title);
+}
+
+void ConsoleBase::timeline(ScriptState* state, const String& title)
+{
+    InspectorInstrumentation::consoleTimeline(context(), title, state);
+}
+
+void ConsoleBase::timelineEnd(ScriptState* state, const String& title)
+{
+    InspectorInstrumentation::consoleTimelineEnd(context(), title, state);
 }
 
 void ConsoleBase::group(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
diff --git a/Source/core/page/ConsoleBase.h b/Source/core/page/ConsoleBase.h
index 07a6955..4fcd971 100644
--- a/Source/core/page/ConsoleBase.h
+++ b/Source/core/page/ConsoleBase.h
@@ -61,12 +61,14 @@
     void trace(ScriptState*, PassRefPtr<ScriptArguments>);
     void assertCondition(ScriptState*, PassRefPtr<ScriptArguments>, bool condition);
     void count(ScriptState*, PassRefPtr<ScriptArguments>);
-    void markTimeline(PassRefPtr<ScriptArguments>);
+    void markTimeline(const String&);
     void profile(ScriptState*, const String&);
     void profileEnd(ScriptState*, const String&);
     void time(const String&);
     void timeEnd(ScriptState*, const String&);
-    void timeStamp(PassRefPtr<ScriptArguments>);
+    void timeStamp(const String&);
+    void timeline(ScriptState*, const String&);
+    void timelineEnd(ScriptState*, const String&);
     void group(ScriptState*, PassRefPtr<ScriptArguments>);
     void groupCollapsed(ScriptState*, PassRefPtr<ScriptArguments>);
     void groupEnd();
diff --git a/Source/core/page/ConsoleBase.idl b/Source/core/page/ConsoleBase.idl
index e830b9b..542610f 100644
--- a/Source/core/page/ConsoleBase.idl
+++ b/Source/core/page/ConsoleBase.idl
@@ -43,14 +43,18 @@
     [CallWith=ScriptArguments&ScriptState] void trace();
     [CallWith=ScriptArguments&ScriptState, ImplementedAs=assertCondition] void assert([Default=Undefined] optional boolean condition);
     [CallWith=ScriptArguments&ScriptState] void count();
-    [DeprecateAs=ConsoleMarkTimeline, CallWith=ScriptArguments] void markTimeline();
+    [DeprecateAs=ConsoleMarkTimeline] void markTimeline([Default=NullString] optional DOMString title);
 
     [CallWith=ScriptState] void profile([Default=NullString] optional DOMString title);
     [CallWith=ScriptState] void profileEnd([Default=NullString] optional DOMString title);
 
-    void time([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString title);
-    [CallWith=ScriptState] void timeEnd([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString title);
-    [CallWith=ScriptArguments] void timeStamp();
+    void time([Default=NullString] optional DOMString title);
+    [CallWith=ScriptState] void timeEnd([Default=NullString] optional DOMString title);
+    void timeStamp([Default=NullString] optional DOMString title);
+
+    [CallWith=ScriptState] void timeline([Default=NullString] optional DOMString title);
+    [CallWith=ScriptState] void timelineEnd([Default=NullString] optional DOMString title);
+
     [CallWith=ScriptArguments&ScriptState] void group();
     [CallWith=ScriptArguments&ScriptState] void groupCollapsed();
     void groupEnd();
diff --git a/Source/core/page/DOMWindow.cpp b/Source/core/page/DOMWindow.cpp
index abe3bee..d77702d 100644
--- a/Source/core/page/DOMWindow.cpp
+++ b/Source/core/page/DOMWindow.cpp
@@ -54,6 +54,7 @@
 #include "core/dom/PageTransitionEvent.h"
 #include "core/dom/RequestAnimationFrameCallback.h"
 #include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/TouchController.h"
 #include "core/editing/Editor.h"
 #include "core/history/BackForwardController.h"
 #include "core/html/HTMLFrameOwnerElement.h"
@@ -365,7 +366,7 @@
 
     if (m_frame->page() && m_frame->page()->mainFrame() == m_frame) {
         m_frame->page()->mainFrame()->notifyChromeClientWheelEventHandlerCountChanged();
-        if (m_document->hasTouchEventHandlers())
+        if (TouchController::from(m_document.get())->hasTouchEventHandlers())
             m_frame->page()->chrome().client().needTouchEvents(true);
     }
 }
@@ -1410,9 +1411,7 @@
 
     if (Document* document = this->document()) {
         document->addListenerTypeIfNeeded(eventType);
-        if (eventNames().isTouchEventType(eventType))
-            document->didAddTouchEventHandler(document);
-        else if (eventType == eventNames().storageEvent)
+        if (eventType == eventNames().storageEvent)
             didAddStorageEventListener(this);
     }
 
@@ -1443,11 +1442,6 @@
     if (!EventTarget::removeEventListener(eventType, listener, useCapture))
         return false;
 
-    if (Document* document = this->document()) {
-        if (eventNames().isTouchEventType(eventType))
-            document->didRemoveTouchEventHandler(document);
-    }
-
     lifecycleNotifier()->notifyRemoveEventListener(this, eventType);
 
     if (eventType == eventNames().unloadEvent) {
@@ -1512,8 +1506,6 @@
 
     if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
         controller->removeAllDeviceEventListeners(this);
-    if (Document* document = this->document())
-        document->didRemoveEventTargetNode(document);
 
     removeAllUnloadEventListeners(this);
     removeAllBeforeUnloadEventListeners(this);
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index 2afd72a..152e7d6 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -41,6 +41,7 @@
 #include "core/dom/KeyboardEvent.h"
 #include "core/dom/MouseEvent.h"
 #include "core/dom/TextEvent.h"
+#include "core/dom/TouchController.h"
 #include "core/dom/TouchEvent.h"
 #include "core/dom/TouchList.h"
 #include "core/dom/UserTypingGestureIndicator.h"
@@ -1105,13 +1106,6 @@
     bool horizontalText = !style || style->isHorizontalWritingMode();
     const Cursor& iBeam = horizontalText ? iBeamCursor() : verticalTextCursor();
 
-    // During selection, use an I-beam no matter what we're over.
-    // If a drag may be starting or we're capturing mouse events for a particular node, don't treat this as a selection.
-    if (m_mousePressed && m_mouseDownMayStartSelect
-        && !m_mouseDownMayStartDrag
-        && m_frame->selection().isCaretOrRange() && !m_capturingMouseEventsNode)
-        return iBeam;
-
     if (renderer) {
         Cursor overrideCursor;
         switch (renderer->getCursor(roundedIntPoint(event.localPoint()), overrideCursor)) {
@@ -1168,6 +1162,16 @@
                     inResizer = layer->isPointInResizeControl(view->windowToContents(event.event().position()), ResizerForPointer);
             }
         }
+
+        // During selection, use an I-beam no matter what we're over.
+        // If a drag may be starting or we're capturing mouse events for a particular node, don't treat this as a selection.
+        if (m_mousePressed && m_mouseDownMayStartSelect
+            && !m_mouseDownMayStartDrag
+            && m_frame->selection().isCaretOrRange()
+            && !m_capturingMouseEventsNode) {
+            return iBeam;
+        }
+
         if ((editable || (renderer && renderer->isText() && node->canStartSelection())) && !inResizer && !scrollbar)
             return iBeam;
         return pointerCursor();
@@ -1263,7 +1267,7 @@
         return true;
 
     UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
-    m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
+    m_frame->tree()->top()->eventHandler()->m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
 
     cancelFakeMouseMoveEvent();
     if (m_eventHandlerWillResetCapturingMouseEventsNode)
@@ -1599,8 +1603,8 @@
 
     OwnPtr<UserGestureIndicator> gestureIndicator;
 
-    if (m_lastMouseDownUserGestureToken)
-        gestureIndicator = adoptPtr(new UserGestureIndicator(m_lastMouseDownUserGestureToken.release()));
+    if (m_frame->tree()->top()->eventHandler()->m_lastMouseDownUserGestureToken)
+        gestureIndicator = adoptPtr(new UserGestureIndicator(m_frame->tree()->top()->eventHandler()->m_lastMouseDownUserGestureToken.release()));
     else
         gestureIndicator = adoptPtr(new UserGestureIndicator(DefinitelyProcessingUserGesture));
 
@@ -2619,7 +2623,10 @@
     // in the case where further processing on the node is required. Returning the shadow ancestor prevents a
     // regression in touchadjustment/html-label.html. Some refinement is required to testing/internals to
     // handle targetNode being a shadow DOM node.
-    bool success = findBestClickableCandidate(targetNode, targetPoint, touchCenter, touchRect, nodes);
+
+    // FIXME: the explicit Vector conversion copies into a temporary and is
+    // wasteful.
+    bool success = findBestClickableCandidate(targetNode, targetPoint, touchCenter, touchRect, Vector<RefPtr<Node> > (nodes));
     if (success && targetNode)
         targetNode = targetNode->deprecatedShadowAncestorNode();
     return success;
@@ -2633,7 +2640,10 @@
     IntRect touchRect(touchCenter - touchRadius, touchRadius + touchRadius);
     Vector<RefPtr<Node>, 11> nodes;
     copyToVector(result.rectBasedTestResult(), nodes);
-    return findBestContextMenuCandidate(targetNode, targetPoint, touchCenter, touchRect, nodes);
+
+    // FIXME: the explicit Vector conversion copies into a temporary and is
+    // wasteful.
+    return findBestContextMenuCandidate(targetNode, targetPoint, touchCenter, touchRect, Vector<RefPtr<Node> >(nodes));
 }
 
 bool EventHandler::bestZoomableAreaForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntRect& targetArea, Node*& targetNode)
@@ -2644,7 +2654,10 @@
     IntRect touchRect(touchCenter - touchRadius, touchRadius + touchRadius);
     Vector<RefPtr<Node>, 11> nodes;
     copyToVector(result.rectBasedTestResult(), nodes);
-    return findBestZoomableArea(targetNode, targetArea, touchCenter, touchRect, nodes);
+
+    // FIXME: the explicit Vector conversion copies into a temporary and is
+    // wasteful.
+    return findBestZoomableArea(targetNode, targetArea, touchCenter, touchRect, Vector<RefPtr<Node> >(nodes));
 }
 
 bool EventHandler::adjustGesturePosition(const PlatformGestureEvent& gestureEvent, IntPoint& adjustedPoint)
@@ -3628,7 +3641,7 @@
                 m_originatingTouchPointDocument = &doc;
                 freshTouchEvents = false;
             }
-            if (!doc.hasTouchEventHandlers())
+            if (!TouchController::from(&doc)->hasTouchEventHandlers())
                 continue;
             m_originatingTouchPointTargets.set(touchPointTargetKey, node);
             touchTarget = node;
@@ -3651,7 +3664,7 @@
         if (!touchTarget.get())
             continue;
         Document& doc = touchTarget->toNode()->document();
-        if (!doc.hasTouchEventHandlers())
+        if (!TouchController::from(&doc)->hasTouchEventHandlers())
             continue;
         Frame* targetFrame = doc.frame();
         if (!targetFrame)
diff --git a/Source/core/page/FrameTree.cpp b/Source/core/page/FrameTree.cpp
index a137634..47e59ad 100644
--- a/Source/core/page/FrameTree.cpp
+++ b/Source/core/page/FrameTree.cpp
@@ -51,46 +51,15 @@
     m_uniqueName = parent()->tree()->uniqueChildName(name);
 }
 
-void FrameTree::clearName()
-{
-    m_name = AtomicString();
-    m_uniqueName = AtomicString();
-}
-
 Frame* FrameTree::parent() const
 {
     return m_parent;
 }
 
-bool FrameTree::transferChild(PassRefPtr<Frame> child)
-{
-    Frame* oldParent = child->tree()->parent();
-    if (oldParent == m_thisFrame)
-        return false; // |child| is already a child of m_thisFrame.
-
-    if (oldParent)
-        oldParent->tree()->removeChild(child.get());
-
-    ASSERT(child->page() == m_thisFrame->page());
-    child->tree()->m_parent = m_thisFrame;
-
-    // We need to ensure that the child still has a unique frame name with respect to its new parent.
-    child->tree()->setName(child->tree()->m_name);
-
-    actuallyAppendChild(child); // Note, on return |child| is null.
-    return true;
-}
-
 void FrameTree::appendChild(PassRefPtr<Frame> child)
 {
     ASSERT(child->page() == m_thisFrame->page());
     child->tree()->m_parent = m_thisFrame;
-    actuallyAppendChild(child); // Note, on return |child| is null.
-}
-
-void FrameTree::actuallyAppendChild(PassRefPtr<Frame> child)
-{
-    ASSERT(child->tree()->m_parent == m_thisFrame);
     Frame* oldLast = m_lastChild;
     m_lastChild = child.get();
 
@@ -168,8 +137,9 @@
     return name.toAtomicString();
 }
 
-inline Frame* FrameTree::scopedChild(unsigned index, TreeScope* scope) const
+Frame* FrameTree::scopedChild(unsigned index) const
 {
+    TreeScope* scope = m_thisFrame->document();
     if (!scope)
         return 0;
 
@@ -185,8 +155,9 @@
     return 0;
 }
 
-inline Frame* FrameTree::scopedChild(const AtomicString& name, TreeScope* scope) const
+Frame* FrameTree::scopedChild(const AtomicString& name) const
 {
+    TreeScope* scope = m_thisFrame->document();
     if (!scope)
         return 0;
 
@@ -210,16 +181,6 @@
     return scopedCount;
 }
 
-Frame* FrameTree::scopedChild(unsigned index) const
-{
-    return scopedChild(index, m_thisFrame->document());
-}
-
-Frame* FrameTree::scopedChild(const AtomicString& name) const
-{
-    return scopedChild(name, m_thisFrame->document());
-}
-
 unsigned FrameTree::scopedChildCount() const
 {
     if (m_scopedChildCount == invalidCount)
@@ -235,14 +196,6 @@
     return count;
 }
 
-Frame* FrameTree::child(unsigned index) const
-{
-    Frame* result = firstChild();
-    for (unsigned i = 0; result && i != index; ++i)
-        result = result->tree()->nextSibling();
-    return result;
-}
-
 Frame* FrameTree::child(const AtomicString& name) const
 {
     for (Frame* child = firstChild(); child; child = child->tree()->nextSibling())
diff --git a/Source/core/page/FrameTree.h b/Source/core/page/FrameTree.h
index ac2886f..9f7f842 100644
--- a/Source/core/page/FrameTree.h
+++ b/Source/core/page/FrameTree.h
@@ -46,7 +46,6 @@
         const AtomicString& name() const { return m_name; }
         const AtomicString& uniqueName() const { return m_uniqueName; }
         void setName(const AtomicString&);
-        void clearName();
         Frame* parent() const;
         void setParent(Frame* parent) { m_parent = parent; }
 
@@ -61,17 +60,13 @@
         Frame* traversePreviousWithWrap(bool) const;
 
         void appendChild(PassRefPtr<Frame>);
-        bool transferChild(PassRefPtr<Frame>);
         void detachFromParent() { m_parent = 0; }
         void removeChild(Frame*);
 
-        Frame* child(unsigned index) const;
         Frame* child(const AtomicString& name) const;
         Frame* find(const AtomicString& name) const;
         unsigned childCount() const;
 
-        AtomicString uniqueChildName(const AtomicString& requestedName) const;
-
         Frame* top() const;
 
         Frame* scopedChild(unsigned index) const;
@@ -80,11 +75,7 @@
 
     private:
         Frame* deepLastChild() const;
-        void actuallyAppendChild(PassRefPtr<Frame>);
-
-        bool scopedBy(TreeScope*) const;
-        Frame* scopedChild(unsigned index, TreeScope*) const;
-        Frame* scopedChild(const AtomicString& name, TreeScope*) const;
+        AtomicString uniqueChildName(const AtomicString& requestedName) const;
         unsigned scopedChildCount(TreeScope*) const;
 
         Frame* m_thisFrame;
diff --git a/Source/core/page/FrameView.cpp b/Source/core/page/FrameView.cpp
index ee27429..b8541cd 100644
--- a/Source/core/page/FrameView.cpp
+++ b/Source/core/page/FrameView.cpp
@@ -31,7 +31,7 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/animation/DocumentTimeline.h"
-#include "core/css/FontLoader.h"
+#include "core/css/FontFaceSet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/DocumentMarkerController.h"
 #include "core/dom/OverflowEvent.h"
@@ -891,6 +891,7 @@
 
         beginDeferredRepaints();
         forceLayoutParentViewIfNeeded();
+        renderView()->updateConfiguration();
 
         // Text Autosizing requires two-pass layout which is incompatible with partial layout.
         // If enabled, only do partial layout for the second layout.
@@ -1019,7 +1020,7 @@
         ScrollbarMode vMode;
         calculateScrollbarModesForLayout(hMode, vMode);
 
-        m_doFullRepaint = !inSubtreeLayout && !isPartialLayout && (m_firstLayout || toRenderView(rootForThisLayout)->printing());
+        m_doFullRepaint = !inSubtreeLayout && !isPartialLayout && (m_firstLayout || toRenderView(rootForThisLayout)->document().printing());
 
         if (!inSubtreeLayout && !isPartialLayout) {
             // Now set our scrollbar state for the layout.
@@ -1075,7 +1076,7 @@
 
     bool neededFullRepaint = m_doFullRepaint;
 
-    if (!inSubtreeLayout && !isPartialLayout && !toRenderView(rootForThisLayout)->printing())
+    if (!inSubtreeLayout && !isPartialLayout && !toRenderView(rootForThisLayout)->document().printing())
         adjustViewSize();
 
     m_doFullRepaint = neededFullRepaint;
@@ -1123,8 +1124,7 @@
 
 #ifndef NDEBUG
     // Post-layout assert that nobody was re-marked as needing layout during layout.
-    for (RenderObject* renderer = document->renderer(); renderer; renderer = renderer->nextInPreOrder())
-        ASSERT_WITH_SECURITY_IMPLICATION(!renderer->needsLayout());
+    document->renderer()->assertSubtreeIsLaidOut();
 #endif
 
     // FIXME: It should be not possible to remove the FrameView from the frame/page during layout
@@ -1351,13 +1351,16 @@
         if (!renderer->style()->hasViewportConstrainedPosition())
             continue;
 
-        if (renderer->isComposited())
-            continue;
-
         // Fixed items should always have layers.
         ASSERT(renderer->hasLayer());
         RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
 
+        // Composited layers may still actually paint into their ancestor.
+        // If that happens, the viewport constrained object needs to be
+        // repainted on scroll.
+        if (layer->isComposited() && !layer->backing()->paintsIntoCompositedAncestor())
+            continue;
+
         if (layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForBoundsOutOfView
             || layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForNoVisibleContent) {
             // Don't invalidate for invisible fixed layers.
@@ -1369,12 +1372,26 @@
             // scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
             return false;
         }
+
         IntRect updateRect = pixelSnappedIntRect(layer->repaintRectIncludingNonCompositingDescendants());
-        updateRect = contentsToRootView(updateRect);
-        if (!isCompositedContentLayer && clipsRepaints())
-            updateRect.intersect(rectToScroll);
-        if (!updateRect.isEmpty())
-            regionToUpdate.unite(updateRect);
+
+        RenderLayer* enclosingCompositingLayer = layer->enclosingCompositingLayer(false);
+        if (enclosingCompositingLayer && !enclosingCompositingLayer->renderer()->isRenderView()) {
+            // If the fixed-position layer is contained by a composited layer that is not its containing block,
+            // then we have to invlidate that enclosing layer, not the RenderView.
+            updateRect.moveBy(scrollPosition());
+            IntRect previousRect = updateRect;
+            previousRect.move(scrollDelta);
+            updateRect.unite(previousRect);
+            enclosingCompositingLayer->setBackingNeedsRepaintInRect(updateRect);
+        } else {
+            // Coalesce the repaints that will be issued to the renderView.
+            updateRect = contentsToRootView(updateRect);
+            if (!isCompositedContentLayer && clipsRepaints())
+                updateRect.intersect(rectToScroll);
+            if (!updateRect.isEmpty())
+                regionToUpdate.unite(updateRect);
+        }
     }
 
     // 1) scroll
@@ -2232,7 +2249,7 @@
     }
 
     m_frame->loader()->didLayout(milestonesAchieved);
-    m_frame->document()->fontloader()->didLayout();
+    m_frame->document()->fonts()->didLayout();
 
     RenderView* renderView = this->renderView();
     if (renderView)
@@ -2260,7 +2277,7 @@
     ASSERT(m_frame);
 
     RenderView* renderView = this->renderView();
-    if (!renderView || renderView->printing())
+    if (!renderView || renderView->document().printing())
         return;
 
     IntSize currentSize = layoutSize(IncludeScrollbars);
@@ -2914,6 +2931,7 @@
     RenderLayer* rootLayer = renderView->layer();
 
 #ifndef NDEBUG
+    renderView->assertSubtreeIsLaidOut();
     RenderObject::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(rootLayer->renderer());
 #endif
 
diff --git a/Source/core/page/Navigator.cpp b/Source/core/page/Navigator.cpp
index 646468b..b93cb62 100644
--- a/Source/core/page/Navigator.cpp
+++ b/Source/core/page/Navigator.cpp
@@ -40,7 +40,7 @@
 #endif // ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB
 
 #ifndef WEBCORE_NAVIGATOR_VENDOR
-#define WEBCORE_NAVIGATOR_VENDOR "Apple Computer, Inc."
+#define WEBCORE_NAVIGATOR_VENDOR "Google Inc."
 #endif // ifndef WEBCORE_NAVIGATOR_VENDOR
 
 #ifndef WEBCORE_NAVIGATOR_VENDOR_SUB
diff --git a/Source/core/page/Navigator.idl b/Source/core/page/Navigator.idl
index 79f322d..546e3e0 100644
--- a/Source/core/page/Navigator.idl
+++ b/Source/core/page/Navigator.idl
@@ -18,11 +18,9 @@
 */
 
 interface Navigator {
-    readonly attribute DOMString appCodeName;
     readonly attribute DOMString language;
     readonly attribute PluginArray plugins;
     readonly attribute MimeTypeArray mimeTypes;
-    readonly attribute DOMString product;
     readonly attribute boolean cookieEnabled;
     boolean javaEnabled();
 
diff --git a/Source/core/page/NavigatorBase.h b/Source/core/page/NavigatorBase.h
index cb6c81f..38ae266 100644
--- a/Source/core/page/NavigatorBase.h
+++ b/Source/core/page/NavigatorBase.h
@@ -30,18 +30,13 @@
 
 namespace WebCore {
 
-    class NavigatorBase {
-    public:
-        virtual String userAgent() const = 0;
+class NavigatorBase {
+public:
+    virtual String userAgent() const = 0;
 
-        // FIXME: The following should be moved to NavigatorID and
-        // exposed on WorkerNavigator as well.
-        String appCodeName() const;
-        String product() const;
-
-    protected:
-        virtual ~NavigatorBase();
-    };
+protected:
+    virtual ~NavigatorBase() { }
+};
 
 } // namespace WebCore
 
diff --git a/Source/core/page/NavigatorID.cpp b/Source/core/page/NavigatorID.cpp
index 6f60f5d..f76f57f 100644
--- a/Source/core/page/NavigatorID.cpp
+++ b/Source/core/page/NavigatorID.cpp
@@ -33,13 +33,16 @@
 #include "NavigatorID.h"
 
 #include "core/page/NavigatorBase.h"
-#include "wtf/CPU.h"
 
-#if OS(LINUX)
+#if !defined(WEBCORE_NAVIGATOR_PLATFORM) && OS(POSIX) && !OS(MACOSX)
 #include "wtf/StdLibExtras.h"
 #include <sys/utsname.h>
 #endif
 
+#ifndef WEBCORE_NAVIGATOR_PRODUCT
+#define WEBCORE_NAVIGATOR_PRODUCT "Gecko"
+#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT
+
 namespace WebCore {
 
 String NavigatorID::appName(const NavigatorBase*)
@@ -63,15 +66,27 @@
 {
 #if defined(WEBCORE_NAVIGATOR_PLATFORM)
     return WEBCORE_NAVIGATOR_PLATFORM;
-#else
-#if OS(LINUX)
+#elif OS(MACOSX)
+    // Match Safari and Mozilla on Mac x86.
+    return "MacIntel";
+#elif OS(WIN)
+    // Match Safari and Mozilla on Windows.
+    return "Win32";
+#else // Unix-like systems
     struct utsname osname;
     DEFINE_STATIC_LOCAL(String, platformName, (uname(&osname) >= 0 ? String(osname.sysname) + String(" ") + String(osname.machine) : emptyString()));
     return platformName;
-#else
-#error Non-Linux ports must define WEBCORE_NAVIGATOR_PLATFORM.
 #endif
-#endif
+}
+
+String NavigatorID::appCodeName(const NavigatorBase*)
+{
+    return "Mozilla";
+}
+
+String NavigatorID::product(const NavigatorBase*)
+{
+    return WEBCORE_NAVIGATOR_PRODUCT;
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/NavigatorID.h b/Source/core/page/NavigatorID.h
index c235fe0..9e31d31 100644
--- a/Source/core/page/NavigatorID.h
+++ b/Source/core/page/NavigatorID.h
@@ -43,6 +43,8 @@
     static String appVersion(const NavigatorBase*);
     static String userAgent(const NavigatorBase*);
     static String platform(const NavigatorBase*);
+    static String appCodeName(const NavigatorBase*);
+    static String product(const NavigatorBase*);
 };
 
 } // namespace WebCore
diff --git a/Source/core/page/NavigatorID.idl b/Source/core/page/NavigatorID.idl
index a0333ba..c581ad9 100644
--- a/Source/core/page/NavigatorID.idl
+++ b/Source/core/page/NavigatorID.idl
@@ -35,4 +35,6 @@
     readonly attribute DOMString appVersion;
     readonly attribute DOMString platform;
     readonly attribute DOMString userAgent;
+    readonly attribute DOMString appCodeName;
+    readonly attribute DOMString product;
 };
diff --git a/Source/core/page/Page.cpp b/Source/core/page/Page.cpp
index 09a0158..d1b954d 100644
--- a/Source/core/page/Page.cpp
+++ b/Source/core/page/Page.cpp
@@ -24,7 +24,7 @@
 #include "core/dom/DocumentMarkerController.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/dom/VisitedLinkState.h"
 #include "core/editing/Caret.h"
 #include "core/history/BackForwardController.h"
@@ -463,7 +463,7 @@
 
     for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext()) {
         if (frame->document())
-            frame->document()->styleSheetCollections()->updatePageUserSheet();
+            frame->document()->styleEngine()->updatePageUserSheet();
     }
 }
 
diff --git a/Source/core/page/PageGroup.cpp b/Source/core/page/PageGroup.cpp
index abe982a..29b1937 100644
--- a/Source/core/page/PageGroup.cpp
+++ b/Source/core/page/PageGroup.cpp
@@ -27,7 +27,7 @@
 #include "core/page/PageGroup.h"
 
 #include "core/dom/Document.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 
@@ -92,7 +92,7 @@
     HashSet<Page*>::const_iterator end = m_pages.end();
     for (HashSet<Page*>::const_iterator it = m_pages.begin(); it != end; ++it) {
         for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree()->traverseNext())
-            frame->document()->styleSheetCollections()->invalidateInjectedStyleSheetCache();
+            frame->document()->styleEngine()->invalidateInjectedStyleSheetCache();
     }
 }
 
diff --git a/Source/core/page/PageSerializer.cpp b/Source/core/page/PageSerializer.cpp
index 2005a65..e22b0d4 100644
--- a/Source/core/page/PageSerializer.cpp
+++ b/Source/core/page/PageSerializer.cpp
@@ -32,9 +32,13 @@
 #include "core/page/PageSerializer.h"
 
 #include "HTMLNames.h"
+#include "core/css/CSSFontFaceRule.h"
+#include "core/css/CSSFontFaceSrcValue.h"
 #include "core/css/CSSImageValue.h"
 #include "core/css/CSSImportRule.h"
+#include "core/css/CSSStyleDeclaration.h"
 #include "core/css/CSSStyleRule.h"
+#include "core/css/CSSValueList.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
 #include "core/css/StyleSheetContents.h"
@@ -42,6 +46,7 @@
 #include "core/dom/Element.h"
 #include "core/dom/Text.h"
 #include "core/editing/MarkupAccumulator.h"
+#include "core/fetch/FontResource.h"
 #include "core/fetch/ImageResource.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLImageElement.h"
@@ -261,16 +266,15 @@
         Document* document = styleSheet->ownerDocument();
         // Some rules have resources associated with them that we need to retrieve.
         if (rule->type() == CSSRule::IMPORT_RULE) {
-            CSSImportRule* importRule = static_cast<CSSImportRule*>(rule);
+            CSSImportRule* importRule = toCSSImportRule(rule);
             KURL importURL = document->completeURL(importRule->href());
             if (m_resourceURLs.contains(importURL))
                 continue;
             serializeCSSStyleSheet(importRule->styleSheet(), importURL);
         } else if (rule->type() == CSSRule::FONT_FACE_RULE) {
-            // FIXME: Add support for font face rule. It is not clear to me at this point if the actual otf/eot file can
-            // be retrieved from the CSSFontFaceRule object.
+            retrieveResourcesForProperties(toCSSFontFaceRule(rule)->styleRule()->properties(), document);
         } else if (rule->type() == CSSRule::STYLE_RULE) {
-            retrieveResourcesForRule(static_cast<CSSStyleRule*>(rule)->styleRule(), document);
+            retrieveResourcesForProperties(toCSSStyleRule(rule)->styleRule()->properties(), document);
         }
     }
 
@@ -285,9 +289,26 @@
     }
 }
 
+bool PageSerializer::shouldAddURL(const KURL& url)
+{
+    return url.isValid() && !m_resourceURLs.contains(url) && !url.protocolIsData();
+}
+
+void PageSerializer::addToResources(Resource* resource, PassRefPtr<SharedBuffer> data, const KURL& url)
+{
+    if (!data) {
+        LOG_ERROR("No data for resource %s", url.string().utf8().data());
+        return;
+    }
+
+    String mimeType = resource->response().mimeType();
+    m_resources->append(SerializedResource(url, mimeType, data));
+    m_resourceURLs.add(url);
+}
+
 void PageSerializer::addImageToResources(ImageResource* image, RenderObject* imageRenderer, const KURL& url)
 {
-    if (!url.isValid() || m_resourceURLs.contains(url) || url.protocolIsData())
+    if (!shouldAddURL(url))
         return;
 
     if (!image || image->image() == Image::nullImage())
@@ -297,19 +318,17 @@
     if (!data)
         data = image->image()->data();
 
-    if (!data) {
-        LOG_ERROR("No data for image %s", url.string().utf8().data());
-        return;
-    }
-
-    String mimeType = image->response().mimeType();
-    m_resources->append(SerializedResource(url, mimeType, data));
-    m_resourceURLs.add(url);
+    addToResources(image, data, url);
 }
 
-void PageSerializer::retrieveResourcesForRule(StyleRule* rule, Document* document)
+void PageSerializer::addFontToResources(FontResource* font)
 {
-    retrieveResourcesForProperties(rule->properties(), document);
+    if (!font || !shouldAddURL(font->url()) || !font->isLoaded() || !font->resourceBuffer()) {
+        return;
+    }
+    RefPtr<SharedBuffer> data(font->resourceBuffer());
+
+    addToResources(font, data, font->url());
 }
 
 void PageSerializer::retrieveResourcesForProperties(const StylePropertySet* styleDeclaration, Document* document)
@@ -323,17 +342,31 @@
     unsigned propertyCount = styleDeclaration->propertyCount();
     for (unsigned i = 0; i < propertyCount; ++i) {
         RefPtr<CSSValue> cssValue = styleDeclaration->propertyAt(i).value();
-        if (!cssValue->isImageValue())
-            continue;
+        retrieveResourcesForCSSValue(cssValue.get(), document);
+    }
+}
 
-        CSSImageValue* imageValue = toCSSImageValue(cssValue.get());
+void PageSerializer::retrieveResourcesForCSSValue(CSSValue* cssValue, Document* document)
+{
+    if (cssValue->isImageValue()) {
+        CSSImageValue* imageValue = toCSSImageValue(cssValue);
         StyleImage* styleImage = imageValue->cachedOrPendingImage();
         // Non cached-images are just place-holders and do not contain data.
         if (!styleImage || !styleImage->isImageResource())
-            continue;
+            return;
 
-        ImageResource* image = static_cast<StyleFetchedImage*>(styleImage)->cachedImage();
-        addImageToResources(image, 0, image->url());
+        addImageToResources(styleImage->cachedImage(), 0, styleImage->cachedImage()->url());
+    } else if (cssValue->isFontFaceSrcValue()) {
+        CSSFontFaceSrcValue* fontFaceSrcValue = toCSSFontFaceSrcValue(cssValue);
+        if (fontFaceSrcValue->isLocal()) {
+            return;
+        }
+
+        addFontToResources(fontFaceSrcValue->fetch(document));
+    } else if (cssValue->isValueList()) {
+        CSSValueList* cssValueList = toCSSValueList(cssValue);
+        for (unsigned i = 0; i < cssValueList->length(); i++)
+            retrieveResourcesForCSSValue(cssValueList->item(i), document);
     }
 }
 
diff --git a/Source/core/page/PageSerializer.h b/Source/core/page/PageSerializer.h
index 296cba6..93a4dc1 100644
--- a/Source/core/page/PageSerializer.h
+++ b/Source/core/page/PageSerializer.h
@@ -39,14 +39,19 @@
 
 namespace WebCore {
 
+class FontResource;
 class ImageResource;
 class CSSStyleSheet;
+class CSSValue;
 class Document;
 class Frame;
 class Page;
 class RenderObject;
+class Resource;
+class SharedBuffer;
 class StylePropertySet;
 class StyleRule;
+class StyleRuleFontFace;
 
 struct SerializedResource;
 
@@ -70,9 +75,14 @@
     // It also adds any resources included in that stylesheet (including any imported stylesheets and their own resources).
     void serializeCSSStyleSheet(CSSStyleSheet*, const KURL&);
 
+    bool shouldAddURL(const KURL&);
+
+    void addToResources(Resource *, PassRefPtr<SharedBuffer>, const KURL&);
     void addImageToResources(ImageResource*, RenderObject*, const KURL&);
+    void addFontToResources(FontResource*);
+
     void retrieveResourcesForProperties(const StylePropertySet*, Document*);
-    void retrieveResourcesForRule(StyleRule*, Document*);
+    void retrieveResourcesForCSSValue(CSSValue*, Document*);
 
     Vector<SerializedResource>* m_resources;
     ListHashSet<KURL> m_resourceURLs;
diff --git a/Source/core/page/RuntimeEnabledFeatures.in b/Source/core/page/RuntimeEnabledFeatures.in
index 6108b66..bd62381 100644
--- a/Source/core/page/RuntimeEnabledFeatures.in
+++ b/Source/core/page/RuntimeEnabledFeatures.in
@@ -62,8 +62,9 @@
 LegacyEncryptedMedia status=stable
 LocalStorage status=stable
 Media status=stable
-MediaSource status=experimental
+MediaSource status=stable
 MediaStream status=stable
+NavigationController status=experimental
 Notifications status=stable
 ObjectFitPosition status=experimental
 PagePopup status=stable
@@ -85,6 +86,7 @@
 SpeechSynthesis status=experimental
 Stream status=experimental
 StyleScoped status=experimental
+SubpixelFontScaling
 SVGPaintOrder status=experimental
 Touch status=stable
 UserSelectAll status=experimental
diff --git a/Source/core/page/Settings.cpp b/Source/core/page/Settings.cpp
index c30a752..d46062d 100644
--- a/Source/core/page/Settings.cpp
+++ b/Source/core/page/Settings.cpp
@@ -93,11 +93,8 @@
     EditingWindowsBehavior
 #elif OS(ANDROID)
     EditingAndroidBehavior
-#elif OS(POSIX)
+#else // Rest of the UNIX-like systems
     EditingUnixBehavior
-#else
-    // Fallback
-    EditingMacBehavior
 #endif
     ;
 }
diff --git a/Source/core/page/TouchDisambiguation.cpp b/Source/core/page/TouchDisambiguation.cpp
index 4cab1f5..6638ce3 100644
--- a/Source/core/page/TouchDisambiguation.cpp
+++ b/Source/core/page/TouchDisambiguation.cpp
@@ -88,7 +88,7 @@
     float score;
 };
 
-void findGoodTouchTargets(const IntRect& touchBox, Frame* mainFrame, Vector<IntRect>& goodTargets)
+void findGoodTouchTargets(const IntRect& touchBox, Frame* mainFrame, Vector<IntRect>& goodTargets, Vector<Node*>& highlightNodes)
 {
     goodTargets.clear();
 
@@ -144,6 +144,7 @@
         if (it->value.score < bestScore * 0.5)
             continue;
         goodTargets.append(it->value.windowBoundingBox);
+        highlightNodes.append(it->key);
     }
 }
 
diff --git a/Source/core/page/TouchDisambiguation.h b/Source/core/page/TouchDisambiguation.h
index c4c517e..36352a9 100644
--- a/Source/core/page/TouchDisambiguation.h
+++ b/Source/core/page/TouchDisambiguation.h
@@ -37,8 +37,9 @@
 
 class Frame;
 class IntRect;
+class Node;
 
-void findGoodTouchTargets(const IntRect& touchBox, Frame* mainFrame, Vector<IntRect>& goodTargets);
+void findGoodTouchTargets(const IntRect& touchBox, Frame* mainFrame, Vector<IntRect>& goodTargets, Vector<Node*>& highlightNodes);
 
 } // namespace WebCore
 
diff --git a/Source/core/page/UseCounter.h b/Source/core/page/UseCounter.h
index 73c4958..33fa001 100644
--- a/Source/core/page/UseCounter.h
+++ b/Source/core/page/UseCounter.h
@@ -202,6 +202,13 @@
         InsertAdjacentText,
         InsertAdjacentElement,
         HasAttributes, // Removed from DOM4.
+        DOMSubtreeModifiedEvent,
+        DOMNodeInsertedEvent,
+        DOMNodeRemovedEvent,
+        DOMNodeRemovedFromDocumentEvent,
+        DOMNodeInsertedIntoDocumentEvent,
+        DOMCharacterDataModifiedEvent,
+        DocumentAllTags,
         // Add new features immediately above this line. Don't change assigned
         // numbers of each items, and don't reuse unused slots.
         NumberOfFeatures, // This enum value must be last.
diff --git a/Source/core/page/animation/AnimationBase.cpp b/Source/core/page/animation/AnimationBase.cpp
index 77b4992..f5dd049 100644
--- a/Source/core/page/animation/AnimationBase.cpp
+++ b/Source/core/page/animation/AnimationBase.cpp
@@ -458,14 +458,27 @@
 
     fractionalTime -= integralTime;
 
+    // Thie method can be called with an elapsedTime which very slightly
+    // exceeds the end of the animation. In this case, clamp the
+    // fractionalTime.
+    if (fractionalTime > 1)
+        fractionalTime = 1;
+    ASSERT(fractionalTime >= 0 && fractionalTime <= 1);
+
     if (((m_animation->direction() == CSSAnimationData::AnimationDirectionAlternate) && (integralTime & 1))
         || ((m_animation->direction() == CSSAnimationData::AnimationDirectionAlternateReverse) && !(integralTime & 1))
         || m_animation->direction() == CSSAnimationData::AnimationDirectionReverse)
         fractionalTime = 1 - fractionalTime;
 
-    if (scale != 1 || offset)
-        fractionalTime = (fractionalTime - offset) * scale;
+    fractionalTime -= offset;
+    // Note that if fractionalTime == 0 here, scale may be infinity, but in
+    // this case we don't need to apply scale anyway.
+    if (scale != 1.0 && fractionalTime) {
+        ASSERT(scale >= 0 && !std::isinf(scale));
+        fractionalTime *= scale;
+    }
 
+    ASSERT(fractionalTime >= 0 && fractionalTime <= 1);
     return fractionalTime;
 }
 
diff --git a/Source/core/page/animation/AnimationController.cpp b/Source/core/page/animation/AnimationController.cpp
index b0fad9b..087325e 100644
--- a/Source/core/page/animation/AnimationController.cpp
+++ b/Source/core/page/animation/AnimationController.cpp
@@ -504,7 +504,7 @@
         return newStyle;
 
     // Don't run transitions when printing.
-    if (renderer->view()->printing())
+    if (renderer->view()->document().printing())
         return newStyle;
 
     // Fetch our current set of implicit animations from a hashtable.  We then compare them
diff --git a/Source/core/page/animation/KeyframeAnimation.cpp b/Source/core/page/animation/KeyframeAnimation.cpp
index da92432..8017ca1 100644
--- a/Source/core/page/animation/KeyframeAnimation.cpp
+++ b/Source/core/page/animation/KeyframeAnimation.cpp
@@ -144,8 +144,11 @@
 
     offset = prevKeyframe.key();
     scale = 1.0 / (nextKeyframe.key() - prevKeyframe.key());
+    // A scale of infinity is handled in AnimationBase::fractionalTime().
+    ASSERT(scale >= 0 && (!std::isinf(scale) || prevIndex == nextIndex));
 
-    const TimingFunction* timingFunction = prevKeyframe.timingFunction(name());
+    // FIXME: This sometimes gets the wrong timing function. See crbug.com/288540.
+    const TimingFunction* timingFunction = KeyframeValue::timingFunction(prevKeyframe.style(), name());
     prog = progress(scale, offset, timingFunction);
 }
 
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.cpp b/Source/core/page/scrolling/ScrollingCoordinator.cpp
index 6d70329..dfa54b6 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -30,6 +30,7 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/Document.h"
 #include "core/dom/Node.h"
+#include "core/dom/TouchController.h"
 #include "core/dom/WheelController.h"
 #include "core/html/HTMLElement.h"
 #include "core/page/Frame.h"
@@ -287,7 +288,7 @@
             OwnPtr<WebScrollbarLayer> webScrollbarLayer;
             if (settings->useSolidColorScrollbars()) {
                 ASSERT(RuntimeEnabledFeatures::overlayScrollbarsEnabled());
-                webScrollbarLayer = createSolidColorScrollbarLayer(orientation, -1, scrollableArea->shouldPlaceVerticalScrollbarOnLeft());
+                webScrollbarLayer = createSolidColorScrollbarLayer(orientation, scrollbar->theme()->thumbThickness(scrollbar), scrollableArea->shouldPlaceVerticalScrollbarOnLeft());
             } else {
                 webScrollbarLayer = createScrollbarLayer(scrollbar);
             }
@@ -511,6 +512,32 @@
     setTouchEventTargetRects(touchEventTargetRects);
 }
 
+void ScrollingCoordinator::updateScrollParentForLayer(RenderLayer* child, RenderLayer* parent)
+{
+    WebLayer* childWebLayer = scrollingWebLayerForGraphicsLayer(child->layerForScrollChild());
+    if (!childWebLayer)
+        return;
+
+    WebLayer* scrollParentWebLayer = 0;
+    if (parent && parent->backing())
+        scrollParentWebLayer = scrollingWebLayerForGraphicsLayer(parent->backing()->parentForSublayers());
+
+    childWebLayer->setScrollParent(scrollParentWebLayer);
+}
+
+void ScrollingCoordinator::updateClipParentForLayer(RenderLayer* child, RenderLayer* parent)
+{
+    WebLayer* childWebLayer = scrollingWebLayerForGraphicsLayer(child->backing()->graphicsLayer());
+    if (!childWebLayer)
+        return;
+
+    WebLayer* clipParentWebLayer = 0;
+    if (parent && parent->backing())
+        clipParentWebLayer = scrollingWebLayerForGraphicsLayer(parent->backing()->parentForSublayers());
+
+    childWebLayer->setClipParent(clipParentWebLayer);
+}
+
 void ScrollingCoordinator::willDestroyRenderLayer(RenderLayer* layer)
 {
     m_layersWithTouchRects.remove(layer);
@@ -610,13 +637,14 @@
     return shouldHandleScrollGestureOnMainThreadRegion;
 }
 
-static void accumulateDocumentTouchEventTargetRects(LayerHitTestRects& rects, const Document* document)
+static void accumulateDocumentTouchEventTargetRects(LayerHitTestRects& rects, Document* document)
 {
     ASSERT(document);
-    if (!document->touchEventTargets())
+    TouchController* controller = TouchController::from(document);
+    if (!controller->touchEventTargets())
         return;
 
-    const TouchEventTargetSet* targets = document->touchEventTargets();
+    const TouchEventTargetSet* targets = controller->touchEventTargets();
 
     // If there's a handler on the document, html or body element (fairly common in practice),
     // then we can quickly mark the entire document and skip looking at any other handlers.
@@ -633,7 +661,7 @@
     }
 
     for (TouchEventTargetSet::const_iterator iter = targets->begin(); iter != targets->end(); ++iter) {
-        const Node* target = iter->key;
+        Node* target = iter->key;
         if (!target->inDocument())
             continue;
 
@@ -785,6 +813,11 @@
         // Any explicit reason that a fixed position element is not composited shouldn't cause slow scrolling.
         if (!layer->isComposited() && layer->viewportConstrainedNotCompositedReason() == RenderLayer::NoNotCompositedReason)
             return true;
+
+        // Composited layers that actually paint into their enclosing ancestor
+        // must also force main thread scrolling.
+        if (layer->isComposited() && layer->backing()->paintsIntoCompositedAncestor())
+            return true;
     }
     return false;
 }
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.h b/Source/core/page/scrolling/ScrollingCoordinator.h
index d94ea48..0f08aab 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.h
+++ b/Source/core/page/scrolling/ScrollingCoordinator.h
@@ -101,6 +101,9 @@
     void touchEventTargetRectsDidChange(const Document*);
     void willDestroyRenderLayer(RenderLayer*);
 
+    void updateScrollParentForLayer(RenderLayer* child, RenderLayer* parent);
+    void updateClipParentForLayer(RenderLayer* child, RenderLayer* parent);
+
     static String mainThreadScrollingReasonsAsText(MainThreadScrollingReasons);
     String mainThreadScrollingReasonsAsText() const;
     Region computeShouldHandleScrollGestureOnMainThreadRegion(const Frame*, const IntPoint& frameLocation) const;
diff --git a/Source/core/platform/AsyncFileSystemCallbacks.h b/Source/core/platform/AsyncFileSystemCallbacks.h
index 788ff1d..a210b99 100644
--- a/Source/core/platform/AsyncFileSystemCallbacks.h
+++ b/Source/core/platform/AsyncFileSystemCallbacks.h
@@ -50,6 +50,9 @@
     // Called when a requested file system is opened.
     virtual void didOpenFileSystem(const String& name, const KURL& rootURL) { ASSERT_NOT_REACHED(); }
 
+    // Called when a filesystem URL is resolved.
+    virtual void didResolveURL(const String& name, const KURL& rootURL, FileSystemType, const String& filePath, bool isDirectory) { ASSERT_NOT_REACHED(); }
+
     // Called when a file metadata is read successfully.
     virtual void didReadMetadata(const FileMetadata&) { ASSERT_NOT_REACHED(); }
 
diff --git a/Source/core/platform/Length.cpp b/Source/core/platform/Length.cpp
index 2699386..bb67fc4 100644
--- a/Source/core/platform/Length.cpp
+++ b/Source/core/platform/Length.cpp
@@ -144,6 +144,16 @@
         return m_map.get(index);
     }
 
+    void decrementRef(int index)
+    {
+        ASSERT(m_map.contains(index));
+        CalculationValue* value = m_map.get(index);
+        if (value->hasOneRef())
+            m_map.remove(index);
+        else
+            value->deref();
+    }
+
 private:
     int m_index;
     HashMap<int, RefPtr<CalculationValue> > m_map;
@@ -190,10 +200,7 @@
 void Length::decrementCalculatedRef() const
 {
     ASSERT(isCalculated());
-    RefPtr<CalculationValue> calcLength = calculationValue();
-    if (calcLength->hasOneRef())
-        calcHandles().remove(calculationHandle());
-    calcLength->deref();
+    calcHandles().decrementRef(calculationHandle());
 }
 
 float Length::nonNanCalculatedValue(int maxValue) const
diff --git a/Source/core/platform/LocalizedStrings.cpp b/Source/core/platform/LocalizedStrings.cpp
index d79d99c..c195272 100644
--- a/Source/core/platform/LocalizedStrings.cpp
+++ b/Source/core/platform/LocalizedStrings.cpp
@@ -35,7 +35,6 @@
 #include "core/platform/graphics/IntSize.h"
 #include "core/platform/text/DateTimeFormat.h"
 #include "public/platform/Platform.h"
-#include "public/platform/WebLocalizedString.h"
 #include "public/platform/WebString.h"
 #include "wtf/text/StringBuilder.h"
 #include "wtf/text/WTFString.h"
@@ -453,16 +452,6 @@
     return query(WebLocalizedString::ValidationTypeMismatch);
 }
 
-String validationMessageTypeMismatchForEmailText()
-{
-    return query(WebLocalizedString::ValidationTypeMismatchForEmail);
-}
-
-String validationMessageTypeMismatchForMultipleEmailText()
-{
-    return query(WebLocalizedString::ValidationTypeMismatchForMultipleEmail);
-}
-
 String validationMessageTypeMismatchForURLText()
 {
     return query(WebLocalizedString::ValidationTypeMismatchForURL);
@@ -488,11 +477,6 @@
     return query(WebLocalizedString::ValidationRangeOverflow, maximum);
 }
 
-String validationMessageStepMismatchText(const String& base, const String& step)
-{
-    return query(WebLocalizedString::ValidationStepMismatch, base, step);
-}
-
 String validationMessageBadInputForNumberText()
 {
     return query(WebLocalizedString::ValidationBadInputForNumber);
diff --git a/Source/core/platform/LocalizedStrings.h b/Source/core/platform/LocalizedStrings.h
index c3193b9..dce4df3 100644
--- a/Source/core/platform/LocalizedStrings.h
+++ b/Source/core/platform/LocalizedStrings.h
@@ -27,12 +27,15 @@
 #ifndef LocalizedStrings_h
 #define LocalizedStrings_h
 
+#include "public/platform/WebLocalizedString.h"
 #include "wtf/Forward.h"
 
 namespace WebCore {
 
     class IntSize;
 
+    // FIXME: Use Locale::queryString instead of the following functions.
+
     String inputElementAltText();
     String resetButtonDefaultLabel();
     String searchableIndexIntroduction();
@@ -111,14 +114,11 @@
     String validationMessageValueMissingForRadioText();
     String validationMessageValueMissingForSelectText();
     String validationMessageTypeMismatchText();
-    String validationMessageTypeMismatchForEmailText();
-    String validationMessageTypeMismatchForMultipleEmailText();
     String validationMessageTypeMismatchForURLText();
     String validationMessagePatternMismatchText();
     String validationMessageTooLongText(int valueLength, int maxLength);
     String validationMessageRangeUnderflowText(const String& minimum);
     String validationMessageRangeOverflowText(const String& maximum);
-    String validationMessageStepMismatchText(const String& base, const String& step);
     String validationMessageBadInputForNumberText();
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
     String validationMessageBadInputForDateTimeText();
diff --git a/Source/core/platform/Pasteboard.cpp b/Source/core/platform/Pasteboard.cpp
index 594cc79..0c36c92 100644
--- a/Source/core/platform/Pasteboard.cpp
+++ b/Source/core/platform/Pasteboard.cpp
@@ -63,18 +63,18 @@
 }
 
 Pasteboard::Pasteboard()
-    : m_selectionMode(false)
+    : m_buffer(WebKit::WebClipboard::BufferStandard)
 {
 }
 
 bool Pasteboard::isSelectionMode() const
 {
-    return m_selectionMode;
+    return m_buffer == WebKit::WebClipboard::BufferSelection;
 }
 
 void Pasteboard::setSelectionMode(bool selectionMode)
 {
-    m_selectionMode = selectionMode;
+    m_buffer = selectionMode ? WebKit::WebClipboard::BufferSelection : WebKit::WebClipboard::BufferStandard;
 }
 
 void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, const String& text)
@@ -155,24 +155,23 @@
 
 bool Pasteboard::canSmartReplace()
 {
-    return WebKit::Platform::current()->clipboard()->isFormatAvailable(WebKit::WebClipboard::FormatSmartPaste, m_selectionMode ? WebKit::WebClipboard::BufferSelection : WebKit::WebClipboard::BufferStandard);
+    return WebKit::Platform::current()->clipboard()->isFormatAvailable(WebKit::WebClipboard::FormatSmartPaste, m_buffer);
 }
 
 String Pasteboard::plainText()
 {
-    return WebKit::Platform::current()->clipboard()->readPlainText(m_selectionMode ? WebKit::WebClipboard::BufferSelection : WebKit::WebClipboard::BufferStandard);
+    return WebKit::Platform::current()->clipboard()->readPlainText(m_buffer);
 }
 
 PassRefPtr<DocumentFragment> Pasteboard::documentFragment(Frame* frame, PassRefPtr<Range> context, bool allowPlainText, bool& chosePlainText)
 {
     chosePlainText = false;
-    WebKit::WebClipboard::Buffer buffer = m_selectionMode ? WebKit::WebClipboard::BufferSelection : WebKit::WebClipboard::BufferStandard;
 
-    if (WebKit::Platform::current()->clipboard()->isFormatAvailable(WebKit::WebClipboard::FormatHTML, buffer)) {
+    if (WebKit::Platform::current()->clipboard()->isFormatAvailable(WebKit::WebClipboard::FormatHTML, m_buffer)) {
         unsigned fragmentStart = 0;
         unsigned fragmentEnd = 0;
         WebKit::WebURL url;
-        WebKit::WebString markup = WebKit::Platform::current()->clipboard()->readHTML(buffer, &url, &fragmentStart, &fragmentEnd);
+        WebKit::WebString markup = WebKit::Platform::current()->clipboard()->readHTML(m_buffer, &url, &fragmentStart, &fragmentEnd);
         if (!markup.isEmpty()) {
             ASSERT(frame->document());
             if (RefPtr<DocumentFragment> fragment = createFragmentFromMarkupWithContext(*frame->document(), markup, fragmentStart, fragmentEnd, KURL(url), DisallowScriptingAndPluginContent))
@@ -181,7 +180,7 @@
     }
 
     if (allowPlainText) {
-        String markup = WebKit::Platform::current()->clipboard()->readPlainText(buffer);
+        String markup = WebKit::Platform::current()->clipboard()->readPlainText(m_buffer);
         if (!markup.isEmpty()) {
             chosePlainText = true;
             if (RefPtr<DocumentFragment> fragment = createFragmentFromText(context.get(), markup))
diff --git a/Source/core/platform/Pasteboard.h b/Source/core/platform/Pasteboard.h
index 8e7c2d9..58a498e 100644
--- a/Source/core/platform/Pasteboard.h
+++ b/Source/core/platform/Pasteboard.h
@@ -26,6 +26,7 @@
 #ifndef Pasteboard_h
 #define Pasteboard_h
 
+#include "public/platform/WebClipboard.h"
 #include "wtf/Forward.h"
 #include "wtf/HashSet.h"
 #include "wtf/Noncopyable.h"
@@ -72,7 +73,7 @@
 private:
     Pasteboard();
 
-    bool m_selectionMode;
+    WebKit::WebClipboard::Buffer m_buffer;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/ScrollView.cpp b/Source/core/platform/ScrollView.cpp
index 17f4180..bbb2b2d 100644
--- a/Source/core/platform/ScrollView.cpp
+++ b/Source/core/platform/ScrollView.cpp
@@ -211,7 +211,7 @@
 
 IntSize ScrollView::layoutSize(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
 {
-    return m_fixedLayoutSize.isEmpty() || !m_useFixedLayout ? unscaledVisibleContentSize(scrollbarInclusion) : m_fixedLayoutSize;
+    return m_fixedLayoutSize.isZero() || !m_useFixedLayout ? unscaledVisibleContentSize(scrollbarInclusion) : m_fixedLayoutSize;
 }
 
 IntSize ScrollView::fixedLayoutSize() const
diff --git a/Source/core/platform/ScrollbarTheme.cpp b/Source/core/platform/ScrollbarTheme.cpp
index 158981e..4e910b0 100644
--- a/Source/core/platform/ScrollbarTheme.cpp
+++ b/Source/core/platform/ScrollbarTheme.cpp
@@ -299,6 +299,12 @@
     return thumbRect;
 }
 
+int ScrollbarTheme::thumbThickness(ScrollbarThemeClient* scrollbar)
+{
+    IntRect track = trackRect(scrollbar);
+    return scrollbar->orientation() == HorizontalScrollbar ? track.height() : track.width();
+}
+
 void ScrollbarTheme::paintOverhangBackground(ScrollView*, GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect& dirtyRect)
 {
     context->setFillColor(Color::white);
diff --git a/Source/core/platform/ScrollbarTheme.h b/Source/core/platform/ScrollbarTheme.h
index 3c31ab8..d1f3c24 100644
--- a/Source/core/platform/ScrollbarTheme.h
+++ b/Source/core/platform/ScrollbarTheme.h
@@ -59,8 +59,6 @@
     virtual bool usesOverlayScrollbars() const { return false; }
     virtual void updateScrollbarOverlayStyle(ScrollbarThemeClient*) { }
 
-    virtual void themeChanged() { }
-
     virtual bool invalidateOnMouseEnterExit() { return false; }
 
     void invalidateParts(ScrollbarThemeClient* scrollbar, ScrollbarControlPartMask mask)
@@ -114,6 +112,7 @@
     virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) = 0;
     virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) = 0;
     virtual IntRect thumbRect(ScrollbarThemeClient*);
+    virtual int thumbThickness(ScrollbarThemeClient*);
 
     virtual int minimumThumbLength(ScrollbarThemeClient*);
 
diff --git a/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp b/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp
index f76772f..88791df 100644
--- a/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp
+++ b/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp
@@ -45,7 +45,7 @@
 ScrollbarTheme* ScrollbarTheme::nativeTheme()
 {
     if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) {
-        DEFINE_STATIC_LOCAL(ScrollbarThemeOverlay, theme, (7, 0, ScrollbarThemeOverlay::AllowHitTest));
+        DEFINE_STATIC_LOCAL(ScrollbarThemeOverlay, theme, (10, 0, ScrollbarThemeOverlay::AllowHitTest, Color(128, 128, 128, 192)));
         return &theme;
     }
 
diff --git a/Source/core/platform/ScrollbarThemeOverlay.cpp b/Source/core/platform/ScrollbarThemeOverlay.cpp
index 97151de..4d705a0 100644
--- a/Source/core/platform/ScrollbarThemeOverlay.cpp
+++ b/Source/core/platform/ScrollbarThemeOverlay.cpp
@@ -104,6 +104,11 @@
     return rect;
 }
 
+int ScrollbarThemeOverlay::thumbThickness(ScrollbarThemeClient*)
+{
+    return m_thumbThickness;
+}
+
 void ScrollbarThemeOverlay::paintThumb(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
 {
     IntRect thumbRect = rect;
diff --git a/Source/core/platform/ScrollbarThemeOverlay.h b/Source/core/platform/ScrollbarThemeOverlay.h
index 14d6d31..0a7e2d1 100644
--- a/Source/core/platform/ScrollbarThemeOverlay.h
+++ b/Source/core/platform/ScrollbarThemeOverlay.h
@@ -51,6 +51,7 @@
     virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
     virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
     virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
+    virtual int thumbThickness(ScrollbarThemeClient*) OVERRIDE;
 
     virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
     virtual ScrollbarPart hitTest(ScrollbarThemeClient*, const IntPoint&) OVERRIDE;
diff --git a/Source/core/platform/Theme.h b/Source/core/platform/Theme.h
index f0a20f0..d4ba797 100644
--- a/Source/core/platform/Theme.h
+++ b/Source/core/platform/Theme.h
@@ -75,9 +75,6 @@
     // How fast the caret blinks in text fields.
     virtual double caretBlinkInterval() const { return 0.5; }
 
-    // Notification when the theme has changed
-    virtual void themeChanged() { }
-
     // Methods used to adjust the RenderStyles of controls.
 
     // The font description result should have a zoomed font size.
@@ -105,10 +102,6 @@
     // amount is also scaled by the zoomFactor.
     virtual void inflateControlPaintRect(ControlPart, ControlStates, IntRect& /*zoomedRect*/, float /*zoomFactor*/) const { }
 
-    // This method is called once, from RenderTheme::adjustDefaultStyleSheet(), to let each platform adjust
-    // the default CSS rules in html.css.
-    static String defaultStyleSheet();
-
 private:
     mutable Color m_activeSelectionColor;
     mutable Color m_inactiveSelectionColor;
diff --git a/Source/core/platform/animation/TimingFunction.h b/Source/core/platform/animation/TimingFunction.h
index c4bb368..5ee8507 100644
--- a/Source/core/platform/animation/TimingFunction.h
+++ b/Source/core/platform/animation/TimingFunction.h
@@ -26,11 +26,13 @@
 #define TimingFunction_h
 
 #include "RuntimeEnabledFeatures.h"
+#include "core/platform/animation/AnimationUtilities.h" // For blend()
 #include "core/platform/graphics/UnitBezier.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
 #include <algorithm>
 
 namespace WebCore {
@@ -39,7 +41,7 @@
 public:
 
     enum Type {
-        LinearFunction, CubicBezierFunction, StepsFunction
+        LinearFunction, CubicBezierFunction, StepsFunction, ChainedFunction
     };
 
     virtual ~TimingFunction() { }
@@ -254,6 +256,73 @@
     SubType m_subType;
 };
 
+class ChainedTimingFunction : public TimingFunction {
+public:
+    static PassRefPtr<ChainedTimingFunction> create()
+    {
+        return adoptRef(new ChainedTimingFunction);
+    }
+
+    void appendSegment(double upperBound, TimingFunction* timingFunction)
+    {
+        double max = m_segments.isEmpty() ? 0 : m_segments.last().max();
+        ASSERT(upperBound > max);
+        m_segments.append(Segment(max, upperBound, timingFunction));
+    }
+    virtual double evaluate(double fraction, double accuracy) const
+    {
+        RELEASE_ASSERT_WITH_MESSAGE(fraction >= 0 && fraction <= 1, "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+        ASSERT(!m_segments.isEmpty());
+        ASSERT(m_segments.last().max() == 1);
+        const Segment* segment;
+        for (size_t i = 0; i < m_segments.size(); ++i) {
+            segment = &m_segments[i];
+            if (fraction < segment->max())
+                break;
+        }
+        return segment->evaluate(fraction, accuracy);
+    }
+
+    virtual bool operator==(const TimingFunction& other) const
+    {
+        // This class is not exposed to CSS, so this method is not required.
+        ASSERT_NOT_REACHED();
+        return false;
+    }
+
+private:
+    class Segment {
+    public:
+        Segment(double min, double max, TimingFunction* timingFunction)
+            : m_min(min)
+            , m_max(max)
+            , m_timingFunction(timingFunction)
+        { }
+
+        double max() const { return m_max; }
+        double evaluate(double fraction, double accuracy) const
+        {
+            return scaleFromLocal(m_timingFunction->evaluate(scaleToLocal(fraction), accuracy));
+        }
+
+    private:
+        double scaleToLocal(double x) const { return (x - m_min) / (m_max - m_min); }
+        double scaleFromLocal(double x) const { return blend(m_min, m_max, x); }
+
+        double m_min;
+        double m_max;
+        RefPtr<TimingFunction> m_timingFunction;
+    };
+
+    ChainedTimingFunction()
+        : TimingFunction(ChainedFunction)
+    {
+        ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled());
+    }
+
+    Vector<Segment> m_segments;
+};
+
 } // namespace WebCore
 
 #endif // TimingFunction_h
diff --git a/Source/core/platform/chromium/Prerender.cpp b/Source/core/platform/chromium/Prerender.cpp
index 0f60968..3b17885 100644
--- a/Source/core/platform/chromium/Prerender.cpp
+++ b/Source/core/platform/chromium/Prerender.cpp
@@ -47,6 +47,7 @@
     , m_url(url)
     , m_referrer(referrer)
     , m_referrerPolicy(policy)
+    , m_isActive(false)
 {
 }
 
@@ -61,6 +62,8 @@
 
 void Prerender::add()
 {
+    ASSERT(!m_isActive);
+    m_isActive = true;
     WebKit::WebPrerenderingSupport* platform = WebKit::WebPrerenderingSupport::current();
     if (!platform)
         return;
@@ -69,6 +72,12 @@
 
 void Prerender::cancel()
 {
+    // The LinkLoader and the Document (via Prerenderer) share ownership of
+    // the Prerender, so it may have been abandoned by the Prerenderer and
+    // then later canceled by the LinkLoader.
+    if (!m_isActive)
+        return;
+    m_isActive = false;
     WebKit::WebPrerenderingSupport* platform = WebKit::WebPrerenderingSupport::current();
     if (!platform)
         return;
@@ -77,6 +86,12 @@
 
 void Prerender::abandon()
 {
+    // The LinkLoader and the Document (via Prerenderer) share ownership of
+    // the Prerender, so it may have been canceled by the LinkLoader and
+    // then later abandoned by the Prerenderer.
+    if (!m_isActive)
+        return;
+    m_isActive = false;
     WebKit::WebPrerenderingSupport* platform = WebKit::WebPrerenderingSupport::current();
     if (!platform)
         return;
diff --git a/Source/core/platform/chromium/Prerender.h b/Source/core/platform/chromium/Prerender.h
index 3a994ea..8177f0b 100644
--- a/Source/core/platform/chromium/Prerender.h
+++ b/Source/core/platform/chromium/Prerender.h
@@ -87,6 +87,8 @@
     const String m_referrer;
     const ReferrerPolicy m_referrerPolicy;
 
+    bool m_isActive;
+
     RefPtr<ExtraData> m_extraData;
 };
 
diff --git a/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp b/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp
index a0c7525..2430c54 100644
--- a/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp
+++ b/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp
@@ -128,6 +128,13 @@
     m_private.reset();
 }
 
+void WebFileSystemCallbacks::didResolveURL(const WebString& name, const WebURL& rootURL, WebFileSystemType type, const WebString& filePath, bool isDirectory)
+{
+    ASSERT(!m_private.isNull());
+    m_private->callbacks()->didResolveURL(name, rootURL, static_cast<WebCore::FileSystemType>(type), filePath, isDirectory);
+    m_private.reset();
+}
+
 void WebFileSystemCallbacks::didCreateFileWriter(WebFileWriter* webFileWriter, long long length)
 {
     ASSERT(!m_private.isNull());
diff --git a/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp b/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
index a671a60..8da7cbd 100644
--- a/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
+++ b/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
@@ -31,6 +31,7 @@
 #include "public/platform/WebMediaStream.h"
 #include "public/platform/WebMediaStreamSource.h"
 #include "public/platform/WebString.h"
+#include "public/web/WebAudioSourceProvider.h"
 #include "wtf/Vector.h"
 
 using namespace WebCore;
@@ -102,6 +103,14 @@
     return WebMediaStreamSource(m_private->source());
 }
 
+void WebMediaStreamTrack::setSourceProvider(WebAudioSourceProvider* provider)
+{
+#if ENABLE(WEB_AUDIO)
+    ASSERT(!m_private.isNull());
+    m_private->setSourceProvider(provider);
+#endif // ENABLE(WEB_AUDIO)
+}
+
 void WebMediaStreamTrack::assign(const WebMediaStreamTrack& other)
 {
     m_private = other.m_private;
diff --git a/Source/core/platform/graphics/FloatPolygon.cpp b/Source/core/platform/graphics/FloatPolygon.cpp
index 85f75fa..c455a3e 100644
--- a/Source/core/platform/graphics/FloatPolygon.cpp
+++ b/Source/core/platform/graphics/FloatPolygon.cpp
@@ -156,11 +156,25 @@
     return ((point.x() - vertex1.x()) * (vertex2.y() - vertex1.y())) - ((vertex2.x() - vertex1.x()) * (point.y() - vertex1.y()));
 }
 
-bool FloatPolygon::contains(const FloatPoint& point) const
+bool FloatPolygon::containsEvenOdd(const FloatPoint& point) const
 {
-    if (!m_boundingBox.contains(point))
-        return false;
+    unsigned crossingCount = 0;
+    for (unsigned i = 0; i < numberOfEdges(); ++i) {
+        const FloatPoint& vertex1 = edgeAt(i).vertex1();
+        const FloatPoint& vertex2 = edgeAt(i).vertex2();
+        if (isPointOnLineSegment(vertex1, vertex2, point))
+            return true;
+        if ((vertex1.y() <= point.y() && vertex2.y() > point.y()) || (vertex1.y() > point.y() && vertex2.y() <= point.y())) {
+            float vt = (point.y()  - vertex1.y()) / (vertex2.y() - vertex1.y());
+            if (point.x() < vertex1.x() + vt * (vertex2.x() - vertex1.x()))
+                ++crossingCount;
+        }
+    }
+    return crossingCount & 1;
+}
 
+bool FloatPolygon::containsNonZero(const FloatPoint& point) const
+{
     int windingNumber = 0;
     for (unsigned i = 0; i < numberOfEdges(); ++i) {
         const FloatPoint& vertex1 = edgeAt(i).vertex1();
@@ -175,10 +189,16 @@
                 --windingNumber;
         }
     }
-
     return windingNumber;
 }
 
+bool FloatPolygon::contains(const FloatPoint& point) const
+{
+    if (!m_boundingBox.contains(point))
+        return false;
+    return (fillRule() == RULE_NONZERO) ? containsNonZero(point) : containsEvenOdd(point);
+}
+
 bool VertexPair::overlapsRect(const FloatRect& rect) const
 {
     bool boundsOverlap = (minX() < rect.maxX()) && (maxX() > rect.x()) && (minY() < rect.maxY()) && (maxY() > rect.y());
diff --git a/Source/core/platform/graphics/FloatPolygon.h b/Source/core/platform/graphics/FloatPolygon.h
index 389aa2a..c2ab193 100644
--- a/Source/core/platform/graphics/FloatPolygon.h
+++ b/Source/core/platform/graphics/FloatPolygon.h
@@ -68,6 +68,9 @@
     typedef PODInterval<float, FloatPolygonEdge*> EdgeInterval;
     typedef PODIntervalTree<float, FloatPolygonEdge*> EdgeIntervalTree;
 
+    bool containsNonZero(const FloatPoint&) const;
+    bool containsEvenOdd(const FloatPoint&) const;
+
     OwnPtr<Vector<FloatPoint> > m_vertices;
     WindRule m_fillRule;
     FloatRect m_boundingBox;
diff --git a/Source/core/platform/graphics/FontCache.cpp b/Source/core/platform/graphics/FontCache.cpp
index 143765a..2d7403c 100644
--- a/Source/core/platform/graphics/FontCache.cpp
+++ b/Source/core/platform/graphics/FontCache.cpp
@@ -31,6 +31,7 @@
 #include "core/platform/graphics/FontCache.h"
 
 #include "FontFamilyNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/FontFallbackList.h"
 #include "core/platform/graphics/FontPlatformData.h"
@@ -63,9 +64,9 @@
 struct FontPlatformDataCacheKey {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    FontPlatformDataCacheKey(const AtomicString& family = AtomicString(), unsigned size = 0, unsigned weight = 0, bool italic = false,
+    FontPlatformDataCacheKey(const AtomicString& family = AtomicString(), float size = 0, unsigned weight = 0, bool italic = false,
         bool isPrinterFont = false, FontOrientation orientation = Horizontal, FontWidthVariant widthVariant = RegularWidth)
-        : m_size(size)
+        : m_size(size * s_fontSizePrecisionMultiplier)
         , m_weight(weight)
         , m_family(family)
         , m_italic(italic)
@@ -94,6 +95,10 @@
     FontWidthVariant m_widthVariant;
 
 private:
+    // Multiplying the floating point size by 100 gives two decimal
+    // point precision which should be sufficient.
+    static const unsigned s_fontSizePrecisionMultiplier = 100;
+
     static unsigned hashTableDeletedSize() { return 0xFFFFFFFFU; }
 };
 
@@ -197,7 +202,13 @@
         platformInit();
     }
 
-    FontPlatformDataCacheKey key(familyName, fontDescription.computedPixelSize(), fontDescription.weight(), fontDescription.italic(),
+    float fontSize;
+    if (RuntimeEnabledFeatures::subpixelFontScalingEnabled())
+        fontSize = fontDescription.computedSize();
+    else
+        fontSize = fontDescription.computedPixelSize();
+    FontPlatformDataCacheKey key(familyName, fontSize, fontDescription.weight(), fontDescription.italic(),
+
         fontDescription.usePrinterFont(), fontDescription.orientation(), fontDescription.widthVariant());
     FontPlatformData* result = 0;
     bool foundResult;
diff --git a/Source/core/platform/graphics/FontFallbackList.cpp b/Source/core/platform/graphics/FontFallbackList.cpp
index e3405e5..a68e8ba 100644
--- a/Source/core/platform/graphics/FontFallbackList.cpp
+++ b/Source/core/platform/graphics/FontFallbackList.cpp
@@ -88,6 +88,21 @@
     }
 }
 
+bool FontFallbackList::loadingCustomFonts() const
+{
+    if (m_loadingCustomFonts)
+        return true;
+
+    unsigned numFonts = m_fontList.size();
+    for (unsigned i = 0; i < numFonts; ++i) {
+        if (m_fontList[i]->isCustomFont() && m_fontList[i]->isLoading()) {
+            m_loadingCustomFonts = true;
+            return true;
+        }
+    }
+    return false;
+}
+
 const FontData* FontFallbackList::fontDataAt(const Font* font, unsigned realizedFontIndex) const
 {
     if (realizedFontIndex < m_fontList.size())
diff --git a/Source/core/platform/graphics/FontFallbackList.h b/Source/core/platform/graphics/FontFallbackList.h
index edf8dcb..a952158 100644
--- a/Source/core/platform/graphics/FontFallbackList.h
+++ b/Source/core/platform/graphics/FontFallbackList.h
@@ -73,7 +73,7 @@
     bool isFixedPitch(const Font* f) const { if (m_pitch == UnknownPitch) determinePitch(f); return m_pitch == FixedPitch; };
     void determinePitch(const Font*) const;
 
-    bool loadingCustomFonts() const { return m_loadingCustomFonts; }
+    bool loadingCustomFonts() const;
 
     FontSelector* fontSelector() const { return m_fontSelector.get(); }
     // FIXME: It should be possible to combine fontSelectorVersion and generation.
@@ -88,8 +88,11 @@
     const SimpleFontData* primarySimpleFontData(const Font* f)
     {
         ASSERT(isMainThread());
-        if (!m_cachedPrimarySimpleFontData)
+        if (!m_cachedPrimarySimpleFontData) {
             m_cachedPrimarySimpleFontData = primaryFontData(f)->fontDataForCharacter(' ');
+            if (m_cachedPrimarySimpleFontData)
+                m_cachedPrimarySimpleFontData->beginLoadIfNeeded();
+        }
         return m_cachedPrimarySimpleFontData;
     }
 
diff --git a/Source/core/platform/graphics/GlyphPageTreeNode.cpp b/Source/core/platform/graphics/GlyphPageTreeNode.cpp
index 7a23d13..23a66b7 100644
--- a/Source/core/platform/graphics/GlyphPageTreeNode.cpp
+++ b/Source/core/platform/graphics/GlyphPageTreeNode.cpp
@@ -226,6 +226,14 @@
                     int from = max(0, static_cast<int>(range.from()) - static_cast<int>(start));
                     int to = 1 + min(static_cast<int>(range.to()) - static_cast<int>(start), static_cast<int>(GlyphPage::size) - 1);
                     if (from < static_cast<int>(GlyphPage::size) && to > 0) {
+                        // If this is a custom font needs to be loaded, kick off
+                        // the load here, and do not fill the page so that
+                        // font fallback is used while loading.
+                        if (range.fontData()->isLoadingFallback()) {
+                            range.fontData()->beginLoadIfNeeded();
+                            continue;
+                        }
+
                         if (haveGlyphs && !scratchPage) {
                             scratchPage = GlyphPage::createForMixedFontData(this);
                             pageToFill = scratchPage.get();
diff --git a/Source/core/platform/graphics/GraphicsContext.cpp b/Source/core/platform/graphics/GraphicsContext.cpp
index 32b266f..7454a1f 100644
--- a/Source/core/platform/graphics/GraphicsContext.cpp
+++ b/Source/core/platform/graphics/GraphicsContext.cpp
@@ -439,9 +439,10 @@
         return;
 
     SkPaint layerPaint;
-    layerPaint.setXfermode(maskType == AlphaMaskType
+    RefPtr<SkXfermode> xferMode = adoptRef(maskType == AlphaMaskType
         ? SkXfermode::Create(SkXfermode::kSrcIn_Mode)
         : SkLumaMaskXfermode::Create(SkXfermode::kSrcIn_Mode));
+    layerPaint.setXfermode(xferMode.get());
 
     SkRect skBounds = WebCoreFloatRectToSKRect(bounds);
     saveLayer(&skBounds, &layerPaint);
@@ -1119,7 +1120,9 @@
     if (paintingDisabled())
         return;
 
-    m_canvas->drawBitmapRectToRect(bitmap, src, dst, paint);
+    SkCanvas::DrawBitmapRectFlags flags = m_state->m_shouldClampToSourceRect ? SkCanvas::kNone_DrawBitmapRectFlag : SkCanvas::kBleed_DrawBitmapRectFlag;
+
+    m_canvas->drawBitmapRectToRect(bitmap, src, dst, paint, flags);
 
     if (m_trackOpaqueRegion)
         m_opaqueRegion.didDrawRect(this, dst, *paint, &bitmap);
diff --git a/Source/core/platform/graphics/GraphicsContext.h b/Source/core/platform/graphics/GraphicsContext.h
index ac6e851..b541fa0 100644
--- a/Source/core/platform/graphics/GraphicsContext.h
+++ b/Source/core/platform/graphics/GraphicsContext.h
@@ -141,6 +141,9 @@
     void setShouldAntialias(bool antialias) { m_state->m_shouldAntialias = antialias; }
     bool shouldAntialias() const { return m_state->m_shouldAntialias; }
 
+    void setShouldClampToSourceRect(bool clampToSourceRect) { m_state->m_shouldClampToSourceRect = clampToSourceRect; }
+    bool shouldClampToSourceRect() const { return m_state->m_shouldClampToSourceRect; }
+
     void setShouldSmoothFonts(bool smoothFonts) { m_state->m_shouldSmoothFonts = smoothFonts; }
     bool shouldSmoothFonts() const { return m_state->m_shouldSmoothFonts; }
 
diff --git a/Source/core/platform/graphics/GraphicsContext3D.cpp b/Source/core/platform/graphics/GraphicsContext3D.cpp
index 5e2b93c..e01c27e 100644
--- a/Source/core/platform/graphics/GraphicsContext3D.cpp
+++ b/Source/core/platform/graphics/GraphicsContext3D.cpp
@@ -362,6 +362,7 @@
 }
 
 DELEGATE_TO_WEBCONTEXT_R(makeContextCurrent, bool)
+DELEGATE_TO_WEBCONTEXT_R(lastFlushID, uint32_t)
 
 DELEGATE_TO_WEBCONTEXT_1(activeTexture, GC3Denum)
 DELEGATE_TO_WEBCONTEXT_2(attachShader, Platform3DObject, Platform3DObject)
diff --git a/Source/core/platform/graphics/GraphicsContext3D.h b/Source/core/platform/graphics/GraphicsContext3D.h
index 4c4aca7..c7a18b0 100644
--- a/Source/core/platform/graphics/GraphicsContext3D.h
+++ b/Source/core/platform/graphics/GraphicsContext3D.h
@@ -445,6 +445,8 @@
 
     bool makeContextCurrent();
 
+    uint32_t lastFlushID();
+
     // Helper to texImage2D with pixel==0 case: pixels are initialized to 0.
     // Return true if no GL error is synthesized.
     // By default, alignment is 4, the OpenGL default setting.
diff --git a/Source/core/platform/graphics/GraphicsContextState.h b/Source/core/platform/graphics/GraphicsContextState.h
index dd5c2b1..eed9fd5 100644
--- a/Source/core/platform/graphics/GraphicsContextState.h
+++ b/Source/core/platform/graphics/GraphicsContextState.h
@@ -64,6 +64,7 @@
 #endif
         , m_shouldAntialias(true)
         , m_shouldSmoothFonts(true)
+        , m_shouldClampToSourceRect(true)
     {
     }
 
@@ -83,6 +84,7 @@
         , m_interpolationQuality(other.m_interpolationQuality)
         , m_shouldAntialias(other.m_shouldAntialias)
         , m_shouldSmoothFonts(other.m_shouldSmoothFonts)
+        , m_shouldClampToSourceRect(other.m_shouldClampToSourceRect)
     {
     }
 
@@ -135,6 +137,7 @@
 
     bool m_shouldAntialias : 1;
     bool m_shouldSmoothFonts : 1;
+    bool m_shouldClampToSourceRect : 1;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/GraphicsLayer.cpp b/Source/core/platform/graphics/GraphicsLayer.cpp
index 8955250..6bae3b2 100644
--- a/Source/core/platform/graphics/GraphicsLayer.cpp
+++ b/Source/core/platform/graphics/GraphicsLayer.cpp
@@ -103,7 +103,6 @@
     , m_paintCount(0)
     , m_contentsLayer(0)
     , m_contentsLayerId(0)
-    , m_linkHighlight(0)
     , m_contentsLayerPurpose(NoContentsLayer)
     , m_scrollableArea(0)
     , m_compositingReasons(WebKit::CompositingReasonUnknown)
@@ -122,10 +121,9 @@
 
 GraphicsLayer::~GraphicsLayer()
 {
-    if (m_linkHighlight) {
-        m_linkHighlight->clearCurrentGraphicsLayer();
-        m_linkHighlight = 0;
-    }
+    for (size_t i = 0; i < m_linkHighlights.size(); ++i)
+        m_linkHighlights[i]->clearCurrentGraphicsLayer();
+    m_linkHighlights.clear();
 
 #ifndef NDEBUG
     if (m_client)
@@ -403,8 +401,8 @@
         childHost->addChild(curChild->platformLayer());
     }
 
-    if (m_linkHighlight)
-        childHost->addChild(m_linkHighlight->layer());
+    for (size_t i = 0; i < m_linkHighlights.size(); ++i)
+        childHost->addChild(m_linkHighlights[i]->layer());
 }
 
 void GraphicsLayer::updateLayerIsDrawable()
@@ -420,8 +418,8 @@
 
     if (m_drawsContent) {
         m_layer->layer()->invalidate();
-        if (m_linkHighlight)
-            m_linkHighlight->invalidate();
+        for (size_t i = 0; i < m_linkHighlights.size(); ++i)
+            m_linkHighlights[i]->invalidate();
     }
 }
 
@@ -746,10 +744,18 @@
     if (!m_client)
         return name;
 
+    String highlightDebugName;
+    for (size_t i = 0; i < m_linkHighlights.size(); ++i) {
+        if (webLayer == m_linkHighlights[i]->layer()) {
+            highlightDebugName = "LinkHighlight[" + String::number(i) + "] for " + m_client->debugName(this);
+            break;
+        }
+    }
+
     if (webLayer == m_contentsLayer) {
         name = "ContentsLayer for " + m_client->debugName(this);
-    } else if (m_linkHighlight && webLayer == m_linkHighlight->layer()) {
-        name = "LinkHighlight for " + m_client->debugName(this);
+    } else if (!highlightDebugName.isEmpty()) {
+        name = highlightDebugName;
     } else if (webLayer == m_layer->layer()) {
         name = m_client->debugName(this);
     } else {
@@ -896,8 +902,8 @@
     if (drawsContent()) {
         m_layer->layer()->invalidate();
         addRepaintRect(FloatRect(FloatPoint(), m_size));
-        if (m_linkHighlight)
-            m_linkHighlight->invalidate();
+        for (size_t i = 0; i < m_linkHighlights.size(); ++i)
+            m_linkHighlights[i]->invalidate();
     }
 }
 
@@ -906,8 +912,8 @@
     if (drawsContent()) {
         m_layer->layer()->invalidateRect(rect);
         addRepaintRect(rect);
-        if (m_linkHighlight)
-            m_linkHighlight->invalidate();
+        for (size_t i = 0; i < m_linkHighlights.size(); ++i)
+            m_linkHighlights[i]->invalidate();
     }
 }
 
@@ -1148,11 +1154,17 @@
     m_layer->layer()->setBackgroundFilters(*webFilters);
 }
 
-void GraphicsLayer::setLinkHighlight(LinkHighlightClient* linkHighlight)
+void GraphicsLayer::addLinkHighlight(LinkHighlightClient* linkHighlight)
 {
-    m_linkHighlight = linkHighlight;
-    if (m_linkHighlight)
-        m_linkHighlight->layer()->setWebLayerClient(this);
+    ASSERT(linkHighlight && !m_linkHighlights.contains(linkHighlight));
+    m_linkHighlights.append(linkHighlight);
+    linkHighlight->layer()->setWebLayerClient(this);
+    updateChildList();
+}
+
+void GraphicsLayer::removeLinkHighlight(LinkHighlightClient* linkHighlight)
+{
+    m_linkHighlights.remove(m_linkHighlights.find(linkHighlight));
     updateChildList();
 }
 
diff --git a/Source/core/platform/graphics/GraphicsLayer.h b/Source/core/platform/graphics/GraphicsLayer.h
index 7572b3c..ddd2609 100644
--- a/Source/core/platform/graphics/GraphicsLayer.h
+++ b/Source/core/platform/graphics/GraphicsLayer.h
@@ -42,6 +42,7 @@
 #include "wtf/HashMap.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
 
 #include "public/platform/WebAnimationDelegate.h"
 #include "public/platform/WebCompositingReasons.h"
@@ -288,9 +289,11 @@
         return false;
     }
 
-    void setLinkHighlight(LinkHighlightClient*);
+    void addLinkHighlight(LinkHighlightClient*);
+    void removeLinkHighlight(LinkHighlightClient*);
     // Exposed for tests
-    LinkHighlightClient* linkHighlight() { return m_linkHighlight; }
+    unsigned numLinkHighlights() { return m_linkHighlights.size(); }
+    LinkHighlightClient* linkHighlight(int i) { return m_linkHighlights[i]; }
 
     void setScrollableArea(ScrollableArea*, bool isMainFrame);
     ScrollableArea* scrollableArea() const { return m_scrollableArea; }
@@ -401,7 +404,7 @@
     // on.
     int m_contentsLayerId;
 
-    LinkHighlightClient* m_linkHighlight;
+    Vector<LinkHighlightClient*> m_linkHighlights;
 
     OwnPtr<OpaqueRectTrackingContentLayerDelegate> m_opaqueRectTrackingContentLayerDelegate;
 
diff --git a/Source/core/platform/graphics/ImageBuffer.cpp b/Source/core/platform/graphics/ImageBuffer.cpp
index 1ecdaaf..c13ba04 100644
--- a/Source/core/platform/graphics/ImageBuffer.cpp
+++ b/Source/core/platform/graphics/ImageBuffer.cpp
@@ -64,7 +64,7 @@
 
 namespace WebCore {
 
-static SkCanvas* createAcceleratedCanvas(const IntSize& size, Canvas2DLayerBridgePtr* outLayerBridge, OpacityMode opacityMode)
+static PassRefPtr<SkCanvas> createAcceleratedCanvas(const IntSize& size, Canvas2DLayerBridgePtr* outLayerBridge, OpacityMode opacityMode)
 {
     RefPtr<GraphicsContext3D> context3D = SharedGraphicsContext3D::get();
     if (!context3D)
@@ -76,11 +76,11 @@
     return (*outLayerBridge) ? (*outLayerBridge)->getCanvas() : 0;
 }
 
-static SkCanvas* createNonPlatformCanvas(const IntSize& size)
+static PassRefPtr<SkCanvas> createNonPlatformCanvas(const IntSize& size)
 {
     SkAutoTUnref<SkBaseDevice> device(new SkBitmapDevice(SkBitmap::kARGB_8888_Config, size.width(), size.height()));
     SkPixelRef* pixelRef = device->accessBitmap(false).pixelRef();
-    return pixelRef ? new SkCanvas(device) : 0;
+    return adoptRef(pixelRef ? new SkCanvas(device) : 0);
 }
 
 PassOwnPtr<ImageBuffer> ImageBuffer::createCompatibleBuffer(const IntSize& size, float resolutionScale, const GraphicsContext* context, bool hasAlpha)
@@ -114,7 +114,7 @@
         return;
     }
 
-    m_canvas = adoptPtr(new SkCanvas(device));
+    m_canvas = adoptRef(new SkCanvas(device));
     m_context = adoptPtr(new GraphicsContext(m_canvas.get()));
     m_context->setCertainlyOpaque(!hasAlpha);
     m_context->scale(FloatSize(m_resolutionScale, m_resolutionScale));
@@ -128,16 +128,16 @@
     , m_resolutionScale(resolutionScale)
 {
     if (renderingMode == Accelerated) {
-        m_canvas = adoptPtr(createAcceleratedCanvas(size, &m_layerBridge, opacityMode));
+        m_canvas = createAcceleratedCanvas(size, &m_layerBridge, opacityMode);
         if (!m_canvas)
             renderingMode = UnacceleratedNonPlatformBuffer;
     }
 
     if (renderingMode == UnacceleratedNonPlatformBuffer)
-        m_canvas = adoptPtr(createNonPlatformCanvas(size));
+        m_canvas = createNonPlatformCanvas(size);
 
     if (!m_canvas)
-        m_canvas = adoptPtr(skia::TryCreateBitmapCanvas(size.width(), size.height(), false));
+        m_canvas = adoptRef(skia::TryCreateBitmapCanvas(size.width(), size.height(), false));
 
     if (!m_canvas) {
         success = false;
diff --git a/Source/core/platform/graphics/ImageBuffer.h b/Source/core/platform/graphics/ImageBuffer.h
index b34b4ea..5c2d771 100644
--- a/Source/core/platform/graphics/ImageBuffer.h
+++ b/Source/core/platform/graphics/ImageBuffer.h
@@ -142,7 +142,7 @@
     IntSize m_size;
     IntSize m_logicalSize;
     float m_resolutionScale;
-    OwnPtr<SkCanvas> m_canvas;
+    RefPtr<SkCanvas> m_canvas;
     OwnPtr<GraphicsContext> m_context;
     Canvas2DLayerBridgePtr m_layerBridge;
 
diff --git a/Source/core/platform/graphics/SegmentedFontData.h b/Source/core/platform/graphics/SegmentedFontData.h
index c57fca9..dda2960 100644
--- a/Source/core/platform/graphics/SegmentedFontData.h
+++ b/Source/core/platform/graphics/SegmentedFontData.h
@@ -80,6 +80,12 @@
     Vector<FontDataRange, 1> m_ranges;
 };
 
+inline SegmentedFontData* toSegmentedFontData(FontData* fontData)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!fontData || fontData->isSegmented());
+    return static_cast<SegmentedFontData*>(fontData);
+}
+
 } // namespace WebCore
 
 #endif // SegmentedFontData_h
diff --git a/Source/core/platform/graphics/SimpleFontData.cpp b/Source/core/platform/graphics/SimpleFontData.cpp
index 7276f15..8dcc30f 100644
--- a/Source/core/platform/graphics/SimpleFontData.cpp
+++ b/Source/core/platform/graphics/SimpleFontData.cpp
@@ -30,6 +30,7 @@
 #include "config.h"
 #include "core/platform/graphics/SimpleFontData.h"
 
+#include "core/css/CSSFontFaceSource.h"
 #include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
 
 #include "wtf/MathExtras.h"
@@ -42,19 +43,18 @@
 const float smallCapsFontSizeMultiplier = 0.7f;
 const float emphasisMarkFontSizeMultiplier = 0.5f;
 
-SimpleFontData::SimpleFontData(const FontPlatformData& platformData, bool isCustomFont, bool isLoading, bool isTextOrientationFallback)
+SimpleFontData::SimpleFontData(const FontPlatformData& platformData, bool isCustomFont, bool isLoadingFallback, bool isTextOrientationFallback)
     : m_maxCharWidth(-1)
     , m_avgCharWidth(-1)
     , m_platformData(platformData)
     , m_treatAsFixedPitch(false)
-    , m_isCustomFont(isCustomFont)
-    , m_isLoading(isLoading)
     , m_isTextOrientationFallback(isTextOrientationFallback)
     , m_isBrokenIdeographFallback(false)
 #if ENABLE(OPENTYPE_VERTICAL)
     , m_verticalData(0)
 #endif
     , m_hasVerticalGlyphs(false)
+    , m_customFontData(isCustomFont, isLoadingFallback)
 {
     platformInit();
     platformGlyphInit();
@@ -71,14 +71,13 @@
     : m_platformData(FontPlatformData(fontSize, syntheticBold, syntheticItalic))
     , m_fontData(fontData)
     , m_treatAsFixedPitch(false)
-    , m_isCustomFont(true)
-    , m_isLoading(false)
     , m_isTextOrientationFallback(false)
     , m_isBrokenIdeographFallback(false)
 #if ENABLE(OPENTYPE_VERTICAL)
     , m_verticalData(0)
 #endif
     , m_hasVerticalGlyphs(false)
+    , m_customFontData(true, false)
 {
     m_fontData->initializeFontData(this, fontSize);
 }
@@ -226,6 +225,14 @@
     return m_derivedFontData->brokenIdeograph;
 }
 
+void SimpleFontData::beginLoadIfNeeded() const
+{
+    if (!m_customFontData.isUsed && m_customFontData.isLoadingFallback && m_customFontData.fontFaceSource) {
+        m_customFontData.isUsed = true;
+        m_customFontData.fontFaceSource->beginLoadingFontSoon();
+    }
+}
+
 #ifndef NDEBUG
 String SimpleFontData::description() const
 {
diff --git a/Source/core/platform/graphics/SimpleFontData.h b/Source/core/platform/graphics/SimpleFontData.h
index 1d0a1ed..ebcf8ab 100644
--- a/Source/core/platform/graphics/SimpleFontData.h
+++ b/Source/core/platform/graphics/SimpleFontData.h
@@ -47,6 +47,7 @@
 
 namespace WebCore {
 
+class CSSFontFaceSource;
 class FontDescription;
 class SharedBuffer;
 struct WidthIterator;
@@ -68,9 +69,9 @@
     };
 
     // Used to create platform fonts.
-    static PassRefPtr<SimpleFontData> create(const FontPlatformData& platformData, bool isCustomFont = false, bool isLoading = false, bool isTextOrientationFallback = false)
+    static PassRefPtr<SimpleFontData> create(const FontPlatformData& platformData, bool isCustomFont = false, bool isLoadingFallback = false, bool isTextOrientationFallback = false)
     {
-        return adoptRef(new SimpleFontData(platformData, isCustomFont, isLoading, isTextOrientationFallback));
+        return adoptRef(new SimpleFontData(platformData, isCustomFont, isLoadingFallback, isTextOrientationFallback));
     }
 
     // Used to create SVG Fonts.
@@ -156,14 +157,17 @@
 
     AdditionalFontData* fontData() const { return m_fontData.get(); }
     bool isSVGFont() const { return m_fontData; }
+    bool isLoadingFallback() const { return m_customFontData.isLoadingFallback; }
 
-    virtual bool isCustomFont() const { return m_isCustomFont; }
-    virtual bool isLoading() const { return m_isLoading; }
+    virtual bool isCustomFont() const { return m_customFontData.isCustomFont; }
+    virtual bool isLoading() const { return m_customFontData.isLoadingFallback && m_customFontData.isUsed; }
     virtual bool isSegmented() const;
 
     const GlyphData& missingGlyphData() const { return m_missingGlyphData; }
     void setMissingGlyphData(const GlyphData& glyphData) { m_missingGlyphData = glyphData; }
 
+    void beginLoadIfNeeded() const;
+
 #ifndef NDEBUG
     virtual String description() const;
 #endif
@@ -190,8 +194,11 @@
         return false;
     }
 
+    void setCSSFontFaceSource(CSSFontFaceSource* source) { m_customFontData.fontFaceSource = source; }
+    void clearCSSFontFaceSource() { m_customFontData.fontFaceSource = 0; }
+
 private:
-    SimpleFontData(const FontPlatformData&, bool isCustomFont = false, bool isLoading = false, bool isTextOrientationFallback = false);
+    SimpleFontData(const FontPlatformData&, bool isCustomFont = false, bool isLoadingFallback = false, bool isTextOrientationFallback = false);
 
     SimpleFontData(PassOwnPtr<AdditionalFontData> , float fontSize, bool syntheticBold, bool syntheticItalic);
 
@@ -216,8 +223,6 @@
     mutable GlyphMetricsMap<float> m_glyphToWidthMap;
 
     bool m_treatAsFixedPitch;
-    bool m_isCustomFont;  // Whether or not we are custom font loaded via @font-face
-    bool m_isLoading; // Whether or not this custom font is still in the act of loading.
 
     bool m_isTextOrientationFallback;
     bool m_isBrokenIdeographFallback;
@@ -258,6 +263,21 @@
 
     mutable OwnPtr<DerivedFontData> m_derivedFontData;
 
+    struct CustomFontData {
+        CustomFontData(bool isCustomFont, bool isLoadingFallback)
+            : isCustomFont(isCustomFont)
+            , isLoadingFallback(isLoadingFallback)
+            , isUsed(false)
+            , fontFaceSource(0)
+        {
+        }
+        bool isCustomFont; // Whether or not we are custom font loaded via @font-face
+        bool isLoadingFallback; // Whether or not this is a temporary font data for a custom font which is not yet loaded.
+        mutable bool isUsed;
+        CSSFontFaceSource* fontFaceSource;
+    };
+    CustomFontData m_customFontData;
+
 #if OS(MACOSX)
     float m_syntheticBoldOffset;
 
diff --git a/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp b/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
index 5650649..d798888 100644
--- a/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
+++ b/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
@@ -242,13 +242,17 @@
                 timingFunctionType = WebKit::WebAnimationCurve::TimingFunctionTypeLinear;
                 break;
             case TimingFunction::CubicBezierFunction:
-                const CubicBezierTimingFunction* originalBezierTimingFunction = static_cast<const CubicBezierTimingFunction*>(originalTimingFunction);
-                isUsingCustomBezierTimingFunction = true;
-                x1 = originalBezierTimingFunction->x1();
-                y1 = originalBezierTimingFunction->y1();
-                x2 = originalBezierTimingFunction->x2();
-                y2 = originalBezierTimingFunction->y2();
-                break;
+                {
+                    const CubicBezierTimingFunction* originalBezierTimingFunction = static_cast<const CubicBezierTimingFunction*>(originalTimingFunction);
+                    isUsingCustomBezierTimingFunction = true;
+                    x1 = originalBezierTimingFunction->x1();
+                    y1 = originalBezierTimingFunction->y1();
+                    x2 = originalBezierTimingFunction->x2();
+                    y2 = originalBezierTimingFunction->y2();
+                    break;
+                }
+            default:
+                ASSERT_NOT_REACHED();
             } // switch
         }
 
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
index 4771925..ca6cb1a 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
@@ -93,7 +93,7 @@
 
     WebKit::WebLayer* layer();
     void contextAcquired();
-    SkCanvas* getCanvas() { return m_canvas; }
+    PassRefPtr<SkCanvas> getCanvas() { return PassRefPtr<SkCanvas>(m_canvas); }
 
     unsigned backBufferTexture();
 
@@ -105,7 +105,7 @@
     Canvas2DLayerBridge(PassRefPtr<GraphicsContext3D>, SkDeferredCanvas*, OpacityMode);
     void setRateLimitingEnabled(bool);
 
-    SkDeferredCanvas* m_canvas;
+    RefPtr<SkDeferredCanvas> m_canvas;
     OwnPtr<WebKit::WebExternalTextureLayer> m_layer;
     RefPtr<GraphicsContext3D> m_context;
     size_t m_bytesAllocated;
diff --git a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
index 04eccf6..30f96c6 100644
--- a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
@@ -35,6 +35,7 @@
 #include <windows.h>
 #include <mlang.h>
 #include <objidl.h>
+#include "core/platform/LayoutTestSupport.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/skia/SkiaFontWin.h"
@@ -82,6 +83,14 @@
     return gFlags;
 }
 
+static bool isWebFont(const LOGFONT& lf)
+{
+    // web-fonts have artifical names constructed to always be
+    // 1. 24 characters, followed by a '\0'
+    // 2. the last two characters are '=='
+    return '=' == lf.lfFaceName[22] && '=' == lf.lfFaceName[23] && '\0' == lf.lfFaceName[24];
+}
+
 static int computePaintTextFlags(const LOGFONT& lf)
 {
     int textFlags = 0;
@@ -101,7 +110,21 @@
     }
 
     // only allow features that SystemParametersInfo allows
-    return textFlags & getDefaultGDITextFlags();
+    textFlags &= getDefaultGDITextFlags();
+
+    /*
+     *  FontPlatformData(...) will read our logfont, and try to honor the the lfQuality
+     *  setting (computing the corresponding SkPaint flags for AA and LCD). However, it
+     *  will limit the quality based on its query of SPI_GETFONTSMOOTHING. This could mean
+     *  we end up drawing the text in BW, even though our lfQuality requested antialiasing.
+     *
+     *  Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW.
+     *  In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA,
+     *  even when the System (getDefaultGDITextFlags) tells us to draw only in BW.
+     */
+    if (isWebFont(lf) && !isRunningLayoutTest())
+        textFlags |= SkPaint::kAntiAlias_Flag;
+    return textFlags;
 }
 
 PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size, int* paintTextFlags)
diff --git a/Source/core/platform/graphics/filters/FEComponentTransfer.cpp b/Source/core/platform/graphics/filters/FEComponentTransfer.cpp
index 7eb2238..18f783a 100644
--- a/Source/core/platform/graphics/filters/FEComponentTransfer.cpp
+++ b/Source/core/platform/graphics/filters/FEComponentTransfer.cpp
@@ -211,7 +211,8 @@
 
     SkAutoTUnref<SkColorFilter> colorFilter(SkTableColorFilter::CreateARGB(aValues, rValues, gValues, bValues));
 
-    return adoptRef(SkColorFilterImageFilter::Create(colorFilter, input.get()));
+    SkIRect cropRect = getCropRect(builder->cropOffset());
+    return adoptRef(SkColorFilterImageFilter::Create(colorFilter, input.get(), &cropRect));
 }
 
 void FEComponentTransfer::getValues(unsigned char rValues[256], unsigned char gValues[256], unsigned char bValues[256], unsigned char aValues[256])
diff --git a/Source/core/platform/graphics/filters/FEComposite.cpp b/Source/core/platform/graphics/filters/FEComposite.cpp
index 03b205d..c8d996a 100644
--- a/Source/core/platform/graphics/filters/FEComposite.cpp
+++ b/Source/core/platform/graphics/filters/FEComposite.cpp
@@ -45,7 +45,7 @@
 
 class CompositeImageFilter : public SkImageFilter {
 public:
-    CompositeImageFilter(SkXfermode::Mode mode, SkImageFilter* background, SkImageFilter* foreground) : SkImageFilter(background, foreground), m_mode(mode)
+    CompositeImageFilter(SkXfermode::Mode mode, SkImageFilter* background, SkImageFilter* foreground, const SkIRect* cropRect) : SkImageFilter(background, foreground, cropRect), m_mode(mode)
     {
     }
 
@@ -62,7 +62,17 @@
         if (foregroundInput && !foregroundInput->filterImage(proxy, src, ctm, &foreground, &foregroundOffset))
             return false;
 
-        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(background.width(), background.height()));
+        SkIRect bounds;
+        background.getBounds(&bounds);
+        if (!applyCropRect(&bounds, ctm)) {
+            return false;
+        }
+        backgroundOffset.fX -= bounds.left();
+        backgroundOffset.fY -= bounds.top();
+        foregroundOffset.fX -= bounds.left();
+        foregroundOffset.fY -= bounds.top();
+
+        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
         SkCanvas canvas(device);
         SkPaint paint;
         paint.setXfermodeMode(SkXfermode::kSrc_Mode);
@@ -70,6 +80,8 @@
         paint.setXfermodeMode(m_mode);
         canvas.drawBitmap(foreground, foregroundOffset.fX, foregroundOffset.fY, &paint);
         *dst = device->accessBitmap(false);
+        offset->fX += bounds.left();
+        offset->fY += bounds.top();
         return true;
     }
 
@@ -400,7 +412,8 @@
         SkAutoTUnref<SkXfermode> mode(SkArithmeticMode::Create(SkFloatToScalar(m_k1), SkFloatToScalar(m_k2), SkFloatToScalar(m_k3), SkFloatToScalar(m_k4)));
         return adoptRef(new SkXfermodeImageFilter(mode, background.get(), foreground.get()));
     }
-    return adoptRef(new CompositeImageFilter(toXfermode(m_type), background.get(), foreground.get()));
+    SkIRect cropRect = getCropRect(builder->cropOffset());
+    return adoptRef(new CompositeImageFilter(toXfermode(m_type), background.get(), foreground.get(), &cropRect));
 }
 
 static TextStream& operator<<(TextStream& ts, const CompositeOperationType& type)
diff --git a/Source/core/platform/graphics/filters/FEFlood.cpp b/Source/core/platform/graphics/filters/FEFlood.cpp
index a2b1572..ce8cc99 100644
--- a/Source/core/platform/graphics/filters/FEFlood.cpp
+++ b/Source/core/platform/graphics/filters/FEFlood.cpp
@@ -29,6 +29,7 @@
 #include "SkImageFilter.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/filters/Filter.h"
+#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "core/platform/text/TextStream.h"
 #include "core/rendering/RenderTreeAsText.h"
 #include "third_party/skia/include/core/SkDevice.h"
@@ -37,8 +38,8 @@
 
 class FloodImageFilter : public SkImageFilter {
 public:
-    FloodImageFilter(const SkColor& color)
-        : SkImageFilter(0, 0)
+    FloodImageFilter(const SkColor& color, const SkIRect* cropRect)
+        : SkImageFilter(0, 0, cropRect)
         , m_color(color)
     {
     }
@@ -51,20 +52,29 @@
 
     virtual void flatten(SkFlattenableWriteBuffer& buffer) const
     {
+        this->SkImageFilter::flatten(buffer);
         buffer.writeColor(m_color);
     }
 
-    virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix&, SkBitmap* result, SkIPoint*)
+    virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* result, SkIPoint* offset)
     {
         if (!src.width() || !src.height())
             return false;
 
-        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(src.width(), src.height()));
+        SkIRect bounds;
+        src.getBounds(&bounds);
+        if (!applyCropRect(&bounds, ctm)) {
+            return false;
+        }
+
+        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
         SkCanvas canvas(device.get());
         SkPaint paint;
         paint.setColor(m_color);
         canvas.drawRect(SkRect::MakeWH(src.width(), src.height()), paint);
         *result = device->accessBitmap(false);
+        offset->fX += bounds.left();
+        offset->fY += bounds.top();
         return true;
     }
 private:
@@ -128,7 +138,9 @@
 PassRefPtr<SkImageFilter> FEFlood::createImageFilter(SkiaImageFilterBuilder* builder)
 {
     Color color = colorWithOverrideAlpha(floodColor().rgb(), floodOpacity());
-    return adoptRef(new FloodImageFilter(color.rgb()));
+
+    SkIRect rect = getCropRect(builder->cropOffset());
+    return adoptRef(new FloodImageFilter(color.rgb(), &rect));
 }
 
 TextStream& FEFlood::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FEOffset.cpp b/Source/core/platform/graphics/filters/FEOffset.cpp
index b946337..c89f4da 100644
--- a/Source/core/platform/graphics/filters/FEOffset.cpp
+++ b/Source/core/platform/graphics/filters/FEOffset.cpp
@@ -40,7 +40,7 @@
 
 class OffsetImageFilter : public SkImageFilter {
 public:
-    OffsetImageFilter(SkScalar dx, SkScalar dy, SkImageFilter* input) : SkImageFilter(input), m_dx(dx), m_dy(dy)
+    OffsetImageFilter(SkScalar dx, SkScalar dy, SkImageFilter* input, const SkIRect* cropRect = 0) : SkImageFilter(input, cropRect), m_dx(dx), m_dy(dy)
     {
     }
 
@@ -52,12 +52,21 @@
         if (input && !input->filterImage(proxy, src, ctm, &source, &srcOffset))
             return false;
 
-        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(source.width(), source.height()));
+        SkIRect bounds;
+        source.getBounds(&bounds);
+
+        if (!applyCropRect(&bounds, ctm)) {
+            return false;
+        }
+
+        SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
         SkCanvas canvas(device);
         SkPaint paint;
         paint.setXfermodeMode(SkXfermode::kSrc_Mode);
-        canvas.drawBitmap(source, m_dx, m_dy, &paint);
+        canvas.drawBitmap(source, m_dx - bounds.left(), m_dy - bounds.top(), &paint);
         *dst = device->accessBitmap(false);
+        offset->fX += bounds.left();
+        offset->fY += bounds.top();
         return true;
     }
 
@@ -156,7 +165,8 @@
 {
     RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     Filter* filter = this->filter();
-    return adoptRef(new OffsetImageFilter(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), input.get()));
+    SkIRect cropRect = getCropRect(builder->cropOffset());
+    return adoptRef(new OffsetImageFilter(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), input.get(), &cropRect));
 }
 
 TextStream& FEOffset::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/gpu/DrawingBuffer.cpp b/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
index 11f4b50..feb0fea 100644
--- a/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
+++ b/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
@@ -539,33 +539,6 @@
     }
 }
 
-// Only way to ensure that we're not getting a bad framebuffer on some AMD/OSX devices.
-// FIXME: This can be removed once renderbufferStorageMultisample starts reporting GL_OUT_OF_MEMORY properly.
-bool DrawingBuffer::checkBufferIntegrity()
-{
-    if (!m_multisampleFBO)
-        return true;
-
-    if (m_scissorEnabled)
-        m_context->disable(GraphicsContext3D::SCISSOR_TEST);
-
-    m_context->colorMask(true, true, true, true);
-
-    m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_multisampleFBO);
-    m_context->clearColor(1.0f, 0.0f, 1.0f, 1.0f);
-    m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT);
-
-    commit(0, 0, 1, 1);
-
-    unsigned char pixel[4] = {0, 0, 0, 0};
-    m_context->readPixels(0, 0, 1, 1, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, &pixel);
-
-    if (m_scissorEnabled)
-        m_context->enable(GraphicsContext3D::SCISSOR_TEST);
-
-    return (pixel[0] == 0xFF && pixel[1] == 0x00 && pixel[2] == 0xFF && pixel[3] == 0xFF);
-}
-
 void DrawingBuffer::setSize(const IntSize& size) {
     if (m_size == size)
         return;
@@ -649,14 +622,6 @@
                 adjustedSize.scale(s_resourceAdjustedRatio);
                 continue;
             }
-
-#if OS(MACOSX)
-            // FIXME: This can be removed once renderbufferStorageMultisample starts reporting GL_OUT_OF_MEMORY properly on OSX.
-            if (!checkBufferIntegrity()) {
-                adjustedSize.scale(s_resourceAdjustedRatio);
-                continue;
-            }
-#endif
             break;
         } while (!adjustedSize.isEmpty());
 
diff --git a/Source/core/platform/graphics/gpu/DrawingBuffer.h b/Source/core/platform/graphics/gpu/DrawingBuffer.h
index af55434..1ec9c6a 100644
--- a/Source/core/platform/graphics/gpu/DrawingBuffer.h
+++ b/Source/core/platform/graphics/gpu/DrawingBuffer.h
@@ -143,7 +143,6 @@
     bool resizeFramebuffer(const IntSize&);
     bool resizeMultisampleFramebuffer(const IntSize&);
     void resizeDepthStencil(const IntSize&, int sampleCount);
-    bool checkBufferIntegrity();
 
     // Bind to the m_framebufferBinding if it's not 0.
     void restoreFramebufferBinding();
diff --git a/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp b/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp
index c71c306..f5ab673 100644
--- a/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp
+++ b/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp
@@ -140,12 +140,6 @@
     }
 }
 
-static void setupForTextPainting(SkPaint* paint, SkColor color)
-{
-    paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding);
-    paint->setColor(color);
-}
-
 void Font::drawComplexText(GraphicsContext* gc, const TextRunPaintInfo& runInfo, const FloatPoint& point) const
 {
     if (!runInfo.run.length())
@@ -160,16 +154,6 @@
     if (!fill && !stroke)
         return;
 
-    SkPaint strokePaint, fillPaint;
-    if (fill) {
-        gc->setupPaintForFilling(&fillPaint);
-        setupForTextPainting(&fillPaint, gc->fillColor().rgb());
-    }
-    if (stroke) {
-        gc->setupPaintForStroking(&strokePaint);
-        setupForTextPainting(&strokePaint, gc->strokeColor().rgb());
-    }
-
     GlyphBuffer glyphBuffer;
     HarfBuzzShaper shaper(this, runInfo.run);
     shaper.setDrawRange(runInfo.from, runInfo.to);
diff --git a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
index 83145c1..e86b341 100644
--- a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
+++ b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h"
 
+#include "RuntimeEnabledFeatures.h"
 #include "SkPaint.h"
 #include "SkTypeface.h"
 #include "core/platform/NotImplemented.h"
@@ -195,7 +196,7 @@
     paint->setHinting(static_cast<SkPaint::Hinting>(m_style.hintStyle));
     paint->setEmbeddedBitmapText(m_style.useBitmaps);
     paint->setAutohinted(m_style.useAutoHint);
-    paint->setSubpixelText(m_style.useSubpixelPositioning);
+    paint->setSubpixelText(m_style.useSubpixelPositioning || RuntimeEnabledFeatures::subpixelFontScalingEnabled());
     if (m_style.useAntiAlias)
         paint->setLCDRenderText(m_style.useSubpixelRendering);
 
diff --git a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
index 0cbb258..8e22570 100644
--- a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
+++ b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
@@ -31,8 +31,7 @@
 #include "config.h"
 #include "core/platform/graphics/harfbuzz/HarfBuzzShaper.h"
 
-#include <unicode/normlzr.h>
-#include <unicode/uchar.h>
+#include "RuntimeEnabledFeatures.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/SurrogatePairAwareTextIterator.h"
 #include "core/platform/graphics/TextRun.h"
@@ -41,6 +40,12 @@
 #include "wtf/MathExtras.h"
 #include "wtf/unicode/Unicode.h"
 #include "wtf/Vector.h"
+#include <unicode/normlzr.h>
+#include <unicode/uchar.h>
+
+#include <list>
+#include <map>
+#include <string>
 
 namespace WebCore {
 
@@ -62,26 +67,178 @@
     }
 
     T* get() { return m_ptr; }
+    void set(T* ptr) { m_ptr = ptr; }
 private:
     T* m_ptr;
     DestroyFunction m_destroy;
 };
 
+
+static const int cHarfBuzzCacheMaxSize = 256;
+
+struct CachedShapingResultsLRUNode;
+struct CachedShapingResults;
+typedef std::map<std::wstring, CachedShapingResults*> CachedShapingResultsMap;
+typedef std::list<CachedShapingResultsLRUNode*> CachedShapingResultsLRU;
+
+struct CachedShapingResults {
+    CachedShapingResults(hb_buffer_t* harfBuzzBuffer, const Font* runFont, hb_direction_t runDir);
+    ~CachedShapingResults();
+
+    hb_buffer_t* buffer;
+    Font font;
+    hb_direction_t dir;
+    CachedShapingResultsLRU::iterator lru;
+};
+
+struct CachedShapingResultsLRUNode {
+    CachedShapingResultsLRUNode(const CachedShapingResultsMap::iterator& cacheEntry);
+    ~CachedShapingResultsLRUNode();
+
+    CachedShapingResultsMap::iterator entry;
+};
+
+CachedShapingResults::CachedShapingResults(hb_buffer_t* harfBuzzBuffer, const Font* fontData, hb_direction_t dirData)
+    : buffer(harfBuzzBuffer)
+    , font(*fontData)
+    , dir(dirData)
+{
+}
+
+CachedShapingResults::~CachedShapingResults()
+{
+    hb_buffer_destroy(buffer);
+}
+
+CachedShapingResultsLRUNode::CachedShapingResultsLRUNode(const CachedShapingResultsMap::iterator& cacheEntry)
+    : entry(cacheEntry)
+{
+}
+
+CachedShapingResultsLRUNode::~CachedShapingResultsLRUNode()
+{
+}
+
+class HarfBuzzRunCache {
+public:
+    HarfBuzzRunCache();
+    ~HarfBuzzRunCache();
+
+    CachedShapingResults* find(const std::wstring& key) const;
+    void remove(CachedShapingResults* node);
+    void moveToBack(CachedShapingResults* node);
+    bool insert(const std::wstring& key, CachedShapingResults* run);
+
+private:
+    CachedShapingResultsMap m_harfBuzzRunMap;
+    CachedShapingResultsLRU m_harfBuzzRunLRU;
+};
+
+
+HarfBuzzRunCache::HarfBuzzRunCache()
+{
+}
+
+HarfBuzzRunCache::~HarfBuzzRunCache()
+{
+    for (CachedShapingResultsMap::iterator it = m_harfBuzzRunMap.begin(); it != m_harfBuzzRunMap.end(); ++it)
+        delete it->second;
+    for (CachedShapingResultsLRU::iterator it = m_harfBuzzRunLRU.begin(); it != m_harfBuzzRunLRU.end(); ++it)
+        delete *it;
+}
+
+bool HarfBuzzRunCache::insert(const std::wstring& key, CachedShapingResults* data)
+{
+    std::pair<CachedShapingResultsMap::iterator, bool> results =
+        m_harfBuzzRunMap.insert(CachedShapingResultsMap::value_type(key, data));
+
+    if (!results.second)
+        return false;
+
+    CachedShapingResultsLRUNode* node = new CachedShapingResultsLRUNode(results.first);
+
+    m_harfBuzzRunLRU.push_back(node);
+    data->lru = --m_harfBuzzRunLRU.end();
+
+    if (m_harfBuzzRunMap.size() > cHarfBuzzCacheMaxSize) {
+        CachedShapingResultsLRUNode* lru = m_harfBuzzRunLRU.front();
+        CachedShapingResults* foo = lru->entry->second;
+        m_harfBuzzRunMap.erase(lru->entry);
+        m_harfBuzzRunLRU.pop_front();
+        delete foo;
+        delete lru;
+    }
+
+    return true;
+}
+
+inline CachedShapingResults* HarfBuzzRunCache::find(const std::wstring& key) const
+{
+    CachedShapingResultsMap::const_iterator it = m_harfBuzzRunMap.find(key);
+
+    return it != m_harfBuzzRunMap.end() ? it->second : 0;
+}
+
+inline void HarfBuzzRunCache::remove(CachedShapingResults* node)
+{
+    CachedShapingResultsLRUNode* lruNode = *node->lru;
+
+    m_harfBuzzRunLRU.erase(node->lru);
+    m_harfBuzzRunMap.erase(lruNode->entry);
+    delete lruNode;
+    delete node;
+}
+
+inline void HarfBuzzRunCache::moveToBack(CachedShapingResults* node)
+{
+    CachedShapingResultsLRUNode* lruNode = *node->lru;
+    m_harfBuzzRunLRU.erase(node->lru);
+    m_harfBuzzRunLRU.push_back(lruNode);
+    node->lru = --m_harfBuzzRunLRU.end();
+}
+
+HarfBuzzRunCache& harfBuzzRunCache()
+{
+    DEFINE_STATIC_LOCAL(HarfBuzzRunCache, globalHarfBuzzRunCache, ());
+    return globalHarfBuzzRunCache;
+}
+
 static inline float harfBuzzPositionToFloat(hb_position_t value)
 {
     return static_cast<float>(value) / (1 << 16);
 }
 
-HarfBuzzShaper::HarfBuzzRun::HarfBuzzRun(const SimpleFontData* fontData, unsigned startIndex, unsigned numCharacters, TextDirection direction, hb_script_t script)
+inline HarfBuzzShaper::HarfBuzzRun::HarfBuzzRun(const SimpleFontData* fontData, unsigned startIndex, unsigned numCharacters, TextDirection direction, hb_script_t script)
     : m_fontData(fontData)
     , m_startIndex(startIndex)
     , m_numCharacters(numCharacters)
     , m_direction(direction)
     , m_script(script)
+    , m_numGlyphs(0)
+    , m_width(0)
 {
 }
 
-void HarfBuzzShaper::HarfBuzzRun::applyShapeResult(hb_buffer_t* harfBuzzBuffer)
+inline HarfBuzzShaper::HarfBuzzRun::HarfBuzzRun(const HarfBuzzRun& rhs)
+    : m_fontData(rhs.m_fontData)
+    , m_startIndex(rhs.m_startIndex)
+    , m_numCharacters(rhs.m_numCharacters)
+    , m_numGlyphs(rhs.m_numGlyphs)
+    , m_direction(rhs.m_direction)
+    , m_script(rhs.m_script)
+    , m_glyphs(rhs.m_glyphs)
+    , m_advances(rhs.m_advances)
+    , m_glyphToCharacterIndexes(rhs.m_glyphToCharacterIndexes)
+    , m_offsets(rhs.m_offsets)
+    , m_width(rhs.m_width)
+{
+}
+
+HarfBuzzShaper::HarfBuzzRun::~HarfBuzzRun()
+{
+}
+
+inline void HarfBuzzShaper::HarfBuzzRun::applyShapeResult(hb_buffer_t* harfBuzzBuffer)
 {
     m_numGlyphs = hb_buffer_get_length(harfBuzzBuffer);
     m_glyphs.resize(m_numGlyphs);
@@ -90,7 +247,17 @@
     m_offsets.resize(m_numGlyphs);
 }
 
-void HarfBuzzShaper::HarfBuzzRun::setGlyphAndPositions(unsigned index, uint16_t glyphId, float advance, float offsetX, float offsetY)
+inline void HarfBuzzShaper::HarfBuzzRun::copyShapeResultAndGlyphPositions(const HarfBuzzRun& run)
+{
+    m_numGlyphs = run.m_numGlyphs;
+    m_glyphs = run.m_glyphs;
+    m_advances = run.m_advances;
+    m_glyphToCharacterIndexes = run.m_glyphToCharacterIndexes;
+    m_offsets = run.m_offsets;
+    m_width = run.m_width;
+}
+
+inline void HarfBuzzShaper::HarfBuzzRun::setGlyphAndPositions(unsigned index, uint16_t glyphId, float advance, float offsetX, float offsetY)
 {
     m_glyphs[index] = glyphId;
     m_advances[index] = advance;
@@ -373,7 +540,9 @@
     // HarfBuzz when we are calculating widths (except when directionalOverride() is set).
     if (!shapeHarfBuzzRuns(glyphBuffer || m_run.directionalOverride()))
         return false;
-    m_totalWidth = roundf(m_totalWidth);
+
+    if (!RuntimeEnabledFeatures::subpixelFontScalingEnabled())
+        m_totalWidth = roundf(m_totalWidth);
 
     if (glyphBuffer && !fillGlyphBuffer(glyphBuffer))
         return false;
@@ -428,10 +597,9 @@
                     clusterLength = markLength;
                     continue;
                 }
-                nextFontData = m_font->glyphDataForCharacter(character, false).fontData;
-            } else
-                nextFontData = m_font->glyphDataForCharacter(character, false).fontData;
+            }
 
+            nextFontData = m_font->glyphDataForCharacter(character, false).fontData;
             nextScript = uscript_getScript(character, &errorCode);
             if (U_FAILURE(errorCode))
                 return false;
@@ -456,6 +624,7 @@
     HarfBuzzScopedPtr<hb_buffer_t> harfBuzzBuffer(hb_buffer_create(), hb_buffer_destroy);
 
     hb_buffer_set_unicode_funcs(harfBuzzBuffer.get(), hb_icu_get_unicode_funcs());
+    HarfBuzzRunCache& runCache = harfBuzzRunCache();
 
     for (unsigned i = 0; i < m_harfBuzzRuns.size(); ++i) {
         unsigned runIndex = m_run.rtl() ? m_harfBuzzRuns.size() - i - 1 : i;
@@ -464,6 +633,11 @@
         if (currentFontData->isSVGFont())
             return false;
 
+        FontPlatformData* platformData = const_cast<FontPlatformData*>(&currentFontData->platformData());
+        HarfBuzzFace* face = platformData->harfBuzzFace();
+        if (!face)
+            return false;
+
         hb_buffer_set_script(harfBuzzBuffer.get(), currentRun->script());
         if (shouldSetDirection)
             hb_buffer_set_direction(harfBuzzBuffer.get(), currentRun->rtl() ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
@@ -471,6 +645,28 @@
             // Leaving direction to HarfBuzz to guess is *really* bad, but will do for now.
             hb_buffer_guess_segment_properties(harfBuzzBuffer.get());
 
+        hb_segment_properties_t props;
+        hb_buffer_get_segment_properties(harfBuzzBuffer.get(), &props);
+
+        const UChar* src = m_normalizedBuffer.get() + currentRun->startIndex();
+        std::wstring key(src, src + currentRun->numCharacters());
+
+        CachedShapingResults* cachedResults = runCache.find(key);
+        if (cachedResults) {
+            if (cachedResults->dir == props.direction && cachedResults->font == *m_font) {
+                currentRun->applyShapeResult(cachedResults->buffer);
+                setGlyphPositionsForHarfBuzzRun(currentRun, cachedResults->buffer);
+
+                hb_buffer_reset(harfBuzzBuffer.get());
+
+                runCache.moveToBack(cachedResults);
+
+                continue;
+            }
+
+            runCache.remove(cachedResults);
+        }
+
         // Add a space as pre-context to the buffer. This prevents showing dotted-circle
         // for combining marks at the beginning of runs.
         static const uint16_t preContext = ' ';
@@ -485,22 +681,19 @@
         } else
             hb_buffer_add_utf16(harfBuzzBuffer.get(), m_normalizedBuffer.get() + currentRun->startIndex(), currentRun->numCharacters(), 0, currentRun->numCharacters());
 
-        FontPlatformData* platformData = const_cast<FontPlatformData*>(&currentFontData->platformData());
-        HarfBuzzFace* face = platformData->harfBuzzFace();
-        if (!face)
-            return false;
-
         if (m_font->fontDescription().orientation() == Vertical)
             face->setScriptForVerticalGlyphSubstitution(harfBuzzBuffer.get());
 
         HarfBuzzScopedPtr<hb_font_t> harfBuzzFont(face->createFont(), hb_font_destroy);
 
         hb_shape(harfBuzzFont.get(), harfBuzzBuffer.get(), m_features.isEmpty() ? 0 : m_features.data(), m_features.size());
-
         currentRun->applyShapeResult(harfBuzzBuffer.get());
         setGlyphPositionsForHarfBuzzRun(currentRun, harfBuzzBuffer.get());
 
-        hb_buffer_reset(harfBuzzBuffer.get());
+        runCache.insert(key, new CachedShapingResults(harfBuzzBuffer.get(), m_font, props.direction));
+
+        harfBuzzBuffer.set(hb_buffer_create());
+        hb_buffer_set_unicode_funcs(harfBuzzBuffer.get(), hb_icu_get_unicode_funcs());
     }
 
     return true;
diff --git a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h
index 2035779..c906262 100644
--- a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h
+++ b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h
@@ -67,12 +67,16 @@
 private:
     class HarfBuzzRun {
     public:
+        HarfBuzzRun(const HarfBuzzRun&);
+        ~HarfBuzzRun();
+
         static PassOwnPtr<HarfBuzzRun> create(const SimpleFontData* fontData, unsigned startIndex, unsigned numCharacters, TextDirection direction, hb_script_t script)
         {
             return adoptPtr(new HarfBuzzRun(fontData, startIndex, numCharacters, direction, script));
         }
 
         void applyShapeResult(hb_buffer_t*);
+        void copyShapeResultAndGlyphPositions(const HarfBuzzRun&);
         void setGlyphAndPositions(unsigned index, uint16_t glyphId, float advance, float offsetX, float offsetY);
         void setWidth(float width) { m_width = width; }
 
@@ -148,6 +152,8 @@
     int m_toIndex;
 
     float m_totalWidth;
+
+    friend struct CachedShapingResults;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/opentype/OpenTypeTypes.h b/Source/core/platform/graphics/opentype/OpenTypeTypes.h
index 345e8ad..c4a945b 100644
--- a/Source/core/platform/graphics/opentype/OpenTypeTypes.h
+++ b/Source/core/platform/graphics/opentype/OpenTypeTypes.h
@@ -26,39 +26,35 @@
 #define OpenTypeTypes_h
 
 #include "core/platform/SharedBuffer.h"
+#include "wtf/ByteOrder.h"
 
 namespace WebCore {
 namespace OpenType {
 
-struct BigEndianShort {
-    operator short() const { return (v & 0x00ff) << 8 | v >> 8; }
-    BigEndianShort(short u) : v((u & 0x00ff) << 8 | u >> 8) { }
-    unsigned short v;
+struct Int16 {
+    Int16(int16_t u) : v(htons(static_cast<uint16_t>(u))) { }
+    operator int16_t() const { return static_cast<int16_t>(ntohs(v)); }
+    uint16_t v; // in BigEndian
 };
 
-struct BigEndianUShort {
-    operator unsigned short() const { return (v & 0x00ff) << 8 | v >> 8; }
-    BigEndianUShort(unsigned short u) : v((u & 0x00ff) << 8 | u >> 8) { }
-    unsigned short v;
+struct UInt16 {
+    UInt16(uint16_t u) : v(htons(u)) { }
+    operator uint16_t() const { return ntohs(v); }
+    uint16_t v; // in BigEndian
 };
 
-struct BigEndianLong {
-    operator int() const { return (v & 0xff) << 24 | (v & 0xff00) << 8 | (v & 0xff0000) >> 8 | v >> 24; }
-    BigEndianLong(int u) : v((u & 0xff) << 24 | (u & 0xff00) << 8 | (u & 0xff0000) >> 8 | u >> 24) { }
-    unsigned v;
+struct Int32 {
+    Int32(int32_t u) : v(htonl(static_cast<uint32_t>(u))) { }
+    operator int32_t() const { return static_cast<int32_t>(ntohl(v)); }
+    uint32_t v; // in BigEndian
 };
 
-struct BigEndianULong {
-    operator unsigned() const { return (v & 0xff) << 24 | (v & 0xff00) << 8 | (v & 0xff0000) >> 8 | v >> 24; }
-    BigEndianULong(unsigned u) : v((u & 0xff) << 24 | (u & 0xff00) << 8 | (u & 0xff0000) >> 8 | u >> 24) { }
-    unsigned v;
+struct UInt32 {
+    UInt32(uint32_t u) : v(htonl(u)) { }
+    operator uint32_t() const { return ntohl(v); }
+    uint32_t v; // in BigEndian
 };
 
-typedef BigEndianShort Int16;
-typedef BigEndianUShort UInt16;
-typedef BigEndianLong Int32;
-typedef BigEndianULong UInt32;
-
 typedef UInt32 Fixed;
 typedef UInt16 Offset;
 typedef UInt16 GlyphID;
diff --git a/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
index ac77135..4462607 100644
--- a/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
+++ b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
@@ -164,7 +164,7 @@
     SkTypeface::LocalizedString actualFamily;
 
     while (actualFamilies->next(&actualFamily)) {
-        if (equalIgnoringCase(family, actualFamily.fString.c_str())) {
+        if (equalIgnoringCase(family, AtomicString::fromUTF8(actualFamily.fString.c_str()))) {
             matchesRequestedFamily = true;
             break;
         }
diff --git a/Source/core/platform/mediastream/MediaStreamComponent.cpp b/Source/core/platform/mediastream/MediaStreamComponent.cpp
index be913c4..722366e 100644
--- a/Source/core/platform/mediastream/MediaStreamComponent.cpp
+++ b/Source/core/platform/mediastream/MediaStreamComponent.cpp
@@ -34,7 +34,9 @@
 #include "core/platform/mediastream/MediaStreamComponent.h"
 
 #include "core/platform/UUID.h"
+#include "core/platform/audio/AudioBus.h"
 #include "core/platform/mediastream/MediaStreamSource.h"
+#include "public/web/WebAudioSourceProvider.h"
 
 namespace WebCore {
 
@@ -62,5 +64,34 @@
     ASSERT(m_id.length());
 }
 
+#if ENABLE(WEB_AUDIO)
+void MediaStreamComponent::AudioSourceProviderImpl::wrap(WebKit::WebAudioSourceProvider* provider)
+{
+    MutexLocker locker(m_provideInputLock);
+    m_webAudioSourceProvider = provider;
+}
+
+void MediaStreamComponent::AudioSourceProviderImpl::provideInput(AudioBus* bus, size_t framesToProcess)
+{
+    ASSERT(bus);
+    if (!bus)
+        return;
+
+    MutexTryLocker tryLocker(m_provideInputLock);
+    if (!tryLocker.locked() || !m_webAudioSourceProvider) {
+        bus->zero();
+        return;
+    }
+
+    // Wrap the AudioBus channel data using WebVector.
+    size_t n = bus->numberOfChannels();
+    WebKit::WebVector<float*> webAudioData(n);
+    for (size_t i = 0; i < n; ++i)
+        webAudioData[i] = bus->channel(i)->mutableData();
+
+    m_webAudioSourceProvider->provideInput(webAudioData, framesToProcess);
+}
+#endif // #if ENABLE(WEB_AUDIO)
+
 } // namespace WebCore
 
diff --git a/Source/core/platform/mediastream/MediaStreamComponent.h b/Source/core/platform/mediastream/MediaStreamComponent.h
index 6a47c54..90a9dee 100644
--- a/Source/core/platform/mediastream/MediaStreamComponent.h
+++ b/Source/core/platform/mediastream/MediaStreamComponent.h
@@ -32,10 +32,16 @@
 #ifndef MediaStreamComponent_h
 #define MediaStreamComponent_h
 
+#include "core/platform/audio/AudioSourceProvider.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
+#include "wtf/ThreadingPrimitives.h"
 #include "wtf/text/WTFString.h"
 
+namespace WebKit {
+class WebAudioSourceProvider;
+}
+
 namespace WebCore {
 
 class MediaStreamDescriptor;
@@ -56,9 +62,41 @@
     bool enabled() const { return m_enabled; }
     void setEnabled(bool enabled) { m_enabled = enabled; }
 
+#if ENABLE(WEB_AUDIO)
+    AudioSourceProvider* audioSourceProvider() { return &m_sourceProvider; }
+    void setSourceProvider(WebKit::WebAudioSourceProvider* provider) { m_sourceProvider.wrap(provider); }
+#endif // ENABLE(WEB_AUDIO)
+
 private:
     MediaStreamComponent(const String& id, MediaStreamDescriptor*, PassRefPtr<MediaStreamSource>);
 
+#if ENABLE(WEB_AUDIO)
+    // AudioSourceProviderImpl wraps a WebAudioSourceProvider::provideInput()
+    // calls into chromium to get a rendered audio stream.
+
+    class AudioSourceProviderImpl : public AudioSourceProvider {
+    public:
+        AudioSourceProviderImpl()
+            : m_webAudioSourceProvider(0)
+        {
+        }
+
+        virtual ~AudioSourceProviderImpl() { }
+
+        // Wraps the given WebKit::WebAudioSourceProvider to WebCore::AudioSourceProvider.
+        void wrap(WebKit::WebAudioSourceProvider*);
+
+        // WebCore::AudioSourceProvider
+        virtual void provideInput(WebCore::AudioBus*, size_t framesToProcess);
+
+    private:
+        WebKit::WebAudioSourceProvider* m_webAudioSourceProvider;
+        Mutex m_provideInputLock;
+    };
+
+    AudioSourceProviderImpl m_sourceProvider;
+#endif // ENABLE(WEB_AUDIO)
+
     MediaStreamDescriptor* m_stream;
     RefPtr<MediaStreamSource> m_source;
     String m_id;
diff --git a/Source/core/platform/midi/OWNERS b/Source/core/platform/midi/OWNERS
index 195c756..88c0a7f 100644
--- a/Source/core/platform/midi/OWNERS
+++ b/Source/core/platform/midi/OWNERS
@@ -1 +1,2 @@
+kouhei@chromium.org
 toyoshim@chromium.org
diff --git a/Source/core/platform/network/HTTPParsers.cpp b/Source/core/platform/network/HTTPParsers.cpp
index 450c422..979dd26 100644
--- a/Source/core/platform/network/HTTPParsers.cpp
+++ b/Source/core/platform/network/HTTPParsers.cpp
@@ -107,7 +107,7 @@
     // FIXME: This should really match name against
     // field-value in section 4.2 of RFC 2616.
 
-    return !name.contains('\r') && !name.contains('\n');
+    return name.containsOnlyLatin1() && !name.contains('\r') && !name.contains('\n');
 }
 
 // See RFC 2616, Section 2.2.
diff --git a/Source/core/platform/text/BidiResolver.h b/Source/core/platform/text/BidiResolver.h
index 71802f9..dc5ee34 100644
--- a/Source/core/platform/text/BidiResolver.h
+++ b/Source/core/platform/text/BidiResolver.h
@@ -178,6 +178,7 @@
 #endif
 
     const Iterator& position() const { return m_current; }
+    Iterator& position() { return m_current; }
     void setPositionIgnoringNestedIsolates(const Iterator& position) { m_current = position; }
     void setPosition(const Iterator& position, unsigned nestedIsolatedCount)
     {
@@ -185,8 +186,6 @@
         m_nestedIsolateCount = nestedIsolatedCount;
     }
 
-    void increment() { m_current.increment(); }
-
     BidiContext* context() const { return m_status.context.get(); }
     void setContext(PassRefPtr<BidiContext> c) { m_status.context = c; }
 
@@ -222,7 +221,10 @@
 
     Vector<Run*>& isolatedRuns() { return m_isolatedRuns; }
 
+    bool isEndOfParagraph(const Iterator& end) { return m_current == end || m_current.atEnd(); }
+
 protected:
+    void increment() { m_current.increment(); }
     // FIXME: Instead of InlineBidiResolvers subclassing this method, we should
     // pass in some sort of Traits object which knows how to create runs for appending.
     void appendRun();
@@ -550,12 +552,31 @@
     m_eor = Iterator();
 
     m_last = m_current;
-    bool pastEnd = false;
+    bool lastParagraphEnded = false;
     BidiResolver<Iterator, Run> stateAtEnd;
 
     while (true) {
+        if (inIsolate() && m_emptyRun) {
+            m_sor = m_current;
+            m_emptyRun = false;
+        }
+
+        if (!lastParagraphEnded && isEndOfParagraph(end)) {
+            if (m_emptyRun)
+                break;
+
+            stateAtEnd.m_status = m_status;
+            stateAtEnd.m_sor = m_sor;
+            stateAtEnd.m_eor = m_eor;
+            stateAtEnd.m_last = m_last;
+            stateAtEnd.m_reachedEndOfLine = m_reachedEndOfLine;
+            stateAtEnd.m_lastBeforeET = m_lastBeforeET;
+            stateAtEnd.m_emptyRun = m_emptyRun;
+            endOfLine = m_last;
+            lastParagraphEnded = true;
+        }
         Direction dirCurrent;
-        if (pastEnd && (hardLineBreak || m_current.atEnd())) {
+        if (lastParagraphEnded && (hardLineBreak || m_current.atEnd())) {
             BidiContext* c = context();
             if (hardLineBreak) {
                 // A deviation from the Unicode Bidi Algorithm in order to match
@@ -842,7 +863,7 @@
             break;
         }
 
-        if (pastEnd && m_eor == m_current) {
+        if (lastParagraphEnded && m_eor == m_current) {
             if (!m_reachedEndOfLine) {
                 m_eor = endOfLine;
                 switch (m_status.eor) {
@@ -882,7 +903,7 @@
         increment();
         if (!m_currentExplicitEmbeddingSequence.isEmpty()) {
             bool committed = commitExplicitEmbedding();
-            if (committed && pastEnd) {
+            if (committed && lastParagraphEnded) {
                 m_current = end;
                 m_status = stateAtEnd.m_status;
                 m_sor = stateAtEnd.m_sor;
@@ -895,20 +916,6 @@
                 break;
             }
         }
-
-        if (!pastEnd && (m_current == end || m_current.atEnd())) {
-            if (m_emptyRun)
-                break;
-            stateAtEnd.m_status = m_status;
-            stateAtEnd.m_sor = m_sor;
-            stateAtEnd.m_eor = m_eor;
-            stateAtEnd.m_last = m_last;
-            stateAtEnd.m_reachedEndOfLine = m_reachedEndOfLine;
-            stateAtEnd.m_lastBeforeET = m_lastBeforeET;
-            stateAtEnd.m_emptyRun = m_emptyRun;
-            endOfLine = m_last;
-            pastEnd = true;
-        }
     }
 
     m_runs.setLogicallyLastRun(m_runs.lastRun());
diff --git a/Source/core/platform/text/PlatformLocale.cpp b/Source/core/platform/text/PlatformLocale.cpp
index c959ac9..1b09c63 100644
--- a/Source/core/platform/text/PlatformLocale.cpp
+++ b/Source/core/platform/text/PlatformLocale.cpp
@@ -33,10 +33,14 @@
 
 #include "core/platform/LocalizedStrings.h"
 #include "core/platform/text/DateTimeFormat.h"
+#include "public/platform/Platform.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
+using WebKit::Platform;
+using WebKit::WebLocalizedString;
+
 class DateTimeStringBuilder : private DateTimeFormat::TokenHandler {
     WTF_MAKE_NONCOPYABLE(DateTimeStringBuilder);
 
@@ -180,6 +184,24 @@
 {
 }
 
+String Locale::queryString(WebLocalizedString::Name name)
+{
+    // FIXME: Returns a string locazlied for this locale.
+    return Platform::current()->queryLocalizedString(name);
+}
+
+String Locale::queryString(WebLocalizedString::Name name, const String& parameter)
+{
+    // FIXME: Returns a string locazlied for this locale.
+    return Platform::current()->queryLocalizedString(name, parameter);
+}
+
+String Locale::queryString(WebLocalizedString::Name name, const String& parameter1, const String& parameter2)
+{
+    // FIXME: Returns a string locazlied for this locale.
+    return Platform::current()->queryLocalizedString(name, parameter1, parameter2);
+}
+
 void Locale::setLocaleData(const Vector<String, DecimalSymbolsSize>& symbols, const String& positivePrefix, const String& positiveSuffix, const String& negativePrefix, const String& negativeSuffix)
 {
     for (size_t i = 0; i < symbols.size(); ++i) {
diff --git a/Source/core/platform/text/PlatformLocale.h b/Source/core/platform/text/PlatformLocale.h
index 0c7ede4..8f19dd4 100644
--- a/Source/core/platform/text/PlatformLocale.h
+++ b/Source/core/platform/text/PlatformLocale.h
@@ -28,6 +28,7 @@
 
 #include "core/platform/DateComponents.h"
 #include "core/platform/Language.h"
+#include "public/platform/WebLocalizedString.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/text/WTFString.h"
 
@@ -40,6 +41,10 @@
     static PassOwnPtr<Locale> create(const AtomicString& localeIdentifier);
     static PassOwnPtr<Locale> createDefault();
 
+    String queryString(WebKit::WebLocalizedString::Name);
+    String queryString(WebKit::WebLocalizedString::Name, const String& parameter);
+    String queryString(WebKit::WebLocalizedString::Name, const String& parameter1, const String& parameter2);
+
     // Converts the specified number string to another number string localized
     // for this Locale locale. The input string must conform to HTML
     // floating-point numbers, and is not empty.
diff --git a/Source/core/plugins/IFrameShimSupport.cpp b/Source/core/plugins/PluginOcclusionSupport.cpp
similarity index 71%
rename from Source/core/plugins/IFrameShimSupport.cpp
rename to Source/core/plugins/PluginOcclusionSupport.cpp
index 4d7af1e..16a66d0 100644
--- a/Source/core/plugins/IFrameShimSupport.cpp
+++ b/Source/core/plugins/PluginOcclusionSupport.cpp
@@ -29,7 +29,7 @@
  */
 
 #include "config.h"
-#include "core/plugins/IFrameShimSupport.h"
+#include "core/plugins/PluginOcclusionSupport.h"
 
 #include "HTMLNames.h"
 #include "core/dom/Element.h"
@@ -42,8 +42,7 @@
 #include "core/rendering/RenderObject.h"
 #include "wtf/HashSet.h"
 
-// This file provides plugin-related utility functions for iframe shims and is shared by platforms that inherit
-// from PluginView (e.g. Qt) and those that do not (e.g. Chromium).
+// This file provides a utility function to support rendering certain elements above plugins.
 
 namespace WebCore {
 
@@ -60,7 +59,7 @@
 static bool iframeIsAbovePlugin(const Vector<const RenderObject*>& iframeZstack, const Vector<const RenderObject*>& pluginZstack)
 {
     for (size_t i = 0; i < iframeZstack.size() && i < pluginZstack.size(); i++) {
-        // The root is at the end of these stacks.  We want to iterate
+        // The root is at the end of these stacks. We want to iterate
         // root-downwards so we index backwards from the end.
         const RenderObject* ro1 = iframeZstack[iframeZstack.size() - 1 - i];
         const RenderObject* ro2 = pluginZstack[pluginZstack.size() - 1 - i];
@@ -95,7 +94,7 @@
                 return true;
             }
 
-            // Inspect the document order.  Later order means higher stacking.
+            // Inspect the document order. Later order means higher stacking.
             const RenderObject* parent = ro1->parent();
             if (!parent)
                 return false;
@@ -114,10 +113,40 @@
     return true;
 }
 
+static bool intersectsRect(const RenderObject* renderer, const IntRect& rect)
+{
+    return renderer->absoluteBoundingBoxRectIgnoringTransforms().intersects(rect)
+        && (!renderer->style() || renderer->style()->visibility() == VISIBLE);
+}
+
+static void addToOcclusions(const RenderBox* renderer, Vector<IntRect>& occlusions)
+{
+    IntPoint point = roundedIntPoint(renderer->localToAbsolute());
+    IntSize size(renderer->width(), renderer->height());
+    occlusions.append(IntRect(point, size));
+}
+
+static void addTreeToOcclusions(const RenderObject* renderer, const IntRect& frameRect, Vector<IntRect>& occlusions)
+{
+    if (!renderer)
+        return;
+    if (renderer->isBox() && intersectsRect(renderer, frameRect))
+        addToOcclusions(toRenderBox(renderer), occlusions);
+    for (RenderObject* child = renderer->firstChild(); child; child = child->nextSibling())
+        addTreeToOcclusions(child, frameRect, occlusions);
+}
+
+static const Element* topLayerAncestor(const Element* element)
+{
+    while (element && !element->isInTopLayer())
+        element = element->parentOrShadowHostElement();
+    return element;
+}
+
 // Return a set of rectangles that should not be overdrawn by the
-// plugin ("cutouts").  This helps implement the "iframe shim"
+// plugin ("cutouts"). This helps implement the "iframe shim"
 // technique of overlaying a windowed plugin with content from the
-// page.  In a nutshell, iframe elements should occlude plugins when
+// page. In a nutshell, iframe elements should occlude plugins when
 // they occur higher in the stacking order.
 void getPluginOcclusions(Element* element, Widget* parentWidget, const IntRect& frameRect, Vector<IntRect>& occlusions)
 {
@@ -134,6 +163,7 @@
 
     FrameView* parentFrameView = toFrameView(parentWidget);
 
+    // Occlusions by iframes.
     const HashSet<RefPtr<Widget> >* children = parentFrameView->children();
     for (HashSet<RefPtr<Widget> >::const_iterator it = children->begin(); it != children->end(); ++it) {
         // We only care about FrameView's because iframes show up as FrameViews.
@@ -149,18 +179,24 @@
 
         RenderObject* iframeRenderer = element->renderer();
 
-        if (element->hasTagName(HTMLNames::iframeTag)
-            && iframeRenderer->absoluteBoundingBoxRectIgnoringTransforms().intersects(frameRect)
-            && (!iframeRenderer->style() || iframeRenderer->style()->visibility() == VISIBLE)) {
+        if (element->hasTagName(HTMLNames::iframeTag) && intersectsRect(iframeRenderer, frameRect)) {
             getObjectStack(iframeRenderer, &iframeZstack);
-            if (iframeIsAbovePlugin(iframeZstack, pluginZstack)) {
-                IntPoint point = roundedIntPoint(iframeRenderer->localToAbsolute());
-                RenderBox* rbox = toRenderBox(iframeRenderer);
-                IntSize size(rbox->width(), rbox->height());
-                occlusions.append(IntRect(point, size));
-            }
+            if (iframeIsAbovePlugin(iframeZstack, pluginZstack))
+                addToOcclusions(toRenderBox(iframeRenderer), occlusions);
         }
     }
+
+    // Occlusions by top layer elements.
+    // FIXME: There's no handling yet for the interaction between top layer and
+    // iframes. For example, a plugin in the top layer will be occluded by an
+    // iframe. And a plugin inside an iframe in the top layer won't be respected
+    // as being in the top layer.
+    const Element* ancestor = topLayerAncestor(element);
+    Document* document = parentFrameView->frame().document();
+    const Vector<RefPtr<Element> >& elements = document->topLayerElements();
+    size_t start = ancestor ? elements.find(ancestor) + 1 : 0;
+    for (size_t i = start; i < elements.size(); ++i)
+        addTreeToOcclusions(elements[i]->renderer(), frameRect, occlusions);
 }
 
 } // namespace WebCore
diff --git a/Source/core/plugins/IFrameShimSupport.h b/Source/core/plugins/PluginOcclusionSupport.h
similarity index 91%
rename from Source/core/plugins/IFrameShimSupport.h
rename to Source/core/plugins/PluginOcclusionSupport.h
index a9d7221..9d13dca 100644
--- a/Source/core/plugins/IFrameShimSupport.h
+++ b/Source/core/plugins/PluginOcclusionSupport.h
@@ -17,8 +17,8 @@
     Boston, MA 02110-1301, USA.
 */
 
-#ifndef IFrameShimSupport_h
-#define IFrameShimSupport_h
+#ifndef PluginOcclusionSupport_h
+#define PluginOcclusionSupport_h
 
 #include "wtf/Vector.h"
 
@@ -31,4 +31,4 @@
 
 } // namespace WebCore
 
-#endif // IFrameShimSupport_h
+#endif // PluginOcclusionSupport_h
diff --git a/Source/core/page/NavigatorBase.cpp b/Source/core/rendering/ClipRect.cpp
similarity index 71%
rename from Source/core/page/NavigatorBase.cpp
rename to Source/core/rendering/ClipRect.cpp
index e03c733..ed63eb4 100644
--- a/Source/core/page/NavigatorBase.cpp
+++ b/Source/core/rendering/ClipRect.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -10,7 +10,7 @@
  *    notice, this list of conditions and the following disclaimer in the
  *    documentation and/or other materials provided with the distribution.
  *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
@@ -21,32 +21,18 @@
  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
  */
 
 #include "config.h"
-#include "core/page/NavigatorBase.h"
+#include "core/rendering/ClipRect.h"
 
-#include "wtf/text/WTFString.h"
-
-#ifndef WEBCORE_NAVIGATOR_PRODUCT
-#define WEBCORE_NAVIGATOR_PRODUCT "Gecko"
-#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT
+#include "core/rendering/HitTestLocation.h"
 
 namespace WebCore {
 
-NavigatorBase::~NavigatorBase()
+bool ClipRect::intersects(const HitTestLocation& hitTestLocation) const
 {
-}
-
-String NavigatorBase::appCodeName() const
-{
-    return "Mozilla";
-}
-
-String NavigatorBase::product() const
-{
-    return WEBCORE_NAVIGATOR_PRODUCT;
+    return hitTestLocation.intersects(m_rect);
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/ClipRect.h b/Source/core/rendering/ClipRect.h
new file mode 100644
index 0000000..d88eb9a
--- /dev/null
+++ b/Source/core/rendering/ClipRect.h
@@ -0,0 +1,274 @@
+/*
+ * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ClipRect_h
+#define ClipRect_h
+
+#include "core/platform/graphics/LayoutRect.h"
+
+#include "wtf/Vector.h"
+
+#ifndef NDEBUG
+#include "core/rendering/RenderBox.h" // For OverlayScrollbarSizeRelevancy.
+#endif
+
+namespace WebCore {
+
+class RenderLayer;
+class HitTestLocation;
+
+class ClipRect {
+public:
+    ClipRect()
+        : m_hasRadius(false)
+    { }
+
+    ClipRect(const LayoutRect& rect)
+        : m_rect(rect)
+        , m_hasRadius(false)
+    { }
+
+    const LayoutRect& rect() const { return m_rect; }
+    void setRect(const LayoutRect& rect) { m_rect = rect; }
+
+    bool hasRadius() const { return m_hasRadius; }
+    void setHasRadius(bool hasRadius) { m_hasRadius = hasRadius; }
+
+    bool operator==(const ClipRect& other) const { return rect() == other.rect() && hasRadius() == other.hasRadius(); }
+    bool operator!=(const ClipRect& other) const { return rect() != other.rect() || hasRadius() != other.hasRadius(); }
+    bool operator!=(const LayoutRect& otherRect) const { return rect() != otherRect; }
+
+    void intersect(const LayoutRect& other) { m_rect.intersect(other); }
+    void intersect(const ClipRect& other)
+    {
+        m_rect.intersect(other.rect());
+        if (other.hasRadius())
+            m_hasRadius = true;
+    }
+    void move(LayoutUnit x, LayoutUnit y) { m_rect.move(x, y); }
+    void move(const LayoutSize& size) { m_rect.move(size); }
+    void moveBy(const LayoutPoint& point) { m_rect.moveBy(point); }
+
+    bool isEmpty() const { return m_rect.isEmpty(); }
+    bool intersects(const LayoutRect& rect) const { return m_rect.intersects(rect); }
+    bool intersects(const HitTestLocation&) const;
+
+private:
+    LayoutRect m_rect;
+    bool m_hasRadius;
+};
+
+inline ClipRect intersection(const ClipRect& a, const ClipRect& b)
+{
+    ClipRect c = a;
+    c.intersect(b);
+    return c;
+}
+
+class ClipRects {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    static PassRefPtr<ClipRects> create()
+    {
+        return adoptRef(new ClipRects);
+    }
+
+    static PassRefPtr<ClipRects> create(const ClipRects& other)
+    {
+        return adoptRef(new ClipRects(other));
+    }
+
+    ClipRects()
+        : m_refCnt(1)
+        , m_fixed(0)
+    {
+    }
+
+    void reset(const LayoutRect& r)
+    {
+        m_overflowClipRect = r;
+        m_fixedClipRect = r;
+        m_posClipRect = r;
+        m_fixed = 0;
+    }
+
+    const ClipRect& overflowClipRect() const { return m_overflowClipRect; }
+    void setOverflowClipRect(const ClipRect& r) { m_overflowClipRect = r; }
+
+    const ClipRect& fixedClipRect() const { return m_fixedClipRect; }
+    void setFixedClipRect(const ClipRect&r) { m_fixedClipRect = r; }
+
+    const ClipRect& posClipRect() const { return m_posClipRect; }
+    void setPosClipRect(const ClipRect& r) { m_posClipRect = r; }
+
+    bool fixed() const { return static_cast<bool>(m_fixed); }
+    void setFixed(bool fixed) { m_fixed = fixed ? 1 : 0; }
+
+    void ref() { m_refCnt++; }
+    void deref()
+    {
+        if (!--m_refCnt)
+            delete this;
+    }
+
+    bool operator==(const ClipRects& other) const
+    {
+        return m_overflowClipRect == other.overflowClipRect()
+            && m_fixedClipRect == other.fixedClipRect()
+            && m_posClipRect == other.posClipRect()
+            && m_fixed == other.fixed();
+    }
+
+    ClipRects& operator=(const ClipRects& other)
+    {
+        m_overflowClipRect = other.overflowClipRect();
+        m_fixedClipRect = other.fixedClipRect();
+        m_posClipRect = other.posClipRect();
+        m_fixed = other.fixed();
+        return *this;
+    }
+
+private:
+    ClipRects(const LayoutRect& r)
+        : m_overflowClipRect(r)
+        , m_fixedClipRect(r)
+        , m_posClipRect(r)
+        , m_refCnt(1)
+        , m_fixed(0)
+    {
+    }
+
+    ClipRects(const ClipRects& other)
+        : m_overflowClipRect(other.overflowClipRect())
+        , m_fixedClipRect(other.fixedClipRect())
+        , m_posClipRect(other.posClipRect())
+        , m_refCnt(1)
+        , m_fixed(other.fixed())
+    {
+    }
+
+    ClipRect m_overflowClipRect;
+    ClipRect m_fixedClipRect;
+    ClipRect m_posClipRect;
+    unsigned m_refCnt : 31;
+    unsigned m_fixed : 1;
+};
+
+enum ClipRectsType {
+    PaintingClipRects, // Relative to painting ancestor. Used for painting.
+    RootRelativeClipRects, // Relative to the ancestor treated as the root (e.g. transformed layer). Used for hit testing.
+    AbsoluteClipRects, // Relative to the RenderView's layer. Used for compositing overlap testing.
+    NumCachedClipRectsTypes,
+    AllClipRectTypes,
+    TemporaryClipRects
+};
+
+enum ShouldRespectOverflowClip {
+    IgnoreOverflowClip,
+    RespectOverflowClip
+};
+
+struct ClipRectsCache {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    ClipRectsCache()
+    {
+#ifndef NDEBUG
+        for (int i = 0; i < NumCachedClipRectsTypes; ++i) {
+            m_clipRectsRoot[i] = 0;
+            m_scrollbarRelevancy[i] = IgnoreOverlayScrollbarSize;
+        }
+#endif
+    }
+
+    PassRefPtr<ClipRects> getClipRects(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow) { return m_clipRects[getIndex(clipRectsType, respectOverflow)]; }
+    void setClipRects(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow, PassRefPtr<ClipRects> clipRects) { m_clipRects[getIndex(clipRectsType, respectOverflow)] = clipRects; }
+
+#ifndef NDEBUG
+    const RenderLayer* m_clipRectsRoot[NumCachedClipRectsTypes];
+    OverlayScrollbarSizeRelevancy m_scrollbarRelevancy[NumCachedClipRectsTypes];
+#endif
+
+private:
+    int getIndex(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow)
+    {
+        int index = static_cast<int>(clipRectsType);
+        if (respectOverflow == RespectOverflowClip)
+            index += static_cast<int>(NumCachedClipRectsTypes);
+        return index;
+    }
+
+    RefPtr<ClipRects> m_clipRects[NumCachedClipRectsTypes * 2];
+};
+
+struct LayerFragment {
+public:
+    LayerFragment()
+        : shouldPaintContent(false)
+    { }
+
+    void setRects(const LayoutRect& bounds, const ClipRect& background, const ClipRect& foreground, const ClipRect& outline)
+    {
+        layerBounds = bounds;
+        backgroundRect = background;
+        foregroundRect = foreground;
+        outlineRect = outline;
+    }
+
+    void moveBy(const LayoutPoint& offset)
+    {
+        layerBounds.moveBy(offset);
+        backgroundRect.moveBy(offset);
+        foregroundRect.moveBy(offset);
+        outlineRect.moveBy(offset);
+        paginationClip.moveBy(offset);
+    }
+
+    void intersect(const LayoutRect& rect)
+    {
+        backgroundRect.intersect(rect);
+        foregroundRect.intersect(rect);
+        outlineRect.intersect(rect);
+    }
+
+    bool shouldPaintContent;
+    LayoutRect layerBounds;
+    ClipRect backgroundRect;
+    ClipRect foregroundRect;
+    ClipRect outlineRect;
+
+    // Unique to paginated fragments. The physical translation to apply to shift the layer when painting/hit-testing.
+    LayoutPoint paginationOffset;
+
+    // Also unique to paginated fragments. An additional clip that applies to the layer. It is in layer-local
+    // (physical) coordinates.
+    LayoutRect paginationClip;
+};
+
+typedef Vector<LayerFragment, 1> LayerFragments;
+
+} // namespace WebCore
+
+#endif // ClipRect_h
diff --git a/Source/core/rendering/FloatingObjects.cpp b/Source/core/rendering/FloatingObjects.cpp
index 7312d7c..0250448 100644
--- a/Source/core/rendering/FloatingObjects.cpp
+++ b/Source/core/rendering/FloatingObjects.cpp
@@ -42,6 +42,63 @@
 
 COMPILE_ASSERT(sizeof(FloatingObject) == sizeof(SameSizeAsFloatingObject), FloatingObject_should_stay_small);
 
+FloatingObject::FloatingObject(RenderBox* renderer)
+    : m_renderer(renderer)
+    , m_originatingLine(0)
+    , m_paginationStrut(0)
+    , m_shouldPaint(true)
+    , m_isDescendant(false)
+    , m_isPlaced(false)
+#ifndef NDEBUG
+    , m_isInPlacedTree(false)
+#endif
+{
+    EFloat type = renderer->style()->floating();
+    ASSERT(type != NoFloat);
+    if (type == LeftFloat)
+        m_type = FloatLeft;
+    else if (type == RightFloat)
+        m_type = FloatRight;
+}
+
+FloatingObject::FloatingObject(RenderBox* renderer, Type type, const LayoutRect& frameRect, bool shouldPaint, bool isDescendant)
+    : m_renderer(renderer)
+    , m_originatingLine(0)
+    , m_frameRect(frameRect)
+    , m_paginationStrut(0)
+    , m_type(type)
+    , m_shouldPaint(shouldPaint)
+    , m_isDescendant(isDescendant)
+    , m_isPlaced(true)
+#ifndef NDEBUG
+    , m_isInPlacedTree(false)
+#endif
+{
+}
+
+PassOwnPtr<FloatingObject> FloatingObject::create(RenderBox* renderer)
+{
+    OwnPtr<FloatingObject> newObj = adoptPtr(new FloatingObject(renderer));
+    newObj->setShouldPaint(!renderer->hasSelfPaintingLayer()); // If a layer exists, the float will paint itself. Otherwise someone else will.
+    newObj->setIsDescendant(true);
+
+    return newObj.release();
+}
+
+PassOwnPtr<FloatingObject> FloatingObject::copyToNewContainer(LayoutSize offset, bool shouldPaint, bool isDescendant) const
+{
+    return adoptPtr(new FloatingObject(renderer(), type(), LayoutRect(frameRect().location() - offset, frameRect().size()), shouldPaint, isDescendant));
+}
+
+PassOwnPtr<FloatingObject> FloatingObject::unsafeClone() const
+{
+    OwnPtr<FloatingObject> cloneObject = adoptPtr(new FloatingObject(renderer(), type(), m_frameRect, m_shouldPaint, m_isDescendant));
+    cloneObject->m_originatingLine = m_originatingLine;
+    cloneObject->m_paginationStrut = m_paginationStrut;
+    cloneObject->m_isPlaced = m_isPlaced;
+    return cloneObject.release();
+}
+
 template <FloatingObject::Type FloatTypeValue>
 class ComputeFloatOffsetAdapter {
 public:
@@ -116,13 +173,101 @@
 
 void FloatingObjects::clear()
 {
-    // FIXME: This should call deleteAllValues, except clearFloats
-    // like to play fast and loose with ownership of these pointers.
-    // If we move to OwnPtr that will fix this ownership oddness.
+    deleteAllValues(m_set);
     m_set.clear();
     m_placedFloatsTree.clear();
     m_leftObjectsCount = 0;
     m_rightObjectsCount = 0;
+    markLowestFloatLogicalBottomCacheAsDirty();
+}
+
+LayoutUnit FloatingObjects::lowestFloatLogicalBottom(FloatingObject::Type floatType)
+{
+    bool isInHorizontalWritingMode = m_horizontalWritingMode;
+    if (floatType != FloatingObject::FloatLeftRight) {
+        if (hasLowestFloatLogicalBottomCached(isInHorizontalWritingMode, floatType))
+            return getCachedlowestFloatLogicalBottom(floatType);
+    } else {
+        if (hasLowestFloatLogicalBottomCached(isInHorizontalWritingMode, FloatingObject::FloatLeft) && hasLowestFloatLogicalBottomCached(isInHorizontalWritingMode, FloatingObject::FloatRight)) {
+            return max(getCachedlowestFloatLogicalBottom(FloatingObject::FloatLeft),
+                getCachedlowestFloatLogicalBottom(FloatingObject::FloatRight));
+        }
+    }
+
+    LayoutUnit lowestFloatBottom = 0;
+    const FloatingObjectSet& floatingObjectSet = set();
+    FloatingObjectSetIterator end = floatingObjectSet.end();
+    if (floatType == FloatingObject::FloatLeftRight) {
+        LayoutUnit lowestFloatBottomLeft = 0;
+        LayoutUnit lowestFloatBottomRight = 0;
+        for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+            FloatingObject* r = *it;
+            if (r->isPlaced()) {
+                FloatingObject::Type curType = r->type();
+                LayoutUnit curFloatLogicalBottom = r->logicalBottom(isInHorizontalWritingMode);
+                if (curType & FloatingObject::FloatLeft)
+                    lowestFloatBottomLeft = max(lowestFloatBottomLeft, curFloatLogicalBottom);
+                if (curType & FloatingObject::FloatRight)
+                    lowestFloatBottomRight = max(lowestFloatBottomRight, curFloatLogicalBottom);
+            }
+        }
+        lowestFloatBottom = max(lowestFloatBottomLeft, lowestFloatBottomRight);
+        setCachedLowestFloatLogicalBottom(isInHorizontalWritingMode, FloatingObject::FloatLeft, lowestFloatBottomLeft);
+        setCachedLowestFloatLogicalBottom(isInHorizontalWritingMode, FloatingObject::FloatRight, lowestFloatBottomRight);
+    } else {
+        for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+            FloatingObject* r = *it;
+            if (r->isPlaced() && r->type() == floatType)
+                lowestFloatBottom = max(lowestFloatBottom, r->logicalBottom(isInHorizontalWritingMode));
+        }
+        setCachedLowestFloatLogicalBottom(isInHorizontalWritingMode, floatType, lowestFloatBottom);
+    }
+
+    return lowestFloatBottom;
+}
+
+bool FloatingObjects::hasLowestFloatLogicalBottomCached(bool isHorizontal, FloatingObject::Type type) const
+{
+    int floatIndex = static_cast<int>(type) - 1;
+    ASSERT(floatIndex < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue));
+    ASSERT(floatIndex >= 0);
+    return (m_cachedHorizontalWritingMode == isHorizontal && !m_lowestFloatBottomCache[floatIndex].dirty);
+}
+
+LayoutUnit FloatingObjects::getCachedlowestFloatLogicalBottom(FloatingObject::Type type) const
+{
+    int floatIndex = static_cast<int>(type) - 1;
+    ASSERT(floatIndex < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue));
+    ASSERT(floatIndex >= 0);
+    return m_lowestFloatBottomCache[floatIndex].value;
+}
+
+void FloatingObjects::setCachedLowestFloatLogicalBottom(bool isHorizontal, FloatingObject::Type type, LayoutUnit value)
+{
+    int floatIndex = static_cast<int>(type) - 1;
+    ASSERT(floatIndex < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue));
+    ASSERT(floatIndex >= 0);
+    m_cachedHorizontalWritingMode = isHorizontal;
+    m_lowestFloatBottomCache[floatIndex].value = value;
+    m_lowestFloatBottomCache[floatIndex].dirty = false;
+}
+
+void FloatingObjects::markLowestFloatLogicalBottomCacheAsDirty()
+{
+    for (int i = 0; i < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue); ++i)
+        m_lowestFloatBottomCache[i].dirty = true;
+}
+
+void FloatingObjects::moveAllToFloatInfoMap(RendererToFloatInfoMap& map)
+{
+    FloatingObjectSetIterator end = m_set.end();
+    for (FloatingObjectSetIterator it = m_set.begin(); it != end; ++it)
+        map.add((*it)->renderer(), *it);
+
+    // clear set before clearing this because we don't want to delete all of
+    // the objects we have just transferred.
+    m_set.clear();
+    clear();
 }
 
 inline void FloatingObjects::increaseObjectsCount(FloatingObject::Type type)
@@ -159,6 +304,7 @@
 #ifndef NDEBUG
     floatingObject->setIsInPlacedTree(true);
 #endif
+    markLowestFloatLogicalBottomCacheAsDirty();
 }
 
 void FloatingObjects::removePlacedObject(FloatingObject* floatingObject)
@@ -174,14 +320,18 @@
 #ifndef NDEBUG
     floatingObject->setIsInPlacedTree(false);
 #endif
+    markLowestFloatLogicalBottomCacheAsDirty();
 }
 
-void FloatingObjects::add(FloatingObject* floatingObject)
+FloatingObject* FloatingObjects::add(PassOwnPtr<FloatingObject> floatingObject)
 {
-    increaseObjectsCount(floatingObject->type());
-    m_set.add(floatingObject);
-    if (floatingObject->isPlaced())
-        addPlacedObject(floatingObject);
+    FloatingObject* newObject = floatingObject.leakPtr();
+    increaseObjectsCount(newObject->type());
+    m_set.add(newObject);
+    if (newObject->isPlaced())
+        addPlacedObject(newObject);
+    markLowestFloatLogicalBottomCacheAsDirty();
+    return newObject;
 }
 
 void FloatingObjects::remove(FloatingObject* floatingObject)
@@ -191,6 +341,9 @@
     ASSERT(floatingObject->isPlaced() || !floatingObject->isInPlacedTree());
     if (floatingObject->isPlaced())
         removePlacedObject(floatingObject);
+    markLowestFloatLogicalBottomCacheAsDirty();
+    ASSERT(!floatingObject->originatingLine());
+    delete floatingObject;
 }
 
 void FloatingObjects::computePlacedFloatsTree()
@@ -248,6 +401,12 @@
     return min(fixedOffset, offset);
 }
 
+FloatingObjects::FloatBottomCachedValue::FloatBottomCachedValue()
+    : value(0)
+    , dirty(true)
+{
+}
+
 inline static bool rangesIntersect(int floatTop, int floatBottom, int objectTop, int objectBottom)
 {
     if (objectTop >= floatBottom || objectBottom < floatTop)
diff --git a/Source/core/rendering/FloatingObjects.h b/Source/core/rendering/FloatingObjects.h
index ba8c4e9..9b258e3 100644
--- a/Source/core/rendering/FloatingObjects.h
+++ b/Source/core/rendering/FloatingObjects.h
@@ -28,6 +28,7 @@
 #include "core/platform/PODIntervalTree.h"
 #include "core/rendering/RootInlineBox.h"
 #include "wtf/ListHashSet.h"
+#include "wtf/OwnPtr.h"
 
 namespace WebCore {
 
@@ -47,50 +48,11 @@
     // Note that Type uses bits so you can use FloatLeftRight as a mask to query for both left and right.
     enum Type { FloatLeft = 1, FloatRight = 2, FloatLeftRight = 3 };
 
-    FloatingObject(EFloat type)
-        : m_renderer(0)
-        , m_originatingLine(0)
-        , m_paginationStrut(0)
-        , m_shouldPaint(true)
-        , m_isDescendant(false)
-        , m_isPlaced(false)
-#ifndef NDEBUG
-        , m_isInPlacedTree(false)
-#endif
-    {
-        ASSERT(type != NoFloat);
-        if (type == LeftFloat)
-            m_type = FloatLeft;
-        else if (type == RightFloat)
-            m_type = FloatRight;
-    }
+    static PassOwnPtr<FloatingObject> create(RenderBox*);
 
-    FloatingObject(Type type, const LayoutRect& frameRect)
-        : m_renderer(0)
-        , m_originatingLine(0)
-        , m_frameRect(frameRect)
-        , m_paginationStrut(0)
-        , m_type(type)
-        , m_shouldPaint(true)
-        , m_isDescendant(false)
-        , m_isPlaced(true)
-#ifndef NDEBUG
-        , m_isInPlacedTree(false)
-#endif
-    {
-    }
+    PassOwnPtr<FloatingObject> copyToNewContainer(LayoutSize, bool shouldPaint = false, bool isDescendant = false) const;
 
-    FloatingObject* clone() const
-    {
-        FloatingObject* cloneObject = new FloatingObject(type(), m_frameRect);
-        cloneObject->m_renderer = m_renderer;
-        cloneObject->m_originatingLine = m_originatingLine;
-        cloneObject->m_paginationStrut = m_paginationStrut;
-        cloneObject->m_shouldPaint = m_shouldPaint;
-        cloneObject->m_isDescendant = m_isDescendant;
-        cloneObject->m_isPlaced = m_isPlaced;
-        return cloneObject;
-    }
+    PassOwnPtr<FloatingObject> unsafeClone() const;
 
     Type type() const { return static_cast<Type>(m_type); }
     RenderBox* renderer() const { return m_renderer; }
@@ -127,7 +89,6 @@
     void setIsDescendant(bool isDescendant) { m_isDescendant = isDescendant; }
 
     // FIXME: Callers of these methods are dangerous and should be whitelisted explicitly or removed.
-    void setRenderer(RenderBox* renderer) { m_renderer = renderer; }
     RootInlineBox* originatingLine() const { return m_originatingLine; }
     void setOriginatingLine(RootInlineBox* line) { m_originatingLine = line; }
 
@@ -172,6 +133,9 @@
     }
 
 private:
+    explicit FloatingObject(RenderBox*);
+    FloatingObject(RenderBox*, Type, const LayoutRect&, bool shouldPaint, bool isDescendant);
+
     RenderBox* m_renderer;
     RootInlineBox* m_originatingLine;
     LayoutRect m_frameRect;
@@ -200,6 +164,7 @@
 typedef PODInterval<int, FloatingObject*> FloatingObjectInterval;
 typedef PODIntervalTree<int, FloatingObject*> FloatingObjectTree;
 typedef PODFreeListArena<PODRedBlackTree<FloatingObjectInterval>::Node> IntervalArena;
+typedef HashMap<RenderBox*, FloatingObject*> RendererToFloatInfoMap;
 
 class FloatingObjects {
     WTF_MAKE_NONCOPYABLE(FloatingObjects); WTF_MAKE_FAST_ALLOCATED;
@@ -208,7 +173,8 @@
     ~FloatingObjects();
 
     void clear();
-    void add(FloatingObject*);
+    void moveAllToFloatInfoMap(RendererToFloatInfoMap&);
+    FloatingObject* add(PassOwnPtr<FloatingObject>);
     void remove(FloatingObject*);
     void addPlacedObject(FloatingObject*);
     void removePlacedObject(FloatingObject*);
@@ -220,7 +186,15 @@
     void clearLineBoxTreePointers();
     LayoutUnit logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode = ShapeOutsideFloatShapeOffset, LayoutUnit* heightRemaining = 0);
     LayoutUnit logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode = ShapeOutsideFloatShapeOffset, LayoutUnit* heightRemaining = 0);
+
+    LayoutUnit lowestFloatLogicalBottom(FloatingObject::Type);
+
 private:
+    bool hasLowestFloatLogicalBottomCached(bool isHorizontal, FloatingObject::Type floatType) const;
+    LayoutUnit getCachedlowestFloatLogicalBottom(FloatingObject::Type floatType) const;
+    void setCachedLowestFloatLogicalBottom(bool isHorizontal, FloatingObject::Type floatType, LayoutUnit value);
+    void markLowestFloatLogicalBottomCacheAsDirty();
+
     void computePlacedFloatsTree();
     const FloatingObjectTree& placedFloatsTree()
     {
@@ -238,6 +212,14 @@
     unsigned m_rightObjectsCount;
     bool m_horizontalWritingMode;
     const RenderBlock* m_renderer;
+
+    struct FloatBottomCachedValue {
+        FloatBottomCachedValue();
+        LayoutUnit value;
+        bool dirty;
+    };
+    FloatBottomCachedValue m_lowestFloatBottomCache[2];
+    bool m_cachedHorizontalWritingMode;
 };
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/InlineIterator.h b/Source/core/rendering/InlineIterator.h
index f277912..fa5a8ad 100644
--- a/Source/core/rendering/InlineIterator.h
+++ b/Source/core/rendering/InlineIterator.h
@@ -36,7 +36,7 @@
 class InlineIterator {
 public:
     enum IncrementRule {
-        FastIncrementInlineRenderer,
+        FastIncrementInIsolatedRenderer,
         FastIncrementInTextNode
     };
 
@@ -361,7 +361,13 @@
 {
     if (!m_obj)
         return;
-    if (m_obj->isText() && rule == FastIncrementInTextNode) {
+
+    if (resolver && resolver->inIsolate() && rule == FastIncrementInIsolatedRenderer) {
+        moveTo(bidiNextSkippingEmptyInlines(m_root, m_obj, resolver), 0);
+        return;
+    }
+
+    if (m_obj->isText()) {
         fastIncrementInTextNode();
         if (m_pos < toRenderText(m_obj)->textLength())
             return;
@@ -410,7 +416,19 @@
 template<>
 inline void InlineBidiResolver::increment()
 {
-    m_current.increment(this);
+    m_current.increment(this, InlineIterator::FastIncrementInIsolatedRenderer);
+}
+
+template <>
+inline bool InlineBidiResolver::isEndOfParagraph(const InlineIterator& end)
+{
+    bool inEndOfParagraph = m_current == end || m_current.atEnd() || (inIsolate() && m_current.m_obj == end.m_obj);
+    if (inIsolate() && inEndOfParagraph) {
+        m_current.moveTo(m_current.m_obj, end.m_pos, m_current.m_nextBreakablePosition);
+        m_last = m_current;
+        updateStatusLastFromCurrentDirection(WTF::Unicode::OtherNeutral);
+    }
+    return inEndOfParagraph;
 }
 
 static inline bool isIsolatedInline(RenderObject* object)
diff --git a/Source/core/rendering/LineWidth.cpp b/Source/core/rendering/LineWidth.cpp
new file mode 100644
index 0000000..72d1656
--- /dev/null
+++ b/Source/core/rendering/LineWidth.cpp
@@ -0,0 +1,177 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ *    copyright notice, this list of conditions and the following
+ *    disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ *    copyright notice, this list of conditions and the following
+ *    disclaimer in the documentation and/or other materials
+ *    provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/LineWidth.h"
+
+namespace WebCore {
+
+LineWidth::LineWidth(RenderBlock& block, bool isFirstLine, IndentTextOrNot shouldIndentText)
+    : m_block(block)
+    , m_uncommittedWidth(0)
+    , m_committedWidth(0)
+    , m_overhangWidth(0)
+    , m_left(0)
+    , m_right(0)
+    , m_availableWidth(0)
+    , m_segment(0)
+    , m_isFirstLine(isFirstLine)
+    , m_shouldIndentText(shouldIndentText)
+{
+    if (ShapeInsideInfo* shapeInsideInfo = m_block.layoutShapeInsideInfo())
+        m_segment = shapeInsideInfo->currentSegment();
+    updateAvailableWidth();
+}
+
+void LineWidth::updateAvailableWidth(LayoutUnit replacedHeight)
+{
+    LayoutUnit height = m_block.logicalHeight();
+    LayoutUnit logicalHeight = logicalHeightForLine(&m_block, m_isFirstLine, replacedHeight);
+    m_left = m_block.logicalLeftOffsetForLine(height, shouldIndentText(), logicalHeight);
+    m_right = m_block.logicalRightOffsetForLine(height, shouldIndentText(), logicalHeight);
+
+    if (m_segment) {
+        m_left = std::max<float>(m_segment->logicalLeft, m_left);
+        m_right = std::min<float>(m_segment->logicalRight, m_right);
+    }
+
+    computeAvailableWidthFromLeftAndRight();
+}
+
+void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(FloatingObject* newFloat)
+{
+    LayoutUnit height = m_block.logicalHeight();
+    if (height < newFloat->logicalTop(m_block.isHorizontalWritingMode()) || height >= newFloat->logicalBottom(m_block.isHorizontalWritingMode()))
+        return;
+
+    // When floats with shape outside are stacked, the floats are positioned based on the margin box of the float,
+    // not the shape's contour. Since we computed the width based on the shape contour when we added the float,
+    // when we add a subsequent float on the same line, we need to undo the shape delta in order to position
+    // based on the margin box. In order to do this, we need to walk back through the floating object list to find
+    // the first previous float that is on the same side as our newFloat.
+    ShapeOutsideInfo* previousShapeOutsideInfo = 0;
+    const FloatingObjectSet& floatingObjectSet = m_block.m_floatingObjects->set();
+    FloatingObjectSetIterator it = floatingObjectSet.end();
+    FloatingObjectSetIterator begin = floatingObjectSet.begin();
+    for (--it; it != begin; --it) {
+        FloatingObject* previousFloat = *it;
+        if (previousFloat != newFloat && previousFloat->type() == newFloat->type()) {
+            previousShapeOutsideInfo = previousFloat->renderer()->shapeOutsideInfo();
+            if (previousShapeOutsideInfo)
+                previousShapeOutsideInfo->computeSegmentsForContainingBlockLine(m_block.logicalHeight(), previousFloat->logicalTop(m_block.isHorizontalWritingMode()), logicalHeightForLine(&m_block, m_isFirstLine));
+            break;
+        }
+    }
+
+    ShapeOutsideInfo* shapeOutsideInfo = newFloat->renderer()->shapeOutsideInfo();
+    if (shapeOutsideInfo)
+        shapeOutsideInfo->computeSegmentsForContainingBlockLine(m_block.logicalHeight(), newFloat->logicalTop(m_block.isHorizontalWritingMode()), logicalHeightForLine(&m_block, m_isFirstLine));
+
+    if (newFloat->type() == FloatingObject::FloatLeft) {
+        float newLeft = newFloat->logicalRight(m_block.isHorizontalWritingMode());
+        if (previousShapeOutsideInfo)
+            newLeft -= previousShapeOutsideInfo->rightSegmentMarginBoxDelta();
+        if (shapeOutsideInfo)
+            newLeft += shapeOutsideInfo->rightSegmentMarginBoxDelta();
+
+        if (shouldIndentText() && m_block.style()->isLeftToRightDirection())
+            newLeft += floorToInt(m_block.textIndentOffset());
+        m_left = std::max<float>(m_left, newLeft);
+    } else {
+        float newRight = newFloat->logicalLeft(m_block.isHorizontalWritingMode());
+        if (previousShapeOutsideInfo)
+            newRight -= previousShapeOutsideInfo->leftSegmentMarginBoxDelta();
+        if (shapeOutsideInfo)
+            newRight += shapeOutsideInfo->leftSegmentMarginBoxDelta();
+
+        if (shouldIndentText() && !m_block.style()->isLeftToRightDirection())
+            newRight -= floorToInt(m_block.textIndentOffset());
+        m_right = std::min<float>(m_right, newRight);
+    }
+
+    computeAvailableWidthFromLeftAndRight();
+}
+
+void LineWidth::commit()
+{
+    m_committedWidth += m_uncommittedWidth;
+    m_uncommittedWidth = 0;
+}
+
+void LineWidth::applyOverhang(RenderRubyRun* rubyRun, RenderObject* startRenderer, RenderObject* endRenderer)
+{
+    int startOverhang;
+    int endOverhang;
+    rubyRun->getOverhang(m_isFirstLine, startRenderer, endRenderer, startOverhang, endOverhang);
+
+    startOverhang = std::min<int>(startOverhang, m_committedWidth);
+    m_availableWidth += startOverhang;
+
+    endOverhang = std::max(std::min<int>(endOverhang, m_availableWidth - currentWidth()), 0);
+    m_availableWidth += endOverhang;
+    m_overhangWidth += startOverhang + endOverhang;
+}
+
+void LineWidth::fitBelowFloats()
+{
+    ASSERT(!m_committedWidth);
+    ASSERT(!fitsOnLine());
+
+    LayoutUnit floatLogicalBottom;
+    LayoutUnit lastFloatLogicalBottom = m_block.logicalHeight();
+    float newLineWidth = m_availableWidth;
+    float newLineLeft = m_left;
+    float newLineRight = m_right;
+    while (true) {
+        floatLogicalBottom = m_block.nextFloatLogicalBottomBelow(lastFloatLogicalBottom);
+        if (floatLogicalBottom <= lastFloatLogicalBottom)
+            break;
+
+        newLineLeft = m_block.logicalLeftOffsetForLine(floatLogicalBottom, shouldIndentText());
+        newLineRight = m_block.logicalRightOffsetForLine(floatLogicalBottom, shouldIndentText());
+        newLineWidth = max(0.0f, newLineRight - newLineLeft);
+        lastFloatLogicalBottom = floatLogicalBottom;
+        if (newLineWidth >= m_uncommittedWidth)
+            break;
+    }
+
+    if (newLineWidth > m_availableWidth) {
+        m_block.setLogicalHeight(lastFloatLogicalBottom);
+        m_availableWidth = newLineWidth + m_overhangWidth;
+        m_left = newLineLeft;
+        m_right = newLineRight;
+    }
+}
+
+void LineWidth::computeAvailableWidthFromLeftAndRight()
+{
+    m_availableWidth = max(0.0f, m_right - m_left) + m_overhangWidth;
+}
+
+}
diff --git a/Source/core/rendering/LineWidth.h b/Source/core/rendering/LineWidth.h
new file mode 100644
index 0000000..f0bd81a
--- /dev/null
+++ b/Source/core/rendering/LineWidth.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ *    copyright notice, this list of conditions and the following
+ *    disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ *    copyright notice, this list of conditions and the following
+ *    disclaimer in the documentation and/or other materials
+ *    provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef LineWidth_h
+#define LineWidth_h
+
+#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderRubyRun.h"
+
+namespace WebCore {
+
+enum IndentTextOrNot { DoNotIndentText, IndentText };
+
+inline LayoutUnit logicalHeightForLine(const RenderBlock* block, bool isFirstLine, LayoutUnit replacedHeight = 0)
+{
+    if (!block->document().inNoQuirksMode() && replacedHeight)
+        return replacedHeight;
+
+    if (!(block->style(isFirstLine)->lineBoxContain() & LineBoxContainBlock))
+        return 0;
+
+    return std::max<LayoutUnit>(replacedHeight, block->lineHeight(isFirstLine, block->isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
+}
+
+class LineWidth {
+public:
+    LineWidth(RenderBlock&, bool isFirstLine, IndentTextOrNot shouldIndentText);
+
+    bool fitsOnLine() const { return currentWidth() <= m_availableWidth; }
+    bool fitsOnLine(float extra) const { return currentWidth() + extra <= m_availableWidth; }
+
+    float currentWidth() const { return m_committedWidth + m_uncommittedWidth; }
+    // FIXME: We should eventually replace these three functions by ones that work on a higher abstraction.
+    float uncommittedWidth() const { return m_uncommittedWidth; }
+    float committedWidth() const { return m_committedWidth; }
+    float availableWidth() const { return m_availableWidth; }
+
+    void updateAvailableWidth(LayoutUnit minimumHeight = 0);
+    void shrinkAvailableWidthForNewFloatIfNeeded(FloatingObject*);
+    void addUncommittedWidth(float delta) { m_uncommittedWidth += delta; }
+    void commit();
+    void applyOverhang(RenderRubyRun*, RenderObject* startRenderer, RenderObject* endRenderer);
+    void fitBelowFloats();
+
+    bool shouldIndentText() const { return m_shouldIndentText == IndentText; }
+
+private:
+    void computeAvailableWidthFromLeftAndRight();
+
+    RenderBlock& m_block;
+    float m_uncommittedWidth;
+    float m_committedWidth;
+    float m_overhangWidth; // The amount by which |m_availableWidth| has been inflated to account for possible contraction due to ruby overhang.
+    float m_left;
+    float m_right;
+    float m_availableWidth;
+    const LineSegment* m_segment;
+    bool m_isFirstLine;
+    IndentTextOrNot m_shouldIndentText;
+};
+
+}
+
+#endif // LineWidth_h
diff --git a/Source/core/rendering/OrderIterator.cpp b/Source/core/rendering/OrderIterator.cpp
index d55779c..1cda9c5 100644
--- a/Source/core/rendering/OrderIterator.cpp
+++ b/Source/core/rendering/OrderIterator.cpp
@@ -62,9 +62,9 @@
                 m_orderValuesIterator = m_orderValues.begin();
             }
 
-            m_currentChild = m_containerBox->firstChildBox();
+            m_currentChild = firstChildBox();
         } else {
-            m_currentChild = m_currentChild->nextSiblingBox();
+            m_currentChild = nextSiblingBox();
         }
     } while (!m_currentChild || m_currentChild->style()->order() != *m_orderValuesIterator);
 
@@ -77,6 +77,26 @@
     m_orderValuesIterator = 0;
 }
 
+RenderBox* OrderIterator::firstChildBox()
+{
+    if (m_children.isEmpty())
+        return m_containerBox->firstChildBox();
+
+    m_childIndex = 0;
+    return m_children[0];
+}
+
+RenderBox* OrderIterator::nextSiblingBox()
+{
+    if (m_children.isEmpty())
+        return m_currentChild->nextSiblingBox();
+
+    if (m_childIndex >= m_children.size() - 1)
+        return 0;
+
+    return m_children[++m_childIndex];
+}
+
 OrderIteratorPopulator::~OrderIteratorPopulator()
 {
     m_iterator.reset();
@@ -110,6 +130,13 @@
     orderValues.shrink(uniqueItemIndex + 1);
 }
 
+void OrderIteratorPopulator::storeChild(RenderBox* child)
+{
+    m_iterator.m_children.append(child);
+
+    collectChild(child);
+}
+
 void OrderIteratorPopulator::collectChild(const RenderBox* child)
 {
     // Avoid growing the vector for the common-case default value of 0.
diff --git a/Source/core/rendering/OrderIterator.h b/Source/core/rendering/OrderIterator.h
index 8639bdc..3f76985 100644
--- a/Source/core/rendering/OrderIterator.h
+++ b/Source/core/rendering/OrderIterator.h
@@ -51,8 +51,16 @@
     void reset();
 
 private:
+    RenderBox* firstChildBox();
+    RenderBox* nextSiblingBox();
+
+    // If |m_children| is not empty, we will use it to iterate over this fixed subset.
     const RenderBox* m_containerBox;
+    Vector<RenderBox*> m_children;
+
     RenderBox* m_currentChild;
+    size_t m_childIndex;
+
     // The inline capacity for a single item is used to cover the most
     // common case by far: if we only have the default 'order' value 0.
     typedef Vector<int, 1> OrderValues;
@@ -73,6 +81,7 @@
 
     ~OrderIteratorPopulator();
 
+    void storeChild(RenderBox*);
     void collectChild(const RenderBox*);
 
 private:
diff --git a/Source/core/rendering/RenderBR.cpp b/Source/core/rendering/RenderBR.cpp
index 785f654..ea74001 100644
--- a/Source/core/rendering/RenderBR.cpp
+++ b/Source/core/rendering/RenderBR.cpp
@@ -45,7 +45,7 @@
 
 int RenderBR::lineHeight(bool firstLine) const
 {
-    if (firstLine && document().styleSheetCollections()->usesFirstLineRules()) {
+    if (firstLine && document().styleEngine()->usesFirstLineRules()) {
         RenderStyle* s = style(firstLine);
         if (s != style())
             return s->computedLineHeight(view());
diff --git a/Source/core/rendering/RenderBlock.cpp b/Source/core/rendering/RenderBlock.cpp
index 20ac848..4520c82 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -81,13 +81,6 @@
 
 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
 
-COMPILE_ASSERT(sizeof(RenderBlock::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
-
-struct SameSizeAsMarginInfo {
-    uint32_t bitfields : 16;
-    LayoutUnit margins[2];
-};
-
 typedef WTF::HashMap<const RenderBox*, OwnPtr<ColumnInfo> > ColumnInfoMap;
 static ColumnInfoMap* gColumnInfoMap = 0;
 
@@ -147,41 +140,6 @@
     bool m_hadVerticalLayoutOverflow;
 };
 
-// Our MarginInfo state used when laying out block children.
-RenderBlock::MarginInfo::MarginInfo(RenderBlock* block, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
-    : m_atBeforeSideOfBlock(true)
-    , m_atAfterSideOfBlock(false)
-    , m_hasMarginBeforeQuirk(false)
-    , m_hasMarginAfterQuirk(false)
-    , m_determinedMarginBeforeQuirk(false)
-    , m_discardMargin(false)
-{
-    RenderStyle* blockStyle = block->style();
-    ASSERT(block->isRenderView() || block->parent());
-    m_canCollapseWithChildren = !block->isRenderView() && !block->isRoot() && !block->isOutOfFlowPositioned()
-        && !block->isFloating() && !block->isTableCell() && !block->hasOverflowClip() && !block->isInlineBlockOrInlineTable()
-        && !block->isRenderFlowThread() && !block->isWritingModeRoot() && !block->parent()->isFlexibleBox()
-        && blockStyle->hasAutoColumnCount() && blockStyle->hasAutoColumnWidth() && !blockStyle->columnSpan();
-
-    m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
-
-    // If any height other than auto is specified in CSS, then we don't collapse our bottom
-    // margins with our children's margins.  To do otherwise would be to risk odd visual
-    // effects when the children overflow out of the parent block and yet still collapse
-    // with it.  We also don't collapse if we have any bottom border/padding.
-    m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && (afterBorderPadding == 0) &&
-        (blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
-
-    m_quirkContainer = block->isTableCell() || block->isBody();
-
-    m_discardMargin = m_canCollapseMarginBeforeWithChildren && block->mustDiscardMarginBefore();
-
-    m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxPositiveMarginBefore() : LayoutUnit();
-    m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxNegativeMarginBefore() : LayoutUnit();
-}
-
-// -------------------------------------------------------------------------------------------------------
-
 RenderBlock::RenderBlock(ContainerNode* node)
     : RenderBox(node)
     , m_lineHeight(-1)
@@ -192,7 +150,6 @@
     , m_hasBorderOrPaddingLogicalWidthChanged(false)
 {
     setChildrenInline(true);
-    COMPILE_ASSERT(sizeof(RenderBlock::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
 }
 
 static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
@@ -1168,7 +1125,7 @@
             if (toBlock->containsFloat(floatingObject->renderer()))
                 continue;
 
-            toBlock->m_floatingObjects->add(floatingObject->clone());
+            toBlock->m_floatingObjects->add(floatingObject->unsafeClone());
         }
     }
 
@@ -1665,51 +1622,6 @@
            || hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
 }
 
-void RenderBlock::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
-{
-    bool isHorizontal = isHorizontalWritingMode();
-    bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
-
-    LayoutUnit logicalTop = logicalHeight();
-    updateStaticInlinePositionForChild(child, logicalTop);
-
-    if (!marginInfo.canCollapseWithMarginBefore()) {
-        // Positioned blocks don't collapse margins, so add the margin provided by
-        // the container now. The child's own margin is added later when calculating its logical top.
-        LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
-        LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
-        logicalTop += collapsedBeforePos - collapsedBeforeNeg;
-    }
-
-    RenderLayer* childLayer = child->layer();
-    if (childLayer->staticBlockPosition() != logicalTop) {
-        childLayer->setStaticBlockPosition(logicalTop);
-        if (hasStaticBlockPosition)
-            child->setChildNeedsLayout(MarkOnlyThis);
-    }
-}
-
-void RenderBlock::adjustFloatingBlock(const MarginInfo& marginInfo)
-{
-    // The float should be positioned taking into account the bottom margin
-    // of the previous flow.  We add that margin into the height, get the
-    // float positioned properly, and then subtract the margin out of the
-    // height again.  In the case of self-collapsing blocks, we always just
-    // use the top margins, since the self-collapsing block collapsed its
-    // own bottom margin into its top margin.
-    //
-    // Note also that the previous flow may collapse its margin into the top of
-    // our block.  If this is the case, then we do not add the margin in to our
-    // height when computing the position of the float.   This condition can be tested
-    // for by simply calling canCollapseWithMarginBefore.  See
-    // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
-    // an example of this scenario.
-    LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
-    setLogicalHeight(logicalHeight() + marginOffset);
-    positionNewFloats();
-    setLogicalHeight(logicalHeight() - marginOffset);
-}
-
 static void destroyRunIn(RenderBoxModelObject* runIn)
 {
     ASSERT(runIn->isRunIn());
@@ -1850,325 +1762,6 @@
     parent()->setNeedsLayoutAndPrefWidthsRecalc();
 }
 
-LayoutUnit RenderBlock::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
-{
-    bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
-    bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
-    bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
-
-    // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
-    childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
-
-    // Get the four margin values for the child and cache them.
-    const MarginValues childMargins = marginValuesForChild(child);
-
-    // Get our max pos and neg top margins.
-    LayoutUnit posTop = childMargins.positiveMarginBefore();
-    LayoutUnit negTop = childMargins.negativeMarginBefore();
-
-    // For self-collapsing blocks, collapse our bottom margins into our
-    // top to get new posTop and negTop values.
-    if (childIsSelfCollapsing) {
-        posTop = max(posTop, childMargins.positiveMarginAfter());
-        negTop = max(negTop, childMargins.negativeMarginAfter());
-    }
-
-    // See if the top margin is quirky. We only care if this child has
-    // margins that will collapse with us.
-    bool topQuirk = hasMarginBeforeQuirk(child);
-
-    if (marginInfo.canCollapseWithMarginBefore()) {
-        if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
-            // This child is collapsing with the top of the
-            // block. If it has larger margin values, then we need to update
-            // our own maximal values.
-            if (!document().inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
-                setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
-
-            // The minute any of the margins involved isn't a quirk, don't
-            // collapse it away, even if the margin is smaller (www.webreference.com
-            // has an example of this, a <dt> with 0.8em author-specified inside
-            // a <dl> inside a <td>.
-            if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
-                setHasMarginBeforeQuirk(false);
-                marginInfo.setDeterminedMarginBeforeQuirk(true);
-            }
-
-            if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore())
-                // We have no top margin and our top child has a quirky margin.
-                // We will pick up this quirky margin and pass it through.
-                // This deals with the <td><div><p> case.
-                // Don't do this for a block that split two inlines though. You do
-                // still apply margins in this case.
-                setHasMarginBeforeQuirk(true);
-        } else
-            // The before margin of the container will also discard all the margins it is collapsing with.
-            setMustDiscardMarginBefore();
-    }
-
-    // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard.
-    if (childDiscardMarginBefore) {
-        marginInfo.setDiscardMargin(true);
-        marginInfo.clearMargin();
-    }
-
-    if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
-        marginInfo.setHasMarginBeforeQuirk(topQuirk);
-
-    LayoutUnit beforeCollapseLogicalTop = logicalHeight();
-    LayoutUnit logicalTop = beforeCollapseLogicalTop;
-    if (childIsSelfCollapsing) {
-        // For a self collapsing block both the before and after margins get discarded. The block doesn't contribute anything to the height of the block.
-        // Also, the child's top position equals the logical height of the container.
-        if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
-            // This child has no height. We need to compute our
-            // position before we collapse the child's margins together,
-            // so that we can get an accurate position for the zero-height block.
-            LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
-            LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
-            marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
-
-            // Now collapse the child's margins together, which means examining our
-            // bottom margin values as well.
-            marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
-            marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
-
-            if (!marginInfo.canCollapseWithMarginBefore())
-                // We need to make sure that the position of the self-collapsing block
-                // is correct, since it could have overflowing content
-                // that needs to be positioned correctly (e.g., a block that
-                // had a specified height of 0 but that actually had subcontent).
-                logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
-        }
-    } else {
-        if (mustSeparateMarginBeforeForChild(child)) {
-            ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
-            // If we are at the before side of the block and we collapse, ignore the computed margin
-            // and just add the child margin to the container height. This will correctly position
-            // the child inside the container.
-            LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
-            setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
-            logicalTop = logicalHeight();
-        } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
-            || (!marginInfo.canCollapseMarginBeforeWithChildren()
-            && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
-            // We're collapsing with a previous sibling's margins and not
-            // with the top of the block.
-            setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
-            logicalTop = logicalHeight();
-        }
-
-        marginInfo.setDiscardMargin(childDiscardMarginAfter);
-
-        if (!marginInfo.discardMargin()) {
-            marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
-            marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
-        } else
-            marginInfo.clearMargin();
-
-        if (marginInfo.margin())
-            marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
-    }
-
-    // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
-    // collapsed into the page edge.
-    LayoutState* layoutState = view()->layoutState();
-    if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
-        && hasNextPage(beforeCollapseLogicalTop)) {
-        LayoutUnit oldLogicalTop = logicalTop;
-        logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
-        setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
-    }
-
-    // If we have collapsed into a previous sibling and so reduced the height of the parent, ensure any floats that now
-    // overhang from the previous sibling are added to our parent. If the child's previous sibling itself is a float the child will avoid
-    // or clear it anyway, so don't worry about any floating children it may contain.
-    LayoutUnit oldLogicalHeight = logicalHeight();
-    setLogicalHeight(logicalTop);
-    RenderObject* prev = child->previousSibling();
-    if (prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
-        RenderBlock* block = toRenderBlock(prev);
-        if (block->containsFloats() && !block->avoidsFloats() && (block->logicalTop() + block->lowestFloatLogicalBottom()) > logicalTop)
-            addOverhangingFloats(block, false);
-    }
-    setLogicalHeight(oldLogicalHeight);
-
-    return logicalTop;
-}
-
-LayoutUnit RenderBlock::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
-{
-    LayoutUnit heightIncrease = getClearDelta(child, yPos);
-    if (!heightIncrease)
-        return yPos;
-
-    if (child->isSelfCollapsingBlock()) {
-        bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
-
-        // For self-collapsing blocks that clear, they can still collapse their
-        // margins with following siblings.  Reset the current margins to represent
-        // the self-collapsing block's margins only.
-        // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
-        if (!childDiscardMargin) {
-            MarginValues childMargins = marginValuesForChild(child);
-            marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
-            marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
-        } else
-            marginInfo.clearMargin();
-        marginInfo.setDiscardMargin(childDiscardMargin);
-
-        // CSS2.1 states:
-        // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
-        // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
-        // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
-        // for a block with height - if none is found then don't allow the margins to collapse with the parent.
-        bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
-        for (RenderBox* curr = child->nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
-            if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
-                wouldCollapseMarginsWithParent = false;
-        }
-        if (wouldCollapseMarginsWithParent)
-            marginInfo.setCanCollapseMarginAfterWithChildren(false);
-
-        // CSS2.1: "the amount of clearance is set so that clearance + margin-top = [height of float], i.e., clearance = [height of float] - margin-top"
-        // Move the top of the child box to the bottom of the float ignoring the child's top margin.
-        LayoutUnit collapsedMargin = collapsedMarginBeforeForChild(child);
-        setLogicalHeight(child->logicalTop() - collapsedMargin);
-        // A negative collapsed margin-top value cancels itself out as it has already been factored into |yPos| above.
-        heightIncrease -= max(LayoutUnit(), collapsedMargin);
-    } else
-        // Increase our height by the amount we had to clear.
-        setLogicalHeight(logicalHeight() + heightIncrease);
-
-    if (marginInfo.canCollapseWithMarginBefore()) {
-        // We can no longer collapse with the top of the block since a clear
-        // occurred.  The empty blocks collapse into the cleared block.
-        // FIXME: This isn't quite correct.  Need clarification for what to do
-        // if the height the cleared block is offset by is smaller than the
-        // margins involved.
-        setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
-        marginInfo.setAtBeforeSideOfBlock(false);
-
-        // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
-        setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
-    }
-
-    LayoutUnit logicalTop = yPos + heightIncrease;
-    // After margin collapsing, one of our floats may now intrude into the child. If the child doesn't contain floats of its own it
-    // won't get picked up for relayout even though the logical top estimate was wrong - so add the newly intruding float now.
-    if (containsFloats() && child->isRenderBlock() && !toRenderBlock(child)->containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
-        toRenderBlock(child)->addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
-
-    return logicalTop;
-}
-
-void RenderBlock::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
-{
-    // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
-    // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
-    // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
-    if ((document().inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
-        return;
-
-    // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
-    // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
-    if (child->style()->marginBeforeCollapse() == MDISCARD) {
-        positiveMarginBefore = 0;
-        negativeMarginBefore = 0;
-        discardMarginBefore = true;
-        return;
-    }
-
-    LayoutUnit beforeChildMargin = marginBeforeForChild(child);
-    positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
-    negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
-
-    if (!child->isRenderBlock())
-        return;
-
-    RenderBlock* childBlock = toRenderBlock(child);
-    if (childBlock->childrenInline() || childBlock->isWritingModeRoot())
-        return;
-
-    MarginInfo childMarginInfo(childBlock, childBlock->borderBefore() + childBlock->paddingBefore(), childBlock->borderAfter() + childBlock->paddingAfter());
-    if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
-        return;
-
-    RenderBox* grandchildBox = childBlock->firstChildBox();
-    for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
-        if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
-            break;
-    }
-
-    // Give up if there is clearance on the box, since it probably won't collapse into us.
-    if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
-        return;
-
-    // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
-    if (grandchildBox->needsLayout()) {
-        grandchildBox->computeAndSetBlockDirectionMargins(this);
-        if (grandchildBox->isRenderBlock()) {
-            RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
-            grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style()->hasMarginBeforeQuirk());
-            grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style()->hasMarginAfterQuirk());
-        }
-    }
-
-    // Collapse the margin of the grandchild box with our own to produce an estimate.
-    childBlock->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
-}
-
-LayoutUnit RenderBlock::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
-{
-    // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
-    // relayout if there are intruding floats.
-    LayoutUnit logicalTopEstimate = logicalHeight();
-    if (!marginInfo.canCollapseWithMarginBefore()) {
-        LayoutUnit positiveMarginBefore = 0;
-        LayoutUnit negativeMarginBefore = 0;
-        bool discardMarginBefore = false;
-        if (child->selfNeedsLayout()) {
-            // Try to do a basic estimation of how the collapse is going to go.
-            marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
-        } else {
-            // Use the cached collapsed margin values from a previous layout. Most of the time they
-            // will be right.
-            MarginValues marginValues = marginValuesForChild(child);
-            positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
-            negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
-            discardMarginBefore = mustDiscardMarginBeforeForChild(child);
-        }
-
-        // Collapse the result with our current margins.
-        if (!discardMarginBefore)
-            logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
-    }
-
-    // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
-    // page.
-    LayoutState* layoutState = view()->layoutState();
-    if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
-        && hasNextPage(logicalHeight()))
-        logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
-
-    logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
-
-    estimateWithoutPagination = logicalTopEstimate;
-
-    if (layoutState->isPaginated()) {
-        // If the object has a page or column break value of "before", then we should shift to the top of the next page.
-        logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
-
-        // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
-        logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
-
-        if (!child->selfNeedsLayout() && child->isRenderBlock())
-            logicalTopEstimate += toRenderBlock(child)->paginationStrut();
-    }
-
-    return logicalTopEstimate;
-}
-
 LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* region)
 {
     LayoutUnit startPosition = startOffsetForContent(region);
@@ -2212,51 +1805,6 @@
     setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
 }
 
-void RenderBlock::setCollapsedBottomMargin(const MarginInfo& marginInfo)
-{
-    if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
-        // Update the after side margin of the container to discard if the after margin of the last child also discards and we collapse with it.
-        // Don't update the max margin values because we won't need them anyway.
-        if (marginInfo.discardMargin()) {
-            setMustDiscardMarginAfter();
-            return;
-        }
-
-        // Update our max pos/neg bottom margins, since we collapsed our bottom margins
-        // with our children.
-        setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
-
-        if (!marginInfo.hasMarginAfterQuirk())
-            setHasMarginAfterQuirk(false);
-
-        if (marginInfo.hasMarginAfterQuirk() && !marginAfter())
-            // We have no bottom margin and our last child has a quirky margin.
-            // We will pick up this quirky margin and pass it through.
-            // This deals with the <td><div><p> case.
-            setHasMarginAfterQuirk(true);
-    }
-}
-
-void RenderBlock::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
-{
-    marginInfo.setAtAfterSideOfBlock(true);
-
-    // If we can't collapse with children then go ahead and add in the bottom margin.
-    if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
-        && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
-        setLogicalHeight(logicalHeight() + marginInfo.margin());
-
-    // Now add in our bottom border/padding.
-    setLogicalHeight(logicalHeight() + afterSide);
-
-    // Negative margins can cause our height to shrink below our minimal height (border/padding).
-    // If this happens, ensure that the computed height is increased to the minimal height.
-    setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
-
-    // Update our bottom collapsed margin info.
-    setCollapsedBottomMargin(marginInfo);
-}
-
 void RenderBlock::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
 {
     if (isHorizontalWritingMode()) {
@@ -2295,153 +1843,6 @@
         child->setPreferredLogicalWidthsDirty(MarkOnlyThis);
 }
 
-void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
-{
-    LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
-    LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
-
-    // The child is a normal flow object.  Compute the margins we will use for collapsing now.
-    child->computeAndSetBlockDirectionMargins(this);
-
-    // Try to guess our correct logical top position.  In most cases this guess will
-    // be correct.  Only if we're wrong (when we compute the real logical top position)
-    // will we have to potentially relayout.
-    LayoutUnit estimateWithoutPagination;
-    LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
-
-    // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
-    LayoutRect oldRect = child->frameRect();
-    LayoutUnit oldLogicalTop = logicalTopForChild(child);
-
-#if !ASSERT_DISABLED
-    LayoutSize oldLayoutDelta = view()->layoutDelta();
-#endif
-    // Go ahead and position the child as though it didn't collapse with the top.
-    setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
-
-    RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
-    bool markDescendantsWithFloats = false;
-    if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats())
-        markDescendantsWithFloats = true;
-    else if (UNLIKELY(logicalTopEstimate.mightBeSaturated()))
-        // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
-        // very large elements. If it does the comparison with oldLogicalTop might yield a
-        // false negative as adding and removing margins, borders etc from a saturated number
-        // might yield incorrect results. If this is the case always mark for layout.
-        markDescendantsWithFloats = true;
-    else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
-        // If an element might be affected by the presence of floats, then always mark it for
-        // layout.
-        LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
-        if (fb > logicalTopEstimate)
-            markDescendantsWithFloats = true;
-    }
-
-    if (childRenderBlock) {
-        if (markDescendantsWithFloats)
-            childRenderBlock->markAllDescendantsWithFloatsForLayout();
-        if (!child->isWritingModeRoot())
-            previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
-    }
-
-    SubtreeLayoutScope layoutScope(child);
-    if (!child->needsLayout())
-        child->markForPaginationRelayoutIfNeeded(layoutScope);
-
-    bool childHadLayout = child->everHadLayout();
-    bool childNeededLayout = child->needsLayout();
-    if (childNeededLayout)
-        child->layout();
-
-    if (frameView()->partialLayout().isStopping())
-        return;
-
-    // Cache if we are at the top of the block right now.
-    bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
-
-    // Now determine the correct ypos based off examination of collapsing margin
-    // values.
-    LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
-
-    // Now check for clear.
-    LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
-
-    bool paginated = view()->layoutState()->isPaginated();
-    if (paginated)
-        logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
-            atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
-
-    setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
-
-    // Now we have a final top position.  See if it really does end up being different from our estimate.
-    // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
-    // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
-    if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlock && childRenderBlock->shouldBreakAtLineToAvoidWidow())) {
-        SubtreeLayoutScope layoutScope(child);
-        if (child->shrinkToAvoidFloats()) {
-            // The child's width depends on the line width.
-            // When the child shifts to clear an item, its width can
-            // change (because it has more available line width).
-            // So go ahead and mark the item as dirty.
-            layoutScope.setChildNeedsLayout(child);
-        }
-
-        if (childRenderBlock) {
-            if (!child->avoidsFloats() && childRenderBlock->containsFloats())
-                childRenderBlock->markAllDescendantsWithFloatsForLayout();
-            if (!child->needsLayout())
-                child->markForPaginationRelayoutIfNeeded(layoutScope);
-        }
-
-        // Our guess was wrong. Make the child lay itself out again.
-        child->layoutIfNeeded();
-    }
-
-    // We are no longer at the top of the block if we encounter a non-empty child.
-    // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
-    if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
-        marginInfo.setAtBeforeSideOfBlock(false);
-
-    // Now place the child in the correct left position
-    determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
-
-    // Update our height now that the child has been placed in the correct position.
-    setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
-    if (mustSeparateMarginAfterForChild(child)) {
-        setLogicalHeight(logicalHeight() + marginAfterForChild(child));
-        marginInfo.clearMargin();
-    }
-    // If the child has overhanging floats that intrude into following siblings (or possibly out
-    // of this block), then the parent gets notified of the floats now.
-    if (childRenderBlock && childRenderBlock->containsFloats())
-        maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
-
-    LayoutSize childOffset = child->location() - oldRect.location();
-    if (childOffset.width() || childOffset.height()) {
-        view()->addLayoutDelta(childOffset);
-
-        // If the child moved, we have to repaint it as well as any floating/positioned
-        // descendants.  An exception is if we need a layout.  In this case, we know we're going to
-        // repaint ourselves (and the child) anyway.
-        if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
-            child->repaintDuringLayoutIfMoved(oldRect);
-    }
-
-    if (!childHadLayout && child->checkForRepaintDuringLayout()) {
-        child->repaint();
-        child->repaintOverhangingFloats(true);
-    }
-
-    if (paginated) {
-        // Check for an after page/column break.
-        LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
-        if (newHeight != height())
-            setLogicalHeight(newHeight);
-    }
-
-    ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
-}
-
 void RenderBlock::simplifiedNormalFlowLayout()
 {
     if (childrenInline()) {
@@ -3684,7 +3085,6 @@
     if (!m_floatingObjects)
         return;
 
-    deleteAllValues(m_floatingObjects->set());
     m_floatingObjects->clear();
 }
 
@@ -3705,7 +3105,7 @@
 
     // Create the special object entry & append it to the list
 
-    FloatingObject* newObj = new FloatingObject(o->style()->floating());
+    OwnPtr<FloatingObject> newObj = FloatingObject::create(o);
 
     // Our location is irrelevant if we're unsplittable or no pagination is in effect.
     // Just go ahead and lay out the float.
@@ -3726,13 +3126,7 @@
     if (ShapeOutsideInfo* shapeOutside = o->shapeOutsideInfo())
         shapeOutside->setShapeSize(logicalWidthForChild(o), logicalHeightForChild(o));
 
-    newObj->setShouldPaint(!o->hasSelfPaintingLayer()); // If a layer exists, the float will paint itself. Otherwise someone else will.
-    newObj->setIsDescendant(true);
-    newObj->setRenderer(o);
-
-    m_floatingObjects->add(newObj);
-
-    return newObj;
+    return m_floatingObjects->add(newObj.release());
 }
 
 void RenderBlock::removeFloatingObject(RenderBox* o)
@@ -3767,8 +3161,6 @@
                 markLinesDirtyInBlockRange(0, logicalBottom);
             }
             m_floatingObjects->remove(r);
-            ASSERT(!r->originatingLine());
-            delete r;
         }
     }
 }
@@ -3782,8 +3174,6 @@
     FloatingObject* curr = floatingObjectSet.last();
     while (curr != lastFloat && (!curr->isPlaced() || curr->logicalTop(isHorizontalWritingMode()) >= logicalOffset)) {
         m_floatingObjects->remove(curr);
-        ASSERT(!curr->originatingLine());
-        delete curr;
         if (floatingObjectSet.isEmpty())
             break;
         curr = floatingObjectSet.last();
@@ -4211,15 +3601,8 @@
 {
     if (!m_floatingObjects)
         return 0;
-    LayoutUnit lowestFloatBottom = 0;
-    const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-    FloatingObjectSetIterator end = floatingObjectSet.end();
-    for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-        FloatingObject* r = *it;
-        if (r->isPlaced() && r->type() & floatType)
-            lowestFloatBottom = max(lowestFloatBottom, r->logicalBottom(isHorizontalWritingMode()));
-    }
-    return lowestFloatBottom;
+
+    return m_floatingObjects->lowestFloatLogicalBottom(floatType);
 }
 
 void RenderBlock::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
@@ -4263,24 +3646,21 @@
             // If the object is not in the list, we add it now.
             if (!containsFloat(r->renderer())) {
                 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
-                FloatingObject* floatingObj = new FloatingObject(r->type(), LayoutRect(r->frameRect().location() - offset, r->frameRect().size()));
-                floatingObj->setRenderer(r->renderer());
+                bool shouldPaint = false;
 
                 // The nearest enclosing layer always paints the float (so that zindex and stacking
                 // behaves properly).  We always want to propagate the desire to paint the float as
                 // far out as we can, to the outermost block that overlaps the float, stopping only
                 // if we hit a self-painting layer boundary.
-                if (r->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer())
+                if (r->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
                     r->setShouldPaint(false);
-                else
-                    floatingObj->setShouldPaint(false);
-
-                floatingObj->setIsDescendant(true);
-
+                    shouldPaint = true;
+                }
                 // We create the floating object list lazily.
                 if (!m_floatingObjects)
                     createFloatingObjects();
-                m_floatingObjects->add(floatingObj);
+
+                m_floatingObjects->add(r->copyToNewContainer(offset, shouldPaint, true));
             }
         } else {
             if (makeChildPaintOtherFloats && !r->shouldPaint() && !r->renderer()->hasSelfPaintingLayer()
@@ -4331,28 +3711,20 @@
         FloatingObject* r = *prevIt;
         if (r->logicalBottom(isHorizontalWritingMode()) > logicalTopOffset) {
             if (!m_floatingObjects || !m_floatingObjects->set().contains(r)) {
-                LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, logicalTopOffset) : LayoutSize(logicalTopOffset, logicalLeftOffset);
-                FloatingObject* floatingObj = new FloatingObject(r->type(), LayoutRect(r->frameRect().location() - offset, r->frameRect().size()));
+                // We create the floating object list lazily.
+                if (!m_floatingObjects)
+                    createFloatingObjects();
 
                 // Applying the child's margin makes no sense in the case where the child was passed in.
                 // since this margin was added already through the modification of the |logicalLeftOffset| variable
                 // above.  |logicalLeftOffset| will equal the margin in this case, so it's already been taken
                 // into account.  Only apply this code if prev is the parent, since otherwise the left margin
                 // will get applied twice.
-                if (prev != parent()) {
-                    if (isHorizontalWritingMode())
-                        floatingObj->setX(floatingObj->x() + prev->marginLeft());
-                    else
-                        floatingObj->setY(floatingObj->y() + prev->marginTop());
-                }
+                LayoutSize offset = isHorizontalWritingMode()
+                    ? LayoutSize(logicalLeftOffset - (prev != parent() ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
+                    : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != parent() ? prev->marginTop() : LayoutUnit()));
 
-                floatingObj->setShouldPaint(false); // We are not in the direct inheritance chain for this float. We will never paint it.
-                floatingObj->setRenderer(r->renderer());
-
-                // We create the floating object list lazily.
-                if (!m_floatingObjects)
-                    createFloatingObjects();
-                m_floatingObjects->add(floatingObj);
+                m_floatingObjects->add(r->copyToNewContainer(offset));
             }
         }
     }
@@ -6018,7 +5390,7 @@
     if (isReplaced() && linePositionMode == PositionOnContainingLine)
         return RenderBox::lineHeight(firstLine, direction, linePositionMode);
 
-    if (firstLine && document().styleSheetCollections()->usesFirstLineRules()) {
+    if (firstLine && document().styleEngine()->usesFirstLineRules()) {
         RenderStyle* s = style(firstLine);
         if (s != style())
             return s->computedLineHeight(view());
@@ -6357,7 +5729,7 @@
 
 void RenderBlock::updateFirstLetter()
 {
-    if (!document().styleSheetCollections()->usesFirstLetterRules())
+    if (!document().styleEngine()->usesFirstLetterRules())
         return;
     // Don't recur
     if (style()->styleType() == FIRST_LETTER)
@@ -6518,8 +5890,7 @@
                 if (box->lastChild())
                     right = max(right, x + static_cast<LayoutUnit>(ceilf(box->lastChild()->logicalRight())));
             }
-        }
-        else {
+        } else {
             for (RenderBox* obj = firstChildBox(); obj; obj = obj->nextSiblingBox()) {
                 if (!obj->isFloatingOrOutOfFlowPositioned()) {
                     if (obj->isRenderBlockFlow() && !obj->hasOverflowClip())
@@ -6592,127 +5963,12 @@
     }
 }
 
-void RenderBlock::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
-{
-    if (!m_rareData) {
-        if (pos == RenderBlockRareData::positiveMarginBeforeDefault(this) && neg == RenderBlockRareData::negativeMarginBeforeDefault(this))
-            return;
-        m_rareData = adoptPtr(new RenderBlockRareData(this));
-    }
-    m_rareData->m_margins.setPositiveMarginBefore(pos);
-    m_rareData->m_margins.setNegativeMarginBefore(neg);
-}
-
-void RenderBlock::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
-{
-    if (!m_rareData) {
-        if (pos == RenderBlockRareData::positiveMarginAfterDefault(this) && neg == RenderBlockRareData::negativeMarginAfterDefault(this))
-            return;
-        m_rareData = adoptPtr(new RenderBlockRareData(this));
-    }
-    m_rareData->m_margins.setPositiveMarginAfter(pos);
-    m_rareData->m_margins.setNegativeMarginAfter(neg);
-}
-
-void RenderBlock::setMustDiscardMarginBefore(bool value)
-{
-    if (style()->marginBeforeCollapse() == MDISCARD) {
-        ASSERT(value);
-        return;
-    }
-
-    if (!m_rareData && !value)
-        return;
-
-    if (!m_rareData)
-        m_rareData = adoptPtr(new RenderBlockRareData(this));
-
-    m_rareData->m_discardMarginBefore = value;
-}
-
-void RenderBlock::setMustDiscardMarginAfter(bool value)
-{
-    if (style()->marginAfterCollapse() == MDISCARD) {
-        ASSERT(value);
-        return;
-    }
-
-    if (!m_rareData && !value)
-        return;
-
-    if (!m_rareData)
-        m_rareData = adoptPtr(new RenderBlockRareData(this));
-
-    m_rareData->m_discardMarginAfter = value;
-}
-
-bool RenderBlock::mustDiscardMarginBefore() const
-{
-    return style()->marginBeforeCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginBefore);
-}
-
-bool RenderBlock::mustDiscardMarginAfter() const
-{
-    return style()->marginAfterCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginAfter);
-}
-
-bool RenderBlock::mustDiscardMarginBeforeForChild(const RenderBox* child) const
-{
-    ASSERT(!child->selfNeedsLayout());
-    if (!child->isWritingModeRoot())
-        return child->isRenderBlock() ? toRenderBlock(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
-    if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
-        return child->isRenderBlock() ? toRenderBlock(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
-
-    // FIXME: We return false here because the implementation is not geometrically complete. We have values only for before/after, not start/end.
-    // In case the boxes are perpendicular we assume the property is not specified.
-    return false;
-}
-
-bool RenderBlock::mustDiscardMarginAfterForChild(const RenderBox* child) const
-{
-    ASSERT(!child->selfNeedsLayout());
-    if (!child->isWritingModeRoot())
-        return child->isRenderBlock() ? toRenderBlock(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
-    if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
-        return child->isRenderBlock() ? toRenderBlock(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
-
-    // FIXME: See |mustDiscardMarginBeforeForChild| above.
-    return false;
-}
-
-bool RenderBlock::mustSeparateMarginBeforeForChild(const RenderBox* child) const
-{
-    ASSERT(!child->selfNeedsLayout());
-    const RenderStyle* childStyle = child->style();
-    if (!child->isWritingModeRoot())
-        return childStyle->marginBeforeCollapse() == MSEPARATE;
-    if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
-        return childStyle->marginAfterCollapse() == MSEPARATE;
-
-    // FIXME: See |mustDiscardMarginBeforeForChild| above.
-    return false;
-}
-
-bool RenderBlock::mustSeparateMarginAfterForChild(const RenderBox* child) const
-{
-    ASSERT(!child->selfNeedsLayout());
-    const RenderStyle* childStyle = child->style();
-    if (!child->isWritingModeRoot())
-        return childStyle->marginAfterCollapse() == MSEPARATE;
-    if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
-        return childStyle->marginBeforeCollapse() == MSEPARATE;
-
-    // FIXME: See |mustDiscardMarginBeforeForChild| above.
-    return false;
-}
-
 void RenderBlock::setPaginationStrut(LayoutUnit strut)
 {
     if (!m_rareData) {
         if (!strut)
             return;
-        m_rareData = adoptPtr(new RenderBlockRareData(this));
+        m_rareData = adoptPtr(new RenderBlockRareData());
     }
     m_rareData->m_paginationStrut = strut;
 }
@@ -6722,7 +5978,7 @@
     if (!m_rareData) {
         if (!logicalOffset)
             return;
-        m_rareData = adoptPtr(new RenderBlockRareData(this));
+        m_rareData = adoptPtr(new RenderBlockRareData());
     }
     m_rareData->m_pageLogicalOffset = logicalOffset;
 }
@@ -6731,7 +5987,7 @@
 {
     ASSERT(lineToBreak);
     if (!m_rareData)
-        m_rareData = adoptPtr(new RenderBlockRareData(this));
+        m_rareData = adoptPtr(new RenderBlockRareData());
     m_rareData->m_shouldBreakAtLineToAvoidWidow = true;
     m_rareData->m_lineBreakToAvoidWidow = lineToBreak;
 }
@@ -6956,74 +6212,11 @@
     return logicalOffset + remainingLogicalHeight;
 }
 
-static bool inNormalFlow(RenderBox* child)
-{
-    RenderBlock* curr = child->containingBlock();
-    RenderView* renderView = child->view();
-    while (curr && curr != renderView) {
-        if (curr->hasColumns() || curr->isRenderFlowThread())
-            return true;
-        if (curr->isFloatingOrOutOfFlowPositioned())
-            return false;
-        curr = curr->containingBlock();
-    }
-    return true;
-}
-
 ColumnInfo::PaginationUnit RenderBlock::paginationUnit() const
 {
     return ColumnInfo::Column;
 }
 
-LayoutUnit RenderBlock::applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset)
-{
-    // FIXME: Add page break checking here when we support printing.
-    bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
-    bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
-    bool checkBeforeAlways = (checkColumnBreaks && child->style()->columnBreakBefore() == PBALWAYS) || (checkPageBreaks && child->style()->pageBreakBefore() == PBALWAYS)
-                             || (checkRegionBreaks && child->style()->regionBreakBefore() == PBALWAYS);
-    if (checkBeforeAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
-        if (checkColumnBreaks)
-            view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
-        if (checkRegionBreaks) {
-            LayoutUnit offsetBreakAdjustment = 0;
-            if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset, child, true, &offsetBreakAdjustment))
-                return logicalOffset + offsetBreakAdjustment;
-        }
-        return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
-    }
-    return logicalOffset;
-}
-
-LayoutUnit RenderBlock::applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
-{
-    // FIXME: Add page break checking here when we support printing.
-    bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
-    bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
-    bool checkAfterAlways = (checkColumnBreaks && child->style()->columnBreakAfter() == PBALWAYS) || (checkPageBreaks && child->style()->pageBreakAfter() == PBALWAYS)
-                            || (checkRegionBreaks && child->style()->regionBreakAfter() == PBALWAYS);
-    if (checkAfterAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
-        LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
-
-        // So our margin doesn't participate in the next collapsing steps.
-        marginInfo.clearMargin();
-
-        if (checkColumnBreaks)
-            view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
-        if (checkRegionBreaks) {
-            LayoutUnit offsetBreakAdjustment = 0;
-            if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, child, false, &offsetBreakAdjustment))
-                return logicalOffset + marginOffset + offsetBreakAdjustment;
-        }
-        return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
-    }
-    return logicalOffset;
-}
-
 LayoutUnit RenderBlock::pageLogicalTopForOffset(LayoutUnit offset) const
 {
     RenderView* renderView = view();
@@ -7207,89 +6400,6 @@
         lineBox->setIsFirstAfterPageBreak(true);
 }
 
-LayoutUnit RenderBlock::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock)
-{
-    RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
-
-    if (estimateWithoutPagination != logicalTopAfterClear) {
-        // Our guess prior to pagination movement was wrong. Before we attempt to paginate, let's try again at the new
-        // position.
-        setLogicalHeight(logicalTopAfterClear);
-        setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
-
-        if (child->shrinkToAvoidFloats()) {
-            // The child's width depends on the line width.
-            // When the child shifts to clear an item, its width can
-            // change (because it has more available line width).
-            // So go ahead and mark the item as dirty.
-            child->setChildNeedsLayout(MarkOnlyThis);
-        }
-
-        SubtreeLayoutScope layoutScope(child);
-
-        if (childRenderBlock) {
-            if (!child->avoidsFloats() && childRenderBlock->containsFloats())
-                childRenderBlock->markAllDescendantsWithFloatsForLayout();
-            if (!child->needsLayout())
-                child->markForPaginationRelayoutIfNeeded(layoutScope);
-        }
-
-        // Our guess was wrong. Make the child lay itself out again.
-        child->layoutIfNeeded();
-    }
-
-    LayoutUnit oldTop = logicalTopAfterClear;
-
-    // If the object has a page or column break value of "before", then we should shift to the top of the next page.
-    LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
-
-    if (pageLogicalHeightForOffset(result)) {
-        LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(result, ExcludePageBoundary);
-        LayoutUnit spaceShortage = child->logicalHeight() - remainingLogicalHeight;
-        if (spaceShortage > 0) {
-            // If the child crosses a column boundary, report a break, in case nothing inside it has already
-            // done so. The column balancer needs to know how much it has to stretch the columns to make more
-            // content fit. If no breaks are reported (but do occur), the balancer will have no clue. FIXME:
-            // This should be improved, though, because here we just pretend that the child is
-            // unsplittable. A splittable child, on the other hand, has break opportunities at every position
-            // where there's no child content, border or padding. In other words, we risk stretching more
-            // than necessary.
-            setPageBreak(result, spaceShortage);
-        }
-    }
-
-    // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
-    LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
-    LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
-
-    LayoutUnit paginationStrut = 0;
-    LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
-    if (unsplittableAdjustmentDelta)
-        paginationStrut = unsplittableAdjustmentDelta;
-    else if (childRenderBlock && childRenderBlock->paginationStrut())
-        paginationStrut = childRenderBlock->paginationStrut();
-
-    if (paginationStrut) {
-        // We are willing to propagate out to our parent block as long as we were at the top of the block prior
-        // to collapsing our margins, and as long as we didn't clear or move as a result of other pagination.
-        if (atBeforeSideOfBlock && oldTop == result && !isOutOfFlowPositioned() && !isTableCell()) {
-            // FIXME: Should really check if we're exceeding the page height before propagating the strut, but we don't
-            // have all the information to do so (the strut only has the remaining amount to push). Gecko gets this wrong too
-            // and pushes to the next page anyway, so not too concerned about it.
-            setPaginationStrut(result + paginationStrut);
-            if (childRenderBlock)
-                childRenderBlock->setPaginationStrut(0);
-        } else
-            result += paginationStrut;
-    }
-
-    // Similar to how we apply clearance. Go ahead and boost height() to be the place where we're going to position the child.
-    setLogicalHeight(logicalHeight() + (result - oldTop));
-
-    // Return the final adjusted logical top.
-    return result;
-}
-
 bool RenderBlock::lineWidthForPaginatedLineChanged(RootInlineBox* rootBox, LayoutUnit lineDelta, RenderFlowThread* flowThread) const
 {
     if (!flowThread)
@@ -7449,66 +6559,6 @@
     return false;
 }
 
-RenderBlock::MarginValues RenderBlock::marginValuesForChild(RenderBox* child) const
-{
-    LayoutUnit childBeforePositive = 0;
-    LayoutUnit childBeforeNegative = 0;
-    LayoutUnit childAfterPositive = 0;
-    LayoutUnit childAfterNegative = 0;
-
-    LayoutUnit beforeMargin = 0;
-    LayoutUnit afterMargin = 0;
-
-    RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
-
-    // If the child has the same directionality as we do, then we can just return its
-    // margins in the same direction.
-    if (!child->isWritingModeRoot()) {
-        if (childRenderBlock) {
-            childBeforePositive = childRenderBlock->maxPositiveMarginBefore();
-            childBeforeNegative = childRenderBlock->maxNegativeMarginBefore();
-            childAfterPositive = childRenderBlock->maxPositiveMarginAfter();
-            childAfterNegative = childRenderBlock->maxNegativeMarginAfter();
-        } else {
-            beforeMargin = child->marginBefore();
-            afterMargin = child->marginAfter();
-        }
-    } else if (child->isHorizontalWritingMode() == isHorizontalWritingMode()) {
-        // The child has a different directionality.  If the child is parallel, then it's just
-        // flipped relative to us.  We can use the margins for the opposite edges.
-        if (childRenderBlock) {
-            childBeforePositive = childRenderBlock->maxPositiveMarginAfter();
-            childBeforeNegative = childRenderBlock->maxNegativeMarginAfter();
-            childAfterPositive = childRenderBlock->maxPositiveMarginBefore();
-            childAfterNegative = childRenderBlock->maxNegativeMarginBefore();
-        } else {
-            beforeMargin = child->marginAfter();
-            afterMargin = child->marginBefore();
-        }
-    } else {
-        // The child is perpendicular to us, which means its margins don't collapse but are on the
-        // "logical left/right" sides of the child box.  We can just return the raw margin in this case.
-        beforeMargin = marginBeforeForChild(child);
-        afterMargin = marginAfterForChild(child);
-    }
-
-    // Resolve uncollapsing margins into their positive/negative buckets.
-    if (beforeMargin) {
-        if (beforeMargin > 0)
-            childBeforePositive = beforeMargin;
-        else
-            childBeforeNegative = -beforeMargin;
-    }
-    if (afterMargin) {
-        if (afterMargin > 0)
-            childAfterPositive = afterMargin;
-        else
-            childAfterNegative = -afterMargin;
-    }
-
-    return MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
-}
-
 const char* RenderBlock::renderName() const
 {
     if (isBody())
diff --git a/Source/core/rendering/RenderBlock.h b/Source/core/rendering/RenderBlock.h
index 40c890f..40f38d5 100644
--- a/Source/core/rendering/RenderBlock.h
+++ b/Source/core/rendering/RenderBlock.h
@@ -326,7 +326,7 @@
     void setLineGridBox(RootInlineBox* box)
     {
         if (!m_rareData)
-            m_rareData = adoptPtr(new RenderBlockRareData(this));
+            m_rareData = adoptPtr(new RenderBlockRareData());
         if (m_rareData->m_lineGridBox)
             m_rareData->m_lineGridBox->destroy();
         m_rareData->m_lineGridBox = box;
@@ -355,33 +355,6 @@
 
     virtual void updateFirstLetter();
 
-    class MarginValues {
-    public:
-        MarginValues(LayoutUnit beforePos, LayoutUnit beforeNeg, LayoutUnit afterPos, LayoutUnit afterNeg)
-            : m_positiveMarginBefore(beforePos)
-            , m_negativeMarginBefore(beforeNeg)
-            , m_positiveMarginAfter(afterPos)
-            , m_negativeMarginAfter(afterNeg)
-        { }
-
-        LayoutUnit positiveMarginBefore() const { return m_positiveMarginBefore; }
-        LayoutUnit negativeMarginBefore() const { return m_negativeMarginBefore; }
-        LayoutUnit positiveMarginAfter() const { return m_positiveMarginAfter; }
-        LayoutUnit negativeMarginAfter() const { return m_negativeMarginAfter; }
-
-        void setPositiveMarginBefore(LayoutUnit pos) { m_positiveMarginBefore = pos; }
-        void setNegativeMarginBefore(LayoutUnit neg) { m_negativeMarginBefore = neg; }
-        void setPositiveMarginAfter(LayoutUnit pos) { m_positiveMarginAfter = pos; }
-        void setNegativeMarginAfter(LayoutUnit neg) { m_negativeMarginAfter = neg; }
-
-    private:
-        LayoutUnit m_positiveMarginBefore;
-        LayoutUnit m_negativeMarginBefore;
-        LayoutUnit m_positiveMarginAfter;
-        LayoutUnit m_negativeMarginAfter;
-    };
-    MarginValues marginValuesForChild(RenderBox* child) const;
-
     virtual void scrollbarsChanged(bool /*horizontalScrollbarChanged*/, bool /*verticalScrollbarChanged*/) { };
 
     LayoutUnit logicalLeftOffsetForContent(RenderRegion*) const;
@@ -448,7 +421,7 @@
     void setShapeInsideInfo(PassOwnPtr<ShapeInsideInfo> value)
     {
         if (!m_rareData)
-            m_rareData = adoptPtr(new RenderBlockRareData(this));
+            m_rareData = adoptPtr(new RenderBlockRareData());
         m_rareData->m_shapeInsideInfo = value;
     }
     ShapeInsideInfo* layoutShapeInsideInfo() const;
@@ -464,38 +437,6 @@
 
     void dirtyForLayoutFromPercentageHeightDescendants(SubtreeLayoutScope&);
 
-    LayoutUnit maxPositiveMarginBefore() const { return m_rareData ? m_rareData->m_margins.positiveMarginBefore() : RenderBlockRareData::positiveMarginBeforeDefault(this); }
-    LayoutUnit maxNegativeMarginBefore() const { return m_rareData ? m_rareData->m_margins.negativeMarginBefore() : RenderBlockRareData::negativeMarginBeforeDefault(this); }
-    LayoutUnit maxPositiveMarginAfter() const { return m_rareData ? m_rareData->m_margins.positiveMarginAfter() : RenderBlockRareData::positiveMarginAfterDefault(this); }
-    LayoutUnit maxNegativeMarginAfter() const { return m_rareData ? m_rareData->m_margins.negativeMarginAfter() : RenderBlockRareData::negativeMarginAfterDefault(this); }
-
-    void setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg);
-    void setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg);
-
-    void setMustDiscardMarginBefore(bool = true);
-    void setMustDiscardMarginAfter(bool = true);
-
-    bool mustDiscardMarginBefore() const;
-    bool mustDiscardMarginAfter() const;
-
-    bool mustDiscardMarginBeforeForChild(const RenderBox*) const;
-    bool mustDiscardMarginAfterForChild(const RenderBox*) const;
-
-    bool mustSeparateMarginBeforeForChild(const RenderBox*) const;
-    bool mustSeparateMarginAfterForChild(const RenderBox*) const;
-
-    void initMaxMarginValues()
-    {
-        if (m_rareData) {
-            m_rareData->m_margins = MarginValues(RenderBlockRareData::positiveMarginBeforeDefault(this) , RenderBlockRareData::negativeMarginBeforeDefault(this),
-                                                 RenderBlockRareData::positiveMarginAfterDefault(this), RenderBlockRareData::negativeMarginAfterDefault(this));
-            m_rareData->m_paginationStrut = 0;
-
-            m_rareData->m_discardMarginBefore = false;
-            m_rareData->m_discardMarginAfter = false;
-        }
-    }
-
     virtual void layout();
 
     void layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly = false);
@@ -582,6 +523,8 @@
 
     virtual void checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight);
 
+    virtual bool isInlineBlockOrInlineTable() const OVERRIDE FINAL { return isInline() && isReplaced(); }
+
 private:
     LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const;
     LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const;
@@ -598,7 +541,6 @@
     virtual const char* renderName() const;
 
     virtual bool isRenderBlock() const OVERRIDE FINAL { return true; }
-    virtual bool isInlineBlockOrInlineTable() const OVERRIDE FINAL { return isInline() && isReplaced(); }
 
     void makeChildrenNonInline(RenderObject* insertionPoint = 0);
     virtual void removeLeftoverAnonymousBlock(RenderBlock* child);
@@ -616,9 +558,6 @@
 
     virtual bool isSelfCollapsingBlock() const OVERRIDE FINAL;
 
-    virtual LayoutUnit collapsedMarginBefore() const OVERRIDE FINAL { return maxPositiveMarginBefore() - maxNegativeMarginBefore(); }
-    virtual LayoutUnit collapsedMarginAfter() const OVERRIDE FINAL { return maxPositiveMarginAfter() - maxNegativeMarginAfter(); }
-
     virtual void repaintOverhangingFloats(bool paintAllDescendants) OVERRIDE FINAL;
 
     BidiRun* handleTrailingSpaces(BidiRunList<BidiRun>&, BidiContext*);
@@ -798,99 +737,9 @@
     RenderBlock* containingColumnsBlock(bool allowAnonymousColumnBlock = true);
     RenderBlock* columnsBlockForSpanningElement(RenderObject* newChild);
 
-    class MarginInfo {
-        // Collapsing flags for whether we can collapse our margins with our children's margins.
-        bool m_canCollapseWithChildren : 1;
-        bool m_canCollapseMarginBeforeWithChildren : 1;
-        bool m_canCollapseMarginAfterWithChildren : 1;
-
-        // Whether or not we are a quirky container, i.e., do we collapse away top and bottom
-        // margins in our container.  Table cells and the body are the common examples. We
-        // also have a custom style property for Safari RSS to deal with TypePad blog articles.
-        bool m_quirkContainer : 1;
-
-        // This flag tracks whether we are still looking at child margins that can all collapse together at the beginning of a block.
-        // They may or may not collapse with the top margin of the block (|m_canCollapseTopWithChildren| tells us that), but they will
-        // always be collapsing with one another.  This variable can remain set to true through multiple iterations
-        // as long as we keep encountering self-collapsing blocks.
-        bool m_atBeforeSideOfBlock : 1;
-
-        // This flag is set when we know we're examining bottom margins and we know we're at the bottom of the block.
-        bool m_atAfterSideOfBlock : 1;
-
-        // These variables are used to detect quirky margins that we need to collapse away (in table cells
-        // and in the body element).
-        bool m_hasMarginBeforeQuirk : 1;
-        bool m_hasMarginAfterQuirk : 1;
-        bool m_determinedMarginBeforeQuirk : 1;
-
-        bool m_discardMargin : 1;
-
-        // These flags track the previous maximal positive and negative margins.
-        LayoutUnit m_positiveMargin;
-        LayoutUnit m_negativeMargin;
-
-    public:
-        MarginInfo(RenderBlock*, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding);
-
-        void setAtBeforeSideOfBlock(bool b) { m_atBeforeSideOfBlock = b; }
-        void setAtAfterSideOfBlock(bool b) { m_atAfterSideOfBlock = b; }
-        void clearMargin()
-        {
-            m_positiveMargin = 0;
-            m_negativeMargin = 0;
-        }
-        void setHasMarginBeforeQuirk(bool b) { m_hasMarginBeforeQuirk = b; }
-        void setHasMarginAfterQuirk(bool b) { m_hasMarginAfterQuirk = b; }
-        void setDeterminedMarginBeforeQuirk(bool b) { m_determinedMarginBeforeQuirk = b; }
-        void setPositiveMargin(LayoutUnit p) { ASSERT(!m_discardMargin); m_positiveMargin = p; }
-        void setNegativeMargin(LayoutUnit n) { ASSERT(!m_discardMargin); m_negativeMargin = n; }
-        void setPositiveMarginIfLarger(LayoutUnit p)
-        {
-            ASSERT(!m_discardMargin);
-            if (p > m_positiveMargin)
-                m_positiveMargin = p;
-        }
-        void setNegativeMarginIfLarger(LayoutUnit n)
-        {
-            ASSERT(!m_discardMargin);
-            if (n > m_negativeMargin)
-                m_negativeMargin = n;
-        }
-
-        void setMargin(LayoutUnit p, LayoutUnit n) { ASSERT(!m_discardMargin); m_positiveMargin = p; m_negativeMargin = n; }
-        void setCanCollapseMarginAfterWithChildren(bool collapse) { m_canCollapseMarginAfterWithChildren = collapse; }
-        void setDiscardMargin(bool value) { m_discardMargin = value; }
-
-        bool atBeforeSideOfBlock() const { return m_atBeforeSideOfBlock; }
-        bool canCollapseWithMarginBefore() const { return m_atBeforeSideOfBlock && m_canCollapseMarginBeforeWithChildren; }
-        bool canCollapseWithMarginAfter() const { return m_atAfterSideOfBlock && m_canCollapseMarginAfterWithChildren; }
-        bool canCollapseMarginBeforeWithChildren() const { return m_canCollapseMarginBeforeWithChildren; }
-        bool canCollapseMarginAfterWithChildren() const { return m_canCollapseMarginAfterWithChildren; }
-        bool quirkContainer() const { return m_quirkContainer; }
-        bool determinedMarginBeforeQuirk() const { return m_determinedMarginBeforeQuirk; }
-        bool hasMarginBeforeQuirk() const { return m_hasMarginBeforeQuirk; }
-        bool hasMarginAfterQuirk() const { return m_hasMarginAfterQuirk; }
-        LayoutUnit positiveMargin() const { return m_positiveMargin; }
-        LayoutUnit negativeMargin() const { return m_negativeMargin; }
-        bool discardMargin() const { return m_discardMargin; }
-        LayoutUnit margin() const { return m_positiveMargin - m_negativeMargin; }
-    };
-
-    void layoutBlockChild(RenderBox* child, MarginInfo&, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom);
-    void adjustPositionedBlock(RenderBox* child, const MarginInfo&);
-    void adjustFloatingBlock(const MarginInfo&);
-
     RenderBoxModelObject* createReplacementRunIn(RenderBoxModelObject* runIn);
     void moveRunInUnderSiblingBlockIfNeeded(RenderObject* runIn);
     void moveRunInToOriginalPosition(RenderObject* runIn);
-
-    LayoutUnit collapseMargins(RenderBox* child, MarginInfo&);
-    LayoutUnit clearFloatsIfNeeded(RenderBox* child, MarginInfo&, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos);
-    LayoutUnit estimateLogicalTopPosition(RenderBox* child, const MarginInfo&, LayoutUnit& estimateWithoutPagination);
-    void marginBeforeEstimateForChild(RenderBox*, LayoutUnit&, LayoutUnit&, bool&) const;
-    void handleAfterSideOfBlock(LayoutUnit top, LayoutUnit bottom, MarginInfo&);
-    void setCollapsedBottomMargin(const MarginInfo&);
     // End helper functions and structs used by layoutBlockChildren.
 
     // Helper function for layoutInlineChildren()
@@ -921,9 +770,6 @@
 
     virtual ColumnInfo::PaginationUnit paginationUnit() const;
 
-    LayoutUnit applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset); // If the child has a before break, then return a new yPos that shifts to the top of the next page/column.
-    LayoutUnit applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo&); // If the child has an after break, then return a new offset that shifts to the top of the next page/column.
-
 public:
     LayoutUnit pageLogicalTopForOffset(LayoutUnit offset) const;
     LayoutUnit pageLogicalHeightForOffset(LayoutUnit offset) const;
@@ -942,7 +788,6 @@
 
     LayoutUnit adjustForUnsplittableChild(RenderBox* child, LayoutUnit logicalOffset, bool includeMargins = false); // If the child is unsplittable and can't fit on the current page, return the top of the next page/column.
     void adjustLinePositionForPagination(RootInlineBox*, LayoutUnit& deltaOffset, RenderFlowThread*); // Computes a deltaOffset value that put a line at the top of the next page if it doesn't fit on the current page.
-    LayoutUnit adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock);
 
     // Adjust from painting offsets to the local coords of this renderer
     void offsetForContents(LayoutPoint&) const;
@@ -975,36 +820,15 @@
     struct RenderBlockRareData {
         WTF_MAKE_NONCOPYABLE(RenderBlockRareData); WTF_MAKE_FAST_ALLOCATED;
     public:
-        RenderBlockRareData(const RenderBlock* block)
-            : m_margins(positiveMarginBeforeDefault(block), negativeMarginBeforeDefault(block), positiveMarginAfterDefault(block), negativeMarginAfterDefault(block))
-            , m_paginationStrut(0)
+        RenderBlockRareData()
+            : m_paginationStrut(0)
             , m_pageLogicalOffset(0)
             , m_lineGridBox(0)
             , m_lineBreakToAvoidWidow(0)
             , m_shouldBreakAtLineToAvoidWidow(false)
-            , m_discardMarginBefore(false)
-            , m_discardMarginAfter(false)
         {
         }
 
-        static LayoutUnit positiveMarginBeforeDefault(const RenderBlock* block)
-        {
-            return std::max<LayoutUnit>(block->marginBefore(), 0);
-        }
-        static LayoutUnit negativeMarginBeforeDefault(const RenderBlock* block)
-        {
-            return std::max<LayoutUnit>(-block->marginBefore(), 0);
-        }
-        static LayoutUnit positiveMarginAfterDefault(const RenderBlock* block)
-        {
-            return std::max<LayoutUnit>(block->marginAfter(), 0);
-        }
-        static LayoutUnit negativeMarginAfterDefault(const RenderBlock* block)
-        {
-            return std::max<LayoutUnit>(-block->marginAfter(), 0);
-        }
-
-        MarginValues m_margins;
         LayoutUnit m_paginationStrut;
         LayoutUnit m_pageLogicalOffset;
 
@@ -1013,8 +837,6 @@
         RootInlineBox* m_lineBreakToAvoidWidow;
         OwnPtr<ShapeInsideInfo> m_shapeInsideInfo;
         bool m_shouldBreakAtLineToAvoidWidow : 1;
-        bool m_discardMarginBefore : 1;
-        bool m_discardMarginAfter : 1;
      };
 
 protected:
diff --git a/Source/core/rendering/RenderBlockFlow.cpp b/Source/core/rendering/RenderBlockFlow.cpp
index 08b29b0..b65fa04 100644
--- a/Source/core/rendering/RenderBlockFlow.cpp
+++ b/Source/core/rendering/RenderBlockFlow.cpp
@@ -41,9 +41,110 @@
 
 namespace WebCore {
 
+struct SameSizeAsMarginInfo {
+    uint16_t bitfields;
+    LayoutUnit margins[2];
+};
+
+COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
+
+class MarginInfo {
+    // Collapsing flags for whether we can collapse our margins with our children's margins.
+    bool m_canCollapseWithChildren : 1;
+    bool m_canCollapseMarginBeforeWithChildren : 1;
+    bool m_canCollapseMarginAfterWithChildren : 1;
+
+    // Whether or not we are a quirky container, i.e., do we collapse away top and bottom
+    // margins in our container. Table cells and the body are the common examples. We
+    // also have a custom style property for Safari RSS to deal with TypePad blog articles.
+    bool m_quirkContainer : 1;
+
+    // This flag tracks whether we are still looking at child margins that can all collapse together at the beginning of a block.
+    // They may or may not collapse with the top margin of the block (|m_canCollapseTopWithChildren| tells us that), but they will
+    // always be collapsing with one another. This variable can remain set to true through multiple iterations
+    // as long as we keep encountering self-collapsing blocks.
+    bool m_atBeforeSideOfBlock : 1;
+
+    // This flag is set when we know we're examining bottom margins and we know we're at the bottom of the block.
+    bool m_atAfterSideOfBlock : 1;
+
+    // These variables are used to detect quirky margins that we need to collapse away (in table cells
+    // and in the body element).
+    bool m_hasMarginBeforeQuirk : 1;
+    bool m_hasMarginAfterQuirk : 1;
+    bool m_determinedMarginBeforeQuirk : 1;
+
+    bool m_discardMargin : 1;
+
+    // These flags track the previous maximal positive and negative margins.
+    LayoutUnit m_positiveMargin;
+    LayoutUnit m_negativeMargin;
+
+public:
+    MarginInfo(RenderBlockFlow*, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding);
+
+    void setAtBeforeSideOfBlock(bool b) { m_atBeforeSideOfBlock = b; }
+    void setAtAfterSideOfBlock(bool b) { m_atAfterSideOfBlock = b; }
+    void clearMargin()
+    {
+        m_positiveMargin = 0;
+        m_negativeMargin = 0;
+    }
+    void setHasMarginBeforeQuirk(bool b) { m_hasMarginBeforeQuirk = b; }
+    void setHasMarginAfterQuirk(bool b) { m_hasMarginAfterQuirk = b; }
+    void setDeterminedMarginBeforeQuirk(bool b) { m_determinedMarginBeforeQuirk = b; }
+    void setPositiveMargin(LayoutUnit p) { ASSERT(!m_discardMargin); m_positiveMargin = p; }
+    void setNegativeMargin(LayoutUnit n) { ASSERT(!m_discardMargin); m_negativeMargin = n; }
+    void setPositiveMarginIfLarger(LayoutUnit p)
+    {
+        ASSERT(!m_discardMargin);
+        if (p > m_positiveMargin)
+            m_positiveMargin = p;
+    }
+    void setNegativeMarginIfLarger(LayoutUnit n)
+    {
+        ASSERT(!m_discardMargin);
+        if (n > m_negativeMargin)
+            m_negativeMargin = n;
+    }
+
+    void setMargin(LayoutUnit p, LayoutUnit n) { ASSERT(!m_discardMargin); m_positiveMargin = p; m_negativeMargin = n; }
+    void setCanCollapseMarginAfterWithChildren(bool collapse) { m_canCollapseMarginAfterWithChildren = collapse; }
+    void setDiscardMargin(bool value) { m_discardMargin = value; }
+
+    bool atBeforeSideOfBlock() const { return m_atBeforeSideOfBlock; }
+    bool canCollapseWithMarginBefore() const { return m_atBeforeSideOfBlock && m_canCollapseMarginBeforeWithChildren; }
+    bool canCollapseWithMarginAfter() const { return m_atAfterSideOfBlock && m_canCollapseMarginAfterWithChildren; }
+    bool canCollapseMarginBeforeWithChildren() const { return m_canCollapseMarginBeforeWithChildren; }
+    bool canCollapseMarginAfterWithChildren() const { return m_canCollapseMarginAfterWithChildren; }
+    bool quirkContainer() const { return m_quirkContainer; }
+    bool determinedMarginBeforeQuirk() const { return m_determinedMarginBeforeQuirk; }
+    bool hasMarginBeforeQuirk() const { return m_hasMarginBeforeQuirk; }
+    bool hasMarginAfterQuirk() const { return m_hasMarginAfterQuirk; }
+    LayoutUnit positiveMargin() const { return m_positiveMargin; }
+    LayoutUnit negativeMargin() const { return m_negativeMargin; }
+    bool discardMargin() const { return m_discardMargin; }
+    LayoutUnit margin() const { return m_positiveMargin - m_negativeMargin; }
+};
+
+static bool inNormalFlow(RenderBox* child)
+{
+    RenderBlock* curr = child->containingBlock();
+    RenderView* renderView = child->view();
+    while (curr && curr != renderView) {
+        if (curr->hasColumns() || curr->isRenderFlowThread())
+            return true;
+        if (curr->isFloatingOrOutOfFlowPositioned())
+            return false;
+        curr = curr->containingBlock();
+    }
+    return true;
+}
+
 RenderBlockFlow::RenderBlockFlow(ContainerNode* node)
     : RenderBlock(node)
 {
+    COMPILE_ASSERT(sizeof(MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
 }
 
 RenderBlockFlow::~RenderBlockFlow()
@@ -228,6 +329,238 @@
     clearNeedsLayout();
 }
 
+void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
+{
+    LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
+    LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
+
+    // The child is a normal flow object. Compute the margins we will use for collapsing now.
+    child->computeAndSetBlockDirectionMargins(this);
+
+    // Try to guess our correct logical top position. In most cases this guess will
+    // be correct. Only if we're wrong (when we compute the real logical top position)
+    // will we have to potentially relayout.
+    LayoutUnit estimateWithoutPagination;
+    LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
+
+    // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
+    LayoutRect oldRect = child->frameRect();
+    LayoutUnit oldLogicalTop = logicalTopForChild(child);
+
+#if !ASSERT_DISABLED
+    LayoutSize oldLayoutDelta = view()->layoutDelta();
+#endif
+    // Go ahead and position the child as though it didn't collapse with the top.
+    setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
+
+    RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
+    bool markDescendantsWithFloats = false;
+    if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats()) {
+        markDescendantsWithFloats = true;
+    } else if (UNLIKELY(logicalTopEstimate.mightBeSaturated())) {
+        // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
+        // very large elements. If it does the comparison with oldLogicalTop might yield a
+        // false negative as adding and removing margins, borders etc from a saturated number
+        // might yield incorrect results. If this is the case always mark for layout.
+        markDescendantsWithFloats = true;
+    } else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
+        // If an element might be affected by the presence of floats, then always mark it for
+        // layout.
+        LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
+        if (fb > logicalTopEstimate)
+            markDescendantsWithFloats = true;
+    }
+
+    if (childRenderBlock) {
+        if (markDescendantsWithFloats)
+            childRenderBlock->markAllDescendantsWithFloatsForLayout();
+        if (!child->isWritingModeRoot())
+            previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
+    }
+
+    SubtreeLayoutScope layoutScope(child);
+    if (!child->needsLayout())
+        child->markForPaginationRelayoutIfNeeded(layoutScope);
+
+    bool childHadLayout = child->everHadLayout();
+    bool childNeededLayout = child->needsLayout();
+    if (childNeededLayout)
+        child->layout();
+
+    if (frameView()->partialLayout().isStopping())
+        return;
+
+    // Cache if we are at the top of the block right now.
+    bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
+
+    // Now determine the correct ypos based off examination of collapsing margin
+    // values.
+    LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
+
+    // Now check for clear.
+    LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
+
+    bool paginated = view()->layoutState()->isPaginated();
+    if (paginated) {
+        logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
+            atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
+    }
+
+    setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
+
+    // Now we have a final top position. See if it really does end up being different from our estimate.
+    // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
+    // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
+    if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlock && childRenderBlock->shouldBreakAtLineToAvoidWidow())) {
+        SubtreeLayoutScope layoutScope(child);
+        if (child->shrinkToAvoidFloats()) {
+            // The child's width depends on the line width.
+            // When the child shifts to clear an item, its width can
+            // change (because it has more available line width).
+            // So go ahead and mark the item as dirty.
+            layoutScope.setChildNeedsLayout(child);
+        }
+
+        if (childRenderBlock) {
+            if (!child->avoidsFloats() && childRenderBlock->containsFloats())
+                childRenderBlock->markAllDescendantsWithFloatsForLayout();
+            if (!child->needsLayout())
+                child->markForPaginationRelayoutIfNeeded(layoutScope);
+        }
+
+        // Our guess was wrong. Make the child lay itself out again.
+        child->layoutIfNeeded();
+    }
+
+    // We are no longer at the top of the block if we encounter a non-empty child.
+    // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
+    if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
+        marginInfo.setAtBeforeSideOfBlock(false);
+
+    // Now place the child in the correct left position
+    determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
+
+    // Update our height now that the child has been placed in the correct position.
+    setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
+    if (mustSeparateMarginAfterForChild(child)) {
+        setLogicalHeight(logicalHeight() + marginAfterForChild(child));
+        marginInfo.clearMargin();
+    }
+    // If the child has overhanging floats that intrude into following siblings (or possibly out
+    // of this block), then the parent gets notified of the floats now.
+    if (childRenderBlock && childRenderBlock->containsFloats())
+        maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
+
+    LayoutSize childOffset = child->location() - oldRect.location();
+    if (childOffset.width() || childOffset.height()) {
+        view()->addLayoutDelta(childOffset);
+
+        // If the child moved, we have to repaint it as well as any floating/positioned
+        // descendants. An exception is if we need a layout. In this case, we know we're going to
+        // repaint ourselves (and the child) anyway.
+        if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
+            child->repaintDuringLayoutIfMoved(oldRect);
+    }
+
+    if (!childHadLayout && child->checkForRepaintDuringLayout()) {
+        child->repaint();
+        child->repaintOverhangingFloats(true);
+    }
+
+    if (paginated) {
+        // Check for an after page/column break.
+        LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
+        if (newHeight != height())
+            setLogicalHeight(newHeight);
+    }
+
+    ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
+}
+
+LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock)
+{
+    RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
+
+    if (estimateWithoutPagination != logicalTopAfterClear) {
+        // Our guess prior to pagination movement was wrong. Before we attempt to paginate, let's try again at the new
+        // position.
+        setLogicalHeight(logicalTopAfterClear);
+        setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
+
+        if (child->shrinkToAvoidFloats()) {
+            // The child's width depends on the line width.
+            // When the child shifts to clear an item, its width can
+            // change (because it has more available line width).
+            // So go ahead and mark the item as dirty.
+            child->setChildNeedsLayout(MarkOnlyThis);
+        }
+
+        SubtreeLayoutScope layoutScope(child);
+
+        if (childRenderBlock) {
+            if (!child->avoidsFloats() && childRenderBlock->containsFloats())
+                childRenderBlock->markAllDescendantsWithFloatsForLayout();
+            if (!child->needsLayout())
+                child->markForPaginationRelayoutIfNeeded(layoutScope);
+        }
+
+        // Our guess was wrong. Make the child lay itself out again.
+        child->layoutIfNeeded();
+    }
+
+    LayoutUnit oldTop = logicalTopAfterClear;
+
+    // If the object has a page or column break value of "before", then we should shift to the top of the next page.
+    LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
+
+    if (pageLogicalHeightForOffset(result)) {
+        LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(result, ExcludePageBoundary);
+        LayoutUnit spaceShortage = child->logicalHeight() - remainingLogicalHeight;
+        if (spaceShortage > 0) {
+            // If the child crosses a column boundary, report a break, in case nothing inside it has already
+            // done so. The column balancer needs to know how much it has to stretch the columns to make more
+            // content fit. If no breaks are reported (but do occur), the balancer will have no clue. FIXME:
+            // This should be improved, though, because here we just pretend that the child is
+            // unsplittable. A splittable child, on the other hand, has break opportunities at every position
+            // where there's no child content, border or padding. In other words, we risk stretching more
+            // than necessary.
+            setPageBreak(result, spaceShortage);
+        }
+    }
+
+    // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
+    LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
+    LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
+
+    LayoutUnit paginationStrut = 0;
+    LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
+    if (unsplittableAdjustmentDelta)
+        paginationStrut = unsplittableAdjustmentDelta;
+    else if (childRenderBlock && childRenderBlock->paginationStrut())
+        paginationStrut = childRenderBlock->paginationStrut();
+
+    if (paginationStrut) {
+        // We are willing to propagate out to our parent block as long as we were at the top of the block prior
+        // to collapsing our margins, and as long as we didn't clear or move as a result of other pagination.
+        if (atBeforeSideOfBlock && oldTop == result && !isOutOfFlowPositioned() && !isTableCell()) {
+            // FIXME: Should really check if we're exceeding the page height before propagating the strut, but we don't
+            // have all the information to do so (the strut only has the remaining amount to push). Gecko gets this wrong too
+            // and pushes to the next page anyway, so not too concerned about it.
+            setPaginationStrut(result + paginationStrut);
+            if (childRenderBlock)
+                childRenderBlock->setPaginationStrut(0);
+        } else {
+            result += paginationStrut;
+        }
+    }
+
+    // Similar to how we apply clearance. Go ahead and boost height() to be the place where we're going to position the child.
+    setLogicalHeight(logicalHeight() + (result - oldTop));
+
+    // Return the final adjusted logical top.
+    return result;
+}
+
 void RenderBlockFlow::clearFloats()
 {
     if (m_floatingObjects)
@@ -247,7 +580,6 @@
     // Inline blocks are covered by the isReplaced() check in the avoidFloats method.
     if (avoidsFloats() || isRoot() || isRenderView() || isFloatingOrOutOfFlowPositioned() || isTableCell()) {
         if (m_floatingObjects) {
-            deleteAllValues(m_floatingObjects->set());
             m_floatingObjects->clear();
         }
         if (!oldIntrudingFloatSet.isEmpty())
@@ -255,21 +587,13 @@
         return;
     }
 
-    typedef HashMap<RenderObject*, FloatingObject*> RendererToFloatInfoMap;
     RendererToFloatInfoMap floatMap;
 
     if (m_floatingObjects) {
-        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-        if (childrenInline()) {
-            FloatingObjectSetIterator end = floatingObjectSet.end();
-            for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-                FloatingObject* f = *it;
-                floatMap.add(f->renderer(), f);
-            }
-        } else {
-            deleteAllValues(floatingObjectSet);
-        }
-        m_floatingObjects->clear();
+        if (childrenInline())
+            m_floatingObjects->moveAllToFloatInfoMap(floatMap);
+        else
+            m_floatingObjects->clear();
     }
 
     // We should not process floats if the parent node is not a RenderBlock. Otherwise, we will add
@@ -435,4 +759,677 @@
     handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
 }
 
+// Our MarginInfo state used when laying out block children.
+MarginInfo::MarginInfo(RenderBlockFlow* blockFlow, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
+    : m_atBeforeSideOfBlock(true)
+    , m_atAfterSideOfBlock(false)
+    , m_hasMarginBeforeQuirk(false)
+    , m_hasMarginAfterQuirk(false)
+    , m_determinedMarginBeforeQuirk(false)
+    , m_discardMargin(false)
+{
+    RenderStyle* blockStyle = blockFlow->style();
+    ASSERT(blockFlow->isRenderView() || blockFlow->parent());
+    m_canCollapseWithChildren = !blockFlow->isRenderView() && !blockFlow->isRoot() && !blockFlow->isOutOfFlowPositioned()
+        && !blockFlow->isFloating() && !blockFlow->isTableCell() && !blockFlow->hasOverflowClip() && !blockFlow->isInlineBlockOrInlineTable()
+        && !blockFlow->isRenderFlowThread() && !blockFlow->isWritingModeRoot() && !blockFlow->parent()->isFlexibleBox()
+        && blockStyle->hasAutoColumnCount() && blockStyle->hasAutoColumnWidth() && !blockStyle->columnSpan();
+
+    m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
+
+    // If any height other than auto is specified in CSS, then we don't collapse our bottom
+    // margins with our children's margins. To do otherwise would be to risk odd visual
+    // effects when the children overflow out of the parent block and yet still collapse
+    // with it. We also don't collapse if we have any bottom border/padding.
+    m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && !afterBorderPadding
+        && (blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
+
+    m_quirkContainer = blockFlow->isTableCell() || blockFlow->isBody();
+
+    m_discardMargin = m_canCollapseMarginBeforeWithChildren && blockFlow->mustDiscardMarginBefore();
+
+    m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxPositiveMarginBefore() : LayoutUnit();
+    m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxNegativeMarginBefore() : LayoutUnit();
+}
+
+RenderBlockFlow::MarginValues RenderBlockFlow::marginValuesForChild(RenderBox* child) const
+{
+    LayoutUnit childBeforePositive = 0;
+    LayoutUnit childBeforeNegative = 0;
+    LayoutUnit childAfterPositive = 0;
+    LayoutUnit childAfterNegative = 0;
+
+    LayoutUnit beforeMargin = 0;
+    LayoutUnit afterMargin = 0;
+
+    RenderBlockFlow* childRenderBlockFlow = child->isRenderBlockFlow() ? toRenderBlockFlow(child) : 0;
+
+    // If the child has the same directionality as we do, then we can just return its
+    // margins in the same direction.
+    if (!child->isWritingModeRoot()) {
+        if (childRenderBlockFlow) {
+            childBeforePositive = childRenderBlockFlow->maxPositiveMarginBefore();
+            childBeforeNegative = childRenderBlockFlow->maxNegativeMarginBefore();
+            childAfterPositive = childRenderBlockFlow->maxPositiveMarginAfter();
+            childAfterNegative = childRenderBlockFlow->maxNegativeMarginAfter();
+        } else {
+            beforeMargin = child->marginBefore();
+            afterMargin = child->marginAfter();
+        }
+    } else if (child->isHorizontalWritingMode() == isHorizontalWritingMode()) {
+        // The child has a different directionality. If the child is parallel, then it's just
+        // flipped relative to us. We can use the margins for the opposite edges.
+        if (childRenderBlockFlow) {
+            childBeforePositive = childRenderBlockFlow->maxPositiveMarginAfter();
+            childBeforeNegative = childRenderBlockFlow->maxNegativeMarginAfter();
+            childAfterPositive = childRenderBlockFlow->maxPositiveMarginBefore();
+            childAfterNegative = childRenderBlockFlow->maxNegativeMarginBefore();
+        } else {
+            beforeMargin = child->marginAfter();
+            afterMargin = child->marginBefore();
+        }
+    } else {
+        // The child is perpendicular to us, which means its margins don't collapse but are on the
+        // "logical left/right" sides of the child box. We can just return the raw margin in this case.
+        beforeMargin = marginBeforeForChild(child);
+        afterMargin = marginAfterForChild(child);
+    }
+
+    // Resolve uncollapsing margins into their positive/negative buckets.
+    if (beforeMargin) {
+        if (beforeMargin > 0)
+            childBeforePositive = beforeMargin;
+        else
+            childBeforeNegative = -beforeMargin;
+    }
+    if (afterMargin) {
+        if (afterMargin > 0)
+            childAfterPositive = afterMargin;
+        else
+            childAfterNegative = -afterMargin;
+    }
+
+    return RenderBlockFlow::MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
+}
+
+LayoutUnit RenderBlockFlow::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
+{
+    bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
+    bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
+    bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
+
+    // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
+    childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
+
+    // Get the four margin values for the child and cache them.
+    const RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
+
+    // Get our max pos and neg top margins.
+    LayoutUnit posTop = childMargins.positiveMarginBefore();
+    LayoutUnit negTop = childMargins.negativeMarginBefore();
+
+    // For self-collapsing blocks, collapse our bottom margins into our
+    // top to get new posTop and negTop values.
+    if (childIsSelfCollapsing) {
+        posTop = max(posTop, childMargins.positiveMarginAfter());
+        negTop = max(negTop, childMargins.negativeMarginAfter());
+    }
+
+    // See if the top margin is quirky. We only care if this child has
+    // margins that will collapse with us.
+    bool topQuirk = hasMarginBeforeQuirk(child);
+
+    if (marginInfo.canCollapseWithMarginBefore()) {
+        if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
+            // This child is collapsing with the top of the
+            // block. If it has larger margin values, then we need to update
+            // our own maximal values.
+            if (!document().inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
+                setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
+
+            // The minute any of the margins involved isn't a quirk, don't
+            // collapse it away, even if the margin is smaller (www.webreference.com
+            // has an example of this, a <dt> with 0.8em author-specified inside
+            // a <dl> inside a <td>.
+            if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
+                setHasMarginBeforeQuirk(false);
+                marginInfo.setDeterminedMarginBeforeQuirk(true);
+            }
+
+            if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore()) {
+                // We have no top margin and our top child has a quirky margin.
+                // We will pick up this quirky margin and pass it through.
+                // This deals with the <td><div><p> case.
+                // Don't do this for a block that split two inlines though. You do
+                // still apply margins in this case.
+                setHasMarginBeforeQuirk(true);
+            }
+        } else {
+            // The before margin of the container will also discard all the margins it is collapsing with.
+            setMustDiscardMarginBefore();
+        }
+    }
+
+    // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard.
+    if (childDiscardMarginBefore) {
+        marginInfo.setDiscardMargin(true);
+        marginInfo.clearMargin();
+    }
+
+    if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
+        marginInfo.setHasMarginBeforeQuirk(topQuirk);
+
+    LayoutUnit beforeCollapseLogicalTop = logicalHeight();
+    LayoutUnit logicalTop = beforeCollapseLogicalTop;
+    if (childIsSelfCollapsing) {
+        // For a self collapsing block both the before and after margins get discarded. The block doesn't contribute anything to the height of the block.
+        // Also, the child's top position equals the logical height of the container.
+        if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
+            // This child has no height. We need to compute our
+            // position before we collapse the child's margins together,
+            // so that we can get an accurate position for the zero-height block.
+            LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
+            LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
+            marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
+
+            // Now collapse the child's margins together, which means examining our
+            // bottom margin values as well.
+            marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
+            marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
+
+            if (!marginInfo.canCollapseWithMarginBefore()) {
+                // We need to make sure that the position of the self-collapsing block
+                // is correct, since it could have overflowing content
+                // that needs to be positioned correctly (e.g., a block that
+                // had a specified height of 0 but that actually had subcontent).
+                logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
+            }
+        }
+    } else {
+        if (mustSeparateMarginBeforeForChild(child)) {
+            ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
+            // If we are at the before side of the block and we collapse, ignore the computed margin
+            // and just add the child margin to the container height. This will correctly position
+            // the child inside the container.
+            LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
+            setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
+            logicalTop = logicalHeight();
+        } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
+            || (!marginInfo.canCollapseMarginBeforeWithChildren()
+            && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
+            // We're collapsing with a previous sibling's margins and not
+            // with the top of the block.
+            setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
+            logicalTop = logicalHeight();
+        }
+
+        marginInfo.setDiscardMargin(childDiscardMarginAfter);
+
+        if (!marginInfo.discardMargin()) {
+            marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
+            marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
+        } else {
+            marginInfo.clearMargin();
+        }
+
+        if (marginInfo.margin())
+            marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
+    }
+
+    // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
+    // collapsed into the page edge.
+    LayoutState* layoutState = view()->layoutState();
+    if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
+        && hasNextPage(beforeCollapseLogicalTop)) {
+        LayoutUnit oldLogicalTop = logicalTop;
+        logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
+        setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
+    }
+
+    // If we have collapsed into a previous sibling and so reduced the height of the parent, ensure any floats that now
+    // overhang from the previous sibling are added to our parent. If the child's previous sibling itself is a float the child will avoid
+    // or clear it anyway, so don't worry about any floating children it may contain.
+    LayoutUnit oldLogicalHeight = logicalHeight();
+    setLogicalHeight(logicalTop);
+    RenderObject* prev = child->previousSibling();
+    if (prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
+        RenderBlockFlow* blockFlow = toRenderBlockFlow(prev);
+        if (blockFlow->containsFloats() && !blockFlow->avoidsFloats() && (blockFlow->logicalTop() + blockFlow->lowestFloatLogicalBottom()) > logicalTop)
+            addOverhangingFloats(blockFlow, false);
+    }
+    setLogicalHeight(oldLogicalHeight);
+
+    return logicalTop;
+}
+
+void RenderBlockFlow::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
+{
+    bool isHorizontal = isHorizontalWritingMode();
+    bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
+
+    LayoutUnit logicalTop = logicalHeight();
+    updateStaticInlinePositionForChild(child, logicalTop);
+
+    if (!marginInfo.canCollapseWithMarginBefore()) {
+        // Positioned blocks don't collapse margins, so add the margin provided by
+        // the container now. The child's own margin is added later when calculating its logical top.
+        LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
+        LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
+        logicalTop += collapsedBeforePos - collapsedBeforeNeg;
+    }
+
+    RenderLayer* childLayer = child->layer();
+    if (childLayer->staticBlockPosition() != logicalTop) {
+        childLayer->setStaticBlockPosition(logicalTop);
+        if (hasStaticBlockPosition)
+            child->setChildNeedsLayout(MarkOnlyThis);
+    }
+}
+
+LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
+{
+    LayoutUnit heightIncrease = getClearDelta(child, yPos);
+    if (!heightIncrease)
+        return yPos;
+
+    if (child->isSelfCollapsingBlock()) {
+        bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
+
+        // For self-collapsing blocks that clear, they can still collapse their
+        // margins with following siblings. Reset the current margins to represent
+        // the self-collapsing block's margins only.
+        // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
+        if (!childDiscardMargin) {
+            RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
+            marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
+            marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
+        } else {
+            marginInfo.clearMargin();
+        }
+        marginInfo.setDiscardMargin(childDiscardMargin);
+
+        // CSS2.1 states:
+        // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
+        // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
+        // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
+        // for a block with height - if none is found then don't allow the margins to collapse with the parent.
+        bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
+        for (RenderBox* curr = child->nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
+            if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
+                wouldCollapseMarginsWithParent = false;
+        }
+        if (wouldCollapseMarginsWithParent)
+            marginInfo.setCanCollapseMarginAfterWithChildren(false);
+
+        // CSS2.1: "the amount of clearance is set so that clearance + margin-top = [height of float], i.e., clearance = [height of float] - margin-top"
+        // Move the top of the child box to the bottom of the float ignoring the child's top margin.
+        LayoutUnit collapsedMargin = collapsedMarginBeforeForChild(child);
+        setLogicalHeight(child->logicalTop() - collapsedMargin);
+        // A negative collapsed margin-top value cancels itself out as it has already been factored into |yPos| above.
+        heightIncrease -= max(LayoutUnit(), collapsedMargin);
+    } else {
+        // Increase our height by the amount we had to clear.
+        setLogicalHeight(logicalHeight() + heightIncrease);
+    }
+
+    if (marginInfo.canCollapseWithMarginBefore()) {
+        // We can no longer collapse with the top of the block since a clear
+        // occurred. The empty blocks collapse into the cleared block.
+        // FIXME: This isn't quite correct. Need clarification for what to do
+        // if the height the cleared block is offset by is smaller than the
+        // margins involved.
+        setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
+        marginInfo.setAtBeforeSideOfBlock(false);
+
+        // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
+        setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
+    }
+
+    LayoutUnit logicalTop = yPos + heightIncrease;
+    // After margin collapsing, one of our floats may now intrude into the child. If the child doesn't contain floats of its own it
+    // won't get picked up for relayout even though the logical top estimate was wrong - so add the newly intruding float now.
+    if (containsFloats() && child->isRenderBlock() && !toRenderBlock(child)->containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
+        toRenderBlock(child)->addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
+
+    return logicalTop;
+}
+
+void RenderBlockFlow::setCollapsedBottomMargin(const MarginInfo& marginInfo)
+{
+    if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
+        // Update the after side margin of the container to discard if the after margin of the last child also discards and we collapse with it.
+        // Don't update the max margin values because we won't need them anyway.
+        if (marginInfo.discardMargin()) {
+            setMustDiscardMarginAfter();
+            return;
+        }
+
+        // Update our max pos/neg bottom margins, since we collapsed our bottom margins
+        // with our children.
+        setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
+
+        if (!marginInfo.hasMarginAfterQuirk())
+            setHasMarginAfterQuirk(false);
+
+        if (marginInfo.hasMarginAfterQuirk() && !marginAfter()) {
+            // We have no bottom margin and our last child has a quirky margin.
+            // We will pick up this quirky margin and pass it through.
+            // This deals with the <td><div><p> case.
+            setHasMarginAfterQuirk(true);
+        }
+    }
+}
+
+void RenderBlockFlow::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
+{
+    // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
+    // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
+    // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
+    if ((document().inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
+        return;
+
+    // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
+    // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
+    if (child->style()->marginBeforeCollapse() == MDISCARD) {
+        positiveMarginBefore = 0;
+        negativeMarginBefore = 0;
+        discardMarginBefore = true;
+        return;
+    }
+
+    LayoutUnit beforeChildMargin = marginBeforeForChild(child);
+    positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
+    negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
+
+    if (!child->isRenderBlockFlow())
+        return;
+
+    RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
+    if (childBlockFlow->childrenInline() || childBlockFlow->isWritingModeRoot())
+        return;
+
+    MarginInfo childMarginInfo(childBlockFlow, childBlockFlow->borderBefore() + childBlockFlow->paddingBefore(), childBlockFlow->borderAfter() + childBlockFlow->paddingAfter());
+    if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
+        return;
+
+    RenderBox* grandchildBox = childBlockFlow->firstChildBox();
+    for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
+        if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
+            break;
+    }
+
+    // Give up if there is clearance on the box, since it probably won't collapse into us.
+    if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
+        return;
+
+    // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
+    if (grandchildBox->needsLayout()) {
+        grandchildBox->computeAndSetBlockDirectionMargins(this);
+        if (grandchildBox->isRenderBlock()) {
+            RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
+            grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style()->hasMarginBeforeQuirk());
+            grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style()->hasMarginAfterQuirk());
+        }
+    }
+
+    // Collapse the margin of the grandchild box with our own to produce an estimate.
+    childBlockFlow->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
+}
+
+LayoutUnit RenderBlockFlow::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
+{
+    // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
+    // relayout if there are intruding floats.
+    LayoutUnit logicalTopEstimate = logicalHeight();
+    if (!marginInfo.canCollapseWithMarginBefore()) {
+        LayoutUnit positiveMarginBefore = 0;
+        LayoutUnit negativeMarginBefore = 0;
+        bool discardMarginBefore = false;
+        if (child->selfNeedsLayout()) {
+            // Try to do a basic estimation of how the collapse is going to go.
+            marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
+        } else {
+            // Use the cached collapsed margin values from a previous layout. Most of the time they
+            // will be right.
+            RenderBlockFlow::MarginValues marginValues = marginValuesForChild(child);
+            positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
+            negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
+            discardMarginBefore = mustDiscardMarginBeforeForChild(child);
+        }
+
+        // Collapse the result with our current margins.
+        if (!discardMarginBefore)
+            logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
+    }
+
+    // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
+    // page.
+    LayoutState* layoutState = view()->layoutState();
+    if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
+        && hasNextPage(logicalHeight()))
+        logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
+
+    logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
+
+    estimateWithoutPagination = logicalTopEstimate;
+
+    if (layoutState->isPaginated()) {
+        // If the object has a page or column break value of "before", then we should shift to the top of the next page.
+        logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
+
+        // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
+        logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
+
+        if (!child->selfNeedsLayout() && child->isRenderBlock())
+            logicalTopEstimate += toRenderBlock(child)->paginationStrut();
+    }
+
+    return logicalTopEstimate;
+}
+
+void RenderBlockFlow::adjustFloatingBlock(const MarginInfo& marginInfo)
+{
+    // The float should be positioned taking into account the bottom margin
+    // of the previous flow. We add that margin into the height, get the
+    // float positioned properly, and then subtract the margin out of the
+    // height again. In the case of self-collapsing blocks, we always just
+    // use the top margins, since the self-collapsing block collapsed its
+    // own bottom margin into its top margin.
+    //
+    // Note also that the previous flow may collapse its margin into the top of
+    // our block. If this is the case, then we do not add the margin in to our
+    // height when computing the position of the float. This condition can be tested
+    // for by simply calling canCollapseWithMarginBefore. See
+    // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
+    // an example of this scenario.
+    LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
+    setLogicalHeight(logicalHeight() + marginOffset);
+    positionNewFloats();
+    setLogicalHeight(logicalHeight() - marginOffset);
+}
+
+void RenderBlockFlow::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
+{
+    marginInfo.setAtAfterSideOfBlock(true);
+
+    // If we can't collapse with children then go ahead and add in the bottom margin.
+    if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
+        && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
+        setLogicalHeight(logicalHeight() + marginInfo.margin());
+
+    // Now add in our bottom border/padding.
+    setLogicalHeight(logicalHeight() + afterSide);
+
+    // Negative margins can cause our height to shrink below our minimal height (border/padding).
+    // If this happens, ensure that the computed height is increased to the minimal height.
+    setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
+
+    // Update our bottom collapsed margin info.
+    setCollapsedBottomMargin(marginInfo);
+}
+
+void RenderBlockFlow::setMustDiscardMarginBefore(bool value)
+{
+    if (style()->marginBeforeCollapse() == MDISCARD) {
+        ASSERT(value);
+        return;
+    }
+
+    if (!m_rareData && !value)
+        return;
+
+    if (!m_rareData)
+        m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
+
+    m_rareData->m_discardMarginBefore = value;
+}
+
+void RenderBlockFlow::setMustDiscardMarginAfter(bool value)
+{
+    if (style()->marginAfterCollapse() == MDISCARD) {
+        ASSERT(value);
+        return;
+    }
+
+    if (!m_rareData && !value)
+        return;
+
+    if (!m_rareData)
+        m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
+
+    m_rareData->m_discardMarginAfter = value;
+}
+
+bool RenderBlockFlow::mustDiscardMarginBefore() const
+{
+    return style()->marginBeforeCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginBefore);
+}
+
+bool RenderBlockFlow::mustDiscardMarginAfter() const
+{
+    return style()->marginAfterCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginAfter);
+}
+
+bool RenderBlockFlow::mustDiscardMarginBeforeForChild(const RenderBox* child) const
+{
+    ASSERT(!child->selfNeedsLayout());
+    if (!child->isWritingModeRoot())
+        return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
+    if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
+        return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
+
+    // FIXME: We return false here because the implementation is not geometrically complete. We have values only for before/after, not start/end.
+    // In case the boxes are perpendicular we assume the property is not specified.
+    return false;
+}
+
+bool RenderBlockFlow::mustDiscardMarginAfterForChild(const RenderBox* child) const
+{
+    ASSERT(!child->selfNeedsLayout());
+    if (!child->isWritingModeRoot())
+        return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
+    if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
+        return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
+
+    // FIXME: See |mustDiscardMarginBeforeForChild| above.
+    return false;
+}
+
+void RenderBlockFlow::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
+{
+    if (!m_rareData) {
+        if (pos == RenderBlockFlowRareData::positiveMarginBeforeDefault(this) && neg == RenderBlockFlowRareData::negativeMarginBeforeDefault(this))
+            return;
+        m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
+    }
+    m_rareData->m_margins.setPositiveMarginBefore(pos);
+    m_rareData->m_margins.setNegativeMarginBefore(neg);
+}
+
+void RenderBlockFlow::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
+{
+    if (!m_rareData) {
+        if (pos == RenderBlockFlowRareData::positiveMarginAfterDefault(this) && neg == RenderBlockFlowRareData::negativeMarginAfterDefault(this))
+            return;
+        m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
+    }
+    m_rareData->m_margins.setPositiveMarginAfter(pos);
+    m_rareData->m_margins.setNegativeMarginAfter(neg);
+}
+
+bool RenderBlockFlow::mustSeparateMarginBeforeForChild(const RenderBox* child) const
+{
+    ASSERT(!child->selfNeedsLayout());
+    const RenderStyle* childStyle = child->style();
+    if (!child->isWritingModeRoot())
+        return childStyle->marginBeforeCollapse() == MSEPARATE;
+    if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
+        return childStyle->marginAfterCollapse() == MSEPARATE;
+
+    // FIXME: See |mustDiscardMarginBeforeForChild| above.
+    return false;
+}
+
+bool RenderBlockFlow::mustSeparateMarginAfterForChild(const RenderBox* child) const
+{
+    ASSERT(!child->selfNeedsLayout());
+    const RenderStyle* childStyle = child->style();
+    if (!child->isWritingModeRoot())
+        return childStyle->marginAfterCollapse() == MSEPARATE;
+    if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
+        return childStyle->marginBeforeCollapse() == MSEPARATE;
+
+    // FIXME: See |mustDiscardMarginBeforeForChild| above.
+    return false;
+}
+
+LayoutUnit RenderBlockFlow::applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset)
+{
+    // FIXME: Add page break checking here when we support printing.
+    bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
+    bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
+    RenderFlowThread* flowThread = flowThreadContainingBlock();
+    bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
+    bool checkBeforeAlways = (checkColumnBreaks && child->style()->columnBreakBefore() == PBALWAYS) || (checkPageBreaks && child->style()->pageBreakBefore() == PBALWAYS)
+        || (checkRegionBreaks && child->style()->regionBreakBefore() == PBALWAYS);
+    if (checkBeforeAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
+        if (checkColumnBreaks)
+            view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
+        if (checkRegionBreaks) {
+            LayoutUnit offsetBreakAdjustment = 0;
+            if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset, child, true, &offsetBreakAdjustment))
+                return logicalOffset + offsetBreakAdjustment;
+        }
+        return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
+    }
+    return logicalOffset;
+}
+
+LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
+{
+    // FIXME: Add page break checking here when we support printing.
+    bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
+    bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
+    RenderFlowThread* flowThread = flowThreadContainingBlock();
+    bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
+    bool checkAfterAlways = (checkColumnBreaks && child->style()->columnBreakAfter() == PBALWAYS) || (checkPageBreaks && child->style()->pageBreakAfter() == PBALWAYS)
+        || (checkRegionBreaks && child->style()->regionBreakAfter() == PBALWAYS);
+    if (checkAfterAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
+        LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
+
+        // So our margin doesn't participate in the next collapsing steps.
+        marginInfo.clearMargin();
+
+        if (checkColumnBreaks)
+            view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
+        if (checkRegionBreaks) {
+            LayoutUnit offsetBreakAdjustment = 0;
+            if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, child, false, &offsetBreakAdjustment))
+                return logicalOffset + marginOffset + offsetBreakAdjustment;
+        }
+        return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
+    }
+    return logicalOffset;
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderBlockFlow.h b/Source/core/rendering/RenderBlockFlow.h
index 888698c..d01686e 100644
--- a/Source/core/rendering/RenderBlockFlow.h
+++ b/Source/core/rendering/RenderBlockFlow.h
@@ -40,6 +40,8 @@
 
 namespace WebCore {
 
+class MarginInfo;
+
 class RenderBlockFlow : public RenderBlock {
 public:
     explicit RenderBlockFlow(ContainerNode*);
@@ -62,7 +64,125 @@
     void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope&);
     void layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom);
 
+    void layoutBlockChild(RenderBox* child, MarginInfo&, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom);
+    void adjustPositionedBlock(RenderBox* child, const MarginInfo&);
+    void adjustFloatingBlock(const MarginInfo&);
+
     void clearFloats();
+
+public:
+    class MarginValues {
+    public:
+        MarginValues(LayoutUnit beforePos, LayoutUnit beforeNeg, LayoutUnit afterPos, LayoutUnit afterNeg)
+            : m_positiveMarginBefore(beforePos)
+            , m_negativeMarginBefore(beforeNeg)
+            , m_positiveMarginAfter(afterPos)
+            , m_negativeMarginAfter(afterNeg)
+        { }
+
+        LayoutUnit positiveMarginBefore() const { return m_positiveMarginBefore; }
+        LayoutUnit negativeMarginBefore() const { return m_negativeMarginBefore; }
+        LayoutUnit positiveMarginAfter() const { return m_positiveMarginAfter; }
+        LayoutUnit negativeMarginAfter() const { return m_negativeMarginAfter; }
+
+        void setPositiveMarginBefore(LayoutUnit pos) { m_positiveMarginBefore = pos; }
+        void setNegativeMarginBefore(LayoutUnit neg) { m_negativeMarginBefore = neg; }
+        void setPositiveMarginAfter(LayoutUnit pos) { m_positiveMarginAfter = pos; }
+        void setNegativeMarginAfter(LayoutUnit neg) { m_negativeMarginAfter = neg; }
+
+    private:
+        LayoutUnit m_positiveMarginBefore;
+        LayoutUnit m_negativeMarginBefore;
+        LayoutUnit m_positiveMarginAfter;
+        LayoutUnit m_negativeMarginAfter;
+    };
+    MarginValues marginValuesForChild(RenderBox* child) const;
+
+    // Allocated only when some of these fields have non-default values
+    struct RenderBlockFlowRareData {
+        WTF_MAKE_NONCOPYABLE(RenderBlockFlowRareData); WTF_MAKE_FAST_ALLOCATED;
+    public:
+        RenderBlockFlowRareData(const RenderBlockFlow* block)
+            : m_margins(positiveMarginBeforeDefault(block), negativeMarginBeforeDefault(block), positiveMarginAfterDefault(block), negativeMarginAfterDefault(block))
+            , m_discardMarginBefore(false)
+            , m_discardMarginAfter(false)
+        {
+        }
+
+        static LayoutUnit positiveMarginBeforeDefault(const RenderBlockFlow* block)
+        {
+            return std::max<LayoutUnit>(block->marginBefore(), 0);
+        }
+        static LayoutUnit negativeMarginBeforeDefault(const RenderBlockFlow* block)
+        {
+            return std::max<LayoutUnit>(-block->marginBefore(), 0);
+        }
+        static LayoutUnit positiveMarginAfterDefault(const RenderBlockFlow* block)
+        {
+            return std::max<LayoutUnit>(block->marginAfter(), 0);
+        }
+        static LayoutUnit negativeMarginAfterDefault(const RenderBlockFlow* block)
+        {
+            return std::max<LayoutUnit>(-block->marginAfter(), 0);
+        }
+
+        MarginValues m_margins;
+        bool m_discardMarginBefore : 1;
+        bool m_discardMarginAfter : 1;
+    };
+
+protected:
+    LayoutUnit maxPositiveMarginBefore() const { return m_rareData ? m_rareData->m_margins.positiveMarginBefore() : RenderBlockFlowRareData::positiveMarginBeforeDefault(this); }
+    LayoutUnit maxNegativeMarginBefore() const { return m_rareData ? m_rareData->m_margins.negativeMarginBefore() : RenderBlockFlowRareData::negativeMarginBeforeDefault(this); }
+    LayoutUnit maxPositiveMarginAfter() const { return m_rareData ? m_rareData->m_margins.positiveMarginAfter() : RenderBlockFlowRareData::positiveMarginAfterDefault(this); }
+    LayoutUnit maxNegativeMarginAfter() const { return m_rareData ? m_rareData->m_margins.negativeMarginAfter() : RenderBlockFlowRareData::negativeMarginAfterDefault(this); }
+
+    void setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg);
+    void setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg);
+
+    void setMustDiscardMarginBefore(bool = true);
+    void setMustDiscardMarginAfter(bool = true);
+
+    bool mustDiscardMarginBefore() const;
+    bool mustDiscardMarginAfter() const;
+
+    bool mustDiscardMarginBeforeForChild(const RenderBox*) const;
+    bool mustDiscardMarginAfterForChild(const RenderBox*) const;
+
+    bool mustSeparateMarginBeforeForChild(const RenderBox*) const;
+    bool mustSeparateMarginAfterForChild(const RenderBox*) const;
+
+    void initMaxMarginValues()
+    {
+        if (m_rareData) {
+            m_rareData->m_margins = MarginValues(RenderBlockFlowRareData::positiveMarginBeforeDefault(this) , RenderBlockFlowRareData::negativeMarginBeforeDefault(this),
+                RenderBlockFlowRareData::positiveMarginAfterDefault(this), RenderBlockFlowRareData::negativeMarginAfterDefault(this));
+
+            m_rareData->m_discardMarginBefore = false;
+            m_rareData->m_discardMarginAfter = false;
+        }
+    }
+
+private:
+    virtual LayoutUnit collapsedMarginBefore() const OVERRIDE FINAL { return maxPositiveMarginBefore() - maxNegativeMarginBefore(); }
+    virtual LayoutUnit collapsedMarginAfter() const OVERRIDE FINAL { return maxPositiveMarginAfter() - maxNegativeMarginAfter(); }
+
+    LayoutUnit collapseMargins(RenderBox* child, MarginInfo&);
+    LayoutUnit clearFloatsIfNeeded(RenderBox* child, MarginInfo&, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos);
+    LayoutUnit estimateLogicalTopPosition(RenderBox* child, const MarginInfo&, LayoutUnit& estimateWithoutPagination);
+    void marginBeforeEstimateForChild(RenderBox*, LayoutUnit&, LayoutUnit&, bool&) const;
+    void handleAfterSideOfBlock(LayoutUnit top, LayoutUnit bottom, MarginInfo&);
+    void setCollapsedBottomMargin(const MarginInfo&);
+
+    LayoutUnit applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset); // If the child has a before break, then return a new yPos that shifts to the top of the next page/column.
+    LayoutUnit applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo&); // If the child has an after break, then return a new offset that shifts to the top of the next page/column.
+
+    LayoutUnit adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock);
+
+protected:
+    OwnPtr<RenderBlockFlowRareData> m_rareData;
+
+    friend class MarginInfo;
 };
 
 inline RenderBlockFlow& toRenderBlockFlow(RenderObject& object)
diff --git a/Source/core/rendering/RenderBlockLineLayout.cpp b/Source/core/rendering/RenderBlockLineLayout.cpp
index 1d0408e..6235fdd 100644
--- a/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -25,6 +25,7 @@
 #include "core/platform/text/BidiResolver.h"
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/InlineTextBox.h"
+#include "core/rendering/LineWidth.h"
 #include "core/rendering/RenderCombineText.h"
 #include "core/rendering/RenderCounter.h"
 #include "core/rendering/RenderFlowThread.h"
@@ -91,17 +92,6 @@
     Vector<RenderBox*> m_positionedObjects;
 };
 
-static LayoutUnit logicalHeightForLine(const RenderBlock* block, bool isFirstLine, LayoutUnit replacedHeight = 0)
-{
-    if (!block->document().inNoQuirksMode() && replacedHeight)
-        return replacedHeight;
-
-    if (!(block->style(isFirstLine)->lineBoxContain() & LineBoxContainBlock))
-        return 0;
-
-    return max<LayoutUnit>(replacedHeight, block->lineHeight(isFirstLine, block->isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
-}
-
 ShapeInsideInfo* RenderBlock::layoutShapeInsideInfo() const
 {
     ShapeInsideInfo* shapeInsideInfo = view()->layoutState()->shapeInsideInfo();
@@ -117,185 +107,6 @@
     return shapeInsideInfo;
 }
 
-enum IndentTextOrNot { DoNotIndentText, IndentText };
-
-class LineWidth {
-public:
-    LineWidth(RenderBlock* block, bool isFirstLine, IndentTextOrNot shouldIndentText)
-        : m_block(block)
-        , m_uncommittedWidth(0)
-        , m_committedWidth(0)
-        , m_overhangWidth(0)
-        , m_left(0)
-        , m_right(0)
-        , m_availableWidth(0)
-        , m_segment(0)
-        , m_isFirstLine(isFirstLine)
-        , m_shouldIndentText(shouldIndentText)
-    {
-        ASSERT(block);
-        ShapeInsideInfo* shapeInsideInfo = m_block->layoutShapeInsideInfo();
-        if (shapeInsideInfo)
-            m_segment = shapeInsideInfo->currentSegment();
-        updateAvailableWidth();
-    }
-    bool fitsOnLine() const { return currentWidth() <= m_availableWidth; }
-    bool fitsOnLine(float extra) const { return currentWidth() + extra <= m_availableWidth; }
-    float currentWidth() const { return m_committedWidth + m_uncommittedWidth; }
-
-    // FIXME: We should eventually replace these three functions by ones that work on a higher abstraction.
-    float uncommittedWidth() const { return m_uncommittedWidth; }
-    float committedWidth() const { return m_committedWidth; }
-    float availableWidth() const { return m_availableWidth; }
-
-    void updateAvailableWidth(LayoutUnit minimumHeight = 0);
-    void shrinkAvailableWidthForNewFloatIfNeeded(FloatingObject*);
-    void addUncommittedWidth(float delta) { m_uncommittedWidth += delta; }
-    void commit()
-    {
-        m_committedWidth += m_uncommittedWidth;
-        m_uncommittedWidth = 0;
-    }
-    void applyOverhang(RenderRubyRun*, RenderObject* startRenderer, RenderObject* endRenderer);
-    void fitBelowFloats();
-
-    bool shouldIndentText() const { return m_shouldIndentText == IndentText; }
-
-private:
-    void computeAvailableWidthFromLeftAndRight()
-    {
-        m_availableWidth = max(0.0f, m_right - m_left) + m_overhangWidth;
-    }
-
-private:
-    RenderBlock* m_block;
-    float m_uncommittedWidth;
-    float m_committedWidth;
-    float m_overhangWidth; // The amount by which |m_availableWidth| has been inflated to account for possible contraction due to ruby overhang.
-    float m_left;
-    float m_right;
-    float m_availableWidth;
-    const LineSegment* m_segment;
-    bool m_isFirstLine;
-    IndentTextOrNot m_shouldIndentText;
-};
-
-inline void LineWidth::updateAvailableWidth(LayoutUnit replacedHeight)
-{
-    LayoutUnit height = m_block->logicalHeight();
-    LayoutUnit logicalHeight = logicalHeightForLine(m_block, m_isFirstLine, replacedHeight);
-    m_left = m_block->logicalLeftOffsetForLine(height, shouldIndentText(), logicalHeight);
-    m_right = m_block->logicalRightOffsetForLine(height, shouldIndentText(), logicalHeight);
-
-    if (m_segment) {
-        m_left = max<float>(m_segment->logicalLeft, m_left);
-        m_right = min<float>(m_segment->logicalRight, m_right);
-    }
-
-    computeAvailableWidthFromLeftAndRight();
-}
-
-inline void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(FloatingObject* newFloat)
-{
-    LayoutUnit height = m_block->logicalHeight();
-    if (height < newFloat->logicalTop(m_block->isHorizontalWritingMode()) || height >= newFloat->logicalBottom(m_block->isHorizontalWritingMode()))
-        return;
-
-    // When floats with shape outside are stacked, the floats are positioned based on the margin box of the float,
-    // not the shape's contour. Since we computed the width based on the shape contour when we added the float,
-    // when we add a subsequent float on the same line, we need to undo the shape delta in order to position
-    // based on the margin box. In order to do this, we need to walk back through the floating object list to find
-    // the first previous float that is on the same side as our newFloat.
-    ShapeOutsideInfo* previousShapeOutsideInfo = 0;
-    const FloatingObjectSet& floatingObjectSet = m_block->m_floatingObjects->set();
-    FloatingObjectSetIterator it = floatingObjectSet.end();
-    FloatingObjectSetIterator begin = floatingObjectSet.begin();
-    while (it != begin) {
-        --it;
-        FloatingObject* previousFloat = *it;
-        if (previousFloat != newFloat && previousFloat->type() == newFloat->type()) {
-            previousShapeOutsideInfo = previousFloat->renderer()->shapeOutsideInfo();
-            if (previousShapeOutsideInfo) {
-                previousShapeOutsideInfo->computeSegmentsForContainingBlockLine(m_block->logicalHeight(), previousFloat->logicalTop(m_block->isHorizontalWritingMode()), logicalHeightForLine(m_block, m_isFirstLine));
-            }
-            break;
-        }
-    }
-
-    ShapeOutsideInfo* shapeOutsideInfo = newFloat->renderer()->shapeOutsideInfo();
-    if (shapeOutsideInfo)
-        shapeOutsideInfo->computeSegmentsForContainingBlockLine(m_block->logicalHeight(), newFloat->logicalTop(m_block->isHorizontalWritingMode()), logicalHeightForLine(m_block, m_isFirstLine));
-
-    if (newFloat->type() == FloatingObject::FloatLeft) {
-        float newLeft = newFloat->logicalRight(m_block->isHorizontalWritingMode());
-        if (previousShapeOutsideInfo)
-            newLeft -= previousShapeOutsideInfo->rightSegmentMarginBoxDelta();
-        if (shapeOutsideInfo)
-            newLeft += shapeOutsideInfo->rightSegmentMarginBoxDelta();
-
-        if (shouldIndentText() && m_block->style()->isLeftToRightDirection())
-            newLeft += floorToInt(m_block->textIndentOffset());
-        m_left = max<float>(m_left, newLeft);
-    } else {
-        float newRight = newFloat->logicalLeft(m_block->isHorizontalWritingMode());
-        if (previousShapeOutsideInfo)
-            newRight -= previousShapeOutsideInfo->leftSegmentMarginBoxDelta();
-        if (shapeOutsideInfo)
-            newRight += shapeOutsideInfo->leftSegmentMarginBoxDelta();
-
-        if (shouldIndentText() && !m_block->style()->isLeftToRightDirection())
-            newRight -= floorToInt(m_block->textIndentOffset());
-        m_right = min<float>(m_right, newRight);
-    }
-
-    computeAvailableWidthFromLeftAndRight();
-}
-
-void LineWidth::applyOverhang(RenderRubyRun* rubyRun, RenderObject* startRenderer, RenderObject* endRenderer)
-{
-    int startOverhang;
-    int endOverhang;
-    rubyRun->getOverhang(m_isFirstLine, startRenderer, endRenderer, startOverhang, endOverhang);
-
-    startOverhang = min<int>(startOverhang, m_committedWidth);
-    m_availableWidth += startOverhang;
-
-    endOverhang = max(min<int>(endOverhang, m_availableWidth - currentWidth()), 0);
-    m_availableWidth += endOverhang;
-    m_overhangWidth += startOverhang + endOverhang;
-}
-
-void LineWidth::fitBelowFloats()
-{
-    ASSERT(!m_committedWidth);
-    ASSERT(!fitsOnLine());
-
-    LayoutUnit floatLogicalBottom;
-    LayoutUnit lastFloatLogicalBottom = m_block->logicalHeight();
-    float newLineWidth = m_availableWidth;
-    float newLineLeft = m_left;
-    float newLineRight = m_right;
-    while (true) {
-        floatLogicalBottom = m_block->nextFloatLogicalBottomBelow(lastFloatLogicalBottom);
-        if (floatLogicalBottom <= lastFloatLogicalBottom)
-            break;
-
-        newLineLeft = m_block->logicalLeftOffsetForLine(floatLogicalBottom, shouldIndentText());
-        newLineRight = m_block->logicalRightOffsetForLine(floatLogicalBottom, shouldIndentText());
-        newLineWidth = max(0.0f, newLineRight - newLineLeft);
-        lastFloatLogicalBottom = floatLogicalBottom;
-        if (newLineWidth >= m_uncommittedWidth)
-            break;
-    }
-
-    if (newLineWidth > m_availableWidth) {
-        m_block->setLogicalHeight(lastFloatLogicalBottom);
-        m_availableWidth = newLineWidth + m_overhangWidth;
-        m_left = newLineLeft;
-        m_right = newLineRight;
-    }
-}
-
 class LineInfo {
 public:
     LineInfo()
@@ -433,7 +244,7 @@
     observer.setStatus(BidiStatus(root->style()->direction(), isOverride(root->style()->unicodeBidi())));
     while (!iter.atEnd()) {
         if (observer.inIsolate()) {
-            iter.increment(&observer, InlineIterator::FastIncrementInlineRenderer);
+            iter.increment(&observer, InlineIterator::FastIncrementInIsolatedRenderer);
             continue;
         }
         if (iter.atParagraphSeparator())
@@ -1463,7 +1274,7 @@
     // text selection in RTL boxes would not work as expected.
     if (isSVGRootInlineBox) {
         ASSERT(isSVGText());
-        static_cast<SVGRootInlineBox*>(lineBox)->computePerCharacterLayoutInformation();
+        toSVGRootInlineBox(lineBox)->computePerCharacterLayoutInformation();
     }
 
     // Compute our overflow now.
@@ -2143,12 +1954,15 @@
 
     // Text truncation kicks in in two cases:
     //     1) If your overflow isn't visible and your text-overflow-mode isn't clip.
-    //     2) If you're an anonymous block with a block parent that satisfies #1.
+    //     2) If you're an anonymous block with a block parent that satisfies #1 that was created
+    //        to accomodate a block that has inline and block children. This excludes parents where
+    //        canCollapseAnonymousBlockChild is false, notabley flex items and grid items.
     // FIXME: CSS3 says that descendants that are clipped must also know how to truncate.  This is insanely
     // difficult to figure out in general (especially in the middle of doing layout), so we only handle the
     // simple case of an anonymous block truncating when it's parent is clipped.
     bool hasTextOverflow = (style()->textOverflow() && hasOverflowClip())
-        || (isAnonymousBlock() && parent() && parent()->isRenderBlock() && parent()->style()->textOverflow() && parent()->hasOverflowClip());
+        || (isAnonymousBlock() && parent() && parent()->isRenderBlock() && toRenderBlock(parent())->canCollapseAnonymousBlockChild()
+            && parent()->style()->textOverflow() && parent()->hasOverflowClip());
 
     // Walk all the lines and delete our ellipsis line boxes if they exist.
     if (hasTextOverflow)
@@ -2597,7 +2411,7 @@
             if (toRenderCombineText(object)->isCombined())
                 continue;
         }
-        resolver.increment();
+        resolver.position().increment(&resolver);
     }
     resolver.commitExplicitEmbedding();
 }
@@ -2752,7 +2566,7 @@
     SegmentRangeList& segmentRanges = shapeInsideInfo->segmentRanges();
 
     for (unsigned i = 0; i < segments.size() && !end.atEnd(); i++) {
-        InlineIterator segmentStart = resolver.position();
+        const InlineIterator segmentStart = resolver.position();
         end = nextSegmentBreak(resolver, lineInfo, renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
 
         ASSERT(segmentRanges.size() == i);
@@ -2797,7 +2611,7 @@
     bool includeEndWidth = true;
     LineMidpointState& lineMidpointState = resolver.midpointState();
 
-    LineWidth width(m_block, lineInfo.isFirstLine(), requiresIndent(lineInfo.isFirstLine(), lineInfo.previousLineBrokeCleanly(), m_block->style()));
+    LineWidth width(*m_block, lineInfo.isFirstLine(), requiresIndent(lineInfo.isFirstLine(), lineInfo.previousLineBrokeCleanly(), m_block->style()));
 
     skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width);
 
@@ -3004,7 +2818,7 @@
                 if (iteratorIsBeyondEndOfRenderCombineText(lBreak, combineRenderer)) {
                     ASSERT(iteratorIsBeyondEndOfRenderCombineText(resolver.position(), combineRenderer));
                     lBreak.increment();
-                    resolver.increment();
+                    resolver.position().increment(&resolver);
                 }
             }
 
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index 80e9c74..f870131 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -2065,7 +2065,7 @@
             if (!itemChild->isListMarker())
                 continue;
             RenderBox* itemMarker = toRenderBox(itemChild);
-            if (itemMarker->requiresLayoutToDetermineWidth()) {
+            if (itemMarker->requiresLayoutToDetermineWidth() && itemMarker->needsLayout()) {
                 // Make sure to compute the autosized width.
                 itemMarker->layout();
             }
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
index 24f9c3c..ee4d483 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
@@ -281,8 +281,6 @@
 
     m_stretchingChildren = false;
 
-    initMaxMarginValues();
-
     if (isHorizontal())
         layoutHorizontalBox(relayoutChildren);
     else
@@ -298,24 +296,6 @@
 
     computeRegionRangeForBlock(flowThread);
 
-    if (!isFloatingOrOutOfFlowPositioned() && height() == 0) {
-        // We are a block with no border and padding and a computed height
-        // of 0.  The CSS spec states that zero-height blocks collapse their margins
-        // together.
-        // When blocks are self-collapsing, we just use the top margin values and set the
-        // bottom margin max values to 0.  This way we don't factor in the values
-        // twice when we collapse with our previous vertically adjacent and
-        // following vertically adjacent blocks.
-        LayoutUnit pos = maxPositiveMarginBefore();
-        LayoutUnit neg = maxNegativeMarginBefore();
-        if (maxPositiveMarginAfter() > pos)
-            pos = maxPositiveMarginAfter();
-        if (maxNegativeMarginAfter() > neg)
-            neg = maxNegativeMarginAfter();
-        setMaxMarginBeforeValues(pos, neg);
-        setMaxMarginAfterValues(0, 0);
-    }
-
     computeOverflow(oldClientAfterEdge);
 
     statePusher.pop();
diff --git a/Source/core/rendering/RenderFlowThread.cpp b/Source/core/rendering/RenderFlowThread.cpp
index 5b46e85..0ec0f06 100644
--- a/Source/core/rendering/RenderFlowThread.cpp
+++ b/Source/core/rendering/RenderFlowThread.cpp
@@ -346,7 +346,7 @@
 
 bool RenderFlowThread::shouldRepaint(const LayoutRect& r) const
 {
-    if (view()->printing() || r.isEmpty())
+    if (view()->document().printing() || r.isEmpty())
         return false;
 
     return true;
diff --git a/Source/core/rendering/RenderGrid.cpp b/Source/core/rendering/RenderGrid.cpp
index 4744fa6..887c26b 100644
--- a/Source/core/rendering/RenderGrid.cpp
+++ b/Source/core/rendering/RenderGrid.cpp
@@ -856,16 +856,14 @@
     computedUsedBreadthOfGridTracks(ForRows, columnTracks, rowTracks);
     ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, rowTracks));
 
-    for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
-        LayoutPoint childPosition = findChildLogicalPosition(child, columnTracks, rowTracks);
+    populateGridPositions(columnTracks, rowTracks);
 
+    for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
         // Because the grid area cannot be styled, we don't need to adjust
         // the grid breadth to account for 'box-sizing'.
         LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
         LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
 
-        // FIXME: For children in a content sized track, we clear the overrideContainingBlockContentLogicalHeight
-        // in minContentForChild / maxContentForChild which means that we will always relayout the child.
         LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, rowTracks);
 
@@ -883,8 +881,7 @@
         // now, just size as if we were a regular child.
         child->layoutIfNeeded();
 
-        // FIXME: Handle border & padding on the grid element.
-        child->setLogicalLocation(childPosition);
+        child->setLogicalLocation(findChildLogicalPosition(child, columnTracks, rowTracks));
 
         // If the child moved, we have to repaint it as well as any floating/positioned
         // descendants. An exception is if we need a layout. In this case, we know we're going to
@@ -1123,25 +1120,68 @@
     return gridAreaBreadth;
 }
 
+void RenderGrid::populateGridPositions(const Vector<GridTrack>& columnTracks, const Vector<GridTrack>& rowTracks)
+{
+    m_columnPositions.resize(columnTracks.size() + 1);
+    m_columnPositions[0] = borderAndPaddingStart();
+    for (size_t i = 0; i < m_columnPositions.size() - 1; ++i)
+        m_columnPositions[i + 1] = m_columnPositions[i] + columnTracks[i].m_usedBreadth;
+
+    m_rowPositions.resize(rowTracks.size() + 1);
+    m_rowPositions[0] = borderAndPaddingBefore();
+    for (size_t i = 0; i < m_rowPositions.size() - 1; ++i)
+        m_rowPositions[i + 1] = m_rowPositions[i] + rowTracks[i].m_usedBreadth;
+}
+
 LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox* child, const Vector<GridTrack>& columnTracks, const Vector<GridTrack>& rowTracks)
 {
     const GridCoordinate& coordinate = cachedGridCoordinate(child);
+    ASSERT(coordinate.columns.initialPositionIndex < columnTracks.size());
+    ASSERT(coordinate.rows.initialPositionIndex < rowTracks.size());
 
     // The grid items should be inside the grid container's border box, that's why they need to be shifted.
-    LayoutPoint offset(borderAndPaddingStart(), borderAndPaddingBefore());
-    // FIXME: |columnTrack| and |rowTrack| should be smaller than our column / row count.
-    for (size_t i = 0; i < coordinate.columns.initialPositionIndex && i < columnTracks.size(); ++i)
-        offset.setX(offset.x() + columnTracks[i].m_usedBreadth);
-    for (size_t i = 0; i < coordinate.rows.initialPositionIndex && i < rowTracks.size(); ++i)
-        offset.setY(offset.y() + rowTracks[i].m_usedBreadth);
+    return LayoutPoint(m_columnPositions[coordinate.columns.initialPositionIndex] + marginStartForChild(child), m_rowPositions[coordinate.rows.initialPositionIndex] + marginBeforeForChild(child));
+}
 
-    // FIXME: Handle margins on the grid item.
-    return offset;
+static GridSpan dirtiedGridAreas(const Vector<LayoutUnit>& coordinates, LayoutUnit start, LayoutUnit end)
+{
+    // This function does a binary search over the coordinates.
+    // FIXME: This doesn't work with grid items overflowing their grid areas and should be tested & fixed.
+
+    size_t startGridAreaIndex = std::upper_bound(coordinates.begin(), coordinates.end() - 1, start) - coordinates.begin();
+    if (startGridAreaIndex > 0)
+        --startGridAreaIndex;
+
+    size_t endGridAreaIndex = std::upper_bound(coordinates.begin() + startGridAreaIndex, coordinates.end() - 1, end) - coordinates.begin();
+    return GridSpan(startGridAreaIndex, endGridAreaIndex);
 }
 
 void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
-    for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
+    ASSERT_WITH_SECURITY_IMPLICATION(!gridIsDirty());
+
+    LayoutRect localRepaintRect = paintInfo.rect;
+    localRepaintRect.moveBy(-paintOffset);
+
+    GridSpan dirtiedColumns = dirtiedGridAreas(m_columnPositions, localRepaintRect.x(), localRepaintRect.maxX());
+    GridSpan dirtiedRows = dirtiedGridAreas(m_rowPositions, localRepaintRect.y(), localRepaintRect.maxY());
+
+    OrderIterator paintIterator(this);
+    {
+        OrderIteratorPopulator populator(paintIterator);
+
+        for (size_t row = dirtiedRows.initialPositionIndex; row < dirtiedRows.finalPositionIndex; ++row) {
+            for (size_t column = dirtiedColumns.initialPositionIndex; column < dirtiedColumns.finalPositionIndex; ++column) {
+                const Vector<RenderBox*, 1> children = m_grid[row][column];
+                // FIXME: If we start adding spanning children in all grid areas they span, this
+                // would make us paint them several times, which is wrong!
+                for (size_t j = 0; j < children.size(); ++j)
+                    populator.storeChild(children[j]);
+            }
+        }
+    }
+
+    for (RenderBox* child = paintIterator.first(); child; child = paintIterator.next())
         paintChild(child, paintInfo, paintOffset);
 }
 
diff --git a/Source/core/rendering/RenderGrid.h b/Source/core/rendering/RenderGrid.h
index cc76159..50b58c1 100644
--- a/Source/core/rendering/RenderGrid.h
+++ b/Source/core/rendering/RenderGrid.h
@@ -91,6 +91,7 @@
     TrackSizingDirection autoPlacementMinorAxisDirection() const;
 
     void layoutGridItems();
+    void populateGridPositions(const Vector<GridTrack>& columnTracks, const Vector<GridTrack>& rowTracks);
 
     virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
@@ -148,6 +149,8 @@
     typedef Vector<Vector<GridCell> > GridRepresentation;
     GridRepresentation m_grid;
     bool m_gridIsDirty;
+    Vector<LayoutUnit> m_rowPositions;
+    Vector<LayoutUnit> m_columnPositions;
     HashMap<const RenderBox*, GridCoordinate> m_gridItemCoordinate;
     OrderIterator m_orderIterator;
 };
diff --git a/Source/core/rendering/RenderInline.cpp b/Source/core/rendering/RenderInline.cpp
index e57e0b8..0ab2423 100644
--- a/Source/core/rendering/RenderInline.cpp
+++ b/Source/core/rendering/RenderInline.cpp
@@ -216,7 +216,7 @@
         || parentStyle->lineHeight() != style()->lineHeight()))
         || (flowThread && flowThread->hasRegionsWithStyling());
 
-    if (!alwaysCreateLineBoxes && checkFonts && document().styleSheetCollections()->usesFirstLineRules()) {
+    if (!alwaysCreateLineBoxes && checkFonts && document().styleEngine()->usesFirstLineRules()) {
         // Have to check the first line style as well.
         parentStyle = parent()->style(true);
         RenderStyle* childStyle = style(true);
@@ -1287,7 +1287,7 @@
 
 LayoutUnit RenderInline::lineHeight(bool firstLine, LineDirectionMode /*direction*/, LinePositionMode /*linePositionMode*/) const
 {
-    if (firstLine && document().styleSheetCollections()->usesFirstLineRules()) {
+    if (firstLine && document().styleEngine()->usesFirstLineRules()) {
         RenderStyle* s = style(firstLine);
         if (s != style())
             return s->computedLineHeight(view());
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index 921ed7a..2e5e260 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -116,11 +116,6 @@
 const int MinimumHeightWhileResizing = 40;
 const int ResizerControlExpandRatioForTouch = 2;
 
-bool ClipRect::intersects(const HitTestLocation& hitTestLocation) const
-{
-    return hitTestLocation.intersects(m_rect);
-}
-
 RenderLayer::RenderLayer(RenderLayerModelObject* renderer)
     : m_inResizeMode(false)
     , m_normalFlowListDirty(true)
@@ -139,7 +134,6 @@
     , m_isRootLayer(renderer->isRenderView())
     , m_usedTransparency(false)
     , m_paintingInsideReflection(false)
-    , m_inOverflowRelayout(false)
     , m_repaintStatus(NeedsNormalRepaint)
     , m_visibleContentStatusDirty(true)
     , m_hasVisibleContent(false)
@@ -203,9 +197,6 @@
     if (!m_renderer->documentBeingDestroyed())
         compositor()->removeOutOfFlowPositionedLayer(this);
 
-    destroyScrollbar(HorizontalScrollbar);
-    destroyScrollbar(VerticalScrollbar);
-
     if (renderer()->frame() && renderer()->frame()->page()) {
         if (ScrollingCoordinator* scrollingCoordinator = renderer()->frame()->page()->scrollingCoordinator())
             scrollingCoordinator->willDestroyRenderLayer(this);
@@ -358,7 +349,7 @@
         // FIXME: Should ASSERT that value calculated for m_outlineBox using the cached offset is the same
         // as the value not using the cached offset, but we can't due to https://bugs.webkit.org/show_bug.cgi?id=37048
         if (flags & CheckForRepaint) {
-            if (view && !view->printing()) {
+            if (view && !view->document().printing()) {
                 if (m_repaintStatus & NeedsFullRepaint) {
                     renderer()->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldRepaintRect));
                     if (m_repaintRect != oldRepaintRect)
@@ -1079,6 +1070,10 @@
     if (!m_hasVisibleContent && !m_hasVisibleDescendant)
         return;
 
+    FrameView* frameView = renderer()->view()->frameView();
+    if (!frameView)
+        return;
+
     const RenderObject* containingBlock = renderer()->containingBlock();
     setIsUnclippedDescendant(false);
     for (RenderLayer* ancestor = parent(); ancestor && ancestor->renderer() != containingBlock; ancestor = ancestor->parent()) {
@@ -1089,7 +1084,7 @@
         // compositor, we will be able to relax this restriction without it being prohibitively
         // expensive (currently, we have to do a lot of work in the compositor to honor a
         // clip child/parent relationship).
-        if (ancestor->needsCompositedScrolling())
+        if (frameView->containsScrollableArea(ancestor->scrollableArea()))
             setIsUnclippedDescendant(true);
         ancestor->setHasUnclippedDescendant(true);
     }
@@ -2067,6 +2062,51 @@
     return m_needsCompositedScrolling;
 }
 
+RenderLayer* RenderLayer::scrollParent() const
+{
+    if (!compositorDrivenAcceleratedScrollingEnabled())
+        return 0;
+
+    // A layer scrolls with its containing block. So to find the overflow scrolling layer
+    // that we scroll with respect to, we must ascend the layer tree until we reach the
+    // first overflow scrolling div at or above our containing block. I will refer to this
+    // layer as our 'scrolling ancestor'.
+    //
+    // Now, if we reside in a normal flow list, then we will naturally scroll with our scrolling
+    // ancestor, and we need not be composited. If, on the other hand, we reside in a z-order
+    // list, and on our walk upwards to our scrolling ancestor we find no layer that is a stacking
+    // context, then we know that in the stacking tree, we will not be in the subtree rooted at
+    // our scrolling ancestor, and we will therefore not scroll with it. In this case, we must
+    // be a composited layer since the compositor will need to take special measures to ensure
+    // that we scroll with our scrolling ancestor and it cannot do this if we do not promote.
+    RenderLayer* scrollParent = ancestorScrollingLayer();
+
+    if (!scrollParent || scrollParent->isStackingContext())
+        return 0;
+
+    // If we hit a stacking context on our way up to the ancestor scrolling layer, it will already
+    // be composited due to an overflow scrolling parent, so we don't need to.
+    for (RenderLayer* ancestor = parent(); ancestor && ancestor != scrollParent; ancestor = ancestor->parent()) {
+        if (ancestor->isStackingContext())
+            return 0;
+    }
+
+    return scrollParent;
+}
+
+RenderLayer* RenderLayer::clipParent() const
+{
+    const bool needsAncestorClip = compositor()->clippedByAncestor(this);
+
+    RenderLayer* clipParent = 0;
+    if ((compositingReasons() & CompositingReasonOutOfFlowClipping) && !needsAncestorClip) {
+        if (RenderObject* containingBlock = renderer()->containingBlock())
+            clipParent = containingBlock->enclosingLayer()->enclosingCompositingLayer(true);
+    }
+
+    return clipParent;
+}
+
 void RenderLayer::updateNeedsCompositedScrolling()
 {
     TRACE_EVENT0("comp-scroll", "RenderLayer::updateNeedsCompositedScrolling");
@@ -2374,10 +2414,15 @@
         scrollX = ScrollAlignment::getPartialBehavior(alignX);
     else
         scrollX = ScrollAlignment::getHiddenBehavior(alignX);
-    // If we're trying to align to the closest edge, and the exposeRect is further right
-    // than the visibleRect, and not bigger than the visible area, then align with the right.
-    if (scrollX == alignToClosestEdge && exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
-        scrollX = alignRight;
+    if (scrollX == alignToClosestEdge) {
+        // Closest edge is the right in two cases:
+        // (1) exposeRect to the right of and smaller than visibleRect
+        // (2) exposeRect to the left of and larger than visibleRect
+        if ((exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
+            || (exposeRect.maxX() < visibleRect.maxX() && exposeRect.width() > visibleRect.width())) {
+            scrollX = alignRight;
+        }
+    }
 
     // Given the X behavior, compute the X coordinate.
     LayoutUnit x;
@@ -2407,10 +2452,15 @@
         scrollY = ScrollAlignment::getPartialBehavior(alignY);
     else
         scrollY = ScrollAlignment::getHiddenBehavior(alignY);
-    // If we're trying to align to the closest edge, and the exposeRect is further down
-    // than the visibleRect, and not bigger than the visible area, then align with the bottom.
-    if (scrollY == alignToClosestEdge && exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
-        scrollY = alignBottom;
+    if (scrollY == alignToClosestEdge) {
+        // Closest edge is the bottom in two cases:
+        // (1) exposeRect below and smaller than visibleRect
+        // (2) exposeRect above and larger than visibleRect
+        if ((exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
+            || (exposeRect.maxY() < visibleRect.maxY() && exposeRect.height() > visibleRect.height())) {
+            scrollY = alignBottom;
+        }
+    }
 
     // Given the Y behavior, compute the Y coordinate.
     LayoutUnit y;
@@ -2629,52 +2679,6 @@
     return !scrollCornerRect().isEmpty();
 }
 
-IntRect RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
-{
-    RenderView* view = renderer()->view();
-    if (!view)
-        return scrollbarRect;
-
-    IntRect rect = scrollbarRect;
-    rect.move(scrollbarOffset(scrollbar));
-
-    return view->frameView()->convertFromRenderer(renderer(), rect);
-}
-
-IntRect RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
-{
-    RenderView* view = renderer()->view();
-    if (!view)
-        return parentRect;
-
-    IntRect rect = view->frameView()->convertToRenderer(renderer(), parentRect);
-    rect.move(-scrollbarOffset(scrollbar));
-    return rect;
-}
-
-IntPoint RenderLayer::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& scrollbarPoint) const
-{
-    RenderView* view = renderer()->view();
-    if (!view)
-        return scrollbarPoint;
-
-    IntPoint point = scrollbarPoint;
-    point.move(scrollbarOffset(scrollbar));
-    return view->frameView()->convertFromRenderer(renderer(), point);
-}
-
-IntPoint RenderLayer::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
-{
-    RenderView* view = renderer()->view();
-    if (!view)
-        return parentPoint;
-
-    IntPoint point = view->frameView()->convertToRenderer(renderer(), parentPoint);
-
-    point.move(-scrollbarOffset(scrollbar));
-    return point;
-}
-
 int RenderLayer::visibleHeight() const
 {
     return m_layerSize.height();
@@ -2706,93 +2710,6 @@
     return renderer()->frame() ? renderer()->frame()->eventHandler()->lastKnownMousePosition() : IntPoint();
 }
 
-IntRect RenderLayer::rectForHorizontalScrollbar(const IntRect& borderBoxRect) const
-{
-    if (!m_hBar)
-        return IntRect();
-
-    const RenderBox* box = renderBox();
-    const IntRect& scrollCorner = scrollCornerRect();
-
-    return IntRect(horizontalScrollbarStart(borderBoxRect.x()),
-        borderBoxRect.maxY() - box->borderBottom() - m_hBar->height(),
-        borderBoxRect.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
-        m_hBar->height());
-}
-
-IntRect RenderLayer::rectForVerticalScrollbar(const IntRect& borderBoxRect) const
-{
-    if (!m_vBar)
-        return IntRect();
-
-    const RenderBox* box = renderBox();
-    const IntRect& scrollCorner = scrollCornerRect();
-
-    return IntRect(verticalScrollbarStart(borderBoxRect.x(), borderBoxRect.maxX()),
-        borderBoxRect.y() + box->borderTop(),
-        m_vBar->width(),
-        borderBoxRect.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height());
-}
-
-LayoutUnit RenderLayer::verticalScrollbarStart(int minX, int maxX) const
-{
-    const RenderBox* box = renderBox();
-    if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
-        return minX + box->borderLeft();
-    return maxX - box->borderRight() - m_vBar->width();
-}
-
-LayoutUnit RenderLayer::horizontalScrollbarStart(int minX) const
-{
-    const RenderBox* box = renderBox();
-    int x = minX + box->borderLeft();
-    if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
-        x += m_vBar ? m_vBar->width() : resizerCornerRect(box->pixelSnappedBorderBoxRect(), ResizerForPointer).width();
-    return x;
-}
-
-IntSize RenderLayer::scrollbarOffset(const Scrollbar* scrollbar) const
-{
-    RenderBox* box = renderBox();
-
-    if (scrollbar == m_vBar.get())
-        return IntSize(verticalScrollbarStart(0, box->width()), box->borderTop());
-
-    if (scrollbar == m_hBar.get())
-        return IntSize(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
-
-    ASSERT_NOT_REACHED();
-    return IntSize();
-}
-
-void RenderLayer::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
-{
-    if (scrollbar == m_vBar.get()) {
-        if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
-            layer->setNeedsDisplayInRect(rect);
-            return;
-        }
-    } else {
-        if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
-            layer->setNeedsDisplayInRect(rect);
-            return;
-        }
-    }
-
-    IntRect scrollRect = rect;
-    RenderBox* box = renderBox();
-    ASSERT(box);
-    // If we are not yet inserted into the tree, there is no need to repaint.
-    if (!box->parent())
-        return;
-
-    if (scrollbar == m_vBar.get())
-        scrollRect.move(verticalScrollbarStart(0, box->width()), box->borderTop());
-    else
-        scrollRect.move(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
-    renderer()->repaintRectangle(scrollRect);
-}
-
 void RenderLayer::invalidateScrollCornerRect(const IntRect& rect)
 {
     if (GraphicsLayer* layer = layerForScrollCorner()) {
@@ -2806,6 +2723,7 @@
         m_resizer->repaintRectangle(rect);
 }
 
+// FIXME: This function is temporarily duplicated in RenderLayerScrollableArea.
 static inline RenderObject* rendererForScrollbar(RenderObject* renderer)
 {
     if (Node* node = renderer->node()) {
@@ -2818,84 +2736,6 @@
     return renderer;
 }
 
-PassRefPtr<Scrollbar> RenderLayer::createScrollbar(ScrollbarOrientation orientation)
-{
-    RefPtr<Scrollbar> widget;
-    RenderObject* actualRenderer = rendererForScrollbar(renderer());
-    bool hasCustomScrollbarStyle = actualRenderer->isBox() && actualRenderer->style()->hasPseudoStyle(SCROLLBAR);
-    if (hasCustomScrollbarStyle)
-        widget = RenderScrollbar::createCustomScrollbar(scrollableArea(), orientation, actualRenderer->node());
-    else {
-        widget = Scrollbar::create(scrollableArea(), orientation, RegularScrollbar);
-        if (orientation == HorizontalScrollbar)
-            scrollableArea()->didAddHorizontalScrollbar(widget.get());
-        else
-            scrollableArea()->didAddVerticalScrollbar(widget.get());
-    }
-    renderer()->document().view()->addChild(widget.get());
-    return widget.release();
-}
-
-void RenderLayer::destroyScrollbar(ScrollbarOrientation orientation)
-{
-    RefPtr<Scrollbar>& scrollbar = orientation == HorizontalScrollbar ? m_hBar : m_vBar;
-    if (!scrollbar)
-        return;
-
-    if (!scrollbar->isCustomScrollbar()) {
-        if (orientation == HorizontalScrollbar)
-            scrollableArea()->willRemoveHorizontalScrollbar(scrollbar.get());
-        else
-            scrollableArea()->willRemoveVerticalScrollbar(scrollbar.get());
-    }
-
-    scrollbar->removeFromParent();
-    scrollbar->disconnectFromScrollableArea();
-    scrollbar = 0;
-}
-
-void RenderLayer::setHasHorizontalScrollbar(bool hasScrollbar)
-{
-    if (hasScrollbar == hasHorizontalScrollbar())
-        return;
-
-    if (hasScrollbar)
-        m_hBar = createScrollbar(HorizontalScrollbar);
-    else
-        destroyScrollbar(HorizontalScrollbar);
-
-    // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
-    if (m_hBar)
-        m_hBar->styleChanged();
-    if (m_vBar)
-        m_vBar->styleChanged();
-
-    // Force an update since we know the scrollbars have changed things.
-    if (renderer()->document().hasAnnotatedRegions())
-        renderer()->document().setAnnotatedRegionsDirty(true);
-}
-
-void RenderLayer::setHasVerticalScrollbar(bool hasScrollbar)
-{
-    if (hasScrollbar == hasVerticalScrollbar())
-        return;
-
-    if (hasScrollbar)
-        m_vBar = createScrollbar(VerticalScrollbar);
-    else
-        destroyScrollbar(VerticalScrollbar);
-
-     // Destroying or creating one bar can cause our scrollbar corner to come and go.  We need to update the opposite scrollbar's style.
-    if (m_hBar)
-        m_hBar->styleChanged();
-    if (m_vBar)
-        m_vBar->styleChanged();
-
-    // Force an update since we know the scrollbars have changed things.
-    if (renderer()->document().hasAnnotatedRegions())
-        renderer()->document().setAnnotatedRegionsDirty(true);
-}
-
 ScrollableArea* RenderLayer::enclosingScrollableArea() const
 {
     if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
@@ -2906,20 +2746,6 @@
     return 0;
 }
 
-int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
-{
-    if (!m_vBar || (m_vBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_vBar->shouldParticipateInHitTesting())))
-        return 0;
-    return m_vBar->width();
-}
-
-int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
-{
-    if (!m_hBar || (m_hBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_hBar->shouldParticipateInHitTesting())))
-        return 0;
-    return m_hBar->height();
-}
-
 IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
 {
     // Currently the resize corner is either the bottom right corner or the bottom left corner.
@@ -2934,33 +2760,23 @@
 
 bool RenderLayer::hasOverflowControls() const
 {
-    return m_hBar || m_vBar || m_scrollCorner || renderer()->style()->resize() != RESIZE_NONE;
+    return m_scrollableArea->hasScrollbar() || m_scrollCorner || renderer()->style()->resize() != RESIZE_NONE;
 }
 
 void RenderLayer::positionOverflowControls(const IntSize& offsetFromRoot)
 {
-    if (!m_hBar && !m_vBar && !canResize())
+    if (!m_scrollableArea->hasScrollbar() && !canResize())
         return;
 
     RenderBox* box = renderBox();
     if (!box)
         return;
 
+    m_scrollableArea->positionOverflowControls(offsetFromRoot);
+
     const IntRect borderBox = box->pixelSnappedBorderBoxRect();
     const IntRect& scrollCorner = scrollCornerRect();
     IntRect absBounds(borderBox.location() + offsetFromRoot, borderBox.size());
-    if (m_vBar) {
-        IntRect vBarRect = rectForVerticalScrollbar(borderBox);
-        vBarRect.move(offsetFromRoot);
-        m_vBar->setFrameRect(vBarRect);
-    }
-
-    if (m_hBar) {
-        IntRect hBarRect = rectForHorizontalScrollbar(borderBox);
-        hBarRect.move(offsetFromRoot);
-        m_hBar->setFrameRect(hBarRect);
-    }
-
     if (m_scrollCorner)
         m_scrollCorner->setFrameRect(scrollCorner);
     if (m_resizer)
@@ -2980,72 +2796,6 @@
     return m_scrollableArea->scrollHeight();
 }
 
-void RenderLayer::updateScrollbarsAfterLayout()
-{
-    RenderBox* box = renderBox();
-    ASSERT(box);
-
-    // List box parts handle the scrollbars by themselves so we have nothing to do.
-    if (box->style()->appearance() == ListboxPart)
-        return;
-
-    bool hasHorizontalOverflow = m_scrollableArea->hasHorizontalOverflow();
-    bool hasVerticalOverflow = m_scrollableArea->hasVerticalOverflow();
-
-    // overflow:scroll should just enable/disable.
-    if (renderer()->style()->overflowX() == OSCROLL)
-        m_hBar->setEnabled(hasHorizontalOverflow);
-    if (renderer()->style()->overflowY() == OSCROLL)
-        m_vBar->setEnabled(hasVerticalOverflow);
-
-    // overflow:auto may need to lay out again if scrollbars got added/removed.
-    bool autoHorizontalScrollBarChanged = box->hasAutoHorizontalScrollbar() && (hasHorizontalScrollbar() != hasHorizontalOverflow);
-    bool autoVerticalScrollBarChanged = box->hasAutoVerticalScrollbar() && (hasVerticalScrollbar() != hasVerticalOverflow);
-
-    if (autoHorizontalScrollBarChanged || autoVerticalScrollBarChanged) {
-        if (box->hasAutoHorizontalScrollbar())
-            setHasHorizontalScrollbar(hasHorizontalOverflow);
-        if (box->hasAutoVerticalScrollbar())
-            setHasVerticalScrollbar(hasVerticalOverflow);
-
-        updateSelfPaintingLayer();
-
-        // Force an update since we know the scrollbars have changed things.
-        if (renderer()->document().hasAnnotatedRegions())
-            renderer()->document().setAnnotatedRegionsDirty(true);
-
-        renderer()->repaint();
-
-        if (renderer()->style()->overflowX() == OAUTO || renderer()->style()->overflowY() == OAUTO) {
-            if (!m_inOverflowRelayout) {
-                // Our proprietary overflow: overlay value doesn't trigger a layout.
-                m_inOverflowRelayout = true;
-                SubtreeLayoutScope layoutScope(renderer());
-                layoutScope.setNeedsLayout(renderer());
-                if (renderer()->isRenderBlock()) {
-                    RenderBlock* block = toRenderBlock(renderer());
-                    block->scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
-                    block->layoutBlock(true);
-                } else
-                    renderer()->layout();
-                m_inOverflowRelayout = false;
-            }
-        }
-    }
-
-    // Set up the range (and page step/line step).
-    if (m_hBar) {
-        int clientWidth = box->pixelSnappedClientWidth();
-        m_hBar->setProportion(clientWidth, m_scrollableArea->overflowRect().width());
-    }
-    if (m_vBar) {
-        int clientHeight = box->pixelSnappedClientHeight();
-        m_vBar->setProportion(clientHeight, m_scrollableArea->overflowRect().height());
-    }
-
-    updateScrollableAreaSet(m_scrollableArea->hasScrollableHorizontalOverflow() || m_scrollableArea->hasScrollableVerticalOverflow());
-}
-
 void RenderLayer::updateScrollInfoAfterLayout()
 {
     RenderBox* box = renderBox();
@@ -3053,7 +2803,6 @@
         return;
 
     m_scrollableArea->updateAfterLayout();
-    updateScrollbarsAfterLayout();
 
     // Composited scrolling may need to be enabled or disabled if the amount of overflow changed.
     if (renderer()->view() && compositor()->updateLayerCompositingState(this))
@@ -3064,10 +2813,10 @@
 {
     const IntRect borderBox = renderBox()->pixelSnappedBorderBoxRect();
 
-    if (rectForHorizontalScrollbar(borderBox).intersects(localRect))
+    if (m_scrollableArea->rectForHorizontalScrollbar(borderBox).intersects(localRect))
         return true;
 
-    if (rectForVerticalScrollbar(borderBox).intersects(localRect))
+    if (m_scrollableArea->rectForVerticalScrollbar(borderBox).intersects(localRect))
         return true;
 
     if (scrollCornerRect().intersects(localRect))
@@ -3085,37 +2834,6 @@
     if (!renderer()->hasOverflowClip())
         return;
 
-    // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
-    // on top of everything else. If this is the normal painting pass, paintingOverlayControls
-    // will be false, and we should just tell the root layer that there are overlay scrollbars
-    // that need to be painted. That will cause the second pass through the layer tree to run,
-    // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the
-    // second pass doesn't need to re-enter the RenderTree to get it right.
-    if (hasOverlayScrollbars() && !paintingOverlayControls) {
-        m_cachedOverlayScrollbarOffset = paintOffset;
-        // It's not necessary to do the second pass if the scrollbars paint into layers.
-        if ((m_hBar && layerForHorizontalScrollbar()) || (m_vBar && layerForVerticalScrollbar()))
-            return;
-        IntRect localDamgeRect = damageRect;
-        localDamgeRect.moveBy(-paintOffset);
-        if (!overflowControlsIntersectRect(localDamgeRect))
-            return;
-
-        RenderView* renderView = renderer()->view();
-
-        RenderLayer* paintingRoot = 0;
-        paintingRoot = enclosingCompositingLayer();
-        if (!paintingRoot)
-            paintingRoot = renderView->layer();
-
-        paintingRoot->setContainsDirtyOverlayScrollbars(true);
-        return;
-    }
-
-    // This check is required to avoid painting custom CSS scrollbars twice.
-    if (paintingOverlayControls && !hasOverlayScrollbars())
-        return;
-
     IntPoint adjustedPaintOffset = paintOffset;
     if (paintingOverlayControls)
         adjustedPaintOffset = m_cachedOverlayScrollbarOffset;
@@ -3125,11 +2843,7 @@
     // contains fixed positioned elements).
     positionOverflowControls(toIntSize(adjustedPaintOffset));
 
-    // Now that we're sure the scrollbars are in the right place, paint them.
-    if (m_hBar && !layerForHorizontalScrollbar())
-        m_hBar->paint(context, damageRect);
-    if (m_vBar && !layerForVerticalScrollbar())
-        m_vBar->paint(context, damageRect);
+    m_scrollableArea->paintOverflowControls(context, paintOffset, damageRect, paintingOverlayControls);
 
     if (layerForScrollCorner())
         return;
@@ -3224,7 +2938,7 @@
 
     // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
     // Clipping will exclude the right and bottom edges of this frame.
-    if (!hasOverlayScrollbars() && (m_vBar || m_hBar)) {
+    if (!hasOverlayScrollbars() && m_scrollableArea->hasScrollbar()) {
         GraphicsContextStateSaver stateSaver(*context);
         context->clip(absRect);
         IntRect largerCorner = absRect;
@@ -3252,7 +2966,7 @@
 
 bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
 {
-    if (!m_hBar && !m_vBar && !canResize())
+    if (!m_scrollableArea->hasScrollbar() && !canResize())
         return false;
 
     RenderBox* box = renderBox();
@@ -3265,34 +2979,9 @@
             return true;
     }
 
-    int resizeControlSize = max(resizeControlRect.height(), 0);
-
     // FIXME: We should hit test the m_scrollCorner and pass it back through the result.
 
-    if (m_vBar && m_vBar->shouldParticipateInHitTesting()) {
-        LayoutRect vBarRect(verticalScrollbarStart(0, box->width()),
-                            box->borderTop(),
-                            m_vBar->width(),
-                            box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
-        if (vBarRect.contains(localPoint)) {
-            result.setScrollbar(m_vBar.get());
-            return true;
-        }
-    }
-
-    resizeControlSize = max(resizeControlRect.width(), 0);
-    if (m_hBar && m_hBar->shouldParticipateInHitTesting()) {
-        LayoutRect hBarRect(horizontalScrollbarStart(0),
-                            box->height() - box->borderBottom() - m_hBar->height(),
-                            box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
-                            m_hBar->height());
-        if (hBarRect.contains(localPoint)) {
-            result.setScrollbar(m_hBar.get());
-            return true;
-        }
-    }
-
-    return false;
+    return m_scrollableArea->hitTestOverflowControls(result, localPoint, resizeControlRect);
 }
 
 bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
@@ -5323,6 +5012,29 @@
     return m_backing ? m_backing->scrollingContentsLayer() : 0;
 }
 
+GraphicsLayer* RenderLayer::layerForScrollChild() const
+{
+    // If we have an ancestor clipping layer because of our scroll parent, we do not want to
+    // scroll that clip layer -- we need it to stay put and we will slide within it. If, on
+    // the other hand, we have an ancestor clipping layer due to some other clipping layer, we
+    // want to scroll the root of the layer's associated graphics layer subtree. I.e., we want it
+    // and its clip to move in concert.
+
+    if (!backing())
+        return 0;
+
+    if (backing()->hasAncestorScrollClippingLayer()) {
+        return backing()->hasAncestorClippingLayer()
+            ? backing()->ancestorClippingLayer()
+            : backing()->graphicsLayer();
+    }
+
+    if (renderer()->containingBlock()->enclosingLayer() == ancestorScrollingLayer())
+        return backing()->graphicsLayer();
+
+    return backing()->childForSuperlayers();
+}
+
 GraphicsLayer* RenderLayer::layerForHorizontalScrollbar() const
 {
     return m_backing ? m_backing->layerForHorizontalScrollbar() : 0;
@@ -5830,51 +5542,6 @@
     compositor()->setNeedsUpdateCompositingRequirementsState();
 }
 
-static bool overflowRequiresScrollbar(EOverflow overflow)
-{
-    return overflow == OSCROLL;
-}
-
-static bool overflowDefinesAutomaticScrollbar(EOverflow overflow)
-{
-    return overflow == OAUTO || overflow == OOVERLAY;
-}
-
-void RenderLayer::updateScrollbarsAfterStyleChange(const RenderStyle* oldStyle)
-{
-    // Overflow are a box concept.
-    RenderBox* box = renderBox();
-    if (!box)
-        return;
-
-    // List box parts handle the scrollbars by themselves so we have nothing to do.
-    if (box->style()->appearance() == ListboxPart)
-        return;
-
-    EOverflow overflowX = box->style()->overflowX();
-    EOverflow overflowY = box->style()->overflowY();
-
-    // To avoid doing a relayout in updateScrollbarsAfterLayout, we try to keep any automatic scrollbar that was already present.
-    bool needsHorizontalScrollbar = (hasHorizontalScrollbar() && overflowDefinesAutomaticScrollbar(overflowX)) || overflowRequiresScrollbar(overflowX);
-    bool needsVerticalScrollbar = (hasVerticalScrollbar() && overflowDefinesAutomaticScrollbar(overflowY)) || overflowRequiresScrollbar(overflowY);
-    setHasHorizontalScrollbar(needsHorizontalScrollbar);
-    setHasVerticalScrollbar(needsVerticalScrollbar);
-
-    // With overflow: scroll, scrollbars are always visible but may be disabled.
-    // When switching to another value, we need to re-enable them (see bug 11985).
-    if (needsHorizontalScrollbar && oldStyle && oldStyle->overflowX() == OSCROLL && overflowX != OSCROLL) {
-        ASSERT(hasHorizontalScrollbar());
-        m_hBar->setEnabled(true);
-    }
-
-    if (needsVerticalScrollbar && oldStyle && oldStyle->overflowY() == OSCROLL && overflowY != OSCROLL) {
-        ASSERT(hasVerticalScrollbar());
-        m_vBar->setEnabled(true);
-    }
-
-    m_scrollableArea->updateAfterStyleChange(oldStyle);
-}
-
 void RenderLayer::updateOutOfFlowPositioned(const RenderStyle* oldStyle)
 {
     if (oldStyle && (renderer()->style()->position() == oldStyle->position()))
@@ -5984,7 +5651,7 @@
     updateIsNormalFlowOnly();
 
     updateResizerAreaSet();
-    updateScrollbarsAfterStyleChange(oldStyle);
+    m_scrollableArea->updateAfterStyleChange(oldStyle);
     updateStackingContextsAfterStyleChange(oldStyle);
     updateVisibilityAfterStyleChange(oldStyle);
     // Overlay scrollbars can make this layer self-painting so we need
@@ -6001,12 +5668,6 @@
         updateReflectionStyle();
     }
 
-    // FIXME: Need to detect a swap from custom to native scrollbars (and vice versa).
-    if (m_hBar)
-        m_hBar->styleChanged();
-    if (m_vBar)
-        m_vBar->styleChanged();
-
     updateScrollCornerStyle();
     updateResizerStyle();
 
@@ -6059,19 +5720,32 @@
     if (HTMLFrameOwnerElement* owner = frame->ownerElement())
         isVisibleToHitTest &= owner->renderer() && owner->renderer()->visibleToHitTesting();
 
-    if (hasOverflow && isVisibleToHitTest) {
-        if (frameView->addScrollableArea(scrollableArea())) {
-            compositor()->setNeedsUpdateCompositingRequirementsState();
-
-            // Count the total number of RenderLayers that are scrollable areas for
-            // any period. We only want to record this at most once per RenderLayer.
-            if (!m_isScrollableAreaHasBeenRecorded) {
-                HistogramSupport::histogramEnumeration("Renderer.CompositedScrolling", IsScrollableAreaBucket, CompositedScrollingHistogramMax);
-                m_isScrollableAreaHasBeenRecorded = true;
-            }
-        }
+    bool requiresScrollableArea = hasOverflow && isVisibleToHitTest;
+    bool updatedScrollableAreaSet = false;
+    if (requiresScrollableArea) {
+        if (frameView->addScrollableArea(scrollableArea()))
+            updatedScrollableAreaSet = true;
     } else {
         if (frameView->removeScrollableArea(scrollableArea()))
+            updatedScrollableAreaSet = true;
+    }
+
+    if (updatedScrollableAreaSet) {
+        // Count the total number of RenderLayers that are scrollable areas for
+        // any period. We only want to record this at most once per RenderLayer.
+        if (requiresScrollableArea && !m_isScrollableAreaHasBeenRecorded) {
+            HistogramSupport::histogramEnumeration("Renderer.CompositedScrolling", IsScrollableAreaBucket, CompositedScrollingHistogramMax);
+            m_isScrollableAreaHasBeenRecorded = true;
+        }
+
+        // We always want composited scrolling if compositor driven accelerated
+        // scrolling is enabled. Since we will not update needs composited scrolling
+        // in this case, we must force our state to update.
+        if (compositorDrivenAcceleratedScrollingEnabled())
+            didUpdateNeedsCompositedScrolling();
+        else if (requiresScrollableArea)
+            compositor()->setNeedsUpdateCompositingRequirementsState();
+        else
             setNeedsCompositedScrolling(false);
     }
 }
@@ -6342,6 +6016,36 @@
     return m_scrollableArea && m_scrollableArea->hasOverlayScrollbars();
 }
 
+Scrollbar* RenderLayer::horizontalScrollbar() const
+{
+    return m_scrollableArea->horizontalScrollbar();
+}
+
+Scrollbar* RenderLayer::verticalScrollbar() const
+{
+    return m_scrollableArea->verticalScrollbar();
+}
+
+bool RenderLayer::hasVerticalScrollbar() const
+{
+    return m_scrollableArea->hasVerticalScrollbar();
+}
+
+bool RenderLayer::hasHorizontalScrollbar() const
+{
+    return m_scrollableArea->hasHorizontalScrollbar();
+}
+
+int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
+{
+    return m_scrollableArea->verticalScrollbarWidth(relevancy);
+}
+
+int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
+{
+    return m_scrollableArea->horizontalScrollbarHeight(relevancy);
+}
+
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/RenderLayer.h b/Source/core/rendering/RenderLayer.h
index b2ec430..db3753a 100644
--- a/Source/core/rendering/RenderLayer.h
+++ b/Source/core/rendering/RenderLayer.h
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
  *
  * Portions are Copyright (C) 1998 Netscape Communications Corporation.
  *
@@ -44,6 +45,7 @@
 #ifndef RenderLayer_h
 #define RenderLayer_h
 
+#include "core/rendering/ClipRect.h"
 #include "core/rendering/CompositingReasons.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBox.h"
@@ -80,236 +82,6 @@
     NeedsFullRepaintForPositionedMovementLayout = 1 << 1
 };
 
-class ClipRect {
-public:
-    ClipRect()
-    : m_hasRadius(false)
-    { }
-
-    ClipRect(const LayoutRect& rect)
-    : m_rect(rect)
-    , m_hasRadius(false)
-    { }
-
-    const LayoutRect& rect() const { return m_rect; }
-    void setRect(const LayoutRect& rect) { m_rect = rect; }
-
-    bool hasRadius() const { return m_hasRadius; }
-    void setHasRadius(bool hasRadius) { m_hasRadius = hasRadius; }
-
-    bool operator==(const ClipRect& other) const { return rect() == other.rect() && hasRadius() == other.hasRadius(); }
-    bool operator!=(const ClipRect& other) const { return rect() != other.rect() || hasRadius() != other.hasRadius(); }
-    bool operator!=(const LayoutRect& otherRect) const { return rect() != otherRect; }
-
-    void intersect(const LayoutRect& other) { m_rect.intersect(other); }
-    void intersect(const ClipRect& other)
-    {
-        m_rect.intersect(other.rect());
-        if (other.hasRadius())
-            m_hasRadius = true;
-    }
-    void move(LayoutUnit x, LayoutUnit y) { m_rect.move(x, y); }
-    void move(const LayoutSize& size) { m_rect.move(size); }
-    void moveBy(const LayoutPoint& point) { m_rect.moveBy(point); }
-
-    bool isEmpty() const { return m_rect.isEmpty(); }
-    bool intersects(const LayoutRect& rect) const { return m_rect.intersects(rect); }
-    bool intersects(const HitTestLocation&) const;
-
-private:
-    LayoutRect m_rect;
-    bool m_hasRadius;
-};
-
-inline ClipRect intersection(const ClipRect& a, const ClipRect& b)
-{
-    ClipRect c = a;
-    c.intersect(b);
-    return c;
-}
-
-class ClipRects {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    static PassRefPtr<ClipRects> create()
-    {
-        return adoptRef(new ClipRects);
-    }
-
-    static PassRefPtr<ClipRects> create(const ClipRects& other)
-    {
-        return adoptRef(new ClipRects(other));
-    }
-
-    ClipRects()
-        : m_refCnt(1)
-        , m_fixed(false)
-    {
-    }
-
-    void reset(const LayoutRect& r)
-    {
-        m_overflowClipRect = r;
-        m_fixedClipRect = r;
-        m_posClipRect = r;
-        m_fixed = false;
-    }
-
-    const ClipRect& overflowClipRect() const { return m_overflowClipRect; }
-    void setOverflowClipRect(const ClipRect& r) { m_overflowClipRect = r; }
-
-    const ClipRect& fixedClipRect() const { return m_fixedClipRect; }
-    void setFixedClipRect(const ClipRect&r) { m_fixedClipRect = r; }
-
-    const ClipRect& posClipRect() const { return m_posClipRect; }
-    void setPosClipRect(const ClipRect& r) { m_posClipRect = r; }
-
-    bool fixed() const { return m_fixed; }
-    void setFixed(bool fixed) { m_fixed = fixed; }
-
-    void ref() { m_refCnt++; }
-    void deref()
-    {
-        if (!--m_refCnt)
-            delete this;
-    }
-
-    bool operator==(const ClipRects& other) const
-    {
-        return m_overflowClipRect == other.overflowClipRect() &&
-               m_fixedClipRect == other.fixedClipRect() &&
-               m_posClipRect == other.posClipRect() &&
-               m_fixed == other.fixed();
-    }
-
-    ClipRects& operator=(const ClipRects& other)
-    {
-        m_overflowClipRect = other.overflowClipRect();
-        m_fixedClipRect = other.fixedClipRect();
-        m_posClipRect = other.posClipRect();
-        m_fixed = other.fixed();
-        return *this;
-    }
-
-private:
-    ClipRects(const LayoutRect& r)
-        : m_overflowClipRect(r)
-        , m_fixedClipRect(r)
-        , m_posClipRect(r)
-        , m_refCnt(1)
-        , m_fixed(false)
-    {
-    }
-
-    ClipRects(const ClipRects& other)
-        : m_overflowClipRect(other.overflowClipRect())
-        , m_fixedClipRect(other.fixedClipRect())
-        , m_posClipRect(other.posClipRect())
-        , m_refCnt(1)
-        , m_fixed(other.fixed())
-    {
-    }
-
-    ClipRect m_overflowClipRect;
-    ClipRect m_fixedClipRect;
-    ClipRect m_posClipRect;
-    unsigned m_refCnt : 31;
-    bool m_fixed : 1;
-};
-
-enum ClipRectsType {
-    PaintingClipRects, // Relative to painting ancestor. Used for painting.
-    RootRelativeClipRects, // Relative to the ancestor treated as the root (e.g. transformed layer). Used for hit testing.
-    AbsoluteClipRects, // Relative to the RenderView's layer. Used for compositing overlap testing.
-    NumCachedClipRectsTypes,
-    AllClipRectTypes,
-    TemporaryClipRects
-};
-
-enum ShouldRespectOverflowClip {
-    IgnoreOverflowClip,
-    RespectOverflowClip
-};
-
-struct ClipRectsCache {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    ClipRectsCache()
-    {
-#ifndef NDEBUG
-        for (int i = 0; i < NumCachedClipRectsTypes; ++i) {
-            m_clipRectsRoot[i] = 0;
-            m_scrollbarRelevancy[i] = IgnoreOverlayScrollbarSize;
-        }
-#endif
-    }
-
-    PassRefPtr<ClipRects> getClipRects(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow) { return m_clipRects[getIndex(clipRectsType, respectOverflow)]; }
-    void setClipRects(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow, PassRefPtr<ClipRects> clipRects) { m_clipRects[getIndex(clipRectsType, respectOverflow)] = clipRects; }
-
-#ifndef NDEBUG
-    const RenderLayer* m_clipRectsRoot[NumCachedClipRectsTypes];
-    OverlayScrollbarSizeRelevancy m_scrollbarRelevancy[NumCachedClipRectsTypes];
-#endif
-
-private:
-    int getIndex(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow)
-    {
-        int index = static_cast<int>(clipRectsType);
-        if (respectOverflow == RespectOverflowClip)
-            index += static_cast<int>(NumCachedClipRectsTypes);
-        return index;
-    }
-
-    RefPtr<ClipRects> m_clipRects[NumCachedClipRectsTypes * 2];
-};
-
-struct LayerFragment {
-public:
-    LayerFragment()
-        : shouldPaintContent(false)
-    { }
-
-    void setRects(const LayoutRect& bounds, const ClipRect& background, const ClipRect& foreground, const ClipRect& outline)
-    {
-        layerBounds = bounds;
-        backgroundRect = background;
-        foregroundRect = foreground;
-        outlineRect = outline;
-    }
-
-    void moveBy(const LayoutPoint& offset)
-    {
-        layerBounds.moveBy(offset);
-        backgroundRect.moveBy(offset);
-        foregroundRect.moveBy(offset);
-        outlineRect.moveBy(offset);
-        paginationClip.moveBy(offset);
-    }
-
-    void intersect(const LayoutRect& rect)
-    {
-        backgroundRect.intersect(rect);
-        foregroundRect.intersect(rect);
-        outlineRect.intersect(rect);
-    }
-
-    bool shouldPaintContent;
-    LayoutRect layerBounds;
-    ClipRect backgroundRect;
-    ClipRect foregroundRect;
-    ClipRect outlineRect;
-
-    // Unique to paginated fragments. The physical translation to apply to shift the layer when painting/hit-testing.
-    LayoutPoint paginationOffset;
-
-    // Also unique to paginated fragments. An additional clip that applies to the layer. It is in layer-local
-    // (physical) coordinates.
-    LayoutRect paginationClip;
-};
-
-typedef Vector<LayerFragment, 1> LayerFragments;
-
 class RenderLayer {
 public:
     friend class RenderReplica;
@@ -392,12 +164,6 @@
 
     LayoutRect getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
 
-    bool hasHorizontalScrollbar() const { return horizontalScrollbar(); }
-    bool hasVerticalScrollbar() const { return verticalScrollbar(); }
-
-    int verticalScrollbarWidth(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
-    int horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
-
     // isPointInResizeControl() is used for testing if a pointer/touch position is in the resize control
     // area.
     bool isPointInResizeControl(const IntPoint& absolutePoint, ResizerHitTestType resizerHitTestType) const;
@@ -715,6 +481,10 @@
     void clearBacking(bool layerBeingDestroyed = false);
     bool needsCompositedScrolling() const;
     bool needsToBeStackingContainer() const;
+
+    RenderLayer* scrollParent() const;
+    RenderLayer* clipParent() const;
+
     bool needsCompositingLayersRebuiltForClip(const RenderStyle* oldStyle, const RenderStyle* newStyle) const;
     bool needsCompositingLayersRebuiltForOverflow(const RenderStyle* oldStyle, const RenderStyle* newStyle) const;
     bool needsCompositingLayersRebuiltForFilters(const RenderStyle* oldStyle, const RenderStyle* newStyle, bool didPaintWithFilters) const;
@@ -803,12 +573,6 @@
         OnlyStackingContextsCanBeStackingContainers
     };
 
-    void setHasHorizontalScrollbar(bool);
-    void setHasVerticalScrollbar(bool);
-
-    PassRefPtr<Scrollbar> createScrollbar(ScrollbarOrientation);
-    void destroyScrollbar(ScrollbarOrientation);
-
     bool hasOverflowControls() const;
 
     void updateZOrderLists();
@@ -857,9 +621,6 @@
     void updateVisibilityAfterStyleChange(const RenderStyle* oldStyle);
     void updateStackingContextsAfterStyleChange(const RenderStyle* oldStyle);
 
-    void updateScrollbarsAfterStyleChange(const RenderStyle* oldStyle);
-    void updateScrollbarsAfterLayout();
-
     void updateOutOfFlowPositioned(const RenderStyle* oldStyle);
 
     void setNeedsCompositedScrolling(bool);
@@ -982,14 +743,19 @@
 
 public:
     GraphicsLayer* layerForScrolling() const;
+    GraphicsLayer* layerForScrollChild() const;
     GraphicsLayer* layerForHorizontalScrollbar() const;
     GraphicsLayer* layerForVerticalScrollbar() const;
     GraphicsLayer* layerForScrollCorner() const;
-    Scrollbar* horizontalScrollbar() const { return m_hBar.get(); }
-    Scrollbar* verticalScrollbar() const { return m_vBar.get(); }
     bool usesCompositedScrolling() const;
 
     bool hasOverlayScrollbars() const;
+    Scrollbar* horizontalScrollbar() const;
+    Scrollbar* verticalScrollbar() const;
+    bool hasVerticalScrollbar() const;
+    bool hasHorizontalScrollbar() const;
+    int verticalScrollbarWidth(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
+    int horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
 
     int scrollXOffset() const;
     int scrollYOffset() const;
@@ -998,15 +764,10 @@
     IntSize adjustedScrollOffset() const { return IntSize(scrollXOffset(), scrollYOffset()); }
 
 private:
-    void invalidateScrollbarRect(Scrollbar*, const IntRect&);
     void invalidateScrollCornerRect(const IntRect&);
     bool isActive() const;
     bool isScrollCornerVisible() const;
     IntRect scrollCornerRect() const;
-    IntRect convertFromScrollbarToContainingView(const Scrollbar*, const IntRect&) const;
-    IntRect convertFromContainingViewToScrollbar(const Scrollbar*, const IntRect&) const;
-    IntPoint convertFromScrollbarToContainingView(const Scrollbar*, const IntPoint&) const;
-    IntPoint convertFromContainingViewToScrollbar(const Scrollbar*, const IntPoint&) const;
     int scrollSize(ScrollbarOrientation) const;
     int visibleHeight() const;
     int visibleWidth() const;
@@ -1028,8 +789,6 @@
 
     void updateCompositingLayersAfterScroll();
 
-    IntSize scrollbarOffset(const Scrollbar*) const;
-
     bool requiresScrollableArea() const { return renderer()->style()->overflowX() != OVISIBLE || canResize() || usesCompositedScrolling(); }
     void updateResizerAreaSet();
     void updateScrollableAreaSet(bool hasOverflow);
@@ -1091,12 +850,6 @@
     friend class RenderLayerCompositor;
     friend class RenderLayerModelObject;
 
-    IntRect rectForHorizontalScrollbar(const IntRect& borderBoxRect) const;
-    IntRect rectForVerticalScrollbar(const IntRect& borderBoxRect) const;
-
-    LayoutUnit verticalScrollbarStart(int minX, int maxX) const;
-    LayoutUnit horizontalScrollbarStart(int minX) const;
-
     bool overflowControlsIntersectRect(const IntRect& localRect) const;
 
 protected:
@@ -1143,7 +896,6 @@
                                  // we ended up painting this layer or any descendants (and therefore need to
                                  // blend).
     unsigned m_paintingInsideReflection : 1; // A state bit tracking if we are painting inside a replica.
-    unsigned m_inOverflowRelayout : 1;
     unsigned m_repaintStatus : 2; // RepaintStatus
 
     unsigned m_visibleContentStatusDirty : 1;
@@ -1192,10 +944,6 @@
     // The layer's width/height
     IntSize m_layerSize;
 
-    // For layers with overflow, we have a pair of scrollbars.
-    RefPtr<Scrollbar> m_hBar;
-    RefPtr<Scrollbar> m_vBar;
-
     // For layers that establish stacking contexts, m_posZOrderList holds a sorted list of all the
     // descendant layers within the stacking context that have z-indices of 0 or greater
     // (auto will count as 0).  m_negZOrderList holds descendants within our stacking context with negative
diff --git a/Source/core/rendering/RenderLayerBacking.cpp b/Source/core/rendering/RenderLayerBacking.cpp
index 0bdbeee..5719cb9 100644
--- a/Source/core/rendering/RenderLayerBacking.cpp
+++ b/Source/core/rendering/RenderLayerBacking.cpp
@@ -172,7 +172,7 @@
 
 RenderLayerBacking::~RenderLayerBacking()
 {
-    updateClippingLayers(false, false);
+    updateClippingLayers(false, false, false);
     updateOverflowControlsLayers(false, false, false);
     updateForegroundLayer(false);
     updateBackgroundLayer(false);
@@ -380,14 +380,16 @@
         // The solution is to update compositing children of this layer here,
         // via updateCompositingChildrenGeometry().
         updateCompositedBounds();
-        layerCompositor->updateCompositingDescendantGeometry(m_owningLayer, m_owningLayer, flags & CompositingChildrenOnly);
+        HashSet<RenderLayer*> visited;
+        layerCompositor->updateCompositingDescendantGeometry(m_owningLayer, m_owningLayer, visited, flags & CompositingChildrenOnly);
+        visited.clear();
 
         if (flags & IsUpdateRoot) {
             updateGraphicsLayerGeometry();
             layerCompositor->updateRootLayerPosition();
             RenderLayer* stackingContainer = m_owningLayer->enclosingStackingContainer();
             if (!layerCompositor->compositingLayersNeedRebuild() && stackingContainer && (stackingContainer != m_owningLayer))
-                layerCompositor->updateCompositingDescendantGeometry(stackingContainer, stackingContainer, flags & CompositingChildrenOnly);
+                layerCompositor->updateCompositingDescendantGeometry(stackingContainer, stackingContainer, visited, flags & CompositingChildrenOnly);
         }
     }
 
@@ -419,7 +421,10 @@
     if (m_owningLayer->needsCompositedScrolling())
         needsDescendentsClippingLayer = false;
 
-    if (updateClippingLayers(compositor->clippedByAncestor(m_owningLayer), needsDescendentsClippingLayer))
+    RenderLayer* scrollParent = m_owningLayer->scrollParent();
+    bool needsAncestorClip = compositor->clippedByAncestor(m_owningLayer);
+    bool needsScrollClip = !!scrollParent;
+    if (updateClippingLayers(needsAncestorClip, needsDescendentsClippingLayer, needsScrollClip))
         layerConfigChanged = true;
 
     if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer()))
@@ -428,6 +433,9 @@
     if (updateScrollingLayers(m_owningLayer->needsCompositedScrolling()))
         layerConfigChanged = true;
 
+    updateScrollParent(scrollParent);
+    updateClipParent(m_owningLayer->clipParent());
+
     if (layerConfigChanged)
         updateInternalHierarchy();
 
@@ -544,6 +552,30 @@
         graphicsLayerParentLocation = scrollOrigin - scrollOffset;
     }
 
+    if (compAncestor && m_ancestorScrollClippingLayer && m_owningLayer->ancestorScrollingLayer()) {
+        // Our scroll parent must have been processed before us. The code in RenderLayerCompositor
+        // that coordinates updating graphics layer geometry has been set up to guarantee that this is the case.
+        RenderLayer* scrollParent = m_owningLayer->ancestorScrollingLayer();
+        GraphicsLayer* scrollParentClippingLayer = scrollParent->backing()->scrollingLayer();
+
+        // Not relative to our parent graphics layer.
+        FloatPoint position;
+        GraphicsLayer* scrollParentChildForSuperlayers = scrollParent->backing()->childForSuperlayers();
+
+        for (GraphicsLayer* scrollAncestor = scrollParentClippingLayer; scrollAncestor; scrollAncestor = scrollAncestor->parent()) {
+            ASSERT(scrollAncestor->transform().isIdentity());
+            position = position + toFloatSize(scrollAncestor->position());
+            if (scrollAncestor == scrollParentChildForSuperlayers)
+                break;
+        }
+
+        m_ancestorScrollClippingLayer->setPosition(position);
+        m_ancestorScrollClippingLayer->setSize(scrollParentClippingLayer->size());
+        m_ancestorScrollClippingLayer->setOffsetFromRenderer(toIntSize(roundedIntPoint(-position)));
+
+        graphicsLayerParentLocation = roundedIntPoint(position);
+    }
+
     if (compAncestor && m_ancestorClippingLayer) {
         // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
         // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
@@ -750,6 +782,9 @@
 
 void RenderLayerBacking::updateInternalHierarchy()
 {
+    if (m_ancestorScrollClippingLayer)
+        m_ancestorScrollClippingLayer->removeAllChildren();
+
     // m_foregroundLayer has to be inserted in the correct order with child layers,
     // so it's not inserted here.
     if (m_ancestorClippingLayer)
@@ -760,6 +795,13 @@
     if (m_ancestorClippingLayer)
         m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
 
+    if (m_ancestorScrollClippingLayer) {
+        if (m_ancestorClippingLayer)
+            m_ancestorScrollClippingLayer->addChild(m_ancestorClippingLayer.get());
+        else
+            m_ancestorScrollClippingLayer->addChild(m_graphicsLayer.get());
+    }
+
     if (m_childContainmentLayer) {
         m_childContainmentLayer->removeFromParent();
         m_graphicsLayer->addChild(m_childContainmentLayer.get());
@@ -838,7 +880,7 @@
 }
 
 // Return true if the layers changed.
-bool RenderLayerBacking::updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip)
+bool RenderLayerBacking::updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip, bool needsScrollClip)
 {
     bool layersChanged = false;
 
@@ -868,6 +910,18 @@
         layersChanged = true;
     }
 
+    if (needsScrollClip) {
+        if (!m_ancestorScrollClippingLayer) {
+            m_ancestorScrollClippingLayer = createGraphicsLayer(CompositingReasonLayerForClip);
+            m_ancestorScrollClippingLayer->setMasksToBounds(true);
+            layersChanged = true;
+        }
+    } else if (m_ancestorScrollClippingLayer) {
+        m_ancestorScrollClippingLayer->removeFromParent();
+        m_ancestorScrollClippingLayer = nullptr;
+        layersChanged = true;
+    }
+
     return layersChanged;
 }
 
@@ -1090,6 +1144,18 @@
     return layerChanged;
 }
 
+void RenderLayerBacking::updateScrollParent(RenderLayer* scrollParent)
+{
+    if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer))
+        scrollingCoordinator->updateScrollParentForLayer(m_owningLayer, scrollParent);
+}
+
+void RenderLayerBacking::updateClipParent(RenderLayer* clipParent)
+{
+    if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer))
+        scrollingCoordinator->updateClipParentForLayer(m_owningLayer, clipParent);
+}
+
 GraphicsLayerPaintingPhase RenderLayerBacking::paintingPhaseForPrimaryLayer() const
 {
     unsigned phase = 0;
@@ -1105,6 +1171,9 @@
         phase |= GraphicsLayerPaintCompositedScroll;
     }
 
+    if (m_owningLayer->compositingReasons() & CompositingReasonOverflowScrollingParent)
+        phase |= GraphicsLayerPaintCompositedScroll;
+
     return static_cast<GraphicsLayerPaintingPhase>(phase);
 }
 
@@ -1442,6 +1511,9 @@
 
 GraphicsLayer* RenderLayerBacking::childForSuperlayers() const
 {
+    if (m_ancestorScrollClippingLayer)
+        return m_ancestorScrollClippingLayer.get();
+
     if (m_ancestorClippingLayer)
         return m_ancestorClippingLayer.get();
 
@@ -1569,6 +1641,10 @@
     if (!(paintInfo.paintingPhase & GraphicsLayerPaintOverflowContents))
         dirtyRect.intersect(paintInfo.compositedBounds);
 
+#ifndef NDEBUG
+    paintInfo.renderLayer->renderer()->assertSubtreeIsLaidOut();
+#endif
+
     // FIXME: GraphicsLayers need a way to split for RenderRegions.
     RenderLayer::LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, LayoutSize());
     paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags);
@@ -1695,7 +1771,7 @@
             continue;
 
         // Get timing function.
-        RefPtr<TimingFunction> tf = currentKeyframe.timingFunction(keyframes.animationName());
+        RefPtr<TimingFunction> tf = KeyframeValue::timingFunction(currentKeyframe.style(), keyframes.animationName());
 
         bool isFirstOrLastKeyframe = key == 0 || key == 1;
         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
@@ -1908,6 +1984,8 @@
     String name;
     if (graphicsLayer == m_graphicsLayer.get()) {
         name = m_owningLayer->debugName();
+    } else if (graphicsLayer == m_ancestorScrollClippingLayer.get()) {
+        name = "Ancestor Scroll Clipping Layer";
     } else if (graphicsLayer == m_ancestorClippingLayer.get()) {
         name = "Ancestor Clipping Layer";
     } else if (graphicsLayer == m_foregroundLayer.get()) {
diff --git a/Source/core/rendering/RenderLayerBacking.h b/Source/core/rendering/RenderLayerBacking.h
index 5a18edd..6285afd 100644
--- a/Source/core/rendering/RenderLayerBacking.h
+++ b/Source/core/rendering/RenderLayerBacking.h
@@ -94,9 +94,12 @@
     GraphicsLayer* clippingLayer() const { return m_childContainmentLayer.get(); }
 
     // Layer to get clipped by ancestor
-    bool hasAncestorClippingLayer() const { return m_ancestorClippingLayer != 0; }
+    bool hasAncestorClippingLayer() const { return m_ancestorClippingLayer; }
     GraphicsLayer* ancestorClippingLayer() const { return m_ancestorClippingLayer.get(); }
 
+    bool hasAncestorScrollClippingLayer() const { return m_ancestorScrollClippingLayer; }
+    GraphicsLayer* ancestorScrollClippingLayer() const { return m_ancestorScrollClippingLayer.get(); }
+
     bool hasContentsLayer() const { return m_foregroundLayer != 0; }
     GraphicsLayer* foregroundLayer() const { return m_foregroundLayer.get(); }
 
@@ -189,7 +192,7 @@
     RenderLayerCompositor* compositor() const { return m_owningLayer->compositor(); }
 
     void updateInternalHierarchy();
-    bool updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip);
+    bool updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip, bool needsScrollClip);
     bool updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer);
     bool updateForegroundLayer(bool needsForegroundLayer);
     bool updateBackgroundLayer(bool needsBackgroundLayer);
@@ -198,6 +201,8 @@
     bool requiresVerticalScrollbarLayer() const { return m_owningLayer->verticalScrollbar(); }
     bool requiresScrollCornerLayer() const { return !m_owningLayer->scrollCornerAndResizerRect().isEmpty(); }
     bool updateScrollingLayers(bool scrollingLayers);
+    void updateScrollParent(RenderLayer*);
+    void updateClipParent(RenderLayer*);
     void updateDrawsContent(bool isSimpleContainer);
     void registerScrollingLayers();
 
@@ -247,22 +252,91 @@
 
     RenderLayer* m_owningLayer;
 
+    // The hierarchy of layers that is maintained by the RenderLayerBacking looks like this:
+    //
+    // m_ancestorScrollClippingLayer [OPTIONAL]
+    //  + m_ancestorClippingLayer [OPTIONAL]
+    //     + m_graphicsLayer
+    //        + m_childContainmentLayer [OPTIONAL] <-OR-> m_scrollingLayer [OPTIONAL]
+    //                                                     + m_scrollingContentsLayer [OPTIONAL]
+    //
+    // We need an ancestor scroll clipping layer if we have a "scroll parent". That is, if
+    // our scrolling ancestor is not our ancestor in the stacking tree. Similarly, we need
+    // an ancestor clipping layer if our clipping ancestor is not our ancestor in the clipping
+    // tree. Here's what that might look like.
+    //
+    // Let A = the scrolling ancestor,
+    //     B = the clipping ancestor,
+    //     C = the scroll/clip descendant, and
+    //     SC = the stacking context that is the ancestor of A, B and C in the stacking tree.
+    //
+    // SC
+    //  + A = m_graphicsLayer
+    //  |      + m_scrollingLayer [*]
+    //  |         + m_scrollingContentsLayer [+]
+    //  |            + ...
+    //  ...
+    //  |
+    //  + B = m_graphicsLayer
+    //  |      + m_childContainmentLayer
+    //  |         + ...
+    //  ...
+    //  |
+    //  + C = m_ancestorScrollClippingLayer [**]
+    //         + m_ancestorClippingLayer [++]
+    //            + m_graphicsLayer
+    //               + ...
+    //
+    // Note that [*] and [**] exist for the same reason: to clip scrolling content. That is,
+    // when we scroll A, in fact [+] and [++] are moved and are clipped to [*] and [**],
+    // respectively.
+    //
+    // Now, it may also be the case that C is also clipped by another layer that doesn't happen
+    // to be its scrolling ancestor. B, in this case. When this happens, we create an
+    // ancestor clipping layer for C, [++]. Unlike the scroll clipping layer, [**], which must
+    // stay put during a scroll to do its job, the ancestor clipping layer [++] does move with
+    // the content it clips.
+    OwnPtr<GraphicsLayer> m_ancestorScrollClippingLayer; // Used if and only if we have a scroll parent.
     OwnPtr<GraphicsLayer> m_ancestorClippingLayer; // Only used if we are clipped by an ancestor which is not a stacking context.
     OwnPtr<GraphicsLayer> m_graphicsLayer;
+    OwnPtr<GraphicsLayer> m_childContainmentLayer; // Only used if we have clipping on a stacking context with compositing children.
+    OwnPtr<GraphicsLayer> m_scrollingLayer; // Only used if the layer is using composited scrolling.
+    OwnPtr<GraphicsLayer> m_scrollingContentsLayer; // Only used if the layer is using composited scrolling.
+
+    // This layer is also added to the hierarchy by the RLB, but in a different way than
+    // the layers above. It's added to m_graphicsLayer as its mask layer (naturally) if
+    // we have a mask, and isn't part of the typical hierarchy (it has no children).
+    OwnPtr<GraphicsLayer> m_maskLayer; // Only used if we have a mask.
+
+    // There are two other (optional) layers whose painting is managed by the RenderLayerBacking,
+    // but whose position in the hierarchy is maintained by the RenderLayerCompositor. These
+    // are the foreground and background layers. The foreground layer exists if we have composited
+    // descendants with negative z-order. We need the extra layer in this case because the layer
+    // needs to draw both below (for the background, say) and above (for the normal flow content, say)
+    // the negative z-order descendants and this is impossible with a single layer. The RLC handles
+    // inserting m_foregroundLayer in the correct position in our descendant list for us (right after
+    // the neg z-order dsecendants).
+    //
+    // The background layer is only created if this is the root layer and our background is entirely
+    // fixed. In this case we want to put the background in a separate composited layer so that when
+    // we scroll, we don't have to re-raster the background into position. This layer is also inserted
+    // into the tree by the RLC as it gets a special home. This layer becomes a descendant of the
+    // frame clipping layer. That is:
+    //   ...
+    //     + frame clipping layer
+    //       + m_backgroundLayer
+    //       + frame scrolling layer
+    //         + root content layer
+    //
+    // With the hierarchy set up like this, the root content layer is able to scroll without affecting
+    // the background layer (or repainting).
     OwnPtr<GraphicsLayer> m_foregroundLayer; // Only used in cases where we need to draw the foreground separately.
     OwnPtr<GraphicsLayer> m_backgroundLayer; // Only used in cases where we need to draw the background separately.
-    OwnPtr<GraphicsLayer> m_childContainmentLayer; // Only used if we have clipping on a stacking context with compositing children, or if the layer has a tile cache.
-    OwnPtr<GraphicsLayer> m_maskLayer; // Only used if we have a mask.
 
     OwnPtr<GraphicsLayer> m_layerForHorizontalScrollbar;
     OwnPtr<GraphicsLayer> m_layerForVerticalScrollbar;
     OwnPtr<GraphicsLayer> m_layerForScrollCorner;
 
-    OwnPtr<GraphicsLayer> m_scrollingLayer; // Only used if the layer is using composited scrolling.
-    OwnPtr<GraphicsLayer> m_scrollingContentsLayer; // Only used if the layer is using composited scrolling.
-
-    uint64_t m_scrollLayerID;
-
     IntRect m_compositedBounds;
 
     bool m_artificiallyInflatedBounds; // bounds had to be made non-zero to make transform-origin work
diff --git a/Source/core/rendering/RenderLayerCompositor.cpp b/Source/core/rendering/RenderLayerCompositor.cpp
index ca69154..cdde2da 100644
--- a/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/RenderLayerCompositor.cpp
@@ -439,9 +439,10 @@
     if (needHierarchyUpdate) {
         // Update the hierarchy of the compositing layers.
         Vector<GraphicsLayer*> childList;
+        HashSet<RenderLayer*> visited;
         {
             TRACE_EVENT0("blink_rendering", "RenderLayerCompositor::rebuildCompositingLayerTree");
-            rebuildCompositingLayerTree(updateRoot, childList, 0);
+            rebuildCompositingLayerTree(updateRoot, childList, visited, 0);
         }
 
         // Host the document layer in the RenderView's root layer.
@@ -456,7 +457,8 @@
     } else if (needGeometryUpdate) {
         // We just need to do a geometry update. This is only used for position:fixed scrolling;
         // most of the time, geometry is updated via RenderLayer::styleChanged().
-        updateLayerTreeGeometry(updateRoot, 0);
+        HashSet<RenderLayer*> visited;
+        updateLayerTreeGeometry(updateRoot, visited, 0);
     }
 
 #if !LOG_DISABLED
@@ -894,8 +896,22 @@
                     if (!willBeComposited) {
                         // make layer compositing
                         childState.m_compositingAncestor = layer;
+                        overlapMap->beginNewOverlapTestingContext();
                         willBeComposited = true;
                         willHaveForegroundLayer = true;
+
+                        // FIXME: temporary solution for the first negative z-index composited child:
+                        //        re-compute the absBounds for the child so that we can add the
+                        //        negative z-index child's bounds to the new overlap context.
+                        if (overlapMap) {
+                            overlapMap->geometryMap().pushMappingsToAncestor(curLayer, layer);
+                            IntRect childAbsBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(curLayer->overlapBounds()));
+                            bool boundsComputed = true;
+                            overlapMap->beginNewOverlapTestingContext();
+                            addToOverlapMap(*overlapMap, curLayer, childAbsBounds, boundsComputed);
+                            overlapMap->finishCurrentOverlapTestingContext();
+                            overlapMap->geometryMap().popMappingsToAncestor(layer);
+                        }
                     }
                 }
             }
@@ -903,8 +919,12 @@
     }
 
     if (overlapMap && willHaveForegroundLayer) {
+        ASSERT(willBeComposited);
         // A foreground layer effectively is a new backing for all subsequent children, so
-        // we don't need to test for overlap with anything behind this.
+        // we don't need to test for overlap with anything behind this. So, we can finish
+        // the previous context that was accumulating rects for the negative z-index
+        // children, and start with a fresh new empty context.
+        overlapMap->finishCurrentOverlapTestingContext();
         overlapMap->beginNewOverlapTestingContext();
         // This layer is going to be composited, so children can safely ignore the fact that there's an
         // animation running behind this layer, meaning they can rely on the overlap map testing again
@@ -1045,7 +1065,46 @@
     return o->supportsAcceleratedRendering();
 }
 
-void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer, int depth)
+// The purpose of this function is to ensure that we call rebuildCompostingLayerTree on curLayer's
+// scroll parent (if it has one) before we call it on curLayer. This is necessary because rebuilding the
+// compositing layer tree for curLayer will use values we computed for the scroll parent. More specifically,
+// rebuildCompositingLayreTree will call RenderLayerBacking::updateGraphicsLayerGeometry, and it's this
+// function that will pull values from a scroll parent's graphics layers. Unfortunately,
+// the childList needs to be populated as if we'd visited all the layers in paint order. To work around
+// this, when we visit a scroll parent out of order, we'll set its additions to childList aside (in
+// scrollParentChildLists), and add them to the real childList when we visit the scroll parent in paint
+// order.
+void RenderLayerCompositor::rebuildCompositingLayerTreeForLayerAndScrollParents(RenderLayer* curLayer, Vector<GraphicsLayer*>& childList, HashSet<RenderLayer*>& visited, HashMap<RenderLayer*, Vector<GraphicsLayer*> >& scrollParentChildLists, int depth)
+{
+    ASSERT(curLayer->zIndex() >= 0 || !visited.contains(curLayer));
+    if (visited.contains(curLayer)) {
+        // We've already processed this layer, but since we processed it out of order, its
+        // contribution to childList was not added. We must do that now.
+        HashMap<RenderLayer*, Vector<GraphicsLayer*> >::iterator it = scrollParentChildLists.find(curLayer);
+        ASSERT(it != scrollParentChildLists.end());
+        childList.append(it->value);
+        scrollParentChildLists.remove(it);
+        return;
+    }
+
+    if (requiresCompositingForOverflowScrollingParent(curLayer)) {
+        RenderLayer* scrollParent = curLayer->ancestorScrollingLayer();
+        if (!visited.contains(scrollParent)) {
+            ASSERT(!scrollParentChildLists.contains(scrollParent));
+            // We will populate scrollParentChildList rather than childList, since we're visiting it
+            // out of order.
+            Vector<GraphicsLayer*> scrollParentChildList;
+            rebuildCompositingLayerTreeForLayerAndScrollParents(scrollParent, scrollParentChildList, visited, scrollParentChildLists, depth);
+            // We will set aside the scrollParentChildList in scrollParentChildLists so that we can
+            // add it to childList when we visit the scrollParent normally.
+            scrollParentChildLists.add(scrollParent, scrollParentChildList);
+        }
+    }
+
+    rebuildCompositingLayerTree(curLayer, childList, visited, depth);
+}
+
+void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, Vector<GraphicsLayer*>& childLayersOfEnclosingLayer, HashSet<RenderLayer*>& visited, int depth)
 {
     // Make the layer compositing if necessary, and set up clipping and content layers.
     // Note that we can only do work here that is independent of whether the descendant layers
@@ -1061,6 +1120,8 @@
         pixelsAddedByPromotingAllTransitions = 0.0;
     }
 
+    visited.add(layer);
+
     RenderLayerBacking* layerBacking = layer->backing();
     if (layerBacking) {
         // The compositing state of all our children has been updated already, so now
@@ -1103,12 +1164,13 @@
     LayerListMutationDetector mutationChecker(layer);
 #endif
 
+    HashMap<RenderLayer*, Vector<GraphicsLayer*> > scrollParentChildLists;
     if (layer->isStackingContainer()) {
         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
             size_t listSize = negZOrderList->size();
             for (size_t i = 0; i < listSize; ++i) {
                 RenderLayer* curLayer = negZOrderList->at(i);
-                rebuildCompositingLayerTree(curLayer, childList, depth + 1);
+                rebuildCompositingLayerTreeForLayerAndScrollParents(curLayer, childList, visited, scrollParentChildLists, depth + 1);
             }
         }
 
@@ -1121,7 +1183,7 @@
         size_t listSize = normalFlowList->size();
         for (size_t i = 0; i < listSize; ++i) {
             RenderLayer* curLayer = normalFlowList->at(i);
-            rebuildCompositingLayerTree(curLayer, childList, depth + 1);
+            rebuildCompositingLayerTreeForLayerAndScrollParents(curLayer, childList, visited, scrollParentChildLists, depth + 1);
         }
     }
 
@@ -1130,7 +1192,7 @@
             size_t listSize = posZOrderList->size();
             for (size_t i = 0; i < listSize; ++i) {
                 RenderLayer* curLayer = posZOrderList->at(i);
-                rebuildCompositingLayerTree(curLayer, childList, depth + 1);
+                rebuildCompositingLayerTreeForLayerAndScrollParents(curLayer, childList, visited, scrollParentChildLists, depth + 1);
             }
         }
     }
@@ -1332,9 +1394,29 @@
     return true;
 }
 
-// This just updates layer geometry without changing the hierarchy.
-void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer, int depth)
+// The purpose of this function is to ensure that we call updateLayerTreeGeometry on layer's
+// scroll parent (if it has one) before we call it on layer. This is necessary because updating
+// layer tree geometry for layer will use values we computed for its scroll parent.
+void RenderLayerCompositor::updateLayerTreeGeometryForLayerAndScrollParents(RenderLayer* layer, HashSet<RenderLayer*>& visited, int depth)
 {
+    ASSERT(layer->zIndex() >= 0 || !visited.contains(layer));
+    if (visited.contains(layer))
+        return;
+
+    if (requiresCompositingForOverflowScrollingParent(layer)) {
+        RenderLayer* scrollParent = layer->ancestorScrollingLayer();
+        if (!visited.contains(scrollParent))
+            updateLayerTreeGeometryForLayerAndScrollParents(scrollParent, visited, depth);
+    }
+
+    updateLayerTreeGeometry(layer, visited, depth);
+}
+
+// This just updates layer geometry without changing the hierarchy.
+void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer, HashSet<RenderLayer*>& visited, int depth)
+{
+    visited.add(layer);
+
     if (RenderLayerBacking* layerBacking = layer->backing()) {
         // The compositing state of all our children has been updated already, so now
         // we can compute and cache the composited bounds for this layer.
@@ -1362,32 +1444,52 @@
     LayerListMutationDetector mutationChecker(layer);
 #endif
 
+    if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
+        size_t listSize = normalFlowList->size();
+        for (size_t i = 0; i < listSize; ++i)
+            updateLayerTreeGeometry(normalFlowList->at(i), visited, depth + 1);
+    }
+
     if (layer->isStackingContainer()) {
         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
             size_t listSize = negZOrderList->size();
             for (size_t i = 0; i < listSize; ++i)
-                updateLayerTreeGeometry(negZOrderList->at(i), depth + 1);
+                updateLayerTreeGeometryForLayerAndScrollParents(negZOrderList->at(i), visited, depth + 1);
         }
     }
 
-    if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
-        size_t listSize = normalFlowList->size();
-        for (size_t i = 0; i < listSize; ++i)
-            updateLayerTreeGeometry(normalFlowList->at(i), depth + 1);
-    }
-
     if (layer->isStackingContainer()) {
         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
             size_t listSize = posZOrderList->size();
             for (size_t i = 0; i < listSize; ++i)
-                updateLayerTreeGeometry(posZOrderList->at(i), depth + 1);
+                updateLayerTreeGeometryForLayerAndScrollParents(posZOrderList->at(i), visited, depth + 1);
         }
     }
 }
 
-// Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
-void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer* layer, bool compositedChildrenOnly)
+// The purpose of this function is to ensure that we call updateCompositingDescendantGeometry on layer's
+// scroll parent (if it has one) before we call it on layer. This is necessary because updating
+// layer tree geometry for layer will use values we computed for its scroll parent.
+void RenderLayerCompositor::updateCompositingDescendantGeometryForLayerAndScrollParents(RenderLayer* compositingAncestor, RenderLayer* layer, HashSet<RenderLayer*>& visited, bool compositedChildrenOnly)
 {
+    ASSERT(layer->zIndex() >= 0 || !visited.contains(layer));
+    if (visited.contains(layer))
+        return;
+
+    if (requiresCompositingForOverflowScrollingParent(layer)) {
+        RenderLayer* scrollParent = layer->ancestorScrollingLayer();
+        if (!visited.contains(scrollParent))
+            updateCompositingDescendantGeometryForLayerAndScrollParents(compositingAncestor, scrollParent, visited, compositedChildrenOnly);
+    }
+
+    updateCompositingDescendantGeometry(compositingAncestor, layer, visited, compositedChildrenOnly);
+}
+
+// Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
+void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer* layer, HashSet<RenderLayer*>& visited, bool compositedChildrenOnly)
+{
+    visited.add(layer);
+
     if (layer != compositingAncestor) {
         if (RenderLayerBacking* layerBacking = layer->backing()) {
             layerBacking->updateCompositedBounds();
@@ -1404,7 +1506,7 @@
     }
 
     if (layer->reflectionLayer())
-        updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionLayer(), compositedChildrenOnly);
+        updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionLayer(), visited, compositedChildrenOnly);
 
     if (!layer->hasCompositingDescendant())
         return;
@@ -1417,21 +1519,21 @@
         if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
             size_t listSize = negZOrderList->size();
             for (size_t i = 0; i < listSize; ++i)
-                updateCompositingDescendantGeometry(compositingAncestor, negZOrderList->at(i), compositedChildrenOnly);
+                updateCompositingDescendantGeometryForLayerAndScrollParents(compositingAncestor, negZOrderList->at(i), visited, compositedChildrenOnly);
         }
     }
 
     if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
         size_t listSize = normalFlowList->size();
         for (size_t i = 0; i < listSize; ++i)
-            updateCompositingDescendantGeometry(compositingAncestor, normalFlowList->at(i), compositedChildrenOnly);
+            updateCompositingDescendantGeometryForLayerAndScrollParents(compositingAncestor, normalFlowList->at(i), visited, compositedChildrenOnly);
     }
 
     if (layer->isStackingContainer()) {
         if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
             size_t listSize = posZOrderList->size();
             for (size_t i = 0; i < listSize; ++i)
-                updateCompositingDescendantGeometry(compositingAncestor, posZOrderList->at(i), compositedChildrenOnly);
+                updateCompositingDescendantGeometryForLayerAndScrollParents(compositingAncestor, posZOrderList->at(i), visited, compositedChildrenOnly);
         }
     }
 }
@@ -1771,22 +1873,26 @@
 // according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
 // Thus, a RenderLayer can be clipped by a RenderLayer that is an ancestor in the renderer hierarchy,
 // but a sibling in the z-order hierarchy.
-bool RenderLayerCompositor::clippedByAncestor(RenderLayer* layer) const
+bool RenderLayerCompositor::clippedByAncestor(const RenderLayer* layer) const
 {
     if (!layer->isComposited() || !layer->parent())
         return false;
 
-    RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
+    // Scroll children use their scrolling ancestor as their clip root.
+    RenderLayer* compositingAncestor = requiresCompositingForOverflowScrollingParent(layer)
+        ? layer->ancestorScrollingLayer()
+        : layer->ancestorCompositingLayer();
+
     if (!compositingAncestor)
         return false;
 
     // If the compositingAncestor clips, that will be taken care of by clipsCompositingDescendants(),
     // so we only care about clipping between its first child that is our ancestor (the computeClipRoot),
     // and layer.
-    RenderLayer* computeClipRoot = 0;
-    RenderLayer* curr = layer;
+    const RenderLayer* computeClipRoot = 0;
+    const RenderLayer* curr = layer;
     while (curr) {
-        RenderLayer* next = curr->parent();
+        const RenderLayer* next = curr->parent();
         if (next == compositingAncestor) {
             computeClipRoot = curr;
             break;
@@ -1998,34 +2104,7 @@
 
 bool RenderLayerCompositor::requiresCompositingForOverflowScrollingParent(const RenderLayer* layer) const
 {
-    if (!layer->compositorDrivenAcceleratedScrollingEnabled())
-        return false;
-
-    // A layer scrolls with its containing block. So to find the overflow scrolling layer
-    // that we scroll with respect to, we must ascend the layer tree until we reach the
-    // first overflow scrolling div at or above our containing block. I will refer to this
-    // layer as our 'scrolling ancestor'.
-    //
-    // Now, if we reside in a normal flow list, then we will naturally scroll with our scrolling
-    // ancestor, and we need not be composited. If, on the other hand, we reside in a z-order
-    // list, and on our walk upwards to our scrolling ancestor we find no layer that is a stacking
-    // context, then we know that in the stacking tree, we will not be in the subtree rooted at
-    // our scrolling ancestor, and we will therefore not scroll with it. In this case, we must
-    // be a composited layer since the compositor will need to take special measures to ensure
-    // that we scroll with our scrolling ancestor and it cannot do this if we do not promote.
-    RenderLayer* scrollParent = layer->ancestorScrollingLayer();
-
-    if (!scrollParent || scrollParent->isStackingContext())
-        return false;
-
-    // If we hit a stacking context on our way up to the ancestor scrolling layer, it will already
-    // be composited due to an overflow scrolling parent, so we don't need to.
-    for (RenderLayer* ancestor = layer->parent(); ancestor && ancestor != scrollParent; ancestor = ancestor->parent()) {
-        if (ancestor->isStackingContext())
-            return false;
-    }
-
-    return true;
+    return !!layer->scrollParent();
 }
 
 bool RenderLayerCompositor::requiresCompositingForOutOfFlowClipping(const RenderLayer* layer) const
diff --git a/Source/core/rendering/RenderLayerCompositor.h b/Source/core/rendering/RenderLayerCompositor.h
index 3496bdd..7b80638 100644
--- a/Source/core/rendering/RenderLayerCompositor.h
+++ b/Source/core/rendering/RenderLayerCompositor.h
@@ -99,10 +99,13 @@
     bool updateLayerCompositingState(RenderLayer*, CompositingChangeRepaint = CompositingChangeRepaintNow);
 
     // Update the geometry for compositing children of compositingAncestor.
-    void updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer*, bool compositedChildrenOnly);
+    void updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer*, HashSet<RenderLayer*>& visited, bool compositedChildrenOnly);
+
+    // Ensures that scroll parents have been processed before recurring into updateCompositedDescendantGeometry for the current layer.
+    void updateCompositingDescendantGeometryForLayerAndScrollParents(RenderLayer* compositingAncestor, RenderLayer*, HashSet<RenderLayer*>& visited, bool compositedChildrenOnly);
 
     // Whether layer's backing needs a graphics layer to do clipping by an ancestor (non-stacking-context parent with overflow).
-    bool clippedByAncestor(RenderLayer*) const;
+    bool clippedByAncestor(const RenderLayer*) const;
     // Whether layer's backing needs a graphics layer to clip z-order children of the given layer.
     bool clipsCompositingDescendants(const RenderLayer*) const;
 
@@ -241,10 +244,16 @@
     void computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer*, OverlapMap*, struct CompositingState&, bool& layersChanged, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants);
 
     // Recurses down the tree, parenting descendant compositing layers and collecting an array of child layers for the current compositing layer.
-    void rebuildCompositingLayerTree(RenderLayer*, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, int depth);
+    void rebuildCompositingLayerTree(RenderLayer*, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, HashSet<RenderLayer*>& visited, int depth);
+
+    // Ensures that scroll parents have been processed before recurring into rebuildCompositingLayerTree for the current layer.
+    void rebuildCompositingLayerTreeForLayerAndScrollParents(RenderLayer*, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, HashSet<RenderLayer*>& visited, HashMap<RenderLayer*, Vector<GraphicsLayer*> >& childGraphicsLayersOfScrollParents, int depth);
 
     // Recurses down the tree, updating layer geometry only.
-    void updateLayerTreeGeometry(RenderLayer*, int depth);
+    void updateLayerTreeGeometry(RenderLayer*, HashSet<RenderLayer*>& visited, int depth);
+
+    // Ensures that scroll parents have been processed before recurring into updateLayerTree for the current layer.
+    void updateLayerTreeGeometryForLayerAndScrollParents(RenderLayer*, HashSet<RenderLayer*>& visited, int depth);
 
     // Hook compositing layers together
     void setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer);
diff --git a/Source/core/rendering/RenderLayerScrollableArea.cpp b/Source/core/rendering/RenderLayerScrollableArea.cpp
index 24222c1..08d919c 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.cpp
+++ b/Source/core/rendering/RenderLayerScrollableArea.cpp
@@ -44,6 +44,7 @@
 #include "config.h"
 #include "core/rendering/RenderLayer.h"
 
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/FrameSelection.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/EventHandler.h"
@@ -52,7 +53,9 @@
 #include "core/page/Page.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/ScrollAnimator.h"
+#include "core/platform/graphics/GraphicsLayer.h"
 #include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderView.h"
 
 namespace WebCore {
@@ -60,6 +63,7 @@
 RenderLayerScrollableArea::RenderLayerScrollableArea(RenderLayer* layer)
     : m_layer(layer)
     , m_scrollDimensionsDirty(true)
+    , m_inOverflowRelayout(false)
 {
     ScrollableArea::setConstrainsScrollingToContentEdge(false);
 
@@ -94,16 +98,8 @@
             toElement(node)->setSavedLayerScrollOffset(m_scrollOffset);
     }
 
-}
-
-Scrollbar* RenderLayerScrollableArea::horizontalScrollbar() const
-{
-    return m_layer->horizontalScrollbar();
-}
-
-Scrollbar* RenderLayerScrollableArea::verticalScrollbar() const
-{
-    return m_layer->verticalScrollbar();
+    destroyScrollbar(HorizontalScrollbar);
+    destroyScrollbar(VerticalScrollbar);
 }
 
 ScrollableArea* RenderLayerScrollableArea::enclosingScrollableArea() const
@@ -143,7 +139,29 @@
 
 void RenderLayerScrollableArea::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
 {
-    m_layer->invalidateScrollbarRect(scrollbar, rect);
+    if (scrollbar == m_vBar.get()) {
+        if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
+            layer->setNeedsDisplayInRect(rect);
+            return;
+        }
+    } else {
+        if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
+            layer->setNeedsDisplayInRect(rect);
+            return;
+        }
+    }
+
+    IntRect scrollRect = rect;
+    RenderBox* box = toRenderBox(renderer());
+    // If we are not yet inserted into the tree, there is no need to repaint.
+    if (!box->parent())
+        return;
+
+    if (scrollbar == m_vBar.get())
+        scrollRect.move(verticalScrollbarStart(0, box->width()), box->borderTop());
+    else
+        scrollRect.move(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
+    renderer()->repaintRectangle(scrollRect);
 }
 
 void RenderLayerScrollableArea::invalidateScrollCornerRect(const IntRect& rect)
@@ -166,24 +184,50 @@
     return m_layer->scrollCornerRect();
 }
 
-IntRect RenderLayerScrollableArea::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& rect) const
+IntRect RenderLayerScrollableArea::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
 {
-    return m_layer->convertFromScrollbarToContainingView(scrollbar, rect);
+    RenderView* view = renderer()->view();
+    if (!view)
+        return scrollbarRect;
+
+    IntRect rect = scrollbarRect;
+    rect.move(scrollbarOffset(scrollbar));
+
+    return view->frameView()->convertFromRenderer(renderer(), rect);
 }
 
-IntRect RenderLayerScrollableArea::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& rect) const
+IntRect RenderLayerScrollableArea::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
 {
-    return m_layer->convertFromContainingViewToScrollbar(scrollbar, rect);
+    RenderView* view = renderer()->view();
+    if (!view)
+        return parentRect;
+
+    IntRect rect = view->frameView()->convertToRenderer(renderer(), parentRect);
+    rect.move(-scrollbarOffset(scrollbar));
+    return rect;
 }
 
-IntPoint RenderLayerScrollableArea::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& point) const
+IntPoint RenderLayerScrollableArea::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& scrollbarPoint) const
 {
-    return m_layer->convertFromScrollbarToContainingView(scrollbar, point);
+    RenderView* view = renderer()->view();
+    if (!view)
+        return scrollbarPoint;
+
+    IntPoint point = scrollbarPoint;
+    point.move(scrollbarOffset(scrollbar));
+    return view->frameView()->convertFromRenderer(renderer(), point);
 }
 
-IntPoint RenderLayerScrollableArea::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& point) const
+IntPoint RenderLayerScrollableArea::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
 {
-    return m_layer->convertFromContainingViewToScrollbar(scrollbar, point);
+    RenderView* view = renderer()->view();
+    if (!view)
+        return parentPoint;
+
+    IntPoint point = view->frameView()->convertToRenderer(renderer(), parentPoint);
+
+    point.move(-scrollbarOffset(scrollbar));
+    return point;
 }
 
 int RenderLayerScrollableArea::scrollSize(ScrollbarOrientation orientation) const
@@ -388,12 +432,17 @@
 
 void RenderLayerScrollableArea::updateAfterLayout()
 {
+    RenderBox* box = toRenderBox(renderer());
+    // List box parts handle the scrollbars by themselves so we have nothing to do.
+    if (box->style()->appearance() == ListboxPart)
+        return;
+
     m_scrollDimensionsDirty = true;
     IntSize originalScrollOffset = adjustedScrollOffset();
 
     computeScrollDimensions();
 
-    if (!toRenderBox(renderer())->isMarquee()) {
+    if (!box->isMarquee()) {
         // Layout may cause us to be at an invalid scroll position. In this case we need
         // to pull our scroll offsets back to the max (or push them up to the min).
         IntSize clampedScrollOffset = clampScrollOffset(adjustedScrollOffset());
@@ -403,6 +452,63 @@
 
     if (originalScrollOffset != adjustedScrollOffset())
         scrollToOffsetWithoutAnimation(-scrollOrigin() + adjustedScrollOffset());
+
+    bool hasHorizontalOverflow = this->hasHorizontalOverflow();
+    bool hasVerticalOverflow = this->hasVerticalOverflow();
+
+    // overflow:scroll should just enable/disable.
+    if (renderer()->style()->overflowX() == OSCROLL)
+        horizontalScrollbar()->setEnabled(hasHorizontalOverflow);
+    if (renderer()->style()->overflowY() == OSCROLL)
+        verticalScrollbar()->setEnabled(hasVerticalOverflow);
+
+    // overflow:auto may need to lay out again if scrollbars got added/removed.
+    bool autoHorizontalScrollBarChanged = box->hasAutoHorizontalScrollbar() && (hasHorizontalScrollbar() != hasHorizontalOverflow);
+    bool autoVerticalScrollBarChanged = box->hasAutoVerticalScrollbar() && (hasVerticalScrollbar() != hasVerticalOverflow);
+
+    if (autoHorizontalScrollBarChanged || autoVerticalScrollBarChanged) {
+        if (box->hasAutoHorizontalScrollbar())
+            setHasHorizontalScrollbar(hasHorizontalOverflow);
+        if (box->hasAutoVerticalScrollbar())
+            setHasVerticalScrollbar(hasVerticalOverflow);
+
+        m_layer->updateSelfPaintingLayer();
+
+        // Force an update since we know the scrollbars have changed things.
+        if (renderer()->document().hasAnnotatedRegions())
+            renderer()->document().setAnnotatedRegionsDirty(true);
+
+        renderer()->repaint();
+
+        if (renderer()->style()->overflowX() == OAUTO || renderer()->style()->overflowY() == OAUTO) {
+            if (!m_inOverflowRelayout) {
+                // Our proprietary overflow: overlay value doesn't trigger a layout.
+                m_inOverflowRelayout = true;
+                SubtreeLayoutScope layoutScope(renderer());
+                layoutScope.setNeedsLayout(renderer());
+                if (renderer()->isRenderBlock()) {
+                    RenderBlock* block = toRenderBlock(renderer());
+                    block->scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
+                    block->layoutBlock(true);
+                } else {
+                    renderer()->layout();
+                }
+                m_inOverflowRelayout = false;
+            }
+        }
+    }
+
+    // Set up the range (and page step/line step).
+    if (Scrollbar* horizontalScrollbar = this->horizontalScrollbar()) {
+        int clientWidth = box->pixelSnappedClientWidth();
+        horizontalScrollbar->setProportion(clientWidth, overflowRect().width());
+    }
+    if (Scrollbar* verticalScrollbar = this->verticalScrollbar()) {
+        int clientHeight = box->pixelSnappedClientHeight();
+        verticalScrollbar->setProportion(clientHeight, overflowRect().height());
+    }
+
+    m_layer->updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
 }
 
 bool RenderLayerScrollableArea::hasHorizontalOverflow() const
@@ -429,10 +535,57 @@
     return hasVerticalOverflow() && toRenderBox(renderer())->scrollsOverflowY();
 }
 
-void RenderLayerScrollableArea::updateAfterStyleChange(const RenderStyle*)
+static bool overflowRequiresScrollbar(EOverflow overflow)
 {
+    return overflow == OSCROLL;
+}
+
+static bool overflowDefinesAutomaticScrollbar(EOverflow overflow)
+{
+    return overflow == OAUTO || overflow == OOVERLAY;
+}
+
+void RenderLayerScrollableArea::updateAfterStyleChange(const RenderStyle* oldStyle)
+{
+    // Overflow are a box concept.
+    if (!renderer()->isBox())
+        return;
+
+    RenderBox* box = toRenderBox(renderer());
+
+    // List box parts handle the scrollbars by themselves so we have nothing to do.
+    if (box->style()->appearance() == ListboxPart)
+        return;
+
     if (!m_scrollDimensionsDirty)
         m_layer->updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
+
+    EOverflow overflowX = box->style()->overflowX();
+    EOverflow overflowY = box->style()->overflowY();
+
+    // To avoid doing a relayout in updateScrollbarsAfterLayout, we try to keep any automatic scrollbar that was already present.
+    bool needsHorizontalScrollbar = (hasHorizontalScrollbar() && overflowDefinesAutomaticScrollbar(overflowX)) || overflowRequiresScrollbar(overflowX);
+    bool needsVerticalScrollbar = (hasVerticalScrollbar() && overflowDefinesAutomaticScrollbar(overflowY)) || overflowRequiresScrollbar(overflowY);
+    setHasHorizontalScrollbar(needsHorizontalScrollbar);
+    setHasVerticalScrollbar(needsVerticalScrollbar);
+
+    // With overflow: scroll, scrollbars are always visible but may be disabled.
+    // When switching to another value, we need to re-enable them (see bug 11985).
+    if (needsHorizontalScrollbar && oldStyle && oldStyle->overflowX() == OSCROLL && overflowX != OSCROLL) {
+        ASSERT(hasHorizontalScrollbar());
+        m_hBar->setEnabled(true);
+    }
+
+    if (needsVerticalScrollbar && oldStyle && oldStyle->overflowY() == OSCROLL && overflowY != OSCROLL) {
+        ASSERT(hasVerticalScrollbar());
+        m_vBar->setEnabled(true);
+    }
+
+    // FIXME: Need to detect a swap from custom to native scrollbars (and vice versa).
+    if (m_hBar)
+        m_hBar->styleChanged();
+    if (m_vBar)
+        m_vBar->styleChanged();
 }
 
 IntSize RenderLayerScrollableArea::clampScrollOffset(const IntSize& scrollOffset) const
@@ -447,4 +600,255 @@
     return IntSize(x, y);
 }
 
+IntRect RenderLayerScrollableArea::rectForHorizontalScrollbar(const IntRect& borderBoxRect) const
+{
+    if (!m_hBar)
+        return IntRect();
+
+    const RenderBox* box = toRenderBox(renderer());
+    const IntRect& scrollCorner = scrollCornerRect();
+
+    return IntRect(horizontalScrollbarStart(borderBoxRect.x()),
+        borderBoxRect.maxY() - box->borderBottom() - m_hBar->height(),
+        borderBoxRect.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
+        m_hBar->height());
+}
+
+IntRect RenderLayerScrollableArea::rectForVerticalScrollbar(const IntRect& borderBoxRect) const
+{
+    if (!m_vBar)
+        return IntRect();
+
+    const RenderBox* box = toRenderBox(renderer());
+    const IntRect& scrollCorner = scrollCornerRect();
+
+    return IntRect(verticalScrollbarStart(borderBoxRect.x(), borderBoxRect.maxX()),
+        borderBoxRect.y() + box->borderTop(),
+        m_vBar->width(),
+        borderBoxRect.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height());
+}
+
+LayoutUnit RenderLayerScrollableArea::verticalScrollbarStart(int minX, int maxX) const
+{
+    const RenderBox* box = toRenderBox(renderer());
+    if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+        return minX + box->borderLeft();
+    return maxX - box->borderRight() - m_vBar->width();
+}
+
+LayoutUnit RenderLayerScrollableArea::horizontalScrollbarStart(int minX) const
+{
+    const RenderBox* box = toRenderBox(renderer());
+    int x = minX + box->borderLeft();
+    if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+        x += m_vBar ? m_vBar->width() : m_layer->resizerCornerRect(box->pixelSnappedBorderBoxRect(), ResizerForPointer).width();
+    return x;
+}
+
+IntSize RenderLayerScrollableArea::scrollbarOffset(const Scrollbar* scrollbar) const
+{
+    RenderBox* box = toRenderBox(renderer());
+
+    if (scrollbar == m_vBar.get())
+        return IntSize(verticalScrollbarStart(0, box->width()), box->borderTop());
+
+    if (scrollbar == m_hBar.get())
+        return IntSize(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
+
+    ASSERT_NOT_REACHED();
+    return IntSize();
+}
+
+static inline RenderObject* rendererForScrollbar(RenderObject* renderer)
+{
+    if (Node* node = renderer->node()) {
+        if (ShadowRoot* shadowRoot = node->containingShadowRoot()) {
+            if (shadowRoot->type() == ShadowRoot::UserAgentShadowRoot)
+                return shadowRoot->host()->renderer();
+        }
+    }
+
+    return renderer;
+}
+
+PassRefPtr<Scrollbar> RenderLayerScrollableArea::createScrollbar(ScrollbarOrientation orientation)
+{
+    RefPtr<Scrollbar> widget;
+    RenderObject* actualRenderer = rendererForScrollbar(renderer());
+    bool hasCustomScrollbarStyle = actualRenderer->isBox() && actualRenderer->style()->hasPseudoStyle(SCROLLBAR);
+    if (hasCustomScrollbarStyle) {
+        widget = RenderScrollbar::createCustomScrollbar(this, orientation, actualRenderer->node());
+    } else {
+        widget = Scrollbar::create(this, orientation, RegularScrollbar);
+        if (orientation == HorizontalScrollbar)
+            didAddHorizontalScrollbar(widget.get());
+        else
+            didAddVerticalScrollbar(widget.get());
+    }
+    renderer()->document().view()->addChild(widget.get());
+    return widget.release();
+}
+
+void RenderLayerScrollableArea::destroyScrollbar(ScrollbarOrientation orientation)
+{
+    RefPtr<Scrollbar>& scrollbar = orientation == HorizontalScrollbar ? m_hBar : m_vBar;
+    if (!scrollbar)
+        return;
+
+    if (!scrollbar->isCustomScrollbar()) {
+        if (orientation == HorizontalScrollbar)
+            willRemoveHorizontalScrollbar(scrollbar.get());
+        else
+            willRemoveVerticalScrollbar(scrollbar.get());
+    }
+
+    scrollbar->removeFromParent();
+    scrollbar->disconnectFromScrollableArea();
+    scrollbar = 0;
+}
+
+void RenderLayerScrollableArea::setHasHorizontalScrollbar(bool hasScrollbar)
+{
+    if (hasScrollbar == hasHorizontalScrollbar())
+        return;
+
+    if (hasScrollbar)
+        m_hBar = createScrollbar(HorizontalScrollbar);
+    else
+        destroyScrollbar(HorizontalScrollbar);
+
+    // Destroying or creating one bar can cause our scrollbar corner to come and go. We need to update the opposite scrollbar's style.
+    if (m_hBar)
+        m_hBar->styleChanged();
+    if (m_vBar)
+        m_vBar->styleChanged();
+
+    // Force an update since we know the scrollbars have changed things.
+    if (renderer()->document().hasAnnotatedRegions())
+        renderer()->document().setAnnotatedRegionsDirty(true);
+}
+
+void RenderLayerScrollableArea::setHasVerticalScrollbar(bool hasScrollbar)
+{
+    if (hasScrollbar == hasVerticalScrollbar())
+        return;
+
+    if (hasScrollbar)
+        m_vBar = createScrollbar(VerticalScrollbar);
+    else
+        destroyScrollbar(VerticalScrollbar);
+
+    // Destroying or creating one bar can cause our scrollbar corner to come and go. We need to update the opposite scrollbar's style.
+    if (m_hBar)
+        m_hBar->styleChanged();
+    if (m_vBar)
+        m_vBar->styleChanged();
+
+    // Force an update since we know the scrollbars have changed things.
+    if (renderer()->document().hasAnnotatedRegions())
+        renderer()->document().setAnnotatedRegionsDirty(true);
+}
+
+int RenderLayerScrollableArea::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
+{
+    if (!m_vBar || (m_vBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_vBar->shouldParticipateInHitTesting())))
+        return 0;
+    return m_vBar->width();
+}
+
+int RenderLayerScrollableArea::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
+{
+    if (!m_hBar || (m_hBar->isOverlayScrollbar() && (relevancy == IgnoreOverlayScrollbarSize || !m_hBar->shouldParticipateInHitTesting())))
+        return 0;
+    return m_hBar->height();
+}
+
+
+void RenderLayerScrollableArea::positionOverflowControls(const IntSize& offsetFromRoot)
+{
+    const IntRect borderBox = toRenderBox(renderer())->pixelSnappedBorderBoxRect();
+    if (Scrollbar* verticalScrollbar = this->verticalScrollbar()) {
+        IntRect vBarRect = rectForVerticalScrollbar(borderBox);
+        vBarRect.move(offsetFromRoot);
+        verticalScrollbar->setFrameRect(vBarRect);
+    }
+
+    if (Scrollbar* horizontalScrollbar = this->horizontalScrollbar()) {
+        IntRect hBarRect = rectForHorizontalScrollbar(borderBox);
+        hBarRect.move(offsetFromRoot);
+        horizontalScrollbar->setFrameRect(hBarRect);
+    }
+}
+
+// FIXME: Move m_cachedOverlayScrollbarOffset.
+void RenderLayerScrollableArea::paintOverflowControls(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
+{
+    // Overlay scrollbars paint in a second pass through the layer tree so that they will paint
+    // on top of everything else. If this is the normal painting pass, paintingOverlayControls
+    // will be false, and we should just tell the root layer that there are overlay scrollbars
+    // that need to be painted. That will cause the second pass through the layer tree to run,
+    // and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the
+    // second pass doesn't need to re-enter the RenderTree to get it right.
+    if (hasOverlayScrollbars() && !paintingOverlayControls) {
+        m_layer->m_cachedOverlayScrollbarOffset = paintOffset;
+        // It's not necessary to do the second pass if the scrollbars paint into layers.
+        if ((m_hBar && layerForHorizontalScrollbar()) || (m_vBar && layerForVerticalScrollbar()))
+            return;
+        IntRect localDamgeRect = damageRect;
+        localDamgeRect.moveBy(-paintOffset);
+        if (!m_layer->overflowControlsIntersectRect(localDamgeRect))
+            return;
+
+        RenderView* renderView = renderer()->view();
+
+        RenderLayer* paintingRoot = m_layer->enclosingCompositingLayer();
+        if (!paintingRoot)
+            paintingRoot = renderView->layer();
+
+        paintingRoot->setContainsDirtyOverlayScrollbars(true);
+        return;
+    }
+
+    // This check is required to avoid painting custom CSS scrollbars twice.
+    if (paintingOverlayControls && !hasOverlayScrollbars())
+        return;
+
+    // Now that we're sure the scrollbars are in the right place, paint them.
+    if (m_hBar && !layerForHorizontalScrollbar())
+        m_hBar->paint(context, damageRect);
+    if (m_vBar && !layerForVerticalScrollbar())
+        m_vBar->paint(context, damageRect);
+}
+
+bool RenderLayerScrollableArea::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint, const IntRect& resizeControlRect)
+{
+    RenderBox* box = toRenderBox(renderer());
+
+    int resizeControlSize = max(resizeControlRect.height(), 0);
+    if (m_vBar && m_vBar->shouldParticipateInHitTesting()) {
+        LayoutRect vBarRect(verticalScrollbarStart(0, box->width()),
+            box->borderTop(),
+            m_vBar->width(),
+            box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
+        if (vBarRect.contains(localPoint)) {
+            result.setScrollbar(m_vBar.get());
+            return true;
+        }
+    }
+
+    resizeControlSize = max(resizeControlRect.width(), 0);
+    if (m_hBar && m_hBar->shouldParticipateInHitTesting()) {
+        LayoutRect hBarRect(horizontalScrollbarStart(0),
+            box->height() - box->borderBottom() - m_hBar->height(),
+            box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
+            m_hBar->height());
+        if (hBarRect.contains(localPoint)) {
+            result.setScrollbar(m_hBar.get());
+            return true;
+        }
+    }
+
+    return false;
+}
+
 } // Namespace WebCore
diff --git a/Source/core/rendering/RenderLayerScrollableArea.h b/Source/core/rendering/RenderLayerScrollableArea.h
index 7d467fd..ea9153e 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.h
+++ b/Source/core/rendering/RenderLayerScrollableArea.h
@@ -68,8 +68,8 @@
     RenderLayerScrollableArea(RenderLayer*);
     virtual ~RenderLayerScrollableArea();
 
-    virtual Scrollbar* horizontalScrollbar() const OVERRIDE;
-    virtual Scrollbar* verticalScrollbar() const OVERRIDE;
+    virtual Scrollbar* horizontalScrollbar() const OVERRIDE { return m_hBar.get(); }
+    virtual Scrollbar* verticalScrollbar() const OVERRIDE { return m_vBar.get(); }
     virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
 
     virtual void updateNeedsCompositedScrolling() OVERRIDE;
@@ -119,6 +119,8 @@
     void updateAfterLayout();
     void updateAfterStyleChange(const RenderStyle*);
 
+    bool hasScrollbar() { return m_hBar || m_vBar; }
+
 private:
     bool hasHorizontalOverflow() const;
     bool hasVerticalOverflow() const;
@@ -135,17 +137,44 @@
 
     void setScrollOffset(const IntSize& scrollOffset) { m_scrollOffset = scrollOffset; }
 
+    IntRect rectForHorizontalScrollbar(const IntRect& borderBoxRect) const;
+    IntRect rectForVerticalScrollbar(const IntRect& borderBoxRect) const;
+    LayoutUnit verticalScrollbarStart(int minX, int maxX) const;
+    LayoutUnit horizontalScrollbarStart(int minX) const;
+    IntSize scrollbarOffset(const Scrollbar*) const;
+
+    PassRefPtr<Scrollbar> createScrollbar(ScrollbarOrientation);
+    void destroyScrollbar(ScrollbarOrientation);
+
+    bool hasHorizontalScrollbar() const { return horizontalScrollbar(); }
+    bool hasVerticalScrollbar() const { return verticalScrollbar(); }
+
+    void setHasHorizontalScrollbar(bool hasScrollbar);
+    void setHasVerticalScrollbar(bool hasScrollbar);
+
+    int verticalScrollbarWidth(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
+    int horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
+
+    void positionOverflowControls(const IntSize& offsetFromRoot);
+    void paintOverflowControls(GraphicsContext*, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls);
+    bool hitTestOverflowControls(HitTestResult&, const IntPoint& localPoint, const IntRect&);
+
     RenderLayerModelObject* renderer() const;
 
     RenderLayer* m_layer;
 
     unsigned m_scrollDimensionsDirty : 1;
+    unsigned m_inOverflowRelayout : 1;
 
     // The width/height of our scrolled area.
     LayoutRect m_overflowRect;
 
     // This is the (scroll) offset from scrollOrigin().
     IntSize m_scrollOffset;
+
+    // For areas with overflow, we have a pair of scrollbars.
+    RefPtr<Scrollbar> m_hBar;
+    RefPtr<Scrollbar> m_vBar;
 };
 
 } // Namespace WebCore
diff --git a/Source/core/rendering/RenderNamedFlowThread.cpp b/Source/core/rendering/RenderNamedFlowThread.cpp
index 8df2c92..7d25ae6 100644
--- a/Source/core/rendering/RenderNamedFlowThread.cpp
+++ b/Source/core/rendering/RenderNamedFlowThread.cpp
@@ -237,9 +237,9 @@
 // This helper function adds a region to a list preserving the order property of the list.
 static void addRegionToList(RenderRegionList& regionList, RenderRegion* renderRegion)
 {
-    if (regionList.isEmpty())
+    if (regionList.isEmpty()) {
         regionList.add(renderRegion);
-    else {
+    } else {
         // Find the first region "greater" than renderRegion.
         RenderRegionList::iterator it = regionList.begin();
         while (it != regionList.end() && !compareRenderRegions(renderRegion, *it))
@@ -567,6 +567,17 @@
         && logicalTopForBox < logicalBottomForRegion && logicalTopForRegion < logicalBottomForBox;
 }
 
+// Retrieve the next node to be visited while computing the ranges inside a region.
+static Node* nextNodeInsideContentNode(const Node* currNode, const Node* contentNode)
+{
+    ASSERT(currNode);
+    ASSERT(contentNode && contentNode->inNamedFlow());
+
+    if (currNode->renderer() && currNode->renderer()->isSVGRoot())
+        return NodeTraversal::nextSkippingChildren(currNode, contentNode);
+    return NodeTraversal::next(currNode, contentNode);
+}
+
 void RenderNamedFlowThread::getRanges(Vector<RefPtr<Range> >& rangeObjects, const RenderRegion* region) const
 {
     LayoutUnit logicalTopForRegion;
@@ -604,17 +615,17 @@
         bool skipOverOutsideNodes = false;
         Node* lastEndNode = 0;
 
-        for (Node* node = contentNode; node; node = NodeTraversal::next(node, contentNode)) {
+        for (Node* node = contentNode; node; node = nextNodeInsideContentNode(node, contentNode)) {
             RenderObject* renderer = node->renderer();
             if (!renderer)
                 continue;
 
             LayoutRect boundingBox;
-            if (renderer->isRenderInline())
+            if (renderer->isRenderInline()) {
                 boundingBox = toRenderInline(renderer)->linesBoundingBox();
-            else if (renderer->isText())
+            } else if (renderer->isText()) {
                 boundingBox = toRenderText(renderer)->linesBoundingBox();
-            else {
+            } else {
                 boundingBox =  toRenderBox(renderer)->frameRect();
                 if (toRenderBox(renderer)->isRelPositioned())
                     boundingBox.move(toRenderBox(renderer)->relativePositionLogicalOffset());
@@ -640,8 +651,9 @@
                         rangeObjects.append(range->cloneRange(IGNORE_EXCEPTION));
                         range = Range::create(contentNode->document());
                         startsAboveRegion = true;
-                    } else
+                    } else {
                         skipOverOutsideNodes = true;
+                    }
                 }
                 if (skipOverOutsideNodes)
                     range->setStartAfter(node, IGNORE_EXCEPTION);
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index c479fff..4f87cef 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -1390,7 +1390,7 @@
     if (!isRooted(&view))
         return;
 
-    if (view->printing())
+    if (view->document().printing())
         return; // Don't repaint if we're printing.
 
     RenderLayerModelObject* repaintContainer = containerForRepaint();
@@ -1404,7 +1404,7 @@
     if (!isRooted(&view))
         return;
 
-    if (view->printing())
+    if (view->document().printing())
         return; // Don't repaint if we're printing.
 
     LayoutRect dirtyRect(r);
@@ -1426,7 +1426,7 @@
 bool RenderObject::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
 {
     RenderView* v = view();
-    if (v->printing())
+    if (v->document().printing())
         return false; // Don't repaint if we're printing.
 
     // This ASSERT fails due to animations.  See https://bugs.webkit.org/show_bug.cgi?id=37048
@@ -2848,7 +2848,7 @@
 
 PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
 {
-    if (!document().styleSheetCollections()->usesFirstLineRules())
+    if (!document().styleEngine()->usesFirstLineRules())
         return 0;
 
     ASSERT(!isText());
@@ -2858,7 +2858,7 @@
 
 RenderStyle* RenderObject::cachedFirstLineStyle() const
 {
-    ASSERT(document().styleSheetCollections()->usesFirstLineRules());
+    ASSERT(document().styleEngine()->usesFirstLineRules());
 
     if (RefPtr<RenderStyle> style = firstLineStyleForCachedUncachedType(Cached, isText() ? parent() : this, m_style.get()))
         return style.get();
@@ -3297,6 +3297,15 @@
     return false;
 }
 
+bool RenderObject::isContainedInParentBoundingBox() const
+{
+    if (!parent())
+        return false;
+
+    IntRect parentRect = parent()->absoluteBoundingBoxRect();
+    return parentRect.contains(absoluteBoundingBoxRect());
+}
+
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/RenderObject.h b/Source/core/rendering/RenderObject.h
index 004d59b..272d765 100644
--- a/Source/core/rendering/RenderObject.h
+++ b/Source/core/rendering/RenderObject.h
@@ -28,7 +28,7 @@
 
 #include "core/dom/Element.h"
 #include "core/dom/Position.h"
-#include "core/dom/StyleSheetCollections.h"
+#include "core/dom/StyleEngine.h"
 #include "core/fetch/ImageResourceClient.h"
 #include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/LayoutRect.h"
@@ -231,6 +231,19 @@
         RenderObject* m_renderObject;
         bool m_preexistingForbidden;
     };
+
+    void assertRendererLaidOut() const
+    {
+        if (needsLayout())
+            showRenderTreeForThis();
+        ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
+    }
+
+    void assertSubtreeIsLaidOut() const
+    {
+        for (const RenderObject* renderer = this; renderer; renderer = renderer->nextInPreOrder())
+            renderer->assertRendererLaidOut();
+    }
 #endif
 
     // Obtains the nearest enclosing block (including this block) that contributes a first-line style to our inline
@@ -747,6 +760,8 @@
     IntRect absoluteBoundingBoxRect(bool useTransform = true) const;
     IntRect absoluteBoundingBoxRectIgnoringTransforms() const { return absoluteBoundingBoxRect(false); }
 
+    bool isContainedInParentBoundingBox() const;
+
     // Build an array of quads in absolute coords for line boxes
     virtual void absoluteQuads(Vector<FloatQuad>&, bool* /*wasFixed*/ = 0) const { }
 
@@ -761,7 +776,7 @@
     virtual LayoutUnit maxPreferredLogicalWidth() const { return 0; }
 
     RenderStyle* style() const { return m_style.get(); }
-    RenderStyle* firstLineStyle() const { return document().styleSheetCollections()->usesFirstLineRules() ? cachedFirstLineStyle() : style(); }
+    RenderStyle* firstLineStyle() const { return document().styleEngine()->usesFirstLineRules() ? cachedFirstLineStyle() : style(); }
     RenderStyle* style(bool firstLine) const { return firstLine ? firstLineStyle() : style(); }
 
     inline Color resolveColor(const RenderStyle* styleToUse, int colorProperty) const
@@ -1366,6 +1381,7 @@
 // We don't make object2 an optional parameter so that showRenderTree
 // can be called from gdb easily.
 void showRenderTree(const WebCore::RenderObject* object1, const WebCore::RenderObject* object2);
+
 #endif
 
 #endif // RenderObject_h
diff --git a/Source/core/rendering/RenderReplaced.cpp b/Source/core/rendering/RenderReplaced.cpp
index 596957a..900fa7d 100644
--- a/Source/core/rendering/RenderReplaced.cpp
+++ b/Source/core/rendering/RenderReplaced.cpp
@@ -24,6 +24,7 @@
 #include "config.h"
 #include "core/rendering/RenderReplaced.h"
 
+#include "RuntimeEnabledFeatures.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderBlock.h"
@@ -314,8 +315,12 @@
 {
     LayoutRect contentRect = contentBoxRect();
     ObjectFit objectFit = style()->objectFit();
-    if (objectFit == ObjectFitFill)
-        return contentRect;
+
+    if (objectFit == ObjectFitFill) {
+        if (!isVideo() || RuntimeEnabledFeatures::objectFitPositionEnabled())
+            return contentRect;
+        objectFit = ObjectFitContain;
+    }
 
     LayoutSize intrinsicSize = overriddenIntrinsicSize ? *overriddenIntrinsicSize : this->intrinsicSize();
     if (!intrinsicSize.width() || !intrinsicSize.height())
diff --git a/Source/core/rendering/RenderTable.cpp b/Source/core/rendering/RenderTable.cpp
index bf35210..2979a16 100644
--- a/Source/core/rendering/RenderTable.cpp
+++ b/Source/core/rendering/RenderTable.cpp
@@ -417,8 +417,6 @@
 
     setLogicalHeight(0);
 
-    initMaxMarginValues();
-
     LayoutUnit oldLogicalWidth = logicalWidth();
     updateLogicalWidth();
 
diff --git a/Source/core/rendering/RenderTableSection.cpp b/Source/core/rendering/RenderTableSection.cpp
index 4fb5a07..b49f47f 100644
--- a/Source/core/rendering/RenderTableSection.cpp
+++ b/Source/core/rendering/RenderTableSection.cpp
@@ -528,6 +528,9 @@
         m_rowPos[0] = 0;
 
     SpanningRenderTableCells rowSpanCells;
+#ifndef NDEBUG
+    HashSet<const RenderTableCell*> uniqueCells;
+#endif
 
     for (unsigned r = 0; r < m_grid.size(); r++) {
         m_grid[r].baseline = 0;
@@ -538,6 +541,7 @@
 
         Row& row = m_grid[r].row;
         unsigned totalCols = row.size();
+        RenderTableCell* lastRowSpanCell = 0;
 
         for (unsigned c = 0; c < totalCols; c++) {
             CellStruct& current = cellAt(r, c);
@@ -549,8 +553,14 @@
                 if (RuntimeEnabledFeatures::rowSpanLogicalHeightSpreadingEnabled()) {
                     if (cell->rowSpan() > 1) {
                         // For row spanning cells, we only handle them for the first row they span. This ensures we take their baseline into account.
-                        if (cell->rowIndex() == r) {
+                        if (lastRowSpanCell != cell && cell->rowIndex() == r) {
+#ifndef NDEBUG
+                            ASSERT(!uniqueCells.contains(cell));
+                            uniqueCells.add(cell);
+#endif
+
                             rowSpanCells.append(cell);
+                            lastRowSpanCell = cell;
 
                             // Find out the baseline. The baseline is set on the first row in a rowSpan.
                             updateBaselineForCell(cell, r, baselineDescent);
@@ -1171,7 +1181,11 @@
 {
     ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
 
-    ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
+    // put this back in when all layout tests can handle it
+    // ASSERT(!needsLayout());
+    // avoid crashing on bugs that cause us to paint with dirty layout
+    if (needsLayout())
+        return;
 
     unsigned totalRows = m_grid.size();
     unsigned totalCols = table()->columns().size();
diff --git a/Source/core/rendering/RenderTextControlSingleLine.cpp b/Source/core/rendering/RenderTextControlSingleLine.cpp
index 98fcf40..3d3985a 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.cpp
+++ b/Source/core/rendering/RenderTextControlSingleLine.cpp
@@ -60,8 +60,8 @@
 
 RenderStyle* RenderTextControlSingleLine::textBaseStyle() const
 {
-    HTMLElement* innerBlock = innerBlockElement();
-    return innerBlock ? innerBlock->renderer()->style() : style();
+    HTMLElement* viewPort = editingViewPortElement();
+    return viewPort ? viewPort->renderer()->style() : style();
 }
 
 void RenderTextControlSingleLine::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
@@ -104,16 +104,16 @@
     // because of compability.
 
     RenderBox* innerTextRenderer = innerTextElement()->renderBox();
-    RenderBox* innerBlockRenderer = innerBlockElement() ? innerBlockElement()->renderBox() : 0;
+    RenderBox* viewPortRenderer = editingViewPortElement() ? editingViewPortElement()->renderBox() : 0;
 
     // To ensure consistency between layouts, we need to reset any conditionally overriden height.
     if (innerTextRenderer && !innerTextRenderer->style()->logicalHeight().isAuto()) {
         innerTextRenderer->style()->setLogicalHeight(Length(Auto));
         layoutScope.setNeedsLayout(innerTextRenderer);
     }
-    if (innerBlockRenderer && !innerBlockRenderer->style()->logicalHeight().isAuto()) {
-        innerBlockRenderer->style()->setLogicalHeight(Length(Auto));
-        layoutScope.setNeedsLayout(innerBlockRenderer);
+    if (viewPortRenderer && !viewPortRenderer->style()->logicalHeight().isAuto()) {
+        viewPortRenderer->style()->setLogicalHeight(Length(Auto));
+        layoutScope.setNeedsLayout(viewPortRenderer);
     }
 
     RenderBlockFlow::layoutBlock(false);
@@ -132,9 +132,9 @@
 
         innerTextRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
         layoutScope.setNeedsLayout(innerTextRenderer);
-        if (innerBlockRenderer) {
-            innerBlockRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
-            layoutScope.setNeedsLayout(innerBlockRenderer);
+        if (viewPortRenderer) {
+            viewPortRenderer->style()->setLogicalHeight(Length(desiredLogicalHeight, Fixed));
+            layoutScope.setNeedsLayout(viewPortRenderer);
         }
     }
     // The container might be taller because of decoration elements.
@@ -185,8 +185,8 @@
         LayoutPoint textOffset;
         if (innerTextRenderer)
             textOffset = innerTextRenderer->location();
-        if (innerBlockElement() && innerBlockElement()->renderBox())
-            textOffset += toLayoutSize(innerBlockElement()->renderBox()->location());
+        if (editingViewPortElement() && editingViewPortElement()->renderBox())
+            textOffset += toLayoutSize(editingViewPortElement()->renderBox()->location());
         if (containerRenderer)
             textOffset += toLayoutSize(containerRenderer->location());
         placeholderBox->setLocation(textOffset);
@@ -215,9 +215,9 @@
     HTMLElement* container = containerElement();
     if (result.innerNode()->isDescendantOf(innerTextElement()) || result.innerNode() == node() || (container && container == result.innerNode())) {
         LayoutPoint pointInParent = locationInContainer.point();
-        if (container && innerBlockElement()) {
-            if (innerBlockElement()->renderBox())
-                pointInParent -= toLayoutSize(innerBlockElement()->renderBox()->location());
+        if (container && editingViewPortElement()) {
+            if (editingViewPortElement()->renderBox())
+                pointInParent -= toLayoutSize(editingViewPortElement()->renderBox()->location());
             if (container->renderBox())
                 pointInParent -= toLayoutSize(container->renderBox()->location());
         }
@@ -233,10 +233,10 @@
 
     // We may have set the width and the height in the old style in layout().
     // Reset them now to avoid getting a spurious layout hint.
-    HTMLElement* innerBlock = innerBlockElement();
-    if (RenderObject* innerBlockRenderer = innerBlock ? innerBlock->renderer() : 0) {
-        innerBlockRenderer->style()->setHeight(Length());
-        innerBlockRenderer->style()->setWidth(Length());
+    HTMLElement* viewPort = editingViewPortElement();
+    if (RenderObject* viewPortRenderer = viewPort ? viewPort->renderer() : 0) {
+        viewPortRenderer->style()->setHeight(Length());
+        viewPortRenderer->style()->setWidth(Length());
     }
     HTMLElement* container = containerElement();
     if (RenderObject* containerRenderer = container ? container->renderer() : 0) {
diff --git a/Source/core/rendering/RenderTextControlSingleLine.h b/Source/core/rendering/RenderTextControlSingleLine.h
index 31f5b52..8a9a986 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.h
+++ b/Source/core/rendering/RenderTextControlSingleLine.h
@@ -43,7 +43,7 @@
     virtual void centerContainerIfNeeded(RenderBox*) const { }
     virtual LayoutUnit computeLogicalHeightLimit() const;
     HTMLElement* containerElement() const;
-    HTMLElement* innerBlockElement() const;
+    HTMLElement* editingViewPortElement() const;
     HTMLInputElement* inputElement() const;
     virtual void updateFromElement() OVERRIDE;
 
@@ -89,9 +89,9 @@
     return inputElement()->containerElement();
 }
 
-inline HTMLElement* RenderTextControlSingleLine::innerBlockElement() const
+inline HTMLElement* RenderTextControlSingleLine::editingViewPortElement() const
 {
-    return inputElement()->innerBlockElement();
+    return inputElement()->editingViewPortElement();
 }
 
 inline RenderTextControlSingleLine* toRenderTextControlSingleLine(RenderObject* object)
diff --git a/Source/core/rendering/RenderTheme.h b/Source/core/rendering/RenderTheme.h
index fc70621..8550b7b 100644
--- a/Source/core/rendering/RenderTheme.h
+++ b/Source/core/rendering/RenderTheme.h
@@ -110,10 +110,6 @@
     // or a control becomes disabled.
     virtual bool stateChanged(RenderObject*, ControlState) const;
 
-    // This method is called whenever the theme changes on the system in order to flush cached resources from the
-    // old theme.
-    virtual void themeChanged() { }
-
     bool shouldDrawDefaultFocusRing(RenderObject*) const;
 
     // A method asking if the theme's controls actually care about redrawing when hovered.
diff --git a/Source/core/rendering/RenderView.cpp b/Source/core/rendering/RenderView.cpp
index c676442..c18c9d0 100644
--- a/Source/core/rendering/RenderView.cpp
+++ b/Source/core/rendering/RenderView.cpp
@@ -251,7 +251,7 @@
 
 void RenderView::layout()
 {
-    if (!document().paginated())
+    if (!configuration().paginated())
         setPageLogicalHeight(0);
 
     if (shouldUsePrintingLayout())
@@ -522,7 +522,7 @@
 
 bool RenderView::shouldRepaint(const LayoutRect& r) const
 {
-    if (printing() || r.width() == 0 || r.height() == 0)
+    if (document().printing() || r.width() == 0 || r.height() == 0)
         return false;
 
     if (!m_frameView)
@@ -585,7 +585,7 @@
     // then we should have found it by now.
     ASSERT_ARG(repaintContainer, !repaintContainer || repaintContainer == this);
 
-    if (printing())
+    if (document().printing())
         return;
 
     if (style()->isFlippedBlocksWritingMode()) {
@@ -879,14 +879,14 @@
     endPos = m_selectionEndPos;
 }
 
-bool RenderView::printing() const
+void RenderView::updateConfiguration()
 {
-    return document().printing();
+    m_configuration.update(document());
 }
 
 bool RenderView::shouldUsePrintingLayout() const
 {
-    if (!printing() || !m_frameView)
+    if (!document().printing() || !m_frameView)
         return false;
     return m_frameView->frame().shouldUsePrintingLayout();
 }
@@ -990,29 +990,29 @@
     return IntRect(overflowRect);
 }
 
-int RenderView::viewHeight() const
+int RenderView::viewHeight(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion) const
 {
     int height = 0;
     if (!shouldUsePrintingLayout() && m_frameView) {
-        height = m_frameView->layoutHeight();
+        height = m_frameView->layoutHeight(scrollbarInclusion);
         height = m_frameView->useFixedLayout() ? ceilf(style()->effectiveZoom() * float(height)) : height;
     }
     return height;
 }
 
-int RenderView::viewWidth() const
+int RenderView::viewWidth(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion) const
 {
     int width = 0;
     if (!shouldUsePrintingLayout() && m_frameView) {
-        width = m_frameView->layoutWidth();
+        width = m_frameView->layoutWidth(scrollbarInclusion);
         width = m_frameView->useFixedLayout() ? ceilf(style()->effectiveZoom() * float(width)) : width;
     }
     return width;
 }
 
-int RenderView::viewLogicalHeight() const
+int RenderView::viewLogicalHeight(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion) const
 {
-    int height = style()->isHorizontalWritingMode() ? viewHeight() : viewWidth();
+    int height = style()->isHorizontalWritingMode() ? viewHeight(scrollbarInclusion) : viewWidth(scrollbarInclusion);
 
     if (hasColumns() && !style()->hasInlineColumnAxis()) {
         if (int pageLength = m_frameView->pagination().pageLength)
@@ -1158,6 +1158,28 @@
     return m_frameView->hasOpaqueBackground();
 }
 
+LayoutUnit RenderView::viewportPercentageWidth(float percentage) const
+{
+    return viewLogicalWidth(ScrollableArea::IncludeScrollbars) * percentage / 100.f;
+}
+
+LayoutUnit RenderView::viewportPercentageHeight(float percentage) const
+{
+    return viewLogicalHeight(ScrollableArea::IncludeScrollbars) * percentage / 100.f;
+}
+
+LayoutUnit RenderView::viewportPercentageMin(float percentage) const
+{
+    return std::min(viewLogicalWidth(ScrollableArea::IncludeScrollbars), viewLogicalHeight(ScrollableArea::IncludeScrollbars))
+        * percentage / 100.f;
+}
+
+LayoutUnit RenderView::viewportPercentageMax(float percentage) const
+{
+    return std::max(viewLogicalWidth(ScrollableArea::IncludeScrollbars), viewLogicalHeight(ScrollableArea::IncludeScrollbars))
+        * percentage / 100.f;
+}
+
 FragmentationDisabler::FragmentationDisabler(RenderObject* root)
 {
     RenderView* renderView = root->view();
diff --git a/Source/core/rendering/RenderView.h b/Source/core/rendering/RenderView.h
index 5bc7ae0..5ac228e 100644
--- a/Source/core/rendering/RenderView.h
+++ b/Source/core/rendering/RenderView.h
@@ -24,8 +24,11 @@
 
 #include "core/page/FrameView.h"
 #include "core/platform/PODFreeListArena.h"
+#include "core/platform/ScrollableArea.h"
+#include "core/rendering/LayoutIndicator.h"
 #include "core/rendering/LayoutState.h"
 #include "core/rendering/RenderBlockFlow.h"
+#include "core/rendering/RenderingConfiguration.h"
 #include "wtf/OwnPtr.h"
 
 namespace WebCore {
@@ -37,7 +40,8 @@
 class RenderWidget;
 
 // The root of the render tree, corresponding to the CSS initial containing block.
-// It's dimensions match that of the viewport, and it is always at position (0,0)
+// It's dimensions match that of the logical viewport (which may be different from
+// the visible viewport in fixed-layout mode), and it is always at position (0,0)
 // relative to the document (and so isn't necessarily in view).
 class RenderView FINAL : public RenderBlockFlow {
 public:
@@ -64,10 +68,13 @@
     virtual LayoutUnit availableLogicalHeight(AvailableLogicalHeightType) const OVERRIDE;
 
     // The same as the FrameView's layoutHeight/layoutWidth but with null check guards.
-    int viewHeight() const;
-    int viewWidth() const;
-    int viewLogicalWidth() const { return style()->isHorizontalWritingMode() ? viewWidth() : viewHeight(); }
-    int viewLogicalHeight() const;
+    int viewHeight(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
+    int viewWidth(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
+    int viewLogicalWidth(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const
+    {
+        return style()->isHorizontalWritingMode() ? viewWidth(scrollbarInclusion) : viewHeight(scrollbarInclusion);
+    }
+    int viewLogicalHeight(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
 
     float zoomFactor() const;
 
@@ -93,7 +100,13 @@
     void selectionStartEnd(int& startPos, int& endPos) const;
     void repaintSelection() const;
 
-    bool printing() const;
+    void updateConfiguration();
+    const RenderingConfiguration& configuration()
+    {
+        // If we're not inLayout(), then the configuration might be out of date.
+        ASSERT(LayoutIndicator::inLayout());
+        return m_configuration;
+    }
 
     virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const;
     virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
@@ -181,8 +194,6 @@
 
     IntervalArena* intervalArena();
 
-    IntSize viewportSize() const { return document().viewportSize(); }
-
     void setRenderQuoteHead(RenderQuote* head) { m_renderQuoteHead = head; }
     RenderQuote* renderQuoteHead() const { return m_renderQuoteHead; }
 
@@ -198,14 +209,18 @@
 
     virtual bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const OVERRIDE FINAL;
 
-protected:
+    LayoutUnit viewportPercentageWidth(float percentage) const;
+    LayoutUnit viewportPercentageHeight(float percentage) const;
+    LayoutUnit viewportPercentageMin(float percentage) const;
+    LayoutUnit viewportPercentageMax(float percentage) const;
+
+private:
     virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE;
     virtual const RenderObject* pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&) const OVERRIDE;
     virtual void mapAbsoluteToLocalPoint(MapCoordinatesFlags, TransformState&) const;
     virtual bool requiresColumns(int desiredColumnCount) const OVERRIDE;
     virtual void computeSelfHitTestRects(Vector<LayoutRect>&, const LayoutPoint& layerOffset) const OVERRIDE;
 
-private:
     bool initializeLayoutState(LayoutState&);
 
     virtual void calcColumnWidth() OVERRIDE;
@@ -260,11 +275,16 @@
     friend class LayoutStateMaintainer;
     friend class LayoutStateDisabler;
 
-protected:
+    bool shouldUsePrintingLayout() const;
+
     FrameView* m_frameView;
 
     RenderObject* m_selectionStart;
     RenderObject* m_selectionEnd;
+
+    // Please use the configuration() accessor instead of accessing this member directly.
+    RenderingConfiguration m_configuration;
+
     int m_selectionStartPos;
     int m_selectionEndPos;
 
@@ -273,9 +293,6 @@
     typedef HashSet<RenderWidget*> RenderWidgetSet;
     RenderWidgetSet m_widgets;
 
-private:
-    bool shouldUsePrintingLayout() const;
-
     LayoutUnit m_pageLogicalHeight;
     bool m_pageLogicalHeightChanged;
     LayoutState* m_layoutState;
diff --git a/Source/core/css/FontLoader.idl b/Source/core/rendering/RenderingConfiguration.cpp
similarity index 72%
copy from Source/core/css/FontLoader.idl
copy to Source/core/rendering/RenderingConfiguration.cpp
index ff4e533..77060a3 100644
--- a/Source/core/css/FontLoader.idl
+++ b/Source/core/rendering/RenderingConfiguration.cpp
@@ -28,21 +28,29 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-[
-    NoInterfaceObject,
-    EnabledAtRuntime=FontLoadEvents,
-    ActiveDOMObject,
-    GenerateIsReachable=document
-] interface FontLoader : EventTarget {
+#include "config.h"
+#include "core/rendering/RenderingConfiguration.h"
 
-    attribute EventHandler onloading;
-    attribute EventHandler onloadingdone;
-    attribute EventHandler onloadstart;
-    attribute EventHandler onload;
-    attribute EventHandler onerror;
+#include "core/dom/Document.h"
 
-    boolean checkFont(DOMString font, [Default=NullString] optional DOMString text);
-    void loadFont(Dictionary params);
-    void notifyWhenFontsReady(VoidCallback callback);
-    readonly attribute boolean loading;
-};
+namespace WebCore {
+
+RenderingConfiguration::RenderingConfiguration()
+    : m_inQuirksMode(false)
+    , m_paginated(false)
+    , m_printing(false)
+{
+}
+
+RenderingConfiguration::~RenderingConfiguration()
+{
+}
+
+void RenderingConfiguration::update(Document& document)
+{
+    m_inQuirksMode = document.inQuirksMode();
+    m_paginated = document.paginated();
+    m_printing = document.printing();
+}
+
+}
diff --git a/Source/core/css/FontLoader.idl b/Source/core/rendering/RenderingConfiguration.h
similarity index 72%
copy from Source/core/css/FontLoader.idl
copy to Source/core/rendering/RenderingConfiguration.h
index ff4e533..dc1af6d 100644
--- a/Source/core/css/FontLoader.idl
+++ b/Source/core/rendering/RenderingConfiguration.h
@@ -28,21 +28,33 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-[
-    NoInterfaceObject,
-    EnabledAtRuntime=FontLoadEvents,
-    ActiveDOMObject,
-    GenerateIsReachable=document
-] interface FontLoader : EventTarget {
+#ifndef RenderingConfiguration_h
+#define RenderingConfiguration_h
 
-    attribute EventHandler onloading;
-    attribute EventHandler onloadingdone;
-    attribute EventHandler onloadstart;
-    attribute EventHandler onload;
-    attribute EventHandler onerror;
+#include "wtf/Noncopyable.h"
 
-    boolean checkFont(DOMString font, [Default=NullString] optional DOMString text);
-    void loadFont(Dictionary params);
-    void notifyWhenFontsReady(VoidCallback callback);
-    readonly attribute boolean loading;
+namespace WebCore {
+
+class Document;
+
+class RenderingConfiguration {
+    WTF_MAKE_NONCOPYABLE(RenderingConfiguration);
+public:
+    RenderingConfiguration();
+    ~RenderingConfiguration();
+
+    void update(Document&);
+
+    bool inQuirksMode() const { return m_inQuirksMode; }
+    bool paginated() const { return m_paginated; }
+    bool printing() const { return m_printing; }
+
+private:
+    bool m_inQuirksMode;
+    bool m_paginated;
+    bool m_printing;
 };
+
+}
+
+#endif // RenderingConfiguration_h
diff --git a/Source/core/rendering/RenderingNodeProxy.h b/Source/core/rendering/RenderingNodeProxy.h
index 30e73bf..ac5cb6d 100644
--- a/Source/core/rendering/RenderingNodeProxy.h
+++ b/Source/core/rendering/RenderingNodeProxy.h
@@ -31,19 +31,32 @@
 #ifndef RenderingNodeProxy_h
 #define RenderingNodeProxy_h
 
+#include "core/rendering/LayoutIndicator.h"
+#include "wtf/Noncopyable.h"
+
 namespace WebCore {
 
 class QualifiedName;
 class Node;
 
+#define STRICT_LAYOUT_THREADING 0
+
 class RenderingNodeProxy {
+    WTF_MAKE_NONCOPYABLE(RenderingNodeProxy);
 public:
     explicit RenderingNodeProxy(Node*);
     ~RenderingNodeProxy();
 
     bool hasTagName(const QualifiedName&) const;
 
-    Node* unsafeNode() const { return m_node; }
+    Node* unsafeNode() const
+    {
+#if STRICT_LAYOUT_THREADING
+        ASSERT(!LayoutIndicator::inLayout());
+#endif
+        return m_node;
+    }
+
     void clear() { m_node = 0; }
     void set(Node* node) { m_node = node; }
 
@@ -51,6 +64,8 @@
     Node* m_node;
 };
 
+#undef STRICT_LAYOUT_THREADING
+
 }
 
 #endif // RenderingNodeProxy_h
diff --git a/Source/core/rendering/RootInlineBox.cpp b/Source/core/rendering/RootInlineBox.cpp
index 5ad1318..bb0887f 100644
--- a/Source/core/rendering/RootInlineBox.cpp
+++ b/Source/core/rendering/RootInlineBox.cpp
@@ -837,7 +837,7 @@
 
     // This method determines the vertical position for inline elements.
     bool firstLine = isFirstLineStyle();
-    if (firstLine && !renderer->document().styleSheetCollections()->usesFirstLineRules())
+    if (firstLine && !renderer->document().styleEngine()->usesFirstLineRules())
         firstLine = false;
 
     // Check the cache.
diff --git a/Source/core/rendering/SubtreeLayoutScope.cpp b/Source/core/rendering/SubtreeLayoutScope.cpp
index 716421f..0484cba 100644
--- a/Source/core/rendering/SubtreeLayoutScope.cpp
+++ b/Source/core/rendering/SubtreeLayoutScope.cpp
@@ -53,13 +53,8 @@
     RELEASE_ASSERT(!m_root->needsLayout());
 
 #ifndef NDEBUG
-    for (HashSet<RenderObject*>::iterator it = m_renderersToLayout.begin(); it != m_renderersToLayout.end(); ++it) {
-        RenderObject* renderer = *it;
-        // FIXME: Thie patter is really common. Move it into an assertRendererLaidOut function.
-        if (renderer->needsLayout())
-            showRenderTree(renderer);
-        ASSERT(!renderer->needsLayout());
-    }
+    for (HashSet<RenderObject*>::iterator it = m_renderersToLayout.begin(); it != m_renderersToLayout.end(); ++it)
+        (*it)->assertRendererLaidOut();
 #endif
 }
 
diff --git a/Source/core/rendering/TextAutosizer.cpp b/Source/core/rendering/TextAutosizer.cpp
index c26dfbd..50a5154 100644
--- a/Source/core/rendering/TextAutosizer.cpp
+++ b/Source/core/rendering/TextAutosizer.cpp
@@ -24,7 +24,9 @@
 #include <algorithm>
 
 #include "core/dom/Document.h"
+#include "core/html/HTMLDivElement.h"
 #include "core/html/HTMLElement.h"
+#include "core/html/HTMLMetaElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Settings.h"
 #include "core/platform/chromium/TraceEvent.h"
@@ -81,6 +83,33 @@
     return formInputTags;
 }
 
+static const String& vBulletinForumCommentId()
+{
+    // Websites using vBulletin forum software typically contain <div id="post_message_*"..> blocks.
+    DEFINE_STATIC_LOCAL(const String, vBulletinForumCommentId, ("post_message_"));
+    return vBulletinForumCommentId;
+}
+
+static bool isVBulletinComment(const RenderBlock* block)
+{
+    Node* blockNode = block->node();
+    if (blockNode && blockNode->hasTagName(divTag)) {
+        const HTMLDivElement* element = toHTMLDivElement(blockNode);
+        if (element && element->hasID() && element->idForStyleResolution().startsWith(vBulletinForumCommentId()))
+            return true;
+    }
+    return false;
+}
+
+static bool hasForumCommentAncestor(const RenderBlock* container)
+{
+    for (const RenderBlock* block = container; block; block = block->containingBlock()) {
+        if (isVBulletinComment(block))
+            return true;
+    }
+    return false;
+}
+
 static RenderListItem* getAncestorListItem(const RenderObject* renderer)
 {
     RenderObject* ancestor = renderer->parent();
@@ -104,6 +133,7 @@
 
 TextAutosizer::TextAutosizer(Document* document)
     : m_document(document)
+    , m_contentType(Unknown)
 {
 }
 
@@ -121,15 +151,29 @@
     }
 }
 
+TextAutosizer::ContentType TextAutosizer::detectContentType()
+{
+    RefPtr<NodeList> metaElements = m_document->getElementsByTagNameNS(xhtmlNamespaceURI, metaTag.localName());
+    for (unsigned i = 0; i < metaElements->length(); ++i) {
+        HTMLMetaElement* metaElement = toHTMLMetaElement(metaElements->item(i));
+        if (equalIgnoringCase(metaElement->name(), "generator") && metaElement->content().startsWith("vBulletin", false))
+            return VBulletin;
+    }
+    return Default;
+}
+
 bool TextAutosizer::processSubtree(RenderObject* layoutRoot)
 {
     TRACE_EVENT0("webkit", "TextAutosizer::processSubtree");
 
     // FIXME: Text Autosizing should only be enabled when m_document->page()->mainFrame()->view()->useFixedLayout()
     // is true, but for now it's useful to ignore this so that it can be tested on desktop.
-    if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->printing() || !m_document->page())
+    if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->document().printing() || !m_document->page())
         return false;
 
+    if (m_contentType == Unknown && m_document->body())
+        m_contentType = detectContentType();
+
     Frame* mainFrame = m_document->page()->mainFrame();
 
     TextAutosizingWindowInfo windowInfo;
@@ -525,15 +569,22 @@
     // few lines of text you'll only need to pan across once or twice.
     //
     // An exception to the 4 lines of text are the textarea and contenteditable
-    // clusters, which are always autosized by default (i.e. threated as if they
+    // clusters, which are always autosized by default (i.e. treated as if they
     // contain more than 4 lines of text). This is to ensure that the text does
     // not suddenly get autosized when the user enters more than 4 lines of text.
+    // Another exception are the forum comments which are autosized by default
+    // to guarantee consistency.
     float totalTextWidth = 0;
     const float minLinesOfText = 4;
     float minTextWidth = blockWidth * minLinesOfText;
     for (size_t i = 0; i < clusterInfos.size(); ++i) {
         if (clusterInfos[i].root->isTextArea() || (clusterInfos[i].root->style() && clusterInfos[i].root->style()->userModify() != READ_ONLY))
             return true;
+        if (m_contentType == VBulletin) {
+            if (hasForumCommentAncestor(clusterInfos[i].blockContainingAllText)
+                || clusterContainsForumComment(clusterInfos[i].blockContainingAllText, clusterInfos[i]))
+                return true;
+        }
         measureDescendantTextWidth(clusterInfos[i].blockContainingAllText, clusterInfos[i], minTextWidth, totalTextWidth);
         if (totalTextWidth >= minTextWidth)
             return true;
@@ -541,6 +592,25 @@
     return false;
 }
 
+bool TextAutosizer::clusterContainsForumComment(const RenderBlock* container, TextAutosizingClusterInfo& clusterInfo)
+{
+    ASSERT(m_contentType == VBulletin);
+
+    RenderObject* descendant = nextInPreOrderSkippingDescendantsOfContainers(container, container);
+    while (descendant) {
+        if (isAutosizingContainer(descendant)) {
+            RenderBlock* descendantBlock = toRenderBlock(descendant);
+            if (isVBulletinComment(descendantBlock))
+                return true;
+            if (!isAutosizingCluster(descendantBlock, clusterInfo)
+                && clusterContainsForumComment(descendantBlock, clusterInfo))
+                return true;
+        }
+        descendant = nextInPreOrderSkippingDescendantsOfContainers(descendant, container);
+    }
+    return false;
+}
+
 void TextAutosizer::measureDescendantTextWidth(const RenderBlock* container, TextAutosizingClusterInfo& clusterInfo, float minTextWidth, float& textWidth)
 {
     bool skipLocalText = !containerShouldBeAutosized(container);
diff --git a/Source/core/rendering/TextAutosizer.h b/Source/core/rendering/TextAutosizer.h
index 7adcbc5..d8f7f89 100644
--- a/Source/core/rendering/TextAutosizer.h
+++ b/Source/core/rendering/TextAutosizer.h
@@ -59,6 +59,12 @@
         LastToFirst
     };
 
+    enum ContentType {
+        Unknown,
+        Default,
+        VBulletin
+    };
+
     explicit TextAutosizer(Document*);
 
     float clusterMultiplier(WritingMode, const TextAutosizingWindowInfo&, float textWidth) const;
@@ -68,9 +74,15 @@
     void processCompositeCluster(Vector<TextAutosizingClusterInfo>&, const TextAutosizingWindowInfo&);
     void processContainer(float multiplier, RenderBlock* container, TextAutosizingClusterInfo&, RenderObject* subtreeRoot, const TextAutosizingWindowInfo&);
 
+    bool clusterShouldBeAutosized(TextAutosizingClusterInfo&, float blockWidth);
+    bool compositeClusterShouldBeAutosized(Vector<TextAutosizingClusterInfo>&, float blockWidth);
+    bool clusterContainsForumComment(const RenderBlock* container, TextAutosizingClusterInfo&);
+
     void setMultiplier(RenderObject*, float);
     void setMultiplierForList(RenderObject* renderer, float multiplier);
 
+    ContentType detectContentType();
+
     static bool isAutosizingContainer(const RenderObject*);
     static bool isNarrowDescendant(const RenderBlock*, TextAutosizingClusterInfo& parentClusterInfo);
     static bool isWiderDescendant(const RenderBlock*, const TextAutosizingClusterInfo& parentClusterInfo);
@@ -81,8 +93,6 @@
     static bool containerContainsOneOfTags(const RenderBlock* cluster, const Vector<QualifiedName>& tags);
     static bool containerIsRowOfLinks(const RenderObject* container);
     static bool contentHeightIsConstrained(const RenderBlock* container);
-    static bool clusterShouldBeAutosized(TextAutosizingClusterInfo&, float blockWidth);
-    static bool compositeClusterShouldBeAutosized(Vector<TextAutosizingClusterInfo>&, float blockWidth);
     static void measureDescendantTextWidth(const RenderBlock* container, TextAutosizingClusterInfo&, float minTextWidth, float& textWidth);
 
     // Use to traverse the tree of descendants, excluding descendants of containers (but returning the containers themselves).
@@ -100,6 +110,7 @@
     static void getNarrowDescendantsGroupedByWidth(const TextAutosizingClusterInfo& parentClusterInfo, Vector<Vector<TextAutosizingClusterInfo> >&);
 
     Document* m_document;
+    ContentType m_contentType;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/shapes/PolygonShape.cpp b/Source/core/rendering/shapes/PolygonShape.cpp
index e1f429a..61da7a3 100644
--- a/Source/core/rendering/shapes/PolygonShape.cpp
+++ b/Source/core/rendering/shapes/PolygonShape.cpp
@@ -281,34 +281,30 @@
             }
         }
 
-        const FloatPolygonEdge& thisEdge = *thisIntersection.edge;
-        bool evenOddCrossing = !windCount;
+        bool edgeCrossing = thisIntersection.type == Normal;
+        if (!edgeCrossing) {
+            FloatPoint prevVertex;
+            FloatPoint thisVertex;
+            FloatPoint nextVertex;
 
-        if (polygon.fillRule() == RULE_EVENODD) {
-            windCount += (thisEdge.vertex2().y() > thisEdge.vertex1().y()) ? 1 : -1;
-            evenOddCrossing = evenOddCrossing || !windCount;
-        }
-
-        if (evenOddCrossing) {
-            bool edgeCrossing = thisIntersection.type == Normal;
-            if (!edgeCrossing) {
-                FloatPoint prevVertex;
-                FloatPoint thisVertex;
-                FloatPoint nextVertex;
-
-                if (getVertexIntersectionVertices(thisIntersection, prevVertex, thisVertex, nextVertex)) {
-                    if (nextVertex.y() == y)
-                        edgeCrossing = (isMinY) ? prevVertex.y() > y : prevVertex.y() < y;
-                    else if (prevVertex.y() == y)
-                        edgeCrossing = (isMinY) ? nextVertex.y() > y : nextVertex.y() < y;
-                    else
-                        edgeCrossing = true;
-                }
+            if (getVertexIntersectionVertices(thisIntersection, prevVertex, thisVertex, nextVertex)) {
+                if (nextVertex.y() == y)
+                    edgeCrossing = (isMinY) ? prevVertex.y() > y : prevVertex.y() < y;
+                else if (prevVertex.y() == y)
+                    edgeCrossing = (isMinY) ? nextVertex.y() > y : nextVertex.y() < y;
+                else
+                    edgeCrossing = true;
             }
-            if (edgeCrossing)
-                inside = appendIntervalX(thisIntersection.point.x(), inside, result);
         }
 
+        if (edgeCrossing && polygon.fillRule() == RULE_NONZERO) {
+            const FloatPolygonEdge& thisEdge = *thisIntersection.edge;
+            windCount += (thisEdge.vertex2().y() > thisEdge.vertex1().y()) ? 1 : -1;
+        }
+
+        if (edgeCrossing && (!inside || !windCount))
+            inside = appendIntervalX(thisIntersection.point.x(), inside, result);
+
         ++index;
     }
 }
diff --git a/Source/core/rendering/shapes/RasterShape.cpp b/Source/core/rendering/shapes/RasterShape.cpp
index a1d0963..55f3340 100644
--- a/Source/core/rendering/shapes/RasterShape.cpp
+++ b/Source/core/rendering/shapes/RasterShape.cpp
@@ -30,114 +30,140 @@
 #include "config.h"
 #include "core/rendering/shapes/RasterShape.h"
 
-#include "core/rendering/shapes/ShapeInterval.h"
 #include "wtf/MathExtras.h"
 
 namespace WebCore {
 
-IntRect RasterShapeIntervals::bounds() const
+void RasterShapeIntervals::appendInterval(int y, int x1, int x2)
 {
-    if (!m_bounds)
-        m_bounds = adoptPtr(new IntRect(m_region.bounds()));
-    return *m_bounds;
+    ASSERT(y >= 0 && y < size() && x1 >= 0 && x2 > x1 && (m_intervalLists[y].isEmpty() || x1 > m_intervalLists[y].last().x2()));
+
+    m_bounds.unite(IntRect(x1, y, x2 - x1, 1));
+    m_intervalLists[y].append(IntShapeInterval(x1, x2));
 }
 
-void RasterShapeIntervals::addInterval(int y, int x1, int x2)
+static inline bool shapeIntervalsContain(const IntShapeIntervals& intervals, const IntShapeInterval& interval)
 {
-    m_region.unite(Region(IntRect(x1, y, x2 - x1, 1)));
-    m_bounds.clear();
+    for (unsigned i = 0; i < intervals.size(); i++) {
+        if (intervals[i].x1() > interval.x2())
+            return false;
+        if (intervals[i].contains(interval))
+            return true;
+    }
+
+    return false;
+}
+
+bool RasterShapeIntervals::contains(const IntRect& rect) const
+{
+    if (!bounds().contains(rect))
+        return false;
+
+    const IntShapeInterval& rectInterval = IntShapeInterval(rect.x(), rect.maxX());
+    for (int y = rect.y(); y < rect.maxY(); y++) {
+        if (!shapeIntervalsContain(getIntervals(y), rectInterval))
+            return false;
+    }
+
+    return true;
+}
+
+static inline void appendX1Values(const IntShapeIntervals& intervals, int minIntervalWidth, Vector<int>& result)
+{
+    for (unsigned i = 0; i < intervals.size(); i++) {
+        if (intervals[i].width() >= minIntervalWidth)
+            result.append(intervals[i].x1());
+    }
+}
+
+bool RasterShapeIntervals::getIntervalX1Values(int y1, int y2, int minIntervalWidth, Vector<int>& result) const
+{
+    ASSERT(y1 >= 0 && y2 > y1);
+
+    for (int y = y1; y < y2;  y++) {
+        if (getIntervals(y).isEmpty())
+            return false;
+    }
+
+    appendX1Values(getIntervals(y1), minIntervalWidth, result);
+    for (int y = y1 + 1; y < y2;  y++) {
+        if (getIntervals(y) != getIntervals(y - 1))
+            appendX1Values(getIntervals(y), minIntervalWidth, result);
+    }
+
+    return true;
 }
 
 bool RasterShapeIntervals::firstIncludedIntervalY(int minY, const IntSize& minSize, LayoutUnit& result) const
 {
-    for (int y = minY; y <= bounds().height() - minSize.height(); y++) {
-        Region lineRegion(IntRect(bounds().x(), y, bounds().width(), minSize.height()));
-        lineRegion.intersect(m_region);
-        if (lineRegion.isEmpty())
+    minY = std::max<int>(bounds().y(), minY);
+
+    ASSERT(minY >= 0 && minY < size());
+
+    if (minSize.isEmpty() || minSize.width() > bounds().width())
+        return false;
+
+    for (int lineY = minY; lineY <= bounds().maxY() - minSize.height(); lineY++) {
+        Vector<int> intervalX1Values;
+        if (!getIntervalX1Values(lineY, lineY + minSize.height(), minSize.width(), intervalX1Values))
             continue;
 
-        const Vector<IntRect>& lineRects = lineRegion.rects();
-        ASSERT(lineRects.size() > 0);
+        std::sort(intervalX1Values.begin(), intervalX1Values.end());
 
-        for (unsigned i = 0; i < lineRects.size(); i++) {
-            IntRect rect = lineRects[i];
-            if (rect.width() >= minSize.width() && lineRegion.contains(Region(IntRect(IntPoint(rect.x(), y), minSize)))) {
-                result = y;
+        IntRect firstFitRect(IntPoint(0, 0), minSize);
+        for (unsigned i = 0; i < intervalX1Values.size(); i++) {
+            int lineX = intervalX1Values[i];
+            if (i > 0 && lineX == intervalX1Values[i - 1])
+                continue;
+            firstFitRect.setLocation(IntPoint(lineX, lineY));
+            if (contains(firstFitRect)) {
+                result = lineY;
                 return true;
             }
         }
     }
+
     return false;
 }
 
-static inline IntRect alignedRect(IntRect r, int y1, int y2)
-{
-    return IntRect(r.x(), y1, r.width(), y2 - y1);
-}
-
-void RasterShapeIntervals::getIncludedIntervals(int y1, int y2, SegmentList& result) const
+void RasterShapeIntervals::getIncludedIntervals(int y1, int y2, IntShapeIntervals& result) const
 {
     ASSERT(y2 >= y1);
 
-    IntRect lineRect(bounds().x(), y1, bounds().width(), y2 - y1);
-    Region lineRegion(lineRect);
-    lineRegion.intersect(m_region);
-    if (lineRegion.isEmpty())
+    if (y1 < bounds().y() || y2 > bounds().maxY())
         return;
 
-    const Vector<IntRect>& lineRects = lineRegion.rects();
-    ASSERT(lineRects.size() > 0);
-
-    Region segmentsRegion(lineRect);
-    Region intervalsRegion;
-
-    // The loop below uses Regions to compute the intersection of the horizontal
-    // shape intervals that fall within the line's box.
-    int currentLineY = lineRects[0].y();
-    int currentLineMaxY = lineRects[0].maxY();
-    for (unsigned i = 0; i < lineRects.size(); ++i) {
-        int lineY = lineRects[i].y();
-        ASSERT(lineY >= currentLineY);
-        if (lineY > currentLineMaxY) // We've encountered a vertical gap in lineRects, there are no included intervals.
+    for (int y = y1; y < y2;  y++) {
+        if (getIntervals(y).isEmpty())
             return;
-        if (lineY > currentLineY) {
-            currentLineY = lineY;
-            currentLineMaxY = lineRects[i].maxY();
-            segmentsRegion.intersect(intervalsRegion);
-            intervalsRegion = Region();
-        } else {
-            currentLineMaxY = std::max<int>(currentLineMaxY, lineRects[i].maxY());
-        }
-        intervalsRegion.unite(Region(alignedRect(lineRects[i], y1, y2)));
     }
-    if (!intervalsRegion.isEmpty())
-        segmentsRegion.intersect(intervalsRegion);
 
-    const Vector<IntRect>& segmentRects = segmentsRegion.rects();
-    for (unsigned i = 0; i < segmentRects.size(); ++i)
-        result.append(LineSegment(segmentRects[i].x(), segmentRects[i].maxX()));
+    result = getIntervals(y1);
+    for (int y = y1 + 1; y < y2 && !result.isEmpty();  y++) {
+        IntShapeIntervals intervals;
+        IntShapeInterval::intersectShapeIntervals(result, getIntervals(y), intervals);
+        result.swap(intervals);
+    }
 }
 
-void RasterShapeIntervals::getExcludedIntervals(int y1, int y2, SegmentList& result) const
+void RasterShapeIntervals::getExcludedIntervals(int y1, int y2, IntShapeIntervals& result) const
 {
     ASSERT(y2 >= y1);
 
-    IntRect lineRect(bounds().x(), y1, bounds().width(), y2 - y1);
-    Region lineRegion(lineRect);
-    lineRegion.intersect(m_region);
-    if (lineRegion.isEmpty())
+    if (y2 < bounds().y() || y1 >= bounds().maxY())
         return;
 
-    const Vector<IntRect>& lineRects = lineRegion.rects();
-    ASSERT(lineRects.size() > 0);
+    for (int y = y1; y < y2;  y++) {
+        if (getIntervals(y).isEmpty())
+            return;
+    }
 
-    Region segmentsRegion;
-    for (unsigned i = 0; i < lineRects.size(); i++)
-        segmentsRegion.unite(Region(alignedRect(lineRects[i], y1, y2)));
-
-    const Vector<IntRect>& segmentRects = segmentsRegion.rects();
-    for (unsigned i = 0; i < segmentRects.size(); i++)
-        result.append(LineSegment(segmentRects[i].x(), segmentRects[i].maxX() + 1));
+    result = getIntervals(y1);
+    for (int y = y1 + 1; y < y2;  y++) {
+        IntShapeIntervals intervals;
+        IntShapeInterval::uniteShapeIntervals(result, getIntervals(y), intervals);
+        result.swap(intervals);
+    }
 }
 
 const RasterShapeIntervals& RasterShape::marginIntervals() const
@@ -146,7 +172,7 @@
     if (!shapeMargin())
         return *m_intervals;
 
-    // FIXME: add support for non-zero margin, see https://code.google.com/p/chromium/issues/detail?id=252737.
+    // FIXME: Add support for non-zero margin, see https://bugs.webkit.org/show_bug.cgi?id=116348.
     return *m_intervals;
 }
 
@@ -156,23 +182,25 @@
     if (!shapePadding())
         return *m_intervals;
 
-    // FIXME: add support for non-zero padding, see https://code.google.com/p/chromium/issues/detail?id=252737.
+    // FIXME: Add support for non-zero padding, see https://bugs.webkit.org/show_bug.cgi?id=116348.
     return *m_intervals;
 }
 
+static inline void appendLineSegments(const IntShapeIntervals& intervals, SegmentList& result)
+{
+    for (unsigned i = 0; i < intervals.size(); i++)
+        result.append(LineSegment(intervals[i].x1(), intervals[i].x2() + 1));
+}
+
 void RasterShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
     const RasterShapeIntervals& intervals = marginIntervals();
     if (intervals.isEmpty())
         return;
 
-    float y1 = logicalTop;
-    float y2 = logicalTop + logicalHeight;
-
-    if (y2 < intervals.bounds().y() || y1 >= intervals.bounds().maxY())
-        return;
-
-    intervals.getExcludedIntervals(y1, y2, result);
+    IntShapeIntervals excludedIntervals;
+    intervals.getExcludedIntervals(logicalTop, logicalTop + logicalHeight, excludedIntervals);
+    appendLineSegments(excludedIntervals, result);
 }
 
 void RasterShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
@@ -181,31 +209,18 @@
     if (intervals.isEmpty())
         return;
 
-    float y1 = logicalTop;
-    float y2 = logicalTop + logicalHeight;
-
-    if (y1 < intervals.bounds().y() || y2 > intervals.bounds().maxY())
-        return;
-
-    intervals.getIncludedIntervals(y1, y2, result);
+    IntShapeIntervals includedIntervals;
+    intervals.getIncludedIntervals(logicalTop, logicalTop + logicalHeight, includedIntervals);
+    appendLineSegments(includedIntervals, result);
 }
 
 bool RasterShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
 {
-    float minIntervalTop = minLogicalIntervalTop;
-    float minIntervalHeight = minLogicalIntervalSize.height();
-    float minIntervalWidth = minLogicalIntervalSize.width();
-
     const RasterShapeIntervals& intervals = paddingIntervals();
-    if (intervals.isEmpty() || minIntervalWidth > intervals.bounds().width())
+    if (intervals.isEmpty())
         return false;
 
-    float minY = std::max<float>(intervals.bounds().y(), minIntervalTop);
-    float maxY = minY + minIntervalHeight;
-    if (maxY > intervals.bounds().maxY())
-        return false;
-
-    return intervals.firstIncludedIntervalY(minY, flooredIntSize(minLogicalIntervalSize), result);
+    return intervals.firstIncludedIntervalY(minLogicalIntervalTop.floor(), flooredIntSize(minLogicalIntervalSize), result);
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/shapes/RasterShape.h b/Source/core/rendering/shapes/RasterShape.h
index 1ad6666..492e50d 100644
--- a/Source/core/rendering/shapes/RasterShape.h
+++ b/Source/core/rendering/shapes/RasterShape.h
@@ -31,8 +31,8 @@
 #define RasterShape_h
 
 #include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/Region.h"
 #include "core/rendering/shapes/Shape.h"
+#include "core/rendering/shapes/ShapeInterval.h"
 #include "wtf/Assertions.h"
 #include "wtf/Vector.h"
 
@@ -40,18 +40,31 @@
 
 class RasterShapeIntervals {
 public:
-    RasterShapeIntervals() { }
+    RasterShapeIntervals(unsigned size)
+    {
+        m_intervalLists.resize(size);
+    }
 
-    IntRect bounds() const;
-    bool isEmpty() const  { return m_region.isEmpty(); }
-    void addInterval(int y, int x1, int x2);
-    void getIncludedIntervals(int y1, int y2, SegmentList&) const;
-    void getExcludedIntervals(int y1, int y2, SegmentList&) const;
-    bool firstIncludedIntervalY(int minY, const IntSize& minIntervalSize, LayoutUnit&) const;
+    const IntRect& bounds() const { return m_bounds; }
+    bool isEmpty() const { return m_bounds.isEmpty(); }
+    void appendInterval(int y, int x1, int x2);
+
+    void getIncludedIntervals(int y1, int y2, IntShapeIntervals& result) const;
+    void getExcludedIntervals(int y1, int y2, IntShapeIntervals& result) const;
+    bool firstIncludedIntervalY(int minY, const IntSize& minSize, LayoutUnit& result) const;
 
 private:
-    Region m_region;
-    mutable OwnPtr<IntRect> m_bounds; // Cached value of m_region.bounds().
+    int size() const { return m_intervalLists.size(); }
+    const IntShapeIntervals& getIntervals(int y) const
+    {
+        ASSERT(y >= 0 && y < size());
+        return m_intervalLists[y];
+    }
+    bool contains(const IntRect&) const;
+    bool getIntervalX1Values(int minY, int maxY, int minIntervalWidth, Vector<int>& result) const;
+
+    IntRect m_bounds;
+    Vector<IntShapeIntervals > m_intervalLists;
 };
 
 class RasterShape : public Shape {
diff --git a/Source/core/rendering/shapes/Shape.cpp b/Source/core/rendering/shapes/Shape.cpp
index b325c07..0d660ae 100644
--- a/Source/core/rendering/shapes/Shape.cpp
+++ b/Source/core/rendering/shapes/Shape.cpp
@@ -205,11 +205,12 @@
 {
     ASSERT(styleImage && styleImage->isImageResource() && styleImage->cachedImage() && styleImage->cachedImage()->image());
 
-    OwnPtr<RasterShapeIntervals> intervals = adoptPtr(new RasterShapeIntervals());
-
     Image* image = styleImage->cachedImage()->image();
     const IntSize& imageSize = image->size();
     OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(imageSize);
+
+    OwnPtr<RasterShapeIntervals> intervals = adoptPtr(new RasterShapeIntervals(imageSize.height()));
+
     if (imageBuffer) {
         GraphicsContext* graphicsContext = imageBuffer->context();
         graphicsContext->drawImage(image, IntPoint());
@@ -228,7 +229,7 @@
                 if ((startX == -1) && alpha > alphaPixelThreshold) {
                     startX = x;
                 } else if (startX != -1 && (alpha <= alphaPixelThreshold || x == imageSize.width() - 1)) {
-                    intervals->addInterval(y, startX, x);
+                    intervals->appendInterval(y, startX, x);
                     startX = -1;
                 }
             }
diff --git a/Source/core/rendering/shapes/ShapeInfo.cpp b/Source/core/rendering/shapes/ShapeInfo.cpp
index 54f97ab..47699d2 100644
--- a/Source/core/rendering/shapes/ShapeInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInfo.cpp
@@ -35,27 +35,26 @@
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
-template<class RenderType, ShapeValue* (RenderStyle::*shapeGetter)() const, void (Shape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
-const Shape* ShapeInfo<RenderType, shapeGetter, intervalGetter>::computedShape() const
+template<class RenderType>
+const Shape* ShapeInfo<RenderType>::computedShape() const
 {
     if (Shape* shape = m_shape.get())
         return shape;
 
-    const LayoutSize logicalBoxSize(m_shapeLogicalWidth, m_shapeLogicalHeight);
     WritingMode writingMode = m_renderer->style()->writingMode();
     Length margin = m_renderer->style()->shapeMargin();
     Length padding = m_renderer->style()->shapePadding();
-    const ShapeValue* shapeValue = (m_renderer->style()->*shapeGetter)();
+    const ShapeValue* shapeValue = this->shapeValue();
     ASSERT(shapeValue);
 
     switch (shapeValue->type()) {
     case ShapeValue::Shape:
         ASSERT(shapeValue->shape());
-        m_shape = Shape::createShape(shapeValue->shape(), logicalBoxSize, writingMode, margin, padding);
+        m_shape = Shape::createShape(shapeValue->shape(), m_shapeLogicalSize, writingMode, margin, padding);
         break;
     case ShapeValue::Image:
         ASSERT(shapeValue->image());
-        m_shape = Shape::createShape(shapeValue->image(), 0, logicalBoxSize, writingMode, margin, padding);
+        m_shape = Shape::createShape(shapeValue->image(), 0, m_shapeLogicalSize, writingMode, margin, padding);
         break;
     default:
         ASSERT_NOT_REACHED();
@@ -65,8 +64,8 @@
     return m_shape.get();
 }
 
-template<class RenderType, ShapeValue* (RenderStyle::*shapeGetter)() const, void (Shape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
-bool ShapeInfo<RenderType, shapeGetter, intervalGetter>::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
+template<class RenderType>
+bool ShapeInfo<RenderType>::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
 {
     ASSERT(lineHeight >= 0);
     m_shapeLineTop = lineTop - logicalTopOffset();
@@ -74,7 +73,7 @@
     m_segments.clear();
 
     if (lineOverlapsShapeBounds())
-        (computedShape()->*intervalGetter)(m_shapeLineTop, std::min(m_lineHeight, shapeLogicalBottom() - lineTop), m_segments);
+        getIntervals(m_shapeLineTop, std::min(m_lineHeight, shapeLogicalBottom() - lineTop), m_segments);
 
     LayoutUnit logicalLeftOffset = this->logicalLeftOffset();
     for (size_t i = 0; i < m_segments.size(); i++) {
@@ -85,6 +84,6 @@
     return m_segments.size();
 }
 
-template class ShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &Shape::getIncludedIntervals>;
-template class ShapeInfo<RenderBox, &RenderStyle::shapeOutside, &Shape::getExcludedIntervals>;
+template class ShapeInfo<RenderBlock>;
+template class ShapeInfo<RenderBox>;
 }
diff --git a/Source/core/rendering/shapes/ShapeInfo.h b/Source/core/rendering/shapes/ShapeInfo.h
index 29cb073..7ad3fea 100644
--- a/Source/core/rendering/shapes/ShapeInfo.h
+++ b/Source/core/rendering/shapes/ShapeInfo.h
@@ -62,7 +62,7 @@
     }
 };
 
-template<class RenderType, ShapeValue* (RenderStyle::*shapeGetter)() const, void (Shape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
+template<class RenderType>
 class ShapeInfo {
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -70,16 +70,15 @@
 
     void setShapeSize(LayoutUnit logicalWidth, LayoutUnit logicalHeight)
     {
-        if (m_renderer->style()->boxSizing() == CONTENT_BOX) {
-            logicalWidth -= m_renderer->borderAndPaddingLogicalWidth();
-            logicalHeight -= m_renderer->borderAndPaddingLogicalHeight();
-        }
+        LayoutSize newLogicalSize(logicalWidth, logicalHeight);
 
-        if (m_shapeLogicalWidth == logicalWidth && m_shapeLogicalHeight == logicalHeight)
+        if (m_renderer->style()->boxSizing() == CONTENT_BOX)
+            newLogicalSize -= LayoutSize(m_renderer->borderAndPaddingLogicalWidth(), m_renderer->borderAndPaddingLogicalHeight());
+
+        if (m_shapeLogicalSize == newLogicalSize)
             return;
         dirtyShapeSize();
-        m_shapeLogicalWidth = logicalWidth;
-        m_shapeLogicalHeight = logicalHeight;
+        m_shapeLogicalSize = newLogicalSize;
     }
 
     virtual bool computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight);
@@ -95,7 +94,7 @@
     LayoutUnit logicalLineTop() const { return m_shapeLineTop + logicalTopOffset(); }
     LayoutUnit logicalLineBottom() const { return m_shapeLineTop + m_lineHeight + logicalTopOffset(); }
 
-    LayoutUnit shapeContainingBlockHeight() const { return (m_renderer->style()->boxSizing() == CONTENT_BOX) ? (m_shapeLogicalHeight + m_renderer->borderAndPaddingLogicalHeight()) : m_shapeLogicalHeight; }
+    LayoutUnit shapeContainingBlockHeight() const { return (m_renderer->style()->boxSizing() == CONTENT_BOX) ? (m_shapeLogicalSize.height() + m_renderer->borderAndPaddingLogicalHeight()) : m_shapeLogicalSize.height(); }
 
     bool lineOverlapsShapeBounds() const { return logicalLineTop() < shapeLogicalBottom() && shapeLogicalTop() <= logicalLineBottom(); }
 
@@ -108,6 +107,8 @@
 
     const Shape* computedShape() const;
     virtual LayoutRect computedShapeLogicalBoundingBox() const = 0;
+    virtual ShapeValue* shapeValue() const = 0;
+    virtual void getIntervals(LayoutUnit, LayoutUnit, SegmentList&) const = 0;
 
     LayoutUnit logicalTopOffset() const { return m_renderer->style()->boxSizing() == CONTENT_BOX ? m_renderer->borderAndPaddingBefore() : LayoutUnit(); }
     LayoutUnit logicalLeftOffset() const { return (m_renderer->style()->boxSizing() == CONTENT_BOX && !m_renderer->isRenderRegion()) ? m_renderer->borderAndPaddingStart() : LayoutUnit(); }
@@ -120,9 +121,7 @@
 
 private:
     mutable OwnPtr<Shape> m_shape;
-
-    LayoutUnit m_shapeLogicalWidth;
-    LayoutUnit m_shapeLogicalHeight;
+    LayoutSize m_shapeLogicalSize;
 };
 }
 #endif
diff --git a/Source/core/rendering/shapes/ShapeInsideInfo.cpp b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
index 8c63f6c..c6e004d 100644
--- a/Source/core/rendering/shapes/ShapeInsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
@@ -76,4 +76,9 @@
     return false;
 }
 
+ShapeValue* ShapeInsideInfo::shapeValue() const
+{
+    return m_renderer->style()->resolvedShapeInside();
+}
+
 }
diff --git a/Source/core/rendering/shapes/ShapeInsideInfo.h b/Source/core/rendering/shapes/ShapeInsideInfo.h
index 4c410f2..02d8907 100644
--- a/Source/core/rendering/shapes/ShapeInsideInfo.h
+++ b/Source/core/rendering/shapes/ShapeInsideInfo.h
@@ -60,7 +60,7 @@
 
 typedef Vector<LineSegmentRange> SegmentRangeList;
 
-class ShapeInsideInfo : public ShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &Shape::getIncludedIntervals> {
+class ShapeInsideInfo FINAL : public ShapeInfo<RenderBlock> {
 public:
     static PassOwnPtr<ShapeInsideInfo> createInfo(const RenderBlock* renderer) { return adoptPtr(new ShapeInsideInfo(renderer)); }
 
@@ -69,7 +69,7 @@
     virtual bool computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight) OVERRIDE
     {
         m_segmentRanges.clear();
-        return ShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &Shape::getIncludedIntervals>::computeSegmentsForLine(lineTop, lineHeight);
+        return ShapeInfo<RenderBlock>::computeSegmentsForLine(lineTop, lineHeight);
     }
 
     bool hasSegments() const
@@ -97,10 +97,15 @@
 
 protected:
     virtual LayoutRect computedShapeLogicalBoundingBox() const OVERRIDE { return computedShape()->shapePaddingLogicalBoundingBox(); }
+    virtual ShapeValue* shapeValue() const OVERRIDE;
+    virtual void getIntervals(LayoutUnit lineTop, LayoutUnit lineHeight, SegmentList& segments) const OVERRIDE
+    {
+        return computedShape()->getIncludedIntervals(lineTop, lineHeight, segments);
+    }
 
 private:
     ShapeInsideInfo(const RenderBlock* renderer)
-    : ShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &Shape::getIncludedIntervals> (renderer)
+    : ShapeInfo<RenderBlock> (renderer)
     , m_needsLayout(false)
     { }
 
diff --git a/Source/core/rendering/shapes/ShapeInterval.h b/Source/core/rendering/shapes/ShapeInterval.h
index e4308e5..a3c1322 100644
--- a/Source/core/rendering/shapes/ShapeInterval.h
+++ b/Source/core/rendering/shapes/ShapeInterval.h
@@ -47,6 +47,7 @@
 
     T x1() const { return m_x1; }
     T x2() const { return m_x2; }
+    T width() const { return m_x2 - m_x1; }
 
     void setX1(T x1)
     {
diff --git a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
index 4993a5f..e2cc9de 100644
--- a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
@@ -60,7 +60,7 @@
 bool ShapeOutsideInfo::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
 {
     if (shapeSizeDirty() || m_lineTop != lineTop || m_lineHeight != lineHeight) {
-        if (ShapeInfo<RenderBox, &RenderStyle::shapeOutside, &Shape::getExcludedIntervals>::computeSegmentsForLine(lineTop, lineHeight)) {
+        if (ShapeInfo<RenderBox>::computeSegmentsForLine(lineTop, lineHeight)) {
             m_leftSegmentMarginBoxDelta = m_segments[0].logicalLeft + m_renderer->marginStart();
             m_rightSegmentMarginBoxDelta = m_segments[m_segments.size()-1].logicalRight - m_renderer->logicalWidth() - m_renderer->marginEnd();
         } else {
@@ -73,4 +73,9 @@
     return m_segments.size();
 }
 
+ShapeValue* ShapeOutsideInfo::shapeValue() const
+{
+    return m_renderer->style()->shapeOutside();
+}
+
 }
diff --git a/Source/core/rendering/shapes/ShapeOutsideInfo.h b/Source/core/rendering/shapes/ShapeOutsideInfo.h
index 21e8380..0d1af35 100644
--- a/Source/core/rendering/shapes/ShapeOutsideInfo.h
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.h
@@ -37,7 +37,7 @@
 
 class RenderBox;
 
-class ShapeOutsideInfo : public ShapeInfo<RenderBox, &RenderStyle::shapeOutside, &Shape::getExcludedIntervals>, public MappedInfo<RenderBox, ShapeOutsideInfo> {
+class ShapeOutsideInfo FINAL : public ShapeInfo<RenderBox>, public MappedInfo<RenderBox, ShapeOutsideInfo> {
 public:
     LayoutUnit leftSegmentMarginBoxDelta() const { return m_leftSegmentMarginBoxDelta; }
     LayoutUnit rightSegmentMarginBoxDelta() const { return m_rightSegmentMarginBoxDelta; }
@@ -50,9 +50,14 @@
 
 protected:
     virtual LayoutRect computedShapeLogicalBoundingBox() const OVERRIDE { return computedShape()->shapeMarginLogicalBoundingBox(); }
+    virtual ShapeValue* shapeValue() const OVERRIDE;
+    virtual void getIntervals(LayoutUnit lineTop, LayoutUnit lineHeight, SegmentList& segments) const OVERRIDE
+    {
+        return computedShape()->getExcludedIntervals(lineTop, lineHeight, segments);
+    }
 
 private:
-    ShapeOutsideInfo(const RenderBox* renderer) : ShapeInfo<RenderBox, &RenderStyle::shapeOutside, &Shape::getExcludedIntervals>(renderer) { }
+    ShapeOutsideInfo(const RenderBox* renderer) : ShapeInfo<RenderBox>(renderer) { }
 
     LayoutUnit m_leftSegmentMarginBoxDelta;
     LayoutUnit m_rightSegmentMarginBoxDelta;
diff --git a/Source/core/rendering/style/KeyframeList.cpp b/Source/core/rendering/style/KeyframeList.cpp
index feaf484..a28da7e 100644
--- a/Source/core/rendering/style/KeyframeList.cpp
+++ b/Source/core/rendering/style/KeyframeList.cpp
@@ -42,9 +42,8 @@
     }
 }
 
-TimingFunction* KeyframeValue::timingFunction(const AtomicString& name) const
+TimingFunction* KeyframeValue::timingFunction(const RenderStyle* keyframeStyle, const AtomicString& name)
 {
-    const RenderStyle* keyframeStyle = style();
     ASSERT(keyframeStyle && keyframeStyle->animations());
     for (size_t i = 0; i < keyframeStyle->animations()->size(); i++) {
         if (name == keyframeStyle->animations()->animation(i)->name())
diff --git a/Source/core/rendering/style/KeyframeList.h b/Source/core/rendering/style/KeyframeList.h
index 85df598..792f1eb 100644
--- a/Source/core/rendering/style/KeyframeList.h
+++ b/Source/core/rendering/style/KeyframeList.h
@@ -58,7 +58,7 @@
     const RenderStyle* style() const { return m_style.get(); }
     void setStyle(PassRefPtr<RenderStyle> style) { m_style = style; }
 
-    TimingFunction* timingFunction(const AtomicString& name) const;
+    static TimingFunction* timingFunction(const RenderStyle*, const AtomicString& name);
 
 private:
     double m_key;
diff --git a/Source/core/rendering/svg/RenderSVGGradientStop.h b/Source/core/rendering/svg/RenderSVGGradientStop.h
index 4899a14..bf2a10a 100644
--- a/Source/core/rendering/svg/RenderSVGGradientStop.h
+++ b/Source/core/rendering/svg/RenderSVGGradientStop.h
@@ -31,7 +31,7 @@
 // This class exists mostly so we can hear about gradient stop style changes
 class RenderSVGGradientStop FINAL : public RenderObject {
 public:
-    RenderSVGGradientStop(SVGStopElement*);
+    explicit RenderSVGGradientStop(SVGStopElement*);
     virtual ~RenderSVGGradientStop();
 
     virtual bool isSVGGradientStop() const { return true; }
diff --git a/Source/core/rendering/svg/RenderSVGImage.h b/Source/core/rendering/svg/RenderSVGImage.h
index 5aba9d1..15c5b5c 100644
--- a/Source/core/rendering/svg/RenderSVGImage.h
+++ b/Source/core/rendering/svg/RenderSVGImage.h
@@ -33,7 +33,7 @@
 
 class RenderSVGImage FINAL : public RenderSVGModelObject {
 public:
-    RenderSVGImage(SVGImageElement*);
+    explicit RenderSVGImage(SVGImageElement*);
     virtual ~RenderSVGImage();
 
     bool updateImageViewport();
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.h b/Source/core/rendering/svg/RenderSVGResourceClipper.h
index 02ce712..9838d28 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.h
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.h
@@ -37,7 +37,7 @@
 
 class RenderSVGResourceClipper FINAL : public RenderSVGResourceContainer {
 public:
-    RenderSVGResourceClipper(SVGClipPathElement*);
+    explicit RenderSVGResourceClipper(SVGClipPathElement*);
     virtual ~RenderSVGResourceClipper();
 
     virtual const char* renderName() const { return "RenderSVGResourceClipper"; }
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.h b/Source/core/rendering/svg/RenderSVGResourceContainer.h
index 5b8cdc2..efb5c18 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.h
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.h
@@ -30,7 +30,7 @@
 class RenderSVGResourceContainer : public RenderSVGHiddenContainer,
                                    public RenderSVGResource {
 public:
-    RenderSVGResourceContainer(SVGElement*);
+    explicit RenderSVGResourceContainer(SVGElement*);
     virtual ~RenderSVGResourceContainer();
 
     virtual void layout();
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.h b/Source/core/rendering/svg/RenderSVGResourceFilter.h
index 36b91ae..25faa03 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.h
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.h
@@ -57,7 +57,7 @@
 
 class RenderSVGResourceFilter FINAL : public RenderSVGResourceContainer {
 public:
-    RenderSVGResourceFilter(SVGFilterElement*);
+    explicit RenderSVGResourceFilter(SVGFilterElement*);
     virtual ~RenderSVGResourceFilter();
 
     virtual const char* renderName() const { return "RenderSVGResourceFilter"; }
@@ -88,12 +88,18 @@
     HashMap<RenderObject*, FilterData*> m_filter;
 };
 
-inline RenderSVGResourceFilter* toRenderSVGFilter(RenderObject* object)
+inline RenderSVGResourceFilter* toRenderSVGResourceFilter(RenderObject* object)
 {
     ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGResourceFilter());
     return static_cast<RenderSVGResourceFilter*>(object);
 }
 
+inline RenderSVGResourceFilter* toRenderSVGResourceFilter(RenderSVGResourceContainer* resource)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == FilterResourceType);
+    return static_cast<RenderSVGResourceFilter*>(resource);
+}
+
 }
 
 #endif
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp b/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp
index 44e2d0b..18cc67a 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp
@@ -46,12 +46,12 @@
     const SVGRenderStyle* newStyle = this->style()->svgStyle();
     if (element()->hasTagName(SVGNames::feFloodTag)) {
         if (newStyle->floodColor() != oldStyle->svgStyle()->floodColor())
-            toRenderSVGFilter(filter)->primitiveAttributeChanged(this, SVGNames::flood_colorAttr);
+            toRenderSVGResourceFilter(filter)->primitiveAttributeChanged(this, SVGNames::flood_colorAttr);
         if (newStyle->floodOpacity() != oldStyle->svgStyle()->floodOpacity())
-            toRenderSVGFilter(filter)->primitiveAttributeChanged(this, SVGNames::flood_opacityAttr);
+            toRenderSVGResourceFilter(filter)->primitiveAttributeChanged(this, SVGNames::flood_opacityAttr);
     } else if (element()->hasTagName(SVGNames::feDiffuseLightingTag) || element()->hasTagName(SVGNames::feSpecularLightingTag)) {
         if (newStyle->lightingColor() != oldStyle->svgStyle()->lightingColor())
-            toRenderSVGFilter(filter)->primitiveAttributeChanged(this, SVGNames::lighting_colorAttr);
+            toRenderSVGResourceFilter(filter)->primitiveAttributeChanged(this, SVGNames::lighting_colorAttr);
     }
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h b/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h
index c44b1e7..e2edf3f 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h
+++ b/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h
@@ -53,7 +53,7 @@
         RenderObject* filter = parent();
         if (!filter || !filter->isSVGResourceFilter())
             return;
-        static_cast<RenderSVGResourceFilter*>(filter)->primitiveAttributeChanged(this, attribute);
+        toRenderSVGResourceFilter(filter)->primitiveAttributeChanged(this, attribute);
     }
 };
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceGradient.h b/Source/core/rendering/svg/RenderSVGResourceGradient.h
index fe04469..13c82fb 100644
--- a/Source/core/rendering/svg/RenderSVGResourceGradient.h
+++ b/Source/core/rendering/svg/RenderSVGResourceGradient.h
@@ -44,7 +44,7 @@
 
 class RenderSVGResourceGradient : public RenderSVGResourceContainer {
 public:
-    RenderSVGResourceGradient(SVGGradientElement*);
+    explicit RenderSVGResourceGradient(SVGGradientElement*);
 
     virtual void removeAllClientsFromCache(bool markForInvalidation = true) OVERRIDE FINAL;
     virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true) OVERRIDE FINAL;
diff --git a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
index ed08fbe..048468c 100644
--- a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
+++ b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
@@ -30,7 +30,7 @@
 
 class RenderSVGResourceLinearGradient FINAL : public RenderSVGResourceGradient {
 public:
-    RenderSVGResourceLinearGradient(SVGLinearGradientElement*);
+    explicit RenderSVGResourceLinearGradient(SVGLinearGradientElement*);
     virtual ~RenderSVGResourceLinearGradient();
 
     virtual const char* renderName() const { return "RenderSVGResourceLinearGradient"; }
diff --git a/Source/core/rendering/svg/RenderSVGResourceMarker.h b/Source/core/rendering/svg/RenderSVGResourceMarker.h
index 7a38f1e..b88869c 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMarker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMarker.h
@@ -34,7 +34,7 @@
 
 class RenderSVGResourceMarker FINAL : public RenderSVGResourceContainer {
 public:
-    RenderSVGResourceMarker(SVGMarkerElement*);
+    explicit RenderSVGResourceMarker(SVGMarkerElement*);
     virtual ~RenderSVGResourceMarker();
 
     virtual const char* renderName() const { return "RenderSVGResourceMarker"; }
@@ -75,6 +75,12 @@
     FloatRect m_viewport;
 };
 
+inline RenderSVGResourceMarker* toRenderSVGResourceMarker(RenderSVGResource* resource)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == MarkerResourceType);
+    return static_cast<RenderSVGResourceMarker*>(resource);
+}
+
 }
 
 #endif
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.h b/Source/core/rendering/svg/RenderSVGResourceMasker.h
index f834bee..629950c 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.h
@@ -35,7 +35,7 @@
 
 class RenderSVGResourceMasker FINAL : public RenderSVGResourceContainer {
 public:
-    RenderSVGResourceMasker(SVGMaskElement*);
+    explicit RenderSVGResourceMasker(SVGMaskElement*);
     virtual ~RenderSVGResourceMasker();
 
     virtual const char* renderName() const { return "RenderSVGResourceMasker"; }
@@ -59,6 +59,12 @@
     FloatRect m_maskContentBoundaries;
 };
 
+inline RenderSVGResourceMasker* toRenderSVGResourceMasker(RenderSVGResource* resource)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == MaskerResourceType);
+    return static_cast<RenderSVGResourceMasker*>(resource);
+}
+
 }
 
 #endif
diff --git a/Source/core/rendering/svg/RenderSVGResourcePattern.h b/Source/core/rendering/svg/RenderSVGResourcePattern.h
index acd7ae6..ad47346 100644
--- a/Source/core/rendering/svg/RenderSVGResourcePattern.h
+++ b/Source/core/rendering/svg/RenderSVGResourcePattern.h
@@ -44,7 +44,7 @@
 
 class RenderSVGResourcePattern FINAL : public RenderSVGResourceContainer {
 public:
-    RenderSVGResourcePattern(SVGPatternElement*);
+    explicit RenderSVGResourcePattern(SVGPatternElement*);
 
     virtual const char* renderName() const { return "RenderSVGResourcePattern"; }
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
index f8a86e7..739de28 100644
--- a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
+++ b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
@@ -30,7 +30,7 @@
 
 class RenderSVGResourceRadialGradient FINAL : public RenderSVGResourceGradient {
 public:
-    RenderSVGResourceRadialGradient(SVGRadialGradientElement*);
+    explicit RenderSVGResourceRadialGradient(SVGRadialGradientElement*);
     virtual ~RenderSVGResourceRadialGradient();
 
     virtual const char* renderName() const { return "RenderSVGResourceRadialGradient"; }
@@ -52,6 +52,12 @@
     RadialGradientAttributes m_attributes;
 };
 
+inline RenderSVGResourceRadialGradient* toRenderSVGResourceRadialGradient(RenderSVGResourceContainer* resource)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == RadialGradientResourceType);
+    return static_cast<RenderSVGResourceRadialGradient*>(resource);
+}
+
 }
 
 #endif
diff --git a/Source/core/rendering/svg/RenderSVGText.cpp b/Source/core/rendering/svg/RenderSVGText.cpp
index 6552c0b..24eb0a0 100644
--- a/Source/core/rendering/svg/RenderSVGText.cpp
+++ b/Source/core/rendering/svg/RenderSVGText.cpp
@@ -468,11 +468,10 @@
     if (!rootBox)
         return createPositionWithAffinity(0, DOWNSTREAM);
 
-    ASSERT_WITH_SECURITY_IMPLICATION(rootBox->isSVGRootInlineBox());
     ASSERT(!rootBox->nextRootBox());
     ASSERT(childrenInline());
 
-    InlineBox* closestBox = static_cast<SVGRootInlineBox*>(rootBox)->closestLeafChildForPosition(pointInContents);
+    InlineBox* closestBox = toSVGRootInlineBox(rootBox)->closestLeafChildForPosition(pointInContents);
     if (!closestBox)
         return createPositionWithAffinity(0, DOWNSTREAM);
 
diff --git a/Source/core/rendering/svg/RenderSVGText.h b/Source/core/rendering/svg/RenderSVGText.h
index a048138..5f750c4 100644
--- a/Source/core/rendering/svg/RenderSVGText.h
+++ b/Source/core/rendering/svg/RenderSVGText.h
@@ -34,7 +34,7 @@
 
 class RenderSVGText FINAL : public RenderSVGBlock {
 public:
-    RenderSVGText(SVGTextElement*);
+    explicit RenderSVGText(SVGTextElement*);
     virtual ~RenderSVGText();
 
     virtual bool isChildAllowed(RenderObject*, RenderStyle*) const;
diff --git a/Source/core/rendering/svg/RenderSVGTextPath.h b/Source/core/rendering/svg/RenderSVGTextPath.h
index 3990a90..690604c 100644
--- a/Source/core/rendering/svg/RenderSVGTextPath.h
+++ b/Source/core/rendering/svg/RenderSVGTextPath.h
@@ -27,7 +27,7 @@
 
 class RenderSVGTextPath FINAL : public RenderSVGInline {
 public:
-    RenderSVGTextPath(Element*);
+    explicit RenderSVGTextPath(Element*);
 
     Path layoutPath() const;
     float startOffset() const;
diff --git a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
index 56be0a9..ada7f29 100644
--- a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
+++ b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
@@ -369,7 +369,7 @@
 
 static void writeRenderSVGTextBox(TextStream& ts, const RenderSVGText& text)
 {
-    SVGRootInlineBox* box = static_cast<SVGRootInlineBox*>(text.firstRootBox());
+    SVGRootInlineBox* box = toSVGRootInlineBox(text.firstRootBox());
     if (!box)
         return;
 
@@ -487,12 +487,12 @@
     ASSERT(resource);
 
     if (resource->resourceType() == MaskerResourceType) {
-        RenderSVGResourceMasker* masker = static_cast<RenderSVGResourceMasker*>(resource);
+        RenderSVGResourceMasker* masker = toRenderSVGResourceMasker(resource);
         writeNameValuePair(ts, "maskUnits", masker->maskUnits());
         writeNameValuePair(ts, "maskContentUnits", masker->maskContentUnits());
         ts << "\n";
     } else if (resource->resourceType() == FilterResourceType) {
-        RenderSVGResourceFilter* filter = static_cast<RenderSVGResourceFilter*>(resource);
+        RenderSVGResourceFilter* filter = toRenderSVGResourceFilter(resource);
         writeNameValuePair(ts, "filterUnits", filter->filterUnits());
         writeNameValuePair(ts, "primitiveUnits", filter->primitiveUnits());
         ts << "\n";
@@ -507,7 +507,7 @@
         writeNameValuePair(ts, "clipPathUnits", toRenderSVGResourceClipper(resource)->clipPathUnits());
         ts << "\n";
     } else if (resource->resourceType() == MarkerResourceType) {
-        RenderSVGResourceMarker* marker = static_cast<RenderSVGResourceMarker*>(resource);
+        RenderSVGResourceMarker* marker = toRenderSVGResourceMarker(resource);
         writeNameValuePair(ts, "markerUnits", marker->markerUnits());
         ts << " [ref at " << marker->referencePoint() << "]";
         ts << " [angle=";
@@ -541,7 +541,7 @@
 
         ts << " [start=" << gradient->startPoint(attributes) << "] [end=" << gradient->endPoint(attributes) << "]\n";
     }  else if (resource->resourceType() == RadialGradientResourceType) {
-        RenderSVGResourceRadialGradient* gradient = static_cast<RenderSVGResourceRadialGradient*>(resource);
+        RenderSVGResourceRadialGradient* gradient = toRenderSVGResourceRadialGradient(resource);
 
         // Dump final results that are used for rendering. No use in asking SVGGradientElement for its gradientUnits(), as it may
         // link to other gradients using xlink:href, we need to build the full inheritance chain, aka. collectGradientProperties()
diff --git a/Source/core/rendering/svg/SVGRootInlineBox.h b/Source/core/rendering/svg/SVGRootInlineBox.h
index e4bd6ea..41475cd 100644
--- a/Source/core/rendering/svg/SVGRootInlineBox.h
+++ b/Source/core/rendering/svg/SVGRootInlineBox.h
@@ -62,6 +62,12 @@
     float m_logicalHeight;
 };
 
+inline SVGRootInlineBox* toSVGRootInlineBox(RootInlineBox* box)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!box || box->isSVGRootInlineBox());
+    return static_cast<SVGRootInlineBox*>(box);
+}
+
 } // namespace WebCore
 
 #endif // SVGRootInlineBox_h
diff --git a/Source/core/scripts/template_expander.py b/Source/core/scripts/template_expander.py
index aafeb68..b1e99b6 100644
--- a/Source/core/scripts/template_expander.py
+++ b/Source/core/scripts/template_expander.py
@@ -31,14 +31,15 @@
 
 _current_dir = os.path.dirname(os.path.realpath(__file__))
 # jinja2 is in chromium's third_party directory
-sys.path.append(os.path.join(_current_dir, *([os.pardir] * 4)))
+# Insert at front to override system libraries, and after path[0] == script dir
+sys.path.insert(1, os.path.join(_current_dir, *([os.pardir] * 4)))
 import jinja2
 
 
 def apply_template(path_to_template, params):
     dirname, basename = os.path.split(path_to_template)
     path_to_templates = os.path.join(_current_dir, "templates")
-    jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader([dirname, path_to_templates]))
+    jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader([dirname, path_to_templates]), keep_trailing_newline=True)
     template = jinja_env.get_template(basename)
     return template.render(params)
 
diff --git a/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl b/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
index fe77d0c..c2d1a36 100644
--- a/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
+++ b/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
@@ -37,4 +37,3 @@
 } // namespace WebCore
 
 #endif // InternalRuntimeFlags_h
-
diff --git a/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl b/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl
index 4affac1..9de600f 100644
--- a/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl
+++ b/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl
@@ -22,4 +22,3 @@
 {%- endfor %}
 
 } // namespace WebCore
-
diff --git a/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl b/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl
index 2e23c87..e9eab83 100644
--- a/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl
+++ b/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl
@@ -45,4 +45,3 @@
 } // namespace WebCore
 
 #endif // RuntimeEnabledFeatures_h
-
diff --git a/Source/core/scripts/templates/StyleBuilder.cpp.tmpl b/Source/core/scripts/templates/StyleBuilder.cpp.tmpl
index a13f2b5..94b468d 100644
--- a/Source/core/scripts/templates/StyleBuilder.cpp.tmpl
+++ b/Source/core/scripts/templates/StyleBuilder.cpp.tmpl
@@ -83,4 +83,3 @@
 }
 
 } // namespace WebCore
-
diff --git a/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl b/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl
index a491e03..257dae4 100644
--- a/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl
+++ b/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl
@@ -74,11 +74,12 @@
         {% for shorthand in shorthands -%}
             {{ longhand_id }}Shorthands.uncheckedAppend({{ shorthand.camel_case_name }}Shorthand());
         {% endfor -%}
-        map.set({{ longhand_id }}, {{ longhand_id }}Shorthands);
+        // FIXME: the explicit Vector conversion copies into a temporary and is
+        // wasteful.
+        map.set({{ longhand_id }}, Vector<StylePropertyShorthand>({{ longhand_id }}Shorthands));
 {%- endfor %}
     }
     return map.get(propertyID);
 }
 
 } // namespace WebCore
-
diff --git a/Source/core/svg/SVGAltGlyphDefElement.cpp b/Source/core/svg/SVGAltGlyphDefElement.cpp
index b632087..d99b165 100644
--- a/Source/core/svg/SVGAltGlyphDefElement.cpp
+++ b/Source/core/svg/SVGAltGlyphDefElement.cpp
@@ -94,7 +94,7 @@
             fountFirstGlyphRef = true;
             String referredGlyphName;
 
-            if (static_cast<SVGGlyphRefElement*>(child)->hasValidGlyphElement(referredGlyphName))
+            if (toSVGGlyphRefElement(child)->hasValidGlyphElement(referredGlyphName))
                 glyphNames.append(referredGlyphName);
             else {
                 // As the spec says "If any of the referenced glyphs are unavailable,
diff --git a/Source/core/svg/SVGAltGlyphItemElement.cpp b/Source/core/svg/SVGAltGlyphItemElement.cpp
index 347233b..22c4d95 100644
--- a/Source/core/svg/SVGAltGlyphItemElement.cpp
+++ b/Source/core/svg/SVGAltGlyphItemElement.cpp
@@ -52,7 +52,7 @@
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
         if (child->hasTagName(SVGNames::glyphRefTag)) {
             String referredGlyphName;
-            if (static_cast<SVGGlyphRefElement*>(child)->hasValidGlyphElement(referredGlyphName))
+            if (toSVGGlyphRefElement(child)->hasValidGlyphElement(referredGlyphName))
                 glyphNames.append(referredGlyphName);
             else {
                 glyphNames.clear();
diff --git a/Source/core/svg/SVGAnimateElement.cpp b/Source/core/svg/SVGAnimateElement.cpp
index d3f1b23..f356c68 100644
--- a/Source/core/svg/SVGAnimateElement.cpp
+++ b/Source/core/svg/SVGAnimateElement.cpp
@@ -32,6 +32,7 @@
 #include "core/svg/SVGAnimatedType.h"
 #include "core/svg/SVGAnimatedTypeAnimator.h"
 #include "core/svg/SVGAnimatorFactory.h"
+#include "core/svg/SVGDocumentExtensions.h"
 
 namespace WebCore {
 
@@ -50,6 +51,8 @@
 
 SVGAnimateElement::~SVGAnimateElement()
 {
+    if (targetElement())
+        clearAnimatedType(targetElement());
 }
 
 bool SVGAnimateElement::hasValidAttributeType()
@@ -165,6 +168,10 @@
     if (animationMode() == ByAnimation && !isAdditive())
         return false;
 
+    // from-by animation may only be used with attributes that support addition (e.g. most numeric attributes).
+    if (animationMode() == FromByAnimation && !animatedPropertyTypeSupportsAddition())
+        return false;
+
     ASSERT(!hasTagName(SVGNames::setTag));
 
     determinePropertyValueTypes(fromString, byString);
@@ -207,6 +214,10 @@
     if (shouldApply == ApplyXMLAnimation) {
         // SVG DOM animVal animation code-path.
         m_animatedProperties = animator->findAnimatedPropertiesForAttributeName(targetElement, attributeName);
+        SVGElementAnimatedPropertyList::const_iterator end = m_animatedProperties.end();
+        for (SVGElementAnimatedPropertyList::const_iterator it = m_animatedProperties.begin(); it != end; ++it)
+            document().accessSVGExtensions()->addElementReferencingTarget(this, it->element);
+
         ASSERT(!m_animatedProperties.isEmpty());
 
         ASSERT(propertyTypesAreConsistent(m_animatedPropertyType, m_animatedProperties));
@@ -367,21 +378,26 @@
     notifyTargetAndInstancesAboutAnimValChange(targetElement(), attributeName());
 }
 
+bool SVGAnimateElement::animatedPropertyTypeSupportsAddition() const
+{
+    // Spec: http://www.w3.org/TR/SVG/animate.html#AnimationAttributesAndProperties.
+    switch (m_animatedPropertyType) {
+    case AnimatedBoolean:
+    case AnimatedEnumeration:
+    case AnimatedPreserveAspectRatio:
+    case AnimatedString:
+    case AnimatedUnknown:
+        return false;
+    default:
+        return true;
+    }
+}
+
 bool SVGAnimateElement::isAdditive() const
 {
-    if (animationMode() == ByAnimation || animationMode() == FromByAnimation) {
-        // Spec: http://www.w3.org/TR/SVG/animate.html#AnimationAttributesAndProperties.
-        switch (m_animatedPropertyType) {
-        case AnimatedBoolean:
-        case AnimatedEnumeration:
-        case AnimatedPreserveAspectRatio:
-        case AnimatedString:
-        case AnimatedUnknown:
+    if (animationMode() == ByAnimation || animationMode() == FromByAnimation)
+        if (!animatedPropertyTypeSupportsAddition())
             return false;
-        default:
-            break;
-        }
-    }
 
     return SVGAnimationElement::isAdditive();
 }
diff --git a/Source/core/svg/SVGAnimateElement.h b/Source/core/svg/SVGAnimateElement.h
index 16ae80d..e7f2c67 100644
--- a/Source/core/svg/SVGAnimateElement.h
+++ b/Source/core/svg/SVGAnimateElement.h
@@ -62,6 +62,7 @@
 private:
     void resetAnimatedPropertyType();
     SVGAnimatedTypeAnimator* ensureAnimator();
+    bool animatedPropertyTypeSupportsAddition() const;
 
     virtual bool hasValidAttributeType();
 
diff --git a/Source/core/svg/SVGAnimateMotionElement.cpp b/Source/core/svg/SVGAnimateMotionElement.cpp
index faf7056..c5f2de8 100644
--- a/Source/core/svg/SVGAnimateMotionElement.cpp
+++ b/Source/core/svg/SVGAnimateMotionElement.cpp
@@ -49,6 +49,12 @@
     ScriptWrappable::init(this);
 }
 
+SVGAnimateMotionElement::~SVGAnimateMotionElement()
+{
+    if (targetElement())
+        clearAnimatedType(targetElement());
+}
+
 PassRefPtr<SVGAnimateMotionElement> SVGAnimateMotionElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGAnimateMotionElement(tagName, document));
diff --git a/Source/core/svg/SVGAnimateMotionElement.h b/Source/core/svg/SVGAnimateMotionElement.h
index 79c8415..3993759 100644
--- a/Source/core/svg/SVGAnimateMotionElement.h
+++ b/Source/core/svg/SVGAnimateMotionElement.h
@@ -30,6 +30,8 @@
 
 class SVGAnimateMotionElement FINAL : public SVGAnimationElement {
 public:
+    virtual ~SVGAnimateMotionElement();
+
     static PassRefPtr<SVGAnimateMotionElement> create(const QualifiedName&, Document&);
     void updateAnimationPath();
 
diff --git a/Source/core/svg/SVGAnimateTransformElement.cpp b/Source/core/svg/SVGAnimateTransformElement.cpp
index e6a1bd4..051cf93 100644
--- a/Source/core/svg/SVGAnimateTransformElement.cpp
+++ b/Source/core/svg/SVGAnimateTransformElement.cpp
@@ -48,6 +48,9 @@
     if (!targetElement)
         return false;
 
+    if (attributeType() == AttributeTypeCSS)
+        return false;
+
     return m_animatedPropertyType == AnimatedTransformList;
 }
 
diff --git a/Source/core/svg/SVGDocumentExtensions.cpp b/Source/core/svg/SVGDocumentExtensions.cpp
index 6df85d2..4542e50 100644
--- a/Source/core/svg/SVGDocumentExtensions.cpp
+++ b/Source/core/svg/SVGDocumentExtensions.cpp
@@ -65,7 +65,7 @@
 
 void SVGDocumentExtensions::removeResource(const AtomicString& id)
 {
-    if (id.isEmpty() || !m_resources.contains(id))
+    if (id.isEmpty())
         return;
 
     m_resources.remove(id);
diff --git a/Source/core/svg/SVGElement.cpp b/Source/core/svg/SVGElement.cpp
index 9524f05..2649482 100644
--- a/Source/core/svg/SVGElement.cpp
+++ b/Source/core/svg/SVGElement.cpp
@@ -79,6 +79,7 @@
 
 SVGElement::~SVGElement()
 {
+    SVGAnimatedProperty::detachAnimatedPropertiesWrappersForElement(this);
     if (!hasSVGRareData())
         ASSERT(!SVGElementRareData::rareDataMap().contains(this));
     else {
@@ -106,6 +107,7 @@
     }
     document().accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
     document().accessSVGExtensions()->removeAllElementReferencesForTarget(this);
+    SVGAnimatedProperty::detachAnimatedPropertiesForElement(this);
 }
 
 void SVGElement::willRecalcStyle(StyleRecalcChange change)
diff --git a/Source/core/svg/SVGFEComponentTransferElement.cpp b/Source/core/svg/SVGFEComponentTransferElement.cpp
index 96cfa14..7b77498 100644
--- a/Source/core/svg/SVGFEComponentTransferElement.cpp
+++ b/Source/core/svg/SVGFEComponentTransferElement.cpp
@@ -90,13 +90,13 @@
 
     for (Node* node = firstChild(); node; node = node->nextSibling()) {
         if (node->hasTagName(SVGNames::feFuncRTag))
-            red = static_cast<SVGFEFuncRElement*>(node)->transferFunction();
+            red = toSVGFEFuncRElement(node)->transferFunction();
         else if (node->hasTagName(SVGNames::feFuncGTag))
-            green = static_cast<SVGFEFuncGElement*>(node)->transferFunction();
+            green = toSVGFEFuncGElement(node)->transferFunction();
         else if (node->hasTagName(SVGNames::feFuncBTag))
-            blue = static_cast<SVGFEFuncBElement*>(node)->transferFunction();
+            blue = toSVGFEFuncBElement(node)->transferFunction();
         else if (node->hasTagName(SVGNames::feFuncATag))
-            alpha = static_cast<SVGFEFuncAElement*>(node)->transferFunction();
+            alpha = toSVGFEFuncAElement(node)->transferFunction();
     }
 
     RefPtr<FilterEffect> effect = FEComponentTransfer::create(filter, red, green, blue, alpha);
diff --git a/Source/core/svg/SVGFEFuncAElement.h b/Source/core/svg/SVGFEFuncAElement.h
index db63a15..7f6cfdc 100644
--- a/Source/core/svg/SVGFEFuncAElement.h
+++ b/Source/core/svg/SVGFEFuncAElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGFEFuncAElement_h
 #define SVGFEFuncAElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGComponentTransferFunctionElement.h"
 
 namespace WebCore {
@@ -33,6 +34,12 @@
     SVGFEFuncAElement(const QualifiedName&, Document&);
 };
 
+inline SVGFEFuncAElement* toSVGFEFuncAElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feFuncATag));
+    return static_cast<SVGFEFuncAElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFEFuncBElement.h b/Source/core/svg/SVGFEFuncBElement.h
index 3c0fbce..6bf582e 100644
--- a/Source/core/svg/SVGFEFuncBElement.h
+++ b/Source/core/svg/SVGFEFuncBElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGFEFuncBElement_h
 #define SVGFEFuncBElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGComponentTransferFunctionElement.h"
 
 namespace WebCore {
@@ -33,6 +34,12 @@
     SVGFEFuncBElement(const QualifiedName&, Document&);
 };
 
+inline SVGFEFuncBElement* toSVGFEFuncBElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feFuncBTag));
+    return static_cast<SVGFEFuncBElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFEFuncGElement.h b/Source/core/svg/SVGFEFuncGElement.h
index 3121aea..5b29bdc 100644
--- a/Source/core/svg/SVGFEFuncGElement.h
+++ b/Source/core/svg/SVGFEFuncGElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGFEFuncGElement_h
 #define SVGFEFuncGElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGComponentTransferFunctionElement.h"
 
 namespace WebCore {
@@ -33,6 +34,12 @@
     SVGFEFuncGElement(const QualifiedName&, Document&);
 };
 
+inline SVGFEFuncGElement* toSVGFEFuncGElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feFuncGTag));
+    return static_cast<SVGFEFuncGElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFEFuncRElement.h b/Source/core/svg/SVGFEFuncRElement.h
index 8b76e46..4822a0b 100644
--- a/Source/core/svg/SVGFEFuncRElement.h
+++ b/Source/core/svg/SVGFEFuncRElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGFEFuncRElement_h
 #define SVGFEFuncRElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGComponentTransferFunctionElement.h"
 
 namespace WebCore {
@@ -33,6 +34,12 @@
     SVGFEFuncRElement(const QualifiedName&, Document&);
 };
 
+inline SVGFEFuncRElement* toSVGFEFuncRElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feFuncRTag));
+    return static_cast<SVGFEFuncRElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFEMergeElement.cpp b/Source/core/svg/SVGFEMergeElement.cpp
index caeb9ff..401fc30 100644
--- a/Source/core/svg/SVGFEMergeElement.cpp
+++ b/Source/core/svg/SVGFEMergeElement.cpp
@@ -47,7 +47,7 @@
     FilterEffectVector& mergeInputs = effect->inputEffects();
     for (Node* node = firstChild(); node; node = node->nextSibling()) {
         if (node->hasTagName(SVGNames::feMergeNodeTag)) {
-            FilterEffect* mergeEffect = filterBuilder->getEffectById(static_cast<SVGFEMergeNodeElement*>(node)->in1CurrentValue());
+            FilterEffect* mergeEffect = filterBuilder->getEffectById(toSVGFEMergeNodeElement(node)->in1CurrentValue());
             if (!mergeEffect)
                 return 0;
             mergeInputs.append(mergeEffect);
diff --git a/Source/core/svg/SVGFEMergeNodeElement.h b/Source/core/svg/SVGFEMergeNodeElement.h
index bd90db7..9bfe59a 100644
--- a/Source/core/svg/SVGFEMergeNodeElement.h
+++ b/Source/core/svg/SVGFEMergeNodeElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGFEMergeNodeElement_h
 #define SVGFEMergeNodeElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedString.h"
 #include "core/svg/SVGElement.h"
 
@@ -44,6 +45,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGFEMergeNodeElement* toSVGFEMergeNodeElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feMergeNodeTag));
+    return static_cast<SVGFEMergeNodeElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFontFaceNameElement.h b/Source/core/svg/SVGFontFaceNameElement.h
index 92cadec..1339e4a 100644
--- a/Source/core/svg/SVGFontFaceNameElement.h
+++ b/Source/core/svg/SVGFontFaceNameElement.h
@@ -21,6 +21,7 @@
 #define SVGFontFaceNameElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/svg/SVGElement.h"
 
 namespace WebCore {
@@ -39,6 +40,12 @@
     virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
+inline SVGFontFaceNameElement* toSVGFontFaceNameElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::font_face_nameTag));
+    return static_cast<SVGFontFaceNameElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(SVG_FONTS)
diff --git a/Source/core/svg/SVGFontFaceSrcElement.cpp b/Source/core/svg/SVGFontFaceSrcElement.cpp
index 849a2a4..e5ba1db 100644
--- a/Source/core/svg/SVGFontFaceSrcElement.cpp
+++ b/Source/core/svg/SVGFontFaceSrcElement.cpp
@@ -51,9 +51,10 @@
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
         RefPtr<CSSFontFaceSrcValue> srcValue;
         if (child->hasTagName(font_face_uriTag))
-            srcValue = static_cast<SVGFontFaceUriElement*>(child)->srcValue();
+            srcValue = toSVGFontFaceUriElement(child)->srcValue();
         else if (child->hasTagName(font_face_nameTag))
-            srcValue = static_cast<SVGFontFaceNameElement*>(child)->srcValue();
+            srcValue = toSVGFontFaceNameElement(child)->srcValue();
+
         if (srcValue && srcValue->resource().length())
             list->append(srcValue);
     }
diff --git a/Source/core/svg/SVGFontFaceUriElement.h b/Source/core/svg/SVGFontFaceUriElement.h
index fb4f8c8..8a3f84e 100644
--- a/Source/core/svg/SVGFontFaceUriElement.h
+++ b/Source/core/svg/SVGFontFaceUriElement.h
@@ -21,6 +21,7 @@
 #define SVGFontFaceUriElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/fetch/FontResource.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/svg/SVGElement.h"
@@ -51,6 +52,12 @@
     ResourcePtr<FontResource> m_resource;
 };
 
+inline SVGFontFaceUriElement* toSVGFontFaceUriElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::font_face_uriTag));
+    return static_cast<SVGFontFaceUriElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(SVG_FONTS)
diff --git a/Source/core/svg/SVGGlyphRefElement.h b/Source/core/svg/SVGGlyphRefElement.h
index 62e1cfe..21a2e4f 100644
--- a/Source/core/svg/SVGGlyphRefElement.h
+++ b/Source/core/svg/SVGGlyphRefElement.h
@@ -21,6 +21,7 @@
 #define SVGGlyphRefElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGURIReference.h"
 
@@ -64,6 +65,12 @@
     float m_dy;
 };
 
+inline SVGGlyphRefElement* toSVGGlyphRefElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::glyphRefTag));
+    return static_cast<SVGGlyphRefElement*>(node);
+}
+
 }
 
 #endif
diff --git a/Source/core/svg/SVGLength.cpp b/Source/core/svg/SVGLength.cpp
index f6ae8a7..4f78c90 100644
--- a/Source/core/svg/SVGLength.cpp
+++ b/Source/core/svg/SVGLength.cpp
@@ -34,6 +34,18 @@
 
 namespace WebCore {
 
+static inline SVGLengthMode toSVGLengthMode(unsigned short mode)
+{
+    ASSERT(mode >= LengthModeWidth && mode <= LengthModeOther);
+    return static_cast<SVGLengthMode>(mode);
+}
+
+static inline SVGLengthType toSVGLengthType(unsigned short type)
+{
+    ASSERT(type >= LengthTypeUnknown && type <= LengthTypePC);
+    return static_cast<SVGLengthType>(type);
+}
+
 static inline unsigned int storeUnit(SVGLengthMode mode, SVGLengthType type)
 {
     return (mode << 4) | type;
@@ -42,14 +54,14 @@
 static inline SVGLengthMode extractMode(unsigned int unit)
 {
     unsigned int mode = unit >> 4;
-    return static_cast<SVGLengthMode>(mode);
+    return toSVGLengthMode(mode);
 }
 
 static inline SVGLengthType extractType(unsigned int unit)
 {
     unsigned int mode = unit >> 4;
     unsigned int type = unit ^ (mode << 4);
-    return static_cast<SVGLengthType>(type);
+    return toSVGLengthType(type);
 }
 
 static inline String lengthTypeToString(SVGLengthType type)
@@ -266,7 +278,7 @@
         return;
     }
 
-    m_unit = storeUnit(extractMode(m_unit), static_cast<SVGLengthType>(type));
+    m_unit = storeUnit(extractMode(m_unit), toSVGLengthType(type));
     m_valueInSpecifiedUnits = value;
 }
 
@@ -282,7 +294,7 @@
         return;
 
     unsigned int originalUnitAndType = m_unit;
-    m_unit = storeUnit(extractMode(m_unit), static_cast<SVGLengthType>(type));
+    m_unit = storeUnit(extractMode(m_unit), toSVGLengthType(type));
     setValue(valueInUserUnits, context, es);
     if (!es.hadException())
         return;
diff --git a/Source/core/svg/SVGStyleElement.h b/Source/core/svg/SVGStyleElement.h
index e263f90..35cf7be 100644
--- a/Source/core/svg/SVGStyleElement.h
+++ b/Source/core/svg/SVGStyleElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGStyleElement_h
 #define SVGStyleElement_h
 
+#include "SVGNames.h"
 #include "core/dom/StyleElement.h"
 #include "core/svg/SVGElement.h"
 
@@ -67,6 +68,12 @@
     Timer<SVGElement> m_svgLoadEventTimer;
 };
 
+inline SVGStyleElement* toSVGStyleElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::styleTag));
+    return static_cast<SVGStyleElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // SVGStyleElement_h
diff --git a/Source/core/svg/SVGUseElement.cpp b/Source/core/svg/SVGUseElement.cpp
index 58910f3..68fbe2f 100644
--- a/Source/core/svg/SVGUseElement.cpp
+++ b/Source/core/svg/SVGUseElement.cpp
@@ -110,7 +110,7 @@
     // wait for the lazy creation to happen if e.g. JS wants to access the instanceRoot
     // object right after creating the element on-the-fly
     if (!m_targetElementInstance)
-        document().updateLayoutIgnorePendingStylesheets();
+        document().updateStyleIfNeeded();
 
     return m_targetElementInstance.get();
 }
diff --git a/Source/core/svg/animation/SVGSMILElement.cpp b/Source/core/svg/animation/SVGSMILElement.cpp
index 91c3499..2e852a6 100644
--- a/Source/core/svg/animation/SVGSMILElement.cpp
+++ b/Source/core/svg/animation/SVGSMILElement.cpp
@@ -45,6 +45,32 @@
 
 namespace WebCore {
 
+class RepeatEvent : public Event {
+public:
+    static PassRefPtr<RepeatEvent> create(const AtomicString& type, int repeat)
+    {
+        return adoptRef(new RepeatEvent(type, false, false, repeat));
+    }
+
+    ~RepeatEvent() { }
+
+    int repeat() const { return m_repeat; }
+protected:
+    RepeatEvent(const AtomicString& type, bool canBubble, bool cancelable, int repeat = -1)
+        : Event(type, canBubble, cancelable)
+        , m_repeat(repeat)
+    {
+    }
+private:
+    int m_repeat;
+};
+
+inline RepeatEvent* toRepeatEvent(Event* event)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->type() == "repeatn");
+    return static_cast<RepeatEvent*>(event);
+}
+
 static SMILEventSender& smilEndEventSender()
 {
     DEFINE_STATIC_LOCAL(SMILEventSender, sender, ("endEvent"));
@@ -121,12 +147,13 @@
     m_animation->handleConditionEvent(event, m_condition);
 }
 
-SVGSMILElement::Condition::Condition(Type type, BeginOrEnd beginOrEnd, const String& baseID, const String& name, SMILTime offset)
+SVGSMILElement::Condition::Condition(Type type, BeginOrEnd beginOrEnd, const String& baseID, const String& name, SMILTime offset, int repeat)
     : m_type(type)
     , m_beginOrEnd(beginOrEnd)
     , m_baseID(baseID)
     , m_name(name)
     , m_offset(offset)
+    , m_repeat(repeat)
 {
 }
 
@@ -373,6 +400,7 @@
     String parseString = value.stripWhiteSpace();
 
     double sign = 1.;
+    bool ok;
     size_t pos = parseString.find('+');
     if (pos == notFound) {
         pos = parseString.find('-');
@@ -407,7 +435,14 @@
         return false;
 
     Condition::Type type;
-    if (nameString == "begin" || nameString == "end") {
+    int repeat = -1;
+    if (nameString.startsWith("repeat(") && nameString.endsWith(')')) {
+        repeat = nameString.substring(7, nameString.length() - 8).toUIntStrict(&ok);
+        if (!ok)
+            return false;
+        nameString = "repeatn";
+        type = Condition::EventBase;
+    } else if (nameString == "begin" || nameString == "end") {
         if (baseID.isEmpty())
             return false;
         type = Condition::Syncbase;
@@ -417,7 +452,7 @@
     } else
         type = Condition::EventBase;
 
-    m_conditions.append(Condition(type, beginOrEnd, baseID, nameString, offset));
+    m_conditions.append(Condition(type, beginOrEnd, baseID, nameString, offset, repeat));
 
     if (type == Condition::EventBase && beginOrEnd == End)
         m_hasEndEventConditions = true;
@@ -516,6 +551,8 @@
     else if (attrName.matches(XLinkNames::hrefAttr)) {
         SVGElementInstance::InvalidationGuard invalidationGuard(this);
         buildPendingResource();
+        if (m_targetElement)
+            clearAnimatedType(m_targetElement);
     } else if (inDocument()) {
         if (attrName == SVGNames::beginAttr)
             beginListChanged(elapsed());
@@ -761,7 +798,7 @@
         return SMILTime::unresolved();
 
     if (currentTime < minimumTime)
-        return beginOrEnd == Begin ? SMILTime::unresolved() : SMILTime::indefinite();
+        return SMILTime::unresolved();
     if (currentTime > minimumTime)
         return currentTime;
 
@@ -872,7 +909,7 @@
     }
 }
 
-void SVGSMILElement::resolveNextInterval(bool notifyDependents)
+bool SVGSMILElement::resolveNextInterval(bool notifyDependents)
 {
     SMILTime begin;
     SMILTime end;
@@ -885,7 +922,10 @@
         if (notifyDependents)
             notifyDependentsIntervalChanged(NewInterval);
         m_nextProgressTime = min(m_nextProgressTime, m_intervalBegin);
+        return true;
     }
+
+    return false;
 }
 
 SMILTime SVGSMILElement::nextProgressTime() const
@@ -984,13 +1024,15 @@
         if (nextBegin < m_intervalEnd && elapsed >= nextBegin) {
             // End current interval, and start a new interval from the 'nextBegin' time.
             m_intervalEnd = nextBegin;
-            resolveNextInterval(false);
+            if (!resolveNextInterval(false))
+                break;
             continue;
         }
 
         // If the desired 'elapsed' time is past the current interval, advance to the next.
         if (elapsed >= m_intervalEnd) {
-            resolveNextInterval(false);
+            if (!resolveNextInterval(false))
+                break;
             continue;
         }
 
@@ -1206,8 +1248,11 @@
     m_timeDependents.remove(animation);
 }
 
-void SVGSMILElement::handleConditionEvent(Event*, Condition* condition)
+void SVGSMILElement::handleConditionEvent(Event* event, Condition* condition)
 {
+    if (event->type() == "repeatn" && toRepeatEvent(event)->repeat() != condition->m_repeat)
+        return;
+
     SMILTime elapsed = this->elapsed();
     if (condition->m_beginOrEnd == Begin)
         addBeginTime(elapsed, elapsed + condition->m_offset);
@@ -1241,7 +1286,7 @@
     if (eventType == "repeatn") {
         unsigned repeatEventCount = m_repeatEventCountList.first();
         m_repeatEventCountList.remove(0);
-        dispatchEvent(Event::create(String("repeat(" + String::number(repeatEventCount) + ")")));
+        dispatchEvent(RepeatEvent::create(eventType, repeatEventCount));
     } else {
         dispatchEvent(Event::create(eventType));
     }
diff --git a/Source/core/svg/animation/SVGSMILElement.h b/Source/core/svg/animation/SVGSMILElement.h
index b7213f5..e9d5e05 100644
--- a/Source/core/svg/animation/SVGSMILElement.h
+++ b/Source/core/svg/animation/SVGSMILElement.h
@@ -145,7 +145,7 @@
 
     SMILTime findInstanceTime(BeginOrEnd, SMILTime minimumTime, bool equalsMinimumOK) const;
     void resolveFirstInterval();
-    void resolveNextInterval(bool notifyDependents);
+    bool resolveNextInterval(bool notifyDependents);
     void resolveInterval(bool first, SMILTime& beginResult, SMILTime& endResult) const;
     SMILTime resolveActiveEnd(SMILTime resolvedBegin, SMILTime resolvedEnd) const;
     SMILTime repeatingDuration() const;
@@ -162,12 +162,13 @@
             AccessKey
         };
 
-        Condition(Type, BeginOrEnd, const String& baseID, const String& name, SMILTime offset);
+        Condition(Type, BeginOrEnd, const String& baseID, const String& name, SMILTime offset, int repeat = -1);
         Type m_type;
         BeginOrEnd m_beginOrEnd;
         String m_baseID;
         String m_name;
         SMILTime m_offset;
+        int m_repeat;
         RefPtr<Element> m_syncbase;
         RefPtr<ConditionEventListener> m_eventListener;
     };
diff --git a/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h b/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h
index fdbd217..f63a625 100644
--- a/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h
@@ -109,16 +109,18 @@
     {
         ASSERT(m_isAnimating);
         ASSERT(m_animVal);
-        ASSERT(m_values.size() == m_wrappers.size());
+        ASSERT(contextElement());
 
         ListProperty* animVal = static_cast<ListProperty*>(m_animVal.get());
-        ASSERT(animVal->values().size() == animVal->wrappers().size());
-        ASSERT(animVal->wrappers().size() == m_animatedWrappers.size());
+        if (animVal->wrappers().size()) {
+            ASSERT(m_values.size() == m_wrappers.size());
+            ASSERT(animVal->values().size() == animVal->wrappers().size());
+            ASSERT(animVal->wrappers().size() == m_animatedWrappers.size());
 
-        animVal->setValuesAndWrappers(&m_values, &m_wrappers, false);
-        ASSERT(animVal->values().size() == animVal->wrappers().size());
-        ASSERT(animVal->wrappers().size() == m_wrappers.size());
-
+            animVal->setValuesAndWrappers(&m_values, &m_wrappers, false);
+            ASSERT(animVal->values().size() == animVal->wrappers().size());
+            ASSERT(animVal->wrappers().size() == m_wrappers.size());
+        }
         m_animatedWrappers.clear();
         m_isAnimating = false;
     }
@@ -153,6 +155,14 @@
         synchronizeWrappersIfNeeded();
     }
 
+    virtual void detachWrappers() OVERRIDE
+    {
+        if (m_animVal) {
+            ListProperty* animVal = static_cast<ListProperty*>(m_animVal.get());
+            animVal->detachListWrappers(0);
+        }
+    }
+
     static PassRefPtr<SVGAnimatedListPropertyTearOff<PropertyType> > create(SVGElement* contextElement, const QualifiedName& attributeName, AnimatedPropertyType animatedPropertyType, PropertyType& values)
     {
         ASSERT(contextElement);
@@ -168,6 +178,14 @@
             m_wrappers.fill(0, values.size());
     }
 
+    ~SVGAnimatedListPropertyTearOff()
+    {
+        if (m_baseVal)
+            static_cast<ListPropertyTearOff*>(m_baseVal.get())->clearAnimatedProperty();
+        if (m_animVal)
+            static_cast<ListPropertyTearOff*>(m_animVal.get())->clearAnimatedProperty();
+    }
+
     PropertyType& m_values;
 
     ListWrapperCache m_wrappers;
diff --git a/Source/core/svg/properties/SVGAnimatedProperty.cpp b/Source/core/svg/properties/SVGAnimatedProperty.cpp
index e15971c..0922ac9 100644
--- a/Source/core/svg/properties/SVGAnimatedProperty.cpp
+++ b/Source/core/svg/properties/SVGAnimatedProperty.cpp
@@ -36,18 +36,37 @@
 
 SVGAnimatedProperty::~SVGAnimatedProperty()
 {
-    // Remove wrapper from cache.
+    // Assure that animationEnded() was called, if animationStarted() was called before.
+    ASSERT(!m_isAnimating);
+}
+
+void SVGAnimatedProperty::detachAnimatedPropertiesWrappersForElement(SVGElement* element)
+{
     Cache* cache = animatedPropertyCache();
     const Cache::const_iterator end = cache->end();
     for (Cache::const_iterator it = cache->begin(); it != end; ++it) {
-        if (it->value == this) {
-            cache->remove(it->key);
-            break;
+        if (it->key.m_element == element)
+            it->value->detachWrappers();
+    }
+}
+
+void SVGAnimatedProperty::detachAnimatedPropertiesForElement(SVGElement* element)
+{
+    // Remove wrappers from cache.
+    Cache* cache = animatedPropertyCache();
+
+    Vector<SVGAnimatedPropertyDescription> keysToRemove;
+
+    const Cache::const_iterator end = cache->end();
+    for (Cache::const_iterator it = cache->begin(); it != end; ++it) {
+        if (it->key.m_element == element) {
+            it->value->resetContextElement();
+            keysToRemove.append(it->key);
         }
     }
 
-    // Assure that animationEnded() was called, if animationStarted() was called before.
-    ASSERT(!m_isAnimating);
+    for (Vector<SVGAnimatedPropertyDescription>::const_iterator it = keysToRemove.begin(); it != keysToRemove.end(); ++it)
+        cache->remove(*it);
 }
 
 void SVGAnimatedProperty::commitChange()
diff --git a/Source/core/svg/properties/SVGAnimatedProperty.h b/Source/core/svg/properties/SVGAnimatedProperty.h
index 37eba88..acf0e74 100644
--- a/Source/core/svg/properties/SVGAnimatedProperty.h
+++ b/Source/core/svg/properties/SVGAnimatedProperty.h
@@ -31,7 +31,8 @@
 
 class SVGAnimatedProperty : public RefCounted<SVGAnimatedProperty> {
 public:
-    SVGElement* contextElement() const { return m_contextElement.get(); }
+    SVGElement* contextElement() const { return m_contextElement; }
+    void resetContextElement() { m_contextElement = 0; }
     const QualifiedName& attributeName() const { return m_attributeName; }
     AnimatedPropertyType animatedPropertyType() const { return m_animatedPropertyType; }
     bool isAnimating() const { return m_isAnimating; }
@@ -41,9 +42,10 @@
     void commitChange();
 
     virtual bool isAnimatedListTearOff() const { return false; }
+    virtual void detachWrappers() { }
 
     // Caching facilities.
-    typedef HashMap<SVGAnimatedPropertyDescription, SVGAnimatedProperty*, SVGAnimatedPropertyDescriptionHash, SVGAnimatedPropertyDescriptionHashTraits> Cache;
+    typedef HashMap<SVGAnimatedPropertyDescription, RefPtr<SVGAnimatedProperty>, SVGAnimatedPropertyDescriptionHash, SVGAnimatedPropertyDescriptionHashTraits> Cache;
 
     virtual ~SVGAnimatedProperty();
 
@@ -57,7 +59,7 @@
             wrapper = TearOffType::create(element, info->attributeName, info->animatedPropertyType, property);
             if (info->animatedPropertyState == PropertyIsReadOnly)
                 wrapper->setIsReadOnly();
-            animatedPropertyCache()->set(key, wrapper.get());
+            animatedPropertyCache()->set(key, wrapper);
         }
         return static_pointer_cast<TearOffType>(wrapper);
     }
@@ -76,13 +78,16 @@
         return lookupWrapper<OwnerType, TearOffType>(const_cast<OwnerType*>(element), info);
     }
 
+    static void detachAnimatedPropertiesWrappersForElement(SVGElement*);
+    static void detachAnimatedPropertiesForElement(SVGElement*);
+
 protected:
     SVGAnimatedProperty(SVGElement*, const QualifiedName&, AnimatedPropertyType);
 
 private:
     static Cache* animatedPropertyCache();
 
-    RefPtr<SVGElement> m_contextElement;
+    SVGElement* m_contextElement;
     const QualifiedName& m_attributeName;
     AnimatedPropertyType m_animatedPropertyType;
 
diff --git a/Source/core/svg/properties/SVGListPropertyTearOff.h b/Source/core/svg/properties/SVGListPropertyTearOff.h
index c6246d7..640d724 100644
--- a/Source/core/svg/properties/SVGListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGListPropertyTearOff.h
@@ -92,7 +92,8 @@
 
     PassListItemTearOff getItem(unsigned index, ExceptionState& es)
     {
-        return Base::getItemValuesAndWrappers(m_animatedProperty.get(), index, es);
+        ASSERT(m_animatedProperty);
+        return Base::getItemValuesAndWrappers(m_animatedProperty, index, es);
     }
 
     PassListItemTearOff insertItemBefore(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
@@ -107,7 +108,8 @@
 
     PassListItemTearOff removeItem(unsigned index, ExceptionState& es)
     {
-        return Base::removeItemValuesAndWrappers(m_animatedProperty.get(), index, es);
+        ASSERT(m_animatedProperty);
+        return Base::removeItemValuesAndWrappers(m_animatedProperty, index, es);
     }
 
     PassListItemTearOff appendItem(PassListItemTearOff passNewItem, ExceptionState& es)
@@ -115,11 +117,27 @@
         return Base::appendItemValuesAndWrappers(passNewItem, es);
     }
 
+    SVGElement* contextElement() const
+    {
+        ASSERT(m_animatedProperty);
+        return m_animatedProperty->contextElement();
+    }
+
+    void clearAnimatedProperty()
+    {
+        ASSERT(m_animatedProperty);
+        Base::detachListWrappers(0);
+        m_animatedProperty = 0;
+        m_values = 0;
+        m_wrappers = 0;
+    }
+
 protected:
     SVGListPropertyTearOff(AnimatedListPropertyTearOff* animatedProperty, SVGPropertyRole role, PropertyType& values, ListWrapperCache& wrappers)
         : SVGListProperty<PropertyType>(role, values, &wrappers)
         , m_animatedProperty(animatedProperty)
     {
+        ASSERT(m_animatedProperty);
     }
 
     virtual bool isReadOnly() const
@@ -135,6 +153,7 @@
     {
         ASSERT(m_values);
         ASSERT(m_wrappers);
+        ASSERT(m_animatedProperty);
 
         // Update existing wrappers, as the index in the values list has changed.
         unsigned size = m_wrappers->size();
@@ -143,7 +162,7 @@
             ListItemTearOff* item = m_wrappers->at(i).get();
             if (!item)
                 continue;
-            item->setAnimatedProperty(m_animatedProperty.get());
+            item->setAnimatedProperty(m_animatedProperty);
             item->setValue(m_values->at(i));
         }
 
@@ -179,6 +198,7 @@
 
         // Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
         // 'newItem' is already living in another list. If it's not our list, synchronize the other lists wrappers after the removal.
+        ASSERT(m_animatedProperty);
         bool livesInOtherList = animatedPropertyOfItem != m_animatedProperty;
         AnimatedListPropertyTearOff* propertyTearOff = static_cast<AnimatedListPropertyTearOff*>(animatedPropertyOfItem);
         int indexToRemove = propertyTearOff->findItem(newItem.get());
@@ -206,7 +226,7 @@
 
     // Back pointer to the animated property that created us
     // For example (text.x.baseVal): m_animatedProperty points to the 'x' SVGAnimatedLengthList object
-    RefPtr<AnimatedListPropertyTearOff> m_animatedProperty;
+    AnimatedListPropertyTearOff* m_animatedProperty;
 };
 
 }
diff --git a/Source/core/svg/properties/SVGMatrixTearOff.h b/Source/core/svg/properties/SVGMatrixTearOff.h
new file mode 100644
index 0000000..338899d
--- /dev/null
+++ b/Source/core/svg/properties/SVGMatrixTearOff.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef SVGMatrixTearOff_h
+#define SVGMatrixTearOff_h
+
+#include "core/svg/SVGTransform.h"
+#include "core/svg/properties/SVGPropertyTearOff.h"
+
+namespace WebCore {
+
+class SVGMatrixTearOff : public SVGPropertyTearOff<SVGMatrix> {
+public:
+    // Used for non-animated POD types that are not associated with a SVGAnimatedProperty object, nor with a XML DOM attribute
+    // and that contain a parent type that's exposed to the bindings via a SVGStaticPropertyTearOff object
+    // (for example: SVGTransform::matrix).
+    static PassRefPtr<SVGMatrixTearOff> create(SVGPropertyTearOff<SVGTransform>* parent, SVGMatrix& value)
+    {
+        ASSERT(parent);
+        RefPtr<SVGMatrixTearOff> result = adoptRef(new SVGMatrixTearOff(parent, value));
+        parent->addChild(result->m_weakFactory.createWeakPtr());
+        return result.release();
+    }
+
+    virtual void commitChange()
+    {
+        m_parent->propertyReference().updateSVGMatrix();
+        m_parent->commitChange();
+    }
+
+private:
+    SVGMatrixTearOff(SVGPropertyTearOff<SVGTransform>* parent, SVGMatrix& value)
+        : SVGPropertyTearOff<SVGMatrix>(0, UndefinedRole, value)
+        , m_parent(parent)
+        , m_weakFactory(this)
+    {
+    }
+
+    RefPtr<SVGPropertyTearOff<SVGTransform> > m_parent;
+    WeakPtrFactory<SVGPropertyTearOffBase > m_weakFactory;
+};
+
+}
+
+#endif // SVGMatrixTearOff_h
diff --git a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
index 56055ed..58791d7 100644
--- a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
@@ -41,6 +41,9 @@
         return adoptRef(new SVGPathSegListPropertyTearOff(animatedProperty, role, pathSegRole, values, wrappers));
     }
 
+    SVGPathElement* contextElement() const;
+    SVGAnimatedProperty* animatedProperty() const { return m_animatedProperty.get(); }
+
     int findItem(const ListItemType& item) const
     {
         ASSERT(m_values);
@@ -119,8 +122,6 @@
     {
     }
 
-    SVGPathElement* contextElement() const;
-
     void clearContextAndRoles();
 
     using Base::m_role;
diff --git a/Source/core/svg/properties/SVGPropertyTearOff.h b/Source/core/svg/properties/SVGPropertyTearOff.h
index ac22ff8..8866bcc 100644
--- a/Source/core/svg/properties/SVGPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGPropertyTearOff.h
@@ -23,11 +23,17 @@
 #include "core/svg/SVGElement.h"
 #include "core/svg/properties/SVGAnimatedProperty.h"
 #include "core/svg/properties/SVGProperty.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
+class SVGPropertyTearOffBase : public SVGProperty {
+public:
+    virtual void detachWrapper() = 0;
+};
+
 template<typename PropertyType>
-class SVGPropertyTearOff : public SVGProperty {
+class SVGPropertyTearOff : public SVGPropertyTearOffBase {
 public:
     typedef SVGPropertyTearOff<PropertyType> Self;
 
@@ -68,14 +74,22 @@
     {
         if (!m_animatedProperty || m_valueIsCopy)
             return 0;
-        return m_contextElement.get();
+        ASSERT(m_contextElement);
+        return m_contextElement;
     }
 
-    void detachWrapper()
+    void addChild(WeakPtr<SVGPropertyTearOffBase> child)
+    {
+        m_childTearOffs.append(child);
+    }
+
+    virtual void detachWrapper() OVERRIDE
     {
         if (m_valueIsCopy)
             return;
 
+        detachChildren();
+
         // Switch from a live value, to a non-live value.
         // For example: <text x="50"/>
         // var item = text.x.baseVal.getItem(0);
@@ -132,10 +146,20 @@
             delete m_value;
     }
 
-    RefPtr<SVGElement> m_contextElement;
+    void detachChildren()
+    {
+        for (Vector<WeakPtr<SVGPropertyTearOffBase> >::iterator iter = m_childTearOffs.begin(); iter != m_childTearOffs.end(); iter++) {
+            if (iter->get())
+                iter->get()->detachWrapper();
+        }
+        m_childTearOffs.clear();
+    }
+
+    SVGElement* m_contextElement;
     SVGAnimatedProperty* m_animatedProperty;
     SVGPropertyRole m_role;
     PropertyType* m_value;
+    Vector<WeakPtr<SVGPropertyTearOffBase> > m_childTearOffs;
     bool m_valueIsCopy : 1;
 };
 
diff --git a/Source/core/svg/properties/SVGStaticListPropertyTearOff.h b/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
index 367560f..1488c59 100644
--- a/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
@@ -43,6 +43,8 @@
         return adoptRef(new SVGStaticListPropertyTearOff<PropertyType>(contextElement, values));
     }
 
+    SVGElement* contextElement() const { return m_contextElement; }
+
     // SVGList API
     void clear(ExceptionState& es)
     {
@@ -94,7 +96,8 @@
     virtual void commitChange()
     {
         ASSERT(m_values);
-        m_values->commitChange(m_contextElement.get());
+        ASSERT(m_contextElement);
+        m_values->commitChange(m_contextElement);
     }
 
     virtual bool processIncomingListItemValue(const ListItemType&, unsigned*)
@@ -110,7 +113,7 @@
     }
 
 private:
-    RefPtr<SVGElement> m_contextElement;
+    SVGElement* m_contextElement;
 };
 
 }
diff --git a/Source/core/svg/properties/SVGStaticPropertyWithParentTearOff.h b/Source/core/svg/properties/SVGStaticPropertyWithParentTearOff.h
deleted file mode 100644
index 19c208b..0000000
--- a/Source/core/svg/properties/SVGStaticPropertyWithParentTearOff.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGStaticPropertyWithParentTearOff_h
-#define SVGStaticPropertyWithParentTearOff_h
-
-#include "core/svg/properties/SVGPropertyTearOff.h"
-
-namespace WebCore {
-
-#if COMPILER(MSVC)
-// UpdateMethod is 12 bytes. We have to pack to a size greater than or equal to that to avoid an
-// alignment warning (C4121). 16 is the next-largest size allowed for packing, so we use that.
-#pragma pack(push, 16)
-#endif
-template<typename ParentType, typename PropertyType>
-class SVGStaticPropertyWithParentTearOff : public SVGPropertyTearOff<PropertyType> {
-public:
-    typedef SVGStaticPropertyWithParentTearOff<ParentType, PropertyType> Self;
-    typedef void (ParentType::*UpdateMethod)();
-
-    // Used for non-animated POD types that are not associated with a SVGAnimatedProperty object, nor with a XML DOM attribute
-    // and that contain a parent type that's exposed to the bindings via a SVGStaticPropertyTearOff object
-    // (for example: SVGTransform::matrix).
-    static PassRefPtr<Self> create(SVGProperty* parent, PropertyType& value, UpdateMethod update)
-    {
-        ASSERT(parent);
-        return adoptRef(new Self(parent, value, update));
-    }
-
-    virtual void commitChange()
-    {
-        (static_cast<SVGPropertyTearOff<ParentType>*>(m_parent.get())->propertyReference().*m_update)();
-        m_parent->commitChange();
-    }
-
-private:
-    SVGStaticPropertyWithParentTearOff(SVGProperty* parent, PropertyType& value, UpdateMethod update)
-        : SVGPropertyTearOff<PropertyType>(0, UndefinedRole, value)
-        , m_update(update)
-        , m_parent(parent)
-    {
-    }
-
-    UpdateMethod m_update;
-    RefPtr<SVGProperty> m_parent;
-};
-#if COMPILER(MSVC)
-#pragma pack(pop)
-#endif
-
-}
-
-#endif // SVGStaticPropertyWithParentTearOff_h
diff --git a/Source/core/testing/GCObservation.cpp b/Source/core/testing/GCObservation.cpp
index 93176bd..90738d4 100644
--- a/Source/core/testing/GCObservation.cpp
+++ b/Source/core/testing/GCObservation.cpp
@@ -46,7 +46,7 @@
 }
 
 GCObservation::GCObservation(v8::Handle<v8::Value> observedValue)
-    : m_observed(observedValue)
+    : m_observed(v8::Isolate::GetCurrent(), observedValue)
     , m_collected(false)
 {
     m_observed.makeWeak(this, makeWeakCallback);
diff --git a/Source/core/testing/InternalSettings.cpp b/Source/core/testing/InternalSettings.cpp
index dc78943..33c45eb 100644
--- a/Source/core/testing/InternalSettings.cpp
+++ b/Source/core/testing/InternalSettings.cpp
@@ -61,6 +61,7 @@
     , m_originalAuthorShadowDOMForAnyElementEnabled(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
     , m_originalExperimentalWebSocketEnabled(settings->experimentalWebSocketEnabled())
     , m_originalStyleScoped(RuntimeEnabledFeatures::styleScopedEnabled())
+    , m_originalOverlayScrollbarsEnabled(RuntimeEnabledFeatures::overlayScrollbarsEnabled())
     , m_originalEditingBehavior(settings->editingBehaviorType())
     , m_originalTextAutosizingEnabled(settings->textAutosizingEnabled())
     , m_originalTextAutosizingWindowSizeOverride(settings->textAutosizingWindowSizeOverride())
@@ -83,6 +84,7 @@
     RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(m_originalAuthorShadowDOMForAnyElementEnabled);
     settings->setExperimentalWebSocketEnabled(m_originalExperimentalWebSocketEnabled);
     RuntimeEnabledFeatures::setStyleScopedEnabled(m_originalStyleScoped);
+    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(m_originalOverlayScrollbarsEnabled);
     settings->setEditingBehaviorType(m_originalEditingBehavior);
     settings->setTextAutosizingEnabled(m_originalTextAutosizingEnabled);
     settings->setTextAutosizingWindowSizeOverride(m_originalTextAutosizingWindowSizeOverride);
@@ -176,6 +178,11 @@
     RuntimeEnabledFeatures::setStyleScopedEnabled(enabled);
 }
 
+void InternalSettings::setOverlayScrollbarsEnabled(bool enabled)
+{
+    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);
+}
+
 void InternalSettings::setTouchEventEmulationEnabled(bool enabled, ExceptionState& es)
 {
     InternalSettingsGuardForSettings();
diff --git a/Source/core/testing/InternalSettings.h b/Source/core/testing/InternalSettings.h
index f364686..7433e1e 100644
--- a/Source/core/testing/InternalSettings.h
+++ b/Source/core/testing/InternalSettings.h
@@ -53,6 +53,7 @@
         bool m_originalAuthorShadowDOMForAnyElementEnabled;
         bool m_originalExperimentalWebSocketEnabled;
         bool m_originalStyleScoped;
+        bool m_originalOverlayScrollbarsEnabled;
         EditingBehaviorType m_originalEditingBehavior;
         bool m_originalTextAutosizingEnabled;
         IntSize m_originalTextAutosizingWindowSizeOverride;
@@ -108,6 +109,7 @@
     void setCSSExclusionsEnabled(bool);
     void setExperimentalWebSocketEnabled(bool);
     void setLangAttributeAwareFormControlUIEnabled(bool);
+    void setOverlayScrollbarsEnabled(bool);
     void setStyleScopedEnabled(bool);
 
 private:
diff --git a/Source/core/testing/InternalSettings.idl b/Source/core/testing/InternalSettings.idl
index f1d7594..9e03edc 100644
--- a/Source/core/testing/InternalSettings.idl
+++ b/Source/core/testing/InternalSettings.idl
@@ -57,5 +57,6 @@
     void setCSSExclusionsEnabled(boolean enabled);
     void setExperimentalWebSocketEnabled(boolean enabled);
     void setLangAttributeAwareFormControlUIEnabled(boolean enabled);
+    void setOverlayScrollbarsEnabled(boolean enabled);
     void setStyleScopedEnabled(boolean enabled);
 };
diff --git a/Source/core/testing/Internals.cpp b/Source/core/testing/Internals.cpp
index ad961fa..52f3499 100644
--- a/Source/core/testing/Internals.cpp
+++ b/Source/core/testing/Internals.cpp
@@ -57,6 +57,7 @@
 #include "core/dom/PseudoElement.h"
 #include "core/dom/Range.h"
 #include "core/dom/StaticNodeList.h"
+#include "core/dom/TouchController.h"
 #include "core/dom/TreeScope.h"
 #include "core/dom/ViewportArguments.h"
 #include "core/dom/WheelController.h"
@@ -195,7 +196,6 @@
     page->setPagination(Pagination());
     TextRun::setAllowsRoundingHacks(false);
     WebCore::overrideUserPreferredLanguages(Vector<String>());
-    WebCore::RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(false);
     delete s_pagePopupDriver;
     s_pagePopupDriver = 0;
     page->chrome().client().resetPagePopupDriver();
@@ -1317,7 +1317,7 @@
         return 0;
     }
 
-    const TouchEventTargetSet* touchHandlers = document->touchEventTargets();
+    const TouchEventTargetSet* touchHandlers = TouchController::from(document)->touchEventTargets();
     if (!touchHandlers)
         return 0;
 
@@ -1737,6 +1737,30 @@
     return layer1->scrollsWithRespectTo(layer2);
 }
 
+bool Internals::isUnclippedDescendant(Element* element, ExceptionState& es)
+{
+    if (!element) {
+        es.throwDOMException(InvalidAccessError);
+        return 0;
+    }
+
+    element->document().updateLayout();
+
+    RenderObject* renderer = element->renderer();
+    if (!renderer || !renderer->isBox()) {
+        es.throwDOMException(InvalidAccessError);
+        return 0;
+    }
+
+    RenderLayer* layer = toRenderBox(renderer)->layer();
+    if (!layer) {
+        es.throwDOMException(InvalidAccessError);
+        return 0;
+    }
+
+    return layer->isUnclippedDescendant();
+}
+
 String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionState& es) const
 {
     if (!document || !document->frame()) {
@@ -1773,6 +1797,28 @@
     return layer->backing()->graphicsLayer()->layerTreeAsText(flags);
 }
 
+static RenderLayer* getRenderLayerForElement(Element* element, ExceptionState& es)
+{
+    if (!element) {
+        es.throwDOMException(InvalidAccessError);
+        return 0;
+    }
+
+    RenderObject* renderer = element->renderer();
+    if (!renderer || !renderer->isBox()) {
+        es.throwDOMException(InvalidAccessError);
+        return 0;
+    }
+
+    RenderLayer* layer = toRenderBox(renderer)->layer();
+    if (!layer) {
+        es.throwDOMException(InvalidAccessError);
+        return 0;
+    }
+
+    return layer;
+}
+
 void Internals::setNeedsCompositedScrolling(Element* element, unsigned needsCompositedScrolling, ExceptionState& es)
 {
     if (!element) {
@@ -1782,19 +1828,46 @@
 
     element->document().updateLayout();
 
-    RenderObject* renderer = element->renderer();
-    if (!renderer || !renderer->isBox()) {
-        es.throwDOMException(InvalidAccessError);
-        return;
-    }
+    if (RenderLayer* layer = getRenderLayerForElement(element, es))
+        layer->setForceNeedsCompositedScrolling(static_cast<RenderLayer::ForceNeedsCompositedScrollingMode>(needsCompositedScrolling));
+}
 
-    RenderLayer* layer = toRenderBox(renderer)->layer();
-    if (!layer) {
-        es.throwDOMException(InvalidAccessError);
-        return;
-    }
+bool Internals::isScrollParent(Element* child, Element* parent, ExceptionState& es)
+{
+    RenderLayer* childLayer = getRenderLayerForElement(child, es);
+    RenderLayer* parentLayer = getRenderLayerForElement(parent, es);
+    return childLayer && parentLayer && childLayer->scrollParent() == parentLayer;
+}
 
-    layer->setForceNeedsCompositedScrolling(static_cast<RenderLayer::ForceNeedsCompositedScrollingMode>(needsCompositedScrolling));
+bool Internals::isClipParent(Element* child, Element* parent, ExceptionState& es)
+{
+    RenderLayer* childLayer = getRenderLayerForElement(child, es);
+    RenderLayer* parentLayer = getRenderLayerForElement(parent, es);
+    return childLayer && parentLayer && childLayer->clipParent() == parentLayer;
+}
+
+PassRefPtr<ClientRect> Internals::scrollClip(Element* element, ExceptionState& es)
+{
+    RenderLayer* layer = getRenderLayerForElement(element, es);
+    if (!layer || !layer->backing() || !layer->backing()->scrollingLayer())
+        return ClientRect::create();
+
+    return ClientRect::create(
+        FloatRect(
+            layer->backing()->scrollingLayer()->boundsOrigin(),
+            layer->backing()->scrollingLayer()->size()));
+}
+
+PassRefPtr<ClientRect> Internals::ancestorScrollClip(Element* element, ExceptionState& es)
+{
+    RenderLayer* layer = getRenderLayerForElement(element, es);
+    if (!layer || !layer->backing() || !layer->backing()->ancestorScrollClippingLayer())
+        return ClientRect::create();
+
+    return ClientRect::create(
+        FloatRect(
+            layer->backing()->ancestorScrollClippingLayer()->boundsOrigin(),
+            layer->backing()->ancestorScrollClippingLayer()->size()));
 }
 
 String Internals::repaintRectsAsText(Document* document, ExceptionState& es) const
@@ -1876,7 +1949,7 @@
     RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(*document);
     parsedSheet->setIsUserStyleSheet(false);
     parsedSheet->parseString(css);
-    document->styleSheetCollections()->addAuthorSheet(parsedSheet);
+    document->styleEngine()->addAuthorSheet(parsedSheet);
 }
 
 void Internals::insertUserCSS(Document* document, const String& css) const
@@ -1887,7 +1960,7 @@
     RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(*document);
     parsedSheet->setIsUserStyleSheet(true);
     parsedSheet->parseString(css);
-    document->styleSheetCollections()->addUserSheet(parsedSheet);
+    document->styleEngine()->addUserSheet(parsedSheet);
 }
 
 String Internals::counterValue(Element* element)
@@ -2151,11 +2224,6 @@
     return SerializedScriptValue::createFromWire(value);
 }
 
-void Internals::setOverlayScrollbarsEnabled(bool enabled)
-{
-    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);
-}
-
 void Internals::forceReload(bool endToEnd)
 {
     frame()->loader()->reload(endToEnd ? EndToEndReload : NormalReload);
diff --git a/Source/core/testing/Internals.h b/Source/core/testing/Internals.h
index 817c1fc..d35185b 100644
--- a/Source/core/testing/Internals.h
+++ b/Source/core/testing/Internals.h
@@ -221,9 +221,16 @@
     PassRefPtr<NodeList> paintOrderListAfterPromote(Element*, ExceptionState&);
 
     bool scrollsWithRespectTo(Element*, Element*, ExceptionState&);
+    bool isUnclippedDescendant(Element*, ExceptionState&);
 
     void setNeedsCompositedScrolling(Element*, unsigned value, ExceptionState&);
 
+    bool isScrollParent(Element* child, Element* parent, ExceptionState&);
+    bool isClipParent(Element* child, Element* parent, ExceptionState&);
+
+    PassRefPtr<ClientRect> scrollClip(Element*, ExceptionState&);
+    PassRefPtr<ClientRect> ancestorScrollClip(Element*, ExceptionState&);
+
     String repaintRectsAsText(Document*, ExceptionState&) const;
     String scrollingStateTreeAsText(Document*, ExceptionState&) const;
     String mainThreadScrollingReasons(Document*, ExceptionState&) const;
@@ -278,8 +285,6 @@
     PassRefPtr<ArrayBuffer> serializeObject(PassRefPtr<SerializedScriptValue>) const;
     PassRefPtr<SerializedScriptValue> deserializeBuffer(PassRefPtr<ArrayBuffer>) const;
 
-    void setOverlayScrollbarsEnabled(bool);
-
     String getCurrentCursorInfo(Document*, ExceptionState&);
 
     String markerTextForListItem(Element*, ExceptionState&);
diff --git a/Source/core/testing/Internals.idl b/Source/core/testing/Internals.idl
index 6e5f1a2..c663830 100644
--- a/Source/core/testing/Internals.idl
+++ b/Source/core/testing/Internals.idl
@@ -179,6 +179,7 @@
     [RaisesException] NodeList paintOrderListAfterPromote(Element element);
 
     [RaisesException] boolean scrollsWithRespectTo(Element element1, Element element2);
+    [RaisesException] boolean isUnclippedDescendant(Element element);
 
     // The values of these constants must be kept in sync with those in RenderLayer.
     const unsigned short DO_NOT_FORCE_COMPOSITED_SCROLLING = 0;
@@ -186,6 +187,12 @@
     const unsigned short COMPOSITED_SCROLLING_ALWAYS_OFF = 2;
     [RaisesException] void setNeedsCompositedScrolling(Element element, unsigned short value);
 
+    [RaisesException] boolean isScrollParent(Element child, Element parent);
+    [RaisesException] boolean isClipParent(Element child, Element parent);
+
+    [RaisesException] ClientRect scrollClip(Element element);
+    [RaisesException] ClientRect ancestorScrollClip(Element element);
+
     [RaisesException] DOMString scrollingStateTreeAsText(Document document);
     [RaisesException] DOMString mainThreadScrollingReasons(Document document);
     [RaisesException] ClientRectList nonFastScrollableRects(Document document);
@@ -248,8 +255,6 @@
     SerializedScriptValue deserializeBuffer(ArrayBuffer buffer);
     ArrayBuffer serializeObject(SerializedScriptValue obj);
 
-    void setOverlayScrollbarsEnabled(boolean enabled);
-
     void forceReload(boolean endToEnd);
 
     void enableMockSpeechSynthesizer();
diff --git a/Source/core/webcore_derived.target.darwin-arm.mk b/Source/core/webcore_derived.target.darwin-arm.mk
index 1626ee5..788e6f4 100644
--- a/Source/core/webcore_derived.target.darwin-arm.mk
+++ b/Source/core/webcore_derived.target.darwin-arm.mk
@@ -386,7 +386,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -400,7 +400,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -552,7 +551,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -566,7 +565,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_derived.target.darwin-mips.mk b/Source/core/webcore_derived.target.darwin-mips.mk
index d7b8411..a07f852 100644
--- a/Source/core/webcore_derived.target.darwin-mips.mk
+++ b/Source/core/webcore_derived.target.darwin-mips.mk
@@ -386,7 +386,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -400,7 +400,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -552,7 +551,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -566,7 +565,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_derived.target.darwin-x86.mk b/Source/core/webcore_derived.target.darwin-x86.mk
index eca73ea..a458d90 100644
--- a/Source/core/webcore_derived.target.darwin-x86.mk
+++ b/Source/core/webcore_derived.target.darwin-x86.mk
@@ -388,7 +388,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -402,7 +402,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -557,7 +556,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -571,7 +570,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_derived.target.linux-arm.mk b/Source/core/webcore_derived.target.linux-arm.mk
index 1626ee5..788e6f4 100644
--- a/Source/core/webcore_derived.target.linux-arm.mk
+++ b/Source/core/webcore_derived.target.linux-arm.mk
@@ -386,7 +386,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -400,7 +400,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -552,7 +551,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -566,7 +565,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_derived.target.linux-mips.mk b/Source/core/webcore_derived.target.linux-mips.mk
index d7b8411..a07f852 100644
--- a/Source/core/webcore_derived.target.linux-mips.mk
+++ b/Source/core/webcore_derived.target.linux-mips.mk
@@ -386,7 +386,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -400,7 +400,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -552,7 +551,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -566,7 +565,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_derived.target.linux-x86.mk b/Source/core/webcore_derived.target.linux-x86.mk
index eca73ea..a458d90 100644
--- a/Source/core/webcore_derived.target.linux-x86.mk
+++ b/Source/core/webcore_derived.target.linux-x86.mk
@@ -388,7 +388,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -402,7 +402,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -557,7 +556,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -571,7 +570,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_dom.target.darwin-arm.mk b/Source/core/webcore_dom.target.darwin-arm.mk
index 007c570..a08ce07 100644
--- a/Source/core/webcore_dom.target.darwin-arm.mk
+++ b/Source/core/webcore_dom.target.darwin-arm.mk
@@ -129,7 +129,6 @@
 	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
-	third_party/WebKit/Source/core/dom/Notation.cpp \
 	third_party/WebKit/Source/core/dom/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -157,14 +156,15 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
+	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
-	third_party/WebKit/Source/core/dom/StyleSheetCollections.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
+	third_party/WebKit/Source/core/dom/TouchController.cpp \
 	third_party/WebKit/Source/core/dom/TouchEvent.cpp \
 	third_party/WebKit/Source/core/dom/TouchList.cpp \
 	third_party/WebKit/Source/core/dom/TransformSourceLibxslt.cpp \
@@ -231,7 +231,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -245,7 +245,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -388,7 +387,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -402,7 +401,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_dom.target.darwin-mips.mk b/Source/core/webcore_dom.target.darwin-mips.mk
index 87cb87b..7d2f2fb 100644
--- a/Source/core/webcore_dom.target.darwin-mips.mk
+++ b/Source/core/webcore_dom.target.darwin-mips.mk
@@ -129,7 +129,6 @@
 	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
-	third_party/WebKit/Source/core/dom/Notation.cpp \
 	third_party/WebKit/Source/core/dom/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -157,14 +156,15 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
+	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
-	third_party/WebKit/Source/core/dom/StyleSheetCollections.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
+	third_party/WebKit/Source/core/dom/TouchController.cpp \
 	third_party/WebKit/Source/core/dom/TouchEvent.cpp \
 	third_party/WebKit/Source/core/dom/TouchList.cpp \
 	third_party/WebKit/Source/core/dom/TransformSourceLibxslt.cpp \
@@ -231,7 +231,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -245,7 +245,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -388,7 +387,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -402,7 +401,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_dom.target.darwin-x86.mk b/Source/core/webcore_dom.target.darwin-x86.mk
index fb7e8df..5a5bbd4 100644
--- a/Source/core/webcore_dom.target.darwin-x86.mk
+++ b/Source/core/webcore_dom.target.darwin-x86.mk
@@ -129,7 +129,6 @@
 	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
-	third_party/WebKit/Source/core/dom/Notation.cpp \
 	third_party/WebKit/Source/core/dom/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -157,14 +156,15 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
+	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
-	third_party/WebKit/Source/core/dom/StyleSheetCollections.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
+	third_party/WebKit/Source/core/dom/TouchController.cpp \
 	third_party/WebKit/Source/core/dom/TouchEvent.cpp \
 	third_party/WebKit/Source/core/dom/TouchList.cpp \
 	third_party/WebKit/Source/core/dom/TransformSourceLibxslt.cpp \
@@ -233,7 +233,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -247,7 +247,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -393,7 +392,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -407,7 +406,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_dom.target.linux-arm.mk b/Source/core/webcore_dom.target.linux-arm.mk
index 007c570..a08ce07 100644
--- a/Source/core/webcore_dom.target.linux-arm.mk
+++ b/Source/core/webcore_dom.target.linux-arm.mk
@@ -129,7 +129,6 @@
 	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
-	third_party/WebKit/Source/core/dom/Notation.cpp \
 	third_party/WebKit/Source/core/dom/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -157,14 +156,15 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
+	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
-	third_party/WebKit/Source/core/dom/StyleSheetCollections.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
+	third_party/WebKit/Source/core/dom/TouchController.cpp \
 	third_party/WebKit/Source/core/dom/TouchEvent.cpp \
 	third_party/WebKit/Source/core/dom/TouchList.cpp \
 	third_party/WebKit/Source/core/dom/TransformSourceLibxslt.cpp \
@@ -231,7 +231,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -245,7 +245,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -388,7 +387,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -402,7 +401,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_dom.target.linux-mips.mk b/Source/core/webcore_dom.target.linux-mips.mk
index 87cb87b..7d2f2fb 100644
--- a/Source/core/webcore_dom.target.linux-mips.mk
+++ b/Source/core/webcore_dom.target.linux-mips.mk
@@ -129,7 +129,6 @@
 	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
-	third_party/WebKit/Source/core/dom/Notation.cpp \
 	third_party/WebKit/Source/core/dom/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -157,14 +156,15 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
+	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
-	third_party/WebKit/Source/core/dom/StyleSheetCollections.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
+	third_party/WebKit/Source/core/dom/TouchController.cpp \
 	third_party/WebKit/Source/core/dom/TouchEvent.cpp \
 	third_party/WebKit/Source/core/dom/TouchList.cpp \
 	third_party/WebKit/Source/core/dom/TransformSourceLibxslt.cpp \
@@ -231,7 +231,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -245,7 +245,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -388,7 +387,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -402,7 +401,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_dom.target.linux-x86.mk b/Source/core/webcore_dom.target.linux-x86.mk
index fb7e8df..5a5bbd4 100644
--- a/Source/core/webcore_dom.target.linux-x86.mk
+++ b/Source/core/webcore_dom.target.linux-x86.mk
@@ -129,7 +129,6 @@
 	third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp \
 	third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp \
 	third_party/WebKit/Source/core/dom/NodeTraversal.cpp \
-	third_party/WebKit/Source/core/dom/Notation.cpp \
 	third_party/WebKit/Source/core/dom/OverflowEvent.cpp \
 	third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp \
 	third_party/WebKit/Source/core/dom/PendingScript.cpp \
@@ -157,14 +156,15 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
+	third_party/WebKit/Source/core/dom/StyleEngine.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp \
-	third_party/WebKit/Source/core/dom/StyleSheetCollections.cpp \
 	third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
 	third_party/WebKit/Source/core/dom/TextLinkColors.cpp \
 	third_party/WebKit/Source/core/dom/Touch.cpp \
+	third_party/WebKit/Source/core/dom/TouchController.cpp \
 	third_party/WebKit/Source/core/dom/TouchEvent.cpp \
 	third_party/WebKit/Source/core/dom/TouchList.cpp \
 	third_party/WebKit/Source/core/dom/TransformSourceLibxslt.cpp \
@@ -233,7 +233,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -247,7 +247,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -393,7 +392,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -407,7 +406,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_html.target.darwin-arm.mk b/Source/core/webcore_html.target.darwin-arm.mk
index d73b1c0..66e52be 100644
--- a/Source/core/webcore_html.target.darwin-arm.mk
+++ b/Source/core/webcore_html.target.darwin-arm.mk
@@ -326,7 +326,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -340,7 +340,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -483,7 +482,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -497,7 +496,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_html.target.darwin-mips.mk b/Source/core/webcore_html.target.darwin-mips.mk
index 34afd9e..ec7fa84 100644
--- a/Source/core/webcore_html.target.darwin-mips.mk
+++ b/Source/core/webcore_html.target.darwin-mips.mk
@@ -326,7 +326,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -340,7 +340,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -483,7 +482,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -497,7 +496,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_html.target.darwin-x86.mk b/Source/core/webcore_html.target.darwin-x86.mk
index 8a9c36a..b6542a6 100644
--- a/Source/core/webcore_html.target.darwin-x86.mk
+++ b/Source/core/webcore_html.target.darwin-x86.mk
@@ -328,7 +328,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -342,7 +342,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -488,7 +487,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -502,7 +501,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_html.target.linux-arm.mk b/Source/core/webcore_html.target.linux-arm.mk
index d73b1c0..66e52be 100644
--- a/Source/core/webcore_html.target.linux-arm.mk
+++ b/Source/core/webcore_html.target.linux-arm.mk
@@ -326,7 +326,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -340,7 +340,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -483,7 +482,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -497,7 +496,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_html.target.linux-mips.mk b/Source/core/webcore_html.target.linux-mips.mk
index 34afd9e..ec7fa84 100644
--- a/Source/core/webcore_html.target.linux-mips.mk
+++ b/Source/core/webcore_html.target.linux-mips.mk
@@ -326,7 +326,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -340,7 +340,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -483,7 +482,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -497,7 +496,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_html.target.linux-x86.mk b/Source/core/webcore_html.target.linux-x86.mk
index 8a9c36a..b6542a6 100644
--- a/Source/core/webcore_html.target.linux-x86.mk
+++ b/Source/core/webcore_html.target.linux-x86.mk
@@ -328,7 +328,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -342,7 +342,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -488,7 +487,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -502,7 +501,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform.target.darwin-arm.mk b/Source/core/webcore_platform.target.darwin-arm.mk
index 59c7030..23464cb 100644
--- a/Source/core/webcore_platform.target.darwin-arm.mk
+++ b/Source/core/webcore_platform.target.darwin-arm.mk
@@ -374,7 +374,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -388,7 +388,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -532,7 +531,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -546,7 +545,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform.target.darwin-mips.mk b/Source/core/webcore_platform.target.darwin-mips.mk
index b1f6956..ecfbaf5 100644
--- a/Source/core/webcore_platform.target.darwin-mips.mk
+++ b/Source/core/webcore_platform.target.darwin-mips.mk
@@ -374,7 +374,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -388,7 +388,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -532,7 +531,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -546,7 +545,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform.target.darwin-x86.mk b/Source/core/webcore_platform.target.darwin-x86.mk
index e73a70c..c5e4112 100644
--- a/Source/core/webcore_platform.target.darwin-x86.mk
+++ b/Source/core/webcore_platform.target.darwin-x86.mk
@@ -376,7 +376,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -390,7 +390,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -537,7 +536,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -551,7 +550,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform.target.linux-arm.mk b/Source/core/webcore_platform.target.linux-arm.mk
index 59c7030..23464cb 100644
--- a/Source/core/webcore_platform.target.linux-arm.mk
+++ b/Source/core/webcore_platform.target.linux-arm.mk
@@ -374,7 +374,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -388,7 +388,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -532,7 +531,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -546,7 +545,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform.target.linux-mips.mk b/Source/core/webcore_platform.target.linux-mips.mk
index b1f6956..ecfbaf5 100644
--- a/Source/core/webcore_platform.target.linux-mips.mk
+++ b/Source/core/webcore_platform.target.linux-mips.mk
@@ -374,7 +374,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -388,7 +388,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -532,7 +531,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -546,7 +545,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform.target.linux-x86.mk b/Source/core/webcore_platform.target.linux-x86.mk
index e73a70c..c5e4112 100644
--- a/Source/core/webcore_platform.target.linux-x86.mk
+++ b/Source/core/webcore_platform.target.linux-x86.mk
@@ -376,7 +376,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -390,7 +390,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -537,7 +536,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -551,7 +550,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-arm.mk b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
index d0a30ba..81e0f2a 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
@@ -75,7 +75,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -89,7 +89,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -232,7 +231,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -246,7 +245,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-mips.mk b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
index 08b02f6..50ab713 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
@@ -75,7 +75,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -89,7 +89,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -232,7 +231,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -246,7 +245,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform_geometry.target.darwin-x86.mk b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
index 0a81c51..3abff95 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
@@ -77,7 +77,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -91,7 +91,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -237,7 +236,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -251,7 +250,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform_geometry.target.linux-arm.mk b/Source/core/webcore_platform_geometry.target.linux-arm.mk
index d0a30ba..81e0f2a 100644
--- a/Source/core/webcore_platform_geometry.target.linux-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-arm.mk
@@ -75,7 +75,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -89,7 +89,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -232,7 +231,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -246,7 +245,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform_geometry.target.linux-mips.mk b/Source/core/webcore_platform_geometry.target.linux-mips.mk
index 08b02f6..50ab713 100644
--- a/Source/core/webcore_platform_geometry.target.linux-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-mips.mk
@@ -75,7 +75,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -89,7 +89,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -232,7 +231,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -246,7 +245,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_platform_geometry.target.linux-x86.mk b/Source/core/webcore_platform_geometry.target.linux-x86.mk
index 0a81c51..3abff95 100644
--- a/Source/core/webcore_platform_geometry.target.linux-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-x86.mk
@@ -77,7 +77,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -91,7 +91,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -237,7 +236,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -251,7 +250,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_remaining.target.darwin-arm.mk b/Source/core/webcore_remaining.target.darwin-arm.mk
index 241625c..d76ddd1 100644
--- a/Source/core/webcore_remaining.target.darwin-arm.mk
+++ b/Source/core/webcore_remaining.target.darwin-arm.mk
@@ -136,8 +136,9 @@
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
+	third_party/WebKit/Source/core/css/FontFace.cpp \
 	third_party/WebKit/Source/core/css/FontFeatureValue.cpp \
-	third_party/WebKit/Source/core/css/FontLoader.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
 	third_party/WebKit/Source/core/css/FontValue.cpp \
 	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
@@ -410,7 +411,6 @@
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
-	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
 	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
@@ -461,9 +461,9 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/IFrameShimSupport.cpp \
 	third_party/WebKit/Source/core/plugins/PluginData.cpp \
 	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
+	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
@@ -555,7 +555,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -569,7 +569,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -713,7 +712,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -727,7 +726,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_remaining.target.darwin-mips.mk b/Source/core/webcore_remaining.target.darwin-mips.mk
index f9b5735..3a01fe0 100644
--- a/Source/core/webcore_remaining.target.darwin-mips.mk
+++ b/Source/core/webcore_remaining.target.darwin-mips.mk
@@ -136,8 +136,9 @@
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
+	third_party/WebKit/Source/core/css/FontFace.cpp \
 	third_party/WebKit/Source/core/css/FontFeatureValue.cpp \
-	third_party/WebKit/Source/core/css/FontLoader.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
 	third_party/WebKit/Source/core/css/FontValue.cpp \
 	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
@@ -410,7 +411,6 @@
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
-	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
 	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
@@ -461,9 +461,9 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/IFrameShimSupport.cpp \
 	third_party/WebKit/Source/core/plugins/PluginData.cpp \
 	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
+	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
@@ -555,7 +555,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -569,7 +569,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -713,7 +712,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -727,7 +726,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_remaining.target.darwin-x86.mk b/Source/core/webcore_remaining.target.darwin-x86.mk
index d14442f..96ac6d7 100644
--- a/Source/core/webcore_remaining.target.darwin-x86.mk
+++ b/Source/core/webcore_remaining.target.darwin-x86.mk
@@ -136,8 +136,9 @@
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
+	third_party/WebKit/Source/core/css/FontFace.cpp \
 	third_party/WebKit/Source/core/css/FontFeatureValue.cpp \
-	third_party/WebKit/Source/core/css/FontLoader.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
 	third_party/WebKit/Source/core/css/FontValue.cpp \
 	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
@@ -410,7 +411,6 @@
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
-	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
 	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
@@ -461,9 +461,9 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/IFrameShimSupport.cpp \
 	third_party/WebKit/Source/core/plugins/PluginData.cpp \
 	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
+	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
@@ -557,7 +557,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -571,7 +571,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -718,7 +717,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -732,7 +731,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_remaining.target.linux-arm.mk b/Source/core/webcore_remaining.target.linux-arm.mk
index 241625c..d76ddd1 100644
--- a/Source/core/webcore_remaining.target.linux-arm.mk
+++ b/Source/core/webcore_remaining.target.linux-arm.mk
@@ -136,8 +136,9 @@
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
+	third_party/WebKit/Source/core/css/FontFace.cpp \
 	third_party/WebKit/Source/core/css/FontFeatureValue.cpp \
-	third_party/WebKit/Source/core/css/FontLoader.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
 	third_party/WebKit/Source/core/css/FontValue.cpp \
 	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
@@ -410,7 +411,6 @@
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
-	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
 	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
@@ -461,9 +461,9 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/IFrameShimSupport.cpp \
 	third_party/WebKit/Source/core/plugins/PluginData.cpp \
 	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
+	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
@@ -555,7 +555,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -569,7 +569,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -713,7 +712,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -727,7 +726,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_remaining.target.linux-mips.mk b/Source/core/webcore_remaining.target.linux-mips.mk
index f9b5735..3a01fe0 100644
--- a/Source/core/webcore_remaining.target.linux-mips.mk
+++ b/Source/core/webcore_remaining.target.linux-mips.mk
@@ -136,8 +136,9 @@
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
+	third_party/WebKit/Source/core/css/FontFace.cpp \
 	third_party/WebKit/Source/core/css/FontFeatureValue.cpp \
-	third_party/WebKit/Source/core/css/FontLoader.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
 	third_party/WebKit/Source/core/css/FontValue.cpp \
 	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
@@ -410,7 +411,6 @@
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
-	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
 	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
@@ -461,9 +461,9 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/IFrameShimSupport.cpp \
 	third_party/WebKit/Source/core/plugins/PluginData.cpp \
 	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
+	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
@@ -555,7 +555,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -569,7 +569,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -713,7 +712,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -727,7 +726,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_remaining.target.linux-x86.mk b/Source/core/webcore_remaining.target.linux-x86.mk
index d14442f..96ac6d7 100644
--- a/Source/core/webcore_remaining.target.linux-x86.mk
+++ b/Source/core/webcore_remaining.target.linux-x86.mk
@@ -136,8 +136,9 @@
 	third_party/WebKit/Source/core/css/DOMWindowCSS.cpp \
 	third_party/WebKit/Source/core/css/DocumentRuleSets.cpp \
 	third_party/WebKit/Source/core/css/ElementRuleCollector.cpp \
+	third_party/WebKit/Source/core/css/FontFaceSet.cpp \
+	third_party/WebKit/Source/core/css/FontFace.cpp \
 	third_party/WebKit/Source/core/css/FontFeatureValue.cpp \
-	third_party/WebKit/Source/core/css/FontLoader.cpp \
 	third_party/WebKit/Source/core/css/FontSize.cpp \
 	third_party/WebKit/Source/core/css/FontValue.cpp \
 	third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp \
@@ -410,7 +411,6 @@
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
 	third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp \
 	third_party/WebKit/Source/core/page/Navigator.cpp \
-	third_party/WebKit/Source/core/page/NavigatorBase.cpp \
 	third_party/WebKit/Source/core/page/NavigatorID.cpp \
 	third_party/WebKit/Source/core/page/Page.cpp \
 	third_party/WebKit/Source/core/page/PageConsole.cpp \
@@ -461,9 +461,9 @@
 	third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPlugin.cpp \
 	third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp \
-	third_party/WebKit/Source/core/plugins/IFrameShimSupport.cpp \
 	third_party/WebKit/Source/core/plugins/PluginData.cpp \
 	third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp \
+	third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp \
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
@@ -557,7 +557,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -571,7 +571,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -718,7 +717,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -732,7 +731,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_rendering.target.darwin-arm.mk b/Source/core/webcore_rendering.target.darwin-arm.mk
index 419df09..073c918 100644
--- a/Source/core/webcore_rendering.target.darwin-arm.mk
+++ b/Source/core/webcore_rendering.target.darwin-arm.mk
@@ -26,6 +26,7 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
+	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
@@ -44,6 +45,7 @@
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
+	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -137,6 +139,7 @@
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
+	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
@@ -219,7 +222,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -233,7 +236,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -376,7 +378,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -390,7 +392,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_rendering.target.darwin-mips.mk b/Source/core/webcore_rendering.target.darwin-mips.mk
index 7a0920e..84cc4e8 100644
--- a/Source/core/webcore_rendering.target.darwin-mips.mk
+++ b/Source/core/webcore_rendering.target.darwin-mips.mk
@@ -26,6 +26,7 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
+	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
@@ -44,6 +45,7 @@
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
+	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -137,6 +139,7 @@
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
+	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
@@ -219,7 +222,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -233,7 +236,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -376,7 +378,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -390,7 +392,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_rendering.target.darwin-x86.mk b/Source/core/webcore_rendering.target.darwin-x86.mk
index 1cdbfa8..bd8b8d1 100644
--- a/Source/core/webcore_rendering.target.darwin-x86.mk
+++ b/Source/core/webcore_rendering.target.darwin-x86.mk
@@ -26,6 +26,7 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
+	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
@@ -44,6 +45,7 @@
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
+	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -137,6 +139,7 @@
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
+	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
@@ -222,7 +225,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -236,7 +239,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -383,7 +385,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -397,7 +399,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_rendering.target.linux-arm.mk b/Source/core/webcore_rendering.target.linux-arm.mk
index 419df09..073c918 100644
--- a/Source/core/webcore_rendering.target.linux-arm.mk
+++ b/Source/core/webcore_rendering.target.linux-arm.mk
@@ -26,6 +26,7 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
+	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
@@ -44,6 +45,7 @@
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
+	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -137,6 +139,7 @@
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
+	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
@@ -219,7 +222,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -233,7 +236,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -376,7 +378,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -390,7 +392,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_rendering.target.linux-mips.mk b/Source/core/webcore_rendering.target.linux-mips.mk
index 7a0920e..84cc4e8 100644
--- a/Source/core/webcore_rendering.target.linux-mips.mk
+++ b/Source/core/webcore_rendering.target.linux-mips.mk
@@ -26,6 +26,7 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
+	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
@@ -44,6 +45,7 @@
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
+	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -137,6 +139,7 @@
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
+	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
@@ -219,7 +222,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -233,7 +236,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -376,7 +378,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -390,7 +392,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_rendering.target.linux-x86.mk b/Source/core/webcore_rendering.target.linux-x86.mk
index 1cdbfa8..bd8b8d1 100644
--- a/Source/core/webcore_rendering.target.linux-x86.mk
+++ b/Source/core/webcore_rendering.target.linux-x86.mk
@@ -26,6 +26,7 @@
 LOCAL_SRC_FILES := \
 	third_party/WebKit/Source/core/rendering/AutoTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
+	third_party/WebKit/Source/core/rendering/ClipRect.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
@@ -44,6 +45,7 @@
 	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutIndicator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
+	third_party/WebKit/Source/core/rendering/LineWidth.cpp \
 	third_party/WebKit/Source/core/rendering/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -137,6 +139,7 @@
 	third_party/WebKit/Source/core/rendering/RenderView.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWidget.cpp \
 	third_party/WebKit/Source/core/rendering/RenderWordBreak.cpp \
+	third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp \
 	third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
@@ -222,7 +225,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -236,7 +239,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -383,7 +385,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -397,7 +399,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_svg.target.darwin-arm.mk b/Source/core/webcore_svg.target.darwin-arm.mk
index 222458d..359e389 100644
--- a/Source/core/webcore_svg.target.darwin-arm.mk
+++ b/Source/core/webcore_svg.target.darwin-arm.mk
@@ -283,7 +283,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -297,7 +297,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -440,7 +439,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -454,7 +453,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_svg.target.darwin-mips.mk b/Source/core/webcore_svg.target.darwin-mips.mk
index 4818894..83f5330 100644
--- a/Source/core/webcore_svg.target.darwin-mips.mk
+++ b/Source/core/webcore_svg.target.darwin-mips.mk
@@ -283,7 +283,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -297,7 +297,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -440,7 +439,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -454,7 +453,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_svg.target.darwin-x86.mk b/Source/core/webcore_svg.target.darwin-x86.mk
index 70e5f01..ca67226 100644
--- a/Source/core/webcore_svg.target.darwin-x86.mk
+++ b/Source/core/webcore_svg.target.darwin-x86.mk
@@ -285,7 +285,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -299,7 +299,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -445,7 +444,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -459,7 +458,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_svg.target.linux-arm.mk b/Source/core/webcore_svg.target.linux-arm.mk
index 222458d..359e389 100644
--- a/Source/core/webcore_svg.target.linux-arm.mk
+++ b/Source/core/webcore_svg.target.linux-arm.mk
@@ -283,7 +283,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -297,7 +297,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -440,7 +439,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -454,7 +453,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_svg.target.linux-mips.mk b/Source/core/webcore_svg.target.linux-mips.mk
index 4818894..83f5330 100644
--- a/Source/core/webcore_svg.target.linux-mips.mk
+++ b/Source/core/webcore_svg.target.linux-mips.mk
@@ -283,7 +283,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -297,7 +297,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -440,7 +439,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -454,7 +453,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/webcore_svg.target.linux-x86.mk b/Source/core/webcore_svg.target.linux-x86.mk
index 70e5f01..ca67226 100644
--- a/Source/core/webcore_svg.target.linux-x86.mk
+++ b/Source/core/webcore_svg.target.linux-x86.mk
@@ -285,7 +285,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -299,7 +299,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
@@ -445,7 +444,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
-	'-DWTF_VECTOR_INITIAL_SIZE=16' \
+	'-DWTF_VECTOR_INITIAL_SIZE=4' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -459,7 +458,6 @@
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
 	'-DCLD_VERSION=1' \
-	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
 	'-DENABLE_CSS3_TEXT=0' \
diff --git a/Source/core/xml/XMLHttpRequest.cpp b/Source/core/xml/XMLHttpRequest.cpp
index 4b041d4..4b5e89b 100644
--- a/Source/core/xml/XMLHttpRequest.cpp
+++ b/Source/core/xml/XMLHttpRequest.cpp
@@ -176,7 +176,6 @@
     , m_uploadEventsAllowed(true)
     , m_uploadComplete(false)
     , m_sameOriginRequest(true)
-    , m_allowCrossOriginRequests(false)
     , m_receivedLength(0)
     , m_lastSendLineNumber(0)
     , m_exceptionCode(0)
@@ -769,7 +768,7 @@
     options.preflightPolicy = uploadEvents ? ForcePreflight : ConsiderPreflight;
     options.allowCredentials = (m_sameOriginRequest || m_includeCredentials) ? AllowStoredCredentials : DoNotAllowStoredCredentials;
     options.credentialsRequested = m_includeCredentials ? ClientRequestedCredentials : ClientDidNotRequestCredentials;
-    options.crossOriginRequestPolicy = m_allowCrossOriginRequests ? AllowCrossOriginRequests : UseAccessControl;
+    options.crossOriginRequestPolicy = UseAccessControl;
     options.securityOrigin = securityOrigin();
     options.initiator = FetchInitiatorTypeNames::xmlhttprequest;
     options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(scriptExecutionContext()) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective;
diff --git a/Source/core/xml/XMLHttpRequest.h b/Source/core/xml/XMLHttpRequest.h
index ad3546d..ca6f921 100644
--- a/Source/core/xml/XMLHttpRequest.h
+++ b/Source/core/xml/XMLHttpRequest.h
@@ -222,7 +222,6 @@
     bool m_uploadComplete;
 
     bool m_sameOriginRequest;
-    bool m_allowCrossOriginRequests;
 
     // Used for onprogress tracking
     long long m_receivedLength;
diff --git a/Source/core/xml/parser/XMLDocumentParser.cpp b/Source/core/xml/parser/XMLDocumentParser.cpp
index 26f839d..a06e969 100644
--- a/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -350,6 +350,10 @@
         return;
     }
 
+    // JavaScript can detach the parser. Make sure this is not released
+    // before the end of this method.
+    RefPtr<XMLDocumentParser> protect(this);
+
     doWrite(source.toString());
 
     if (isStopped())