Merge from Chromium at DEPS revision 222756

This commit was generated by merge_to_master.py.

Change-Id: I085d892f6f1583a45f10eb394f195bbea5a334ef
diff --git a/Source/core/ConvertFileToHeaderWithCharacterArray.gypi b/Source/core/ConvertFileToHeaderWithCharacterArray.gypi
index e41a20a..063e38c 100644
--- a/Source/core/ConvertFileToHeaderWithCharacterArray.gypi
+++ b/Source/core/ConvertFileToHeaderWithCharacterArray.gypi
@@ -43,13 +43,13 @@
     {
       'action_name': 'ConvertFileToHeaderWithCharacterArray',
       'inputs': [
-        'inspector/xxd.pl',
+        'scripts/xxd.pl',
         '<(input_file_path)',
       ],
       'outputs': [ '<@(output_file_path)', ],
       'action': [
         '<(perl_exe)',
-        'inspector/xxd.pl',
+        'scripts/xxd.pl',
         '<(character_array_name)',
         '<(input_file_path)',
         '<@(_outputs)'
diff --git a/Source/core/Resources/pagepopups/calendarPicker.css b/Source/core/Resources/pagepopups/calendarPicker.css
index 18d1cf2..a4e6ae9 100644
--- a/Source/core/Resources/pagepopups/calendarPicker.css
+++ b/Source/core/Resources/pagepopups/calendarPicker.css
@@ -149,13 +149,13 @@
 
 .calendar-header-view {
     margin-bottom: 10px;
-    display: -webkit-flex;
-    -webkit-flex-flow: row;
+    display: flex;
+    flex-flow: row;
 }
 
 .calendar-title {
     -webkit-align-self: center;
-    -webkit-flex: 1;
+    flex: 1;
     text-align: left;
 }
 
@@ -239,11 +239,11 @@
 }
 
 .month-buttons-row {
-    display: -webkit-flex;
+    display: flex;
 }
 
 .month-button {
-    -webkit-flex: 1;
+    flex: 1;
     height: 32px;
     padding: 0 !important;
     margin: 0 !important;
diff --git a/Source/core/Resources/pagepopups/colorSuggestionPicker.css b/Source/core/Resources/pagepopups/colorSuggestionPicker.css
index 6f847fe..39a162b 100644
--- a/Source/core/Resources/pagepopups/colorSuggestionPicker.css
+++ b/Source/core/Resources/pagepopups/colorSuggestionPicker.css
@@ -58,9 +58,9 @@
     width: 100%;
     max-height: 104px;
     overflow: auto;
-    display: -webkit-flex;
-    -webkit-flex-flow: row wrap;
-    -webkit-align-items: center;
+    display: flex;
+    flex-flow: row wrap;
+    align-items: center;
 }
 
 .other-color {
diff --git a/Source/core/accessibility/AXObjectCache.cpp b/Source/core/accessibility/AXObjectCache.cpp
index 69b2ad6..526c600 100644
--- a/Source/core/accessibility/AXObjectCache.cpp
+++ b/Source/core/accessibility/AXObjectCache.cpp
@@ -131,7 +131,7 @@
     if (!imageElement)
         return 0;
 
-    AccessibilityObject* axRenderImage = areaElement->document()->axObjectCache()->getOrCreate(imageElement);
+    AccessibilityObject* axRenderImage = areaElement->document().axObjectCache()->getOrCreate(imageElement);
     if (!axRenderImage)
         return 0;
 
@@ -163,7 +163,7 @@
     if (isHTMLAreaElement(focusedNode))
         return focusedImageMapUIElement(toHTMLAreaElement(focusedNode));
 
-    AccessibilityObject* obj = focusedNode->document()->axObjectCache()->getOrCreate(focusedNode);
+    AccessibilityObject* obj = focusedNode->document().axObjectCache()->getOrCreate(focusedNode);
     if (!obj)
         return 0;
 
@@ -664,7 +664,7 @@
     if (!renderer)
         return;
 
-    postNotification(object.get(), renderer->document(), notification, postToElement, postType);
+    postNotification(object.get(), &renderer->document(), notification, postToElement, postType);
 }
 
 void AXObjectCache::postNotification(Node* node, AXNotification notification, bool postToElement, PostType postType)
@@ -685,7 +685,7 @@
     if (!node)
         return;
 
-    postNotification(object.get(), node->document(), notification, postToElement, postType);
+    postNotification(object.get(), &node->document(), notification, postToElement, postType);
 }
 
 void AXObjectCache::postNotification(AccessibilityObject* object, Document* document, AXNotification notification, bool postToElement, PostType postType)
@@ -832,7 +832,7 @@
     if (!renderer)
         return VisiblePosition();
 
-    AXObjectCache* cache = renderer->document()->axObjectCache();
+    AXObjectCache* cache = renderer->document().axObjectCache();
     if (!cache->isIDinUse(textMarkerData.axID))
         return VisiblePosition();
 
@@ -861,7 +861,7 @@
         return;
 
     // find or create an accessibility object for this node
-    AXObjectCache* cache = domNode->document()->axObjectCache();
+    AXObjectCache* cache = domNode->document().axObjectCache();
     RefPtr<AccessibilityObject> obj = cache->getOrCreate(domNode);
 
     textMarkerData.axID = obj.get()->axObjectID();
@@ -922,16 +922,16 @@
         Scrollbar* scrollBar = static_cast<AccessibilityScrollbar*>(obj)->scrollbar();
         if (!scrollBar || !scrollBar->parent() || !scrollBar->parent()->isFrameView())
             return;
-        Document* document = toFrameView(scrollBar->parent())->frame()->document();
+        Document* document = toFrameView(scrollBar->parent())->frame().document();
         if (document != document->topDocument())
             return;
         obj = get(document->renderer());
     }
 
-    if (!obj || !obj->document() || !obj->documentFrameView() || !obj->documentFrameView()->frame() || !obj->documentFrameView()->frame()->page())
+    if (!obj || !obj->document() || !obj->documentFrameView() || !obj->documentFrameView()->frame().page())
         return;
 
-    ChromeClient& client = obj->documentFrameView()->frame()->page()->chrome().client();
+    ChromeClient& client = obj->documentFrameView()->frame().page()->chrome().client();
 
     if (notification == AXActiveDescendantChanged
         && obj->document()->focusedElement()
@@ -949,7 +949,7 @@
     if (!newFocusedNode)
         return;
 
-    Page* page = newFocusedNode->document()->page();
+    Page* page = newFocusedNode->document().page();
     if (!page)
         return;
 
diff --git a/Source/core/accessibility/AccessibilityARIAGrid.cpp b/Source/core/accessibility/AccessibilityARIAGrid.cpp
index 52d0d0e..73b2fb7 100644
--- a/Source/core/accessibility/AccessibilityARIAGrid.cpp
+++ b/Source/core/accessibility/AccessibilityARIAGrid.cpp
@@ -93,7 +93,7 @@
     if (!m_renderer)
         return;
 
-    AXObjectCache* axCache = m_renderer->document()->axObjectCache();
+    AXObjectCache* axCache = m_renderer->document().axObjectCache();
 
     // add only rows that are labeled as aria rows
     HashSet<AccessibilityObject*> appendedRows;
diff --git a/Source/core/accessibility/AccessibilityImageMapLink.cpp b/Source/core/accessibility/AccessibilityImageMapLink.cpp
index 6c36cfdf..312548e 100644
--- a/Source/core/accessibility/AccessibilityImageMapLink.cpp
+++ b/Source/core/accessibility/AccessibilityImageMapLink.cpp
@@ -66,7 +66,7 @@
     if (!m_mapElement.get() || !m_mapElement->renderer())
         return 0;
 
-    return m_mapElement->document()->axObjectCache()->getOrCreate(m_mapElement->renderer());
+    return m_mapElement->document().axObjectCache()->getOrCreate(m_mapElement->renderer());
 }
 
 AccessibilityRole AccessibilityImageMapLink::roleValue() const
diff --git a/Source/core/accessibility/AccessibilityListBox.cpp b/Source/core/accessibility/AccessibilityListBox.cpp
index b3d4a25..3b5e578 100644
--- a/Source/core/accessibility/AccessibilityListBox.cpp
+++ b/Source/core/accessibility/AccessibilityListBox.cpp
@@ -129,7 +129,7 @@
     if (!element || element->hasTagName(hrTag))
         return 0;
 
-    AccessibilityObject* listBoxObject = m_renderer->document()->axObjectCache()->getOrCreate(ListBoxOptionRole);
+    AccessibilityObject* listBoxObject = m_renderer->document().axObjectCache()->getOrCreate(ListBoxOptionRole);
     static_cast<AccessibilityListBoxOption*>(listBoxObject)->setHTMLElement(element);
 
     return listBoxObject;
diff --git a/Source/core/accessibility/AccessibilityListBoxOption.cpp b/Source/core/accessibility/AccessibilityListBoxOption.cpp
index 571bf76..fffc791 100644
--- a/Source/core/accessibility/AccessibilityListBoxOption.cpp
+++ b/Source/core/accessibility/AccessibilityListBoxOption.cpp
@@ -106,7 +106,7 @@
     if (!listBoxRenderer)
         return rect;
 
-    LayoutRect parentRect = listBoxRenderer->document()->axObjectCache()->getOrCreate(listBoxRenderer)->elementRect();
+    LayoutRect parentRect = listBoxRenderer->document().axObjectCache()->getOrCreate(listBoxRenderer)->elementRect();
     int index = listBoxOptionIndex();
     if (index != -1)
         rect = toRenderListBox(listBoxRenderer)->itemBoundingBoxRect(parentRect.location(), index);
@@ -172,7 +172,7 @@
     if (!parentNode)
         return 0;
 
-    return m_optionElement->document()->axObjectCache()->getOrCreate(parentNode);
+    return m_optionElement->document().axObjectCache()->getOrCreate(parentNode);
 }
 
 void AccessibilityListBoxOption::setSelected(bool selected)
diff --git a/Source/core/accessibility/AccessibilityMenuList.cpp b/Source/core/accessibility/AccessibilityMenuList.cpp
index b84ab0a..46dd227 100644
--- a/Source/core/accessibility/AccessibilityMenuList.cpp
+++ b/Source/core/accessibility/AccessibilityMenuList.cpp
@@ -56,7 +56,7 @@
 {
     m_haveChildren = true;
 
-    AXObjectCache* cache = m_renderer->document()->axObjectCache();
+    AXObjectCache* cache = m_renderer->document().axObjectCache();
 
     AccessibilityObject* list = cache->getOrCreate(MenuListPopupRole);
     if (!list)
@@ -97,7 +97,7 @@
 
 void AccessibilityMenuList::didUpdateActiveOption(int optionIndex)
 {
-    RefPtr<Document> document = m_renderer->document();
+    RefPtr<Document> document = &m_renderer->document();
     AXObjectCache* cache = document->axObjectCache();
 
     const AccessibilityChildrenVector& childObjects = children();
diff --git a/Source/core/accessibility/AccessibilityNodeObject.cpp b/Source/core/accessibility/AccessibilityNodeObject.cpp
index 11dda04..7e7bc64 100644
--- a/Source/core/accessibility/AccessibilityNodeObject.cpp
+++ b/Source/core/accessibility/AccessibilityNodeObject.cpp
@@ -259,9 +259,7 @@
     if (!node || !node->isElementNode())
         return;
 
-    TreeScope* scope = node->treeScope();
-    if (!scope)
-        return;
+    TreeScope& scope = node->treeScope();
 
     String idList = getAttribute(attribute).string();
     if (idList.isEmpty())
@@ -274,7 +272,7 @@
     unsigned size = idVector.size();
     for (unsigned i = 0; i < size; ++i) {
         AtomicString idName(idVector[i]);
-        Element* idElement = scope->getElementById(idName);
+        Element* idElement = scope.getElementById(idName);
         if (idElement)
             elements.append(idElement);
     }
@@ -343,7 +341,7 @@
 
     const AtomicString& id = element->getIdAttribute();
     if (!id.isEmpty()) {
-        if (HTMLLabelElement* label = element->treeScope()->labelElementForId(id))
+        if (HTMLLabelElement* label = element->treeScope().labelElementForId(id))
             return label;
     }
 
@@ -900,7 +898,7 @@
         return 0;
 
     if (isFieldset())
-        return axObjectCache()->getOrCreate(static_cast<HTMLFieldSetElement*>(node())->legend());
+        return axObjectCache()->getOrCreate(toHTMLFieldSetElement(node())->legend());
 
     HTMLLabelElement* label = labelForElement(toElement(node()));
     if (label)
@@ -935,7 +933,7 @@
         return;
 
     // HTMLInputElement::value always returns a string parseable by Color().
-    StyleColor color(input->value());
+    Color color(input->value());
     r = color.red();
     g = color.green();
     b = color.blue();
@@ -1453,7 +1451,7 @@
 {
     if (!node())
         return 0;
-    return node()->document();
+    return &node()->document();
 }
 
 void AccessibilityNodeObject::setNode(Node* node)
diff --git a/Source/core/accessibility/AccessibilityObject.cpp b/Source/core/accessibility/AccessibilityObject.cpp
index f1ee094..64f7800 100644
--- a/Source/core/accessibility/AccessibilityObject.cpp
+++ b/Source/core/accessibility/AccessibilityObject.cpp
@@ -34,6 +34,7 @@
 #include "core/dom/UserGestureIndicator.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
+#include "core/page/Frame.h"
 #include "core/platform/LocalizedStrings.h"
 #include "core/rendering/RenderListItem.h"
 #include "core/rendering/RenderTheme.h"
@@ -505,12 +506,7 @@
     if (!node)
         return 0;
 
-    Document* document = node->document();
-    if (!document)
-        return 0;
-
-    AXObjectCache* cache = document->axObjectCache();
-
+    AXObjectCache* cache = node->document().axObjectCache();
     AccessibilityObject* accessibleObject = cache->getOrCreate(node->renderer());
     while (accessibleObject && accessibleObject->accessibilityIsIgnored()) {
         node = NodeTraversal::next(node);
@@ -563,7 +559,7 @@
     if (!frameView)
         return 0;
 
-    return frameView->frame()->document();
+    return frameView->frame().document();
 }
 
 FrameView* AccessibilityObject::documentFrameView() const
@@ -888,7 +884,7 @@
         return false;
 
     // create an AX object, but skip it if it is not supposed to be seen
-    AccessibilityObject* object = replacedNode->renderer()->document()->axObjectCache()->getOrCreate(replacedNode);
+    AccessibilityObject* object = replacedNode->renderer()->document().axObjectCache()->getOrCreate(replacedNode);
     if (object->accessibilityIsIgnored())
         return false;
 
diff --git a/Source/core/accessibility/AccessibilityRenderObject.cpp b/Source/core/accessibility/AccessibilityRenderObject.cpp
index 6c7b0b8..f604032 100644
--- a/Source/core/accessibility/AccessibilityRenderObject.cpp
+++ b/Source/core/accessibility/AccessibilityRenderObject.cpp
@@ -49,6 +49,7 @@
 #include "core/html/HTMLTextAreaElement.h"
 #include "core/html/shadow/ShadowElementNames.h"
 #include "core/loader/ProgressTracker.h"
+#include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/LocalizedStrings.h"
 #include "core/rendering/HitTestResult.h"
@@ -61,6 +62,7 @@
 #include "core/rendering/RenderMenuList.h"
 #include "core/rendering/RenderTextControlSingleLine.h"
 #include "core/rendering/RenderTextFragment.h"
+#include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
 #include "core/svg/SVGDocument.h"
 #include "core/svg/SVGSVGElement.h"
@@ -435,7 +437,7 @@
     if (node && node->hasTagName(aTag) && isClickable())
         return LinkRole;
 
-    if (m_renderer->isBlockFlow())
+    if (m_renderer->isRenderBlockFlow())
         return GroupRole;
 
     // If the element does not have role, but it has ARIA attributes, accessibility should fallback to exposing it as a group.
@@ -512,7 +514,7 @@
 
 bool AccessibilityRenderObject::isLoaded() const
 {
-    return !m_renderer->document()->parser();
+    return !m_renderer->document().parser();
 }
 
 bool AccessibilityRenderObject::isOffScreen() const
@@ -530,15 +532,12 @@
     ASSERT(m_renderer);
 
     if (isWebArea()) {
-        Document* document = m_renderer->document();
-        if (!document)
-            return true;
-
-        HTMLElement* body = document->body();
+        Document& document = m_renderer->document();
+        HTMLElement* body = document.body();
         if (body && body->rendererIsEditable())
             return false;
 
-        return !document->rendererIsEditable();
+        return !document.rendererIsEditable();
     }
 
     return AccessibilityNodeObject::isReadOnly();
@@ -559,18 +558,15 @@
     if (!m_renderer)
         return false;
 
-    Document* document = m_renderer->document();
-    if (!document)
-        return false;
-
-    Element* focusedElement = document->focusedElement();
+    Document& document = m_renderer->document();
+    Element* focusedElement = document.focusedElement();
     if (!focusedElement)
         return false;
 
     // A web area is represented by the Document node in the DOM tree, which isn't focusable.
     // Check instead if the frame's selection controller is focused
     if (focusedElement == m_renderer->node()
-        || (roleValue() == WebAreaRole && document->frame()->selection()->isFocusedAndActive()))
+        || (roleValue() == WebAreaRole && document.frame()->selection().isFocusedAndActive()))
         return true;
 
     return false;
@@ -724,7 +720,7 @@
     if (node && node->hasTagName(spanTag))
         return true;
 
-    if (m_renderer->isBlockFlow() && m_renderer->childrenInline() && !canSetFocusAttribute())
+    if (m_renderer->isRenderBlockFlow() && m_renderer->childrenInline() && !canSetFocusAttribute())
         return !toRenderBlock(m_renderer)->firstLineBox() && !mouseButtonListener();
 
     // ignore images seemingly used as spacers
@@ -847,7 +843,7 @@
     }
 
     if (isWebArea())
-        return m_renderer->document()->url();
+        return m_renderer->document().url();
 
     if (isImage() && m_renderer->node() && m_renderer->node()->hasTagName(imgTag))
         return toHTMLImageElement(m_renderer->node())->src();
@@ -969,7 +965,7 @@
     if (activeDescendantAttrStr.isNull() || activeDescendantAttrStr.isEmpty())
         return 0;
 
-    Element* target = element->treeScope()->getElementById(activeDescendantAttrStr);
+    Element* target = element->treeScope().getElementById(activeDescendantAttrStr);
     if (!target)
         return 0;
 
@@ -1148,9 +1144,9 @@
         // If possible, use a text iterator to get the text, so that whitespace
         // is handled consistently.
         if (Node* node = this->node()) {
-            if (Frame* frame = node->document()->frame()) {
+            if (Frame* frame = node->document().frame()) {
                 // catch stale WebCoreAXObject (see <rdar://problem/3960196>)
-                if (frame->document() != node->document())
+                if (frame->document() != &node->document())
                     return String();
 
                 return plainText(rangeOfContents(node).get(), textIteratorBehaviorForTextRange());
@@ -1319,7 +1315,7 @@
     if (!obj)
         return 0;
 
-    AccessibilityObject* result = obj->document()->axObjectCache()->getOrCreate(obj);
+    AccessibilityObject* result = obj->document().axObjectCache()->getOrCreate(obj);
     result->updateChildrenIfNecessary();
 
     // Allow the element to perform any hit-testing it might need to do to reach non-render children.
@@ -1519,7 +1515,7 @@
     if (isLoaded())
         return 1.0;
 
-    if (Page* page = m_renderer->document()->page())
+    if (Page* page = m_renderer->document().page())
         return page->progress().estimatedProgress();
     return 0;
 }
@@ -1537,16 +1533,16 @@
 {
     if (!m_renderer)
         return 0;
-    return m_renderer->document();
+    return &m_renderer->document();
 }
 
 FrameView* AccessibilityRenderObject::documentFrameView() const
 {
-    if (!m_renderer || !m_renderer->document())
+    if (!m_renderer)
         return 0;
 
     // this is the RenderObject's Document's Frame's FrameView
-    return m_renderer->document()->view();
+    return m_renderer->document().view();
 }
 
 Element* AccessibilityRenderObject::anchorElement() const
@@ -1613,7 +1609,7 @@
 
 VisibleSelection AccessibilityRenderObject::selection() const
 {
-    return m_renderer->frame()->selection()->selection();
+    return m_renderer->frame()->selection().selection();
 }
 
 String AccessibilityRenderObject::selectedText() const
@@ -1646,14 +1642,12 @@
         return;
     }
 
-    Document* document = m_renderer->document();
-    if (!document)
-        return;
-    Frame* frame = document->frame();
+    Document& document = m_renderer->document();
+    Frame* frame = document.frame();
     if (!frame)
         return;
     Node* node = m_renderer->node();
-    frame->selection()->setSelection(VisibleSelection(Position(node, range.start, Position::PositionIsOffsetInAnchor),
+    frame->selection().setSelection(VisibleSelection(Position(node, range.start, Position::PositionIsOffsetInAnchor),
         Position(node, range.start + range.length, Position::PositionIsOffsetInAnchor), DOWNSTREAM));
 }
 
@@ -1685,7 +1679,7 @@
         return;
 
     RenderLayer* layer = box->layer();
-    layer->scrollToOffset(toIntSize(point), RenderLayer::ScrollOffsetClamped);
+    layer->scrollToOffset(toIntSize(point), ScrollOffsetClamped);
 }
 
 //
@@ -1697,13 +1691,13 @@
     Element* element = toElement(renderer()->node());
     if (!element)
         return;
-    Document* doc = renderer()->document();
-    if (!doc->frame()->selection()->isFocusedAndActive() || doc->focusedElement() != element)
+    Document& doc = renderer()->document();
+    if (!doc.frame()->selection().isFocusedAndActive() || doc.focusedElement() != element)
         return;
     AccessibilityRenderObject* activedescendant = static_cast<AccessibilityRenderObject*>(activeDescendant());
 
     if (activedescendant && shouldNotifyActiveDescendant())
-        doc->axObjectCache()->postNotification(m_renderer, AXObjectCache::AXActiveDescendantChanged, true);
+        doc.axObjectCache()->postNotification(m_renderer, AXObjectCache::AXActiveDescendantChanged, true);
 }
 
 void AccessibilityRenderObject::handleAriaExpandedChanged()
@@ -1968,11 +1962,11 @@
         return 0;
 
     // check if URL is the same as current URL
-    KURL documentURL = m_renderer->document()->url();
+    KURL documentURL = m_renderer->document().url();
     if (!equalIgnoringFragmentIdentifier(documentURL, linkURL))
         return 0;
 
-    Node* linkedNode = m_renderer->document()->findAnchor(fragmentIdentifier);
+    Node* linkedNode = m_renderer->document().findAnchor(fragmentIdentifier);
     if (!linkedNode)
         return 0;
 
@@ -2092,15 +2086,10 @@
     if (!image || !image->isSVGImage())
         return 0;
 
-    SVGImage* svgImage = static_cast<SVGImage*>(image);
-    FrameView* frameView = svgImage->frameView();
+    FrameView* frameView = toSVGImage(image)->frameView();
     if (!frameView)
         return 0;
-    Frame* frame = frameView->frame();
-    if (!frame)
-        return 0;
-
-    Document* doc = frame->document();
+    Document* doc = frameView->frame().document();
     if (!doc || !doc->isSVGDocument())
         return 0;
 
@@ -2111,7 +2100,7 @@
     if (!rendererRoot)
         return 0;
 
-    AccessibilityObject* rootSVGObject = frame->document()->axObjectCache()->getOrCreate(rendererRoot);
+    AccessibilityObject* rootSVGObject = doc->axObjectCache()->getOrCreate(rendererRoot);
 
     // In order to connect the AX hierarchy from the SVG root element from the loaded resource
     // the parent must be set, because there's no other way to get back to who created the image.
diff --git a/Source/core/accessibility/AccessibilityScrollView.cpp b/Source/core/accessibility/AccessibilityScrollView.cpp
index f9ef675..cc35e73 100644
--- a/Source/core/accessibility/AccessibilityScrollView.cpp
+++ b/Source/core/accessibility/AccessibilityScrollView.cpp
@@ -29,6 +29,7 @@
 #include "core/accessibility/AXObjectCache.h"
 #include "core/accessibility/AccessibilityScrollbar.h"
 #include "core/html/HTMLFrameOwnerElement.h"
+#include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 
 namespace WebCore {
@@ -166,7 +167,7 @@
     if (!m_scrollView || !m_scrollView->isFrameView())
         return 0;
 
-    Document* doc = toFrameView(m_scrollView)->frame()->document();
+    Document* doc = toFrameView(m_scrollView)->frame().document();
     if (!doc || !doc->renderer())
         return 0;
 
@@ -208,7 +209,7 @@
     if (!m_scrollView || !m_scrollView->isFrameView())
         return 0;
 
-    HTMLFrameOwnerElement* owner = toFrameView(m_scrollView)->frame()->ownerElement();
+    HTMLFrameOwnerElement* owner = toFrameView(m_scrollView)->frame().ownerElement();
     if (owner && owner->renderer())
         return axObjectCache()->getOrCreate(owner);
 
@@ -220,7 +221,7 @@
     if (!m_scrollView || !m_scrollView->isFrameView())
         return 0;
 
-    HTMLFrameOwnerElement* owner = toFrameView(m_scrollView)->frame()->ownerElement();
+    HTMLFrameOwnerElement* owner = toFrameView(m_scrollView)->frame().ownerElement();
     if (owner && owner->renderer())
         return axObjectCache()->get(owner);
 
diff --git a/Source/core/accessibility/AccessibilitySlider.cpp b/Source/core/accessibility/AccessibilitySlider.cpp
index 12bd7a9..5873bd7 100644
--- a/Source/core/accessibility/AccessibilitySlider.cpp
+++ b/Source/core/accessibility/AccessibilitySlider.cpp
@@ -83,7 +83,7 @@
 
     m_haveChildren = true;
 
-    AXObjectCache* cache = m_renderer->document()->axObjectCache();
+    AXObjectCache* cache = m_renderer->document().axObjectCache();
 
     AccessibilitySliderThumb* thumb = static_cast<AccessibilitySliderThumb*>(cache->getOrCreate(SliderThumbRole));
     thumb->setParent(this);
diff --git a/Source/core/accessibility/AccessibilityTable.cpp b/Source/core/accessibility/AccessibilityTable.cpp
index de07abe..0eb0832 100644
--- a/Source/core/accessibility/AccessibilityTable.cpp
+++ b/Source/core/accessibility/AccessibilityTable.cpp
@@ -146,7 +146,7 @@
     RenderStyle* tableStyle = table->style();
     if (!tableStyle)
         return false;
-    StyleColor tableBGColor = tableStyle->visitedDependentColor(CSSPropertyBackgroundColor);
+    Color tableBGColor = tableStyle->visitedDependentColor(CSSPropertyBackgroundColor);
 
     // check enough of the cells to find if the table matches our criteria
     // Criteria:
@@ -161,7 +161,7 @@
     unsigned cellsWithLeftBorder = 0;
     unsigned cellsWithRightBorder = 0;
 
-    StyleColor alternatingRowColors[5];
+    Color alternatingRowColors[5];
     int alternatingRowColorCount = 0;
 
     int headersInFirstColumnCount = 0;
@@ -223,7 +223,7 @@
 
             // If the cell has a different color from the table and there is cell spacing,
             // then it is probably a data table cell (spacing and colors take the place of borders).
-            StyleColor cellColor = renderStyle->visitedDependentColor(CSSPropertyBackgroundColor);
+            Color cellColor = renderStyle->visitedDependentColor(CSSPropertyBackgroundColor);
             if (table->hBorderSpacing() > 0 && table->vBorderSpacing() > 0
                 && tableBGColor != cellColor && cellColor.alpha() != 1)
                 backgroundDifferenceCellCount++;
@@ -240,7 +240,7 @@
                 RenderStyle* rowRenderStyle = renderRow->style();
                 if (!rowRenderStyle)
                     continue;
-                StyleColor rowColor = rowRenderStyle->visitedDependentColor(CSSPropertyBackgroundColor);
+                Color rowColor = rowRenderStyle->visitedDependentColor(CSSPropertyBackgroundColor);
                 alternatingRowColors[alternatingRowColorCount] = rowColor;
                 alternatingRowColorCount++;
             }
@@ -272,7 +272,7 @@
 
     // Check if there is an alternating row background color indicating a zebra striped style pattern.
     if (alternatingRowColorCount > 2) {
-        StyleColor firstColor = alternatingRowColors[0];
+        Color firstColor = alternatingRowColors[0];
         for (int k = 1; k < alternatingRowColorCount; k++) {
             // If an odd row was the same color as the first row, its not alternating.
             if (k % 2 == 1 && alternatingRowColors[k] == firstColor)
@@ -331,7 +331,7 @@
         return;
 
     RenderTable* table = toRenderTable(m_renderer);
-    AXObjectCache* axCache = m_renderer->document()->axObjectCache();
+    AXObjectCache* axCache = m_renderer->document().axObjectCache();
 
     // Go through all the available sections to pull out the rows and add them as children.
     table->recalcSectionsIfNeeded();
diff --git a/Source/core/animation/AnimatableNeutral.h b/Source/core/animation/AnimatableNeutral.h
index af45451..91b702d 100644
--- a/Source/core/animation/AnimatableNeutral.h
+++ b/Source/core/animation/AnimatableNeutral.h
@@ -48,8 +48,6 @@
         return 0;
     }
 
-    virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue* value) const OVERRIDE { return defaultAddWith(this, value); }
-
 private:
     AnimatableNeutral() : AnimatableValue(TypeNeutral) { }
 
diff --git a/Source/core/animation/AnimatableNumber.cpp b/Source/core/animation/AnimatableNumber.cpp
index 3693953..f57a829 100644
--- a/Source/core/animation/AnimatableNumber.cpp
+++ b/Source/core/animation/AnimatableNumber.cpp
@@ -81,9 +81,9 @@
     return value->isCalculationValue();
 }
 
-PassRefPtr<CSSValue> AnimatableNumber::toCSSValue() const
+PassRefPtr<CSSValue> AnimatableNumber::toCSSValue(CalculationPermittedValueRange calcRange) const
 {
-    return toCSSPrimitiveValue();
+    return toCSSPrimitiveValue(calcRange);
 }
 
 double AnimatableNumber::toDouble() const
@@ -92,14 +92,14 @@
     return m_number;
 }
 
-Length AnimatableNumber::toLength(const RenderStyle* style, const RenderStyle* rootStyle, double zoom) const
+Length AnimatableNumber::toLength(const RenderStyle* style, const RenderStyle* rootStyle, double zoom, CalculationPermittedValueRange calcRange) 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()->convertToLength<AnyConversion>(style, rootStyle, zoom);
+    return toCSSPrimitiveValue(calcRange)->convertToLength<AnyConversion>(style, rootStyle, zoom);
 }
 
 PassRefPtr<AnimatableValue> AnimatableNumber::interpolateTo(const AnimatableValue* value, double fraction) const
@@ -124,15 +124,15 @@
 {
     if (m_isCalc)
         return m_calcExpression;
-    return CSSCalcValue::createExpressionNode(toCSSPrimitiveValue(), m_number == trunc(m_number));
+    return CSSCalcValue::createExpressionNode(toCSSPrimitiveValue(CalculationRangeAll), m_number == trunc(m_number));
 }
 
-PassRefPtr<CSSPrimitiveValue> AnimatableNumber::toCSSPrimitiveValue() const
+PassRefPtr<CSSPrimitiveValue> AnimatableNumber::toCSSPrimitiveValue(CalculationPermittedValueRange calcRange) const
 {
     ASSERT(m_unitType != UnitTypeInvalid);
-    if (!m_cachedCSSPrimitiveValue) {
+    if (!m_cachedCSSPrimitiveValue || !isCompatibleWithCalcRange(m_cachedCSSPrimitiveValue.get(), calcRange)) {
         if (m_isCalc)
-            m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(CSSCalcValue::create(m_calcExpression));
+            m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(CSSCalcValue::create(m_calcExpression, calcRange));
         else
             m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(m_number, static_cast<CSSPrimitiveValue::UnitTypes>(numberTypeToPrimitiveUnit(m_unitType)));
     }
@@ -150,6 +150,12 @@
     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 e5d6b2c..30b2d54 100644
--- a/Source/core/animation/AnimatableNumber.h
+++ b/Source/core/animation/AnimatableNumber.h
@@ -34,6 +34,7 @@
 #include "core/animation/AnimatableValue.h"
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSPrimitiveValue.h"
+#include "core/platform/CalculationValue.h"
 
 namespace WebCore {
 
@@ -67,9 +68,9 @@
     {
         return adoptRef(new AnimatableNumber(number, unitType, cssPrimitiveValue));
     }
-    PassRefPtr<CSSValue> toCSSValue() const;
+    PassRefPtr<CSSValue> toCSSValue(CalculationPermittedValueRange = CalculationRangeAll) const;
     double toDouble() const;
-    Length toLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, double zoom) const;
+    Length toLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, double zoom, CalculationPermittedValueRange = CalculationRangeAll) const;
 
 protected:
     virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
@@ -100,10 +101,11 @@
     }
     static PassRefPtr<AnimatableNumber> create(const AnimatableNumber* leftAddend, const AnimatableNumber* rightAddend);
 
-    PassRefPtr<CSSPrimitiveValue> toCSSPrimitiveValue() const;
+    PassRefPtr<CSSPrimitiveValue> toCSSPrimitiveValue(CalculationPermittedValueRange) const;
     PassRefPtr<CSSCalcExpressionNode> toCSSCalcExpressionNode() const;
 
     PassRefPtr<AnimatableNumber> scale(double) const;
+    static bool isCompatibleWithCalcRange(const CSSPrimitiveValue*, CalculationPermittedValueRange&);
     static NumberUnitType primitiveUnitToNumberType(unsigned short primitiveUnit);
     static unsigned short numberTypeToPrimitiveUnit(NumberUnitType numberType);
 
diff --git a/Source/core/animation/AnimatableUnknown.h b/Source/core/animation/AnimatableUnknown.h
index c136380..1c0d2c6 100644
--- a/Source/core/animation/AnimatableUnknown.h
+++ b/Source/core/animation/AnimatableUnknown.h
@@ -52,11 +52,6 @@
         return defaultInterpolateTo(this, value, fraction);
     }
 
-    virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue* value) const OVERRIDE
-    {
-        return defaultAddWith(this, value);
-    }
-
 private:
     explicit AnimatableUnknown(PassRefPtr<CSSValue> value)
         : AnimatableValue(TypeUnknown)
diff --git a/Source/core/animation/AnimatableValue.cpp b/Source/core/animation/AnimatableValue.cpp
index 30708ac..5c0d57b 100644
--- a/Source/core/animation/AnimatableValue.cpp
+++ b/Source/core/animation/AnimatableValue.cpp
@@ -70,4 +70,9 @@
     return defaultAddWith(left, right);
 }
 
+PassRefPtr<AnimatableValue> AnimatableValue::addWith(const AnimatableValue* value) const
+{
+    return defaultAddWith(this, value);
+}
+
 } // namespace WebCore
diff --git a/Source/core/animation/AnimatableValue.h b/Source/core/animation/AnimatableValue.h
index 7eadc56..bfaa571 100644
--- a/Source/core/animation/AnimatableValue.h
+++ b/Source/core/animation/AnimatableValue.h
@@ -55,6 +55,7 @@
     bool isNeutral() const { return m_type == TypeNeutral; }
     bool isTransform() const { return m_type == TypeTransform; }
     bool isUnknown() const { return m_type == TypeUnknown; }
+    bool isVisibility() const { return m_type == TypeVisibility; }
 
 protected:
     enum AnimatableType {
@@ -65,6 +66,7 @@
         TypeNumber,
         TypeTransform,
         TypeUnknown,
+        TypeVisibility,
     };
 
     AnimatableValue(AnimatableType type) : m_type(type) { }
@@ -79,7 +81,7 @@
     static PassRefPtr<AnimatableValue> defaultInterpolateTo(const AnimatableValue* left, const AnimatableValue* right, double fraction) { return takeConstRef((fraction < 0.5) ? left : right); }
 
     // For noncommutative values read A->addWith(B) to mean the value A with B composed onto it.
-    virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const = 0;
+    virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const;
     static PassRefPtr<AnimatableValue> defaultAddWith(const AnimatableValue* left, const AnimatableValue* right) { return takeConstRef(right); }
 
     template <class T>
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/animation/AnimatableVisibility.cpp
similarity index 71%
copy from Source/core/loader/CachedMetadata.cpp
copy to Source/core/animation/AnimatableVisibility.cpp
index f3f2a30..2cfc097 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/animation/AnimatableVisibility.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * 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
@@ -29,8 +29,21 @@
  */
 
 #include "config.h"
-#include "core/loader/CachedMetadata.h"
+#include "core/animation/AnimatableVisibility.h"
 
 namespace WebCore {
 
+PassRefPtr<AnimatableValue> AnimatableVisibility::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+    EVisibility from = m_visibility;
+    EVisibility to = toAnimatableVisibility(value)->m_visibility;
+    if (from != VISIBLE && to != VISIBLE)
+        return defaultInterpolateTo(this, value, fraction);
+    if (fraction <= 0)
+        return takeConstRef(this);
+    if (fraction >= 1)
+        return takeConstRef(value);
+    return takeConstRef(from == VISIBLE ? this : value);
+}
+
 } // namespace WebCore
diff --git a/Source/core/animation/AnimatableVisibility.h b/Source/core/animation/AnimatableVisibility.h
new file mode 100644
index 0000000..d24058f
--- /dev/null
+++ b/Source/core/animation/AnimatableVisibility.h
@@ -0,0 +1,69 @@
+/*
+ * 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 AnimatableVisibility_h
+#define AnimatableVisibility_h
+
+#include "core/animation/AnimatableValue.h"
+#include "core/rendering/style/RenderStyleConstants.h"
+
+namespace WebCore {
+
+class AnimatableVisibility : public AnimatableValue {
+public:
+    virtual ~AnimatableVisibility() { }
+    static PassRefPtr<AnimatableVisibility> create(EVisibility visibility)
+    {
+        return adoptRef(new AnimatableVisibility(visibility));
+    }
+
+    EVisibility visibility() const { return m_visibility; }
+
+protected:
+    virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+
+private:
+    explicit AnimatableVisibility(EVisibility visibility)
+        : AnimatableValue(TypeVisibility)
+        , m_visibility(visibility)
+    {
+    }
+    const EVisibility m_visibility;
+};
+
+inline const AnimatableVisibility* toAnimatableVisibility(const AnimatableValue* value)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(value && value->isVisibility());
+    return static_cast<const AnimatableVisibility*>(value);
+}
+
+} // namespace WebCore
+
+#endif // AnimatableVisibility_h
diff --git a/Source/core/animation/DocumentTimeline.cpp b/Source/core/animation/DocumentTimeline.cpp
index 07c8748..902897d 100644
--- a/Source/core/animation/DocumentTimeline.cpp
+++ b/Source/core/animation/DocumentTimeline.cpp
@@ -63,7 +63,11 @@
 
 void DocumentTimeline::serviceAnimations(double monotonicAnimationStartTime)
 {
-    if (!isNull(m_zeroTimeAsPerfTime)) {
+    // FIXME: The below ASSERT fires on Windows when running chrome.exe.
+    // Does not fire with --single-process, or on Linux, or in
+    // content_shell.exe. The assert condition has been moved up into the
+    // outer 'if' to work around this. http://crbug.com/280439.
+    if (!isNull(m_zeroTimeAsPerfTime) && (m_currentTime <= monotonicAnimationStartTime - m_zeroTimeAsPerfTime)) {
         ASSERT(m_currentTime <= monotonicAnimationStartTime - m_zeroTimeAsPerfTime);
         m_currentTime = monotonicAnimationStartTime - m_zeroTimeAsPerfTime;
     }
diff --git a/Source/core/animation/Timing.h b/Source/core/animation/Timing.h
index 9494979..43b04c0 100644
--- a/Source/core/animation/Timing.h
+++ b/Source/core/animation/Timing.h
@@ -85,7 +85,6 @@
     double playbackRate;
     PlaybackDirection direction;
     RefPtr<TimingFunction> timingFunction;
-
 };
 
 } // namespace WebCore
diff --git a/Source/core/animation/css/CSSAnimatableValueFactory.cpp b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
index 8d4bf34..14933d0 100644
--- a/Source/core/animation/css/CSSAnimatableValueFactory.cpp
+++ b/Source/core/animation/css/CSSAnimatableValueFactory.cpp
@@ -38,6 +38,7 @@
 #include "core/animation/AnimatableNumber.h"
 #include "core/animation/AnimatableTransform.h"
 #include "core/animation/AnimatableUnknown.h"
+#include "core/animation/AnimatableVisibility.h"
 #include "core/animation/css/CSSAnimations.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/platform/Length.h"
@@ -102,18 +103,18 @@
 
 PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::createFromColor(CSSPropertyID property, const RenderStyle* style)
 {
-    StyleColor color = style->colorIncludingFallback(property, false);
-    StyleColor visitedLinkColor = style->colorIncludingFallback(property, true);
-    Color fallbackColor = style->color().color();
-    Color fallbackVisitedLinkColor = style->visitedLinkColor().color();
+    Color color = style->colorIncludingFallback(property, false);
+    Color visitedLinkColor = style->colorIncludingFallback(property, true);
+    Color fallbackColor = style->color();
+    Color fallbackVisitedLinkColor = style->visitedLinkColor();
     Color resolvedColor;
-    if (color.isValid() && !color.isCurrentColor())
-        resolvedColor = color.color();
+    if (color.isValid())
+        resolvedColor = color;
     else
         resolvedColor = fallbackColor;
     Color resolvedVisitedLinkColor;
-    if (visitedLinkColor.isValid() && !visitedLinkColor.isCurrentColor())
-        resolvedVisitedLinkColor = visitedLinkColor.color();
+    if (visitedLinkColor.isValid())
+        resolvedVisitedLinkColor = visitedLinkColor;
     else
         resolvedVisitedLinkColor = fallbackVisitedLinkColor;
     return AnimatableColor::create(resolvedColor, resolvedVisitedLinkColor);
@@ -181,6 +182,10 @@
         return createFromDouble(style->opacity());
     case CSSPropertyOutlineColor:
         return createFromColor(property, style);
+    case CSSPropertyOutlineOffset:
+        return createFromDouble(style->outlineOffset());
+    case CSSPropertyOutlineWidth:
+        return createFromDouble(style->outlineWidth());
     case CSSPropertyPaddingBottom:
         return createFromLength(style->paddingBottom(), style);
     case CSSPropertyPaddingLeft:
@@ -219,6 +224,8 @@
         return createFromLength(style->transformOriginY(), style);
     case CSSPropertyWidth:
         return createFromLength(style->width(), style);
+    case CSSPropertyVisibility:
+        return AnimatableVisibility::create(style->visibility());
     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 3d62974..ce36831 100644
--- a/Source/core/animation/css/CSSAnimations.cpp
+++ b/Source/core/animation/css/CSSAnimations.cpp
@@ -79,12 +79,15 @@
         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()->isLinearTimingFunction())
+        if (animationData->timingFunction()->type() != TimingFunction::LinearFunction)
             timing.timingFunction = animationData->timingFunction();
     } else {
-        // CSS default is ease, default in model is linear.
-        timing.timingFunction = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease);
+        timing.timingFunction = CSSAnimationData::initialAnimationTimingFunction();
     }
     if (animationData->isFillModeSet()) {
         switch (animationData->fillMode()) {
@@ -222,7 +225,7 @@
     for (Vector<CSSAnimationUpdate::NewAnimation>::const_iterator iter = update->newAnimations().begin(); iter != update->newAnimations().end(); ++iter) {
         OwnPtr<CSSAnimations::EventDelegate> eventDelegate = adoptPtr(new EventDelegate(element, iter->name));
         RefPtr<Animation> animation = Animation::create(element, iter->animation->effect(), iter->animation->specified(), eventDelegate.release());
-        RefPtr<Player> player = element->document()->timeline()->play(animation.get());
+        RefPtr<Player> player = element->document().timeline()->play(animation.get());
         m_animations.set(iter->name, player.get());
     }
 }
@@ -238,8 +241,8 @@
 
 void CSSAnimations::EventDelegate::maybeDispatch(Document::ListenerType listenerType, AtomicString& eventName, double elapsedTime)
 {
-    if (m_target->document()->hasListenerType(listenerType))
-        m_target->document()->timeline()->addEventToDispatch(m_target, WebKitAnimationEvent::create(eventName, m_name, elapsedTime));
+    if (m_target->document().hasListenerType(listenerType))
+        m_target->document().timeline()->addEventToDispatch(m_target, WebKitAnimationEvent::create(eventName, m_name, elapsedTime));
 }
 
 void CSSAnimations::EventDelegate::onEventCondition(const TimedItem* timedItem, bool isFirstSample, TimedItem::Phase previousPhase, double previousIteration)
diff --git a/Source/core/core.gyp b/Source/core/core.gyp
index 93f7975..ebfc56c 100644
--- a/Source/core/core.gyp
+++ b/Source/core/core.gyp
@@ -830,11 +830,6 @@
             ['exclude', 'platform/chromium/PlatformThemeChromiumDefault\\.(cpp|h)'],
           ],
         }],
-        ['use_default_render_theme==0 and OS!="android"', {
-          'sources/': [
-            ['exclude', 'platform/ScrollbarThemeOverlay\\.(cpp|h)'],
-          ]
-        }],
       ],
     },
     {
diff --git a/Source/core/core.gypi b/Source/core/core.gypi
index f7c323f..8a1c624 100644
--- a/Source/core/core.gypi
+++ b/Source/core/core.gypi
@@ -53,8 +53,10 @@
             'dom/DOMError.idl',
             'dom/DOMException.idl',
             'dom/DOMImplementation.idl',
+            'dom/DOMSettableTokenList.idl',
             'dom/DOMStringList.idl',
             'dom/DOMStringMap.idl',
+            'dom/DOMTokenList.idl',
             'dom/DataTransferItem.idl',
             'dom/DataTransferItemList.idl',
             'dom/Document.idl',
@@ -112,8 +114,6 @@
             'fileapi/FileReader.idl',
             'fileapi/FileReaderSync.idl',
             'fileapi/Stream.idl',
-            'html/DOMSettableTokenList.idl',
-            'html/DOMTokenList.idl',
             'html/FormData.idl',
             'html/HTMLAllCollection.idl',
             'html/HTMLAnchorElement.idl',
@@ -447,7 +447,6 @@
             'svg/SVGStyleElement.idl',
             'svg/SVGSwitchElement.idl',
             'svg/SVGSymbolElement.idl',
-            'svg/SVGTRefElement.idl',
             'svg/SVGTSpanElement.idl',
             'svg/SVGTextContentElement.idl',
             'svg/SVGTextElement.idl',
@@ -541,6 +540,8 @@
             'animation/AnimatableUnknown.h',
             'animation/AnimatableValue.cpp',
             'animation/AnimatableValue.h',
+            'animation/AnimatableVisibility.cpp',
+            'animation/AnimatableVisibility.h',
             'animation/Animation.cpp',
             'animation/Animation.h',
             'animation/AnimationEffect.h',
@@ -738,7 +739,6 @@
             'css/ShadowValue.cpp',
             'css/ShadowValue.h',
             'css/SiblingTraversalStrategies.h',
-            'css/StyleColor.cpp',
             'css/StyleColor.h',
             'css/StyleInvalidationAnalysis.cpp',
             'css/StyleInvalidationAnalysis.h',
@@ -889,10 +889,19 @@
             'editing/chromium/EditorChromium.cpp',
             'editing/htmlediting.cpp',
             'editing/markup.cpp',
+            'fetch/CachedMetadata.cpp',
+            'fetch/CachedMetadata.h',
+            'fetch/CrossOriginAccessControl.cpp',
+            'fetch/CrossOriginAccessControl.h',
             'fetch/CSSStyleSheetResource.cpp',
             'fetch/CSSStyleSheetResource.h',
             'fetch/DocumentResource.cpp',
             'fetch/DocumentResource.h',
+            'fetch/DocumentResourceReference.h',
+            'fetch/FetchContext.cpp',
+            'fetch/FetchContext.h',
+            'fetch/FetchRequest.cpp',
+            'fetch/FetchRequest.h',
             'fetch/FontResource.cpp',
             'fetch/FontResource.h',
             'fetch/ImageResource.cpp',
@@ -904,21 +913,20 @@
             'fetch/ResourceClientWalker.h',
             'fetch/ResourceFetcher.cpp',
             'fetch/ResourceFetcher.h',
-            'fetch/ResourceLoadNotifier.cpp',
-            'fetch/ResourceLoadNotifier.h',
             'fetch/ResourceLoader.cpp',
             'fetch/ResourceLoader.h',
             'fetch/ResourceLoaderOptions.h',
+            'fetch/ResourceLoaderSet.cpp',
+            'fetch/ResourceLoaderSet.h',
             'fetch/ResourcePtr.cpp',
             'fetch/ResourcePtr.h',
-            'fetch/FetchRequest.cpp',
-            'fetch/FetchRequest.h',
             'fetch/FetchInitiatorInfo.h',
             'fetch/ScriptResource.cpp',
             'fetch/ScriptResource.h',
             'fetch/ShaderResource.cpp',
             'fetch/ShaderResource.h',
-            'fetch/DocumentResourceReference.h',
+            'fetch/TextResourceDecoder.cpp',
+            'fetch/TextResourceDecoder.h',
             'fetch/TextTrackResource.cpp',
             'fetch/TextTrackResource.h',
             'fetch/XSLStyleSheetResource.cpp',
@@ -1080,11 +1088,7 @@
             'inspector/WorkerInspectorController.h',
             'inspector/WorkerRuntimeAgent.cpp',
             'inspector/WorkerRuntimeAgent.h',
-            'loader/CachedMetadata.cpp',
-            'loader/CachedMetadata.h',
             'loader/CookieJar.cpp',
-            'loader/CrossOriginAccessControl.cpp',
-            'loader/CrossOriginAccessControl.h',
             'loader/CrossOriginPreflightResultCache.cpp',
             'loader/DocumentLoadTiming.cpp',
             'loader/DocumentLoader.cpp',
@@ -1096,6 +1100,8 @@
             'loader/EmptyClients.h',
             'loader/FormState.cpp',
             'loader/FormSubmission.cpp',
+            'loader/FrameFetchContext.h',
+            'loader/FrameFetchContext.cpp',
             'loader/FrameLoadRequest.h',
             'loader/FrameLoader.cpp',
             'loader/FrameLoaderStateMachine.cpp',
@@ -1124,7 +1130,6 @@
             'loader/SinkDocument.cpp',
             'loader/SinkDocument.h',
             'loader/SubstituteData.h',
-            'loader/TextResourceDecoder.cpp',
             'loader/TextResourceDecoderBuilder.cpp',
             'loader/TextResourceDecoderBuilder.h',
             'loader/TextTrackLoader.cpp',
@@ -1346,7 +1351,10 @@
             'rendering/LayoutState.cpp',
             'rendering/OrderIterator.cpp',
             'rendering/OrderIterator.h',
+            'rendering/LayoutIndicator.cpp',
+            'rendering/LayoutIndicator.h',
             'rendering/LayoutRepainter.cpp',
+            'rendering/PartialLayoutState.h',
             'rendering/Pagination.cpp',
             'rendering/Pagination.h',
             'rendering/PointerEventsHitRules.cpp',
@@ -1355,6 +1363,7 @@
             'rendering/RenderApplet.h',
             'rendering/RenderBR.cpp',
             'rendering/RenderBlock.cpp',
+            'rendering/RenderBlockFlow.cpp',
             'rendering/RenderBlockLineLayout.cpp',
             'rendering/RenderBox.cpp',
             'rendering/RenderBoxModelObject.cpp',
@@ -1513,6 +1522,8 @@
             'rendering/RenderWidget.cpp',
             'rendering/RenderWordBreak.cpp',
             'rendering/RenderWordBreak.h',
+            'rendering/RenderingNodeProxy.cpp',
+            'rendering/RenderingNodeProxy.h',
             'rendering/RootInlineBox.cpp',
             'rendering/ScrollBehavior.cpp',
             'rendering/SubtreeLayoutScope.cpp',
@@ -1534,7 +1545,6 @@
             'rendering/shapes/ShapeInfo.h',
             'rendering/shapes/ShapeInsideInfo.cpp',
             'rendering/shapes/ShapeInsideInfo.h',
-            'rendering/shapes/ShapeInterval.cpp',
             'rendering/shapes/ShapeInterval.h',
             'rendering/shapes/ShapeOutsideInfo.cpp',
             'rendering/shapes/ShapeOutsideInfo.h',
@@ -1810,6 +1820,8 @@
             'dom/DOMStringList.h',
             'dom/DOMStringMap.cpp',
             'dom/DOMStringMap.h',
+            'dom/DOMTokenList.cpp',
+            'dom/DOMTokenList.h',
             'dom/DataTransferItem.cpp',
             'dom/DataTransferItem.h',
             'dom/DataTransferItemList.h',
@@ -1947,6 +1959,8 @@
             'dom/ProcessingInstruction.h',
             'dom/ProgressEvent.cpp',
             'dom/ProgressEvent.h',
+            'dom/PostAttachCallbacks.cpp',
+            'dom/PostAttachCallbacks.h',
             'dom/Promise.h',
             'dom/PromiseResolver.h',
             'dom/PseudoElement.cpp',
@@ -1971,6 +1985,8 @@
             'dom/SecurityPolicyViolationEvent.h',
             'dom/SelectorQuery.cpp',
             'dom/SelectorQuery.h',
+            'dom/DOMSettableTokenList.cpp',
+            'dom/DOMSettableTokenList.h',
             'dom/ShadowTreeStyleSheetCollection.cpp',
             'dom/ShadowTreeStyleSheetCollection.h',
             'dom/SimulatedClickOptions.h',
@@ -2024,6 +2040,8 @@
             'dom/VisitedLinkState.h',
             'dom/WebKitAnimationEvent.cpp',
             'dom/WebKitAnimationEvent.h',
+            'dom/WheelController.cpp',
+            'dom/WheelController.h',
             'dom/WheelEvent.cpp',
             'dom/WheelEvent.h',
             'dom/WindowEventContext.cpp',
@@ -2071,10 +2089,6 @@
             'html/ColorInputType.h',
             'html/DOMFormData.cpp',
             'html/DOMFormData.h',
-            'html/DOMSettableTokenList.cpp',
-            'html/DOMSettableTokenList.h',
-            'html/DOMTokenList.cpp',
-            'html/DOMTokenList.h',
             'html/DOMURL.cpp',
             'html/DOMURL.h',
             'html/DateInputType.cpp',
@@ -2569,7 +2583,6 @@
             'html/track/WebVTTTokenizer.h',
         ],
         'webcore_platform_files': [
-            'platform/AsyncFileSystem.h',
             'platform/AsyncFileSystemCallbacks.h',
             'platform/CalculationValue.cpp',
             'platform/CalculationValue.h',
@@ -2607,6 +2620,8 @@
             'platform/LifecycleObserver.cpp',
             'platform/LifecycleObserver.h',
             'platform/LinkHash.cpp',
+            'platform/LocalizedStrings.cpp',
+            'platform/LocalizedStrings.h',
             'platform/Logging.cpp',
             'platform/MIMETypeFromURL.cpp',
             'platform/MIMETypeFromURL.h',
@@ -2676,8 +2691,11 @@
             'platform/UUID.h',
             'platform/Widget.cpp',
             'platform/Widget.h',
+            'platform/animation/AnimationValue.h',
             'platform/animation/CSSAnimationData.cpp',
             'platform/animation/CSSAnimationDataList.cpp',
+            'platform/animation/KeyframeValueList.cpp',
+            'platform/animation/KeyframeValueList.h',
             'platform/audio/AudioArray.h',
             'platform/audio/AudioBus.cpp',
             'platform/audio/AudioBus.h',
@@ -2785,7 +2803,6 @@
             'platform/chromium/KeyCodeConversionGtk.cpp',
             'platform/chromium/KeyboardCodes.h',
             'platform/chromium/LanguageChromium.cpp',
-            'platform/chromium/LocalizedStringsChromium.cpp',
             'platform/chromium/MemoryUsageSupportChromium.cpp',
             'platform/chromium/MIMETypeRegistryChromium.cpp',
             'platform/chromium/PlatformKeyboardEventChromium.cpp',
@@ -2842,8 +2859,6 @@
             'platform/graphics/GraphicsContext3DImagePacking.cpp',
             'platform/graphics/GraphicsContextAnnotation.cpp',
             'platform/graphics/GraphicsLayer.cpp',
-            'platform/graphics/GraphicsLayerTransform.cpp',
-            'platform/graphics/GraphicsLayerTransform.h',
             'platform/graphics/GraphicsTypes.cpp',
             'platform/graphics/Image.cpp',
             'platform/graphics/ImageBuffer.cpp',
@@ -3157,6 +3172,7 @@
             'platform/mock/PlatformSpeechSynthesizerMock.h',
             'platform/mock/ScrollbarThemeMock.cpp',
             'platform/mock/ScrollbarThemeMock.h',
+            'platform/mock/ScrollbarThemeOverlayMock.h',
             'platform/network/BlobData.cpp',
             'platform/network/BlobData.h',
             'platform/network/DNS.cpp',
@@ -3638,8 +3654,6 @@
             'svg/SVGSwitchElement.h',
             'svg/SVGSymbolElement.cpp',
             'svg/SVGSymbolElement.h',
-            'svg/SVGTRefElement.cpp',
-            'svg/SVGTRefElement.h',
             'svg/SVGTSpanElement.cpp',
             'svg/SVGTSpanElement.h',
             'svg/SVGTests.cpp',
@@ -3750,6 +3764,7 @@
             'platform/chromium/support/WebData.cpp',
             'platform/chromium/support/WebDeviceMotionData.cpp',
             'platform/chromium/support/WebDeviceOrientationData.cpp',
+            'platform/chromium/support/WebFileSystemCallbacks.cpp',
             'platform/chromium/support/WebFloatQuad.cpp',
             'platform/chromium/support/WebHTTPBody.cpp',
             'platform/chromium/support/WebHTTPLoadInfo.cpp',
@@ -3826,6 +3841,7 @@
             'platform/graphics/gpu/DrawingBufferTest.cpp',
             'platform/image-decoders/ImageDecoderTest.cpp',
             'platform/image-decoders/gif/GIFImageDecoderTest.cpp',
+            'platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp',
             'platform/image-decoders/webp/WEBPImageDecoderTest.cpp',
             'platform/text/DateTimeFormatTest.cpp',
             'rendering/RenderOverflowTest.cpp',
diff --git a/Source/core/core_derived_sources.gyp b/Source/core/core_derived_sources.gyp
index e89bab6..058f19e 100644
--- a/Source/core/core_derived_sources.gyp
+++ b/Source/core/core_derived_sources.gyp
@@ -111,7 +111,7 @@
           'msvs_cygwin_shell': 0,
           'action': [
             '<(perl_exe)',
-            'inspector/xxd.pl',
+            'scripts/xxd.pl',
             'V8ArrayBufferViewCustomScript_js',
             '<@(_inputs)',
             '<@(_outputs)'
@@ -129,7 +129,7 @@
           'msvs_cygwin_shell': 0,
           'action': [
             '<(perl_exe)',
-            'inspector/xxd.pl',
+            'scripts/xxd.pl',
             'XMLViewer_css',
             '<@(_inputs)',
             '<@(_outputs)'
@@ -146,7 +146,7 @@
           'msvs_cygwin_shell': 0,
           'action': [
             '<(perl_exe)',
-            'inspector/xxd.pl',
+            'scripts/xxd.pl',
             'XMLViewer_js',
             '<@(_inputs)',
             '<@(_outputs)'
@@ -174,6 +174,7 @@
           'inputs': [
             '<@(scripts_for_in_files)',
             'scripts/make_runtime_features.py',
+            'scripts/name_utilities.py',
             'page/RuntimeEnabledFeatures.in',
             'scripts/templates/RuntimeEnabledFeatures.cpp.tmpl',
             'scripts/templates/RuntimeEnabledFeatures.h.tmpl',
@@ -372,6 +373,7 @@
           'inputs': [
             '<@(scripts_for_in_files)',
             'scripts/make_event_factory.py',
+            'scripts/name_utilities.py',
             '<(SHARED_INTERMEDIATE_DIR)/blink/EventInterfaces.in',
             'dom/EventAliases.in',
           ],
@@ -394,6 +396,7 @@
           'inputs': [
             '<@(scripts_for_in_files)',
             'scripts/make_event_factory.py',
+            'scripts/name_utilities.py',
             'dom/EventTargetFactory.in',
           ],
           'outputs': [
@@ -453,6 +456,7 @@
               'css/mediaControls.css',
               'css/mediaControlsAndroid.css',
               'css/fullscreen.css',
+              'css/xhtmlmp.css',
             ],
           },
           'inputs': [
diff --git a/Source/core/css/CSSCalculationValue.h b/Source/core/css/CSSCalculationValue.h
index 85db53c..6bf1ac7 100644
--- a/Source/core/css/CSSCalculationValue.h
+++ b/Source/core/css/CSSCalculationValue.h
@@ -110,6 +110,7 @@
     bool isInt() const { return m_expression->isInteger(); }
     double doubleValue() const;
     bool isNegative() const { return m_expression->doubleValue() < 0; }
+    CalculationPermittedValueRange permittedValueRange() { return m_nonNegative ? CalculationRangeNonNegative : CalculationRangeAll; }
     double computeLengthPx(const RenderStyle* currentStyle, const RenderStyle* rootStyle, double multiplier = 1.0, bool computingFontSize = false) const;
     CSSCalcExpressionNode* expressionNode() const { return m_expression.get(); }
 
diff --git a/Source/core/css/CSSCanvasValue.cpp b/Source/core/css/CSSCanvasValue.cpp
index 73fbfed..ca89a87 100644
--- a/Source/core/css/CSSCanvasValue.cpp
+++ b/Source/core/css/CSSCanvasValue.cpp
@@ -69,7 +69,7 @@
 
 IntSize CSSCanvasValue::fixedSize(const RenderObject* renderer)
 {
-    if (HTMLCanvasElement* elt = element(renderer->document()))
+    if (HTMLCanvasElement* elt = element(&renderer->document()))
         return IntSize(elt->width(), elt->height());
     return IntSize();
 }
@@ -88,7 +88,7 @@
 PassRefPtr<Image> CSSCanvasValue::image(RenderObject* renderer, const IntSize& /*size*/)
 {
     ASSERT(clients().contains(renderer));
-    HTMLCanvasElement* elt = element(renderer->document());
+    HTMLCanvasElement* elt = element(&renderer->document());
     if (!elt || !elt->buffer())
         return 0;
     return elt->copiedImage();
diff --git a/Source/core/css/CSSComputedStyleDeclaration.cpp b/Source/core/css/CSSComputedStyleDeclaration.cpp
index 870d206..dd2e82d 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -362,6 +362,7 @@
     CSSPropertyMarkerMid,
     CSSPropertyMarkerStart,
     CSSPropertyMaskType,
+    CSSPropertyMaskSourceType,
     CSSPropertyShapeRendering,
     CSSPropertyStroke,
     CSSPropertyStrokeDasharray,
@@ -652,7 +653,7 @@
     return zoomAdjustedPixelValueForLength(l, style);
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(RenderStyle* style, const StyleColor& color) const
+PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(RenderStyle* style, const Color& color) const
 {
     // This function does NOT look at visited information, so that computed style doesn't expose that.
     if (!color.isValid())
@@ -660,48 +661,36 @@
     return cssValuePool().createColorValue(color.rgb());
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(const RenderObject* renderer, const RenderStyle* style, int colorProperty) const
-{
-    Color color;
-    if (renderer) {
-        if (m_allowVisitedStyle)
-            color = renderer->resolveColor(colorProperty);
-        else
-            color = renderer->resolveColor(style->colorIncludingFallback(colorProperty, false /* visited */));
-    } else {
-        if (m_allowVisitedStyle)
-            color = style->visitedDependentColor(colorProperty).color();
-        else
-            color = style->colorIncludingFallback(colorProperty, false /* visited */).color();
-    }
-    return cssValuePool().createColorValue(color.rgb());
-}
-
-static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderObject* renderer, RenderView* renderView)
 {
     RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+    LayoutUnit width = 0;
+    LayoutUnit height = 0;
+    if (radius.width().isCalculated() || radius.height().isCalculated()) {
+        LayoutRect layoutRect = (renderer && renderer->isBox()) ? toRenderBox(renderer)->borderBoxRect() : LayoutRect();
+        width = layoutRect.width();
+        height = layoutRect.height();
+    }
     if (radius.width().type() == Percent)
         list->append(cssValuePool().createValue(radius.width().percent(), CSSPrimitiveValue::CSS_PERCENTAGE));
     else
-        list->append(zoomAdjustedPixelValue(valueForLength(radius.width(), 0, renderView), style));
+        list->append(zoomAdjustedPixelValue(valueForLength(radius.width(), width, renderView), style));
     if (radius.height().type() == Percent)
         list->append(cssValuePool().createValue(radius.height().percent(), CSSPrimitiveValue::CSS_PERCENTAGE));
     else
-        list->append(zoomAdjustedPixelValue(valueForLength(radius.height(), 0, renderView), style));
+        list->append(zoomAdjustedPixelValue(valueForLength(radius.height(), height, renderView), style));
     return list.release();
 }
 
-static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderObject* renderer, RenderView* renderView)
 {
-    if (radius.width() == radius.height()) {
-        if (radius.width().type() == Percent)
-            return cssValuePool().createValue(radius.width().percent(), CSSPrimitiveValue::CSS_PERCENTAGE);
-        return zoomAdjustedPixelValue(valueForLength(radius.width(), 0, renderView), style);
-    }
-    return valuesForBorderRadiusCorner(radius, style, renderView);
+    RefPtr<CSSValueList> list = valuesForBorderRadiusCorner(radius, style, renderer, renderView);
+    if (list->item(0)->equals(*list->item(1)))
+        return list->item(0);
+    return list.release();
 }
 
-static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle* style, RenderObject* renderer, RenderView* renderView)
 {
     RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
     bool showHorizontalBottomLeft = style->borderTopRightRadius().width() != style->borderBottomLeftRadius().width();
@@ -713,10 +702,10 @@
     bool showVerticalTopRight = (style->borderTopRightRadius().height() != style->borderTopLeftRadius().height()) || showVerticalBottomRight;
     bool showVerticalTopLeft = (style->borderTopLeftRadius().width() != style->borderTopLeftRadius().height());
 
-    RefPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style->borderTopLeftRadius(), style, renderView);
-    RefPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style->borderTopRightRadius(), style, renderView);
-    RefPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style->borderBottomRightRadius(), style, renderView);
-    RefPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style->borderBottomLeftRadius(), style, renderView);
+    RefPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style->borderTopLeftRadius(), style, renderer, renderView);
+    RefPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style->borderTopRightRadius(), style, renderer, renderView);
+    RefPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style->borderBottomRightRadius(), style, renderer, renderView);
+    RefPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style->borderBottomLeftRadius(), style, renderer, renderView);
 
     RefPtr<CSSValueList> horizontalRadii = CSSValueList::createSpaceSeparated();
     horizontalRadii->append(topLeftRadius->item(0));
@@ -933,7 +922,7 @@
             filterValue = CSSFilterValue::create(CSSFilterValue::DropShadowFilterOperation);
             // We want our computed style to look like that of a text shadow (has neither spread nor inset style).
             OwnPtr<ShadowData> shadow = ShadowData::create(dropShadowOperation->location(), dropShadowOperation->stdDeviation(), 0, Normal, dropShadowOperation->color());
-            filterValue->append(valueForShadow(renderer, shadow.get(), CSSPropertyTextShadow, style));
+            filterValue->append(valueForShadow(shadow.get(), CSSPropertyTextShadow, style));
             break;
         }
         case FilterOperation::VALIDATED_CUSTOM:
@@ -1132,22 +1121,46 @@
 
 static PassRefPtr<CSSValue> createTimingFunctionValue(const TimingFunction* timingFunction)
 {
-    if (timingFunction->isCubicBezierTimingFunction()) {
-        const CubicBezierTimingFunction* bezierTimingFunction = static_cast<const CubicBezierTimingFunction*>(timingFunction);
-        if (bezierTimingFunction->timingFunctionPreset() != CubicBezierTimingFunction::Custom) {
-            CSSValueID valueId = CSSValueInvalid;
-            switch (bezierTimingFunction->timingFunctionPreset()) {
-            case CubicBezierTimingFunction::Ease:
-                valueId = CSSValueEase;
+    switch (timingFunction->type()) {
+    case TimingFunction::CubicBezierFunction:
+        {
+            const CubicBezierTimingFunction* bezierTimingFunction = static_cast<const CubicBezierTimingFunction*>(timingFunction);
+            if (bezierTimingFunction->subType() != CubicBezierTimingFunction::Custom) {
+                CSSValueID valueId = CSSValueInvalid;
+                switch (bezierTimingFunction->subType()) {
+                case CubicBezierTimingFunction::Ease:
+                    valueId = CSSValueEase;
+                    break;
+                case CubicBezierTimingFunction::EaseIn:
+                    valueId = CSSValueEaseIn;
+                    break;
+                case CubicBezierTimingFunction::EaseOut:
+                    valueId = CSSValueEaseOut;
+                    break;
+                case CubicBezierTimingFunction::EaseInOut:
+                    valueId = CSSValueEaseInOut;
+                    break;
+                default:
+                    ASSERT_NOT_REACHED();
+                    return 0;
+                }
+                return cssValuePool().createIdentifierValue(valueId);
+            }
+            return CSSCubicBezierTimingFunctionValue::create(bezierTimingFunction->x1(), bezierTimingFunction->y1(), bezierTimingFunction->x2(), bezierTimingFunction->y2());
+        }
+
+    case TimingFunction::StepsFunction:
+        {
+            const StepsTimingFunction* stepsTimingFunction = static_cast<const StepsTimingFunction*>(timingFunction);
+            if (stepsTimingFunction->subType() == StepsTimingFunction::Custom)
+                return CSSStepsTimingFunctionValue::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart());
+            CSSValueID valueId;
+            switch (stepsTimingFunction->subType()) {
+            case StepsTimingFunction::Start:
+                valueId = CSSValueStepStart;
                 break;
-            case CubicBezierTimingFunction::EaseIn:
-                valueId = CSSValueEaseIn;
-                break;
-            case CubicBezierTimingFunction::EaseOut:
-                valueId = CSSValueEaseOut;
-                break;
-            case CubicBezierTimingFunction::EaseInOut:
-                valueId = CSSValueEaseInOut;
+            case StepsTimingFunction::End:
+                valueId = CSSValueStepEnd;
                 break;
             default:
                 ASSERT_NOT_REACHED();
@@ -1155,15 +1168,10 @@
             }
             return cssValuePool().createIdentifierValue(valueId);
         }
-        return CSSCubicBezierTimingFunctionValue::create(bezierTimingFunction->x1(), bezierTimingFunction->y1(), bezierTimingFunction->x2(), bezierTimingFunction->y2());
-    }
 
-    if (timingFunction->isStepsTimingFunction()) {
-        const StepsTimingFunction* stepsTimingFunction = static_cast<const StepsTimingFunction*>(timingFunction);
-        return CSSStepsTimingFunctionValue::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart());
+    default:
+        return cssValuePool().createIdentifierValue(CSSValueLinear);
     }
-
-    return CSSLinearTimingFunctionValue::create();
 }
 
 static PassRefPtr<CSSValue> valueForAnimationTimingFunction(const CSSAnimationDataList* animList)
@@ -1171,7 +1179,7 @@
     RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
     if (animList) {
         for (size_t i = 0; i < animList->size(); ++i)
-            list->append(createTimingFunctionValue(animList->animation(i)->timingFunction().get()));
+            list->append(createTimingFunctionValue(animList->animation(i)->timingFunction()));
     } else
         // Note that initialAnimationTimingFunction() is used for both transitions and animations
         list->append(createTimingFunctionValue(CSSAnimationData::initialAnimationTimingFunction().get()));
@@ -1279,7 +1287,7 @@
     if (!m_node)
         return 0;
 
-    m_node->document()->updateLayoutIgnorePendingStylesheets();
+    m_node->document().updateLayoutIgnorePendingStylesheets();
 
     RefPtr<RenderStyle> style = m_node->computedStyle(m_pseudoElementSpecifier);
     if (!style)
@@ -1304,7 +1312,7 @@
     return style->fontDescription().useFixedDefaultSize();
 }
 
-PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadow(const RenderObject* renderer, const ShadowData* shadow, CSSPropertyID propertyID, const RenderStyle* style) const
+PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadow(const ShadowData* shadow, CSSPropertyID propertyID, const RenderStyle* style) const
 {
     if (!shadow)
         return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -1316,7 +1324,7 @@
         RefPtr<CSSPrimitiveValue> blur = zoomAdjustedPixelValue(s->blur(), style);
         RefPtr<CSSPrimitiveValue> spread = propertyID == CSSPropertyTextShadow ? PassRefPtr<CSSPrimitiveValue>() : zoomAdjustedPixelValue(s->spread(), style);
         RefPtr<CSSPrimitiveValue> style = propertyID == CSSPropertyTextShadow || s->style() == Normal ? PassRefPtr<CSSPrimitiveValue>() : cssValuePool().createIdentifierValue(CSSValueInset);
-        RefPtr<CSSPrimitiveValue> color = cssValuePool().createColorValue(renderer ? renderer->resolveColor(s->color()).rgb() : s->color().rgb());
+        RefPtr<CSSPrimitiveValue> color = cssValuePool().createColorValue(s->color().rgb());
         list->prepend(ShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), style.release(), color.release()));
     }
     return list.release();
@@ -1403,6 +1411,20 @@
     return list.release();
 }
 
+static PassRefPtr<CSSValue> valueForFillSourceType(EMaskSourceType type)
+{
+    switch (type) {
+    case MaskAlpha:
+        return cssValuePool().createValue(CSSValueAlpha);
+    case MaskLuminance:
+        return cssValuePool().createValue(CSSValueLuminance);
+    }
+
+    ASSERT_NOT_REACHED();
+
+    return 0;
+}
+
 static PassRefPtr<CSSValue> valueForFillSize(const FillSize& fillSize, const RenderStyle* style)
 {
     if (fillSize.type == Contain)
@@ -1551,6 +1573,19 @@
     case CSSPropertyWidth:
     case CSSPropertyWebkitFilter:
         return true;
+    case CSSPropertyBorderBottomLeftRadius:
+        return renderer && (style->borderBottomLeftRadius().width().isCalculated() || style->borderBottomLeftRadius().height().isCalculated());
+    case CSSPropertyBorderBottomRightRadius:
+        return renderer && (style->borderBottomRightRadius().width().isCalculated() || style->borderBottomRightRadius().height().isCalculated());
+    case CSSPropertyBorderRadius:
+        return isLayoutDependent(CSSPropertyBorderBottomLeftRadius, style.get(), renderer)
+            || isLayoutDependent(CSSPropertyBorderBottomRightRadius, style.get(), renderer)
+            || isLayoutDependent(CSSPropertyBorderTopLeftRadius, style.get(), renderer)
+            || isLayoutDependent(CSSPropertyBorderTopRightRadius, style, renderer);
+    case CSSPropertyBorderTopLeftRadius:
+        return renderer && (style->borderTopLeftRadius().width().isCalculated() || style->borderTopLeftRadius().height().isCalculated());
+    case CSSPropertyBorderTopRightRadius:
+        return renderer && (style->borderTopRightRadius().width().isCalculated() || style->borderTopRightRadius().height().isCalculated());
     case CSSPropertyMargin:
         return renderer && renderer->isBox() && (!style || !style->marginBottom().isFixed() || !style->marginTop().isFixed() || !style->marginLeft().isFixed() || !style->marginRight().isFixed());
     case CSSPropertyMarginLeft:
@@ -1612,9 +1647,9 @@
     RefPtr<RenderStyle> style;
 
     if (updateLayout) {
-        Document* document = styledNode->document();
+        Document& document = styledNode->document();
 
-        document->updateStyleForNodeIfNeeded(styledNode);
+        document.updateStyleForNodeIfNeeded(styledNode);
 
         // The style recalc could have caused the styled node to be discarded or replaced
         // if it was a PseudoElement so we need to update it.
@@ -1625,11 +1660,11 @@
 
         bool forceFullLayout = isLayoutDependent(propertyID, style, renderer)
             || styledNode->isInShadowTree()
-            || (document->styleResolverIfExists() && document->styleResolverIfExists()->hasViewportDependentMediaQueries() && document->ownerElement())
-            || document->seamlessParentIFrame();
+            || (document.styleResolverIfExists() && document.styleResolverIfExists()->hasViewportDependentMediaQueries() && document.ownerElement())
+            || document.seamlessParentIFrame();
 
         if (forceFullLayout) {
-            document->updateLayoutIgnorePendingStylesheets();
+            document.updateLayoutIgnorePendingStylesheets();
             styledNode = this->styledNode();
             style = computeRenderStyle(propertyID);
             renderer = styledNode->renderer();
@@ -1649,7 +1684,7 @@
             break;
 
         case CSSPropertyBackgroundColor:
-            return cssValuePool().createColorValue(renderer->resolveColor(m_allowVisitedStyle? style->visitedDependentColor(CSSPropertyBackgroundColor).rgb() : style->backgroundColor()).rgb());
+            return cssValuePool().createColorValue(m_allowVisitedStyle? style->visitedDependentColor(CSSPropertyBackgroundColor).rgb() : style->backgroundColor().rgb());
         case CSSPropertyBackgroundImage:
         case CSSPropertyWebkitMaskImage: {
             const FillLayer* layers = propertyID == CSSPropertyWebkitMaskImage ? style->maskLayers() : style->backgroundLayers();
@@ -1697,6 +1732,21 @@
 
             return list.release();
         }
+        case CSSPropertyMaskSourceType: {
+            const FillLayer* layers = style->maskLayers();
+
+            if (!layers)
+                return cssValuePool().createIdentifierValue(CSSValueNone);
+
+            if (!layers->next())
+                return valueForFillSourceType(layers->maskSourceType());
+
+            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
+            for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
+                list->append(valueForFillSourceType(currLayer->maskSourceType()));
+
+            return list.release();
+        }
         case CSSPropertyWebkitBackgroundComposite:
         case CSSPropertyWebkitMaskComposite: {
             const FillLayer* layers = propertyID == CSSPropertyWebkitMaskComposite ? style->maskLayers() : style->backgroundLayers();
@@ -1795,13 +1845,13 @@
                 return style->borderImageSource()->cssValue();
             return cssValuePool().createIdentifierValue(CSSValueNone);
         case CSSPropertyBorderTopColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyBorderTopColor);
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderTopColor).rgb()) : currentColorOrValidColor(style.get(), style->borderTopColor());
         case CSSPropertyBorderRightColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyBorderRightColor);
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderRightColor).rgb()) : currentColorOrValidColor(style.get(), style->borderRightColor());
         case CSSPropertyBorderBottomColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyBorderBottomColor);
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderBottomColor).rgb()) : currentColorOrValidColor(style.get(), style->borderBottomColor());
         case CSSPropertyBorderLeftColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyBorderLeftColor);
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderLeftColor).rgb()) : currentColorOrValidColor(style.get(), style->borderLeftColor());
         case CSSPropertyBorderTopStyle:
             return cssValuePool().createValue(style->borderTopStyle());
         case CSSPropertyBorderRightStyle:
@@ -1819,7 +1869,7 @@
         case CSSPropertyBorderLeftWidth:
             return zoomAdjustedPixelValue(style->borderLeftWidth(), style.get());
         case CSSPropertyBottom:
-            return valueForPositionOffset(style.get(), CSSPropertyBottom, renderer, m_node->document()->renderView());
+            return valueForPositionOffset(style.get(), CSSPropertyBottom, renderer, m_node->document().renderView());
         case CSSPropertyWebkitBoxAlign:
             return cssValuePool().createValue(style->boxAlign());
         case CSSPropertyWebkitBoxDecorationBreak:
@@ -1844,7 +1894,7 @@
             return valueForReflection(style->boxReflect(), style.get());
         case CSSPropertyBoxShadow:
         case CSSPropertyWebkitBoxShadow:
-            return valueForShadow(renderer, style->boxShadow(), propertyID, style.get());
+            return valueForShadow(style->boxShadow(), propertyID, style.get());
         case CSSPropertyCaptionSide:
             return cssValuePool().createValue(style->captionSide());
         case CSSPropertyClear:
@@ -1866,7 +1916,7 @@
         case CSSPropertyWebkitColumnProgression:
             return cssValuePool().createValue(style->columnProgression());
         case CSSPropertyWebkitColumnRuleColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyWebkitColumnRuleColor);
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(style.get(), style->columnRuleColor());
         case CSSPropertyWebkitColumnRuleStyle:
             return cssValuePool().createValue(style->columnRuleStyle());
         case CSSPropertyWebkitColumnRuleWidth:
@@ -1953,7 +2003,7 @@
             computedFont->variant = valueForFontVariant(style.get());
             computedFont->weight = valueForFontWeight(style.get());
             computedFont->size = valueForFontSize(style.get());
-            computedFont->lineHeight = valueForLineHeight(style.get(), m_node->document()->renderView());
+            computedFont->lineHeight = valueForLineHeight(style.get(), m_node->document().renderView());
             computedFont->family = valueForFontFamily(style.get());
             return computedFont.release();
         }
@@ -1986,15 +2036,15 @@
             return list.release();
         }
         case CSSPropertyGridAutoColumns:
-            return valueForGridTrackSize(style->gridAutoColumns(), style.get(), m_node->document()->renderView());
+            return valueForGridTrackSize(style->gridAutoColumns(), style.get(), m_node->document().renderView());
         case CSSPropertyGridAutoFlow:
             return cssValuePool().createValue(style->gridAutoFlow());
         case CSSPropertyGridAutoRows:
-            return valueForGridTrackSize(style->gridAutoRows(), style.get(), m_node->document()->renderView());
+            return valueForGridTrackSize(style->gridAutoRows(), style.get(), m_node->document().renderView());
         case CSSPropertyGridDefinitionColumns:
-            return valueForGridTrackList(style->gridDefinitionColumns(), style->orderedNamedGridColumnLines(), style.get(), m_node->document()->renderView());
+            return valueForGridTrackList(style->gridDefinitionColumns(), style->orderedNamedGridColumnLines(), style.get(), m_node->document().renderView());
         case CSSPropertyGridDefinitionRows:
-            return valueForGridTrackList(style->gridDefinitionRows(), style->orderedNamedGridRowLines(), style.get(), m_node->document()->renderView());
+            return valueForGridTrackList(style->gridDefinitionRows(), style->orderedNamedGridRowLines(), style.get(), m_node->document().renderView());
 
         case CSSPropertyGridColumnStart:
             return valueForGridPosition(style->gridColumnStart());
@@ -2043,7 +2093,7 @@
         case CSSPropertyImageRendering:
             return CSSPrimitiveValue::create(style->imageRendering());
         case CSSPropertyLeft:
-            return valueForPositionOffset(style.get(), CSSPropertyLeft, renderer, m_node->document()->renderView());
+            return valueForPositionOffset(style.get(), CSSPropertyLeft, renderer, m_node->document().renderView());
         case CSSPropertyLetterSpacing:
             if (!style->letterSpacing())
                 return cssValuePool().createIdentifierValue(CSSValueNormal);
@@ -2053,7 +2103,7 @@
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             return cssValuePool().createValue(style->lineClamp().value(), style->lineClamp().isPercentage() ? CSSPrimitiveValue::CSS_PERCENTAGE : CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyLineHeight:
-            return valueForLineHeight(style.get(), m_node->document()->renderView());
+            return valueForLineHeight(style.get(), m_node->document().renderView());
         case CSSPropertyListStyleImage:
             if (style->listStyleImage())
                 return style->listStyleImage()->cssValue();
@@ -2077,13 +2127,14 @@
             if (marginRight.isFixed() || !renderer || !renderer->isBox())
                 return zoomAdjustedPixelValueForLength(marginRight, style.get());
             float value;
-            if (marginRight.isPercent() || marginRight.isViewportPercentage())
+            if (marginRight.isPercent() || marginRight.isViewportPercentage()) {
                 // RenderBox gives a marginRight() that is the distance between the right-edge of the child box
                 // and the right-edge of the containing box, when display == BLOCK. Let's calculate the absolute
                 // value of the specified margin-right % instead of relying on RenderBox's marginRight() value.
-                value = minimumValueForLength(marginRight, toRenderBox(renderer)->containingBlockLogicalWidthForContent(), m_node->document()->renderView());
-            else
+                value = minimumValueForLength(marginRight, toRenderBox(renderer)->containingBlockLogicalWidthForContent(), m_node->document().renderView());
+            } else {
                 value = toRenderBox(renderer)->marginRight();
+            }
             return zoomAdjustedPixelValue(value, style.get());
         }
         case CSSPropertyMarginBottom: {
@@ -2139,7 +2190,7 @@
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
             return cssValuePool().createValue(style->orphans(), CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyOutlineColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyOutlineColor);
+            return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(style.get(), style->outlineColor());
         case CSSPropertyOutlineOffset:
             return zoomAdjustedPixelValue(style->outlineOffset(), style.get());
         case CSSPropertyOutlineStyle:
@@ -2194,7 +2245,7 @@
         case CSSPropertyPosition:
             return cssValuePool().createValue(style->position());
         case CSSPropertyRight:
-            return valueForPositionOffset(style.get(), CSSPropertyRight, renderer, m_node->document()->renderView());
+            return valueForPositionOffset(style.get(), CSSPropertyRight, renderer, m_node->document().renderView());
         case CSSPropertyWebkitRubyPosition:
             return cssValuePool().createValue(style->rubyPosition());
         case CSSPropertyTableLayout:
@@ -2218,9 +2269,9 @@
         case CSSPropertyWebkitTextDecorationsInEffect:
             return renderTextDecorationFlagsToCSSValue(style->textDecorationsInEffect());
         case CSSPropertyWebkitTextFillColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyWebkitTextFillColor);
+            return currentColorOrValidColor(style.get(), style->textFillColor());
         case CSSPropertyWebkitTextEmphasisColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyWebkitTextEmphasisColor);
+            return currentColorOrValidColor(style.get(), style->textEmphasisColor());
         case CSSPropertyWebkitTextEmphasisPosition:
             return cssValuePool().createValue(style->textEmphasisPosition());
         case CSSPropertyWebkitTextEmphasisStyle:
@@ -2254,7 +2305,7 @@
             return textIndent.release();
         }
         case CSSPropertyTextShadow:
-            return valueForShadow(renderer, style->textShadow(), propertyID, style.get());
+            return valueForShadow(style->textShadow(), propertyID, style.get());
         case CSSPropertyTextRendering:
             return cssValuePool().createValue(style->fontDescription().textRenderingMode());
         case CSSPropertyTextOverflow:
@@ -2264,13 +2315,13 @@
         case CSSPropertyWebkitTextSecurity:
             return cssValuePool().createValue(style->textSecurity());
         case CSSPropertyWebkitTextStrokeColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyWebkitTextStrokeColor);
+            return currentColorOrValidColor(style.get(), style->textStrokeColor());
         case CSSPropertyWebkitTextStrokeWidth:
             return zoomAdjustedPixelValue(style->textStrokeWidth(), style.get());
         case CSSPropertyTextTransform:
             return cssValuePool().createValue(style->textTransform());
         case CSSPropertyTop:
-            return valueForPositionOffset(style.get(), CSSPropertyTop, renderer, m_node->document()->renderView());
+            return valueForPositionOffset(style.get(), CSSPropertyTop, renderer, m_node->document().renderView());
         case CSSPropertyTouchAction:
             return cssValuePool().createValue(style->touchAction());
         case CSSPropertyUnicodeBidi:
@@ -2361,13 +2412,11 @@
         case CSSPropertyWebkitAppRegion:
             return cssValuePool().createIdentifierValue(style->getDraggableRegionMode() == DraggableRegionDrag ? CSSValueDrag : CSSValueNoDrag);
         case CSSPropertyAnimationDelay:
-            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
-                break;
+            ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationDelay:
             return valueForAnimationDelay(style->animations());
         case CSSPropertyAnimationDirection:
-            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
-                break;
+            ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationDirection: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
@@ -2379,13 +2428,11 @@
             return list.release();
         }
         case CSSPropertyAnimationDuration:
-            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
-                break;
+            ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationDuration:
             return valueForAnimationDuration(style->animations());
         case CSSPropertyAnimationFillMode:
-            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
-                break;
+            ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationFillMode: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
@@ -2397,8 +2444,7 @@
             return list.release();
         }
         case CSSPropertyAnimationIterationCount:
-            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
-                break;
+            ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationIterationCount: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
@@ -2415,8 +2461,7 @@
             return list.release();
         }
         case CSSPropertyAnimationName:
-            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
-                break;
+            ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationName: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
@@ -2428,8 +2473,7 @@
             return list.release();
         }
         case CSSPropertyAnimationPlayState:
-            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
-                break;
+            ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationPlayState: {
             RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
             const CSSAnimationDataList* t = style->animations();
@@ -2446,8 +2490,7 @@
             return list.release();
         }
         case CSSPropertyAnimationTimingFunction:
-            if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
-                break;
+            ASSERT(RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
         case CSSPropertyWebkitAnimationTimingFunction:
             return valueForAnimationTimingFunction(style->animations());
         case CSSPropertyAnimation:
@@ -2460,7 +2503,7 @@
                     const CSSAnimationData* animation = animations->animation(i);
                     list->append(cssValuePool().createValue(animation->name(), CSSPrimitiveValue::CSS_STRING));
                     list->append(cssValuePool().createValue(animation->duration(), CSSPrimitiveValue::CSS_S));
-                    list->append(createTimingFunctionValue(animation->timingFunction().get()));
+                    list->append(createTimingFunctionValue(animation->timingFunction()));
                     list->append(cssValuePool().createValue(animation->delay(), CSSPrimitiveValue::CSS_S));
                     if (animation->iterationCount() == CSSAnimationData::IterationCountInfinite)
                         list->append(cssValuePool().createIdentifierValue(CSSValueInfinite));
@@ -2542,7 +2585,7 @@
                 if (renderer->isBox())
                     box = toRenderBox(renderer)->borderBoxRect();
 
-                RenderView* renderView = m_node->document()->renderView();
+                RenderView* renderView = m_node->document().renderView();
                 list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginX(), box.width(), renderView), style.get()));
                 list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginY(), box.height(), renderView), style.get()));
             }
@@ -2556,19 +2599,19 @@
         case CSSPropertyWebkitRtlOrdering:
             return cssValuePool().createIdentifierValue(style->rtlOrdering() ? CSSValueVisual : CSSValueLogical);
         case CSSPropertyWebkitTapHighlightColor:
-            return currentColorOrValidColor(renderer, style.get(), CSSPropertyWebkitTapHighlightColor);
+            return currentColorOrValidColor(style.get(), style->tapHighlightColor());
         case CSSPropertyWebkitUserDrag:
             return cssValuePool().createValue(style->userDrag());
         case CSSPropertyWebkitUserSelect:
             return cssValuePool().createValue(style->userSelect());
         case CSSPropertyBorderBottomLeftRadius:
-            return valueForBorderRadiusCorner(style->borderBottomLeftRadius(), style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusCorner(style->borderBottomLeftRadius(), style.get(), renderer, m_node->document().renderView());
         case CSSPropertyBorderBottomRightRadius:
-            return valueForBorderRadiusCorner(style->borderBottomRightRadius(), style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusCorner(style->borderBottomRightRadius(), style.get(), renderer, m_node->document().renderView());
         case CSSPropertyBorderTopLeftRadius:
-            return valueForBorderRadiusCorner(style->borderTopLeftRadius(), style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusCorner(style->borderTopLeftRadius(), style.get(), renderer, m_node->document().renderView());
         case CSSPropertyBorderTopRightRadius:
-            return valueForBorderRadiusCorner(style->borderTopRightRadius(), style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusCorner(style->borderTopRightRadius(), style.get(), renderer, m_node->document().renderView());
         case CSSPropertyClip: {
             if (!style->hasClip())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
@@ -2590,7 +2633,7 @@
                 if (renderer->isBox())
                     box = toRenderBox(renderer)->borderBoxRect();
 
-                RenderView* renderView = m_node->document()->renderView();
+                RenderView* renderView = m_node->document().renderView();
                 list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginX(), box.width(), renderView), style.get()));
                 list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginY(), box.height(), renderView), style.get()));
                 if (style->transformOriginZ() != 0)
@@ -2627,7 +2670,7 @@
                     const CSSAnimationData* animation = animList->animation(i);
                     list->append(createTransitionPropertyValue(animation));
                     list->append(cssValuePool().createValue(animation->duration(), CSSPrimitiveValue::CSS_S));
-                    list->append(createTimingFunctionValue(animation->timingFunction().get()));
+                    list->append(createTimingFunctionValue(animation->timingFunction()));
                     list->append(cssValuePool().createValue(animation->delay(), CSSPrimitiveValue::CSS_S));
                     transitionsList->append(list);
                 }
@@ -2753,7 +2796,7 @@
         case CSSPropertyBorderImage:
             return valueForNinePieceImage(style->borderImage(), style.get());
         case CSSPropertyBorderRadius:
-            return valueForBorderRadiusShorthand(style.get(), m_node->document()->renderView());
+            return valueForBorderRadiusShorthand(style.get(), renderer, m_node->document().renderView());
         case CSSPropertyBorderRight:
             return valuesForShorthandProperty(borderRightShorthand());
         case CSSPropertyBorderStyle:
@@ -2950,7 +2993,7 @@
 bool CSSComputedStyleDeclaration::cssPropertyMatches(CSSPropertyID propertyID, const CSSValue* propertyValue) const
 {
     if (propertyID == CSSPropertyFontSize && propertyValue->isPrimitiveValue() && m_node) {
-        m_node->document()->updateLayoutIgnorePendingStylesheets();
+        m_node->document().updateLayoutIgnorePendingStylesheets();
         RenderStyle* style = m_node->computedStyle(m_pseudoElementSpecifier);
         if (style && style->fontDescription().keywordSize()) {
             CSSValueID sizeValue = cssIdentifierForFontSizeKeyword(style->fontDescription().keywordSize());
@@ -3045,9 +3088,7 @@
 String CSSComputedStyleDeclaration::getPropertyValue(const String& propertyName)
 {
     CSSPropertyID propertyID = cssPropertyID(propertyName);
-    // FIXME: This should check RuntimeEnabledFeature::isCSSPropertyEnabled instead of just
-    // isInternalProperty. However we need to test that which requires crbug.com/234853 to be fixed.
-    if (!propertyID || isInternalProperty(propertyID))
+    if (!propertyID || !RuntimeCSSEnabled::isCSSPropertyEnabled(propertyID))
         return String();
     return getPropertyValue(propertyID);
 }
diff --git a/Source/core/css/CSSComputedStyleDeclaration.h b/Source/core/css/CSSComputedStyleDeclaration.h
index a42ca6e..6116b50 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/Source/core/css/CSSComputedStyleDeclaration.h
@@ -22,7 +22,6 @@
 #define CSSComputedStyleDeclaration_h
 
 #include "core/css/CSSStyleDeclaration.h"
-#include "core/css/StyleColor.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "wtf/HashMap.h"
 #include "wtf/RefPtr.h"
@@ -110,9 +109,8 @@
 
     virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const OVERRIDE;
 
-    PassRefPtr<CSSValue> valueForShadow(const RenderObject*, const ShadowData*, CSSPropertyID, const RenderStyle*) const;
-    PassRefPtr<CSSPrimitiveValue> currentColorOrValidColor(RenderStyle*, const StyleColor&) const;
-    PassRefPtr<CSSPrimitiveValue> currentColorOrValidColor(const RenderObject*, const RenderStyle*, int colorProperty) const;
+    PassRefPtr<CSSValue> valueForShadow(const ShadowData*, CSSPropertyID, const RenderStyle*) const;
+    PassRefPtr<CSSPrimitiveValue> currentColorOrValidColor(RenderStyle*, const Color&) const;
     PassRefPtr<SVGPaint> adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint>, RenderStyle*) const;
 
     PassRefPtr<CSSValue> valueForFilter(const RenderObject*, const RenderStyle*) const;
diff --git a/Source/core/css/CSSCrossfadeValue.cpp b/Source/core/css/CSSCrossfadeValue.cpp
index d409f79..b45f6cc 100644
--- a/Source/core/css/CSSCrossfadeValue.cpp
+++ b/Source/core/css/CSSCrossfadeValue.cpp
@@ -111,7 +111,7 @@
     float percentage = m_percentageValue->getFloatValue();
     float inversePercentage = 1 - percentage;
 
-    ResourceFetcher* fetcher = renderer->document()->fetcher();
+    ResourceFetcher* fetcher = renderer->document().fetcher();
     ImageResource* cachedFromImage = cachedImageForCSSValue(m_fromValue.get(), fetcher);
     ImageResource* cachedToImage = cachedImageForCSSValue(m_toValue.get(), fetcher);
 
@@ -170,7 +170,7 @@
     if (size.isEmpty())
         return 0;
 
-    ResourceFetcher* fetcher = renderer->document()->fetcher();
+    ResourceFetcher* fetcher = renderer->document().fetcher();
     ImageResource* cachedFromImage = cachedImageForCSSValue(m_fromValue.get(), fetcher);
     ImageResource* cachedToImage = cachedImageForCSSValue(m_toValue.get(), fetcher);
 
diff --git a/Source/core/css/CSSCursorImageValue.cpp b/Source/core/css/CSSCursorImageValue.cpp
index dd68e0b..24caef7 100644
--- a/Source/core/css/CSSCursorImageValue.cpp
+++ b/Source/core/css/CSSCursorImageValue.cpp
@@ -39,7 +39,7 @@
 
 namespace WebCore {
 
-static inline SVGCursorElement* resourceReferencedByCursorElement(const String& url, Document* document)
+static inline SVGCursorElement* resourceReferencedByCursorElement(const String& url, Document& document)
 {
     Element* element = SVGURIReference::targetElementFromIRIString(url, document);
     if (element && element->hasTagName(SVGNames::cursorTag))
@@ -106,7 +106,7 @@
         float y = roundf(cursorElement->yCurrentValue().value(lengthContext));
         m_hotSpot.setY(static_cast<int>(y));
 
-        if (cachedImageURL() != element->document()->completeURL(cursorElement->hrefCurrentValue()))
+        if (cachedImageURL() != element->document().completeURL(cursorElement->hrefCurrentValue()))
             clearImageResource();
 
         SVGElement* svgElement = toSVGElement(element);
@@ -133,7 +133,7 @@
         if (isSVGCursor() && loader && loader->document()) {
             RefPtr<CSSImageValue> imageValue = toCSSImageValue(m_imageValue.get());
             // FIXME: This will fail if the <cursor> element is in a shadow DOM (bug 59827)
-            if (SVGCursorElement* cursorElement = resourceReferencedByCursorElement(imageValue->url(), loader->document())) {
+            if (SVGCursorElement* cursorElement = resourceReferencedByCursorElement(imageValue->url(), *loader->document())) {
                 RefPtr<CSSImageValue> svgImageValue = CSSImageValue::create(cursorElement->hrefCurrentValue());
                 StyleFetchedImage* cachedImage = svgImageValue->cachedImage(loader);
                 m_image = cachedImage;
diff --git a/Source/core/css/CSSDefaultStyleSheets.cpp b/Source/core/css/CSSDefaultStyleSheets.cpp
index 7061f9b..436ab64 100644
--- a/Source/core/css/CSSDefaultStyleSheets.cpp
+++ b/Source/core/css/CSSDefaultStyleSheets.cpp
@@ -47,17 +47,17 @@
 RuleSet* CSSDefaultStyleSheets::defaultQuirksStyle;
 RuleSet* CSSDefaultStyleSheets::defaultPrintStyle;
 RuleSet* CSSDefaultStyleSheets::defaultViewSourceStyle;
+RuleSet* CSSDefaultStyleSheets::defaultXHTMLMobileProfileStyle;
 
 StyleSheetContents* CSSDefaultStyleSheets::simpleDefaultStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::defaultStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::quirksStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::svgStyleSheet;
-StyleSheetContents* CSSDefaultStyleSheets::mathMLStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::mediaControlsStyleSheet;
 StyleSheetContents* CSSDefaultStyleSheets::fullscreenStyleSheet;
 
 // FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
-static const char* simpleUserAgentStyleSheet = "html,body,div{display:block}head{display:none}body{margin:8px}div:focus,span:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}";
+static const char* simpleUserAgentStyleSheet = "html,body,div{display:block}head{display:none}body{margin:8px}div:focus,span:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}body:-webkit-seamless-document{margin:0}body:-webkit-full-page-media{background-color:black}";
 
 static inline bool elementCanUseSimpleDefaultStyle(Element* e)
 {
@@ -152,6 +152,14 @@
     return defaultViewSourceStyle;
 }
 
+RuleSet* CSSDefaultStyleSheets::xhtmlMobileProfileStyle()
+{
+    if (!defaultXHTMLMobileProfileStyle) {
+        defaultXHTMLMobileProfileStyle = RuleSet::create().leakPtr();
+        defaultXHTMLMobileProfileStyle->addRulesFromSheet(parseUASheet(xhtmlmpUserAgentStyleSheet, sizeof(xhtmlmpUserAgentStyleSheet)), screenEval());
+    }
+    return defaultXHTMLMobileProfileStyle;
+}
 
 void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(Element* element, bool& changedDefaultStyle)
 {
@@ -160,14 +168,15 @@
         changedDefaultStyle = true;
     }
 
+    // FIXME: We should assert that the sheet only styles SVG elements.
     if (element->isSVGElement() && !svgStyleSheet) {
-        // SVG rules.
         svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
         defaultStyle->addRulesFromSheet(svgStyleSheet, screenEval());
         defaultPrintStyle->addRulesFromSheet(svgStyleSheet, printEval());
         changedDefaultStyle = true;
     }
 
+    // FIXME: We should assert that this sheet only contains rules for <video> and <audio>.
     if (!mediaControlsStyleSheet && (isHTMLVideoElement(element) || element->hasTagName(audioTag))) {
         String mediaRules = String(mediaControlsUserAgentStyleSheet, sizeof(mediaControlsUserAgentStyleSheet)) + RenderTheme::theme().extraMediaControlsStyleSheet();
         mediaControlsStyleSheet = parseUASheet(mediaRules);
@@ -176,7 +185,9 @@
         changedDefaultStyle = true;
     }
 
-    if (!fullscreenStyleSheet && FullscreenElementStack::isFullScreen(element->document())) {
+    // FIXME: This only works because we Force recalc the entire document so the new sheet
+    // is loaded for <html> and the correct styles apply to everyone.
+    if (!fullscreenStyleSheet && FullscreenElementStack::isFullScreen(&element->document())) {
         String fullscreenRules = String(fullscreenUserAgentStyleSheet, sizeof(fullscreenUserAgentStyleSheet)) + RenderTheme::theme().extraFullScreenStyleSheet();
         fullscreenStyleSheet = parseUASheet(fullscreenRules);
         defaultStyle->addRulesFromSheet(fullscreenStyleSheet, screenEval());
@@ -185,7 +196,7 @@
     }
 
     ASSERT(defaultStyle->features().idsInRules.isEmpty());
-    ASSERT(mathMLStyleSheet || defaultStyle->features().siblingRules.isEmpty());
+    ASSERT(defaultStyle->features().siblingRules.isEmpty());
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSDefaultStyleSheets.h b/Source/core/css/CSSDefaultStyleSheets.h
index e3469f3..5cf0035 100644
--- a/Source/core/css/CSSDefaultStyleSheets.h
+++ b/Source/core/css/CSSDefaultStyleSheets.h
@@ -35,12 +35,12 @@
     static RuleSet* defaultQuirksStyle;
     static RuleSet* defaultPrintStyle;
     static RuleSet* defaultViewSourceStyle;
+    static RuleSet* defaultXHTMLMobileProfileStyle;
 
     static StyleSheetContents* simpleDefaultStyleSheet;
     static StyleSheetContents* defaultStyleSheet;
     static StyleSheetContents* quirksStyleSheet;
     static StyleSheetContents* svgStyleSheet;
-    static StyleSheetContents* mathMLStyleSheet;
     static StyleSheetContents* mediaControlsStyleSheet;
     static StyleSheetContents* fullscreenStyleSheet;
 
@@ -49,6 +49,7 @@
     static void loadSimpleDefaultStyle();
     static void initDefaultStyle(Element*);
     static RuleSet* viewSourceStyle();
+    static RuleSet* xhtmlMobileProfileStyle();
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/CSSFontFaceLoadEvent.idl b/Source/core/css/CSSFontFaceLoadEvent.idl
index d89e765..7a1b32b 100644
--- a/Source/core/css/CSSFontFaceLoadEvent.idl
+++ b/Source/core/css/CSSFontFaceLoadEvent.idl
@@ -30,7 +30,7 @@
 
 [
     NoInterfaceObject,
-    EnabledAtRuntime=fontLoadEvents,
+    EnabledAtRuntime=FontLoadEvents,
     ConstructorTemplate=Event
 ] interface CSSFontFaceLoadEvent : Event {
     [InitializedByEventConstructor] readonly attribute CSSFontFaceRule fontface;
diff --git a/Source/core/css/CSSFontFaceSource.cpp b/Source/core/css/CSSFontFaceSource.cpp
index 106a66b..264c496 100644
--- a/Source/core/css/CSSFontFaceSource.cpp
+++ b/Source/core/css/CSSFontFaceSource.cpp
@@ -250,37 +250,14 @@
 
 void CSSFontFaceSource::willUseFontData()
 {
-    if (!isLoaded())
-        m_histograms.willUseFontData();
-}
-
-CSSFontFaceSource::FontLoadHistograms::~FontLoadHistograms()
-{
-    if (m_styledTime > 0)
-        HistogramSupport::histogramEnumeration("WebFont.UsageType", StyledButNotUsed, UsageTypeMax);
-}
-
-void CSSFontFaceSource::FontLoadHistograms::willUseFontData()
-{
-    if (!m_styledTime)
-        m_styledTime = currentTimeMS();
+    if (m_font)
+        m_font->willUseFontData();
 }
 
 void CSSFontFaceSource::FontLoadHistograms::loadStarted()
 {
     if (!m_loadStartTime)
         m_loadStartTime = currentTimeMS();
-
-    if (m_styledTime < 0)
-        return;
-    if (!m_styledTime) {
-        HistogramSupport::histogramEnumeration("WebFont.UsageType", NotStyledButUsed, UsageTypeMax);
-    } else {
-        int duration = static_cast<int>(currentTimeMS() - m_styledTime);
-        HistogramSupport::histogramCustomCounts("WebFont.StyleRecalcToDownloadLatency", duration, 0, 10000, 50);
-        HistogramSupport::histogramEnumeration("WebFont.UsageType", StyledAndUsed, UsageTypeMax);
-    }
-    m_styledTime = -1;
 }
 
 void CSSFontFaceSource::FontLoadHistograms::recordLocalFont(bool loadSuccess)
diff --git a/Source/core/css/CSSFontFaceSource.h b/Source/core/css/CSSFontFaceSource.h
index ebb733b..6414ae6 100644
--- a/Source/core/css/CSSFontFaceSource.h
+++ b/Source/core/css/CSSFontFaceSource.h
@@ -80,21 +80,13 @@
 private:
     class FontLoadHistograms {
     public:
-        enum UsageType {
-            StyledAndUsed,
-            StyledButNotUsed,
-            NotStyledButUsed,
-            UsageTypeMax
-        };
-        FontLoadHistograms() : m_styledTime(0), m_loadStartTime(0) { }
-        ~FontLoadHistograms();
+        FontLoadHistograms() : m_loadStartTime(0) { }
         void willUseFontData();
         void loadStarted();
         void recordLocalFont(bool loadSuccess);
         void recordRemoteFont(const FontResource*);
     private:
         const char* histogramName(const FontResource*);
-        double m_styledTime;
         double m_loadStartTime;
     };
 
diff --git a/Source/core/css/CSSGradientValue.cpp b/Source/core/css/CSSGradientValue.cpp
index 316513f..0c6e578 100644
--- a/Source/core/css/CSSGradientValue.cpp
+++ b/Source/core/css/CSSGradientValue.cpp
@@ -105,7 +105,7 @@
     { }
 };
 
-PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(const TextLinkColors& textLinkColors)
+PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(const TextLinkColors& textLinkColors, Color currentColor)
 {
     bool derived = false;
     for (unsigned i = 0; i < m_stops.size(); i++)
@@ -128,7 +128,7 @@
     }
 
     for (unsigned i = 0; i < result->m_stops.size(); i++)
-        result->m_stops[i].m_resolvedColor = textLinkColors.colorFromPrimitiveValue(result->m_stops[i].m_color.get());
+        result->m_stops[i].m_resolvedColor = textLinkColors.colorFromPrimitiveValue(result->m_stops[i].m_color.get(), currentColor);
 
     return result.release();
 }
@@ -149,7 +149,7 @@
             else
                 offset = stop.m_position->getFloatValue(CSSPrimitiveValue::CSS_NUMBER);
 
-            gradient->addColorStop(offset, renderer->resolveColor(stop.m_resolvedColor));
+            gradient->addColorStop(offset, stop.m_resolvedColor);
         }
 
         // The back end already sorted the stops.
@@ -174,7 +174,7 @@
     for (size_t i = 0; i < numStops; ++i) {
         const CSSGradientColorStop& stop = m_stops[i];
 
-        stops[i].color = renderer->resolveColor(stop.m_resolvedColor);
+        stops[i].color = stop.m_resolvedColor;
 
         if (stop.m_position) {
             if (stop.m_position->isPercentage())
@@ -642,7 +642,7 @@
 {
     ASSERT(!size.isEmpty());
 
-    RenderStyle* rootStyle = renderer->document()->documentElement()->renderStyle();
+    RenderStyle* rootStyle = renderer->document().documentElement()->renderStyle();
 
     FloatPoint firstPoint;
     FloatPoint secondPoint;
@@ -984,7 +984,7 @@
 {
     ASSERT(!size.isEmpty());
 
-    RenderStyle* rootStyle = renderer->document()->documentElement()->renderStyle();
+    RenderStyle* rootStyle = renderer->document().documentElement()->renderStyle();
 
     FloatPoint firstPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), renderer->style(), rootStyle, size);
     if (!m_firstX)
diff --git a/Source/core/css/CSSGradientValue.h b/Source/core/css/CSSGradientValue.h
index 2eed10b..75e5152 100644
--- a/Source/core/css/CSSGradientValue.h
+++ b/Source/core/css/CSSGradientValue.h
@@ -28,7 +28,6 @@
 
 #include "core/css/CSSImageGeneratorValue.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/css/StyleColor.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
 
@@ -52,7 +51,7 @@
     CSSGradientColorStop() : m_colorIsDerivedFromElement(false) { };
     RefPtr<CSSPrimitiveValue> m_position; // percentage or length
     RefPtr<CSSPrimitiveValue> m_color;
-    StyleColor m_resolvedColor;
+    Color m_resolvedColor;
     bool m_colorIsDerivedFromElement;
     bool operator==(const CSSGradientColorStop& other) const
     {
@@ -90,7 +89,7 @@
     bool knownToBeOpaque(const RenderObject*) const;
 
     void loadSubimages(ResourceFetcher*) { }
-    PassRefPtr<CSSGradientValue> gradientWithStylesResolved(const TextLinkColors&);
+    PassRefPtr<CSSGradientValue> gradientWithStylesResolved(const TextLinkColors&, Color currentColor);
 
 protected:
     CSSGradientValue(ClassType classType, CSSGradientRepeat repeat, CSSGradientType gradientType)
diff --git a/Source/core/css/CSSGrammar.y.in b/Source/core/css/CSSGrammar.y.in
index 024f514..d437fb6 100644
--- a/Source/core/css/CSSGrammar.y.in
+++ b/Source/core/css/CSSGrammar.y.in
@@ -141,6 +141,7 @@
 %token INTERNAL_SELECTOR_SYM
 %token INTERNAL_VALUE_SYM
 %token INTERNAL_KEYFRAME_RULE_SYM
+%token INTERNAL_KEYFRAME_KEY_LIST_SYM
 %token INTERNAL_SUPPORTS_CONDITION_SYM
 %token KEYFRAMES_SYM
 %token WEBKIT_KEYFRAMES_SYM
@@ -339,6 +340,7 @@
   | internal_value
   | internal_medialist
   | internal_keyframe_rule
+  | internal_keyframe_key_list
   | internal_supports_condition
   ;
 
@@ -354,6 +356,12 @@
     }
 ;
 
+internal_keyframe_key_list:
+    INTERNAL_KEYFRAME_KEY_LIST_SYM maybe_space key_list TOKEN_EOF {
+        parser->m_valueList = parser->sinkFloatingValueList($3);
+    }
+;
+
 internal_decls:
     INTERNAL_DECLS_SYM maybe_space_before_declaration declaration_list TOKEN_EOF {
         /* can be empty */
diff --git a/Source/core/css/CSSHostRule.idl b/Source/core/css/CSSHostRule.idl
index 237a051..d86b738 100644
--- a/Source/core/css/CSSHostRule.idl
+++ b/Source/core/css/CSSHostRule.idl
@@ -22,8 +22,7 @@
 interface CSSHostRule : CSSRule {
     readonly attribute CSSRuleList cssRules;
 
-    [RaisesException] unsigned long      insertRule([Default=Undefined] optional DOMString rule,
-                                  [Default=Undefined] optional unsigned long index);
-    [RaisesException] void               deleteRule([Default=Undefined] optional unsigned long index);
+    [RaisesException] unsigned long      insertRule(DOMString rule, unsigned long index);
+    [RaisesException] void               deleteRule(unsigned long index);
 };
 
diff --git a/Source/core/css/CSSKeyframeRule.cpp b/Source/core/css/CSSKeyframeRule.cpp
index 672b726..2b1a1fd 100644
--- a/Source/core/css/CSSKeyframeRule.cpp
+++ b/Source/core/css/CSSKeyframeRule.cpp
@@ -27,6 +27,7 @@
 #include "core/css/CSSKeyframeRule.h"
 
 #include "core/css/CSSKeyframesRule.h"
+#include "core/css/CSSParser.h"
 #include "core/css/PropertySetCSSStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
 #include "wtf/text/StringBuilder.h"
@@ -41,6 +42,55 @@
 {
 }
 
+String StyleKeyframe::keyText() const
+{
+    if (m_keyText.isNull()) {
+        // Keys are always set when these objects are created.
+        ASSERT(m_keys && !m_keys->isEmpty());
+        StringBuilder keyText;
+        for (unsigned i = 0; i < m_keys->size(); ++i) {
+            if (i)
+                keyText.append(',');
+            keyText.append(String::number(m_keys->at(i) * 100));
+            keyText.append('%');
+        }
+        m_keyText = keyText.toString();
+    }
+    ASSERT(!m_keyText.isNull());
+    return m_keyText;
+}
+
+void StyleKeyframe::setKeyText(const String& keyText)
+{
+    // FIXME: Should we trim whitespace?
+    // FIXME: Should we leave keyText unchanged when attempting to set to an
+    // invalid string?
+    ASSERT(!keyText.isNull());
+    m_keyText = keyText;
+    m_keys.clear();
+}
+
+const Vector<double>& StyleKeyframe::keys() const
+{
+    if (!m_keys) {
+        // Keys can only be cleared by setting the key text from JavaScript
+        // and this can never be null.
+        ASSERT(!m_keyText.isNull());
+        m_keys = CSSParser(CSSStrictMode).parseKeyframeKeyList(m_keyText);
+    }
+    // If an invalid key string was set, m_keys may be empty.
+    ASSERT(m_keys);
+    return *m_keys;
+}
+
+void StyleKeyframe::setKeys(PassOwnPtr<Vector<double> > keys)
+{
+    ASSERT(keys && !keys->isEmpty());
+    m_keys = keys;
+    m_keyText = String();
+    ASSERT(m_keyText.isNull());
+}
+
 MutableStylePropertySet* StyleKeyframe::mutableProperties()
 {
     if (!m_properties->isMutable())
@@ -53,35 +103,6 @@
     m_properties = properties;
 }
 
-/* static */
-void StyleKeyframe::parseKeyString(const String& s, Vector<double>& keys)
-{
-    keys.clear();
-    Vector<String> strings;
-    s.split(',', strings);
-
-    for (size_t i = 0; i < strings.size(); ++i) {
-        double key = -1;
-        String cur = strings[i].stripWhiteSpace();
-
-        // For now the syntax MUST be 'xxx%' or 'from' or 'to', where xxx is a legal floating point number
-        if (cur == "from")
-            key = 0;
-        else if (cur == "to")
-            key = 1;
-        else if (cur.endsWith('%')) {
-            double k = cur.substring(0, cur.length() - 1).toDouble();
-            if (k >= 0 && k <= 100)
-                key = k / 100;
-        }
-        if (key < 0) {
-            keys.clear();
-            return;
-        }
-        keys.append(key);
-    }
-}
-
 String StyleKeyframe::cssText() const
 {
     StringBuilder result;
@@ -95,6 +116,25 @@
     return result.toString();
 }
 
+PassOwnPtr<Vector<double> > StyleKeyframe::createKeyList(CSSParserValueList* keys)
+{
+    OwnPtr<Vector<double> > keyVector = adoptPtr(new Vector<double>(keys->size()));
+    for (unsigned i = 0; i < keys->size(); ++i) {
+        ASSERT(keys->valueAt(i)->unit == WebCore::CSSPrimitiveValue::CSS_NUMBER);
+        double key = keys->valueAt(i)->fValue;
+        if (key < 0 || key > 100) {
+            // As per http://www.w3.org/TR/css3-animations/#keyframes,
+            // "If a keyframe selector specifies negative percentage values
+            // or values higher than 100%, then the keyframe will be ignored."
+            keyVector->clear();
+            break;
+        }
+        keyVector->at(i) = key / 100;
+    }
+    return keyVector.release();
+}
+
+
 CSSKeyframeRule::CSSKeyframeRule(StyleKeyframe* keyframe, CSSKeyframesRule* parent)
     : CSSRule(0)
     , m_keyframe(keyframe)
diff --git a/Source/core/css/CSSKeyframeRule.h b/Source/core/css/CSSKeyframeRule.h
index d6f5ad5..44e2d75 100644
--- a/Source/core/css/CSSKeyframeRule.h
+++ b/Source/core/css/CSSKeyframeRule.h
@@ -30,11 +30,12 @@
 
 namespace WebCore {
 
+class CSSKeyframesRule;
+class CSSParserValueList;
 class CSSStyleDeclaration;
 class MutableStylePropertySet;
 class StylePropertySet;
 class StyleRuleCSSStyleDeclaration;
-class CSSKeyframesRule;
 
 class StyleKeyframe FINAL : public RefCounted<StyleKeyframe> {
     WTF_MAKE_FAST_ALLOCATED;
@@ -45,13 +46,14 @@
     }
     ~StyleKeyframe();
 
-    String keyText() const { return m_key; }
-    // FIXME: Should we trim whitespace?
-    // FIXME: Should we leave keyText unchanged when attempting to set to an
-    // invalid string?
-    void setKeyText(const String& s) { m_key = s; }
+    // Exposed to JavaScript.
+    String keyText() const;
+    void setKeyText(const String&);
 
-    void getKeys(Vector<double>& keys) const { parseKeyString(m_key, keys); }
+    // Used by StyleResolver.
+    const Vector<double>& keys() const;
+    // Used by CSSParser when constructing a new StyleKeyframe.
+    void setKeys(PassOwnPtr<Vector<double> >);
 
     const StylePropertySet* properties() const { return m_properties.get(); }
     MutableStylePropertySet* mutableProperties();
@@ -59,15 +61,15 @@
 
     String cssText() const;
 
+    static PassOwnPtr<Vector<double> > createKeyList(CSSParserValueList*);
+
 private:
     StyleKeyframe();
 
-    static void parseKeyString(const String&, Vector<double>& keys);
-
     RefPtr<StylePropertySet> m_properties;
-    // FIXME: This should be a parsed vector of floats.
-    // comma separated list of keys
-    String m_key;
+    // These are both calculated lazily. Either one can be set, which invalidates the other.
+    mutable String m_keyText;
+    mutable OwnPtr<Vector<double> > m_keys;
 };
 
 class CSSKeyframeRule FINAL : public CSSRule {
diff --git a/Source/core/css/CSSMediaRule.idl b/Source/core/css/CSSMediaRule.idl
index 71185a7..0f1d76d 100644
--- a/Source/core/css/CSSMediaRule.idl
+++ b/Source/core/css/CSSMediaRule.idl
@@ -23,8 +23,7 @@
     readonly attribute MediaList media;
     readonly attribute CSSRuleList cssRules;
 
-     [RaisesException] unsigned long      insertRule([Default=Undefined] optional DOMString rule,
-                                                 [Default=Undefined] optional unsigned long index);
-    [RaisesException] void               deleteRule([Default=Undefined] optional unsigned long index);
+    [RaisesException] unsigned long insertRule(DOMString rule, unsigned long index);
+    [RaisesException] void deleteRule(unsigned long index);
 };
 
diff --git a/Source/core/css/CSSParser-in.cpp b/Source/core/css/CSSParser-in.cpp
index ff6a758..873c347 100644
--- a/Source/core/css/CSSParser-in.cpp
+++ b/Source/core/css/CSSParser-in.cpp
@@ -212,15 +212,15 @@
 {
 }
 
-CSSParserContext::CSSParserContext(Document* document, const KURL& baseURL, const String& charset)
-    : baseURL(baseURL.isNull() ? document->baseURL() : baseURL)
+CSSParserContext::CSSParserContext(const Document& document, const KURL& baseURL, const String& charset)
+    : baseURL(baseURL.isNull() ? document.baseURL() : baseURL)
     , charset(charset)
-    , mode(document->inQuirksMode() ? CSSQuirksMode : CSSStrictMode)
-    , isHTMLDocument(document->isHTMLDocument())
-    , isCSSCustomFilterEnabled(document->settings() ? document->settings()->isCSSCustomFilterEnabled() : false)
-    , isCSSStickyPositionEnabled(document->cssStickyPositionEnabled())
-    , needsSiteSpecificQuirks(document->settings() ? document->settings()->needsSiteSpecificQuirks() : false)
-    , useLegacyBackgroundSizeShorthandBehavior(document->settings() ? document->settings()->useLegacyBackgroundSizeShorthandBehavior() : false)
+    , mode(document.inQuirksMode() ? CSSQuirksMode : CSSStrictMode)
+    , isHTMLDocument(document.isHTMLDocument())
+    , isCSSCustomFilterEnabled(document.settings() ? document.settings()->isCSSCustomFilterEnabled() : false)
+    , isCSSStickyPositionEnabled(document.cssStickyPositionEnabled())
+    , needsSiteSpecificQuirks(document.settings() ? document.settings()->needsSiteSpecificQuirks() : false)
+    , useLegacyBackgroundSizeShorthandBehavior(document.settings() ? document.settings()->useLegacyBackgroundSizeShorthandBehavior() : false)
 {
 }
 
@@ -398,6 +398,14 @@
     return m_keyframe.release();
 }
 
+PassOwnPtr<Vector<double> > CSSParser::parseKeyframeKeyList(const String& string)
+{
+    setupParser("@-internal-keyframe-key-list ", string, "");
+    cssyyparse(this);
+    ASSERT(m_valueList);
+    return StyleKeyframe::createKeyList(m_valueList.get());
+}
+
 bool CSSParser::parseSupportsCondition(const String& string)
 {
     m_supportsCondition = false;
@@ -1148,10 +1156,15 @@
     RefPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
     if (!parseValue(dummyStyle.get(), CSSPropertyFontFamily, string, false, CSSQuirksMode, 0))
         return 0;
-    return static_pointer_cast<CSSValueList>(dummyStyle->getPropertyCSSValue(CSSPropertyFontFamily));
+
+    RefPtr<CSSValue> fontFamily = dummyStyle->getPropertyCSSValue(CSSPropertyFontFamily);
+    if (!fontFamily->isValueList())
+        return 0;
+
+    return toCSSValueList(dummyStyle->getPropertyCSSValue(CSSPropertyFontFamily).get());
 }
 
-bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, Document* document)
+bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID propertyID, const String& string, bool important, const Document& document)
 {
     ASSERT(!string.isEmpty());
 
@@ -1164,7 +1177,7 @@
     if (parseKeywordValue(declaration, propertyID, string, important, context))
         return true;
 
-    CSSParser parser(context, UseCounter::getFrom(document));
+    CSSParser parser(context, UseCounter::getFrom(&document));
     return parser.parseValue(declaration, propertyID, string, important, static_cast<StyleSheetContents*>(0));
 }
 
@@ -1285,10 +1298,10 @@
 
 PassRefPtr<ImmutableStylePropertySet> CSSParser::parseInlineStyleDeclaration(const String& string, Element* element)
 {
-    Document* document = element->document();
-    CSSParserContext context = document->elementSheet()->contents()->parserContext();
-    context.mode = strictToCSSParserMode(element->isHTMLElement() && !document->inQuirksMode());
-    return CSSParser(context, UseCounter::getFrom(document)).parseDeclaration(string, document->elementSheet()->contents());
+    Document& document = element->document();
+    CSSParserContext context = document.elementSheet()->contents()->parserContext();
+    context.mode = strictToCSSParserMode(element->isHTMLElement() && !document.inQuirksMode());
+    return CSSParser(context, UseCounter::getFrom(&document)).parseDeclaration(string, document.elementSheet()->contents());
 }
 
 PassRefPtr<ImmutableStylePropertySet> CSSParser::parseDeclaration(const String& string, StyleSheetContents* contextStyleSheet)
@@ -1348,7 +1361,7 @@
     setupParser("@-internal-medialist ", string, "");
     cssyyparse(this);
 
-    ASSERT(m_mediaList.get());
+    ASSERT(m_mediaList);
     return m_mediaList.release();
 }
 
@@ -1679,6 +1692,14 @@
     if (!value)
         return false;
 
+    if (inViewport()) {
+        // Allow @viewport rules from UA stylesheets even if the feature is disabled.
+        if (!RuntimeEnabledFeatures::cssViewportEnabled() && m_context.mode != UASheetMode)
+            return false;
+
+        return parseViewportProperty(propId, important);
+    }
+
     // Note: m_parsedCalculation is used to pass the calc value to validUnit and then cleared at the end of this function.
     // FIXME: This is to avoid having to pass parsedCalc to all validUnit callers.
     ASSERT(!m_parsedCalculation);
@@ -1716,13 +1737,6 @@
         return true;
     }
 
-    if (inViewport()) {
-        if (!RuntimeEnabledFeatures::cssViewportEnabled())
-            return false;
-
-        return parseViewportProperty(propId, important);
-    }
-
     bool validPrimitive = false;
     RefPtr<CSSValue> parsedValue;
 
@@ -1932,6 +1946,7 @@
     case CSSPropertyWebkitBackgroundComposite:
     case CSSPropertyBackgroundImage:
     case CSSPropertyBackgroundOrigin:
+    case CSSPropertyMaskSourceType:
     case CSSPropertyWebkitBackgroundOrigin:
     case CSSPropertyBackgroundPosition:
     case CSSPropertyBackgroundPositionX:
@@ -4230,6 +4245,17 @@
                         m_valueList->next();
                     break;
                 }
+                case CSSPropertyMaskSourceType: {
+                    if (RuntimeEnabledFeatures::cssMaskSourceTypeEnabled()) {
+                        if (val->id == CSSValueAuto || val->id == CSSValueAlpha || val->id == CSSValueLuminance) {
+                            currValue = cssValuePool().createIdentifierValue(val->id);
+                            m_valueList->next();
+                        } else {
+                            currValue = 0;
+                        }
+                    }
+                    break;
+                }
                 default:
                     break;
             }
@@ -6127,10 +6153,10 @@
         return true;
 
     // Try named colors.
-    StyleColor color;
-    color.setNamedColor(name);
-    if (color.isValid()) {
-        rgb = color.rgb();
+    Color tc;
+    tc.setNamedColor(name);
+    if (tc.isValid()) {
+        rgb = tc.rgb();
         return true;
     }
     return false;
@@ -10387,6 +10413,9 @@
             if (LIKELY(!hasEscape))
                 m_token = INTERNAL_KEYFRAME_RULE_SYM;
         }
+        CASE("-internal-keyframe-key-list") {
+            m_token = INTERNAL_KEYFRAME_KEY_LIST_SYM;
+        }
         CASE("-internal-supports-condition") {
             m_parsingMode = SupportsMode;
             m_token = INTERNAL_SUPPORTS_CONDITION_SYM;
@@ -11531,26 +11560,12 @@
 
 StyleKeyframe* CSSParser::createKeyframe(CSSParserValueList* keys)
 {
-    // Create a key string from the passed keys
-    StringBuilder keyString;
-    for (unsigned i = 0; i < keys->size(); ++i) {
-        ASSERT(keys->valueAt(i)->unit == CSSPrimitiveValue::CSS_NUMBER);
-        double key = keys->valueAt(i)->fValue;
-        if (key < 0 || key > 100) {
-            // As per http://www.w3.org/TR/css3-animations/#keyframes,
-            // "If a keyframe selector specifies negative percentage values
-            // or values higher than 100%, then the keyframe will be ignored."
-            clearProperties();
-            return 0;
-        }
-        if (i != 0)
-            keyString.append(',');
-        keyString.append(String::number(key));
-        keyString.append('%');
-    }
+    OwnPtr<Vector<double> > keyVector = StyleKeyframe::createKeyList(keys);
+    if (keyVector->isEmpty())
+        return 0;
 
     RefPtr<StyleKeyframe> keyframe = StyleKeyframe::create();
-    keyframe->setKeyText(keyString.toString());
+    keyframe->setKeys(keyVector.release());
     keyframe->setProperties(createStylePropertySet());
 
     clearProperties();
@@ -11634,8 +11649,11 @@
 
 StyleRuleBase* CSSParser::createViewportRule()
 {
-    if (!RuntimeEnabledFeatures::cssViewportEnabled())
+    // Allow @viewport rules from UA stylesheets even if the feature is disabled.
+    if (!RuntimeEnabledFeatures::cssViewportEnabled() && m_context.mode != UASheetMode) {
+        endRuleBody(true);
         return 0;
+    }
 
     m_allowImportRules = m_allowNamespaceDeclarations = false;
 
@@ -11653,7 +11671,7 @@
 
 bool CSSParser::parseViewportProperty(CSSPropertyID propId, bool important)
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled());
+    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || m_context.mode == UASheetMode);
 
     CSSParserValue* value = m_valueList->current();
     if (!value)
@@ -11713,7 +11731,7 @@
 
 bool CSSParser::parseViewportShorthand(CSSPropertyID propId, CSSPropertyID first, CSSPropertyID second, bool important)
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled());
+    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || m_context.mode == UASheetMode);
     unsigned numValues = m_valueList->size();
 
     if (numValues > 2)
diff --git a/Source/core/css/CSSParser.h b/Source/core/css/CSSParser.h
index 4dbe3da..275e55d 100644
--- a/Source/core/css/CSSParser.h
+++ b/Source/core/css/CSSParser.h
@@ -109,6 +109,7 @@
     bool parseDeclaration(MutableStylePropertySet*, const String&, SourceDataHandler*, StyleSheetContents* contextStyleSheet);
     static PassRefPtr<ImmutableStylePropertySet> parseInlineStyleDeclaration(const String&, Element*);
     PassRefPtr<MediaQuerySet> parseMediaQueryList(const String&);
+    PassOwnPtr<Vector<double> > parseKeyframeKeyList(const String&);
 
     void addPropertyWithPrefixingVariant(CSSPropertyID, PassRefPtr<CSSValue>, bool important, bool implicit = false);
     void addProperty(CSSPropertyID, PassRefPtr<CSSValue>, bool important, bool implicit = false);
@@ -123,7 +124,7 @@
     bool parseContent(CSSPropertyID, bool important);
     bool parseQuotes(CSSPropertyID, bool important);
 
-    static bool parseValue(MutableStylePropertySet*, CSSPropertyID, const String&, bool important, Document*);
+    static bool parseValue(MutableStylePropertySet*, CSSPropertyID, const String&, bool important, const Document&);
     void storeVariableDeclaration(const CSSParserString&, PassOwnPtr<CSSParserValueList>, bool important);
 
     PassRefPtr<CSSValue> parseAttr(CSSParserValueList* args);
diff --git a/Source/core/css/CSSParserMode.h b/Source/core/css/CSSParserMode.h
index 43295e5..075d2e2 100644
--- a/Source/core/css/CSSParserMode.h
+++ b/Source/core/css/CSSParserMode.h
@@ -61,7 +61,7 @@
     WTF_MAKE_FAST_ALLOCATED;
 public:
     CSSParserContext(CSSParserMode, const KURL& baseURL = KURL());
-    CSSParserContext(Document*, const KURL& baseURL = KURL(), const String& charset = emptyString());
+    CSSParserContext(const Document&, const KURL& baseURL = KURL(), const String& charset = emptyString());
 
     KURL baseURL;
     String charset;
@@ -73,7 +73,7 @@
     bool isCSSTouchActionEnabled;
     bool needsSiteSpecificQuirks;
     // This quirk is to maintain compatibility with Android apps built on
-    // the Android SDK prior to and including version 17. Presumably, this
+    // the Android SDK prior to and including version 18. Presumably, this
     // can be removed any time after 2015. See http://crbug.com/277157.
     bool useLegacyBackgroundSizeShorthandBehavior;
 };
diff --git a/Source/core/css/CSSProperties.in b/Source/core/css/CSSProperties.in
index 340f0cc..3af1522 100644
--- a/Source/core/css/CSSProperties.in
+++ b/Source/core/css/CSSProperties.in
@@ -75,6 +75,7 @@
 margin-left type_name=Length, initial=initialMargin, converter=convertLengthOrAuto
 margin-right type_name=Length, initial=initialMargin, converter=convertLengthOrAuto
 margin-top type_name=Length, initial=initialMargin, converter=convertLengthOrAuto
+mask-source-type custom_all
 max-height type_name=Length, initial=initialMaxSize, converter=convertLengthMaxSizing
 max-width type_name=Length, initial=initialMaxSize, converter=convertLengthMaxSizing
 min-height type_name=Length, initial=initialMinSize, converter=convertLengthSizing
diff --git a/Source/core/css/CSSProperty.cpp b/Source/core/css/CSSProperty.cpp
index 930f3ab..9097f0e 100644
--- a/Source/core/css/CSSProperty.cpp
+++ b/Source/core/css/CSSProperty.cpp
@@ -446,6 +446,7 @@
     case CSSPropertyMarginTop:
     case CSSPropertyMask:
     case CSSPropertyMaskType:
+    case CSSPropertyMaskSourceType:
     case CSSPropertyMaxHeight:
     case CSSPropertyMaxWidth:
     case CSSPropertyMinHeight:
diff --git a/Source/core/css/CSSPropertyNames.in b/Source/core/css/CSSPropertyNames.in
index 95d21f6..c58da6b 100644
--- a/Source/core/css/CSSPropertyNames.in
+++ b/Source/core/css/CSSPropertyNames.in
@@ -146,6 +146,7 @@
 margin-left
 margin-right
 margin-top
+mask-source-type
 max-height
 max-width
 min-height
diff --git a/Source/core/css/CSSRule.idl b/Source/core/css/CSSRule.idl
index e9b0dde..94ce538 100644
--- a/Source/core/css/CSSRule.idl
+++ b/Source/core/css/CSSRule.idl
@@ -21,7 +21,6 @@
 // Introduced in DOM Level 2:
 [
     CustomToV8,
-
     DependentLifetime
 ] interface CSSRule {
 
@@ -38,8 +37,8 @@
     const unsigned short KEYFRAME_RULE = 8;
     const unsigned short WEBKIT_KEYFRAME_RULE = 8;
     const unsigned short SUPPORTS_RULE = 12;
-    [EnabledAtRuntime=cssViewport] const unsigned short VIEWPORT_RULE = 15;
-    [EnabledAtRuntime=cssRegions] const unsigned short WEBKIT_REGION_RULE = 16;
+    [EnabledAtRuntime=CSSViewport] const unsigned short VIEWPORT_RULE = 15;
+    [EnabledAtRuntime=CSSRegions] const unsigned short WEBKIT_REGION_RULE = 16;
     const unsigned short WEBKIT_FILTER_RULE = 17;
     const unsigned short HOST_RULE = 1001;
 
diff --git a/Source/core/css/CSSRuleList.idl b/Source/core/css/CSSRuleList.idl
index b2d90d6..dd18910 100644
--- a/Source/core/css/CSSRuleList.idl
+++ b/Source/core/css/CSSRuleList.idl
@@ -28,6 +28,6 @@
     DependentLifetime
 ] interface CSSRuleList {
     readonly attribute unsigned long    length;
-    getter CSSRule           item([Default=Undefined] optional unsigned long index);
+    getter CSSRule           item(unsigned long index);
 };
 
diff --git a/Source/core/css/CSSStyleSheet.cpp b/Source/core/css/CSSStyleSheet.cpp
index 6a3ed58..1f6e6e7 100644
--- a/Source/core/css/CSSStyleSheet.cpp
+++ b/Source/core/css/CSSStyleSheet.cpp
@@ -357,7 +357,7 @@
     const CSSStyleSheet* root = this;
     while (root->parentStyleSheet())
         root = root->parentStyleSheet();
-    return root->ownerNode() ? root->ownerNode()->document() : 0;
+    return root->ownerNode() ? &root->ownerNode()->document() : 0;
 }
 
 void CSSStyleSheet::clearChildRuleCSSOMWrappers()
diff --git a/Source/core/css/CSSStyleSheet.idl b/Source/core/css/CSSStyleSheet.idl
index 7d00744..986303a 100644
--- a/Source/core/css/CSSStyleSheet.idl
+++ b/Source/core/css/CSSStyleSheet.idl
@@ -25,9 +25,8 @@
     readonly attribute CSSRule          ownerRule;
     readonly attribute CSSRuleList      cssRules;
 
-    [RaisesException] unsigned long insertRule([Default=Undefined] optional DOMString rule,
-                                            [Default=Undefined] optional unsigned long index);
-    [RaisesException] void               deleteRule([Default=Undefined] optional unsigned long index);
+    [RaisesException] unsigned long insertRule(DOMString rule, unsigned long index);
+    [RaisesException] void deleteRule(unsigned long index);
 
     // IE Extensions
     readonly attribute CSSRuleList      rules;
diff --git a/Source/core/css/CSSTimingFunctionValue.cpp b/Source/core/css/CSSTimingFunctionValue.cpp
index 60717d8..8c13102 100644
--- a/Source/core/css/CSSTimingFunctionValue.cpp
+++ b/Source/core/css/CSSTimingFunctionValue.cpp
@@ -30,11 +30,6 @@
 
 namespace WebCore {
 
-String CSSLinearTimingFunctionValue::customCssText() const
-{
-    return "linear";
-}
-
 String CSSCubicBezierTimingFunctionValue::customCssText() const
 {
     return "cubic-bezier("
diff --git a/Source/core/css/CSSTimingFunctionValue.h b/Source/core/css/CSSTimingFunctionValue.h
index 0fc990f..87f2b7a 100644
--- a/Source/core/css/CSSTimingFunctionValue.h
+++ b/Source/core/css/CSSTimingFunctionValue.h
@@ -31,24 +31,6 @@
 
 namespace WebCore {
 
-class CSSLinearTimingFunctionValue : public CSSValue {
-public:
-    static PassRefPtr<CSSLinearTimingFunctionValue> create()
-    {
-        return adoptRef(new CSSLinearTimingFunctionValue);
-    }
-
-    String customCssText() const;
-
-    bool equals(const CSSLinearTimingFunctionValue&) const { return true; }
-
-private:
-    CSSLinearTimingFunctionValue()
-        : CSSValue(LinearTimingFunctionClass)
-    {
-    }
-};
-
 class CSSCubicBezierTimingFunctionValue : public CSSValue {
 public:
     static PassRefPtr<CSSCubicBezierTimingFunctionValue> create(double x1, double y1, double x2, double y2)
diff --git a/Source/core/css/CSSToStyleMap.cpp b/Source/core/css/CSSToStyleMap.cpp
index 272d1a9..8a96e56 100644
--- a/Source/core/css/CSSToStyleMap.cpp
+++ b/Source/core/css/CSSToStyleMap.cpp
@@ -58,7 +58,7 @@
 
 PassRefPtr<StyleImage> CSSToStyleMap::styleImage(CSSPropertyID propertyId, CSSValue* value)
 {
-    return m_elementStyleResources.styleImage(m_state.document()->textLinkColors(), propertyId, value);
+    return m_elementStyleResources.styleImage(m_state.document().textLinkColors(), m_state.style()->visitedDependentColor(CSSPropertyColor), propertyId, value);
 }
 
 void CSSToStyleMap::mapFillAttachment(CSSPropertyID, FillLayer* layer, CSSValue* value) const
@@ -297,6 +297,34 @@
         layer->setBackgroundYOrigin(*(pair->first()));
 }
 
+void CSSToStyleMap::mapFillMaskSourceType(CSSPropertyID, FillLayer* layer, CSSValue* value)
+{
+    EMaskSourceType type = FillLayer::initialFillMaskSourceType(layer->type());
+    if (value->isInitialValue()) {
+        layer->setMaskSourceType(type);
+        return;
+    }
+
+    if (!value->isPrimitiveValue())
+        return;
+
+    CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
+    switch (primitiveValue->getValueID()) {
+    case CSSValueAlpha:
+        type = MaskAlpha;
+        break;
+    case CSSValueLuminance:
+        type = MaskLuminance;
+        break;
+    case CSSValueAuto:
+        break;
+    default:
+        ASSERT_NOT_REACHED();
+    }
+
+    layer->setMaskSourceType(type);
+}
+
 void CSSToStyleMap::mapAnimationDelay(CSSAnimationData* animation, CSSValue* value) const
 {
     if (value->isInitialValue()) {
@@ -482,10 +510,10 @@
             animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut));
             break;
         case CSSValueStepStart:
-            animation->setTimingFunction(StepsTimingFunction::create(1, true));
+            animation->setTimingFunction(StepsTimingFunction::preset(StepsTimingFunction::Start));
             break;
         case CSSValueStepEnd:
-            animation->setTimingFunction(StepsTimingFunction::create(1, false));
+            animation->setTimingFunction(StepsTimingFunction::preset(StepsTimingFunction::End));
             break;
         default:
             break;
@@ -499,8 +527,7 @@
     } else if (value->isStepsTimingFunctionValue()) {
         CSSStepsTimingFunctionValue* stepsTimingFunction = static_cast<CSSStepsTimingFunctionValue*>(value);
         animation->setTimingFunction(StepsTimingFunction::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart()));
-    } else if (value->isLinearTimingFunctionValue())
-        animation->setTimingFunction(LinearTimingFunction::create());
+    }
 }
 
 void CSSToStyleMap::mapNinePieceImage(RenderStyle* mutableStyle, CSSPropertyID property, CSSValue* value, NinePieceImage& image)
diff --git a/Source/core/css/CSSToStyleMap.h b/Source/core/css/CSSToStyleMap.h
index 95eb006..7ea347e 100644
--- a/Source/core/css/CSSToStyleMap.h
+++ b/Source/core/css/CSSToStyleMap.h
@@ -57,6 +57,7 @@
     void mapFillSize(CSSPropertyID, FillLayer*, CSSValue*) const;
     void mapFillXPosition(CSSPropertyID, FillLayer*, CSSValue*) const;
     void mapFillYPosition(CSSPropertyID, FillLayer*, CSSValue*) const;
+    void mapFillMaskSourceType(CSSPropertyID, FillLayer*, CSSValue*);
 
     void mapAnimationDelay(CSSAnimationData*, CSSValue*) const;
     void mapAnimationDirection(CSSAnimationData*, CSSValue*) const;
diff --git a/Source/core/css/CSSValue.cpp b/Source/core/css/CSSValue.cpp
index 0b0ba28..1ffc0b1 100644
--- a/Source/core/css/CSSValue.cpp
+++ b/Source/core/css/CSSValue.cpp
@@ -188,8 +188,6 @@
             return compareCSSValues<CSSReflectValue>(*this, other);
         case ShadowClass:
             return compareCSSValues<ShadowValue>(*this, other);
-        case LinearTimingFunctionClass:
-            return compareCSSValues<CSSLinearTimingFunctionValue>(*this, other);
         case CubicBezierTimingFunctionClass:
             return compareCSSValues<CSSCubicBezierTimingFunctionValue>(*this, other);
         case StepsTimingFunctionClass:
@@ -278,8 +276,6 @@
         return static_cast<const CSSReflectValue*>(this)->customCssText();
     case ShadowClass:
         return static_cast<const ShadowValue*>(this)->customCssText();
-    case LinearTimingFunctionClass:
-        return static_cast<const CSSLinearTimingFunctionValue*>(this)->customCssText();
     case CubicBezierTimingFunctionClass:
         return static_cast<const CSSCubicBezierTimingFunctionValue*>(this)->customCssText();
     case StepsTimingFunctionClass:
@@ -397,9 +393,6 @@
     case ShadowClass:
         delete static_cast<ShadowValue*>(this);
         return;
-    case LinearTimingFunctionClass:
-        delete static_cast<CSSLinearTimingFunctionValue*>(this);
-        return;
     case CubicBezierTimingFunctionClass:
         delete static_cast<CSSCubicBezierTimingFunctionValue*>(this);
         return;
diff --git a/Source/core/css/CSSValue.h b/Source/core/css/CSSValue.h
index 6fe3119..27f6467 100644
--- a/Source/core/css/CSSValue.h
+++ b/Source/core/css/CSSValue.h
@@ -85,7 +85,6 @@
     bool isReflectValue() const { return m_classType == ReflectClass; }
     bool isShadowValue() const { return m_classType == ShadowClass; }
     bool isCubicBezierTimingFunctionValue() const { return m_classType == CubicBezierTimingFunctionClass; }
-    bool isLinearTimingFunctionValue() const { return m_classType == LinearTimingFunctionClass; }
     bool isStepsTimingFunctionValue() const { return m_classType == StepsTimingFunctionClass; }
     bool isCSSTransformValue() const { return m_classType == CSSTransformClass; }
     bool isCSSLineBoxContainValue() const { return m_classType == LineBoxContainClass; }
@@ -132,7 +131,6 @@
 
         // Timing function classes.
         CubicBezierTimingFunctionClass,
-        LinearTimingFunctionClass,
         StepsTimingFunctionClass,
 
         // Other class types.
diff --git a/Source/core/css/CSSValueList.idl b/Source/core/css/CSSValueList.idl
index ea58b39..b44fcac 100644
--- a/Source/core/css/CSSValueList.idl
+++ b/Source/core/css/CSSValueList.idl
@@ -27,6 +27,6 @@
 [
 ] interface CSSValueList : CSSValue {
     readonly attribute unsigned long    length;
-    getter CSSValue           item([Default=Undefined] optional unsigned long index);
+    getter CSSValue           item(unsigned long index);
 };
 
diff --git a/Source/core/css/ElementRuleCollector.cpp b/Source/core/css/ElementRuleCollector.cpp
index 40240b7..5ccfc77 100644
--- a/Source/core/css/ElementRuleCollector.cpp
+++ b/Source/core/css/ElementRuleCollector.cpp
@@ -100,14 +100,14 @@
 
 static bool rulesApplicableInCurrentTreeScope(const Element* element, const ContainerNode* scopingNode, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary, bool elementApplyAuthorStyles)
 {
-    TreeScope* treeScope = element->treeScope();
+    TreeScope& treeScope = element->treeScope();
 
     // [skipped, because already checked] a) it's a UA rule
     // b) element is allowed to apply author rules
     if (elementApplyAuthorStyles)
         return true;
     // c) the rules comes from a scoped style sheet within the same tree scope
-    if (!scopingNode || treeScope == scopingNode->treeScope())
+    if (!scopingNode || &treeScope == &scopingNode->treeScope())
         return true;
     // d) the rules comes from a scoped style sheet within an active shadow root whose host is the given element
     if (element->isInShadowTree() && (behaviorAtBoundary & SelectorChecker::ScopeIsShadowHost) && scopingNode == element->containingShadowRoot()->host())
diff --git a/Source/core/css/ElementRuleCollector.h b/Source/core/css/ElementRuleCollector.h
index c52aa21..60f7abc 100644
--- a/Source/core/css/ElementRuleCollector.h
+++ b/Source/core/css/ElementRuleCollector.h
@@ -105,7 +105,7 @@
     void sortAndTransferMatchedRulesWithOnlySortBySpecificity();
 
 private:
-    Document* document() { return m_context.document(); }
+    Document& document() { return m_context.document(); }
 
     void collectRuleIfMatches(const RuleData&, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
     void collectMatchingRulesForList(const Vector<RuleData>*, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
diff --git a/Source/core/css/FontLoader.cpp b/Source/core/css/FontLoader.cpp
index c1648c5..4e0609c 100644
--- a/Source/core/css/FontLoader.cpp
+++ b/Source/core/css/FontLoader.cpp
@@ -117,7 +117,6 @@
 
 FontLoader::FontLoader(Document* document)
     : ActiveDOMObject(document)
-    , m_document(document)
     , m_loadingCount(0)
     , m_timer(this, &FontLoader::timerFired)
 {
@@ -128,6 +127,11 @@
 {
 }
 
+Document* FontLoader::document() const
+{
+    return toDocument(scriptExecutionContext());
+}
+
 EventTargetData* FontLoader::eventTargetData()
 {
     return &m_eventTargetData;
@@ -150,7 +154,8 @@
 
 void FontLoader::didLayout()
 {
-    if (m_document->page() && m_document->page()->mainFrame() == m_document->frame())
+    Document* d = document();
+    if (d->page() && d->page()->mainFrame() == d->frame())
         m_histogram.record();
     if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
         return;
@@ -261,7 +266,8 @@
     // 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.
-    if (!m_document->view() || m_document->view()->needsLayout())
+    Document* d = document();
+    if (!d->view() || d->view()->needsLayout())
         return;
 
     if (m_pendingDoneEvent)
@@ -287,10 +293,11 @@
     RefPtr<LoadFontCallback> callback = LoadFontCallback::createFromParams(params, font.family());
 
     for (const FontFamily* f = &font.family(); f; f = f->next()) {
-        CSSSegmentedFontFace* face = m_document->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
+        Document* d = document();
+        CSSSegmentedFontFace* face = d->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
         if (!face) {
             if (callback)
-                callback->error(m_document);
+                callback->error(d);
             continue;
         }
         face->loadFont(font.fontDescription(), callback);
@@ -304,7 +311,7 @@
     if (!resolveFontStyle(fontString, font))
         return false;
     for (const FontFamily* f = &font.family(); f; f = f->next()) {
-        CSSSegmentedFontFace* face = m_document->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
+        CSSSegmentedFontFace* face = document()->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
         if (!face || !face->checkFont())
             return false;
     }
@@ -346,7 +353,7 @@
         CSSPropertyValue(CSSPropertyFontSize, *parsedStyle),
         CSSPropertyValue(CSSPropertyLineHeight, *parsedStyle),
     };
-    StyleResolver* styleResolver = m_document->styleResolver();
+    StyleResolver* styleResolver = document()->styleResolver();
     styleResolver->applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), style.get());
 
     font = style->font();
diff --git a/Source/core/css/FontLoader.h b/Source/core/css/FontLoader.h
index cd296ed..c67a407 100644
--- a/Source/core/css/FontLoader.h
+++ b/Source/core/css/FontLoader.h
@@ -73,7 +73,7 @@
     using RefCounted<FontLoader>::ref;
     using RefCounted<FontLoader>::deref;
 
-    Document* document() const { return m_document; }
+    Document* document() const;
 
     void didLayout();
     void beginFontLoading(CSSFontFaceRule*);
@@ -108,7 +108,6 @@
     bool resolveFontStyle(const String&, Font&);
     void timerFired(Timer<FontLoader>*);
 
-    Document* m_document;
     EventTargetData m_eventTargetData;
     unsigned m_loadingCount;
     Vector<RefPtr<Event> > m_pendingEvents;
diff --git a/Source/core/css/FontLoader.idl b/Source/core/css/FontLoader.idl
index 06ce8c0..ff4e533 100644
--- a/Source/core/css/FontLoader.idl
+++ b/Source/core/css/FontLoader.idl
@@ -30,7 +30,7 @@
 
 [
     NoInterfaceObject,
-    EnabledAtRuntime=fontLoadEvents,
+    EnabledAtRuntime=FontLoadEvents,
     ActiveDOMObject,
     GenerateIsReachable=document
 ] interface FontLoader : EventTarget {
diff --git a/Source/core/css/InspectorCSSOMWrappers.cpp b/Source/core/css/InspectorCSSOMWrappers.cpp
index 90007ff..7cdd0f7 100644
--- a/Source/core/css/InspectorCSSOMWrappers.cpp
+++ b/Source/core/css/InspectorCSSOMWrappers.cpp
@@ -118,7 +118,6 @@
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::defaultStyleSheet);
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::quirksStyleSheet);
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::svgStyleSheet);
-        collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::mathMLStyleSheet);
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::mediaControlsStyleSheet);
         collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::fullscreenStyleSheet);
 
diff --git a/Source/core/css/MediaList.idl b/Source/core/css/MediaList.idl
index 9d26617..20ef3ec 100644
--- a/Source/core/css/MediaList.idl
+++ b/Source/core/css/MediaList.idl
@@ -30,9 +30,9 @@
     [TreatNullAs=NullString, TreatReturnedNullStringAs=Null] attribute DOMString mediaText;
     readonly attribute unsigned long length;
 
-    [TreatReturnedNullStringAs=Null] getter DOMString item([Default=Undefined] optional unsigned long index);
-    [RaisesException] void deleteMedium([Default=Undefined] optional DOMString oldMedium);
-    [RaisesException] void appendMedium([Default=Undefined] optional DOMString newMedium);
+    [TreatReturnedNullStringAs=Null] getter DOMString item(unsigned long index);
+    [RaisesException] void deleteMedium(DOMString oldMedium);
+    [RaisesException] void appendMedium(DOMString newMedium);
 
 };
 
diff --git a/Source/core/css/MediaQueryListListener.cpp b/Source/core/css/MediaQueryListListener.cpp
index 74f976c..36bf5c4 100644
--- a/Source/core/css/MediaQueryListListener.cpp
+++ b/Source/core/css/MediaQueryListListener.cpp
@@ -28,7 +28,7 @@
 void MediaQueryListListener::queryChanged(ScriptState* state, MediaQueryList* query)
 {
     ScriptCallback callback(state, m_value);
-    v8::HandleScope handleScope;
+    v8::HandleScope handleScope(state->isolate());
 
     v8::Handle<v8::Context> context = state->context();
     if (context.IsEmpty())
diff --git a/Source/core/css/PageRuleCollector.cpp b/Source/core/css/PageRuleCollector.cpp
index daae716..65c409e 100644
--- a/Source/core/css/PageRuleCollector.cpp
+++ b/Source/core/css/PageRuleCollector.cpp
@@ -43,7 +43,7 @@
 bool PageRuleCollector::isLeftPage(int pageIndex) const
 {
     bool isFirstPageLeft = false;
-    if (!m_context.rootElementStyle()->isLeftToRightDirection())
+    if (!m_context.rootElementStyle() || !m_context.rootElementStyle()->isLeftToRightDirection())
         isFirstPageLeft = true;
 
     return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.cpp b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
index aa7c9ee..64107b4 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.cpp
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
@@ -91,8 +91,8 @@
         PropertySetCSSStyleDeclaration* localCopyStyleDecl = s_currentDecl;
         s_currentDecl = 0;
         s_shouldNotifyInspector = false;
-        if (localCopyStyleDecl->parentElement() && localCopyStyleDecl->parentElement()->document())
-            InspectorInstrumentation::didInvalidateStyleAttr(localCopyStyleDecl->parentElement()->document(), localCopyStyleDecl->parentElement());
+        if (localCopyStyleDecl->parentElement())
+            InspectorInstrumentation::didInvalidateStyleAttr(&localCopyStyleDecl->parentElement()->document(), localCopyStyleDecl->parentElement());
     }
 
     void enqueueMutationRecord()
@@ -418,7 +418,7 @@
 
 CSSStyleSheet* InlineCSSStyleDeclaration::parentStyleSheet() const
 {
-    return m_parentElement ? m_parentElement->document()->elementSheet() : 0;
+    return m_parentElement ? m_parentElement->document().elementSheet() : 0;
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/RuleSet.cpp b/Source/core/css/RuleSet.cpp
index e694109..2ffda78 100644
--- a/Source/core/css/RuleSet.cpp
+++ b/Source/core/css/RuleSet.cpp
@@ -393,7 +393,7 @@
             resolver->setBuildScopedStyleTreeInDocumentOrder(false);
             resolver->ensureScopedStyleResolver(scope->shadowHost())->addHostRule(static_cast<StyleRuleHost*>(rule), hasDocumentSecurityOrigin, scope);
             resolver->setBuildScopedStyleTreeInDocumentOrder(enabled);
-        } else if (RuntimeEnabledFeatures::cssViewportEnabled() && rule->isViewportRule()) {
+        } else if (rule->isViewportRule()) {
             // @viewport should not be scoped.
             if (!isDocumentScope(scope))
                 continue;
@@ -415,7 +415,7 @@
             addRulesFromSheet(importRule->styleSheet(), medium, resolver, scope);
     }
 
-    bool hasDocumentSecurityOrigin = resolver && resolver->document()->securityOrigin()->canRequest(sheet->baseURL());
+    bool hasDocumentSecurityOrigin = resolver && resolver->document().securityOrigin()->canRequest(sheet->baseURL());
     AddRuleFlags addRuleFlags = static_cast<AddRuleFlags>((hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : 0) | (!scope ? RuleCanUseFastCheckSelector : 0));
 
     addChildRules(sheet->childRules(), medium, resolver, scope, hasDocumentSecurityOrigin, addRuleFlags);
diff --git a/Source/core/css/SVGCSSComputedStyleDeclaration.cpp b/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
index b773e4f..5858b48 100644
--- a/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
@@ -83,11 +83,8 @@
 PassRefPtr<SVGPaint> CSSComputedStyleDeclaration::adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint> newPaint, RenderStyle* style) const
 {
     RefPtr<SVGPaint> paint = newPaint;
-    if (paint->paintType() == SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR || paint->paintType() == SVGPaint::SVG_PAINTTYPE_URI_CURRENTCOLOR) {
-        // SVG handles currentColor itself, style->color() is guaranteed not to be currentColor.
-        ASSERT(!style->color().isCurrentColor());
-        paint->setColor(style->color().color());
-    }
+    if (paint->paintType() == SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR || paint->paintType() == SVGPaint::SVG_PAINTTYPE_URI_CURRENTCOLOR)
+        paint->setColor(style->color());
     return paint.release();
 }
 
@@ -99,7 +96,7 @@
 
     // Make sure our layout is up to date before we allow a query on these attributes.
     if (updateLayout)
-        node->document()->updateLayout();
+        node->document().updateLayout();
 
     RenderStyle* style = node->computedStyle();
     if (!style)
diff --git a/Source/core/css/SelectorChecker.cpp b/Source/core/css/SelectorChecker.cpp
index d9cfdf9..d6d28b8 100644
--- a/Source/core/css/SelectorChecker.cpp
+++ b/Source/core/css/SelectorChecker.cpp
@@ -63,9 +63,9 @@
 
 using namespace HTMLNames;
 
-SelectorChecker::SelectorChecker(Document* document, Mode mode)
-    : m_strictParsing(!document->inQuirksMode())
-    , m_documentIsHTML(document->isHTMLDocument())
+SelectorChecker::SelectorChecker(Document& document, Mode mode)
+    : m_strictParsing(!document.inQuirksMode())
+    , m_documentIsHTML(document.isHTMLDocument())
     , m_mode(mode)
 {
 }
@@ -153,10 +153,8 @@
                 return SelectorFailsLocally;
 
             PseudoId pseudoId = CSSSelector::pseudoId(context.selector->pseudoType());
-            if (pseudoId == FIRST_LETTER) {
-                if (Document* document = context.element->document())
-                    document->styleSheetCollections()->setUsesFirstLetterRules(true);
-            }
+            if (pseudoId == FIRST_LETTER)
+                context.element->document().styleSheetCollections()->setUsesFirstLetterRules(true);
             if (pseudoId != NOPSEUDO && m_mode != SharingRules)
                 dynamicPseudo = pseudoId;
         }
@@ -265,7 +263,7 @@
     case CSSSelector::ShadowPseudo:
         {
             // If we're in the same tree-scope as the scoping element, then following a shadow descendant combinator would escape that and thus the scope.
-            if (context.scope && context.scope->treeScope() == context.element->treeScope() && (context.behaviorAtBoundary & BoundaryBehaviorMask) != StaysWithinTreeScope)
+            if (context.scope && &context.scope->treeScope() == &context.element->treeScope() && (context.behaviorAtBoundary & BoundaryBehaviorMask) != StaysWithinTreeScope)
                 return SelectorFailsCompletely;
             Element* shadowHostNode = context.element->shadowHost();
             if (!shadowHostNode)
@@ -437,10 +435,10 @@
         } else if (context.hasScrollbarPseudo) {
             // CSS scrollbars match a specific subset of pseudo classes, and they have specialized rules for each
             // (since there are no elements involved).
-            return checkScrollbarPseudoClass(context, element->document(), selector);
+            return checkScrollbarPseudoClass(context, &element->document(), selector);
         } else if (context.hasSelectionPseudo) {
             if (selector->pseudoType() == CSSSelector::PseudoWindowInactive)
-                return !element->document()->page()->focusController().isActive();
+                return !element->document().page()->focusController().isActive();
         }
 
         // Normal element pseudo class checking.
@@ -468,7 +466,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().styleSheetCollections()->usesSiblingRules() || element->renderStyle()->unique()))
                         element->renderStyle()->setEmptyState(result);
                 }
                 return result;
@@ -603,7 +601,7 @@
             }
             break;
         case CSSSelector::PseudoTarget:
-            if (element == element->document()->cssTarget())
+            if (element == element->document().cssTarget())
                 return true;
             break;
         case CSSSelector::PseudoAny:
@@ -675,7 +673,7 @@
                 return !element->isDisabledFormControl();
             break;
         case CSSSelector::PseudoFullPageMedia:
-            return element && element->document() && element->document()->isMediaDocument();
+            return element && element->document().isMediaDocument();
             break;
         case CSSSelector::PseudoDefault:
             return element && element->isDefaultButtonForForm();
@@ -694,12 +692,12 @@
         case CSSSelector::PseudoValid:
             if (!element)
                 return false;
-            element->document()->setContainsValidityStyleRules();
+            element->document().setContainsValidityStyleRules();
             return element->willValidate() && element->isValidFormControlElement();
         case CSSSelector::PseudoInvalid:
             if (!element)
                 return false;
-            element->document()->setContainsValidityStyleRules();
+            element->document().setContainsValidityStyleRules();
             return element->willValidate() && !element->isValidFormControlElement();
         case CSSSelector::PseudoChecked:
             {
@@ -721,7 +719,7 @@
         case CSSSelector::PseudoIndeterminate:
             return element && element->shouldAppearIndeterminate();
         case CSSSelector::PseudoRoot:
-            if (element == element->document()->documentElement())
+            if (element == element->document().documentElement())
                 return true;
             break;
         case CSSSelector::PseudoLang:
@@ -745,7 +743,7 @@
             // context's Document is in the fullscreen state has the 'full-screen' pseudoclass applied.
             if (element->isFrameElementBase() && element->containsFullScreenElement())
                 return true;
-            if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(element->document())) {
+            if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(&element->document())) {
                 if (!fullscreen->webkitIsFullScreen())
                     return false;
                 return element == fullscreen->webkitCurrentFullScreenElement();
@@ -756,22 +754,22 @@
         case CSSSelector::PseudoFullScreenDocument:
             // While a Document is in the fullscreen state, the 'full-screen-document' pseudoclass applies
             // to all elements of that Document.
-            if (!FullscreenElementStack::isFullScreen(element->document()))
+            if (!FullscreenElementStack::isFullScreen(&element->document()))
                 return false;
             return true;
         case CSSSelector::PseudoSeamlessDocument:
             // While a document is rendered in a seamless iframe, the 'seamless-document' pseudoclass applies
             // to all elements of that Document.
-            return element->document()->shouldDisplaySeamlesslyWithParent();
+            return element->document().shouldDisplaySeamlesslyWithParent();
         case CSSSelector::PseudoInRange:
             if (!element)
                 return false;
-            element->document()->setContainsValidityStyleRules();
+            element->document().setContainsValidityStyleRules();
             return element->isInRange();
         case CSSSelector::PseudoOutOfRange:
             if (!element)
                 return false;
-            element->document()->setContainsValidityStyleRules();
+            element->document().setContainsValidityStyleRules();
             return element->isOutOfRange();
         case CSSSelector::PseudoFutureCue:
             return (element->isWebVTTElement() && !toWebVTTElement(element)->isPastNode());
@@ -780,7 +778,7 @@
 
         case CSSSelector::PseudoScope:
             {
-                const Node* contextualReferenceNode = !context.scope || (context.behaviorAtBoundary & BoundaryBehaviorMask) == CrossesBoundary ? element->document()->documentElement() : context.scope;
+                const Node* contextualReferenceNode = !context.scope || (context.behaviorAtBoundary & BoundaryBehaviorMask) == CrossesBoundary ? element->document().documentElement() : context.scope;
                 if (element == contextualReferenceNode)
                     return true;
                 break;
@@ -984,7 +982,7 @@
 
 bool SelectorChecker::isFrameFocused(const Element* element)
 {
-    return element->document()->frame() && element->document()->frame()->selection()->isFocusedAndActive();
+    return element->document().frame() && element->document().frame()->selection().isFocusedAndActive();
 }
 
 bool SelectorChecker::matchesFocusPseudoClass(const Element* element)
diff --git a/Source/core/css/SelectorChecker.h b/Source/core/css/SelectorChecker.h
index 50c7727..aba4e03 100644
--- a/Source/core/css/SelectorChecker.h
+++ b/Source/core/css/SelectorChecker.h
@@ -44,7 +44,7 @@
     enum Match { SelectorMatches, SelectorFailsLocally, SelectorFailsAllSiblings, SelectorFailsCompletely };
     enum VisitedMatchType { VisitedMatchDisabled, VisitedMatchEnabled };
     enum Mode { ResolvingStyle = 0, CollectingRules, QueryingRules, SharingRules };
-    explicit SelectorChecker(Document*, Mode);
+    explicit SelectorChecker(Document&, Mode);
     enum BehaviorAtBoundary {
         DoesNotCrossBoundary = 0,
         CrossesBoundary = 1,
diff --git a/Source/core/css/StyleColor.cpp b/Source/core/css/StyleColor.cpp
deleted file mode 100644
index d6d2d30..0000000
--- a/Source/core/css/StyleColor.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006, 2008 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 COMPUTER, 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.
- */
-
-#include "config.h"
-#include "core/css/StyleColor.h"
-
-#include "core/platform/HashTools.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-StyleColor::StyleColor(const String& name)
-{
-    if (name[0] == '#') {
-        RGBA32 rgba;
-        if (name.is8Bit())
-            m_valid = Color::parseHexColor(name.characters8() + 1, name.length() - 1, rgba);
-        else
-            m_valid = Color::parseHexColor(name.characters16() + 1, name.length() - 1, rgba);
-        m_color = rgba;
-    } else {
-        setNamedColor(name);
-    }
-}
-
-StyleColor::StyleColor(const char* name)
-{
-    if (name[0] == '#') {
-        RGBA32 rgba;
-        m_valid = Color::parseHexColor(&name[1], rgba);
-        m_color = rgba;
-    } else {
-        const NamedColor* foundColor = findColor(name, strlen(name));
-        m_color = foundColor ? foundColor->ARGBValue : 0;
-        m_valid = foundColor;
-    }
-}
-
-static inline const NamedColor* findNamedColor(const String& name)
-{
-    char buffer[64]; // easily big enough for the longest color name
-    unsigned length = name.length();
-    if (length > sizeof(buffer) - 1)
-        return 0;
-    for (unsigned i = 0; i < length; ++i) {
-        UChar c = name[i];
-        if (!c || c > 0x7F)
-            return 0;
-        buffer[i] = toASCIILower(static_cast<char>(c));
-    }
-    buffer[length] = '\0';
-    return findColor(buffer, length);
-}
-
-void StyleColor::setNamedColor(const String& name)
-{
-    const NamedColor* foundColor = findNamedColor(name);
-    m_color = foundColor ? foundColor->ARGBValue : 0;
-    m_valid = foundColor;
-}
-
-} // namespace WebCore
diff --git a/Source/core/css/StyleColor.h b/Source/core/css/StyleColor.h
index 41c9f97..eb893e4 100644
--- a/Source/core/css/StyleColor.h
+++ b/Source/core/css/StyleColor.h
@@ -43,11 +43,11 @@
         : m_color()
         , m_valid(false)
         , m_currentColor(false) { }
-    StyleColor(RGBA32 color)
+    StyleColor(Color color)
         : m_color(color)
         , m_valid(true)
         , m_currentColor(false) { }
-    StyleColor(Color color, bool valid = true, bool currentColor = false)
+    StyleColor(RGBA32 color, bool valid = true, bool currentColor = false)
         : m_color(color)
         , m_valid(valid)
         , m_currentColor(currentColor) { }
@@ -63,15 +63,12 @@
         : m_color(other.m_color)
         , m_valid(other.m_valid)
         , m_currentColor(other.m_currentColor) { }
-    explicit StyleColor(const String&);
-    explicit StyleColor(const char*);
 
     Color color() const { return m_color; }
     bool isValid() const { return m_valid; }
     bool isCurrentColor() const { return m_currentColor; }
     bool hasAlpha() const { return m_color.hasAlpha(); }
 
-    void setNamedColor(const String&);
     void setRGB(int r, int g, int b)
     {
         m_color.setRGB(r, g, b);
diff --git a/Source/core/css/StyleRule.cpp b/Source/core/css/StyleRule.cpp
index 4e37545..2fc1fda 100644
--- a/Source/core/css/StyleRule.cpp
+++ b/Source/core/css/StyleRule.cpp
@@ -342,14 +342,12 @@
 StyleRuleViewport::StyleRuleViewport()
     : StyleRuleBase(Viewport)
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled());
 }
 
 StyleRuleViewport::StyleRuleViewport(const StyleRuleViewport& o)
     : StyleRuleBase(o)
     , m_properties(o.m_properties->mutableCopy())
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled());
 }
 
 StyleRuleViewport::~StyleRuleViewport()
diff --git a/Source/core/css/StyleSheetContents.cpp b/Source/core/css/StyleSheetContents.cpp
index 76e6d55..3c48a6b 100644
--- a/Source/core/css/StyleSheetContents.cpp
+++ b/Source/core/css/StyleSheetContents.cpp
@@ -387,7 +387,7 @@
 Document* StyleSheetContents::singleOwnerDocument() const
 {
     Node* ownerNode = singleOwnerNode();
-    return ownerNode ? ownerNode->document() : 0;
+    return ownerNode ? &ownerNode->document() : 0;
 }
 
 KURL StyleSheetContents::completeURL(const String& url) const
diff --git a/Source/core/css/StyleSheetList.idl b/Source/core/css/StyleSheetList.idl
index 390e2c9..dcf92c2 100644
--- a/Source/core/css/StyleSheetList.idl
+++ b/Source/core/css/StyleSheetList.idl
@@ -23,7 +23,7 @@
     GenerateIsReachable=document,
 ] interface StyleSheetList {
     readonly attribute unsigned long    length;
-    getter StyleSheet         item([Default=Undefined] optional unsigned long index);
+    getter StyleSheet         item(unsigned long index);
     [ImplementedAs=anonymousNamedGetter, NotEnumerable] getter CSSStyleSheet (DOMString name);
 };
 
diff --git a/Source/core/css/WebKitCSSFilterValue.idl b/Source/core/css/WebKitCSSFilterValue.idl
index c6f4b80..db2fb1d 100644
--- a/Source/core/css/WebKitCSSFilterValue.idl
+++ b/Source/core/css/WebKitCSSFilterValue.idl
@@ -44,5 +44,5 @@
     const unsigned short CSS_FILTER_CUSTOM = 12;
 
     readonly attribute unsigned short operationType;
-    [ImplementedAs=item] getter CSSValue([Default=Undefined] optional unsigned long index);
+    [ImplementedAs=item] getter CSSValue(unsigned long index);
 };
diff --git a/Source/core/css/WebKitCSSRegionRule.idl b/Source/core/css/WebKitCSSRegionRule.idl
index 5835319..ad91ce0 100644
--- a/Source/core/css/WebKitCSSRegionRule.idl
+++ b/Source/core/css/WebKitCSSRegionRule.idl
@@ -28,7 +28,7 @@
  */
 
 [
-    EnabledAtRuntime=cssRegions,
+    EnabledAtRuntime=CSSRegions,
     ImplementedAs=CSSRegionRule
 ] interface WebKitCSSRegionRule : CSSRule {
     readonly attribute CSSRuleList cssRules;
diff --git a/Source/core/css/WebKitCSSTransformValue.idl b/Source/core/css/WebKitCSSTransformValue.idl
index 8b59a43..836bcc6 100644
--- a/Source/core/css/WebKitCSSTransformValue.idl
+++ b/Source/core/css/WebKitCSSTransformValue.idl
@@ -56,6 +56,6 @@
     const unsigned short CSS_MATRIX3D    = 21;
 
     readonly attribute unsigned short operationType;
-    [ImplementedAs=item] getter CSSValue([Default=Undefined] optional unsigned long index);
+    [ImplementedAs=item] getter CSSValue(unsigned long index);
 };
 
diff --git a/Source/core/css/fullscreen.css b/Source/core/css/fullscreen.css
index c7c2dcd..62b33ea 100644
--- a/Source/core/css/fullscreen.css
+++ b/Source/core/css/fullscreen.css
@@ -27,7 +27,7 @@
     margin: 0 !important;
     height: 100% !important;
     width: 100% !important;
-    -webkit-flex: 1 !important;
+    flex: 1 !important;
     display: block !important;
 }
 
diff --git a/Source/core/css/html.css b/Source/core/css/html.css
index 1fe1b6d..b41ccf0 100644
--- a/Source/core/css/html.css
+++ b/Source/core/css/html.css
@@ -60,7 +60,11 @@
 }
 
 body:-webkit-seamless-document {
-    margin: 0px;
+    margin: 0px
+}
+
+body:-webkit-full-page-media {
+    background-color: rgb(0, 0, 0)
 }
 
 p {
@@ -428,8 +432,8 @@
 }
 
 input::-webkit-textfield-decoration-container {
-    display: -webkit-flex;
-    -webkit-align-items: center;
+    display: flex;
+    align-items: center;
     -webkit-user-modify: read-only !important;
     content: none !important;
 }
@@ -441,7 +445,7 @@
 input::-webkit-clear-button {
     -webkit-appearance: searchfield-cancel-button;
     display: inline-block;
-    -webkit-flex: none;
+    flex: none;
     -webkit-user-modify: read-only !important;
     -webkit-margin-start: 2px;
 }
@@ -449,7 +453,7 @@
 input[type="search"]::-webkit-search-cancel-button {
     -webkit-appearance: searchfield-cancel-button;
     display: block;
-    -webkit-flex: none;
+    flex: none;
     -webkit-user-modify: read-only !important;
     -webkit-margin-start: 1px;
 }
@@ -457,7 +461,7 @@
 input[type="search"]::-webkit-search-decoration {
     -webkit-appearance: searchfield-decoration;
     display: block;
-    -webkit-flex: none;
+    flex: none;
     -webkit-user-modify: read-only !important;
     -webkit-align-self: flex-start;
     margin: auto 0;
@@ -466,7 +470,7 @@
 input[type="search"]::-webkit-search-results-decoration {
     -webkit-appearance: searchfield-results-decoration;
     display: block;
-    -webkit-flex: none;
+    flex: none;
     -webkit-user-modify: read-only !important;
     -webkit-align-self: flex-start;
     margin: auto 0;
@@ -478,7 +482,7 @@
 input[type="month"],
 input[type="time"],
 input[type="week"] {
-    -webkit-align-items: center;
+    align-items: center;
     display: -webkit-inline-flex;
     font-family: monospace;
     overflow: hidden;
@@ -487,7 +491,7 @@
 }
 
 input::-webkit-datetime-edit {
-    -webkit-flex: 1;
+    flex: 1;
     -webkit-user-modify: read-only !important;
     display: inline-block;
     overflow: hidden;
@@ -570,7 +574,7 @@
 input[type="month"],
 input[type="time"],
 input[type="week"] {
-    -webkit-align-items: center;
+    align-items: center;
     -webkit-appearance: menulist-button;
     display: -webkit-inline-flex;
     overflow: hidden;
@@ -593,7 +597,7 @@
      * button in layout(). */
     height: 1.5em;
     vertical-align: top;
-    -webkit-flex: none;
+    flex: none;
     -webkit-user-select: none;
     -webkit-user-modify: read-only !important;
 }
@@ -603,7 +607,7 @@
     -webkit-appearance: -webkit-input-speech-button;
     display: block;
     vertical-align: top;
-    -webkit-flex: none;
+    flex: none;
     -webkit-user-modify: read-only !important;
     -webkit-align-self: flex-start;
     margin: auto 0;
@@ -624,7 +628,7 @@
     border: 1px solid;
     -webkit-rtl-ordering: logical;
     -webkit-user-select: text;
-    -webkit-flex-direction: column;
+    flex-direction: column;
     resize: auto;
     cursor: auto;
     padding: 2px;
@@ -658,7 +662,7 @@
 }
 
 input[type="file"] {
-    -webkit-align-items: baseline;
+    align-items: baseline;
     color: inherit;
     text-align: start !important;
 }
@@ -690,7 +694,7 @@
 }
 
 input[type="button"], input[type="submit"], input[type="reset"], input[type="file"]::-webkit-file-upload-button, button {
-    -webkit-align-items: flex-start;
+    align-items: flex-start;
     text-align: center;
     cursor: default;
     color: ButtonText;
@@ -709,15 +713,15 @@
 }
 
 input[type="range"]::-webkit-slider-container, input[type="range"]::-webkit-media-slider-container {
-    -webkit-flex: 1;
+    flex: 1;
     box-sizing: border-box;
     -webkit-user-modify: read-only !important;
-    display: -webkit-flex;
+    display: flex;
     -webkit-align-contents: center;
 }
 
 input[type="range"]::-webkit-slider-runnable-track {
-    -webkit-flex: 1;
+    flex: 1;
     -webkit-align-self: center;
 
     box-sizing: border-box;
@@ -768,7 +772,7 @@
 }
 
 input[type="color"]::-webkit-color-swatch-wrapper {
-    display:-webkit-flex;
+    display:flex;
     padding: 4px 2px;
     box-sizing: border-box;
     -webkit-user-modify: read-only !important;
@@ -779,7 +783,7 @@
 input[type="color"]::-webkit-color-swatch {
     background-color: #000000;
     border: 1px solid #777777;
-    -webkit-flex: 1;
+    flex: 1;
     -webkit-user-modify: read-only !important;
 }
 
@@ -821,7 +825,7 @@
 select {
     -webkit-appearance: menulist;
     box-sizing: border-box;
-    -webkit-align-items: center;
+    align-items: center;
     border: 1px solid;
     white-space: pre;
     -webkit-rtl-ordering: logical;
@@ -834,7 +838,7 @@
 select[multiple],
 select[size][multiple] {
     -webkit-appearance: listbox;
-    -webkit-align-items: flex-start;
+    align-items: flex-start;
     border: 1px inset gray;
     border-radius: initial;
     white-space: initial;
@@ -843,7 +847,7 @@
 select[size="0"],
 select[size="1"] {
     -webkit-appearance: menulist;
-    -webkit-align-items: center;
+    align-items: center;
     border: 1px solid;
     border-radius: 5px;
     white-space: pre;
@@ -1126,5 +1130,11 @@
     border-width: 0px;
 }
 
+/* viewport */
+
+@viewport {
+    min-width: 980px;
+}
+
 /* noscript is handled internally, as it depends on settings. */
 
diff --git a/Source/core/css/mediaControls.css b/Source/core/css/mediaControls.css
index d31a0aa..2c8e073 100644
--- a/Source/core/css/mediaControls.css
+++ b/Source/core/css/mediaControls.css
@@ -25,31 +25,30 @@
 
 /* Chromium default media controls */
 
-body:-webkit-full-page-media {
-    background-color: rgb(0, 0, 0);
-}
+/* WARNING: This css file can only style <audio> and <video> elements */
 
 audio {
     width: 300px;
     height: 30px;
 }
 
-::-webkit-media-controls {
+audio::-webkit-media-controls,
+video::-webkit-media-controls {
     width: inherit;
     height: inherit;
     position: relative;
     direction: ltr;
-    display: -webkit-flex;
-    -webkit-flex-direction: column;
-    -webkit-justify-content: flex-end;
-    -webkit-align-items: center;
+    display: flex;
+    flex-direction: column;
+    justify-content: flex-end;
+    align-items: center;
 }
 
 audio::-webkit-media-controls-enclosure, video::-webkit-media-controls-enclosure {
     width: 100%;
     max-width: 800px;
     height: 30px;
-    -webkit-flex-shrink: 0;
+    flex-shrink: 0;
     bottom: 0;
     text-indent: 0;
     padding: 0;
@@ -59,17 +58,17 @@
 video::-webkit-media-controls-enclosure {
     padding: 0px 5px 5px 5px;
     height: 35px;
-    -webkit-flex-shrink: 0;
+    flex-shrink: 0;
 }
 
 audio::-webkit-media-controls-panel, video::-webkit-media-controls-panel {
-    display: -webkit-flex;
-    -webkit-flex-direction: row;
-    -webkit-align-items: center;
+    display: flex;
+    flex-direction: row;
+    align-items: center;
     /* We use flex-start here to ensure that the play button is visible even
      * if we are too small to show all controls.
      */
-    -webkit-justify-content: flex-start;
+    justify-content: flex-start;
     -webkit-user-select: none;
     position: relative;
     width: 100%;
@@ -103,8 +102,8 @@
 
 audio::-webkit-media-controls-mute-button, video::-webkit-media-controls-mute-button {
     -webkit-appearance: media-mute-button;
-    display: -webkit-flex;
-    -webkit-flex: none;
+    display: flex;
+    flex: none;
     border: none;
     box-sizing: border-box;
     width: 35px;
@@ -122,8 +121,8 @@
 
 audio::-webkit-media-controls-play-button, video::-webkit-media-controls-play-button {
     -webkit-appearance: media-play-button;
-    display: -webkit-flex;
-    -webkit-flex: none;
+    display: flex;
+    flex: none;
     border: none;
     box-sizing: border-box;
     width: 30px;
@@ -138,11 +137,11 @@
 
 audio::-webkit-media-controls-timeline-container, video::-webkit-media-controls-timeline-container {
     -webkit-appearance: media-controls-background;
-    display: -webkit-flex;
-    -webkit-flex-direction: row;
-    -webkit-align-items: center;
-    -webkit-justify-content: flex-end;
-    -webkit-flex: 1 1;
+    display: flex;
+    flex-direction: row;
+    align-items: center;
+    justify-content: flex-end;
+    flex: 1 1;
     -webkit-user-select: none;
     height: 16px;
     min-width: 0;
@@ -152,8 +151,8 @@
 audio::-webkit-media-controls-time-remaining-display, video::-webkit-media-controls-time-remaining-display {
     -webkit-appearance: media-current-time-display;
     -webkit-user-select: none;
-    -webkit-flex: none;
-    display: -webkit-flex;
+    flex: none;
+    display: flex;
     border: none;
     cursor: default;
 
@@ -178,8 +177,8 @@
 
 audio::-webkit-media-controls-timeline, video::-webkit-media-controls-timeline {
     -webkit-appearance: media-slider;
-    display: -webkit-flex;
-    -webkit-flex: 1 1 auto;
+    display: flex;
+    flex: 1 1 auto;
     height: 8px;
     margin: 0 15px 0 0;
     padding: 0;
@@ -191,11 +190,11 @@
 
 audio::-webkit-media-controls-volume-slider, video::-webkit-media-controls-volume-slider {
     -webkit-appearance: media-volume-slider;
-    display: -webkit-flex;
+    display: flex;
     /* The 1.9 value was empirically chosen to match old-flexbox behaviour
      * and be aesthetically pleasing.
      */
-    -webkit-flex: 1 1.9 auto;
+    flex: 1 1.9 auto;
     height: 8px;
     max-width: 70px;
     margin: 0 15px 0 0;
@@ -211,9 +210,9 @@
    https://bugs.webkit.org/show_bug.cgi?id=62218
 */
 input[type="range"]::-webkit-media-slider-container {
-    display: -webkit-flex;
-    -webkit-align-items: center;
-    -webkit-flex-direction: row; /* This property is updated by C++ code. */
+    display: flex;
+    align-items: center;
+    flex-direction: row; /* This property is updated by C++ code. */
     box-sizing: border-box;
     height: 100%;
     width: 100%;
@@ -234,7 +233,7 @@
 
 audio::-webkit-media-controls-seek-back-button, video::-webkit-media-controls-seek-back-button {
     -webkit-appearance: media-seek-back-button;
-    display: -webkit-flex;
+    display: flex;
     width: 16px;
     height: 16px;
     background-color: initial;
@@ -244,7 +243,7 @@
 
 audio::-webkit-media-controls-seek-forward-button, video::-webkit-media-controls-seek-forward-button {
     -webkit-appearance: media-seek-forward-button;
-    display: -webkit-flex;
+    display: flex;
     width: 16px;
     height: 16px;
     background-color: initial;
@@ -254,8 +253,8 @@
 
 audio::-webkit-media-controls-fullscreen-button, video::-webkit-media-controls-fullscreen-button {
     -webkit-appearance: media-enter-fullscreen-button;
-    display: -webkit-flex;
-    -webkit-flex: none;
+    display: flex;
+    flex: none;
     border: none;
     box-sizing: border-box;
     width: 30px;
@@ -284,8 +283,8 @@
 
 audio::-webkit-media-controls-toggle-closed-captions-button, video::-webkit-media-controls-toggle-closed-captions-button {
     -webkit-appearance: media-toggle-closed-captions-button;
-    display: -webkit-flex;
-    -webkit-flex: none;
+    display: flex;
+    flex: none;
     border: none;
     box-sizing: border-box;
     width: 30px;
@@ -337,7 +336,7 @@
     -webkit-user-select: none;
     word-break: break-word;
 
-    -webkit-flex: 1 1;
+    flex: 1 1;
 }
 
 video::cue {
@@ -361,9 +360,9 @@
 video::-webkit-media-text-track-region-container {
     position: relative;
 
-    display: -webkit-flex;
-    -webkit-flex-flow: column;
-    -webkit-flex-direction: column;
+    display: flex;
+    flex-flow: column;
+    flex-direction: column;
 }
 
 video::-webkit-media-text-track-region-container.scrolling {
@@ -376,7 +375,7 @@
     overflow: hidden;
     white-space: pre-wrap;
     -webkit-box-sizing: border-box;
-    -webkit-flex: 0 0 auto;
+    flex: 0 0 auto;
 }
 
 video::cue(:future) {
diff --git a/Source/core/css/mediaControlsAndroid.css b/Source/core/css/mediaControlsAndroid.css
index 1849402..69bdd8d 100644
--- a/Source/core/css/mediaControlsAndroid.css
+++ b/Source/core/css/mediaControlsAndroid.css
@@ -24,6 +24,8 @@
 
 /* Media controls for Chromium on Android */
 
+/* WARNING: This css file can only style <audio> and <video> elements */
+
 audio {
     height: 35px;
 }
@@ -37,12 +39,12 @@
 }
 
 video::-webkit-media-controls-overlay-enclosure {
-    display: -webkit-flex;
+    display: flex;
     position: relative;
-    -webkit-flex-direction: column;
-    -webkit-justify-content: flex-end;
-    -webkit-align-items: center;
-    -webkit-flex: 1 1;
+    flex-direction: column;
+    justify-content: flex-end;
+    align-items: center;
+    flex: 1 1;
     width: 100%;
     max-width: 800px;
     text-indent: 0;
@@ -61,7 +63,7 @@
 
 video::-webkit-media-controls-overlay-play-button {
     -webkit-appearance: media-overlay-play-button;
-    display: -webkit-flex;
+    display: flex;
     position: absolute;
     top: 50%;
     left: 50%;
diff --git a/Source/core/css/resolver/AnimatedStyleBuilder.cpp b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
index 9524115..f1388f8 100644
--- a/Source/core/css/resolver/AnimatedStyleBuilder.cpp
+++ b/Source/core/css/resolver/AnimatedStyleBuilder.cpp
@@ -38,12 +38,14 @@
 #include "core/animation/AnimatableTransform.h"
 #include "core/animation/AnimatableUnknown.h"
 #include "core/animation/AnimatableValue.h"
+#include "core/animation/AnimatableVisibility.h"
 #include "core/animation/css/CSSAnimations.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/StyleResolverState.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "wtf/MathExtras.h"
+#include "wtf/TypeTraits.h"
 
 namespace WebCore {
 
@@ -64,6 +66,22 @@
     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);
+    return clampTo<T>(round(toAnimatableNumber(value)->toDouble()));
+}
+
 LengthBox animatableValueToLengthBox(const AnimatableValue* value, const StyleResolverState& state)
 {
     const AnimatableLengthBox* animatableLengthBox = toAnimatableLengthBox(value);
@@ -94,7 +112,7 @@
         style->setVisitedLinkBorderBottomColor(toAnimatableColor(value)->visitedLinkColor());
         return;
     case CSSPropertyBorderBottomWidth:
-        style->setBorderBottomWidth(animatableValueToUnsigned(value));
+        style->setBorderBottomWidth(animatableValueRoundClampTo<unsigned>(value));
         return;
     case CSSPropertyBorderImageOutset:
         style->setBorderImageOutset(animatableValueToLengthBox(value, state));
@@ -113,21 +131,21 @@
         style->setVisitedLinkBorderLeftColor(toAnimatableColor(value)->visitedLinkColor());
         return;
     case CSSPropertyBorderLeftWidth:
-        style->setBorderLeftWidth(animatableValueToUnsigned(value));
+        style->setBorderLeftWidth(animatableValueRoundClampTo<unsigned>(value));
         return;
     case CSSPropertyBorderRightColor:
         style->setBorderRightColor(toAnimatableColor(value)->color());
         style->setVisitedLinkBorderRightColor(toAnimatableColor(value)->visitedLinkColor());
         return;
     case CSSPropertyBorderRightWidth:
-        style->setBorderRightWidth(animatableValueToUnsigned(value));
+        style->setBorderRightWidth(animatableValueRoundClampTo<unsigned>(value));
         return;
     case CSSPropertyBorderTopColor:
         style->setBorderTopColor(toAnimatableColor(value)->color());
         style->setVisitedLinkBorderTopColor(toAnimatableColor(value)->visitedLinkColor());
         return;
     case CSSPropertyBorderTopWidth:
-        style->setBorderTopWidth(animatableValueToUnsigned(value));
+        style->setBorderTopWidth(animatableValueRoundClampTo<unsigned>(value));
         return;
     case CSSPropertyBottom:
         style->setBottom(animatableValueToLength(value, state));
@@ -179,6 +197,12 @@
         style->setOutlineColor(toAnimatableColor(value)->color());
         style->setVisitedLinkOutlineColor(toAnimatableColor(value)->visitedLinkColor());
         return;
+    case CSSPropertyOutlineOffset:
+        style->setOutlineOffset(animatableValueToInt(value));
+        return;
+    case CSSPropertyOutlineWidth:
+        style->setOutlineWidth(animatableValueRoundClampTo<unsigned short>(value));
+        return;
     case CSSPropertyPaddingBottom:
         style->setPaddingBottom(animatableValueToLength(value, state));
         return;
@@ -241,6 +265,9 @@
     case CSSPropertyWidth:
         style->setWidth(animatableValueToLength(value, state));
         return;
+    case CSSPropertyVisibility:
+        style->setVisibility(toAnimatableVisibility(value)->visibility());
+        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/ElementResolveContext.cpp b/Source/core/css/resolver/ElementResolveContext.cpp
index b9973b3..00f9315 100644
--- a/Source/core/css/resolver/ElementResolveContext.cpp
+++ b/Source/core/css/resolver/ElementResolveContext.cpp
@@ -31,7 +31,7 @@
 
 ElementResolveContext::ElementResolveContext(Element* element)
     : m_element(element)
-    , m_elementLinkState(element ? element->document()->visitedLinkState()->determineLinkState(element) : NotInsideLink)
+    , m_elementLinkState(element ? element->document().visitedLinkState()->determineLinkState(element) : NotInsideLink)
     , m_distributedToInsertionPoint(false)
     , m_resetStyleInheritance(false)
 {
@@ -40,9 +40,11 @@
     m_distributedToInsertionPoint = parentDetails.insertionPoint();
     m_resetStyleInheritance = parentDetails.resetStyleInheritance();
 
-    Node* documentElement = document()->documentElement();
-    RenderStyle* documentStyle = document()->renderStyle();
+    Node* documentElement = document().documentElement();
+    RenderStyle* documentStyle = document().renderStyle();
     m_rootElementStyle = documentElement && element != documentElement ? documentElement->renderStyle() : documentStyle;
+    if (!m_rootElementStyle)
+        m_rootElementStyle = documentStyle;
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/ElementResolveContext.h b/Source/core/css/resolver/ElementResolveContext.h
index 4ab5292..ebbe1cf 100644
--- a/Source/core/css/resolver/ElementResolveContext.h
+++ b/Source/core/css/resolver/ElementResolveContext.h
@@ -47,8 +47,8 @@
 
     explicit ElementResolveContext(Element*);
 
-    Document* document() const { return m_element->document(); }
-    bool isDocumentElement() const { return m_element && m_element == m_element->document()->documentElement(); }
+    Document& document() const { return m_element->document(); }
+    bool isDocumentElement() const { return m_element && m_element == m_element->document().documentElement(); }
 
     Element* element() const { return m_element; }
     const ContainerNode* parentNode() const { return m_parentNode; }
diff --git a/Source/core/css/resolver/ElementStyleResources.cpp b/Source/core/css/resolver/ElementStyleResources.cpp
index ab9b0c3..f99919a 100644
--- a/Source/core/css/resolver/ElementStyleResources.cpp
+++ b/Source/core/css/resolver/ElementStyleResources.cpp
@@ -38,14 +38,14 @@
 {
 }
 
-PassRefPtr<StyleImage> ElementStyleResources::styleImage(const TextLinkColors& textLinkColors, CSSPropertyID property, CSSValue* value)
+PassRefPtr<StyleImage> ElementStyleResources::styleImage(const TextLinkColors& textLinkColors, Color currentColor, CSSPropertyID property, CSSValue* value)
 {
     if (value->isImageValue())
         return cachedOrPendingFromValue(property, toCSSImageValue(value));
 
     if (value->isImageGeneratorValue()) {
         if (value->isGradientValue())
-            return generatedOrPendingFromValue(property, static_cast<CSSGradientValue*>(value)->gradientWithStylesResolved(textLinkColors).get());
+            return generatedOrPendingFromValue(property, static_cast<CSSGradientValue*>(value)->gradientWithStylesResolved(textLinkColors, currentColor).get());
         return generatedOrPendingFromValue(property, static_cast<CSSImageGeneratorValue*>(value));
     }
 
diff --git a/Source/core/css/resolver/ElementStyleResources.h b/Source/core/css/resolver/ElementStyleResources.h
index a296abb..08aaede 100644
--- a/Source/core/css/resolver/ElementStyleResources.h
+++ b/Source/core/css/resolver/ElementStyleResources.h
@@ -53,7 +53,7 @@
 public:
     ElementStyleResources();
 
-    PassRefPtr<StyleImage> styleImage(const TextLinkColors&, CSSPropertyID, CSSValue*);
+    PassRefPtr<StyleImage> styleImage(const TextLinkColors&, Color currentColor, CSSPropertyID, CSSValue*);
 
     PassRefPtr<StyleImage> generatedOrPendingFromValue(CSSPropertyID, CSSImageGeneratorValue*);
     PassRefPtr<StyleImage> cachedOrPendingFromValue(CSSPropertyID, CSSImageValue*);
diff --git a/Source/core/css/resolver/FilterOperationResolver.cpp b/Source/core/css/resolver/FilterOperationResolver.cpp
index a409394..39d0f95 100644
--- a/Source/core/css/resolver/FilterOperationResolver.cpp
+++ b/Source/core/css/resolver/FilterOperationResolver.cpp
@@ -233,7 +233,7 @@
     CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType,
     StyleResolverState& state)
 {
-    ResourceFetcher* fetcher = state.document()->fetcher();
+    ResourceFetcher* fetcher = state.document().fetcher();
     KURL vertexShaderURL = vertexShader ? vertexShader->completeURL(fetcher) : KURL();
     KURL fragmentShaderURL = fragmentShader ? fragmentShader->completeURL(fetcher) : KURL();
     RefPtr<StyleCustomFilterProgram> program = StyleCustomFilterProgram::create(vertexShaderURL, vertexShader ? styleShader(vertexShader, state) : 0,
@@ -402,7 +402,7 @@
                 continue;
 
             CSSSVGDocumentValue* svgDocumentValue = static_cast<CSSSVGDocumentValue*>(argument);
-            KURL url = state.document()->completeURL(svgDocumentValue->url());
+            KURL url = state.document().completeURL(svgDocumentValue->url());
 
             RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), url.fragmentIdentifier(), operationType);
             if (SVGURIReference::isExternalURIReference(svgDocumentValue->url(), state.document())) {
@@ -487,11 +487,11 @@
             ShadowValue* item = static_cast<ShadowValue*>(cssValue);
             IntPoint location(item->x->computeLength<int>(style, rootStyle, zoomFactor), item->y->computeLength<int>(style, rootStyle, zoomFactor));
             int blur = item->blur ? item->blur->computeLength<int>(style, rootStyle, zoomFactor) : 0;
-            StyleColor shadowColor;
+            Color shadowColor;
             if (item->color)
-                shadowColor = state.document()->textLinkColors().colorFromPrimitiveValue(item->color.get());
+                shadowColor = state.document().textLinkColors().colorFromPrimitiveValue(item->color.get(), state.style()->visitedDependentColor(CSSPropertyColor));
 
-            operations.operations().append(DropShadowFilterOperation::create(location, blur, shadowColor.isValid() ? shadowColor.color() : Color::transparent, operationType));
+            operations.operations().append(DropShadowFilterOperation::create(location, blur, shadowColor.isValid() ? shadowColor : Color::transparent, operationType));
             break;
         }
         case CSSFilterValue::UnknownFilterOperation:
diff --git a/Source/core/css/resolver/FontBuilder.cpp b/Source/core/css/resolver/FontBuilder.cpp
index 8d3f5aa..684f36d 100644
--- a/Source/core/css/resolver/FontBuilder.cpp
+++ b/Source/core/css/resolver/FontBuilder.cpp
@@ -65,13 +65,13 @@
 {
 }
 
-void FontBuilder::initForStyleResolve(const Document* document, RenderStyle* style, bool useSVGZoomRules)
+void FontBuilder::initForStyleResolve(const Document& document, RenderStyle* style, bool useSVGZoomRules)
 {
     // All documents need to be in a frame (and thus have access to Settings)
     // for style-resolution to make sense.
     // Unfortunately SVG Animations currently violate this: crbug.com/260966
     // ASSERT(m_document->frame());
-    m_document = document;
+    m_document = &document;
     m_useSVGZoomRules = useSVGZoomRules;
     m_style = style;
     m_fontDirty = false;
diff --git a/Source/core/css/resolver/FontBuilder.h b/Source/core/css/resolver/FontBuilder.h
index 78c1740..8aa5d38 100644
--- a/Source/core/css/resolver/FontBuilder.h
+++ b/Source/core/css/resolver/FontBuilder.h
@@ -42,7 +42,7 @@
     FontBuilder();
 
     // FIXME: The name is probably wrong, but matches StyleResolverState callsite for consistency.
-    void initForStyleResolve(const Document*, RenderStyle*, bool useSVGZoomRules);
+    void initForStyleResolve(const Document&, RenderStyle*, bool useSVGZoomRules);
     void clear();
 
     void setInitial(float effectiveZoom);
diff --git a/Source/core/css/resolver/MatchedPropertiesCache.cpp b/Source/core/css/resolver/MatchedPropertiesCache.cpp
index 1b0946d..1736795 100644
--- a/Source/core/css/resolver/MatchedPropertiesCache.cpp
+++ b/Source/core/css/resolver/MatchedPropertiesCache.cpp
@@ -35,6 +35,24 @@
 
 namespace WebCore {
 
+void CachedMatchedProperties::set(const RenderStyle* style, const RenderStyle* parentStyle, const MatchResult& matchResult)
+{
+    matchedProperties.append(matchResult.matchedProperties);
+    ranges = matchResult.ranges;
+
+    // Note that we don't cache the original RenderStyle instance. It may be further modified.
+    // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
+    this->renderStyle = RenderStyle::clone(style);
+    this->parentRenderStyle = RenderStyle::clone(parentStyle);
+}
+
+void CachedMatchedProperties::clear()
+{
+    matchedProperties.clear();
+    renderStyle = 0;
+    parentRenderStyle = 0;
+}
+
 MatchedPropertiesCache::MatchedPropertiesCache()
     : m_additionsSinceLastSweep(0)
     , m_sweepTimer(this, &MatchedPropertiesCache::sweep)
@@ -48,20 +66,21 @@
     Cache::iterator it = m_cache.find(hash);
     if (it == m_cache.end())
         return 0;
-    CachedMatchedProperties& cacheItem = it->value;
+    CachedMatchedProperties* cacheItem = it->value.get();
+    ASSERT(cacheItem);
 
     size_t size = matchResult.matchedProperties.size();
-    if (size != cacheItem.matchedProperties.size())
+    if (size != cacheItem->matchedProperties.size())
         return 0;
-    if (cacheItem.renderStyle->insideLink() != styleResolverState.style()->insideLink())
+    if (cacheItem->renderStyle->insideLink() != styleResolverState.style()->insideLink())
         return 0;
     for (size_t i = 0; i < size; ++i) {
-        if (matchResult.matchedProperties[i] != cacheItem.matchedProperties[i])
+        if (matchResult.matchedProperties[i] != cacheItem->matchedProperties[i])
             return 0;
     }
-    if (cacheItem.ranges != matchResult.ranges)
+    if (cacheItem->ranges != matchResult.ranges)
         return 0;
-    return &cacheItem;
+    return cacheItem;
 }
 
 void MatchedPropertiesCache::add(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult)
@@ -74,14 +93,15 @@
     }
 
     ASSERT(hash);
-    CachedMatchedProperties cacheItem;
-    cacheItem.matchedProperties.append(matchResult.matchedProperties);
-    cacheItem.ranges = matchResult.ranges;
-    // Note that we don't cache the original RenderStyle instance. It may be further modified.
-    // The RenderStyle in the cache is really just a holder for the substructures and never used as-is.
-    cacheItem.renderStyle = RenderStyle::clone(style);
-    cacheItem.parentRenderStyle = RenderStyle::clone(parentStyle);
-    m_cache.add(hash, cacheItem);
+    Cache::AddResult addResult = m_cache.add(hash, nullptr);
+    if (addResult.isNewEntry)
+        addResult.iterator->value = adoptPtr(new CachedMatchedProperties);
+
+    CachedMatchedProperties* cacheItem = addResult.iterator->value.get();
+    if (!addResult.isNewEntry)
+        cacheItem->clear();
+
+    cacheItem->set(style, parentStyle, matchResult);
 }
 
 void MatchedPropertiesCache::clear()
@@ -98,7 +118,8 @@
     Cache::iterator it = m_cache.begin();
     Cache::iterator end = m_cache.end();
     for (; it != end; ++it) {
-        Vector<MatchedProperties>& matchedProperties = it->value.matchedProperties;
+        CachedMatchedProperties* cacheItem = it->value.get();
+        Vector<MatchedProperties>& matchedProperties = cacheItem->matchedProperties;
         for (size_t i = 0; i < matchedProperties.size(); ++i) {
             if (matchedProperties[i].properties->hasOneRef()) {
                 toRemove.append(it->key);
@@ -115,7 +136,7 @@
 bool MatchedPropertiesCache::isCacheable(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle)
 {
     // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching.
-    if (element == element->document()->documentElement() && element->document()->writingModeSetOnDocumentElement())
+    if (element == element->document().documentElement() && element->document().writingModeSetOnDocumentElement())
         return false;
     if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique()))
         return false;
@@ -125,6 +146,8 @@
         return false;
     if (style->writingMode() != RenderStyle::initialWritingMode())
         return false;
+    if (style->hasCurrentColor())
+        return false;
     // The cache assumes static knowledge about which properties are inherited.
     if (parentStyle->hasExplicitlyInheritedProperties())
         return false;
diff --git a/Source/core/css/resolver/MatchedPropertiesCache.h b/Source/core/css/resolver/MatchedPropertiesCache.h
index 9f732c5..f1ccc3d 100644
--- a/Source/core/css/resolver/MatchedPropertiesCache.h
+++ b/Source/core/css/resolver/MatchedPropertiesCache.h
@@ -40,6 +40,9 @@
     MatchRanges ranges;
     RefPtr<RenderStyle> renderStyle;
     RefPtr<RenderStyle> parentRenderStyle;
+
+    void set(const RenderStyle*, const RenderStyle* parentStyle, const MatchResult&);
+    void clear();
 };
 
 class MatchedPropertiesCache {
@@ -61,7 +64,7 @@
 
     unsigned m_additionsSinceLastSweep;
 
-    typedef HashMap<unsigned, CachedMatchedProperties> Cache;
+    typedef HashMap<unsigned, OwnPtr<CachedMatchedProperties> > Cache;
     Cache m_cache;
 
     Timer<MatchedPropertiesCache> m_sweepTimer;
diff --git a/Source/core/css/resolver/ScopedStyleResolver.cpp b/Source/core/css/resolver/ScopedStyleResolver.cpp
index 261d458..cb60fdc 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -41,9 +41,8 @@
 
 namespace WebCore {
 
-ScopedStyleResolver* ScopedStyleTree::ensureScopedStyleResolver(const ContainerNode* scopingNode)
+ScopedStyleResolver* ScopedStyleTree::ensureScopedStyleResolver(const ContainerNode& scopingNode)
 {
-    ASSERT(scopingNode);
     bool isNewEntry;
     ScopedStyleResolver* scopedStyleResolver = addScopedStyleResolver(scopingNode, isNewEntry);
     if (isNewEntry)
@@ -51,24 +50,24 @@
     return scopedStyleResolver;
 }
 
-ScopedStyleResolver* ScopedStyleTree::scopedStyleResolverFor(const ContainerNode* scopingNode)
+ScopedStyleResolver* ScopedStyleTree::scopedStyleResolverFor(const ContainerNode& scopingNode)
 {
-    if (!scopingNode->hasScopedHTMLStyleChild()
-        && !(scopingNode->isElementNode() && toElement(scopingNode)->shadow())
-        && !scopingNode->isDocumentNode()
-        && !scopingNode->isShadowRoot())
+    if (!scopingNode.hasScopedHTMLStyleChild()
+        && !(scopingNode.isElementNode() && toElement(scopingNode).shadow())
+        && !scopingNode.isDocumentNode()
+        && !scopingNode.isShadowRoot())
         return 0;
-    HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.find(scopingNode);
+    HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.find(&scopingNode);
     return it != m_authorStyles.end() ? it->value.get() : 0;
 }
 
-ScopedStyleResolver* ScopedStyleTree::addScopedStyleResolver(const ContainerNode* scopingNode, bool& isNewEntry)
+ScopedStyleResolver* ScopedStyleTree::addScopedStyleResolver(const ContainerNode& scopingNode, bool& isNewEntry)
 {
-    HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::AddResult addResult = m_authorStyles.add(scopingNode, nullptr);
+    HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::AddResult addResult = m_authorStyles.add(&scopingNode, nullptr);
 
     if (addResult.isNewEntry) {
         addResult.iterator->value = ScopedStyleResolver::create(scopingNode);
-        if (!scopingNode || scopingNode->isDocumentNode())
+        if (scopingNode.isDocumentNode())
             m_scopedResolverForDocument = addResult.iterator->value.get();
     }
     isNewEntry = addResult.isNewEntry;
@@ -78,21 +77,20 @@
 void ScopedStyleTree::setupScopedStylesTree(ScopedStyleResolver* target)
 {
     ASSERT(target);
-    ASSERT(target->scopingNode());
 
-    const ContainerNode* scopingNode = target->scopingNode();
+    const ContainerNode& scopingNode = target->scopingNode();
 
     // Since StyleResolver creates RuleSets according to styles' document
     // order, a parent of the given ScopedRuleData has been already
     // prepared.
-    for (const ContainerNode* node = scopingNode->parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode()) {
-        if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(node)) {
+    for (const ContainerNode* node = scopingNode.parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode()) {
+        if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(*node)) {
             target->setParent(scopedResolver);
             break;
         }
         if (node->isDocumentNode()) {
             bool dummy;
-            ScopedStyleResolver* scopedResolver = addScopedStyleResolver(node, dummy);
+            ScopedStyleResolver* scopedResolver = addScopedStyleResolver(*node, dummy);
             target->setParent(scopedResolver);
             setupScopedStylesTree(scopedResolver);
             break;
@@ -106,7 +104,7 @@
     for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
         if (it->value == target)
             continue;
-        if (it->value->parent() == target->parent() && scopingNode->containsIncludingShadowDOM(it->key))
+        if (it->value->parent() == target->parent() && scopingNode.containsIncludingShadowDOM(it->key))
             it->value->setParent(target);
     }
 }
@@ -133,7 +131,7 @@
     // Adding scoped resolver for active shadow roots for shadow host styling.
     for (ShadowRoot* shadowRoot = shadow->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
         if (shadowRoot->hasScopedHTMLStyleChild()) {
-            if (ScopedStyleResolver* resolver = scopedStyleResolverFor(shadowRoot))
+            if (ScopedStyleResolver* resolver = scopedStyleResolverFor(*shadowRoot))
                 resolvers.append(resolver);
         }
         if (!shadowRoot->containsShadowElements())
@@ -143,12 +141,12 @@
 
 void ScopedStyleTree::resolveScopedKeyframesRules(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
 {
-    Document* document = element->document();
-    TreeScope* treeScope = element->treeScope();
-    bool applyAuthorStyles = treeScope->applyAuthorStyles();
+    Document& document = element->document();
+    TreeScope& treeScope = element->treeScope();
+    bool applyAuthorStyles = treeScope.applyAuthorStyles();
 
     for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent()) {
-        if (scopedResolver->treeScope() == treeScope || (applyAuthorStyles && scopedResolver->treeScope() == document))
+        if (&scopedResolver->treeScope() == &treeScope || (applyAuthorStyles && &scopedResolver->treeScope() == &document))
             resolvers.append(scopedResolver);
     }
 }
@@ -156,7 +154,7 @@
 inline ScopedStyleResolver* ScopedStyleTree::enclosingScopedStyleResolverFor(const ContainerNode* scopingNode)
 {
     for (; scopingNode; scopingNode = scopingNode->parentOrShadowHostNode()) {
-        if (ScopedStyleResolver* scopedStyleResolver = scopedStyleResolverFor(scopingNode))
+        if (ScopedStyleResolver* scopedStyleResolver = scopedStyleResolverFor(*scopingNode))
             return scopedStyleResolver;
     }
     return 0;
@@ -168,30 +166,30 @@
     m_cache.nodeForScopedStyles = scopingNode;
 }
 
-void ScopedStyleTree::pushStyleCache(const ContainerNode* scopingNode, const ContainerNode* parent)
+void ScopedStyleTree::pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent)
 {
     if (m_authorStyles.isEmpty())
         return;
 
     if (!cacheIsValid(parent)) {
-        resolveStyleCache(scopingNode);
+        resolveStyleCache(&scopingNode);
         return;
     }
 
     ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(scopingNode);
     if (scopedResolver)
         m_cache.scopedResolver = scopedResolver;
-    m_cache.nodeForScopedStyles = scopingNode;
+    m_cache.nodeForScopedStyles = &scopingNode;
 }
 
-void ScopedStyleTree::popStyleCache(const ContainerNode* scopingNode)
+void ScopedStyleTree::popStyleCache(const ContainerNode& scopingNode)
 {
-    if (!cacheIsValid(scopingNode))
+    if (!cacheIsValid(&scopingNode))
         return;
 
-    if (m_cache.scopedResolver && m_cache.scopedResolver->scopingNode() == scopingNode)
+    if (m_cache.scopedResolver && &m_cache.scopedResolver->scopingNode() == &scopingNode)
         m_cache.scopedResolver = m_cache.scopedResolver->parent();
-    m_cache.nodeForScopedStyles = scopingNode->parentOrShadowHostNode();
+    m_cache.nodeForScopedStyles = scopingNode.parentOrShadowHostNode();
 }
 
 void ScopedStyleTree::collectFeaturesTo(RuleFeatureSet& features)
@@ -214,7 +212,7 @@
     if (!scopingNode || scopingNode->isDocumentNode())
         return;
 
-    ScopedStyleResolver* resolverRemoved = scopedStyleResolverFor(scopingNode);
+    ScopedStyleResolver* resolverRemoved = scopedStyleResolverFor(*scopingNode);
     if (!resolverRemoved)
         return;
 
@@ -251,7 +249,7 @@
 {
     if (!m_authorStyle)
         m_authorStyle = RuleSet::create();
-    m_authorStyle->addRulesFromSheet(sheet, medium, resolver, m_scopingNode);
+    m_authorStyle->addRulesFromSheet(sheet, medium, resolver, &m_scopingNode);
 }
 
 inline RuleSet* ScopedStyleResolver::ensureAtHostRuleSetFor(const ShadowRoot* shadowRoot)
@@ -357,10 +355,10 @@
     // FIXME: Determine tree position.
     CascadeScope cascadeScope = ignoreCascadeScope;
 
-    if (m_atHostRules.isEmpty() || !m_scopingNode->isElementNode())
+    if (m_atHostRules.isEmpty() || !m_scopingNode.isElementNode())
         return;
 
-    ElementShadow* shadow = toElement(m_scopingNode)->shadow();
+    ElementShadow* shadow = toElement(m_scopingNode).shadow();
     if (!shadow)
         return;
 
@@ -383,7 +381,7 @@
     collector.setBehaviorAtBoundary(static_cast<SelectorChecker::BehaviorAtBoundary>(SelectorChecker::DoesNotCrossBoundary | SelectorChecker::ScopeContainsLastMatchedElement));
     for (; shadowRoot; shadowRoot = shadowRoot->youngerShadowRoot()) {
         if (RuleSet* ruleSet = atHostRuleSetFor(shadowRoot))
-            collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, m_scopingNode), ruleRange, cascadeScope);
+            collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, &m_scopingNode), ruleRange, cascadeScope);
     }
 
     collector.sortAndTransferMatchedRules();
@@ -402,14 +400,14 @@
     if (!m_authorStyle)
         return;
 
-    const ContainerNode* scopingNode = m_scopingNode;
+    const ContainerNode* scopingNode = &m_scopingNode;
     unsigned behaviorAtBoundary = SelectorChecker::DoesNotCrossBoundary;
 
     if (!applyAuthorStyles)
         behaviorAtBoundary |= SelectorChecker::ScopeContainsLastMatchedElement;
 
-    if (m_scopingNode->isShadowRoot()) {
-        scopingNode = toShadowRoot(m_scopingNode)->host();
+    if (m_scopingNode.isShadowRoot()) {
+        scopingNode = toShadowRoot(m_scopingNode).host();
         behaviorAtBoundary |= SelectorChecker::ScopeIsShadowHost;
     }
 
@@ -423,14 +421,14 @@
 void ScopedStyleResolver::matchPageRules(PageRuleCollector& collector)
 {
     // Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
-    ASSERT(m_scopingNode->isDocumentNode());
+    ASSERT(m_scopingNode.isDocumentNode());
     collector.matchPageRules(m_authorStyle.get());
 }
 
 void ScopedStyleResolver::collectViewportRulesTo(StyleResolver* resolver) const
 {
     if (m_authorStyle)
-        resolver->collectViewportRules(m_authorStyle.get());
+        resolver->collectViewportRules(m_authorStyle.get(), StyleResolver::AuthorOrigin);
 }
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/ScopedStyleResolver.h b/Source/core/css/resolver/ScopedStyleResolver.h
index fa06133..5372edd 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.h
+++ b/Source/core/css/resolver/ScopedStyleResolver.h
@@ -50,12 +50,12 @@
 class ScopedStyleResolver {
     WTF_MAKE_NONCOPYABLE(ScopedStyleResolver); WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<ScopedStyleResolver> create(const ContainerNode* scopingNode) { return adoptPtr(new ScopedStyleResolver(scopingNode)); }
+    static PassOwnPtr<ScopedStyleResolver> create(const ContainerNode& scopingNode) { return adoptPtr(new ScopedStyleResolver(scopingNode)); }
 
     static const ContainerNode* scopingNodeFor(const CSSStyleSheet*);
 
-    const ContainerNode* scopingNode() const { return m_scopingNode; }
-    const TreeScope* treeScope() const { return m_scopingNode->treeScope(); }
+    const ContainerNode& scopingNode() const { return m_scopingNode; }
+    const TreeScope& treeScope() const { return m_scopingNode.treeScope(); }
     void prepareEmptyRuleSet() { m_authorStyle = RuleSet::create(); }
     void setParent(ScopedStyleResolver* newParent) { m_parent = newParent; }
     ScopedStyleResolver* parent() { return m_parent; }
@@ -79,13 +79,12 @@
     void collectViewportRulesTo(StyleResolver*) const;
 
 private:
-    ScopedStyleResolver() : m_scopingNode(0), m_parent(0) { }
-    ScopedStyleResolver(const ContainerNode* scopingNode) : m_scopingNode(scopingNode), m_parent(0) { }
+    explicit ScopedStyleResolver(const ContainerNode& scopingNode) : m_scopingNode(scopingNode), m_parent(0) { }
 
     RuleSet* ensureAtHostRuleSetFor(const ShadowRoot*);
     RuleSet* atHostRuleSetFor(const ShadowRoot*) const;
 
-    const ContainerNode* m_scopingNode;
+    const ContainerNode& m_scopingNode;
     ScopedStyleResolver* m_parent;
 
     OwnPtr<RuleSet> m_authorStyle;
@@ -100,9 +99,9 @@
 public:
     ScopedStyleTree() : m_scopedResolverForDocument(0), m_buildInDocumentOrder(true) { }
 
-    ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode* scopingNode);
-    ScopedStyleResolver* scopedStyleResolverFor(const ContainerNode* scopingNode);
-    ScopedStyleResolver* addScopedStyleResolver(const ContainerNode* scopingNode, bool& isNewEntry);
+    ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode& scopingNode);
+    ScopedStyleResolver* scopedStyleResolverFor(const ContainerNode& scopingNode);
+    ScopedStyleResolver* addScopedStyleResolver(const ContainerNode& scopingNode, bool& isNewEntry);
     void clear();
 
     // for fast-path.
@@ -116,8 +115,8 @@
 
     void remove(const ContainerNode* scopingNode);
 
-    void pushStyleCache(const ContainerNode* scopingNode, const ContainerNode* parent);
-    void popStyleCache(const ContainerNode* scopingNode);
+    void pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent);
+    void popStyleCache(const ContainerNode& scopingNode);
 
     void collectFeaturesTo(RuleFeatureSet& features);
     void setBuildInDocumentOrder(bool enabled) { m_buildInDocumentOrder = enabled; }
diff --git a/Source/core/css/resolver/SharedStyleFinder.cpp b/Source/core/css/resolver/SharedStyleFinder.cpp
index 781998a..aad32e7 100644
--- a/Source/core/css/resolver/SharedStyleFinder.cpp
+++ b/Source/core/css/resolver/SharedStyleFinder.cpp
@@ -36,6 +36,7 @@
 #include "core/dom/ContainerNode.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
+#include "core/dom/ElementTraversal.h"
 #include "core/dom/FullscreenElementStack.h"
 #include "core/dom/Node.h"
 #include "core/dom/NodeRenderStyle.h"
@@ -55,64 +56,11 @@
 
 using namespace HTMLNames;
 
-static const unsigned cStyleSearchThreshold = 10;
-static const unsigned cStyleSearchLevelThreshold = 10;
-
 static inline bool parentElementPreventsSharing(const Element* parentElement)
 {
-    if (!parentElement)
-        return false;
     return parentElement->hasFlagsSetDuringStylingOfChildren();
 }
 
-Node* SharedStyleFinder::locateCousinList(Element* parent, unsigned& visitedNodeCount) const
-{
-    if (visitedNodeCount >= cStyleSearchThreshold * cStyleSearchLevelThreshold)
-        return 0;
-    if (!parent || !parent->isStyledElement())
-        return 0;
-    if (parent->hasScopedHTMLStyleChild())
-        return 0;
-    if (parent->inlineStyle())
-        return 0;
-    if (parent->isSVGElement() && toSVGElement(parent)->animatedSMILStyleProperties())
-        return 0;
-    if (parent->hasID() && m_features.idsInRules.contains(parent->idForStyleResolution().impl()))
-        return 0;
-    if (isShadowHost(parent) && parent->shadow()->containsActiveStyles())
-        return 0;
-
-    RenderStyle* parentStyle = parent->renderStyle();
-    unsigned subcount = 0;
-    Node* thisCousin = parent;
-    Node* currentNode = parent->previousSibling();
-
-    // Reserve the tries for this level. This effectively makes sure that the algorithm
-    // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
-    visitedNodeCount += cStyleSearchThreshold;
-    while (thisCousin) {
-        while (currentNode) {
-            ++subcount;
-            if (!currentNode->hasScopedHTMLStyleChild() && currentNode->renderStyle() == parentStyle && currentNode->lastChild()
-                && currentNode->isElementNode() && !parentElementPreventsSharing(toElement(currentNode))
-                && !toElement(currentNode)->shadow()
-                ) {
-                // Adjust for unused reserved tries.
-                visitedNodeCount -= cStyleSearchThreshold - subcount;
-                return currentNode->lastChild();
-            }
-            if (subcount >= cStyleSearchThreshold)
-                return 0;
-            currentNode = currentNode->previousSibling();
-        }
-        currentNode = locateCousinList(thisCousin->parentElement(), visitedNodeCount);
-        thisCousin = currentNode;
-    }
-
-    return 0;
-}
-
-
 bool SharedStyleFinder::canShareStyleWithControl(const ElementResolveContext& context, Element* element) const
 {
     if (!element->hasTagName(inputTag) || !context.element()->hasTagName(inputTag))
@@ -142,7 +90,7 @@
     if (element->isDefaultButtonForForm() != context.element()->isDefaultButtonForForm())
         return false;
 
-    if (context.document()->containsValidityStyleRules()) {
+    if (context.document().containsValidityStyleRules()) {
         bool willValidate = element->willValidate();
 
         if (willValidate != context.element()->willValidate())
@@ -213,9 +161,16 @@
 
 bool SharedStyleFinder::canShareStyleWithElement(const ElementResolveContext& context, Element* element) const
 {
+    if (context.element() == element)
+        return false;
+    Element* parent = element->parentElement();
     RenderStyle* style = element->renderStyle();
     if (!style)
         return false;
+    if (!parent)
+        return false;
+    if (context.element()->parentElement()->renderStyle() != parent->renderStyle())
+        return false;
     if (style->unique())
         return false;
     if (style->hasUniquePseudoStyle())
@@ -238,7 +193,7 @@
         return false;
     if (element->shadowPseudoId() != context.element()->shadowPseudoId())
         return false;
-    if (element == element->document()->cssTarget())
+    if (element == element->document().cssTarget())
         return false;
     if (!sharingCandidateHasIdenticalStyleAffectingAttributes(context, element))
         return false;
@@ -290,31 +245,33 @@
     if (element->isWebVTTElement() && context.element()->isWebVTTElement() && toWebVTTElement(element)->isPastNode() != toWebVTTElement(context.element())->isPastNode())
         return false;
 
-    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(context.document())) {
+    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(&context.document())) {
         if (element == fullscreen->webkitCurrentFullScreenElement() || context.element() == fullscreen->webkitCurrentFullScreenElement())
             return false;
     }
 
+    if (context.element()->parentElement() != parent) {
+        if (!parent->isStyledElement())
+            return false;
+        if (parent->hasScopedHTMLStyleChild())
+            return false;
+        if (parent->inlineStyle())
+            return false;
+        if (parent->isSVGElement() && toSVGElement(parent)->animatedSMILStyleProperties())
+            return false;
+        if (parent->hasID() && m_features.idsInRules.contains(parent->idForStyleResolution().impl()))
+            return false;
+        if (parentElementPreventsSharing(parent))
+            return false;
+    }
+
     return true;
 }
 
-inline Element* SharedStyleFinder::findSiblingForStyleSharing(const ElementResolveContext& context, Node* node, unsigned& count) const
-{
-    for (; node; node = node->previousSibling()) {
-        if (!node->isStyledElement())
-            continue;
-        if (canShareStyleWithElement(context, toElement(node)))
-            break;
-        if (count++ == cStyleSearchThreshold)
-            return 0;
-    }
-    return toElement(node);
-}
-
 #ifdef STYLE_STATS
 Element* SharedStyleFinder::searchDocumentForSharedStyle(const ElementResolveContext& context) const
 {
-    for (Element* element = context.element()->document()->documentElement(); element; element = ElementTraversal::next(element)) {
+    for (Element* element = context.element()->document().documentElement(); element; element = ElementTraversal::next(element)) {
         if (canShareStyleWithElement(context, element))
             return element;
     }
@@ -322,45 +279,29 @@
 }
 #endif
 
+inline Element* SharedStyleFinder::findElementForStyleSharing(const ElementResolveContext& context) const
+{
+    StyleSharingList& styleSharingList = m_styleResolver->styleSharingList();
+    for (StyleSharingList::iterator it = styleSharingList.begin(); it != styleSharingList.end(); ++it) {
+        if (!canShareStyleWithElement(context, it->get()))
+            continue;
+        Element* element = it->get();
+        if (it != styleSharingList.begin()) {
+            // Move the element to the front of the LRU
+            styleSharingList.remove(it);
+            styleSharingList.prepend(element);
+        }
+        return element;
+    }
+    m_styleResolver->addToStyleSharingList(context.element());
+    return 0;
+}
+
 RenderStyle* SharedStyleFinder::locateSharedStyle(const ElementResolveContext& context, RenderStyle* newStyle)
 {
     STYLE_STATS_ADD_SEARCH();
-    if (!context.element() || !context.element()->isStyledElement())
-        return 0;
 
-    // If the element has inline style it is probably unique.
-    if (context.element()->inlineStyle())
-        return 0;
-    if (context.element()->isSVGElement() && toSVGElement(context.element())->animatedSMILStyleProperties())
-        return 0;
-    // Ids stop style sharing if they show up in the stylesheets.
-    if (context.element()->hasID() && m_features.idsInRules.contains(context.element()->idForStyleResolution().impl()))
-        return 0;
-    // Active and hovered elements always make a chain towards the document node
-    // and no siblings or cousins will have the same state.
-    if (context.element()->hovered())
-        return 0;
-    if (context.element()->active())
-        return 0;
-    // There is always only one focused element.
-    if (context.element()->focused())
-        return 0;
-    if (parentElementPreventsSharing(context.element()->parentElement()))
-        return 0;
-    if (context.element()->hasScopedHTMLStyleChild())
-        return 0;
-    if (context.element() == context.document()->cssTarget())
-        return 0;
-    if (elementHasDirectionAuto(context.element()))
-        return 0;
-    if (context.element()->hasActiveAnimations())
-        return 0;
-    // When a dialog is first shown, its style is mutated to center it in the
-    // viewport. So the styles can't be shared since the viewport position and
-    // size may be different each time a dialog is opened.
-    if (context.element()->hasTagName(dialogTag))
-        return 0;
-    if (isShadowHost(context.element()) && context.element()->shadow()->containsActiveStyles())
+    if (!m_styleResolver->supportsStyleSharing(context.element()))
         return 0;
 
     STYLE_STATS_ADD_ELEMENT_ELIGIBLE_FOR_SHARING();
@@ -369,17 +310,7 @@
     // FIXME: This should be an explicit out parameter, instead of a member variable.
     m_elementAffectedByClassRules = context.element() && context.element()->hasClass() && classNamesAffectedByRules(context.element()->classNames());
 
-    // Check previous siblings and their cousins.
-    unsigned count = 0;
-    unsigned visitedNodeCount = 0;
-    Element* shareElement = 0;
-    Node* cousinList = context.element()->previousSibling();
-    while (cousinList) {
-        shareElement = findSiblingForStyleSharing(context, cousinList, count);
-        if (shareElement)
-            break;
-        cousinList = locateCousinList(cousinList->parentElement(), visitedNodeCount);
-    }
+    Element* shareElement = findElementForStyleSharing(context);
 
 #ifdef STYLE_STATS
     // FIXME: these stats don't to into account whether or not sibling/attribute
diff --git a/Source/core/css/resolver/SharedStyleFinder.h b/Source/core/css/resolver/SharedStyleFinder.h
index 7734c36..d407279 100644
--- a/Source/core/css/resolver/SharedStyleFinder.h
+++ b/Source/core/css/resolver/SharedStyleFinder.h
@@ -51,8 +51,7 @@
     RenderStyle* locateSharedStyle(const ElementResolveContext&, RenderStyle* newStyle);
 
 private:
-    Node* locateCousinList(Element* parent, unsigned& visitedNodeCount) const;
-    Element* findSiblingForStyleSharing(const ElementResolveContext&, Node*, unsigned& count) const;
+    Element* findElementForStyleSharing(const ElementResolveContext&) const;
 
     // Only used when we're collecting stats on styles
     Element* searchDocumentForSharedStyle(const ElementResolveContext&) const;
diff --git a/Source/core/css/resolver/StyleAdjuster.cpp b/Source/core/css/resolver/StyleAdjuster.cpp
index ebc03ca..10f572f 100644
--- a/Source/core/css/resolver/StyleAdjuster.cpp
+++ b/Source/core/css/resolver/StyleAdjuster.cpp
@@ -159,6 +159,11 @@
     return display == GRID || display == INLINE_GRID;
 }
 
+static bool parentStyleForcesZIndexToCreateStackingContext(const RenderStyle* parentStyle)
+{
+    return isDisplayFlexibleBox(parentStyle->display()) || isDisplayGridBox(parentStyle->display());
+}
+
 void StyleAdjuster::adjustRenderStyle(RenderStyle* style, RenderStyle* parentStyle, Element *e)
 {
     ASSERT(parentStyle);
@@ -222,7 +227,7 @@
             style->setPosition(AbsolutePosition);
 
         // Absolute/fixed positioned elements, floating elements and the document element need block-like outside display.
-        if (style->hasOutOfFlowPosition() || style->isFloating() || (e && e->document()->documentElement() == e))
+        if (style->hasOutOfFlowPosition() || style->isFloating() || (e && e->document().documentElement() == e))
             style->setDisplay(equivalentBlockDisplay(style->display(), style->isFloating(), !m_useQuirksModeStyles));
 
         // FIXME: Don't support this mutation for pseudo styles like first-letter or first-line, since it's not completely
@@ -258,13 +263,13 @@
     }
 
     // Make sure our z-index value is only applied if the object is positioned.
-    if (style->position() == StaticPosition && !isDisplayFlexibleBox(parentStyle->display()))
+    if (style->position() == StaticPosition && !parentStyleForcesZIndexToCreateStackingContext(parentStyle))
         style->setHasAutoZIndex();
 
     // Auto z-index becomes 0 for the root element and transparent objects. This prevents
     // cases where objects that should be blended as a single unit end up with a non-transparent
     // object wedged in between them. Auto z-index also becomes 0 for objects that specify transforms/masks/reflections.
-    if (style->hasAutoZIndex() && ((e && e->document()->documentElement() == e)
+    if (style->hasAutoZIndex() && ((e && e->document().documentElement() == e)
         || style->opacity() < 1.0f
         || style->hasTransformRelatedProperty()
         || style->hasMask()
@@ -273,7 +278,7 @@
         || style->hasFilter()
         || style->hasBlendMode()
         || style->position() == StickyPosition
-        || (style->position() == FixedPosition && e && e->document()->page() && e->document()->page()->settings().fixedPositionCreatesStackingContext())
+        || (style->position() == FixedPosition && e && e->document().page() && e->document().page()->settings().fixedPositionCreatesStackingContext())
         || isInTopLayer(e, style)
         ))
         style->setZIndex(0);
diff --git a/Source/core/css/resolver/StyleBuilderCustom.cpp b/Source/core/css/resolver/StyleBuilderCustom.cpp
index 5eaec6e..a29932a 100644
--- a/Source/core/css/resolver/StyleBuilderCustom.cpp
+++ b/Source/core/css/resolver/StyleBuilderCustom.cpp
@@ -172,8 +172,8 @@
 {
     state.style()->setDirection(*toCSSPrimitiveValue(value));
     Element* element = state.element();
-    if (element && element == element->document()->documentElement())
-        element->document()->setDirectionSetOnDocumentElement(true);
+    if (element && element == element->document().documentElement())
+        element->document().setDirectionSetOnDocumentElement(true);
 }
 
 static inline bool isValidDisplayValue(StyleResolverState& state, EDisplay displayPropertyValue)
@@ -276,7 +276,7 @@
         lineHeight = RenderStyle::initialLineHeight();
     } else if (primitiveValue->isLength()) {
         double multiplier = state.style()->effectiveZoom();
-        if (Frame* frame = state.document()->frame())
+        if (Frame* frame = state.document().frame())
             multiplier *= frame->textZoomFactor();
         lineHeight = primitiveValue->computeLength<Length>(state.style(), state.rootElementStyle(), multiplier);
     } else if (primitiveValue->isPercentage()) {
@@ -329,7 +329,7 @@
     case 0:
         return;
     case CSSValueAuto:
-        if (Settings* settings = state.document()->settings())
+        if (Settings* settings = state.document().settings())
             r = settings->textAreasAreResizable() ? RESIZE_BOTH : RESIZE_NONE;
         break;
     default:
@@ -645,7 +645,7 @@
             state.style()->setClipPath(ShapeClipPathOperation::create(basicShapeForValue(state, primitiveValue->getShapeValue())));
         } else if (primitiveValue->primitiveType() == CSSPrimitiveValue::CSS_URI) {
             String cssURLValue = primitiveValue->getStringValue();
-            KURL url = state.document()->completeURL(cssURLValue);
+            KURL url = state.document().completeURL(cssURLValue);
             // FIXME: It doesn't work with forward or external SVG references (see https://bugs.webkit.org/show_bug.cgi?id=90405)
             state.style()->setClipPath(ReferenceClipPathOperation::create(cssURLValue, url.fragmentIdentifier()));
         }
@@ -1095,11 +1095,11 @@
     return true;
 }
 
-static Color colorFromSVGColorCSSValue(SVGColor* svgColor, const StyleColor& fgColor)
+static Color colorFromSVGColorCSSValue(SVGColor* svgColor, const Color& fgColor)
 {
     Color color;
     if (svgColor->colorType() == SVGColor::SVG_COLORTYPE_CURRENTCOLOR)
-        color = fgColor.color();
+        color = fgColor;
     else
         color = svgColor->color();
     return color;
@@ -1159,7 +1159,7 @@
     return numberToFloat(primitiveValue, out);
 }
 
-static String fragmentIdentifier(const CSSPrimitiveValue* primitiveValue, Document* document)
+static String fragmentIdentifier(const CSSPrimitiveValue* primitiveValue, Document& document)
 {
     if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_URI)
         return String();
@@ -1266,6 +1266,10 @@
         return;
     }
 
+    CSSPrimitiveValue* primitiveValue = value->isPrimitiveValue() ? toCSSPrimitiveValue(value) : 0;
+    if (primitiveValue && primitiveValue->getValueID() == CSSValueCurrentcolor)
+        state.style()->setHasCurrentColor();
+
     if (isInherit && !state.parentStyle()->hasExplicitlyInheritedProperties() && !CSSProperty::isInheritedProperty(id))
         state.parentStyle()->setHasExplicitlyInheritedProperties();
 
@@ -1314,7 +1318,7 @@
                 CSSValue* item = i.value();
                 if (item->isImageGeneratorValue()) {
                     if (item->isGradientValue())
-                        state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSGradientValue*>(item)->gradientWithStylesResolved(state.document()->textLinkColors()).get()), didSet);
+                        state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSGradientValue*>(item)->gradientWithStylesResolved(state.document().textLinkColors(), state.style()->color()).get()), didSet);
                     else
                         state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
                     didSet = true;
@@ -1494,9 +1498,9 @@
             int blur = item->blur ? item->blur->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor) : 0;
             int spread = item->spread ? item->spread->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor) : 0;
             ShadowStyle shadowStyle = item->style && item->style->getValueID() == CSSValueInset ? Inset : Normal;
-            StyleColor color;
+            Color color;
             if (item->color)
-                color = state.document()->textLinkColors().colorFromPrimitiveValue(item->color.get());
+                color = state.document().textLinkColors().colorFromPrimitiveValue(item->color.get(), state.style()->visitedDependentColor(CSSPropertyColor));
             else if (state.style())
                 color = state.style()->color();
 
@@ -1552,7 +1556,7 @@
         if (!primitiveValue || !primitiveValue->getValueID())
             return;
         state.style()->setDraggableRegionMode(primitiveValue->getValueID() == CSSValueDrag ? DraggableRegionDrag : DraggableRegionNoDrag);
-        state.document()->setHasAnnotatedRegions(true);
+        state.document().setHasAnnotatedRegions(true);
         return;
     }
     case CSSPropertyWebkitTextStrokeWidth: {
@@ -1614,7 +1618,7 @@
         if (!primitiveValue)
             break;
 
-        StyleColor col = state.document()->textLinkColors().colorFromPrimitiveValue(primitiveValue);
+        Color col = state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->visitedDependentColor(CSSPropertyColor));
         state.style()->setTapHighlightColor(col);
         return;
     }
@@ -1682,8 +1686,8 @@
             state.setWritingMode(*primitiveValue);
 
         // FIXME: It is not ok to modify document state while applying style.
-        if (state.element() && state.element() == state.document()->documentElement())
-            state.document()->setWritingModeSetOnDocumentElement(true);
+        if (state.element() && state.element() == state.document().documentElement())
+            state.document().setWritingModeSetOnDocumentElement(true);
         return;
     }
 
@@ -2119,6 +2123,7 @@
     case CSSPropertyColorRendering:
     case CSSPropertyDominantBaseline:
     case CSSPropertyFillRule:
+    case CSSPropertyMaskSourceType:
     case CSSPropertyMaskType:
     case CSSPropertyShapeRendering:
     case CSSPropertyStrokeLinecap:
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index 0840477..cefc546 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -64,7 +64,6 @@
 #include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/ViewportStyleResolver.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/StyleSheetCollections.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ElementShadow.h"
@@ -106,14 +105,14 @@
     return rightToLeftDecl.get();
 }
 
-StyleResolver::StyleResolver(Document* document, bool matchAuthorAndUserStyles)
+StyleResolver::StyleResolver(Document& document, bool matchAuthorAndUserStyles)
     : m_document(document)
     , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
-    , m_fontSelector(CSSFontSelector::create(document))
-    , m_viewportStyleResolver(ViewportStyleResolver::create(document))
-    , m_styleResourceLoader(document->fetcher())
+    , m_fontSelector(CSSFontSelector::create(&document))
+    , m_viewportStyleResolver(ViewportStyleResolver::create(&document))
+    , m_styleResourceLoader(document.fetcher())
 {
-    Element* root = document->documentElement();
+    Element* root = document.documentElement();
 
     CSSDefaultStyleSheets::initDefaultStyle(root);
 
@@ -123,7 +122,7 @@
     // document doesn't have documentElement
     // NOTE: this assumes that element that gets passed to styleForElement -call
     // is always from the document that owns the style selector
-    FrameView* view = document->view();
+    FrameView* view = document.view();
     if (view)
         m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
     else
@@ -133,16 +132,16 @@
         m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
 
     if (m_rootDefaultStyle && view)
-        m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), view->frame(), m_rootDefaultStyle.get()));
+        m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType(), &view->frame(), m_rootDefaultStyle.get()));
 
     m_styleTree.clear();
 
-    StyleSheetCollections* styleSheetCollection = document->styleSheetCollections();
+    StyleSheetCollections* styleSheetCollection = document.styleSheetCollections();
     m_ruleSets.initUserStyle(styleSheetCollection, *m_medium, *this);
 
 #if ENABLE(SVG_FONTS)
-    if (document->svgExtensions()) {
-        const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document->svgExtensions()->svgFontFaceElements();
+    if (document.svgExtensions()) {
+        const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements();
         HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
         for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
             fontSelector()->addFontFaceRule((*it)->fontFaceRule());
@@ -175,16 +174,15 @@
 {
     collectFeatures();
 
-    if (document()->renderer() && document()->renderer()->style())
-        document()->renderer()->style()->font().update(fontSelector());
+    if (document().renderer() && document().renderer()->style())
+        document().renderer()->style()->font().update(fontSelector());
 
-    if (RuntimeEnabledFeatures::cssViewportEnabled())
-        collectViewportRules();
+    collectViewportRules();
 }
 
 void StyleResolver::resetAuthorStyle(const ContainerNode* scopingNode)
 {
-    ScopedStyleResolver* resolver = scopingNode ? m_styleTree.scopedStyleResolverFor(scopingNode) : m_styleTree.scopedStyleResolverForDocument();
+    ScopedStyleResolver* resolver = scopingNode ? m_styleTree.scopedStyleResolverFor(*scopingNode) : m_styleTree.scopedStyleResolverForDocument();
     if (!resolver)
         return;
 
@@ -210,7 +208,8 @@
 
     const ShadowRoot* shadowRoot = toShadowRoot(scopingNode);
     const ContainerNode* shadowHost = shadowRoot->shadowHost();
-    ScopedStyleResolver* resolver = m_styleTree.scopedStyleResolverFor(shadowHost);
+    ASSERT(shadowHost);
+    ScopedStyleResolver* resolver = m_styleTree.scopedStyleResolverFor(*shadowHost);
     if (!resolver)
         return;
 
@@ -235,15 +234,70 @@
 void StyleResolver::collectFeatures()
 {
     m_features.clear();
-    m_ruleSets.collectFeaturesTo(m_features, document()->isViewSource());
+    m_ruleSets.collectFeaturesTo(m_features, document().isViewSource());
     m_styleTree.collectFeaturesTo(m_features);
 
     m_siblingRuleSet = makeRuleSet(m_features.siblingRules);
     m_uncommonAttributeRuleSet = makeRuleSet(m_features.uncommonAttributeRules);
 }
 
+bool StyleResolver::supportsStyleSharing(Element* element)
+{
+    if (!element || !element->isStyledElement() || !element->parentElement())
+        return false;
+
+    // If the element has inline style it is probably unique.
+    if (element->inlineStyle())
+        return false;
+    if (element->isSVGElement() && toSVGElement(element)->animatedSMILStyleProperties())
+        return false;
+    // Ids stop style sharing if they show up in the stylesheets.
+    if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
+        return false;
+    // Active and hovered elements always make a chain towards the document node
+    // and no siblings or cousins will have the same state.
+    if (element->hovered())
+        return false;
+    if (element->active())
+        return false;
+    // There is always only one focused element.
+    if (element->focused())
+        return false;
+    if (element->parentElement()->hasFlagsSetDuringStylingOfChildren())
+        return false;
+    if (element->hasScopedHTMLStyleChild())
+        return false;
+    if (element == m_document.cssTarget())
+        return false;
+    if (element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto())
+        return false;
+    if (element->hasActiveAnimations())
+        return false;
+    // When a dialog is first shown, its style is mutated to center it in the
+    // viewport. So the styles can't be shared since the viewport position and
+    // size may be different each time a dialog is opened.
+    if (element->hasTagName(dialogTag))
+        return false;
+    if (isShadowHost(element) && element->shadow()->containsActiveStyles())
+        return false;
+    return true;
+}
+
+void StyleResolver::addToStyleSharingList(Element* element)
+{
+    if (m_styleSharingList.size() >= styleSharingListSize)
+        m_styleSharingList.remove(--m_styleSharingList.end());
+    m_styleSharingList.prepend(element);
+}
+
+void StyleResolver::clearStyleSharingList()
+{
+    m_styleSharingList.clear();
+}
+
 void StyleResolver::pushParentElement(Element* parent)
 {
+    ASSERT(parent);
     const ContainerNode* parentsParent = parent->parentOrShadowHostElement();
 
     // We are not always invoked consistently. For example, script execution can cause us to enter
@@ -256,28 +310,29 @@
         m_selectorFilter.pushParent(parent);
 
     // Note: We mustn't skip ShadowRoot nodes for the scope stack.
-    m_styleTree.pushStyleCache(parent, parent->parentOrShadowHostNode());
+    m_styleTree.pushStyleCache(*parent, parent->parentOrShadowHostNode());
 }
 
 void StyleResolver::popParentElement(Element* parent)
 {
+    ASSERT(parent);
     // Note that we may get invoked for some random elements in some wacky cases during style resolve.
     // Pause maintaining the stack in this case.
     if (m_selectorFilter.parentStackIsConsistent(parent))
         m_selectorFilter.popParent();
 
-    m_styleTree.popStyleCache(parent);
+    m_styleTree.popStyleCache(*parent);
 }
 
-void StyleResolver::pushParentShadowRoot(const ShadowRoot* shadowRoot)
+void StyleResolver::pushParentShadowRoot(const ShadowRoot& shadowRoot)
 {
-    ASSERT(shadowRoot->host());
-    m_styleTree.pushStyleCache(shadowRoot, shadowRoot->host());
+    ASSERT(shadowRoot.host());
+    m_styleTree.pushStyleCache(shadowRoot, shadowRoot.host());
 }
 
-void StyleResolver::popParentShadowRoot(const ShadowRoot* shadowRoot)
+void StyleResolver::popParentShadowRoot(const ShadowRoot& shadowRoot)
 {
-    ASSERT(shadowRoot->host());
+    ASSERT(shadowRoot.host());
     m_styleTree.popStyleCache(shadowRoot);
 }
 
@@ -316,14 +371,14 @@
 
 void StyleResolver::matchHostRules(Element* element, ScopedStyleResolver* resolver, ElementRuleCollector& collector, bool includeEmptyRules)
 {
-    if (element != resolver->scopingNode())
+    if (element != &resolver->scopingNode())
         return;
     resolver->matchHostRules(collector, includeEmptyRules);
 }
 
 static inline bool applyAuthorStylesOf(const Element* element)
 {
-    return element->treeScope()->applyAuthorStyles() || (element->shadow() && element->shadow()->applyAuthorStyles());
+    return element->treeScope().applyAuthorStyles() || (element->shadow() && element->shadow()->applyAuthorStyles());
 }
 
 void StyleResolver::matchScopedAuthorRulesForShadowHost(Element* element, ElementRuleCollector& collector, bool includeEmptyRules, Vector<ScopedStyleResolver*, 8>& resolvers, Vector<ScopedStyleResolver*, 8>& resolversInShadowTree)
@@ -338,7 +393,7 @@
     for (int j = resolversInShadowTree.size() - 1; j >= 0; --j)
         resolversInShadowTree.at(j)->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope, cascadeOrder++);
 
-    if (resolvers.isEmpty() || resolvers.first()->treeScope() != element->treeScope())
+    if (resolvers.isEmpty() || &resolvers.first()->treeScope() != &element->treeScope())
         ++cascadeScope;
     cascadeOrder += resolvers.size();
     for (unsigned i = 0; i < resolvers.size(); ++i)
@@ -379,7 +434,7 @@
     for (unsigned i = 0; i < resolvers.size(); ++i, --cascadeOrder) {
         ScopedStyleResolver* resolver = resolvers.at(i);
         // FIXME: Need to clarify how to treat style scoped.
-        resolver->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope++, resolver->treeScope() == element->treeScope() && resolver->scopingNode()->isShadowRoot() ? 0 : cascadeOrder);
+        resolver->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope++, &resolver->treeScope() == &element->treeScope() && resolver->scopingNode().isShadowRoot() ? 0 : cascadeOrder);
     }
 
     collector.sortAndTransferMatchedRules();
@@ -422,11 +477,11 @@
     matchUARules(collector, userAgentStyleSheet);
 
     // In quirks mode, we match rules from the quirks user agent sheet.
-    if (document()->inQuirksMode())
+    if (document().inQuirksMode())
         matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle);
 
     // If document uses view source styles (in view source mode or in xml viewer mode), then we match rules from the view source style sheet.
-    if (document()->isViewSource())
+    if (document().isViewSource())
         matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle());
 
     collector.setMatchingUARules(false);
@@ -500,18 +555,18 @@
     return collector.hasAnyMatchingRules(ruleSet);
 }
 
-PassRefPtr<RenderStyle> StyleResolver::styleForDocument(const Document* document, CSSFontSelector* fontSelector)
+PassRefPtr<RenderStyle> StyleResolver::styleForDocument(Document& document, CSSFontSelector* fontSelector)
 {
-    const Frame* frame = document->frame();
+    const Frame* frame = document.frame();
 
     // HTML5 states that seamless iframes should replace default CSS values
     // with values inherited from the containing iframe element. However,
     // some values (such as the case of designMode = "on") still need to
     // be set by this "document style".
     RefPtr<RenderStyle> documentStyle = RenderStyle::create();
-    bool seamlessWithParent = document->shouldDisplaySeamlesslyWithParent();
+    bool seamlessWithParent = document.shouldDisplaySeamlesslyWithParent();
     if (seamlessWithParent) {
-        RenderStyle* iframeStyle = document->seamlessParentIFrame()->renderStyle();
+        RenderStyle* iframeStyle = document.seamlessParentIFrame()->renderStyle();
         if (iframeStyle)
             documentStyle->inheritFrom(iframeStyle);
     }
@@ -519,52 +574,14 @@
     // FIXME: It's not clear which values below we want to override in the seamless case!
     documentStyle->setDisplay(BLOCK);
     if (!seamlessWithParent) {
-        documentStyle->setRTLOrdering(document->visuallyOrdered() ? VisualOrder : LogicalOrder);
-        documentStyle->setZoom(frame && !document->printing() ? frame->pageZoomFactor() : 1);
-        documentStyle->setLocale(document->contentLanguage());
+        documentStyle->setRTLOrdering(document.visuallyOrdered() ? VisualOrder : LogicalOrder);
+        documentStyle->setZoom(frame && !document.printing() ? frame->pageZoomFactor() : 1);
+        documentStyle->setLocale(document.contentLanguage());
     }
     // This overrides any -webkit-user-modify inherited from the parent iframe.
-    documentStyle->setUserModify(document->inDesignMode() ? READ_WRITE : READ_ONLY);
+    documentStyle->setUserModify(document.inDesignMode() ? READ_WRITE : READ_ONLY);
 
-    Element* docElement = document->documentElement();
-    RenderObject* docElementRenderer = docElement ? docElement->renderer() : 0;
-    if (docElementRenderer) {
-        // Use the direction and writing-mode of the body to set the
-        // viewport's direction and writing-mode unless the property is set on the document element.
-        // If there is no body, then use the document element.
-        RenderObject* bodyRenderer = document->body() ? document->body()->renderer() : 0;
-        if (bodyRenderer && !document->writingModeSetOnDocumentElement())
-            documentStyle->setWritingMode(bodyRenderer->style()->writingMode());
-        else
-            documentStyle->setWritingMode(docElementRenderer->style()->writingMode());
-        if (bodyRenderer && !document->directionSetOnDocumentElement())
-            documentStyle->setDirection(bodyRenderer->style()->direction());
-        else
-            documentStyle->setDirection(docElementRenderer->style()->direction());
-    }
-
-    if (frame) {
-        if (FrameView* frameView = frame->view()) {
-            const Pagination& pagination = frameView->pagination();
-            if (pagination.mode != Pagination::Unpaginated) {
-                Pagination::setStylesForPaginationMode(pagination.mode, documentStyle.get());
-                documentStyle->setColumnGap(pagination.gap);
-                if (RenderView* view = document->renderView()) {
-                    if (view->hasColumns())
-                        view->updateColumnInfoFromStyle(documentStyle.get());
-                }
-            }
-        }
-    }
-
-    // Seamless iframes want to inherit their font from their parent iframe, so early return before setting the font.
-    if (seamlessWithParent)
-        return documentStyle.release();
-
-    FontBuilder fontBuilder;
-    fontBuilder.initForStyleResolve(document, documentStyle.get(), document->isSVGDocument());
-    fontBuilder.createFontForDocument(fontSelector, documentStyle.get());
-
+    document.setStyleDependentState(documentStyle.get());
     return documentStyle.release();
 }
 
@@ -578,10 +595,10 @@
     return parentNode && parentNode->isShadowRoot();
 }
 
-static inline void resetDirectionAndWritingModeOnDocument(Document* document)
+static inline void resetDirectionAndWritingModeOnDocument(Document& document)
 {
-    document->setDirectionSetOnDocumentElement(false);
-    document->setWritingModeSetOnDocumentElement(false);
+    document.setDirectionSetOnDocumentElement(false);
+    document.setWritingModeSetOnDocumentElement(false);
 }
 
 static void addContentAttrValuesToFeatures(const Vector<AtomicString>& contentAttrValues, RuleFeatureSet& features)
@@ -593,22 +610,22 @@
 PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderStyle* defaultParent, StyleSharingBehavior sharingBehavior,
     RuleMatchingBehavior matchingBehavior, RenderRegion* regionForStyling)
 {
-    ASSERT(document()->frame());
+    ASSERT(document().frame());
     ASSERT(documentSettings());
 
     // Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
     // will vanish if a style recalc happens during loading.
-    if (sharingBehavior == AllowStyleSharing && !element->document()->haveStylesheetsLoaded() && !element->renderer()) {
+    if (sharingBehavior == AllowStyleSharing && !element->document().haveStylesheetsLoaded() && !element->renderer()) {
         if (!s_styleNotYetAvailable) {
             s_styleNotYetAvailable = RenderStyle::create().leakRef();
             s_styleNotYetAvailable->setDisplay(NONE);
             s_styleNotYetAvailable->font().update(m_fontSelector);
         }
-        element->document()->setHasNodesWithPlaceholderStyle();
+        element->document().setHasNodesWithPlaceholderStyle();
         return s_styleNotYetAvailable;
     }
 
-    if (element == document()->documentElement())
+    if (element == document().documentElement())
         resetDirectionAndWritingModeOnDocument(document());
     StyleResolverState state(document(), element, defaultParent, regionForStyling);
 
@@ -669,14 +686,14 @@
         addContentAttrValuesToFeatures(state.contentAttrValues(), m_features);
     }
     {
-        StyleAdjuster adjuster(state.cachedUAStyle(), m_document->inQuirksMode());
+        StyleAdjuster adjuster(state.cachedUAStyle(), m_document.inQuirksMode());
         adjuster.adjustRenderStyle(state.style(), state.parentStyle(), element);
     }
-    document()->didAccessStyleResolver();
+    document().didAccessStyleResolver();
 
     // FIXME: Shouldn't this be on RenderBody::styleDidChange?
     if (element->hasTagName(bodyTag))
-        document()->textLinkColors().setTextColor(state.style()->visitedDependentColor(CSSPropertyColor));
+        document().textLinkColors().setTextColor(state.style()->visitedDependentColor(CSSPropertyColor));
 
     // If any changes to CSS Animations were detected, stash the update away for application after the
     // render object is updated if we're in the appropriate scope.
@@ -689,10 +706,10 @@
 
 PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(Element* e, const RenderStyle* elementStyle, const StyleKeyframe* keyframe)
 {
-    ASSERT(document()->frame());
+    ASSERT(document().frame());
     ASSERT(documentSettings());
 
-    if (e == document()->documentElement())
+    if (e == document().documentElement())
         resetDirectionAndWritingModeOnDocument(document());
     StyleResolverState state(document(), e);
 
@@ -735,7 +752,7 @@
     // Start loading resources referenced by this style.
     m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
 
-    document()->didAccessStyleResolver();
+    document().didAccessStyleResolver();
 
     return state.takeStyle();
 }
@@ -781,8 +798,7 @@
         keyframeValue.addProperties(keyframe->properties());
 
         // Add this keyframe style to all the indicated key times
-        Vector<double> keys;
-        keyframe->getKeys(keys);
+        const Vector<double>& keys = keyframe->keys();
         for (size_t keyIndex = 0; keyIndex < keys.size(); ++keyIndex) {
             keyframeValue.setKey(keys[keyIndex]);
             list.insert(keyframeValue);
@@ -829,8 +845,7 @@
     for (size_t i = 0; i < styleKeyframes.size(); ++i) {
         const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
         RefPtr<RenderStyle> keyframeStyle = styleForKeyframe(0, style, styleKeyframe);
-        Vector<double> offsets;
-        styleKeyframe->getKeys(offsets);
+        const Vector<double>& offsets = styleKeyframe->keys();
         RefPtr<Keyframe> firstOffsetKeyframe;
         for (size_t j = 0; j < offsets.size(); ++j) {
             RefPtr<Keyframe> keyframe = Keyframe::create();
@@ -907,14 +922,12 @@
 
 PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* e, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle)
 {
-    ASSERT(document()->frame());
+    ASSERT(document().frame());
     ASSERT(documentSettings());
     ASSERT(parentStyle);
     if (!e)
         return 0;
 
-    if (e == document()->documentElement())
-        resetDirectionAndWritingModeOnDocument(document());
     StyleResolverState state(document(), e, parentStyle);
 
     if (pseudoStyleRequest.allowsInheritance(state.parentStyle())) {
@@ -951,7 +964,7 @@
         addContentAttrValuesToFeatures(state.contentAttrValues(), m_features);
     }
     {
-        StyleAdjuster adjuster(state.cachedUAStyle(), m_document->inQuirksMode());
+        StyleAdjuster adjuster(state.cachedUAStyle(), m_document.inQuirksMode());
         // FIXME: Passing 0 as the Element* introduces a lot of complexity
         // in the adjustRenderStyle code.
         adjuster.adjustRenderStyle(state.style(), state.parentStyle(), 0);
@@ -960,7 +973,7 @@
     // Start loading resources referenced by this style.
     m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
 
-    document()->didAccessStyleResolver();
+    document().didAccessStyleResolver();
 
     // Now return the style.
     return state.takeStyle();
@@ -969,10 +982,11 @@
 PassRefPtr<RenderStyle> StyleResolver::styleForPage(int pageIndex)
 {
     resetDirectionAndWritingModeOnDocument(document());
-    StyleResolverState state(document(), document()->documentElement()); // m_rootElementStyle will be set to the document style.
+    StyleResolverState state(document(), document().documentElement()); // m_rootElementStyle will be set to the document style.
 
     state.setStyle(RenderStyle::create());
-    state.style()->inheritFrom(state.rootElementStyle());
+    if (state.rootElementStyle())
+        state.style()->inheritFrom(state.rootElementStyle());
 
     state.fontBuilder().initForStyleResolve(state.document(), state.style(), state.useSVGZoomRules());
 
@@ -1005,7 +1019,7 @@
     // Start loading resources referenced by this style.
     m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
 
-    document()->didAccessStyleResolver();
+    document().didAccessStyleResolver();
 
     // Now return the style.
     return state.takeStyle();
@@ -1013,11 +1027,13 @@
 
 void StyleResolver::collectViewportRules()
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled());
+    collectViewportRules(CSSDefaultStyleSheets::defaultStyle, UserAgentOrigin);
 
-    collectViewportRules(CSSDefaultStyleSheets::defaultStyle);
+    if (document().isMobileDocument())
+        collectViewportRules(CSSDefaultStyleSheets::xhtmlMobileProfileStyle(), UserAgentOrigin);
+
     if (m_ruleSets.userStyle())
-        collectViewportRules(m_ruleSets.userStyle());
+        collectViewportRules(m_ruleSets.userStyle(), UserAgentOrigin);
 
     if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument())
         scopedResolver->collectViewportRulesTo(this);
@@ -1025,13 +1041,13 @@
     viewportStyleResolver()->resolve();
 }
 
-void StyleResolver::collectViewportRules(RuleSet* rules)
+void StyleResolver::collectViewportRules(RuleSet* rules, ViewportOrigin origin)
 {
-    ASSERT(RuntimeEnabledFeatures::cssViewportEnabled());
-
     rules->compactRulesIfNeeded();
 
     const Vector<StyleRuleViewport*>& viewportRules = rules->viewportRules();
+    if (origin == AuthorOrigin && viewportRules.size())
+        viewportStyleResolver()->setHasAuthorStyle();
     for (size_t i = 0; i < viewportRules.size(); ++i)
         viewportStyleResolver()->addViewportRule(viewportRules[i]);
 }
@@ -1092,10 +1108,10 @@
 
 PassRefPtr<CSSRuleList> StyleResolver::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
 {
-    if (!e || !e->document()->haveStylesheetsLoaded())
+    if (!e || !e->document().haveStylesheetsLoaded())
         return 0;
 
-    if (e == document()->documentElement())
+    if (e == document().documentElement())
         resetDirectionAndWritingModeOnDocument(document());
     StyleResolverState state(document(), e);
 
@@ -1445,13 +1461,13 @@
     if (RuntimeEnabledFeatures::webAnimationsEnabled() && !applyInheritedOnly) {
         calculateCSSAnimationUpdate(state);
         // Apply animated properties, then reapply any rules marked important.
-        if (applyAnimatedProperties<HighPriorityProperties>(state, element->document()->timeline())) {
+        if (applyAnimatedProperties<HighPriorityProperties>(state, element->document().timeline())) {
             bool important = true;
             applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
             applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
             applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
         }
-        if (applyAnimatedProperties<LowPriorityProperties>(state, element->document()->timeline())) {
+        if (applyAnimatedProperties<LowPriorityProperties>(state, element->document().timeline())) {
             bool important = true;
             applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
             applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index e412395..5d9ae8e 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -36,6 +36,7 @@
 #include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/StyleResolverState.h"
 #include "core/css/resolver/StyleResourceLoader.h"
+#include "wtf/Deque.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/RefPtr.h"
@@ -85,6 +86,9 @@
     MatchOnlyUserAgentRules,
 };
 
+const unsigned styleSharingListSize = 40;
+typedef WTF::Deque<RefPtr<Element>, styleSharingListSize> StyleSharingList;
+
 #undef STYLE_STATS
 
 #ifdef STYLE_STATS
@@ -172,7 +176,7 @@
 class StyleResolver {
     WTF_MAKE_NONCOPYABLE(StyleResolver); WTF_MAKE_FAST_ALLOCATED;
 public:
-    StyleResolver(Document*, bool matchAuthorAndUserStyles);
+    StyleResolver(Document&, bool matchAuthorAndUserStyles);
     ~StyleResolver();
 
     // FIXME: StyleResolver should not be keeping tree-walk state.
@@ -181,8 +185,8 @@
     // Using these during tree walk will allow style selector to optimize child and descendant selector lookups.
     void pushParentElement(Element*);
     void popParentElement(Element*);
-    void pushParentShadowRoot(const ShadowRoot*);
-    void popParentShadowRoot(const ShadowRoot*);
+    void pushParentShadowRoot(const ShadowRoot&);
+    void popParentShadowRoot(const ShadowRoot&);
 
     PassRefPtr<RenderStyle> styleForElement(Element*, RenderStyle* parentStyle = 0, StyleSharingBehavior = AllowStyleSharing,
         RuleMatchingBehavior = MatchAllRules, RenderRegion* regionForStyling = 0);
@@ -202,11 +206,11 @@
     PassRefPtr<RenderStyle> defaultStyleForElement();
     PassRefPtr<RenderStyle> styleForText(Text*);
 
-    static PassRefPtr<RenderStyle> styleForDocument(const Document*, CSSFontSelector* = 0);
+    static PassRefPtr<RenderStyle> styleForDocument(Document&, CSSFontSelector* = 0);
 
     // FIXME: This only has 5 callers and should be removed. Callers should be explicit about
     // their dependency on Document* instead of grabbing one through StyleResolver.
-    Document* document() { return m_document; }
+    Document& document() { return m_document; }
 
     // FIXME: It could be better to call m_ruleSets.appendAuthorStyleSheets() directly after we factor StyleRsolver further.
     // https://bugs.webkit.org/show_bug.cgi?id=108890
@@ -224,7 +228,7 @@
 
     ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode* scope)
     {
-        return m_styleTree.ensureScopedStyleResolver(scope ? scope : document());
+        return m_styleTree.ensureScopedStyleResolver(scope ? *scope : document());
     }
 
     // FIXME: Used by SharingStyleFinder, but should be removed.
@@ -265,12 +269,21 @@
     // FIXME: StyleResolver should not have this member or method.
     InspectorCSSOMWrappers& inspectorCSSOMWrappers() { return m_inspectorCSSOMWrappers; }
 
+    enum ViewportOrigin { UserAgentOrigin, AuthorOrigin };
+
     // Exposed for ScopedStyleResolver.
     // FIXME: Likely belongs on viewportStyleResolver.
-    void collectViewportRules(RuleSet*);
+    void collectViewportRules(RuleSet*, ViewportOrigin);
 
     const RuleFeatureSet& ruleFeatureSet() const { return m_features; }
 
+    StyleSharingList& styleSharingList() { return m_styleSharingList; }
+
+    bool supportsStyleSharing(Element*);
+
+    void addToStyleSharingList(Element*);
+    void clearStyleSharingList();
+
 #ifdef STYLE_STATS
     ALWAYS_INLINE static StyleSharingStats& styleSharingStats() { return m_styleSharingStats; }
 #endif
@@ -310,7 +323,7 @@
     void matchPageRules(MatchResult&, RuleSet*, bool isLeftPage, bool isFirstPage, const String& pageName);
     void matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>&, bool isLeftPage, bool isFirstPage, const String& pageName);
     void collectViewportRules();
-    Settings* documentSettings() { return m_document->settings(); }
+    Settings* documentSettings() { return m_document.settings(); }
 
     bool isLeftPage(int pageIndex) const;
     bool isRightPage(int pageIndex) const { return !isLeftPage(pageIndex); }
@@ -332,7 +345,7 @@
     OwnPtr<MediaQueryEvaluator> m_medium;
     RefPtr<RenderStyle> m_rootDefaultStyle;
 
-    Document* m_document;
+    Document& m_document;
     SelectorFilter m_selectorFilter;
 
     bool m_matchAuthorAndUserStyles;
@@ -354,6 +367,8 @@
 
     StyleResourceLoader m_styleResourceLoader;
 
+    StyleSharingList m_styleSharingList;
+
 #ifdef STYLE_STATS
     static StyleSharingStats m_styleSharingStats;
 #endif
diff --git a/Source/core/css/resolver/StyleResolverState.cpp b/Source/core/css/resolver/StyleResolverState.cpp
index 059d57d..b98a30c 100644
--- a/Source/core/css/resolver/StyleResolverState.cpp
+++ b/Source/core/css/resolver/StyleResolverState.cpp
@@ -29,21 +29,15 @@
 
 namespace WebCore {
 
-StyleResolverState::StyleResolverState(Document* document, Element* element, RenderStyle* parentStyle, RenderRegion* regionForStyling)
-    : m_regionForStyling(0)
+StyleResolverState::StyleResolverState(Document& document, Element* element, RenderStyle* parentStyle, RenderRegion* regionForStyling)
+    : m_elementContext(element ? ElementResolveContext(element) : ElementResolveContext())
+    , m_document(element ? m_elementContext.document() : document)
+    , m_regionForStyling(0)
     , m_applyPropertyToRegularStyle(true)
     , m_applyPropertyToVisitedLinkStyle(false)
     , m_lineHeightValue(0)
     , m_styleMap(*this, m_elementStyleResources)
 {
-    if (element) {
-        m_elementContext = ElementResolveContext(element);
-        m_document = m_elementContext.document();
-    } else {
-        m_elementContext = ElementResolveContext();
-        m_document = document;
-    }
-
     m_regionForStyling = regionForStyling;
 
     if (m_elementContext.resetStyleInheritance())
@@ -62,7 +56,7 @@
     // FIXME: StyleResolverState is never passed between documents
     // so we should be able to do this initialization at StyleResolverState
     // createion time instead of now, correct?
-    if (Page* page = document->page())
+    if (Page* page = document.page())
         m_elementStyleResources.setDeviceScaleFactor(page->deviceScaleFactor());
 }
 
diff --git a/Source/core/css/resolver/StyleResolverState.h b/Source/core/css/resolver/StyleResolverState.h
index fd88ffc..5f2deda 100644
--- a/Source/core/css/resolver/StyleResolverState.h
+++ b/Source/core/css/resolver/StyleResolverState.h
@@ -43,12 +43,12 @@
 class StyleResolverState {
 WTF_MAKE_NONCOPYABLE(StyleResolverState);
 public:
-    StyleResolverState(Document*, Element*, RenderStyle* parentStyle = 0, RenderRegion* regionForStyling = 0);
+    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.
     // This is why we have to store the document separately.
-    Document* document() const { return m_document; }
+    Document& document() const { return m_document; }
     // These are all just pass-through methods to ElementResolveContext.
     Element* element() const { return m_elementContext.element(); }
     const ContainerNode* parentNode() const { return m_elementContext.parentNode(); }
@@ -101,7 +101,7 @@
     // sites are extremely verbose.
     PassRefPtr<StyleImage> styleImage(CSSPropertyID propertyId, CSSValue* value)
     {
-        return m_elementStyleResources.styleImage(document()->textLinkColors(), propertyId, value);
+        return m_elementStyleResources.styleImage(document().textLinkColors(), style()->visitedDependentColor(CSSPropertyColor), propertyId, value);
     }
 
     FontBuilder& fontBuilder() { return m_fontBuilder; }
@@ -131,8 +131,8 @@
 
     void initElement(Element*);
 
-    Document* m_document;
     ElementResolveContext m_elementContext;
+    Document& m_document;
 
     // m_style is the primary output for each element's style resolve.
     RefPtr<RenderStyle> m_style;
diff --git a/Source/core/css/resolver/ViewportStyleResolver.cpp b/Source/core/css/resolver/ViewportStyleResolver.cpp
index 3423937..f38f7d7 100644
--- a/Source/core/css/resolver/ViewportStyleResolver.cpp
+++ b/Source/core/css/resolver/ViewportStyleResolver.cpp
@@ -40,7 +40,8 @@
 namespace WebCore {
 
 ViewportStyleResolver::ViewportStyleResolver(Document* document)
-    : m_document(document)
+    : m_document(document),
+    m_hasAuthorStyle(false)
 {
     ASSERT(m_document);
 }
@@ -78,37 +79,32 @@
     if (!m_document)
         return;
 
-    if (!m_propertySet) {
-        // FIXME: This is not entirely correct. If the doctype is XHTML MP, or there is a Meta
-        // element for setting the viewport, the viewport arguments should fall back to those
-        // settings when the @viewport rules are all removed. For now, reset to implicit when
-        // there was an @viewport rule which has now been removed.
-        if (m_document->viewportArguments().type == ViewportArguments::CSSDeviceAdaptation) {
-            m_document->setViewportArguments(ViewportArguments());
-            m_document->updateViewportArguments();
-        }
+    if (!m_propertySet || (!m_hasAuthorStyle && m_document->hasLegacyViewportTag())) {
+        ASSERT(!m_hasAuthorStyle);
+        m_propertySet = 0;
+        m_document->setViewportArguments(ViewportArguments());
         return;
     }
 
-    ViewportArguments arguments(ViewportArguments::CSSDeviceAdaptation);
+    ViewportArguments arguments(m_hasAuthorStyle ? ViewportArguments::AuthorStyleSheet : ViewportArguments::UserAgentStyleSheet);
 
-    arguments.userZoom = getViewportArgumentValue(CSSPropertyUserZoom);
-    arguments.zoom = getViewportArgumentValue(CSSPropertyZoom);
-    arguments.minZoom = getViewportArgumentValue(CSSPropertyMinZoom);
-    arguments.maxZoom = getViewportArgumentValue(CSSPropertyMaxZoom);
-    arguments.minWidth = getViewportArgumentValue(CSSPropertyMinWidth);
-    arguments.maxWidth = getViewportArgumentValue(CSSPropertyMaxWidth);
-    arguments.minHeight = getViewportArgumentValue(CSSPropertyMinHeight);
-    arguments.maxHeight = getViewportArgumentValue(CSSPropertyMaxHeight);
-    arguments.orientation = getViewportArgumentValue(CSSPropertyOrientation);
+    arguments.userZoom = viewportArgumentValue(CSSPropertyUserZoom);
+    arguments.zoom = viewportArgumentValue(CSSPropertyZoom);
+    arguments.minZoom = viewportArgumentValue(CSSPropertyMinZoom);
+    arguments.maxZoom = viewportArgumentValue(CSSPropertyMaxZoom);
+    arguments.minWidth = viewportLengthValue(CSSPropertyMinWidth);
+    arguments.maxWidth = viewportLengthValue(CSSPropertyMaxWidth);
+    arguments.minHeight = viewportLengthValue(CSSPropertyMinHeight);
+    arguments.maxHeight = viewportLengthValue(CSSPropertyMaxHeight);
+    arguments.orientation = viewportArgumentValue(CSSPropertyOrientation);
 
     m_document->setViewportArguments(arguments);
-    m_document->updateViewportArguments();
 
     m_propertySet = 0;
+    m_hasAuthorStyle = false;
 }
 
-float ViewportStyleResolver::getViewportArgumentValue(CSSPropertyID id) const
+float ViewportStyleResolver::viewportArgumentValue(CSSPropertyID id) const
 {
     float defaultValue = ViewportArguments::ValueAuto;
 
@@ -133,12 +129,6 @@
     if (primitiveValue->isPercentage()) {
         float percentValue = primitiveValue->getFloatValue() / 100.0f;
         switch (id) {
-        case CSSPropertyMaxHeight:
-        case CSSPropertyMinHeight:
-            return percentValue * m_document->initialViewportSize().height();
-        case CSSPropertyMaxWidth:
-        case CSSPropertyMinWidth:
-            return percentValue * m_document->initialViewportSize().width();
         case CSSPropertyMaxZoom:
         case CSSPropertyMinZoom:
         case CSSPropertyZoom:
@@ -167,4 +157,38 @@
     }
 }
 
+Length ViewportStyleResolver::viewportLengthValue(CSSPropertyID id) const
+{
+    ASSERT(id == CSSPropertyMaxHeight
+        || id == CSSPropertyMinHeight
+        || id == CSSPropertyMaxWidth
+        || id == CSSPropertyMinWidth);
+
+    RefPtr<CSSValue> value = m_propertySet->getPropertyCSSValue(id);
+    if (!value || !value->isPrimitiveValue())
+        return Length(); // auto
+
+    CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
+
+    if (primitiveValue->isLength())
+        return primitiveValue->computeLength<Length>(m_document->renderStyle(), m_document->renderStyle());
+
+    if (primitiveValue->isViewportPercentageLength())
+        return primitiveValue->viewportPercentageLength();
+
+    if (primitiveValue->isPercentage())
+        return Length(primitiveValue->getFloatValue(), Percent);
+
+    switch (primitiveValue->getValueID()) {
+    case CSSValueInternalExtendToZoom:
+        return Length(ExtendToZoom);
+    case CSSValueAuto:
+        return Length();
+    default:
+        // Unrecognized keyword.
+        ASSERT_NOT_REACHED();
+        return Length(0, Fixed);
+    }
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/resolver/ViewportStyleResolver.h b/Source/core/css/resolver/ViewportStyleResolver.h
index 9f86309..b71128e 100644
--- a/Source/core/css/resolver/ViewportStyleResolver.h
+++ b/Source/core/css/resolver/ViewportStyleResolver.h
@@ -31,6 +31,7 @@
 #define ViewportStyleResolver_h
 
 #include "CSSPropertyNames.h"
+#include "core/platform/Length.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 
@@ -49,6 +50,7 @@
 
     ~ViewportStyleResolver();
 
+    void setHasAuthorStyle() { m_hasAuthorStyle = true; }
     void addViewportRule(StyleRuleViewport*);
 
     void clearDocument();
@@ -57,10 +59,12 @@
 private:
     explicit ViewportStyleResolver(Document*);
 
-    float getViewportArgumentValue(CSSPropertyID) const;
+    float viewportArgumentValue(CSSPropertyID) const;
+    Length viewportLengthValue(CSSPropertyID) const;
 
     Document* m_document;
     RefPtr<MutableStylePropertySet> m_propertySet;
+    bool m_hasAuthorStyle;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/themeChromiumAndroid.css b/Source/core/css/themeChromiumAndroid.css
index d081018..be5488f 100644
--- a/Source/core/css/themeChromiumAndroid.css
+++ b/Source/core/css/themeChromiumAndroid.css
@@ -34,7 +34,7 @@
 select[multiple],
 select[size][multiple] {
     -webkit-appearance: menulist;
-    -webkit-align-items: center;
+    align-items: center;
     border: 1px solid;
     border-radius: initial;
     white-space: pre;
diff --git a/Source/core/css/xhtmlmp.css b/Source/core/css/xhtmlmp.css
new file mode 100644
index 0000000..11ea1cf
--- /dev/null
+++ b/Source/core/css/xhtmlmp.css
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. 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.
+ * 3. Neither the name of Opera Software ASA 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 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.
+ */
+
+/* Default styles for XHTML Mobile Profile documents where they differ from html.css */
+
+@viewport {
+    width: auto;
+    /* Ideally these should be removed. Currently here to avoid test result regressions. */
+    min-zoom: 0.25;
+    max-zoom: 5;
+}
diff --git a/Source/core/debugger_script_source.target.darwin-arm.mk b/Source/core/debugger_script_source.target.darwin-arm.mk
index 8ae067d..8952acb 100644
--- a/Source/core/debugger_script_source.target.darwin-arm.mk
+++ b/Source/core/debugger_script_source.target.darwin-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.darwin-mips.mk b/Source/core/debugger_script_source.target.darwin-mips.mk
index 8ae067d..8952acb 100644
--- a/Source/core/debugger_script_source.target.darwin-mips.mk
+++ b/Source/core/debugger_script_source.target.darwin-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.darwin-x86.mk b/Source/core/debugger_script_source.target.darwin-x86.mk
index 8ae067d..8952acb 100644
--- a/Source/core/debugger_script_source.target.darwin-x86.mk
+++ b/Source/core/debugger_script_source.target.darwin-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.linux-arm.mk b/Source/core/debugger_script_source.target.linux-arm.mk
index 8ae067d..8952acb 100644
--- a/Source/core/debugger_script_source.target.linux-arm.mk
+++ b/Source/core/debugger_script_source.target.linux-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.linux-mips.mk b/Source/core/debugger_script_source.target.linux-mips.mk
index 8ae067d..8952acb 100644
--- a/Source/core/debugger_script_source.target.linux-mips.mk
+++ b/Source/core/debugger_script_source.target.linux-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/debugger_script_source.target.linux-x86.mk b/Source/core/debugger_script_source.target.linux-x86.mk
index 8ae067d..8952acb 100644
--- a/Source/core/debugger_script_source.target.linux-x86.mk
+++ b/Source/core/debugger_script_source.target.linux-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/DebuggerScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h from ../bindings/v8/DebuggerScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl DebuggerScriptSource_js ../bindings/v8/DebuggerScript.js "$(gyp_shared_intermediate_dir)/blink/DebuggerScriptSource.h"
 
 
 
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index bf990a3..0d20c05 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -37,9 +37,9 @@
 
 using namespace HTMLNames;
 
-Attr::Attr(Element* element, const QualifiedName& name)
-    : ContainerNode(element->document())
-    , m_element(element)
+Attr::Attr(Element& element, const QualifiedName& name)
+    : ContainerNode(&element.document())
+    , m_element(&element)
     , m_name(name)
     , m_ignoreChildrenChanged(0)
     , m_specified(true)
@@ -47,8 +47,8 @@
     ScriptWrappable::init(this);
 }
 
-Attr::Attr(Document* document, const QualifiedName& name, const AtomicString& standaloneValue)
-    : ContainerNode(document)
+Attr::Attr(Document& document, const QualifiedName& name, const AtomicString& standaloneValue)
+    : ContainerNode(&document)
     , m_element(0)
     , m_name(name)
     , m_standaloneValue(standaloneValue)
@@ -58,14 +58,14 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<Attr> Attr::create(Element* element, const QualifiedName& name)
+PassRefPtr<Attr> Attr::create(Element& element, const QualifiedName& name)
 {
     RefPtr<Attr> attr = adoptRef(new Attr(element, name));
     attr->createTextChild();
     return attr.release();
 }
 
-PassRefPtr<Attr> Attr::create(Document* document, const QualifiedName& name, const AtomicString& value)
+PassRefPtr<Attr> Attr::create(Document& document, const QualifiedName& name, const AtomicString& value)
 {
     RefPtr<Attr> attr = adoptRef(new Attr(document, name, value));
     attr->createTextChild();
@@ -80,12 +80,12 @@
 {
     ASSERT(refCount());
     if (!value().isEmpty()) {
-        RefPtr<Text> textNode = document()->createTextNode(value().string());
+        RefPtr<Text> textNode = document().createTextNode(value().string());
 
         // This does everything appendChild() would do in this situation (assuming m_ignoreChildrenChanged was set),
         // but much more efficiently.
         textNode->setParentOrShadowHostNode(this);
-        treeScope()->adoptIfNeeded(textNode.get());
+        treeScope().adoptIfNeeded(textNode.get());
         setFirstChild(textNode.get());
         setLastChild(textNode.get());
     }
@@ -182,7 +182,7 @@
 
 bool Attr::isId() const
 {
-    return qualifiedName().matches(document()->idAttributeName());
+    return qualifiedName().matches(document().idAttributeName());
 }
 
 const AtomicString& Attr::value() const
diff --git a/Source/core/dom/Attr.h b/Source/core/dom/Attr.h
index 21b3685..bd9e7eb 100644
--- a/Source/core/dom/Attr.h
+++ b/Source/core/dom/Attr.h
@@ -42,8 +42,8 @@
 
 class Attr FINAL : public ContainerNode {
 public:
-    static PassRefPtr<Attr> create(Element*, const QualifiedName&);
-    static PassRefPtr<Attr> create(Document*, const QualifiedName&, const AtomicString& value);
+    static PassRefPtr<Attr> create(Element&, const QualifiedName&);
+    static PassRefPtr<Attr> create(Document&, const QualifiedName&, const AtomicString& value);
     virtual ~Attr();
 
     String name() const { return qualifiedName().toString(); }
@@ -70,8 +70,8 @@
     virtual void setPrefix(const AtomicString&, ExceptionState&) OVERRIDE;
 
 private:
-    Attr(Element*, const QualifiedName&);
-    Attr(Document*, const QualifiedName&, const AtomicString& value);
+    Attr(Element&, const QualifiedName&);
+    Attr(Document&, const QualifiedName&, const AtomicString& value);
 
     void createTextChild();
 
diff --git a/Source/core/dom/CDATASection.cpp b/Source/core/dom/CDATASection.cpp
index 5e19e27..ec61f09 100644
--- a/Source/core/dom/CDATASection.cpp
+++ b/Source/core/dom/CDATASection.cpp
@@ -26,13 +26,13 @@
 
 namespace WebCore {
 
-inline CDATASection::CDATASection(Document* document, const String& data)
+inline CDATASection::CDATASection(Document& document, const String& data)
     : Text(document, data, CreateText)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<CDATASection> CDATASection::create(Document* document, const String& data)
+PassRefPtr<CDATASection> CDATASection::create(Document& document, const String& data)
 {
     return adoptRef(new CDATASection(document, data));
 }
diff --git a/Source/core/dom/CDATASection.h b/Source/core/dom/CDATASection.h
index 3adcd28..ed9075f 100644
--- a/Source/core/dom/CDATASection.h
+++ b/Source/core/dom/CDATASection.h
@@ -29,10 +29,10 @@
 
 class CDATASection FINAL : public Text {
 public:
-    static PassRefPtr<CDATASection> create(Document*, const String&);
+    static PassRefPtr<CDATASection> create(Document&, const String&);
 
 private:
-    CDATASection(Document*, const String&);
+    CDATASection(Document&, const String&);
 
     virtual String nodeName() const;
     virtual NodeType nodeType() const;
@@ -40,6 +40,18 @@
     virtual PassRefPtr<Text> cloneWithData(const String&) OVERRIDE;
 };
 
+inline CDATASection* toCDATASection(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::CDATA_SECTION_NODE);
+    return static_cast<CDATASection*>(node);
+}
+
+inline const CDATASection* toCDATASection(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::CDATA_SECTION_NODE);
+    return static_cast<const CDATASection*>(node);
+}
+
 } // namespace WebCore
 
 #endif // CDATASection_h
diff --git a/Source/core/dom/CharacterData.cpp b/Source/core/dom/CharacterData.cpp
index 50b44c3..ecf9f6c 100644
--- a/Source/core/dom/CharacterData.cpp
+++ b/Source/core/dom/CharacterData.cpp
@@ -55,7 +55,7 @@
     unsigned oldLength = length();
 
     setDataAndUpdate(nonNullData, 0, oldLength, nonNullData.length());
-    document()->textRemoved(this, 0, oldLength);
+    document().textRemoved(this, 0, oldLength);
 }
 
 String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& es)
@@ -98,9 +98,9 @@
 
     ASSERT(!renderer() || isTextNode());
     if (isTextNode())
-        toText(this)->updateTextRenderer(oldLength, 0, DeprecatedAttachNow);
+        toText(this)->updateTextRenderer(oldLength, 0);
 
-    document()->incDOMTreeVersion();
+    document().incDOMTreeVersion();
 
     if (parentNode())
         parentNode()->childrenChanged();
@@ -108,16 +108,16 @@
     return characterLengthLimit;
 }
 
-void CharacterData::appendData(const String& data, AttachBehavior attachBehavior)
+void CharacterData::appendData(const String& data)
 {
     String newStr = m_data + data;
 
-    setDataAndUpdate(newStr, m_data.length(), 0, data.length(), attachBehavior);
+    setDataAndUpdate(newStr, m_data.length(), 0, data.length());
 
     // FIXME: Should we call textInserted here?
 }
 
-void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es, AttachBehavior attachBehavior)
+void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es, RecalcStyleBehavior recalcStyleBehavior)
 {
     if (offset > length()) {
         es.throwDOMException(IndexSizeError);
@@ -127,12 +127,12 @@
     String newStr = m_data;
     newStr.insert(data, offset);
 
-    setDataAndUpdate(newStr, offset, 0, data.length(), attachBehavior);
+    setDataAndUpdate(newStr, offset, 0, data.length(), recalcStyleBehavior);
 
-    document()->textInserted(this, offset, data.length());
+    document().textInserted(this, offset, data.length());
 }
 
-void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es, AttachBehavior attachBehavior)
+void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es, RecalcStyleBehavior recalcStyleBehavior)
 {
     if (offset > length()) {
         es.throwDOMException(IndexSizeError);
@@ -148,12 +148,12 @@
     String newStr = m_data;
     newStr.remove(offset, realCount);
 
-    setDataAndUpdate(newStr, offset, count, 0, attachBehavior);
+    setDataAndUpdate(newStr, offset, count, 0, recalcStyleBehavior);
 
-    document()->textRemoved(this, offset, realCount);
+    document().textRemoved(this, offset, realCount);
 }
 
-void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& es, AttachBehavior attachBehavior)
+void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& es)
 {
     if (offset > length()) {
         es.throwDOMException(IndexSizeError);
@@ -170,11 +170,11 @@
     newStr.remove(offset, realCount);
     newStr.insert(data, offset);
 
-    setDataAndUpdate(newStr, offset, count, data.length(), attachBehavior);
+    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().textRemoved(this, offset, realCount);
+    document().textInserted(this, offset, data.length());
 }
 
 String CharacterData::nodeValue() const
@@ -192,22 +192,22 @@
     setData(nodeValue);
 }
 
-void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength, AttachBehavior attachBehavior)
+void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength, RecalcStyleBehavior recalcStyleBehavior)
 {
     String oldData = m_data;
     m_data = newData;
 
     ASSERT(!renderer() || isTextNode());
     if (isTextNode())
-        toText(this)->updateTextRenderer(offsetOfReplacedData, oldLength, attachBehavior);
+        toText(this)->updateTextRenderer(offsetOfReplacedData, oldLength, recalcStyleBehavior);
 
     if (nodeType() == PROCESSING_INSTRUCTION_NODE)
         toProcessingInstruction(this)->checkStyleSheet();
 
-    if (document()->frame())
-        document()->frame()->selection()->textWasReplaced(this, offsetOfReplacedData, oldLength, newLength);
+    if (document().frame())
+        document().frame()->selection().textWasReplaced(this, offsetOfReplacedData, oldLength, newLength);
 
-    document()->incDOMTreeVersion();
+    document().incDOMTreeVersion();
     didModifyData(oldData);
 }
 
@@ -220,11 +220,11 @@
         parentNode()->childrenChanged();
 
     if (!isInShadowTree()) {
-        if (document()->hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER))
+        if (document().hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER))
             dispatchScopedEvent(MutationEvent::create(eventNames().DOMCharacterDataModifiedEvent, true, 0, oldData, m_data));
         dispatchSubtreeModifiedEvent();
     }
-    InspectorInstrumentation::characterDataModified(document(), this);
+    InspectorInstrumentation::characterDataModified(&document(), this);
 }
 
 int CharacterData::maxCharacterOffset() const
diff --git a/Source/core/dom/CharacterData.h b/Source/core/dom/CharacterData.h
index 473456e..8c50a3f 100644
--- a/Source/core/dom/CharacterData.h
+++ b/Source/core/dom/CharacterData.h
@@ -37,10 +37,12 @@
     void setData(const String&);
     unsigned length() const { return m_data.length(); }
     String substringData(unsigned offset, unsigned count, ExceptionState&);
-    void appendData(const String&, AttachBehavior = AttachLazily);
-    void insertData(unsigned offset, const String&, ExceptionState&, AttachBehavior = AttachLazily);
-    void deleteData(unsigned offset, unsigned count, ExceptionState&, AttachBehavior = AttachLazily);
-    void replaceData(unsigned offset, unsigned count, const String&, ExceptionState&, AttachBehavior = AttachLazily);
+    void appendData(const String&);
+    void replaceData(unsigned offset, unsigned count, const String&, ExceptionState&);
+
+    enum RecalcStyleBehavior { DoNotRecalcStyle, DeprecatedRecalcStyleImmediatlelyForEditing };
+    void insertData(unsigned offset, const String&, ExceptionState&, RecalcStyleBehavior = DoNotRecalcStyle);
+    void deleteData(unsigned offset, unsigned count, ExceptionState&, RecalcStyleBehavior = DoNotRecalcStyle);
 
     bool containsOnlyWhitespace() const;
 
@@ -51,8 +53,8 @@
     unsigned parserAppendData(const String& string, unsigned offset, unsigned lengthLimit);
 
 protected:
-    CharacterData(TreeScope* treeScope, const String& text, ConstructionType type)
-        : Node(treeScope, type)
+    CharacterData(TreeScope& treeScope, const String& text, ConstructionType type)
+        : Node(&treeScope, type)
         , m_data(!text.isNull() ? text : emptyString())
     {
         ASSERT(type == CreateOther || type == CreateText || type == CreateEditingText);
@@ -74,9 +76,21 @@
     virtual bool isCharacterDataNode() const OVERRIDE FINAL { return true; }
     virtual int maxCharacterOffset() const OVERRIDE FINAL;
     virtual bool offsetInCharacters() const OVERRIDE FINAL;
-    void setDataAndUpdate(const String&, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength, AttachBehavior = AttachLazily);
+    void setDataAndUpdate(const String&, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength, RecalcStyleBehavior = DoNotRecalcStyle);
 };
 
+inline CharacterData* toCharacterData(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isCharacterDataNode());
+    return static_cast<CharacterData*>(node);
+}
+
+inline const CharacterData* toCharacterData(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isCharacterDataNode());
+    return static_cast<const CharacterData*>(node);
+}
+
 } // namespace WebCore
 
 #endif // CharacterData_h
diff --git a/Source/core/dom/ChildListMutationScope.h b/Source/core/dom/ChildListMutationScope.h
index 78c63c3..442df97 100644
--- a/Source/core/dom/ChildListMutationScope.h
+++ b/Source/core/dom/ChildListMutationScope.h
@@ -77,7 +77,7 @@
 public:
     explicit ChildListMutationScope(Node* target)
     {
-        if (target->document()->hasMutationObserversOfType(MutationObserver::ChildList))
+        if (target->document().hasMutationObserversOfType(MutationObserver::ChildList))
             m_accumulator = ChildListMutationAccumulator::getOrCreate(target);
     }
 
diff --git a/Source/core/dom/ClassNodeList.cpp b/Source/core/dom/ClassNodeList.cpp
index f70f671..8b36218 100644
--- a/Source/core/dom/ClassNodeList.cpp
+++ b/Source/core/dom/ClassNodeList.cpp
@@ -37,7 +37,7 @@
 
 ClassNodeList::ClassNodeList(PassRefPtr<Node> rootNode, const String& classNames)
     : LiveNodeList(rootNode, ClassNodeListType, InvalidateOnClassAttrChange)
-    , m_classNames(classNames, document()->inQuirksMode())
+    , m_classNames(classNames, document().inQuirksMode())
     , m_originalClassNames(classNames)
 {
 }
diff --git a/Source/core/dom/Comment.cpp b/Source/core/dom/Comment.cpp
index 5b8374f..186008a 100644
--- a/Source/core/dom/Comment.cpp
+++ b/Source/core/dom/Comment.cpp
@@ -26,13 +26,13 @@
 
 namespace WebCore {
 
-inline Comment::Comment(Document* document, const String& text)
+inline Comment::Comment(Document& document, const String& text)
     : CharacterData(document, text, CreateOther)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<Comment> Comment::create(Document* document, const String& text)
+PassRefPtr<Comment> Comment::create(Document& document, const String& text)
 {
     return adoptRef(new Comment(document, text));
 }
diff --git a/Source/core/dom/Comment.h b/Source/core/dom/Comment.h
index affc488..6b4a449 100644
--- a/Source/core/dom/Comment.h
+++ b/Source/core/dom/Comment.h
@@ -31,10 +31,10 @@
 
 class Comment FINAL : public CharacterData {
 public:
-    static PassRefPtr<Comment> create(Document*, const String&);
+    static PassRefPtr<Comment> create(Document&, const String&);
 
 private:
-    Comment(Document*, const String&);
+    Comment(Document&, const String&);
 
     virtual String nodeName() const;
     virtual NodeType nodeType() const;
@@ -42,6 +42,18 @@
     virtual bool childTypeAllowed(NodeType) const;
 };
 
+inline Comment* toComment(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::COMMENT_NODE);
+    return static_cast<Comment*>(node);
+}
+
+inline const Comment* toComment(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::COMMENT_NODE);
+    return static_cast<const Comment*>(node);
+}
+
 } // namespace WebCore
 
 #endif // Comment_h
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index 94c37e5..de26f39 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -39,6 +39,7 @@
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/RenderTheme.h"
+#include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
 #include "wtf/Vector.h"
 
@@ -50,30 +51,12 @@
 static void dispatchChildRemovalEvents(Node*);
 static void updateTreeAfterInsertion(ContainerNode*, Node*);
 
-typedef pair<NodeCallback, RefPtr<Node> > CallbackInfo;
-typedef Vector<CallbackInfo> NodeCallbackQueue;
-
-static NodeCallbackQueue* s_postAttachCallbackQueue;
-
-static size_t s_attachDepth;
-
 ChildNodesLazySnapshot* ChildNodesLazySnapshot::latestSnapshot = 0;
 
 #ifndef NDEBUG
 unsigned NoEventDispatchAssertion::s_count = 0;
 #endif
 
-static inline void attachAfterInsertion(Node* node, AttachBehavior attachBehavior = AttachLazily)
-{
-    if (node->attached() || !node->parentNode() || !node->parentNode()->attached())
-        return;
-
-    if (attachBehavior == AttachLazily)
-        node->lazyAttach();
-    else
-        node->attach();
-}
-
 static void collectChildrenAndRemoveFromOldParent(Node* node, NodeVector& nodes, ExceptionState& es)
 {
     if (node->nodeType() != Node::DOCUMENT_FRAGMENT_NODE) {
@@ -101,7 +84,7 @@
     NodeVector children;
     getChildNodes(oldParent, children);
 
-    if (oldParent->document()->hasMutationObserversOfType(MutationObserver::ChildList)) {
+    if (oldParent->document().hasMutationObserversOfType(MutationObserver::ChildList)) {
         ChildListMutationScope mutation(oldParent);
         for (unsigned i = 0; i < children.size(); ++i)
             mutation.willRemoveChild(children[i].get());
@@ -116,12 +99,12 @@
         if (children[i]->attached())
             children[i]->detach();
         // FIXME: We need a no mutation event version of adoptNode.
-        RefPtr<Node> child = document()->adoptNode(children[i].release(), ASSERT_NO_EXCEPTION);
+        RefPtr<Node> child = document().adoptNode(children[i].release(), ASSERT_NO_EXCEPTION);
         // FIXME: Together with adoptNode above, the tree scope might get updated recursively twice
         // (if the document changed or oldParent was in a shadow tree, AND *this is in a shadow tree).
         // Can we do better?
-        treeScope()->adoptIfNeeded(child.get());
-        parserAppendChild(child.get(), DeprecatedAttachNow);
+        treeScope().adoptIfNeeded(child.get());
+        parserAppendChild(child.get());
     }
 }
 
@@ -146,8 +129,8 @@
 
 static inline bool isInTemplateContent(const Node* node)
 {
-    Document* document = node->document();
-    return document && document == document->templateDocument();
+    Document& document = node->document();
+    return &document == document.templateDocument();
 }
 
 static inline bool containsConsideringHostElements(const Node* newChild, const Node* newParent)
@@ -263,7 +246,7 @@
     if (!checkAcceptChildGuaranteedNodeTypes(this, newChild.get(), es))
         return;
 
-    InspectorInstrumentation::willInsertDOMNode(document(), this);
+    InspectorInstrumentation::willInsertDOMNode(&document(), this);
 
     ChildListMutationScope mutation(this);
     for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
@@ -278,7 +261,7 @@
         if (child->parentNode())
             break;
 
-        treeScope()->adoptIfNeeded(child);
+        treeScope().adoptIfNeeded(child);
 
         insertBeforeCommon(next.get(), child);
 
@@ -314,7 +297,7 @@
     newChild->setNextSibling(nextChild);
 }
 
-void ContainerNode::parserInsertBefore(PassRefPtr<Node> newChild, Node* nextChild, AttachBehavior attachBehavior)
+void ContainerNode::parserInsertBefore(PassRefPtr<Node> newChild, Node* nextChild)
 {
     ASSERT(newChild);
     ASSERT(nextChild);
@@ -325,8 +308,8 @@
     if (nextChild->previousSibling() == newChild || nextChild == newChild) // nothing to do
         return;
 
-    if (document() != newChild->document())
-        document()->adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
+    if (&document() != &newChild->document())
+        document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
 
     insertBeforeCommon(nextChild, newChild.get());
 
@@ -337,8 +320,6 @@
     childrenChanged(true, newChild->previousSibling(), nextChild, 1);
 
     ChildNodeInsertionNotifier(this).notify(newChild.get());
-
-    attachAfterInsertion(newChild.get(), attachBehavior);
 }
 
 void ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& es)
@@ -393,7 +374,7 @@
     if (!checkReplaceChild(this, newChild.get(), oldChild, es))
         return;
 
-    InspectorInstrumentation::willInsertDOMNode(document(), this);
+    InspectorInstrumentation::willInsertDOMNode(&document(), this);
 
     // Add the new child(ren)
     for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
@@ -408,7 +389,7 @@
         if (child->parentNode())
             break;
 
-        treeScope()->adoptIfNeeded(child);
+        treeScope().adoptIfNeeded(child);
 
         // Add child before "next".
         {
@@ -431,7 +412,7 @@
     ChildListMutationScope(child->parentNode()).willRemoveChild(child);
     child->notifyMutationObserversNodeWillDetach();
     dispatchChildRemovalEvents(child);
-    child->document()->nodeWillBeRemoved(child); // e.g. mutation event listener can create a new range.
+    child->document().nodeWillBeRemoved(child); // e.g. mutation event listener can create a new range.
     ChildFrameDisconnector(child).disconnect();
 }
 
@@ -440,7 +421,7 @@
     NodeVector children;
     getChildNodes(container, children);
 
-    container->document()->nodeChildrenWillBeRemoved(container);
+    container->document().nodeChildrenWillBeRemoved(container);
 
     ChildListMutationScope mutation(container);
     for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) {
@@ -476,9 +457,9 @@
 
     RefPtr<Node> child = oldChild;
 
-    document()->removeFocusedElementOfSubtree(child.get());
+    document().removeFocusedElementOfSubtree(child.get());
 
-    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(document()))
+    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(&document()))
         fullscreen->removeFullScreenElementOfSubtree(child.get());
 
     // Events fired when blurring currently focused node might have moved this
@@ -532,7 +513,7 @@
     oldChild->setNextSibling(0);
     oldChild->setParentOrShadowHostNode(0);
 
-    document()->adoptIfNeeded(oldChild);
+    document().adoptIfNeeded(oldChild);
 }
 
 void ContainerNode::parserRemoveChild(Node* oldChild)
@@ -565,7 +546,7 @@
     // The container node can be removed from event handlers.
     RefPtr<ContainerNode> protect(this);
 
-    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(document()))
+    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(&document()))
         fullscreen->removeFullScreenElementOfSubtree(this, true);
 
     // Do any prep work needed before actually starting to detach
@@ -576,7 +557,7 @@
     // children will be removed.
     // This must be later than willRemvoeChildren, which might change focus
     // state of a child.
-    document()->removeFocusedElementOfSubtree(this, true);
+    document().removeFocusedElementOfSubtree(this, true);
 
     NodeVector removedChildren;
     {
@@ -626,7 +607,7 @@
     if (!checkAcceptChildGuaranteedNodeTypes(this, newChild.get(), es))
         return;
 
-    InspectorInstrumentation::willInsertDOMNode(document(), this);
+    InspectorInstrumentation::willInsertDOMNode(&document(), this);
 
     // Now actually add the child(ren)
     ChildListMutationScope mutation(this);
@@ -639,7 +620,7 @@
         if (child->parentNode())
             break;
 
-        treeScope()->adoptIfNeeded(child);
+        treeScope().adoptIfNeeded(child);
 
         // Append child to the end of the list
         {
@@ -653,22 +634,22 @@
     dispatchSubtreeModifiedEvent();
 }
 
-void ContainerNode::parserAppendChild(PassRefPtr<Node> newChild, AttachBehavior attachBehavior)
+void ContainerNode::parserAppendChild(PassRefPtr<Node> newChild)
 {
     ASSERT(newChild);
     ASSERT(!newChild->parentNode()); // Use appendChild if you need to handle reparenting (and want DOM mutation events).
     ASSERT(!newChild->isDocumentFragment());
     ASSERT(!hasTagName(HTMLNames::templateTag));
 
-    if (document() != newChild->document())
-        document()->adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
+    if (&document() != &newChild->document())
+        document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
 
     Node* last = m_lastChild;
     {
         NoEventDispatchAssertion assertNoEventDispatch;
         // FIXME: This method should take a PassRefPtr.
         appendChildToContainer(newChild.get(), this);
-        treeScope()->adoptIfNeeded(newChild.get());
+        treeScope().adoptIfNeeded(newChild.get());
     }
 
     newChild->updateAncestorConnectedSubframeCountForInsertion();
@@ -677,47 +658,6 @@
 
     childrenChanged(true, last, 0, 1);
     ChildNodeInsertionNotifier(this).notify(newChild.get());
-
-    attachAfterInsertion(newChild.get(), attachBehavior);
-}
-
-void ContainerNode::suspendPostAttachCallbacks()
-{
-    ++s_attachDepth;
-}
-
-void ContainerNode::resumePostAttachCallbacks()
-{
-    if (s_attachDepth == 1) {
-        RefPtr<ContainerNode> protect(this);
-
-        if (s_postAttachCallbackQueue)
-            dispatchPostAttachCallbacks();
-    }
-    --s_attachDepth;
-}
-
-void ContainerNode::queuePostAttachCallback(NodeCallback callback, Node* node)
-{
-    if (!s_postAttachCallbackQueue)
-        s_postAttachCallbackQueue = new NodeCallbackQueue;
-    s_postAttachCallbackQueue->append(CallbackInfo(callback, node));
-}
-
-bool ContainerNode::postAttachCallbacksAreSuspended()
-{
-    return s_attachDepth;
-}
-
-void ContainerNode::dispatchPostAttachCallbacks()
-{
-    // We recalculate size() each time through the loop because a callback
-    // can add more callbacks to the end of the queue.
-    for (size_t i = 0; i < s_postAttachCallbackQueue->size(); ++i) {
-        const CallbackInfo& info = (*s_postAttachCallbackQueue)[i];
-        info.first(info.second.get());
-    }
-    s_postAttachCallbackQueue->clear();
 }
 
 void ContainerNode::attach(const AttachContext& context)
@@ -736,9 +676,9 @@
 
 void ContainerNode::childrenChanged(bool changedByParser, Node*, Node*, int childCountDelta)
 {
-    document()->incDOMTreeVersion();
+    document().incDOMTreeVersion();
     if (!changedByParser && childCountDelta)
-        document()->updateRangesAfterChildrenChanged(this);
+        document().updateRangesAfterChildrenChanged(this);
     invalidateNodeListCachesInAncestors();
 }
 
@@ -805,8 +745,8 @@
 
     // If the target doesn't have any children or siblings that could be used to calculate the scroll position, we must be
     // at the end of the document. Scroll to the bottom. FIXME: who said anything about scrolling?
-    if (!o && document()->view()) {
-        point = FloatPoint(0, document()->view()->contentsHeight());
+    if (!o && document().view()) {
+        point = FloatPoint(0, document().view()->contentsHeight());
         return true;
     }
     return false;
@@ -992,7 +932,7 @@
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
 
     RefPtr<Node> c = child;
-    RefPtr<Document> document = child->document();
+    RefPtr<Document> document = &child->document();
 
     if (c->parentNode() && document->hasListenerType(Document::DOMNODEINSERTED_LISTENER))
         c->dispatchScopedEvent(MutationEvent::create(eventNames().DOMNodeInsertedEvent, true, c->parentNode()));
@@ -1007,16 +947,16 @@
 static void dispatchChildRemovalEvents(Node* child)
 {
     if (child->isInShadowTree()) {
-        InspectorInstrumentation::willRemoveDOMNode(child->document(), child);
+        InspectorInstrumentation::willRemoveDOMNode(&child->document(), child);
         return;
     }
 
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
 
-    InspectorInstrumentation::willRemoveDOMNode(child->document(), child);
+    InspectorInstrumentation::willRemoveDOMNode(&child->document(), child);
 
     RefPtr<Node> c = child;
-    RefPtr<Document> document = child->document();
+    RefPtr<Document> document = &child->document();
 
     // dispatch pre-removal mutation events
     if (c->parentNode() && document->hasListenerType(Document::DOMNODEREMOVED_LISTENER))
@@ -1040,9 +980,6 @@
 
     ChildNodeInsertionNotifier(parent).notify(child);
 
-    // FIXME: Decide if it's safe to go through ::insertedInto while aleady attached() and then move this first.
-    attachAfterInsertion(child);
-
     dispatchChildInsertionEvents(child);
 }
 
diff --git a/Source/core/dom/ContainerNode.h b/Source/core/dom/ContainerNode.h
index 7ed7733..80b9c88 100644
--- a/Source/core/dom/ContainerNode.h
+++ b/Source/core/dom/ContainerNode.h
@@ -35,8 +35,6 @@
 class FloatPoint;
 class HTMLCollection;
 
-typedef void (*NodeCallback)(Node*);
-
 namespace Private {
     template<class GenericNode, class GenericNodeContainer>
     void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer*);
@@ -79,7 +77,6 @@
 };
 
 class ContainerNode : public Node {
-    friend class PostAttachCallbackDisabler;
 public:
     virtual ~ContainerNode();
 
@@ -107,9 +104,9 @@
     // These methods are only used during parsing.
     // They don't send DOM mutation events or handle reparenting.
     // However, arbitrary code may be run by beforeload handlers.
-    void parserAppendChild(PassRefPtr<Node>, AttachBehavior = AttachLazily);
+    void parserAppendChild(PassRefPtr<Node>);
     void parserRemoveChild(Node*);
-    void parserInsertBefore(PassRefPtr<Node> newChild, Node* refChild, AttachBehavior = AttachLazily);
+    void parserInsertBefore(PassRefPtr<Node> newChild, Node* refChild);
 
     void removeChildren();
     void takeAllChildrenFrom(ContainerNode*);
@@ -132,14 +129,11 @@
 
     void disconnectDescendantFrames();
 
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const { return true; }
+    virtual bool childShouldCreateRenderer(const Node& child) const { return true; }
 
 protected:
     ContainerNode(TreeScope*, ConstructionType = CreateContainer);
 
-    static void queuePostAttachCallback(NodeCallback, Node*);
-    static bool postAttachCallbacksAreSuspended();
-
     template<class GenericNode, class GenericNodeContainer>
     friend void appendChildToContainer(GenericNode* child, GenericNodeContainer*);
 
@@ -157,11 +151,6 @@
     void attachChildren(const AttachContext& = AttachContext());
     void detachChildren(const AttachContext& = AttachContext());
 
-    static void dispatchPostAttachCallbacks();
-
-    void suspendPostAttachCallbacks();
-    void resumePostAttachCallbacks();
-
     bool getUpperLeftCorner(FloatPoint&) const;
     bool getLowerRightCorner(FloatPoint&) const;
 
@@ -331,24 +320,6 @@
     ChildNodesLazySnapshot* m_nextSnapshot;
 };
 
-class PostAttachCallbackDisabler {
-public:
-    PostAttachCallbackDisabler(ContainerNode* node)
-        : m_node(node)
-    {
-        ASSERT(m_node);
-        m_node->suspendPostAttachCallbacks();
-    }
-
-    ~PostAttachCallbackDisabler()
-    {
-        m_node->resumePostAttachCallbacks();
-    }
-
-private:
-    ContainerNode* m_node;
-};
-
 } // namespace WebCore
 
 #endif // ContainerNode_h
diff --git a/Source/core/dom/ContainerNodeAlgorithms.cpp b/Source/core/dom/ContainerNodeAlgorithms.cpp
index 9f4eeac..ab67eef 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.cpp
+++ b/Source/core/dom/ContainerNodeAlgorithms.cpp
@@ -90,8 +90,8 @@
     if (!node->isElementNode())
         return;
 
-    if (node->document()->cssTarget() == node)
-        node->document()->setCSSTarget(0);
+    if (node->document().cssTarget() == node)
+        node->document().setCSSTarget(0);
 
     if (ElementShadow* shadow = toElement(node)->shadow()) {
         ShadowRootVector roots(shadow);
diff --git a/Source/core/dom/ContainerNodeAlgorithms.h b/Source/core/dom/ContainerNodeAlgorithms.h
index ebd5263..d8910cf 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.h
+++ b/Source/core/dom/ContainerNodeAlgorithms.h
@@ -213,9 +213,9 @@
 {
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
 
-    InspectorInstrumentation::didInsertDOMNode(node->document(), node);
+    InspectorInstrumentation::didInsertDOMNode(&node->document(), node);
 
-    RefPtr<Document> protectDocument(node->document());
+    RefPtr<Document> protectDocument(&node->document());
     RefPtr<Node> protectNode(node);
 
     if (m_insertionPoint->inDocument())
@@ -223,10 +223,20 @@
     else if (node->isContainerNode())
         notifyNodeInsertedIntoTree(toContainerNode(node));
 
-    for (size_t i = 0; i < m_postInsertionNotificationTargets.size(); ++i)
-        m_postInsertionNotificationTargets[i]->didNotifySubtreeInsertions(m_insertionPoint);
-}
+    // Script runs in didNotifySubtreeInsertions so we should lazy attach before
+    // to ensure that triggering a style recalc in script attaches all nodes that
+    // were inserted.
+    // FIXME: We should merge the lazy attach logic into the tree traversal in
+    // notifyNodeInsertedIntoDocument.
+    if (!node->attached() && node->parentNode() && node->parentNode()->attached())
+        node->lazyAttach();
 
+    for (size_t i = 0; i < m_postInsertionNotificationTargets.size(); ++i) {
+        Node* node = m_postInsertionNotificationTargets[i].get();
+        if (node->inDocument())
+            node->didNotifySubtreeInsertionsToDocument();
+    }
+}
 
 inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromDocument(Node* node)
 {
@@ -250,7 +260,7 @@
 {
     if (node->inDocument()) {
         notifyNodeRemovedFromDocument(node);
-        node->document()->notifyRemovePendingSheetIfNeeded();
+        node->document().notifyRemovePendingSheetIfNeeded();
     } else if (node->isContainerNode())
         notifyNodeRemovedFromTree(toContainerNode(node));
 }
diff --git a/Source/core/dom/CustomElement.cpp b/Source/core/dom/CustomElement.cpp
index 0529882..ddb8db2 100644
--- a/Source/core/dom/CustomElement.cpp
+++ b/Source/core/dom/CustomElement.cpp
@@ -132,20 +132,20 @@
     CustomElementCallbackScheduler::scheduleAttributeChangedCallback(definitionFor(element)->callbacks(), element, name, oldValue, newValue);
 }
 
-void CustomElement::didEnterDocument(Element* element, Document* document)
+void CustomElement::didEnterDocument(Element* element, const Document& document)
 {
     ASSERT(element->customElementState() == Element::Upgraded);
-    if (!document->defaultView())
+    if (!document.defaultView())
         return;
-    CustomElementCallbackScheduler::scheduleEnteredDocumentCallback(definitionFor(element)->callbacks(), element);
+    CustomElementCallbackScheduler::scheduleEnteredViewCallback(definitionFor(element)->callbacks(), element);
 }
 
-void CustomElement::didLeaveDocument(Element* element, Document* document)
+void CustomElement::didLeaveDocument(Element* element, const Document& document)
 {
     ASSERT(element->customElementState() == Element::Upgraded);
-    if (!document->defaultView())
+    if (!document.defaultView())
         return;
-    CustomElementCallbackScheduler::scheduleLeftDocumentCallback(definitionFor(element)->callbacks(), element);
+    CustomElementCallbackScheduler::scheduleLeftViewCallback(definitionFor(element)->callbacks(), element);
 }
 
 void CustomElement::wasDestroyed(Element* element)
diff --git a/Source/core/dom/CustomElement.h b/Source/core/dom/CustomElement.h
index 07ba3c0..3e66512 100644
--- a/Source/core/dom/CustomElement.h
+++ b/Source/core/dom/CustomElement.h
@@ -64,8 +64,8 @@
 
     static void didFinishParsingChildren(Element*);
     static void attributeDidChange(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
-    static void didEnterDocument(Element*, Document*);
-    static void didLeaveDocument(Element*, Document*);
+    static void didEnterDocument(Element*, const Document&);
+    static void didLeaveDocument(Element*, const Document&);
     static void wasDestroyed(Element*);
 
 private:
diff --git a/Source/core/dom/CustomElementCallbackInvocation.cpp b/Source/core/dom/CustomElementCallbackInvocation.cpp
index 4974dc0..5729833 100644
--- a/Source/core/dom/CustomElementCallbackInvocation.cpp
+++ b/Source/core/dom/CustomElementCallbackInvocation.cpp
@@ -50,14 +50,14 @@
 
 void CreatedInvocation::dispatch(Element* element)
 {
-    if (element->inDocument() && element->document()->defaultView())
-        CustomElementCallbackScheduler::scheduleEnteredDocumentCallback(callbacks(), element);
+    if (element->inDocument() && element->document().defaultView())
+        CustomElementCallbackScheduler::scheduleEnteredViewCallback(callbacks(), element);
     callbacks()->created(element);
 }
 
-class EnteredLeftDocumentInvocation : public CustomElementCallbackInvocation {
+class EnteredLeftViewInvocation : public CustomElementCallbackInvocation {
 public:
-    EnteredLeftDocumentInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, CustomElementLifecycleCallbacks::CallbackType which);
+    EnteredLeftViewInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, CustomElementLifecycleCallbacks::CallbackType which);
 
 private:
     virtual void dispatch(Element*) OVERRIDE;
@@ -65,21 +65,21 @@
     CustomElementLifecycleCallbacks::CallbackType m_which;
 };
 
-EnteredLeftDocumentInvocation::EnteredLeftDocumentInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, CustomElementLifecycleCallbacks::CallbackType which)
+EnteredLeftViewInvocation::EnteredLeftViewInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, CustomElementLifecycleCallbacks::CallbackType which)
     : CustomElementCallbackInvocation(callbacks)
     , m_which(which)
 {
-    ASSERT(m_which == CustomElementLifecycleCallbacks::EnteredDocument || m_which == CustomElementLifecycleCallbacks::LeftDocument);
+    ASSERT(m_which == CustomElementLifecycleCallbacks::EnteredView || m_which == CustomElementLifecycleCallbacks::LeftView);
 }
 
-void EnteredLeftDocumentInvocation::dispatch(Element* element)
+void EnteredLeftViewInvocation::dispatch(Element* element)
 {
     switch (m_which) {
-    case CustomElementLifecycleCallbacks::EnteredDocument:
-        callbacks()->enteredDocument(element);
+    case CustomElementLifecycleCallbacks::EnteredView:
+        callbacks()->enteredView(element);
         break;
-    case CustomElementLifecycleCallbacks::LeftDocument:
-        callbacks()->leftDocument(element);
+    case CustomElementLifecycleCallbacks::LeftView:
+        callbacks()->leftView(element);
         break;
     default:
         ASSERT_NOT_REACHED();
@@ -117,9 +117,9 @@
     case CustomElementLifecycleCallbacks::Created:
         return adoptPtr(new CreatedInvocation(callbacks));
 
-    case CustomElementLifecycleCallbacks::EnteredDocument:
-    case CustomElementLifecycleCallbacks::LeftDocument:
-        return adoptPtr(new EnteredLeftDocumentInvocation(callbacks, which));
+    case CustomElementLifecycleCallbacks::EnteredView:
+    case CustomElementLifecycleCallbacks::LeftView:
+        return adoptPtr(new EnteredLeftViewInvocation(callbacks, which));
 
     default:
         ASSERT_NOT_REACHED();
diff --git a/Source/core/dom/CustomElementCallbackScheduler.cpp b/Source/core/dom/CustomElementCallbackScheduler.cpp
index 79252ba..31c8252 100644
--- a/Source/core/dom/CustomElementCallbackScheduler.cpp
+++ b/Source/core/dom/CustomElementCallbackScheduler.cpp
@@ -56,22 +56,22 @@
     queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Created));
 }
 
-void CustomElementCallbackScheduler::scheduleEnteredDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+void CustomElementCallbackScheduler::scheduleEnteredViewCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
 {
-    if (!callbacks->hasEnteredDocumentCallback())
+    if (!callbacks->hasEnteredViewCallback())
         return;
 
     CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().schedule(element);
-    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::EnteredDocument));
+    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::EnteredView));
 }
 
-void CustomElementCallbackScheduler::scheduleLeftDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+void CustomElementCallbackScheduler::scheduleLeftViewCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
 {
-    if (!callbacks->hasLeftDocumentCallback())
+    if (!callbacks->hasLeftViewCallback())
         return;
 
     CustomElementCallbackQueue* queue = CustomElementCallbackDispatcher::instance().schedule(element);
-    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::LeftDocument));
+    queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::LeftView));
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/CustomElementCallbackScheduler.h b/Source/core/dom/CustomElementCallbackScheduler.h
index 3f5194e..42542e5 100644
--- a/Source/core/dom/CustomElementCallbackScheduler.h
+++ b/Source/core/dom/CustomElementCallbackScheduler.h
@@ -43,8 +43,8 @@
 public:
     static void scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
     static void scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
-    static void scheduleEnteredDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
-    static void scheduleLeftDocumentCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+    static void scheduleEnteredViewCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+    static void scheduleLeftViewCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
 
 private:
     CustomElementCallbackScheduler();
diff --git a/Source/core/dom/CustomElementException.cpp b/Source/core/dom/CustomElementException.cpp
index b5752a8..73b1717 100644
--- a/Source/core/dom/CustomElementException.cpp
+++ b/Source/core/dom/CustomElementException.cpp
@@ -64,22 +64,18 @@
         es.throwDOMException(NotSupportedError);
         return;
 
+    case ExtendsIsInvalidName:
+        es.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is not a valid tag name.");
+        return;
+
+    case ExtendsIsCustomElementName:
+        es.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is a custom element name. Use inheritance instead.");
+        return;
+
     case InvalidName:
         es.throwDOMException(InvalidCharacterError, preamble(type) + ": '" + type + "' is not a valid name.");
         return;
 
-    case NotYetImplemented:
-        es.throwDOMException(InvalidStateError);
-        return;
-
-    case PrototypeDoesNotExtendHTMLElementSVGElementNamespace:
-        es.throwDOMException(NamespaceError, preamble(type) + "the prototype does not extend an HTML or SVG element.");
-        return;
-
-    case PrototypeDoesNotExtendHTMLElementSVGElementPrototype:
-        es.throwDOMException(InvalidStateError, preamble(type) + "the prototype does not extend an HTML or SVG element.");
-        return;
-
     case PrototypeInUse:
         es.throwDOMException(NotSupportedError, preamble(type) + "prototype is already in-use as an interface prototype object.");
         return;
diff --git a/Source/core/dom/CustomElementException.h b/Source/core/dom/CustomElementException.h
index 622ef22..30bdb3b 100644
--- a/Source/core/dom/CustomElementException.h
+++ b/Source/core/dom/CustomElementException.h
@@ -46,10 +46,9 @@
         ContextDestroyedCheckingPrototype,
         ContextDestroyedCreatingCallbacks,
         ContextDestroyedRegisteringDefinition,
+        ExtendsIsInvalidName,
+        ExtendsIsCustomElementName,
         InvalidName,
-        NotYetImplemented,
-        PrototypeDoesNotExtendHTMLElementSVGElementNamespace,
-        PrototypeDoesNotExtendHTMLElementSVGElementPrototype,
         PrototypeInUse,
         PrototypeNotAnObject,
         TypeAlreadyRegistered
diff --git a/Source/core/dom/CustomElementLifecycleCallbacks.h b/Source/core/dom/CustomElementLifecycleCallbacks.h
index e48628d..eb2f32f 100644
--- a/Source/core/dom/CustomElementLifecycleCallbacks.h
+++ b/Source/core/dom/CustomElementLifecycleCallbacks.h
@@ -45,11 +45,11 @@
     bool hasCreatedCallback() const { return m_which & Created; }
     virtual void created(Element*) = 0;
 
-    bool hasEnteredDocumentCallback() const { return m_which & EnteredDocument; }
-    virtual void enteredDocument(Element*) = 0;
+    bool hasEnteredViewCallback() const { return m_which & EnteredView; }
+    virtual void enteredView(Element*) = 0;
 
-    bool hasLeftDocumentCallback() const { return m_which & LeftDocument; }
-    virtual void leftDocument(Element*) = 0;
+    bool hasLeftViewCallback() const { return m_which & LeftView; }
+    virtual void leftView(Element*) = 0;
 
     bool hasAttributeChangedCallback() const { return m_which & AttributeChanged; }
     virtual void attributeChanged(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue) = 0;
@@ -57,8 +57,8 @@
     enum CallbackType {
         None             = 0,
         Created          = 1 << 0,
-        EnteredDocument  = 1 << 1,
-        LeftDocument     = 1 << 2,
+        EnteredView      = 1 << 1,
+        LeftView         = 1 << 2,
         AttributeChanged = 1 << 3
     };
 
diff --git a/Source/core/dom/CustomElementRegistrationContext.cpp b/Source/core/dom/CustomElementRegistrationContext.cpp
index bedaf5e..6c4133f 100644
--- a/Source/core/dom/CustomElementRegistrationContext.cpp
+++ b/Source/core/dom/CustomElementRegistrationContext.cpp
@@ -58,13 +58,10 @@
         didResolveElement(definition, *it);
 }
 
-PassRefPtr<Element> CustomElementRegistrationContext::createCustomTagElement(Document* document, const QualifiedName& tagName, CreationMode mode)
+PassRefPtr<Element> CustomElementRegistrationContext::createCustomTagElement(Document& document, const QualifiedName& tagName, CreationMode mode)
 {
     ASSERT(CustomElement::isValidName(tagName.localName()));
 
-    if (!document)
-        return 0;
-
     RefPtr<Element> element;
 
     if (HTMLNames::xhtmlNamespaceURI == tagName.namespaceURI()) {
@@ -73,7 +70,7 @@
         element = SVGUnknownElement::create(tagName, document);
     } else {
         // XML elements are not custom elements, so return early.
-        return Element::create(tagName, document);
+        return Element::create(tagName, &document);
     }
 
     element->setCustomElementState(mode == CreatedByParser ? Element::WaitingForParser : Element::WaitingForUpgrade);
@@ -146,7 +143,7 @@
 
     element->setCustomElementState(mode == CreatedByParser ? Element::WaitingForParser : Element::WaitingForUpgrade);
 
-    if (CustomElementRegistrationContext* context = element->document()->registrationContext())
+    if (CustomElementRegistrationContext* context = element->document().registrationContext())
         context->didGiveTypeExtension(element, type);
 }
 
diff --git a/Source/core/dom/CustomElementRegistrationContext.h b/Source/core/dom/CustomElementRegistrationContext.h
index 7b8449f..7d23d72 100644
--- a/Source/core/dom/CustomElementRegistrationContext.h
+++ b/Source/core/dom/CustomElementRegistrationContext.h
@@ -62,7 +62,7 @@
         NotCreatedByParser
     };
 
-    PassRefPtr<Element> createCustomTagElement(Document*, const QualifiedName&, CreationMode = NotCreatedByParser);
+    PassRefPtr<Element> createCustomTagElement(Document&, const QualifiedName&, CreationMode = NotCreatedByParser);
     static void setIsAttributeAndTypeExtension(Element*, const AtomicString& type);
     static void setTypeExtension(Element*, const AtomicString& type, CreationMode = NotCreatedByParser);
 
diff --git a/Source/core/dom/CustomElementRegistry.cpp b/Source/core/dom/CustomElementRegistry.cpp
index b734c82..00d6d71 100644
--- a/Source/core/dom/CustomElementRegistry.cpp
+++ b/Source/core/dom/CustomElementRegistry.cpp
@@ -78,16 +78,13 @@
         return 0;
     }
 
-    if (!constructorBuilder->validateOptions(type, es))
+    QualifiedName tagName = nullQName();
+    if (!constructorBuilder->validateOptions(type, tagName, es))
         return 0;
 
-    QualifiedName tagName = nullQName();
-    if (!constructorBuilder->findTagName(type, tagName)) {
-        CustomElementException::throwException(CustomElementException::PrototypeDoesNotExtendHTMLElementSVGElementNamespace, type, es);
-        return 0;
-    }
     ASSERT(tagName.namespaceURI() == HTMLNames::xhtmlNamespaceURI || tagName.namespaceURI() == SVGNames::svgNamespaceURI);
 
+    // FIXME: This should be done earlier in validateOptions.
     if (m_registeredTypeNames.contains(type)) {
         CustomElementException::throwException(CustomElementException::TypeAlreadyRegistered, type, es);
         return 0;
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index 3b888bc..3215a6a 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -32,6 +32,7 @@
 #include "core/css/MediaList.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/ContextFeatures.h"
+#include "core/dom/CustomElementRegistrationContext.h"
 #include "core/dom/DocumentInit.h"
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
@@ -196,12 +197,14 @@
     const String& qualifiedName, DocumentType* doctype, ExceptionState& es)
 {
     RefPtr<Document> doc;
-    if (namespaceURI == SVGNames::svgNamespaceURI)
-        doc = SVGDocument::create();
-    else if (namespaceURI == HTMLNames::xhtmlNamespaceURI)
-        doc = Document::createXHTML(DocumentInit().withRegistrationContext(m_document->registrationContext()));
-    else
-        doc = Document::create();
+    DocumentInit init = DocumentInit::fromContext(m_document->contextDocument());
+    if (namespaceURI == SVGNames::svgNamespaceURI) {
+        doc = SVGDocument::create(init);
+    } else if (namespaceURI == HTMLNames::xhtmlNamespaceURI) {
+        doc = Document::createXHTML(init.withRegistrationContext(m_document->registrationContext()));
+    } else {
+        doc = Document::create(init);
+    }
 
     doc->setSecurityOrigin(m_document->securityOrigin());
     doc->setContextFeatures(m_document->contextFeatures());
@@ -304,7 +307,9 @@
 
 PassRefPtr<HTMLDocument> DOMImplementation::createHTMLDocument(const String& title)
 {
-    RefPtr<HTMLDocument> d = HTMLDocument::create(DocumentInit().withRegistrationContext(m_document->registrationContext()));
+    DocumentInit init = DocumentInit::fromContext(m_document->contextDocument())
+        .withRegistrationContext(m_document->registrationContext());
+    RefPtr<HTMLDocument> d = HTMLDocument::create(init);
     d->open();
     d->write("<!doctype html><html><body></body></html>");
     if (!title.isNull())
diff --git a/Source/core/html/DOMSettableTokenList.cpp b/Source/core/dom/DOMSettableTokenList.cpp
similarity index 98%
rename from Source/core/html/DOMSettableTokenList.cpp
rename to Source/core/dom/DOMSettableTokenList.cpp
index f311268..10692ca 100644
--- a/Source/core/html/DOMSettableTokenList.cpp
+++ b/Source/core/dom/DOMSettableTokenList.cpp
@@ -23,7 +23,7 @@
  */
 
 #include "config.h"
-#include "core/html/DOMSettableTokenList.h"
+#include "core/dom/DOMSettableTokenList.h"
 
 #include "bindings/v8/ExceptionState.h"
 
diff --git a/Source/core/html/DOMSettableTokenList.h b/Source/core/dom/DOMSettableTokenList.h
similarity index 98%
rename from Source/core/html/DOMSettableTokenList.h
rename to Source/core/dom/DOMSettableTokenList.h
index ed1a725..234b505 100644
--- a/Source/core/html/DOMSettableTokenList.h
+++ b/Source/core/dom/DOMSettableTokenList.h
@@ -25,8 +25,8 @@
 #ifndef DOMSettableTokenList_h
 #define DOMSettableTokenList_h
 
+#include "core/dom/DOMTokenList.h"
 #include "core/dom/SpaceSplitString.h"
-#include "core/html/DOMTokenList.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/AtomicString.h"
 
diff --git a/Source/core/html/DOMSettableTokenList.idl b/Source/core/dom/DOMSettableTokenList.idl
similarity index 100%
rename from Source/core/html/DOMSettableTokenList.idl
rename to Source/core/dom/DOMSettableTokenList.idl
diff --git a/Source/core/html/DOMTokenList.cpp b/Source/core/dom/DOMTokenList.cpp
similarity index 99%
rename from Source/core/html/DOMTokenList.cpp
rename to Source/core/dom/DOMTokenList.cpp
index 74f7279..9b48609 100644
--- a/Source/core/html/DOMTokenList.cpp
+++ b/Source/core/dom/DOMTokenList.cpp
@@ -23,7 +23,7 @@
  */
 
 #include "config.h"
-#include "core/html/DOMTokenList.h"
+#include "core/dom/DOMTokenList.h"
 
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
diff --git a/Source/core/html/DOMTokenList.h b/Source/core/dom/DOMTokenList.h
similarity index 98%
rename from Source/core/html/DOMTokenList.h
rename to Source/core/dom/DOMTokenList.h
index a476803..d758214 100644
--- a/Source/core/html/DOMTokenList.h
+++ b/Source/core/dom/DOMTokenList.h
@@ -41,7 +41,7 @@
     {
         ScriptWrappable::init(this);
     }
-    virtual ~DOMTokenList() {};
+    virtual ~DOMTokenList() { };
 
     virtual void ref() = 0;
     virtual void deref() = 0;
diff --git a/Source/core/html/DOMTokenList.idl b/Source/core/dom/DOMTokenList.idl
similarity index 100%
rename from Source/core/html/DOMTokenList.idl
rename to Source/core/dom/DOMTokenList.idl
diff --git a/Source/core/dom/DecodedDataDocumentParser.cpp b/Source/core/dom/DecodedDataDocumentParser.cpp
index 53c846b..06ce4e7 100644
--- a/Source/core/dom/DecodedDataDocumentParser.cpp
+++ b/Source/core/dom/DecodedDataDocumentParser.cpp
@@ -27,7 +27,7 @@
 #include "core/dom/DecodedDataDocumentParser.h"
 
 #include "core/dom/Document.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index bc0bd80..d04d081 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -43,6 +43,8 @@
 #include "bindings/v8/ScriptController.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/animation/DocumentTimeline.h"
+#include "core/css/CSSDefaultStyleSheets.h"
+#include "core/css/CSSFontSelector.h"
 #include "core/css/CSSStyleDeclaration.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/FontLoader.h"
@@ -50,6 +52,7 @@
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/StyleSheetList.h"
+#include "core/css/resolver/FontBuilder.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Attr.h"
 #include "core/dom/BeforeUnloadEvent.h"
@@ -77,11 +80,13 @@
 #include "core/dom/NodeFilter.h"
 #include "core/dom/NodeIterator.h"
 #include "core/dom/NodeRareData.h"
+#include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingTraversal.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/NodeWithIndex.h"
 #include "core/dom/PageTransitionEvent.h"
 #include "core/dom/PopStateEvent.h"
+#include "core/dom/PostAttachCallbacks.h"
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/QualifiedName.h"
 #include "core/dom/RequestAnimationFrameCallback.h"
@@ -100,6 +105,7 @@
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
 #include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/html/FormController.h"
 #include "core/html/HTMLAllCollection.h"
 #include "core/html/HTMLAnchorElement.h"
@@ -131,7 +137,6 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/ImageLoader.h"
 #include "core/loader/Prerenderer.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
@@ -153,6 +158,7 @@
 #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"
 #include "core/platform/chromium/TraceEvent.h"
 #include "core/platform/network/HTTPParsers.h"
@@ -298,7 +304,7 @@
     ASSERT(element->rendererIsEditable());
 
     Element* root = element->rootEditableElement();
-    Frame* frame = element->document()->frame();
+    Frame* frame = element->document().frame();
     if (!frame || !root)
         return false;
 
@@ -380,6 +386,7 @@
     , m_lastStyleResolverAccessTime(0)
     , m_didCalculateStyleResolver(false)
     , m_ignorePendingStylesheets(false)
+    , m_evaluateMediaQueriesOnStyleRecalc(false)
     , m_needsNotifyRemoveAllPendingStylesheet(false)
     , m_hasNodesWithPlaceholderStyle(false)
     , m_pendingSheetLayout(NoLayoutWithPendingSheets)
@@ -398,7 +405,7 @@
     , m_domTreeVersion(++s_globalTreeVersion)
     , m_listenerTypes(0)
     , m_mutationObserverTypes(0)
-    , m_styleSheetCollections(StyleSheetCollections::create(this))
+    , m_styleSheetCollections(StyleSheetCollections::create(*this))
     , m_visitedLinkState(VisitedLinkState::create(this))
     , m_visuallyOrdered(false)
     , m_readyState(Complete)
@@ -428,9 +435,11 @@
     , m_isViewSource(false)
     , m_sawElementsInKnownNamespaces(false)
     , m_isSrcdocDocument(false)
+    , m_isMobileDocument(false)
     , m_renderer(0)
     , m_eventQueue(DocumentEventQueue::create(this))
     , m_weakFactory(this)
+    , m_contextDocument(initializer.contextDocument())
     , m_idAttributeName(idAttr)
     , m_hasFullscreenElementStack(false)
     , m_loadEventDelayCount(0)
@@ -441,7 +450,6 @@
     , m_didAllowNavigationViaBeforeUnloadConfirmationPanel(false)
     , m_writeRecursionIsTooDeep(false)
     , m_writeRecursionDepth(0)
-    , m_wheelEventHandlerCount(0)
     , m_lastHandledUserGestureTimestamp(0)
     , m_prerenderer(Prerenderer::create(this))
     , m_textAutosizer(TextAutosizer::create(this))
@@ -503,7 +511,7 @@
     do {
         if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
             return false;
-    } while ((owner = owner->document()->ownerElement()));
+    } while ((owner = owner->document().ownerElement()));
     return true;
 }
 
@@ -668,7 +676,7 @@
     if (m_docType) {
         this->adoptIfNeeded(m_docType.get());
         if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
-            processViewport("width=device-width, height=device-height", ViewportArguments::XHTMLMobileProfile);
+            m_isMobileDocument = true;
     }
     // Doctype affects the interpretation of the stylesheets.
     clearStyleResolver();
@@ -721,7 +729,7 @@
     RefPtr<Element> element;
 
     if (CustomElement::isValidName(localName) && registrationContext())
-        element = registrationContext()->createCustomTagElement(this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
+        element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
     else
         element = createElement(localName, es);
 
@@ -745,7 +753,7 @@
 
     RefPtr<Element> element;
     if (CustomElement::isValidName(qName.localName()) && registrationContext())
-        element = registrationContext()->createCustomTagElement(this, qName);
+        element = registrationContext()->createCustomTagElement(*this, qName);
     else
         element = createElementNS(namespaceURI, qualifiedName, es);
 
@@ -795,12 +803,12 @@
 
 PassRefPtr<Text> Document::createTextNode(const String& data)
 {
-    return Text::create(this, data);
+    return Text::create(*this, data);
 }
 
 PassRefPtr<Comment> Document::createComment(const String& data)
 {
-    return Comment::create(this, data);
+    return Comment::create(*this, data);
 }
 
 PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& es)
@@ -813,7 +821,7 @@
         es.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
         return 0;
     }
-    return CDATASection::create(this, data);
+    return CDATASection::create(*this, data);
 }
 
 PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& es)
@@ -826,12 +834,12 @@
         es.throwDOMException(NotSupportedError);
         return 0;
     }
-    return ProcessingInstruction::create(this, target, data);
+    return ProcessingInstruction::create(*this, target, data);
 }
 
 PassRefPtr<Text> Document::createEditingTextNode(const String& text)
 {
-    return Text::createEditingText(this, text);
+    return Text::createEditingText(*this, text);
 }
 
 PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
@@ -881,14 +889,14 @@
         return newElement.release();
     }
     case ATTRIBUTE_NODE:
-        return Attr::create(this, QualifiedName(nullAtom, toAttr(importedNode)->name(), nullAtom), toAttr(importedNode)->value());
+        return Attr::create(*this, QualifiedName(nullAtom, toAttr(importedNode)->name(), nullAtom), toAttr(importedNode)->value());
     case DOCUMENT_FRAGMENT_NODE: {
         if (importedNode->isShadowRoot()) {
             // ShadowRoot nodes should not be explicitly importable.
             // Either they are imported along with their host node, or created implicitly.
             break;
         }
-        DocumentFragment* oldFragment = static_cast<DocumentFragment*>(importedNode);
+        DocumentFragment* oldFragment = toDocumentFragment(importedNode);
         RefPtr<DocumentFragment> newFragment = createDocumentFragment();
         if (deep) {
             for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
@@ -1009,7 +1017,7 @@
     if (e)
         m_sawElementsInKnownNamespaces = true;
     else
-        e = Element::create(qName, document());
+        e = Element::create(qName, &document());
 
     // <image> uses imgTag so we need a special rule.
     ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
@@ -1223,7 +1231,7 @@
     if (shadowAncestorNode != node) {
         unsigned offset = shadowAncestorNode->nodeIndex();
         ContainerNode* container = shadowAncestorNode->parentNode();
-        return Range::create(this, container, offset, container, offset);
+        return Range::create(*this, container, offset, container, offset);
     }
 
     RenderObject* renderer = node->renderer();
@@ -1234,7 +1242,7 @@
         return 0;
 
     Position rangeCompliantPosition = positionWithAffinity.position().parentAnchoredEquivalent();
-    return Range::create(this, rangeCompliantPosition, rangeCompliantPosition);
+    return Range::create(*this, rangeCompliantPosition, rangeCompliantPosition);
 }
 
 /*
@@ -1456,7 +1464,7 @@
 
 PassRefPtr<Range> Document::createRange()
 {
-    return Range::create(this);
+    return Range::create(*this);
 }
 
 PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& es)
@@ -1543,7 +1551,7 @@
     if (shouldDisplaySeamlesslyWithParent()) {
         // When we're seamless, our parent document manages our style recalcs.
         ownerElement()->setNeedsStyleRecalc();
-        ownerElement()->document()->scheduleStyleRecalc();
+        ownerElement()->document().scheduleStyleRecalc();
         return;
     }
 
@@ -1601,7 +1609,79 @@
         root->recalcDistribution();
 }
 
-void Document::recalcStyle(StyleChange change)
+void Document::setStyleDependentState(RenderStyle* documentStyle)
+{
+    const Pagination& pagination = view()->pagination();
+    if (pagination.mode != Pagination::Unpaginated) {
+        Pagination::setStylesForPaginationMode(pagination.mode, documentStyle);
+        documentStyle->setColumnGap(pagination.gap);
+        if (renderView()->hasColumns())
+            renderView()->updateColumnInfoFromStyle(documentStyle);
+    }
+
+    // Seamless iframes want to inherit their font from their parent iframe, so early return before setting the font.
+    if (shouldDisplaySeamlesslyWithParent())
+        return;
+
+    FontBuilder fontBuilder;
+    fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
+    RefPtr<CSSFontSelector> selector = m_styleResolver ? m_styleResolver->fontSelector() : 0;
+    fontBuilder.createFontForDocument(selector, documentStyle);
+}
+
+void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
+{
+    RenderView* renderView = this->renderView();
+
+    if (!documentElement() || !frame() || !view())
+        return;
+
+    RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
+    if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
+        documentElementStyle = styleResolver()->styleForElement(documentElement());
+
+    RefPtr<RenderStyle> bodyStyle = 0;
+    if (body()) {
+        bodyStyle = body()->renderStyle();
+        if (!bodyStyle || body()->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
+            bodyStyle = styleResolver()->styleForElement(body(), documentElementStyle.get());
+    }
+
+    WritingMode rootWritingMode = documentElementStyle->writingMode();
+    bool isHorizontalWritingMode = documentElementStyle->isHorizontalWritingMode();
+    TextDirection rootDirection = documentElementStyle->direction();
+
+    if (!writingModeSetOnDocumentElement() && body()) {
+        rootWritingMode = bodyStyle->writingMode();
+        isHorizontalWritingMode = bodyStyle->isHorizontalWritingMode();
+    }
+
+    if (!directionSetOnDocumentElement() && body())
+        rootDirection = bodyStyle->direction();
+
+    RefPtr<RenderStyle> documentStyle = renderView->style();
+    if (documentStyle->writingMode() != rootWritingMode || documentStyle->direction() != rootDirection) {
+        RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
+        newStyle->setWritingMode(rootWritingMode);
+        newStyle->setDirection(rootDirection);
+        renderView->setStyle(newStyle);
+        setStyleDependentState(newStyle.get());
+    }
+
+    if (body()) {
+        if (RenderStyle* style = body()->renderStyle()) {
+            if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
+                body()->setNeedsStyleRecalc();
+        }
+    }
+
+    if (RenderStyle* style = documentElement()->renderStyle()) {
+        if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
+            documentElement()->setNeedsStyleRecalc();
+    }
+}
+
+void Document::recalcStyle(StyleRecalcChange change)
 {
     // we should not enter style recalc while painting
     ASSERT(!view() || !view()->isPainting());
@@ -1614,6 +1694,11 @@
     TRACE_EVENT0("webkit", "Document::recalcStyle");
     TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "RecalcStyle");
 
+    if (m_evaluateMediaQueriesOnStyleRecalc) {
+        m_evaluateMediaQueriesOnStyleRecalc = false;
+        evaluateMediaQueryList();
+    }
+
     updateDistributionIfNeeded();
 
     // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
@@ -1633,7 +1718,7 @@
 
     m_inStyleRecalc = true;
     {
-        PostAttachCallbackDisabler disabler(this);
+        PostAttachCallbacks::SuspendScope suspendPostAttachCallbacks;
         WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
 
         RefPtr<FrameView> frameView = view();
@@ -1648,17 +1733,16 @@
         if (styleChangeType() >= SubtreeStyleChange)
             change = Force;
 
-        // Recalculating the root style (on the document) is not needed in the common case.
         if ((change == Force) || (shouldDisplaySeamlesslyWithParent() && (change >= Inherit))) {
-            // style selector may set this again during recalc
             m_hasNodesWithPlaceholderStyle = false;
-
-            RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
-            StyleChange ch = Node::diff(documentStyle.get(), renderer()->style(), this);
-            if (ch != NoChange)
+            RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
+            StyleRecalcChange localChange = RenderStyle::compare(documentStyle.get(), renderer()->style());
+            if (localChange != NoChange)
                 renderer()->setStyle(documentStyle.release());
         }
 
+        inheritHtmlAndBodyElementStyles(change);
+
         for (Node* n = firstChild(); n; n = n->nextSibling()) {
             if (!n->isElementNode())
                 continue;
@@ -1683,8 +1767,10 @@
         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)
+        if (m_styleResolver) {
             m_styleSheetCollections->resetCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
+            m_styleResolver->clearStyleSharingList();
+        }
 
         if (frameView) {
             frameView->resumeScheduledEvents();
@@ -1740,7 +1826,7 @@
     }
 
     if (Element* oe = ownerElement())
-        oe->document()->updateLayout();
+        oe->document().updateLayout();
 
     updateStyleIfNeeded();
 
@@ -1748,6 +1834,9 @@
     if (frameView && renderer() && (frameView->layoutPending() || renderer()->needsLayout()))
         frameView->layout();
 
+    if (frameView)
+        frameView->partialLayout().reset();
+
     setNeedsFocusedElementCheck();
 }
 
@@ -1760,6 +1849,31 @@
     m_didPostCheckFocusedElementTask = true;
 }
 
+void Document::recalcStyleForLayoutIgnoringPendingStylesheets()
+{
+    TemporaryChange<bool> ignorePendingStylesheets(m_ignorePendingStylesheets, m_ignorePendingStylesheets);
+    if (!haveStylesheetsLoaded()) {
+        m_ignorePendingStylesheets = true;
+        // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
+        // Our assumption is that it would be dangerous to try to stop it a second time, after page
+        // content has already been loaded and displayed with accurate style information. (Our
+        // suppression involves blanking the whole page at the moment. If it were more refined, we
+        // might be able to do something better.) It's worth noting though that this entire method
+        // is a hack, since what we really want to do is suspend JS instead of doing a layout with
+        // inaccurate information.
+        HTMLElement* bodyElement = body();
+        if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
+            m_pendingSheetLayout = DidLayoutWithPendingSheets;
+            styleResolverChanged(RecalcStyleImmediately);
+        } else if (m_hasNodesWithPlaceholderStyle) {
+            // If new nodes have been added or style recalc has been done with style sheets still
+            // pending, some nodes may not have had their real style calculated yet. Normally this
+            // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
+            recalcStyle(Force);
+        }
+    }
+}
+
 // FIXME: This is a bad idea and needs to be removed eventually.
 // Other browsers load stylesheets before they continue parsing the web page.
 // Since we don't, we can run JavaScript code that needs answers before the
@@ -1768,35 +1882,45 @@
 // to instead suspend JavaScript execution.
 void Document::updateLayoutIgnorePendingStylesheets()
 {
-    bool oldIgnore = m_ignorePendingStylesheets;
+    recalcStyleForLayoutIgnoringPendingStylesheets();
+    updateLayout();
+}
 
-    if (!haveStylesheetsLoaded()) {
-        m_ignorePendingStylesheets = true;
-        // FIXME: We are willing to attempt to suppress painting with outdated style info only once.  Our assumption is that it would be
-        // dangerous to try to stop it a second time, after page content has already been loaded and displayed
-        // with accurate style information.  (Our suppression involves blanking the whole page at the
-        // moment.  If it were more refined, we might be able to do something better.)
-        // It's worth noting though that this entire method is a hack, since what we really want to do is
-        // suspend JS instead of doing a layout with inaccurate information.
-        HTMLElement* bodyElement = body();
-        if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
-            m_pendingSheetLayout = DidLayoutWithPendingSheets;
-            styleResolverChanged(RecalcStyleImmediately);
-        } else if (m_hasNodesWithPlaceholderStyle)
-            // If new nodes have been added or style recalc has been done with style sheets still pending, some nodes
-            // may not have had their real style calculated yet. Normally this gets cleaned when style sheets arrive
-            // but here we need up-to-date style immediately.
-            recalcStyle(Force);
+void Document::partialUpdateLayoutIgnorePendingStylesheets(Node* stopLayoutAtNode)
+{
+    // Non-overlay scrollbars can cause a second layout that is dependent
+    // on a first layout. This is disabled for partial layout for now.
+    if (!RuntimeEnabledFeatures::partialLayoutEnabled() || !ScrollbarTheme::theme()->usesOverlayScrollbars()) {
+        updateLayoutIgnorePendingStylesheets();
+        return;
+    }
+
+    TemporaryChange<bool> ignorePendingStylesheets(m_ignorePendingStylesheets, m_ignorePendingStylesheets);
+    recalcStyleForLayoutIgnoringPendingStylesheets();
+
+    if (stopLayoutAtNode) {
+        RenderObject* renderer = stopLayoutAtNode->renderer();
+        bool canPartialLayout = renderer;
+        while (renderer) {
+            if (!renderer->supportsPartialLayout()) {
+                canPartialLayout = false;
+                break;
+            }
+            renderer = renderer->parent();
+        }
+        if (canPartialLayout && view())
+            view()->partialLayout().setStopAtRenderer(stopLayoutAtNode->renderer());
     }
 
     updateLayout();
 
-    m_ignorePendingStylesheets = oldIgnore;
+    if (view())
+        view()->partialLayout().reset();
 }
 
 PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
 {
-    ASSERT_ARG(element, element->document() == this);
+    ASSERT_ARG(element, &element->document() == this);
     TemporaryChange<bool> ignoreStyleSheets(m_ignorePendingStylesheets, true);
     return styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
 }
@@ -1865,7 +1989,7 @@
     bool matchAuthorAndUserStyles = true;
     if (Settings* docSettings = settings())
         matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
-    m_styleResolver = adoptPtr(new StyleResolver(this, matchAuthorAndUserStyles));
+    m_styleResolver = adoptPtr(new StyleResolver(*this, matchAuthorAndUserStyles));
     m_styleSheetCollections->combineCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
 }
 
@@ -1932,6 +2056,8 @@
 
     unscheduleStyleRecalc();
 
+    clearStyleResolver();
+
     if (render)
         render->destroy();
 
@@ -2038,9 +2164,9 @@
 
 PassRefPtr<DocumentParser> Document::createParser()
 {
-    if (isHTMLDocument() || (RuntimeEnabledFeatures::parseSVGAsHTMLEnabled() && isSVGDocument())) {
+    if (isHTMLDocument()) {
         bool reportErrors = InspectorInstrumentation::collectingHTMLParseErrors(this->page());
-        return HTMLDocumentParser::create(this, reportErrors);
+        return HTMLDocumentParser::create(toHTMLDocument(this), reportErrors);
     }
     // FIXME: this should probably pass the frame instead
     return XMLDocumentParser::create(this, view());
@@ -2181,10 +2307,10 @@
     if (!de)
         return 0;
 
-    for (Node* e = de->firstChild(); e; e = e->nextSibling())
-        if (e->hasTagName(headTag))
-            return static_cast<HTMLHeadElement*>(e);
-
+    for (Node* node = de->firstChild(); node; node = node->nextSibling()) {
+        if (node->hasTagName(headTag))
+            return toHTMLHeadElement(node);
+    }
     return 0;
 }
 
@@ -2713,7 +2839,7 @@
 {
     m_needsNotifyRemoveAllPendingStylesheet = false;
 
-    styleResolverChanged(RecalcStyleImmediately, AnalyzedStyleUpdate);
+    styleResolverChanged(RecalcStyleDeferred, AnalyzedStyleUpdate);
     executeScriptsWaitingForResourcesIfNeeded();
 
     if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
@@ -2915,19 +3041,70 @@
         String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
         callback(keyString, valueString, this, data);
     }
-    if (error)
-        reportViewportWarning(this, InvalidKeyValuePairSeparatorError, String(), String());
+    if (error) {
+        String message = "Error parsing a meta element's content: ';' is not a valid key-value pair separator. Please use ',' instead.";
+        addConsoleMessage(RenderingMessageSource, WarningMessageLevel, message);
+    }
 }
 
 void Document::processViewport(const String& features, ViewportArguments::Type origin)
 {
     ASSERT(!features.isNull());
 
-    if (origin < m_viewportArguments.type)
+    if (!page() || !shouldOverrideLegacyViewport(origin))
         return;
 
-    m_viewportArguments = ViewportArguments(origin);
-    processArguments(features, (void*)&m_viewportArguments, &setViewportFeature);
+    ViewportArguments newArgumentsFromLegacyTag(origin);
+    processArguments(features, (void*)&newArgumentsFromLegacyTag, &setViewportFeature);
+
+    if (newArgumentsFromLegacyTag.minZoom == ViewportArguments::ValueAuto)
+        newArgumentsFromLegacyTag.minZoom = 0.25;
+
+    if (newArgumentsFromLegacyTag.maxZoom == ViewportArguments::ValueAuto) {
+        newArgumentsFromLegacyTag.maxZoom = 5;
+        newArgumentsFromLegacyTag.minZoom = std::min(newArgumentsFromLegacyTag.minZoom, float(5));
+    }
+
+    const Settings& settings = document().page()->settings();
+
+    if (newArgumentsFromLegacyTag.maxWidth.isAuto()) {
+        if (newArgumentsFromLegacyTag.zoom == ViewportArguments::ValueAuto) {
+            newArgumentsFromLegacyTag.minWidth = Length(ExtendToZoom);
+            newArgumentsFromLegacyTag.maxWidth = Length(settings.layoutFallbackWidth(), Fixed);
+        } else if (newArgumentsFromLegacyTag.maxHeight.isAuto()) {
+            newArgumentsFromLegacyTag.minWidth = Length(ExtendToZoom);
+            newArgumentsFromLegacyTag.maxWidth = Length(ExtendToZoom);
+        }
+    }
+
+    if (settings.viewportMetaZeroValuesQuirk()
+        && newArgumentsFromLegacyTag.type == ViewportArguments::ViewportMeta
+        && newArgumentsFromLegacyTag.maxWidth.type() == ViewportPercentageWidth
+        && !static_cast<int>(newArgumentsFromLegacyTag.zoom)) {
+        newArgumentsFromLegacyTag.zoom = 1.0;
+    }
+
+    setViewportArguments(newArgumentsFromLegacyTag);
+}
+
+void Document::setViewportArguments(const ViewportArguments& viewportArguments)
+{
+    if (viewportArguments.isLegacyViewportType()) {
+        m_legacyViewportArguments = viewportArguments;
+
+        // When no author style for @viewport is present, and a meta tag for defining
+        // the viewport is, apply the meta tag viewport instead of the UA styles.
+        if (m_viewportArguments.type == ViewportArguments::AuthorStyleSheet)
+            return;
+        m_viewportArguments = viewportArguments;
+    } else {
+        // If the legacy viewport tag has higher priority than the cascaded @viewport
+        // descriptors, use the values from the legacy tag.
+        if (!shouldOverrideLegacyViewport(viewportArguments.type))
+            m_viewportArguments = m_legacyViewportArguments;
+        else
+            m_viewportArguments = viewportArguments;
+    }
 
     updateViewportArguments();
 }
@@ -3137,34 +3314,21 @@
 
     bool needsRecalc = m_styleSheetCollections->updateActiveStyleSheets(updateMode);
 
-    if (updateType >= RecalcStyleDeferred) {
-        setNeedsStyleRecalc();
-        return;
-    }
-
     if (didLayoutWithPendingStylesheets() && !m_styleSheetCollections->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;
-        if (renderer())
-            renderView()->repaintViewAndCompositedLayers();
+        renderView()->repaintViewAndCompositedLayers();
     }
 
     if (!needsRecalc)
         return;
 
-    // This recalcStyle initiates a new recalc cycle. We need to bracket it to
-    // make sure animations get the correct update time
-    {
-        AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
-        recalcStyle(Force);
-    }
+    m_evaluateMediaQueriesOnStyleRecalc = true;
+    setNeedsStyleRecalc();
 
-    if (renderer()) {
-        renderer()->setNeedsLayoutAndPrefWidthsRecalc();
-        if (view())
-            view()->scheduleRelayout();
-    }
-
-    evaluateMediaQueryList();
+    if (updateType == RecalcStyleImmediately)
+        updateStyleIfNeeded();
 }
 
 void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
@@ -3177,7 +3341,7 @@
     for (Frame* child = frame()->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
         Document* childDocument = child->document();
         if (childDocument->shouldDisplaySeamlesslyWithParent()) {
-            ASSERT(childDocument->seamlessParentIFrame()->document() == this);
+            ASSERT(&childDocument->seamlessParentIFrame()->document() == this);
             childDocument->seamlessParentUpdatedStylesheets();
         }
     }
@@ -3203,7 +3367,7 @@
     if (!m_focusedElement)
         return;
 
-    Element* focusedElement = node->treeScope()->adjustedFocusedElement();
+    Element* focusedElement = node->treeScope().adjustedFocusedElement();
     if (!focusedElement)
         return;
 
@@ -3270,7 +3434,7 @@
     RefPtr<Element> newFocusedElement = prpNewFocusedElement;
 
     // Make sure newFocusedNode is actually in this document
-    if (newFocusedElement && (newFocusedElement->document() != this))
+    if (newFocusedElement && (&newFocusedElement->document() != this))
         return true;
 
     if (m_focusedElement == newFocusedElement)
@@ -3396,7 +3560,7 @@
 SetFocusedElementDone:
     updateStyleIfNeeded();
     if (Frame* frame = this->frame())
-        frame->selection()->didChangeFocus();
+        frame->selection().didChangeFocus();
     return !focusChangeBlocked;
 }
 
@@ -3479,7 +3643,7 @@
     if (Frame* frame = this->frame()) {
         for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
             frame->eventHandler()->nodeWillBeRemoved(n);
-            frame->selection()->nodeWillBeRemoved(n);
+            frame->selection().nodeWillBeRemoved(n);
             frame->page()->dragCaretController().nodeWillBeRemoved(n);
         }
     }
@@ -3499,7 +3663,7 @@
 
     if (Frame* frame = this->frame()) {
         frame->eventHandler()->nodeWillBeRemoved(n);
-        frame->selection()->nodeWillBeRemoved(n);
+        frame->selection().nodeWillBeRemoved(n);
         frame->page()->dragCaretController().nodeWillBeRemoved(n);
     }
 }
@@ -3549,6 +3713,9 @@
             (*it)->textNodeSplit(oldNode);
     }
 
+    if (m_frame)
+        m_frame->selection().textNodeSplit(*oldNode);
+
     // FIXME: This should update markers for spelling and grammar checking.
 }
 
@@ -4132,14 +4299,23 @@
 
 Document* Document::topDocument() const
 {
-    Document* doc = const_cast<Document *>(this);
+    Document* doc = const_cast<Document*>(this);
     Element* element;
     while ((element = doc->ownerElement()))
-        doc = element->document();
+        doc = &element->document();
 
     return doc;
 }
 
+WeakPtr<Document> Document::contextDocument()
+{
+    if (m_contextDocument)
+        return m_contextDocument;
+    if (m_frame)
+        return m_weakFactory.createWeakPtr();
+    return WeakPtr<Document>(0);
+}
+
 PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionState& es)
 {
     return createAttributeNS(String(), name, es, true);
@@ -4158,7 +4334,7 @@
         return 0;
     }
 
-    return Attr::create(this, qName, emptyString());
+    return Attr::create(*this, qName, emptyString());
 }
 
 const SVGDocumentExtensions* Document::svgExtensions()
@@ -4353,7 +4529,7 @@
         return;
 
     m_useSecureKeyboardEntryWhenActive = usesSecureKeyboard;
-    m_frame->selection()->updateSecureKeyboardEntryIfActive();
+    m_frame->selection().updateSecureKeyboardEntryIfActive();
 }
 
 bool Document::useSecureKeyboardEntryWhenActive() const
@@ -4377,7 +4553,7 @@
 
 void Document::initSecurityContext()
 {
-    initSecurityContext(DocumentInit(m_url, m_frame, m_import));
+    initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_import));
 }
 
 void Document::initSecurityContext(const DocumentInit& initializer)
@@ -4421,7 +4597,7 @@
         }
     }
 
-    Document* parentDocument = ownerElement() ? ownerElement()->document() : 0;
+    Document* parentDocument = ownerElement() ? &ownerElement()->document() : 0;
     if (parentDocument && initializer.shouldTreatURLAsSrcdocDocument()) {
         m_isSrcdocDocument = true;
         setBaseURLOverride(parentDocument->baseURL());
@@ -4479,12 +4655,26 @@
         return false;
     if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
         return false;
-    if (node && node->document() != this && !node->document()->allowInlineEventHandlers(node, listener, contextURL, contextLine))
+    if (node && &node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
         return false;
 
     return true;
 }
 
+bool Document::allowExecutingScripts(Node* node)
+{
+    // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
+    // viewless document but this'll do for now.
+    // See http://bugs.webkit.org/show_bug.cgi?id=5727
+    if (!frame() && !import())
+        return false;
+    if (!node->document().frame() && !node->document().import())
+        return false;
+    if (!contextDocument().get()->frame()->script()->canExecuteScripts(AboutToExecuteScript))
+        return false;
+    return true;
+}
+
 void Document::didUpdateSecurityOrigin()
 {
     if (!m_frame)
@@ -4558,7 +4748,7 @@
 {
     RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, 0).iterator->value;
     if (!element) {
-        element = HTMLCanvasElement::create(this);
+        element = HTMLCanvasElement::create(*this);
         element->setAccelerationDisabled(true);
     }
     return element.get();
@@ -4790,7 +4980,7 @@
 {
     if (m_topLayerElements.isEmpty())
         return 0;
-    return static_cast<HTMLDialogElement*>(m_topLayerElements.last().get());
+    return toHTMLDialogElement(m_topLayerElements.last().get());
 }
 
 void Document::webkitExitPointerLock()
@@ -4798,7 +4988,7 @@
     if (!page())
         return;
     if (Element* target = page()->pointerLockController().element()) {
-        if (target->document() != this)
+        if (&target->document() != this)
             return;
     }
     page()->pointerLockController().requestPointerUnlock();
@@ -4809,7 +4999,7 @@
     if (!page() || page()->pointerLockController().lockPending())
         return 0;
     if (Element* element = page()->pointerLockController().element()) {
-        if (element->document() == this)
+        if (&element->document() == this)
             return element;
     }
     return 0;
@@ -4866,44 +5056,6 @@
     return Touch::create(frame, target, identifier, screenX, screenY, pageX, pageY, radiusX, radiusY, rotationAngle, force);
 }
 
-static void wheelEventHandlerCountChanged(Document* document)
-{
-    Page* page = document->page();
-    if (!page)
-        return;
-
-    ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
-    if (!scrollingCoordinator)
-        return;
-
-    FrameView* frameView = document->view();
-    if (!frameView)
-        return;
-
-    scrollingCoordinator->frameViewWheelEventHandlerCountChanged(frameView);
-}
-
-void Document::didAddWheelEventHandler()
-{
-    ++m_wheelEventHandlerCount;
-    Frame* mainFrame = page() ? page()->mainFrame() : 0;
-    if (mainFrame)
-        mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
-
-    wheelEventHandlerCountChanged(this);
-}
-
-void Document::didRemoveWheelEventHandler()
-{
-    ASSERT(m_wheelEventHandlerCount > 0);
-    --m_wheelEventHandlerCount;
-    Frame* mainFrame = page() ? page()->mainFrame() : 0;
-    if (mainFrame)
-        mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
-
-    wheelEventHandlerCountChanged(this);
-}
-
 void Document::didAddTouchEventHandler(Node* handler)
 {
     if (!m_touchEventTargets.get())
@@ -5090,9 +5242,9 @@
     ASSERT(!request.readOnly());
 
     Element* innerElementInDocument = innerElement;
-    while (innerElementInDocument && innerElementInDocument->document() != this) {
-        innerElementInDocument->document()->updateHoverActiveState(request, innerElementInDocument, event);
-        innerElementInDocument = innerElementInDocument->document()->ownerElement();
+    while (innerElementInDocument && &innerElementInDocument->document() != this) {
+        innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
+        innerElementInDocument = innerElementInDocument->document().ownerElement();
     }
 
     Element* oldActiveElement = activeElement();
@@ -5246,19 +5398,22 @@
     return *(result.iterator->value);
 }
 
-Document* Document::ensureTemplateDocument()
+Document& Document::ensureTemplateDocument()
 {
     if (const Document* document = templateDocument())
-        return const_cast<Document*>(document);
+        return *const_cast<Document*>(document);
 
-    if (isHTMLDocument())
-        m_templateDocument = HTMLDocument::create(DocumentInit(blankURL()).withRegistrationContext(registrationContext()));
-    else
+    if (isHTMLDocument()) {
+        DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL())
+            .withRegistrationContext(registrationContext());
+        m_templateDocument = HTMLDocument::create(init);
+    } else {
         m_templateDocument = Document::create(DocumentInit(blankURL()));
+    }
 
     m_templateDocument->setTemplateDocumentHost(this); // balanced in dtor.
 
-    return m_templateDocument.get();
+    return *m_templateDocument.get();
 }
 
 PassRefPtr<FontLoader> Document::fontloader()
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index b5fc9e6..1d0be02 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -289,11 +289,13 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitvisibilitychange);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(securitypolicyviolation);
 
-    void setViewportArguments(const ViewportArguments& viewportArguments) { m_viewportArguments = viewportArguments; }
+    bool shouldOverrideLegacyViewport(ViewportArguments::Type);
+    void setViewportArguments(const ViewportArguments&);
     const ViewportArguments& viewportArguments() const { return m_viewportArguments; }
 #ifndef NDEBUG
     bool didDispatchViewportPropertiesChanged() const { return m_didDispatchViewportPropertiesChanged; }
 #endif
+    bool hasLegacyViewportTag() const { return m_legacyViewportArguments.isLegacyViewportType(); }
 
     void setReferrerPolicy(ReferrerPolicy referrerPolicy) { m_referrerPolicy = referrerPolicy; }
     ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
@@ -417,6 +419,7 @@
     bool isFrameSet() const;
 
     bool isSrcdocDocument() const { return m_isSrcdocDocument; }
+    bool isMobileDocument() const { return m_isMobileDocument; }
 
     StyleResolver* styleResolverIfExists() const { return m_styleResolver.get(); }
 
@@ -484,11 +487,14 @@
     PassRefPtr<CSSStyleDeclaration> createCSSStyleDeclaration();
     PassRefPtr<Text> createEditingTextNode(const String&);
 
-    void recalcStyle(StyleChange = NoChange);
+    void setStyleDependentState(RenderStyle* documentStyle);
+    void inheritHtmlAndBodyElementStyles(StyleRecalcChange);
+    void recalcStyle(StyleRecalcChange);
     void updateStyleIfNeeded();
     void updateStyleForNodeIfNeeded(Node*);
     void updateLayout();
     void updateLayoutIgnorePendingStylesheets();
+    void partialUpdateLayoutIgnorePendingStylesheets(Node*);
     PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
     PassRefPtr<RenderStyle> styleForPage(int pageIndex);
 
@@ -838,6 +844,7 @@
 
     Document* parentDocument() const;
     Document* topDocument() const;
+    WeakPtr<Document> contextDocument();
 
     ScriptRunner* scriptRunner() { return m_scriptRunner.get(); }
 
@@ -921,6 +928,7 @@
     void initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders&);
 
     bool allowInlineEventHandlers(Node*, EventListener*, const String& contextURL, const WTF::OrdinalNumber& contextLine);
+    bool allowExecutingScripts(Node*);
 
     void statePopped(PassRefPtr<SerializedScriptValue>);
 
@@ -978,10 +986,6 @@
 
     void initDNSPrefetch();
 
-    unsigned wheelEventHandlerCount() const { return m_wheelEventHandlerCount; }
-    void didAddWheelEventHandler();
-    void didRemoveWheelEventHandler();
-
     double lastHandledUserGestureTimestamp() const { return m_lastHandledUserGestureTimestamp; }
     void resetLastHandledUserGestureTimestamp();
 
@@ -1048,7 +1052,7 @@
     HTMLDialogElement* activeModalDialog() const;
 
     const Document* templateDocument() const;
-    Document* ensureTemplateDocument();
+    Document& ensureTemplateDocument();
     void setTemplateDocumentHost(Document* templateDocumentHost) { m_templateDocumentHost = templateDocumentHost; }
     Document* templateDocumentHost() { return m_templateDocumentHost; }
 
@@ -1119,6 +1123,8 @@
 
     void seamlessParentUpdatedStylesheets();
 
+    void recalcStyleForLayoutIgnoringPendingStylesheets();
+
     PassRefPtr<NodeList> handleZeroPadding(const HitTestRequest&, HitTestResult&) const;
 
     void loadEventDelayTimerFired(Timer<Document>*);
@@ -1161,6 +1167,7 @@
     // But sometimes you need to ignore pending stylesheet count to
     // force an immediate layout when requested by JS.
     bool m_ignorePendingStylesheets;
+    bool m_evaluateMediaQueriesOnStyleRecalc;
 
     // If we do ignore the pending stylesheet count, then we need to add a boolean
     // to track that this happened so that we can do a full repaint when the stylesheets
@@ -1308,11 +1315,13 @@
     bool m_isViewSource;
     bool m_sawElementsInKnownNamespaces;
     bool m_isSrcdocDocument;
+    bool m_isMobileDocument;
 
     RenderObject* m_renderer;
     RefPtr<DocumentEventQueue> m_eventQueue;
 
     WeakPtrFactory<Document> m_weakFactory;
+    WeakPtr<Document> m_contextDocument;
 
     QualifiedName m_idAttributeName;
 
@@ -1324,6 +1333,7 @@
     Timer<Document> m_loadEventDelayTimer;
 
     ViewportArguments m_viewportArguments;
+    ViewportArguments m_legacyViewportArguments;
 
     ReferrerPolicy m_referrerPolicy;
 
@@ -1337,7 +1347,6 @@
     bool m_writeRecursionIsTooDeep;
     unsigned m_writeRecursionDepth;
 
-    unsigned m_wheelEventHandlerCount;
     OwnPtr<TouchEventTargetSet> m_touchEventTargets;
 
     double m_lastHandledUserGestureTimestamp;
@@ -1397,6 +1406,14 @@
     return m_templateDocument.get();
 }
 
+inline bool Document::shouldOverrideLegacyViewport(ViewportArguments::Type origin)
+{
+    // The different (legacy) meta tags have different priorities based on the type
+    // regardless of which order they appear in the DOM. The priority is given by the
+    // ViewportArguments::Type enum.
+    return origin >= m_legacyViewportArguments.type;
+}
+
 inline Document* toDocument(ScriptExecutionContext* scriptExecutionContext)
 {
     ASSERT_WITH_SECURITY_IMPLICATION(!scriptExecutionContext || scriptExecutionContext->isDocument());
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index bea2b66..f2fba14 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -165,9 +165,9 @@
     void webkitExitPointerLock();
     readonly attribute Element webkitPointerLockElement;
 
-    [EnabledAtRuntime=cssRegions] WebKitNamedFlowCollection webkitGetNamedFlows();
+    [EnabledAtRuntime=CSSRegions] WebKitNamedFlowCollection webkitGetNamedFlows();
 
-    [EnabledAtRuntime=fontLoadEvents] readonly attribute FontLoader fontloader;
+    [EnabledAtRuntime=FontLoadEvents] readonly attribute FontLoader fontloader;
 
     // Event handler DOM attributes
     [NotEnumerable] attribute EventHandler onabort;
@@ -238,17 +238,17 @@
     [NotEnumerable] attribute EventHandler onsearch;
     [NotEnumerable] attribute EventHandler onselectstart;
     [NotEnumerable] attribute EventHandler onselectionchange;
-    [NotEnumerable,EnabledAtRuntime=touch] attribute EventHandler ontouchstart;
-    [NotEnumerable,EnabledAtRuntime=touch] attribute EventHandler ontouchmove;
-    [NotEnumerable,EnabledAtRuntime=touch] attribute EventHandler ontouchend;
-    [NotEnumerable,EnabledAtRuntime=touch] attribute EventHandler ontouchcancel;
+    [NotEnumerable, EnabledAtRuntime=Touch] attribute EventHandler ontouchstart;
+    [NotEnumerable, EnabledAtRuntime=Touch] attribute EventHandler ontouchmove;
+    [NotEnumerable, EnabledAtRuntime=Touch] attribute EventHandler ontouchend;
+    [NotEnumerable, EnabledAtRuntime=Touch] attribute EventHandler ontouchcancel;
     [NotEnumerable] attribute EventHandler onwebkitfullscreenchange;
     [NotEnumerable] attribute EventHandler onwebkitfullscreenerror;
     [NotEnumerable] attribute EventHandler onwebkitpointerlockchange;
     [NotEnumerable] attribute EventHandler onwebkitpointerlockerror;
-    [NotEnumerable, EnabledAtRuntime=experimentalContentSecurityPolicyFeatures] attribute EventHandler onsecuritypolicyviolation;
+    [NotEnumerable, EnabledAtRuntime=ExperimentalContentSecurityPolicyFeatures] attribute EventHandler onsecuritypolicyviolation;
 
-    [EnabledAtRuntime=touch] Touch createTouch([Default=Undefined] optional Window window,
+    [EnabledAtRuntime=Touch] Touch createTouch([Default=Undefined] optional Window window,
                                                [Default=Undefined] optional EventTarget target,
                                                [Default=Undefined] optional long identifier,
                                                [Default=Undefined] optional long pageX,
@@ -259,10 +259,10 @@
                                                [Default=Undefined] optional long webkitRadiusY,
                                                [Default=Undefined] optional float webkitRotationAngle,
                                                [Default=Undefined] optional float webkitForce);
-    [EnabledAtRuntime=touch, Custom, RaisesException] TouchList createTouchList();
+    [EnabledAtRuntime=Touch, Custom, RaisesException] TouchList createTouchList();
 
-    [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);
+    [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);
     [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElement(DOMString localName, [TreatNullAs=NullString] DOMString typeExtension);
     [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName,
                             [TreatNullAs=NullString] DOMString typeExtension);
@@ -272,7 +272,7 @@
     readonly attribute boolean webkitHidden;
 
     // Security Policy API: http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html#script-interfaces
-    [EnabledAtRuntime=experimentalContentSecurityPolicyFeatures] readonly attribute SecurityPolicy securityPolicy;
+    [EnabledAtRuntime=ExperimentalContentSecurityPolicyFeatures] readonly attribute SecurityPolicy securityPolicy;
 
     readonly attribute HTMLScriptElement currentScript;
 };
diff --git a/Source/core/dom/DocumentEventQueue.cpp b/Source/core/dom/DocumentEventQueue.cpp
index 8768c1e..eba99c1 100644
--- a/Source/core/dom/DocumentEventQueue.cpp
+++ b/Source/core/dom/DocumentEventQueue.cpp
@@ -80,12 +80,11 @@
 
 void DocumentEventQueue::enqueueOrDispatchScrollEvent(PassRefPtr<Node> target, ScrollEventTargetType targetType)
 {
-    if (!target->document()->hasListenerType(Document::SCROLL_LISTENER))
+    if (!target->document().hasListenerType(Document::SCROLL_LISTENER))
         return;
 
     // Per the W3C CSSOM View Module, scroll events fired at the document should bubble, others should not.
-    bool canBubble = targetType == ScrollEventDocumentTarget;
-    RefPtr<Event> scrollEvent = Event::create(eventNames().scrollEvent, canBubble, false /* non cancelleable */);
+    RefPtr<Event> scrollEvent = targetType == ScrollEventDocumentTarget ? Event::createBubble(eventNames().scrollEvent) : Event::create(eventNames().scrollEvent);
 
     if (!m_nodesWithQueuedScrollEvents.add(target.get()).isNewEntry)
         return;
diff --git a/Source/core/dom/DocumentFragment.cpp b/Source/core/dom/DocumentFragment.cpp
index 6f052be..141d571 100644
--- a/Source/core/dom/DocumentFragment.cpp
+++ b/Source/core/dom/DocumentFragment.cpp
@@ -35,10 +35,9 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<DocumentFragment> DocumentFragment::create(Document* document)
+PassRefPtr<DocumentFragment> DocumentFragment::create(Document& document)
 {
-    ASSERT(document);
-    return adoptRef(new DocumentFragment(document, Node::CreateDocumentFragment));
+    return adoptRef(new DocumentFragment(&document, Node::CreateDocumentFragment));
 }
 
 String DocumentFragment::nodeName() const
diff --git a/Source/core/dom/DocumentFragment.h b/Source/core/dom/DocumentFragment.h
index 82e7f6e..ed8a76a 100644
--- a/Source/core/dom/DocumentFragment.h
+++ b/Source/core/dom/DocumentFragment.h
@@ -33,7 +33,7 @@
 
 class DocumentFragment : public ContainerNode {
 public:
-    static PassRefPtr<DocumentFragment> create(Document*);
+    static PassRefPtr<DocumentFragment> create(Document&);
 
     void parseHTML(const String&, Element* contextElement, ParserContentPolicy = AllowScriptingContent);
     bool parseXML(const String&, Element* contextElement, ParserContentPolicy = AllowScriptingContent);
@@ -51,6 +51,18 @@
     virtual bool childTypeAllowed(NodeType) const;
 };
 
-} //namespace
+inline DocumentFragment* toDocumentFragment(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::DOCUMENT_FRAGMENT_NODE);
+    return static_cast<DocumentFragment*>(node);
+}
+
+inline const DocumentFragment* toDocumentFragment(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::DOCUMENT_FRAGMENT_NODE);
+    return static_cast<const DocumentFragment*>(node);
+}
+
+} // namespace WebCore
 
 #endif
diff --git a/Source/core/dom/DocumentFullscreen.idl b/Source/core/dom/DocumentFullscreen.idl
index 854492e..3081eac 100644
--- a/Source/core/dom/DocumentFullscreen.idl
+++ b/Source/core/dom/DocumentFullscreen.idl
@@ -20,13 +20,13 @@
  */
 partial interface Document {
     // Mozilla version
-    [EnabledAtRuntime=fullscreen] readonly attribute boolean webkitIsFullScreen;
-    [EnabledAtRuntime=fullscreen] readonly attribute boolean webkitFullScreenKeyboardInputAllowed;
-    [EnabledAtRuntime=fullscreen] readonly attribute Element webkitCurrentFullScreenElement;
-    [EnabledAtRuntime=fullscreen] void webkitCancelFullScreen();
+    [EnabledAtRuntime=Fullscreen] readonly attribute boolean webkitIsFullScreen;
+    [EnabledAtRuntime=Fullscreen] readonly attribute boolean webkitFullScreenKeyboardInputAllowed;
+    [EnabledAtRuntime=Fullscreen] readonly attribute Element webkitCurrentFullScreenElement;
+    [EnabledAtRuntime=Fullscreen] void webkitCancelFullScreen();
 
     // W3C version
-    [EnabledAtRuntime=fullscreen] readonly attribute boolean webkitFullscreenEnabled;
-    [EnabledAtRuntime=fullscreen] readonly attribute Element webkitFullscreenElement;
-    [EnabledAtRuntime=fullscreen] void webkitExitFullscreen();
+    [EnabledAtRuntime=Fullscreen] readonly attribute boolean webkitFullscreenEnabled;
+    [EnabledAtRuntime=Fullscreen] readonly attribute Element webkitFullscreenElement;
+    [EnabledAtRuntime=Fullscreen] void webkitExitFullscreen();
 };
diff --git a/Source/core/dom/DocumentInit.cpp b/Source/core/dom/DocumentInit.cpp
index caa4f8f..ba30041 100644
--- a/Source/core/dom/DocumentInit.cpp
+++ b/Source/core/dom/DocumentInit.cpp
@@ -29,12 +29,34 @@
 #include "core/dom/DocumentInit.h"
 
 #include "RuntimeEnabledFeatures.h"
+#include "core/dom/CustomElementRegistrationContext.h"
 #include "core/dom/Document.h"
 #include "core/html/HTMLImportsController.h"
 #include "core/page/Frame.h"
 
 namespace WebCore {
 
+DocumentInit::DocumentInit(const KURL& url, Frame* frame, WeakPtr<Document> contextDocument, HTMLImport* import)
+    : m_url(url)
+    , m_frame(frame)
+    , m_contextDocument(contextDocument)
+    , m_import(import)
+{
+}
+
+DocumentInit::DocumentInit(const DocumentInit& other)
+    : m_url(other.m_url)
+    , m_frame(other.m_frame)
+    , m_contextDocument(other.m_contextDocument)
+    , m_import(other.m_import)
+    , m_registrationContext(other.m_registrationContext)
+{
+}
+
+DocumentInit::~DocumentInit()
+{
+}
+
 bool DocumentInit::shouldSetURL() const
 {
     Frame* frame = frameForSecurityContext();
@@ -100,5 +122,15 @@
     return CustomElementRegistrationContext::create();
 }
 
+WeakPtr<Document> DocumentInit::contextDocument() const
+{
+    return m_contextDocument;
+}
+
+DocumentInit DocumentInit::fromContext(WeakPtr<Document> contextDocument, const KURL& url)
+{
+    return DocumentInit(url, 0, contextDocument, 0);
+}
+
 } // namespace WebCore
 
diff --git a/Source/core/dom/DocumentInit.h b/Source/core/dom/DocumentInit.h
index 73ce2be..b647e4e 100644
--- a/Source/core/dom/DocumentInit.h
+++ b/Source/core/dom/DocumentInit.h
@@ -28,14 +28,15 @@
 #ifndef DocumentInit_h
 #define DocumentInit_h
 
-#include "core/dom/CustomElementRegistrationContext.h"
 #include "core/dom/SecurityContext.h"
 #include "weborigin/KURL.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
+class CustomElementRegistrationContext;
 class Document;
 class Frame;
 class HTMLImport;
@@ -43,11 +44,9 @@
 
 class DocumentInit {
 public:
-    explicit DocumentInit(const KURL& url = KURL(), Frame* frame = 0, HTMLImport* import = 0)
-        : m_url(url)
-        , m_frame(frame)
-        , m_import(import)
-    { }
+    explicit DocumentInit(const KURL& = KURL(), Frame* = 0, WeakPtr<Document> = WeakPtr<Document>(), HTMLImport* = 0);
+    DocumentInit(const DocumentInit&);
+    ~DocumentInit();
 
     const KURL& url() const { return m_url; }
     Frame* frame() const { return m_frame; }
@@ -63,12 +62,16 @@
 
     DocumentInit& withRegistrationContext(CustomElementRegistrationContext*);
     PassRefPtr<CustomElementRegistrationContext> registrationContext(Document*) const;
+    WeakPtr<Document> contextDocument() const;
+
+    static DocumentInit fromContext(WeakPtr<Document> contextDocument, const KURL& = KURL());
 
 private:
     Frame* frameForSecurityContext() const;
 
     KURL m_url;
     Frame* m_frame;
+    WeakPtr<Document> m_contextDocument;
     HTMLImport* m_import;
     RefPtr<CustomElementRegistrationContext> m_registrationContext;
 };
diff --git a/Source/core/dom/DocumentMarkerController.cpp b/Source/core/dom/DocumentMarkerController.cpp
index 168772b..0682b64 100644
--- a/Source/core/dom/DocumentMarkerController.cpp
+++ b/Source/core/dom/DocumentMarkerController.cpp
@@ -346,20 +346,6 @@
     return result;
 }
 
-// FIXME: Should be removed after all relevant patches are landed
-Vector<DocumentMarker> DocumentMarkerController::markersForNode(Node* node)
-{
-    Vector<DocumentMarker> result;
-    MarkerList* list = m_markers.get(node);
-    if (!list)
-        return result;
-
-    for (size_t i = 0; i < list->size(); ++i)
-        result.append(list->at(i));
-
-    return result;
-}
-
 Vector<DocumentMarker*> DocumentMarkerController::markers()
 {
     Vector<DocumentMarker*> result;
diff --git a/Source/core/dom/DocumentMarkerController.h b/Source/core/dom/DocumentMarkerController.h
index 59fca3e..0b14aaa 100644
--- a/Source/core/dom/DocumentMarkerController.h
+++ b/Source/core/dom/DocumentMarkerController.h
@@ -76,7 +76,6 @@
     DocumentMarker* markerContainingPoint(const LayoutPoint&, DocumentMarker::MarkerType);
     Vector<DocumentMarker*> markersFor(Node*, DocumentMarker::MarkerTypes = DocumentMarker::AllMarkers());
     Vector<DocumentMarker*> markersInRange(Range*, DocumentMarker::MarkerTypes);
-    Vector<DocumentMarker> markersForNode(Node*);
     Vector<DocumentMarker*> markers();
     Vector<IntRect> renderedRectsForMarkers(DocumentMarker::MarkerType);
 
diff --git a/Source/core/dom/DocumentStyleSheetCollection.cpp b/Source/core/dom/DocumentStyleSheetCollection.cpp
index 3fa1ce5..8055751 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -45,10 +45,10 @@
 
 using namespace HTMLNames;
 
-DocumentStyleSheetCollection::DocumentStyleSheetCollection(TreeScope* treeScope)
+DocumentStyleSheetCollection::DocumentStyleSheetCollection(TreeScope& treeScope)
     : StyleSheetCollection(treeScope)
 {
-    ASSERT(treeScope->rootNode() == treeScope->rootNode()->document());
+    ASSERT(treeScope.rootNode() == &treeScope.rootNode()->document());
 }
 
 void DocumentStyleSheetCollection::collectStyleSheets(StyleSheetCollections* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
@@ -65,7 +65,7 @@
         if (n->nodeType() == Node::PROCESSING_INSTRUCTION_NODE && !document()->isHTMLDocument()) {
             // Processing instruction (XML documents only).
             // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
-            ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
+            ProcessingInstruction* pi = toProcessingInstruction(n);
             // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
             if (pi->isXSL() && !document()->transformSourceDocument()) {
                 // Don't apply XSL transforms until loading is finished.
@@ -102,7 +102,7 @@
             } else if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag)) {
                 sheet = static_cast<SVGStyleElement*>(n)->sheet();
             } else {
-                sheet = static_cast<HTMLStyleElement*>(n)->sheet();
+                sheet = toHTMLStyleElement(n)->sheet();
             }
 
             if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
@@ -143,7 +143,7 @@
     HTMLIFrameElement* seamlessParentIFrame = document->seamlessParentIFrame();
     if (!seamlessParentIFrame)
         return;
-    sheets.append(seamlessParentIFrame->document()->styleSheetCollections()->activeAuthorStyleSheets());
+    sheets.append(seamlessParentIFrame->document().styleSheetCollections()->activeAuthorStyleSheets());
 }
 
 bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleSheetCollections* collections, StyleResolverUpdateMode updateMode)
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index 4072cc8..9f035f0 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -41,7 +41,7 @@
 class DocumentStyleSheetCollection FINAL : public StyleSheetCollection {
     WTF_MAKE_NONCOPYABLE(DocumentStyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit DocumentStyleSheetCollection(TreeScope*);
+    explicit DocumentStyleSheetCollection(TreeScope&);
 
     bool updateActiveStyleSheets(StyleSheetCollections*, StyleResolverUpdateMode);
 
diff --git a/Source/core/dom/DocumentType.cpp b/Source/core/dom/DocumentType.cpp
index 12fbd2f..7c392a7 100644
--- a/Source/core/dom/DocumentType.cpp
+++ b/Source/core/dom/DocumentType.cpp
@@ -54,7 +54,7 @@
 
 PassRefPtr<Node> DocumentType::cloneNode(bool /*deep*/)
 {
-    return create(document(), m_name, m_publicId, m_systemId);
+    return create(&document(), m_name, m_publicId, m_systemId);
 }
 
 Node::InsertionNotificationRequest DocumentType::insertedInto(ContainerNode* insertionPoint)
@@ -64,14 +64,14 @@
     // DocumentType can only be inserted into a Document.
     ASSERT(parentNode()->isDocumentNode());
 
-    document()->setDoctype(this);
+    document().setDoctype(this);
 
     return InsertionDone;
 }
 
 void DocumentType::removedFrom(ContainerNode* insertionPoint)
 {
-    document()->setDoctype(0);
+    document().setDoctype(0);
     Node::removedFrom(insertionPoint);
 }
 
diff --git a/Source/core/dom/DocumentType.h b/Source/core/dom/DocumentType.h
index 0ad56fa..7da8ac8 100644
--- a/Source/core/dom/DocumentType.h
+++ b/Source/core/dom/DocumentType.h
@@ -64,6 +64,18 @@
     String m_subset;
 };
 
+inline DocumentType* toDocumentType(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::DOCUMENT_TYPE_NODE);
+    return static_cast<DocumentType*>(node);
+}
+
+inline const DocumentType* toDocumentType(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::DOCUMENT_TYPE_NODE);
+    return static_cast<const DocumentType*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index ce5e91a..02518c5 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -61,6 +61,7 @@
 #include "core/dom/NamedNodeMap.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingContext.h"
+#include "core/dom/PostAttachCallbacks.h"
 #include "core/dom/PseudoElement.h"
 #include "core/dom/ScriptableDocumentParser.h"
 #include "core/dom/SelectorQuery.h"
@@ -104,7 +105,7 @@
 
 static inline bool shouldIgnoreAttributeCase(const Element* e)
 {
-    return e && e->document()->isHTMLDocument() && e->isHTMLElement();
+    return e && e->document().isHTMLDocument() && e->isHTMLElement();
 }
 
 class StyleResolverParentPusher {
@@ -118,7 +119,7 @@
     {
         if (m_pushedStyleResolver)
             return;
-        m_pushedStyleResolver = m_parent->document()->styleResolver();
+        m_pushedStyleResolver = m_parent->document().styleResolver();
         m_pushedStyleResolver->pushParentElement(m_parent);
     }
     ~StyleResolverParentPusher()
@@ -129,8 +130,8 @@
 
         // This tells us that our pushed style selector is in a bad state,
         // so we should just bail out in that scenario.
-        ASSERT(m_pushedStyleResolver == m_parent->document()->styleResolver());
-        if (m_pushedStyleResolver != m_parent->document()->styleResolver())
+        ASSERT(m_pushedStyleResolver == m_parent->document().styleResolver());
+        if (m_pushedStyleResolver != m_parent->document().styleResolver())
             return;
 
         m_pushedStyleResolver->popParentElement(m_parent);
@@ -195,7 +196,7 @@
 Element::~Element()
 {
 #ifndef NDEBUG
-    if (document() && document()->renderer()) {
+    if (document().renderer()) {
         // When the document is not destroyed, an element that was part of a named flow
         // content nodes should have been removed from the content nodes collection
         // and the inNamedFlow flag reset.
@@ -226,7 +227,7 @@
         detachAllAttrNodesFromElement();
 
     if (hasPendingResources()) {
-        document()->accessSVGExtensions()->removeElementFromPendingResources(this);
+        document().accessSVGExtensions()->removeElementFromPendingResources(this);
         ASSERT(!hasPendingResources());
     }
 }
@@ -284,7 +285,7 @@
         // We can't just use needsStyleRecalc() because if the node is in a
         // display:none tree it might say it needs style recalc but the whole
         // document is actually up to date.
-        ASSERT(!document()->childNeedsStyleRecalc());
+        ASSERT(!document().childNeedsStyleRecalc());
     }
 
     // FIXME: Even if we are not visible, we might have a child that is visible.
@@ -325,7 +326,7 @@
 
 PassRefPtr<Element> Element::cloneElementWithoutAttributesAndChildren()
 {
-    return document()->createElement(tagQName(), false);
+    return document().createElement(tagQName(), false);
 }
 
 PassRefPtr<Attr> Element::detachAttribute(size_t index)
@@ -480,7 +481,7 @@
 
 void Element::scrollIntoView(bool alignToTop)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (!renderer())
         return;
@@ -495,7 +496,7 @@
 
 void Element::scrollIntoViewIfNeeded(bool centerIfNeeded)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (!renderer())
         return;
@@ -509,7 +510,7 @@
 
 void Element::scrollByUnits(int units, ScrollGranularity granularity)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (!renderer())
         return;
@@ -569,7 +570,7 @@
 
 int Element::offsetLeft()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().partialUpdateLayoutIgnorePendingStylesheets(this);
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
         return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
     return 0;
@@ -577,7 +578,7 @@
 
 int Element::offsetTop()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().partialUpdateLayoutIgnorePendingStylesheets(this);
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
         return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
     return 0;
@@ -585,14 +586,14 @@
 
 int Element::offsetWidth()
 {
-    document()->updateStyleForNodeIfNeeded(this);
+    document().updateStyleForNodeIfNeeded(this);
 
     if (RenderBox* renderer = renderBox()) {
         if (!renderer->requiresLayoutToDetermineWidth())
             return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
     }
 
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().partialUpdateLayoutIgnorePendingStylesheets(this);
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
         return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
     return 0;
@@ -600,7 +601,7 @@
 
 int Element::offsetHeight()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().partialUpdateLayoutIgnorePendingStylesheets(this);
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
         return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
     return 0;
@@ -616,7 +617,7 @@
 
 Element* Element::offsetParent()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     if (RenderObject* renderer = this->renderer())
         return renderer->offsetParent();
     return 0;
@@ -624,7 +625,7 @@
 
 int Element::clientLeft()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (RenderBox* renderer = renderBox())
         return adjustForAbsoluteZoom(roundToInt(renderer->clientLeft()), renderer);
@@ -633,7 +634,7 @@
 
 int Element::clientTop()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (RenderBox* renderer = renderBox())
         return adjustForAbsoluteZoom(roundToInt(renderer->clientTop()), renderer);
@@ -642,15 +643,15 @@
 
 int Element::clientWidth()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     // When in strict mode, clientWidth for the document element should return the width of the containing frame.
     // When in quirks mode, clientWidth for the body element should return the width of the containing frame.
-    bool inQuirksMode = document()->inQuirksMode();
-    if ((!inQuirksMode && document()->documentElement() == this) ||
-        (inQuirksMode && isHTMLElement() && document()->body() == this)) {
-        if (FrameView* view = document()->view()) {
-            if (RenderView* renderView = document()->renderView())
+    bool inQuirksMode = document().inQuirksMode();
+    if ((!inQuirksMode && document().documentElement() == this)
+        || (inQuirksMode && isHTMLElement() && document().body() == this)) {
+        if (FrameView* view = document().view()) {
+            if (RenderView* renderView = document().renderView())
                 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
         }
     }
@@ -662,16 +663,16 @@
 
 int Element::clientHeight()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     // When in strict mode, clientHeight for the document element should return the height of the containing frame.
     // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
-    bool inQuirksMode = document()->inQuirksMode();
+    bool inQuirksMode = document().inQuirksMode();
 
-    if ((!inQuirksMode && document()->documentElement() == this) ||
-        (inQuirksMode && isHTMLElement() && document()->body() == this)) {
-        if (FrameView* view = document()->view()) {
-            if (RenderView* renderView = document()->renderView())
+    if ((!inQuirksMode && document().documentElement() == this)
+        || (inQuirksMode && isHTMLElement() && document().body() == this)) {
+        if (FrameView* view = document().view()) {
+            if (RenderView* renderView = document().renderView())
                 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
         }
     }
@@ -683,7 +684,7 @@
 
 int Element::scrollLeft()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     if (RenderBox* rend = renderBox())
         return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
     return 0;
@@ -691,7 +692,7 @@
 
 int Element::scrollTop()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     if (RenderBox* rend = renderBox())
         return adjustForAbsoluteZoom(rend->scrollTop(), rend);
     return 0;
@@ -699,21 +700,21 @@
 
 void Element::setScrollLeft(int newLeft)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     if (RenderBox* rend = renderBox())
         rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
 }
 
 void Element::setScrollTop(int newTop)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     if (RenderBox* rend = renderBox())
         rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
 }
 
 int Element::scrollWidth()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     if (RenderBox* rend = renderBox())
         return adjustForAbsoluteZoom(rend->scrollWidth(), rend);
     return 0;
@@ -721,7 +722,7 @@
 
 int Element::scrollHeight()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     if (RenderBox* rend = renderBox())
         return adjustForAbsoluteZoom(rend->scrollHeight(), rend);
     return 0;
@@ -729,9 +730,9 @@
 
 IntRect Element::boundsInRootViewSpace()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
-    FrameView* view = document()->view();
+    FrameView* view = document().view();
     if (!view)
         return IntRect();
 
@@ -761,7 +762,7 @@
 
 PassRefPtr<ClientRectList> Element::getClientRects()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     RenderBoxModelObject* renderBoxModelObject = this->renderBoxModelObject();
     if (!renderBoxModelObject)
@@ -772,13 +773,13 @@
 
     Vector<FloatQuad> quads;
     renderBoxModelObject->absoluteQuads(quads);
-    document()->adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
+    document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
     return ClientRectList::create(quads);
 }
 
 PassRefPtr<ClientRect> Element::getBoundingClientRect()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     Vector<FloatQuad> quads;
     if (isSVGElement() && renderer() && !renderer()->isSVGRoot()) {
@@ -800,7 +801,7 @@
     for (size_t i = 1; i < quads.size(); ++i)
         result.unite(quads[i].boundingBox());
 
-    document()->adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
+    document().adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
     return ClientRect::create(result);
 }
 
@@ -809,7 +810,7 @@
     if (!renderer())
         return IntRect();
     // FIXME: this should probably respect transforms
-    return document()->view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
+    return document().view()->contentsToScreen(renderer()->absoluteBoundingBoxRectIgnoringTransforms());
 }
 
 const AtomicString& Element::getAttribute(const AtomicString& localName) const
@@ -868,21 +869,23 @@
         return;
     }
 
+    QualifiedName existingAttributeName = attributeItem(index)->name();
+
     if (!inSynchronizationOfLazyAttribute)
-        willModifyAttribute(name, attributeItem(index)->value(), newValue);
+        willModifyAttribute(existingAttributeName, attributeItem(index)->value(), newValue);
 
     if (newValue != attributeItem(index)->value()) {
         // If there is an Attr node hooked to this attribute, the Attr::setValue() call below
         // will write into the ElementData.
         // FIXME: Refactor this so it makes some sense.
-        if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(name))
+        if (RefPtr<Attr> attrNode = inSynchronizationOfLazyAttribute ? 0 : attrIfExists(existingAttributeName))
             attrNode->setValue(newValue);
         else
             ensureUniqueElementData()->attributeItem(index)->setValue(newValue);
     }
 
     if (!inSynchronizationOfLazyAttribute)
-        didModifyAttribute(name, newValue);
+        didModifyAttribute(existingAttributeName, newValue);
 }
 
 static inline AtomicString makeIdForStyleResolution(const AtomicString& value, bool inQuirksMode)
@@ -911,9 +914,9 @@
 
     parseAttribute(name, newValue);
 
-    document()->incDOMTreeVersion();
+    document().incDOMTreeVersion();
 
-    StyleResolver* styleResolver = document()->styleResolverIfExists();
+    StyleResolver* styleResolver = document().styleResolverIfExists();
     bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
     bool shouldInvalidateStyle = false;
 
@@ -926,7 +929,7 @@
 
     if (isIdAttributeName(name)) {
         AtomicString oldId = elementData()->idForStyleResolution();
-        AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
+        AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
         if (newId != oldId) {
             elementData()->setIdForStyleResolution(newId);
             shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ruleFeatureSet());
@@ -947,7 +950,7 @@
     if (shouldInvalidateStyle)
         setNeedsStyleRecalc();
 
-    if (AXObjectCache* cache = document()->existingAXObjectCache())
+    if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->handleAttributeChanged(name, this);
 }
 
@@ -1028,12 +1031,12 @@
 
 void Element::classAttributeChanged(const AtomicString& newClassString)
 {
-    StyleResolver* styleResolver = document()->styleResolverIfExists();
+    StyleResolver* styleResolver = document().styleResolverIfExists();
     bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
     bool shouldInvalidateStyle = false;
 
     if (classStringHasClassName(newClassString)) {
-        const bool shouldFoldCase = document()->inQuirksMode();
+        const bool shouldFoldCase = document().inQuirksMode();
         const SpaceSplitString oldClasses = elementData()->classNames();
         elementData()->setClass(newClassString, shouldFoldCase);
         const SpaceSplitString& newClasses = elementData()->classNames();
@@ -1058,7 +1061,7 @@
 
     if (isIdAttributeName(name)) {
         AtomicString oldId = elementData()->idForStyleResolution();
-        AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
+        AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
         if (newId != oldId) {
             if (!oldId.isEmpty() && featureSet.hasSelectorForId(oldId))
                 return true;
@@ -1070,7 +1073,7 @@
     if (name == HTMLNames::classAttr) {
         const AtomicString& newClassString = newValue;
         if (classStringHasClassName(newClassString)) {
-            const bool shouldFoldCase = document()->inQuirksMode();
+            const bool shouldFoldCase = document().inQuirksMode();
             const SpaceSplitString& oldClasses = elementData()->classNames();
             const SpaceSplitString newClasses(newClassString, shouldFoldCase);
             if (checkSelectorForClassChange(oldClasses, newClasses, featureSet))
@@ -1126,8 +1129,8 @@
     if (attributeVector.isEmpty())
         return;
 
-    if (document() && document()->sharedObjectPool())
-        m_elementData = document()->sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
+    if (document().sharedObjectPool())
+        m_elementData = document().sharedObjectPool()->cachedShareableElementDataWithAttributes(attributeVector);
     else
         m_elementData = ShareableElementData::createWithAttributes(attributeVector);
 
@@ -1192,14 +1195,14 @@
     return KURL(parentBase, baseAttribute);
 }
 
-const AtomicString& Element::imageSourceURL() const
+const AtomicString Element::imageSourceURL() const
 {
     return getAttribute(srcAttr);
 }
 
-bool Element::rendererIsNeeded(const NodeRenderingContext& context)
+bool Element::rendererIsNeeded(const RenderStyle& style)
 {
-    return context.style()->display() != NONE;
+    return style.display() != NONE;
 }
 
 RenderObject* Element::createRenderer(RenderStyle* style)
@@ -1234,8 +1237,8 @@
     if (isUpgradedCustomElement() && inDocument())
         CustomElement::didEnterDocument(this, document());
 
-    TreeScope* scope = insertionPoint->treeScope();
-    if (scope != treeScope())
+    TreeScope& scope = insertionPoint->treeScope();
+    if (&scope != &treeScope())
         return InsertionDone;
 
     const AtomicString& idValue = getIdAttribute();
@@ -1247,7 +1250,7 @@
         updateName(nullAtom, nameValue);
 
     if (hasTagName(labelTag)) {
-        if (scope->shouldCacheLabelsByForAttribute())
+        if (scope.shouldCacheLabelsByForAttribute())
             updateLabel(scope, nullAtom, fastGetAttribute(forAttr));
     }
 
@@ -1269,17 +1272,17 @@
 
     if (Element* backdrop = pseudoElement(BACKDROP))
         backdrop->removedFrom(insertionPoint);
-    document()->removeFromTopLayer(this);
+    document().removeFromTopLayer(this);
 
     if (containsFullScreenElement())
         setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
 
-    if (document()->page())
-        document()->page()->pointerLockController().elementRemoved(this);
+    if (document().page())
+        document().page()->pointerLockController().elementRemoved(this);
 
     setSavedLayerScrollOffset(IntSize());
 
-    if (insertionPoint->isInTreeScope() && treeScope() == document()) {
+    if (insertionPoint->isInTreeScope() && &treeScope() == &document()) {
         const AtomicString& idValue = getIdAttribute();
         if (!idValue.isNull())
             updateId(insertionPoint->treeScope(), idValue, nullAtom);
@@ -1289,8 +1292,8 @@
             updateName(nameValue, nullAtom);
 
         if (hasTagName(labelTag)) {
-            TreeScope* treeScope = insertionPoint->treeScope();
-            if (treeScope->shouldCacheLabelsByForAttribute())
+            TreeScope& treeScope = insertionPoint->treeScope();
+            if (treeScope.shouldCacheLabelsByForAttribute())
                 updateLabel(treeScope, fastGetAttribute(forAttr), nullAtom);
         }
     }
@@ -1298,7 +1301,7 @@
     ContainerNode::removedFrom(insertionPoint);
     if (wasInDocument) {
         if (hasPendingResources())
-            document()->accessSVGExtensions()->removeElementFromPendingResources(this);
+            document().accessSVGExtensions()->removeElementFromPendingResources(this);
 
         if (isUpgradedCustomElement())
             CustomElement::didLeaveDocument(this, insertionPoint->document());
@@ -1310,9 +1313,9 @@
 
 void Element::attach(const AttachContext& context)
 {
-    PostAttachCallbackDisabler callbackDisabler(this);
+    ASSERT(document().inStyleRecalc());
+
     StyleResolverParentPusher parentPusher(this);
-    WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
 
     // We've already been through detach when doing a lazyAttach, but we might
     // need to clear any state that's been added since then.
@@ -1343,23 +1346,19 @@
     if (hasRareData()) {
         ElementRareData* data = elementRareData();
         if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
-            if (isFocusable() && document()->focusedElement() == this)
-                document()->updateFocusAppearanceSoon(false /* don't restore selection */);
+            if (isFocusable() && document().focusedElement() == this)
+                document().updateFocusAppearanceSoon(false /* don't restore selection */);
             data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
         }
     }
 
-    // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
-    // not in a Document::recalcStyle. Since we're hopefully going to always
-    // lazyAttach in the future that problem should go away.
-    if (document()->inStyleRecalc())
-        InspectorInstrumentation::didRecalculateStyleForElement(this);
+    InspectorInstrumentation::didRecalculateStyleForElement(this);
 }
 
 void Element::unregisterNamedFlowContentNode()
 {
-    if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document()->renderView())
-        document()->renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
+    if (RuntimeEnabledFeatures::cssRegionsEnabled() && inNamedFlow() && document().renderView())
+        document().renderView()->flowThreadController()->unregisterNamedFlowContentNode(this);
 }
 
 void Element::detach(const AttachContext& context)
@@ -1440,12 +1439,12 @@
 
 PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
 {
-    return document()->styleResolver()->styleForElement(this);
+    return document().styleResolver()->styleForElement(this);
 }
 
-bool Element::recalcStyle(StyleChange change)
+bool Element::recalcStyle(StyleRecalcChange change)
 {
-    ASSERT(document()->inStyleRecalc());
+    ASSERT(document().inStyleRecalc());
 
     if (hasCustomStyleCallbacks())
         willRecalcStyle(change);
@@ -1473,14 +1472,14 @@
     return change == Reattach;
 }
 
-Node::StyleChange Element::recalcOwnStyle(StyleChange change)
+StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
 {
-    ASSERT(document()->inStyleRecalc());
+    ASSERT(document().inStyleRecalc());
 
     CSSAnimationUpdateScope cssAnimationUpdateScope(this);
     RefPtr<RenderStyle> oldStyle = renderStyle();
     RefPtr<RenderStyle> newStyle = styleForRenderer();
-    StyleChange localChange = oldStyle ? Node::diff(oldStyle.get(), newStyle.get(), document()) : Reattach;
+    StyleRecalcChange localChange = RenderStyle::compare(oldStyle.get(), newStyle.get());
 
     if (localChange == Reattach) {
         AttachContext reattachContext;
@@ -1503,9 +1502,9 @@
 
     // 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().styleSheetCollections()->usesRemUnits() && document().documentElement() == this && oldStyle && newStyle && oldStyle->fontSize() != newStyle->fontSize()) {
         // Cached RenderStyles may depend on the re units.
-        document()->styleResolver()->invalidateMatchedPropertiesCache();
+        document().styleResolver()->invalidateMatchedPropertiesCache();
         return Force;
     }
 
@@ -1515,9 +1514,9 @@
     return max(localChange, change);
 }
 
-void Element::recalcChildStyle(StyleChange change)
+void Element::recalcChildStyle(StyleRecalcChange change)
 {
-    ASSERT(document()->inStyleRecalc());
+    ASSERT(document().inStyleRecalc());
 
     StyleResolverParentPusher parentPusher(this);
 
@@ -1564,6 +1563,8 @@
             if (shouldRecalcStyle(change, element)) {
                 parentPusher.push();
                 didReattach = element->recalcStyle(change);
+            } else if (document().styleResolver()->supportsStyleSharing(element)) {
+                document().styleResolver()->addToStyleSharingList(element);
             }
         }
 
@@ -1622,6 +1623,10 @@
     return 0;
 }
 
+void Element::didAddShadowRoot(ShadowRoot&)
+{
+}
+
 ShadowRoot* Element::userAgentShadowRoot() const
 {
     if (ElementShadow* elementShadow = shadow()) {
@@ -1670,7 +1675,7 @@
 static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
                                         Node* beforeChange, Node* afterChange, int childCountDelta)
 {
-    if (!e->attached() || e->document()->hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
+    if (!e->attached() || e->document().hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
         return;
 
     // :empty selector.
@@ -1762,18 +1767,12 @@
 void Element::beginParsingChildren()
 {
     clearIsParsingChildrenFinished();
-    StyleResolver* styleResolver = document()->styleResolverIfExists();
-    if (styleResolver && attached())
-        styleResolver->pushParentElement(this);
 }
 
 void Element::finishParsingChildren()
 {
-    ContainerNode::finishParsingChildren();
     setIsParsingChildrenFinished();
     checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
-    if (StyleResolver* styleResolver = document()->styleResolverIfExists())
-        styleResolver->popParentElement(this);
     if (isCustomElement())
         CustomElement::didFinishParsingChildren(this);
 }
@@ -1844,7 +1843,7 @@
     setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
 
     attrNode->attachToElement(this);
-    treeScope()->adoptIfNeeded(attrNode);
+    treeScope().adoptIfNeeded(attrNode);
     ensureAttrNodeListForElement(this)->append(attrNode);
 
     return oldAttrNode.release();
@@ -1866,7 +1865,7 @@
         return 0;
     }
 
-    ASSERT(document() == attr->document());
+    ASSERT(&document() == &attr->document());
 
     synchronizeAttribute(attr->qualifiedName());
 
@@ -2005,15 +2004,15 @@
     if (!inDocument())
         return;
 
-    Document* doc = document();
-    if (doc->focusedElement() == this)
+    Document& doc = document();
+    if (doc.focusedElement() == this)
         return;
 
     // If the stylesheets have already been loaded we can reliably check isFocusable.
     // If not, we continue and set the focused node on the focus controller below so
     // that it can be updated soon after attach.
-    if (doc->haveStylesheetsLoaded()) {
-        doc->updateLayoutIgnorePendingStylesheets();
+    if (doc.haveStylesheetsLoaded()) {
+        doc.updateLayoutIgnorePendingStylesheets();
         if (!isFocusable())
             return;
     }
@@ -2022,17 +2021,17 @@
         return;
 
     RefPtr<Node> protect;
-    if (Page* page = doc->page()) {
+    if (Page* page = doc.page()) {
         // Focus and change event handlers can cause us to lose our last ref.
         // If a focus event handler changes the focus to a different node it
         // does not make sense to continue and update appearence.
         protect = this;
-        if (!page->focusController().setFocusedElement(this, doc->frame(), direction))
+        if (!page->focusController().setFocusedElement(this, doc.frame(), direction))
             return;
     }
 
     // Setting the focused node above might have invalidated the layout due to scripts.
-    doc->updateLayoutIgnorePendingStylesheets();
+    doc.updateLayoutIgnorePendingStylesheets();
 
     if (!isFocusable()) {
         ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
@@ -2046,20 +2045,20 @@
 void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
 {
     if (isRootEditableElement()) {
-        Frame* frame = document()->frame();
+        Frame* frame = document().frame();
         if (!frame)
             return;
 
         // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
-        if (this == frame->selection()->rootEditableElement())
+        if (this == frame->selection().rootEditableElement())
             return;
 
         // FIXME: We should restore the previous selection if there is one.
         VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
 
-        if (frame->selection()->shouldChangeSelection(newSelection)) {
-            frame->selection()->setSelection(newSelection);
-            frame->selection()->revealSelection();
+        if (frame->selection().shouldChangeSelection(newSelection)) {
+            frame->selection().setSelection(newSelection);
+            frame->selection().revealSelection();
         }
     } else if (renderer() && !renderer()->isWidget())
         renderer()->scrollRectToVisible(boundingBox());
@@ -2068,12 +2067,12 @@
 void Element::blur()
 {
     cancelFocusAppearanceUpdate();
-    if (treeScope()->adjustedFocusedElement() == this) {
-        Document* doc = document();
-        if (doc->page())
-            doc->page()->focusController().setFocusedElement(0, doc->frame());
+    if (treeScope().adjustedFocusedElement() == this) {
+        Document& doc = document();
+        if (doc.page())
+            doc.page()->focusController().setFocusedElement(0, doc.frame());
         else
-            doc->setFocusedElement(0);
+            doc.setFocusedElement(0);
     }
 }
 
@@ -2094,13 +2093,13 @@
 
 void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
 {
-    RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document()->defaultView(), 0, oldFocusedElement);
+    RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document().defaultView(), 0, oldFocusedElement);
     EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
 }
 
 void Element::dispatchBlurEvent(Element* newFocusedElement)
 {
-    RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document()->defaultView(), 0, newFocusedElement);
+    RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document().defaultView(), 0, newFocusedElement);
     EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
 }
 
@@ -2108,20 +2107,20 @@
 {
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
     ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
-    dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, oldFocusedElement)));
+    dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().defaultView(), 0, oldFocusedElement)));
 }
 
 void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
 {
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
     ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
-    dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, newFocusedElement)));
+    dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().defaultView(), 0, newFocusedElement)));
 }
 
 String Element::innerText()
 {
     // We need to update layout, since plainText uses line boxes in the render tree.
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (!renderer())
         return textContent(true);
@@ -2230,7 +2229,7 @@
 
     ElementRareData* data = ensureElementRareData();
     if (!data->computedStyle())
-        data->setComputedStyle(document()->styleForElementIgnoringPendingStylesheets(this));
+        data->setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
     return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
 }
 
@@ -2424,15 +2423,15 @@
 
 Locale& Element::locale() const
 {
-    return document()->getCachedLocale(computeInheritedLanguage());
+    return document().getCachedLocale(computeInheritedLanguage());
 }
 
 void Element::cancelFocusAppearanceUpdate()
 {
     if (hasRareData())
         elementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
-    if (document()->focusedElement() == this)
-        document()->cancelFocusAppearanceUpdate();
+    if (document().focusedElement() == this)
+        document().cancelFocusAppearanceUpdate();
 }
 
 void Element::normalizeAttributes()
@@ -2445,7 +2444,7 @@
     }
 }
 
-void Element::updatePseudoElement(PseudoId pseudoId, StyleChange change)
+void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
 {
     PseudoElement* element = pseudoElement(pseudoId);
     if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
@@ -2477,7 +2476,7 @@
     ASSERT(!isPseudoElement());
     RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
     if (pseudoId == BACKDROP)
-        document()->addToTopLayer(element.get(), this);
+        document().addToTopLayer(element.get(), this);
     element->attach();
 
     ensureElementRareData()->setPseudoElement(pseudoId, element.release());
@@ -2502,7 +2501,7 @@
         return false;
     }
 
-    SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selector, document(), es);
+    SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selector, document(), es);
     if (!selectorQuery)
         return false;
     return selectorQuery->matches(this);
@@ -2532,7 +2531,7 @@
             ASSERT(isURLAttribute(*attribute));
     }
 #endif
-    return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
+    return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(name)));
 }
 
 KURL Element::getNonEmptyURLAttribute(const QualifiedName& name) const
@@ -2546,7 +2545,7 @@
     String value = stripLeadingAndTrailingHTMLSpaces(getAttribute(name));
     if (value.isEmpty())
         return KURL();
-    return document()->completeURL(value);
+    return document().completeURL(value);
 }
 
 int Element::getIntegralAttribute(const QualifiedName& attributeName) const
@@ -2571,23 +2570,23 @@
     setAttribute(attributeName, String::number(value));
 }
 
-bool Element::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool Element::childShouldCreateRenderer(const Node& child) const
 {
     // Only create renderers for SVG elements whose parents are SVG elements, or for proper <svg xmlns="svgNS"> subdocuments.
-    if (childContext.node()->isSVGElement())
-        return childContext.node()->hasTagName(SVGNames::svgTag) || isSVGElement();
+    if (child.isSVGElement())
+        return child.hasTagName(SVGNames::svgTag) || isSVGElement();
 
-    return ContainerNode::childShouldCreateRenderer(childContext);
+    return ContainerNode::childShouldCreateRenderer(child);
 }
 
 void Element::webkitRequestFullscreen()
 {
-    FullscreenElementStack::from(document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
+    FullscreenElementStack::from(&document())->requestFullScreenForElement(this, ALLOW_KEYBOARD_INPUT, FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
 }
 
 void Element::webkitRequestFullScreen(unsigned short flags)
 {
-    FullscreenElementStack::from(document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
+    FullscreenElementStack::from(&document())->requestFullScreenForElement(this, (flags | LEGACY_MOZILLA_REQUEST), FullscreenElementStack::EnforceIFrameAllowFullScreenRequirement);
 }
 
 bool Element::containsFullScreenElement() const
@@ -2604,7 +2603,7 @@
 static Element* parentCrossingFrameBoundaries(Element* element)
 {
     ASSERT(element);
-    return element->parentElement() ? element->parentElement() : element->document()->ownerElement();
+    return element->parentElement() ? element->parentElement() : element->document().ownerElement();
 }
 
 void Element::setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(bool flag)
@@ -2632,8 +2631,8 @@
 
 void Element::webkitRequestPointerLock()
 {
-    if (document()->page())
-        document()->page()->pointerLockController().requestPointerLock(this);
+    if (document().page())
+        document().page()->pointerLockController().requestPointerLock(this);
 }
 
 SpellcheckAttributeState Element::spellcheckAttributeState() const
@@ -2691,7 +2690,7 @@
 
 const AtomicString& Element::webkitRegionOverset() const
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
     if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
@@ -2720,7 +2719,7 @@
 
 Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     Vector<RefPtr<Range> > rangeObjects;
     if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
@@ -2775,21 +2774,21 @@
     updateId(treeScope(), oldId, newId);
 }
 
-inline void Element::updateId(TreeScope* scope, const AtomicString& oldId, const AtomicString& newId)
+inline void Element::updateId(TreeScope& scope, const AtomicString& oldId, const AtomicString& newId)
 {
     ASSERT(isInTreeScope());
     ASSERT(oldId != newId);
 
     if (!oldId.isEmpty())
-        scope->removeElementById(oldId, this);
+        scope.removeElementById(oldId, this);
     if (!newId.isEmpty())
-        scope->addElementById(newId, this);
+        scope.addElementById(newId, this);
 
     if (shouldRegisterAsExtraNamedItem())
         updateExtraNamedItemRegistration(oldId, newId);
 }
 
-void Element::updateLabel(TreeScope* scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
+void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue)
 {
     ASSERT(hasTagName(labelTag));
 
@@ -2800,9 +2799,9 @@
         return;
 
     if (!oldForAttributeValue.isEmpty())
-        scope->removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
+        scope.removeLabel(oldForAttributeValue, toHTMLLabelElement(this));
     if (!newForAttributeValue.isEmpty())
-        scope->addLabel(newForAttributeValue, toHTMLLabelElement(this));
+        scope.addLabel(newForAttributeValue, toHTMLLabelElement(this));
 }
 
 static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
@@ -2817,13 +2816,13 @@
     else if (name == HTMLNames::nameAttr)
         updateName(oldValue, newValue);
     else if (name == HTMLNames::forAttr && hasTagName(labelTag)) {
-        TreeScope* scope = treeScope();
-        if (scope->shouldCacheLabelsByForAttribute())
+        TreeScope& scope = treeScope();
+        if (scope.shouldCacheLabelsByForAttribute())
             updateLabel(scope, oldValue, newValue);
     }
 
     if (oldValue != newValue) {
-        if (attached() && hasSelectorForAttribute(document(), name.localName()))
+        if (attached() && hasSelectorForAttribute(&document(), name.localName()))
            setNeedsStyleRecalc();
 
         if (isUpgradedCustomElement())
@@ -2833,27 +2832,27 @@
     if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
         recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
 
-    InspectorInstrumentation::willModifyDOMAttr(document(), this, oldValue, newValue);
+    InspectorInstrumentation::willModifyDOMAttr(&document(), this, oldValue, newValue);
 }
 
 void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
 {
     attributeChanged(name, value);
-    InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
+    InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), value);
     dispatchSubtreeModifiedEvent();
 }
 
 void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
 {
     attributeChanged(name, value);
-    InspectorInstrumentation::didModifyDOMAttr(document(), this, name.localName(), value);
+    InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), value);
     // Do not dispatch a DOMSubtreeModified event here; see bug 81141.
 }
 
 void Element::didRemoveAttribute(const QualifiedName& name)
 {
     attributeChanged(name, nullAtom);
-    InspectorInstrumentation::didRemoveDOMAttr(document(), this, name.localName());
+    InspectorInstrumentation::didRemoveDOMAttr(&document(), this, name.localName());
     dispatchSubtreeModifiedEvent();
 }
 
@@ -2864,7 +2863,7 @@
     // If the documents differ by quirks mode then they differ by case sensitivity
     // for class and id names so we need to go through the attribute change logic
     // to pick up the new casing in the ElementData.
-    if (oldDocument->inQuirksMode() != document()->inQuirksMode()) {
+    if (oldDocument->inQuirksMode() != document().inQuirksMode()) {
         if (hasID())
             setIdAttribute(getIdAttribute());
         if (hasClass())
@@ -2874,26 +2873,26 @@
 
 void Element::updateNamedItemRegistration(const AtomicString& oldName, const AtomicString& newName)
 {
-    if (!document()->isHTMLDocument())
+    if (!document().isHTMLDocument())
         return;
 
     if (!oldName.isEmpty())
-        toHTMLDocument(document())->removeNamedItem(oldName);
+        toHTMLDocument(document()).removeNamedItem(oldName);
 
     if (!newName.isEmpty())
-        toHTMLDocument(document())->addNamedItem(newName);
+        toHTMLDocument(document()).addNamedItem(newName);
 }
 
 void Element::updateExtraNamedItemRegistration(const AtomicString& oldId, const AtomicString& newId)
 {
-    if (!document()->isHTMLDocument())
+    if (!document().isHTMLDocument())
         return;
 
     if (!oldId.isEmpty())
-        toHTMLDocument(document())->removeExtraNamedItem(oldId);
+        toHTMLDocument(document()).removeExtraNamedItem(oldId);
 
     if (!newId.isEmpty())
-        toHTMLDocument(document())->addExtraNamedItem(newId);
+        toHTMLDocument(document()).addExtraNamedItem(newId);
 }
 
 PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType type)
@@ -2924,8 +2923,8 @@
 
 void Element::scheduleLayerUpdate()
 {
-    if (postAttachCallbacksAreSuspended())
-        queuePostAttachCallback(scheduleLayerUpdateCallback, this);
+    if (document().inStyleRecalc())
+        PostAttachCallbacks::queueCallback(scheduleLayerUpdateCallback, this);
     else
         scheduleLayerUpdateCallback(this);
 }
@@ -2959,8 +2958,8 @@
     AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
     RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
     if (!attrNode) {
-        attrNode = Attr::create(this, name);
-        treeScope()->adoptIfNeeded(attrNode.get());
+        attrNode = Attr::create(*this, name);
+        treeScope().adoptIfNeeded(attrNode.get());
         attrNodeList->append(attrNode);
     }
     return attrNode.release();
@@ -2997,12 +2996,12 @@
     removeAttrNodeListForElement(this);
 }
 
-void Element::willRecalcStyle(StyleChange)
+void Element::willRecalcStyle(StyleRecalcChange)
 {
     ASSERT(hasCustomStyleCallbacks());
 }
 
-void Element::didRecalcStyle(StyleChange)
+void Element::didRecalcStyle(StyleRecalcChange)
 {
     ASSERT(hasCustomStyleCallbacks());
 }
@@ -3041,7 +3040,7 @@
     // if the idForStyleResolution and the className need different casing.
     bool ownerDocumentsHaveDifferentCaseSensitivity = false;
     if (other.hasClass() || other.hasID())
-        ownerDocumentsHaveDifferentCaseSensitivity = other.document()->inQuirksMode() != document()->inQuirksMode();
+        ownerDocumentsHaveDifferentCaseSensitivity = other.document().inQuirksMode() != document().inQuirksMode();
 
     // If 'other' has a mutable ElementData, convert it to an immutable one so we can share it between both elements.
     // We can only do this if there is no CSSOM wrapper for other's inline style, and there are no presentation attributes,
@@ -3195,7 +3194,7 @@
     ASSERT(isStyledElement());
     RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
     if (!inlineStyle)
-        inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
+        inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document().inQuirksMode()));
     else if (!inlineStyle->isMutable())
         inlineStyle = inlineStyle->mutableCopy();
     ASSERT(inlineStyle->isMutable());
@@ -3229,7 +3228,7 @@
         inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
     } else {
         ASSERT(inlineStyle->isMutable());
-        static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
+        static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document().elementSheet()->contents());
     }
 }
 
@@ -3237,21 +3236,21 @@
 {
     ASSERT(isStyledElement());
     WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
-    if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
-        startLineNumber = document()->scriptableDocumentParser()->lineNumber();
+    if (document().scriptableDocumentParser() && !document().isInDocumentWrite())
+        startLineNumber = document().scriptableDocumentParser()->lineNumber();
 
     if (newStyleString.isNull()) {
         if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
             cssomWrapper->clearParentElement();
         ensureUniqueElementData()->m_inlineStyle.clear();
-    } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
+    } else if (modificationReason == ModifiedByCloning || document().contentSecurityPolicy()->allowInlineStyle(document().url(), startLineNumber)) {
         setInlineStyleFromString(newStyleString);
     }
 
     elementData()->m_styleAttributeIsDirty = false;
 
     setNeedsStyleRecalc(LocalStyleChange);
-    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
+    InspectorInstrumentation::didInvalidateStyleAttr(&document(), this);
 }
 
 void Element::inlineStyleChanged()
@@ -3260,7 +3259,7 @@
     setNeedsStyleRecalc(LocalStyleChange);
     ASSERT(elementData());
     elementData()->m_styleAttributeIsDirty = true;
-    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
+    InspectorInstrumentation::didInvalidateStyleAttr(&document(), this);
 }
 
 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
@@ -3290,7 +3289,7 @@
 bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
 {
     ASSERT(isStyledElement());
-    bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
+    bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document().elementSheet()->contents());
     if (changes)
         inlineStyleChanged();
     return changes;
@@ -3320,7 +3319,7 @@
 {
     ASSERT(isStyledElement());
     if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
-        inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
+        inlineStyle->addSubresourceStyleURLs(urls, document().elementSheet()->contents());
 }
 
 static inline bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
@@ -3435,7 +3434,7 @@
 void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
 {
     ASSERT(isStyledElement());
-    style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
+    style->setProperty(propertyID, value, false, document().elementSheet()->contents());
 }
 
 void ElementData::deref()
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index 1b35d58..25c434b 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -434,8 +434,8 @@
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
-    bool recalcStyle(StyleChange = NoChange);
+    virtual bool rendererIsNeeded(const RenderStyle&);
+    bool recalcStyle(StyleRecalcChange);
     void didAffectSelector(AffectedSelectorMask);
 
     ElementShadow* shadow() const;
@@ -444,7 +444,7 @@
     ShadowRoot* shadowRoot() const;
 
     bool hasAuthorShadowRoot() const { return shadowRoot(); }
-
+    virtual void didAddShadowRoot(ShadowRoot&);
     ShadowRoot* userAgentShadowRoot() const;
     ShadowRoot* ensureUserAgentShadowRoot();
     virtual const AtomicString& shadowPseudoId() const { return !part().isEmpty() ? part() : pseudo(); }
@@ -500,7 +500,7 @@
     KURL getURLAttribute(const QualifiedName&) const;
     KURL getNonEmptyURLAttribute(const QualifiedName&) const;
 
-    virtual const AtomicString& imageSourceURL() const;
+    virtual const AtomicString imageSourceURL() const;
     virtual String target() const { return String(); }
     virtual Image* imageContents() { return 0; }
 
@@ -554,7 +554,6 @@
 
     DOMStringMap* dataset();
 
-    static bool isMathMLElement() { return false; }
     virtual bool isMediaElement() const { return false; }
 
 #if ENABLE(INPUT_SPEECH)
@@ -595,7 +594,7 @@
 
     virtual bool shouldBeReparentedUnderRenderView(const RenderStyle*) const { return isInTopLayer(); }
 
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
+    virtual bool childShouldCreateRenderer(const Node& child) const;
     bool hasPendingResources() const;
     void setHasPendingResources();
     void clearHasPendingResources();
@@ -665,8 +664,8 @@
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
     virtual void removeAllEventListeners() OVERRIDE;
 
-    virtual void willRecalcStyle(StyleChange);
-    virtual void didRecalcStyle(StyleChange);
+    virtual void willRecalcStyle(StyleRecalcChange);
+    virtual void didRecalcStyle(StyleRecalcChange);
     virtual PassRefPtr<RenderStyle> customStyleForRenderer();
 
     virtual bool shouldRegisterAsNamedItem() const { return false; }
@@ -697,13 +696,13 @@
     void setInlineStyleFromString(const AtomicString&);
     MutableStylePropertySet* ensureMutableInlineStyle();
 
-    StyleChange recalcOwnStyle(StyleChange);
-    void recalcChildStyle(StyleChange);
+    StyleRecalcChange recalcOwnStyle(StyleRecalcChange);
+    void recalcChildStyle(StyleRecalcChange);
 
     void makePresentationAttributeCacheKey(PresentationAttributeCacheKey&) const;
     void rebuildPresentationAttributeStyle();
 
-    void updatePseudoElement(PseudoId, StyleChange);
+    void updatePseudoElement(PseudoId, StyleRecalcChange);
     void createPseudoElementIfNeeded(PseudoId);
 
     // FIXME: Everyone should allow author shadows.
@@ -725,9 +724,9 @@
     void synchronizeAttribute(const AtomicString& localName) const;
 
     void updateId(const AtomicString& oldId, const AtomicString& newId);
-    void updateId(TreeScope*, const AtomicString& oldId, const AtomicString& newId);
+    void updateId(TreeScope&, const AtomicString& oldId, const AtomicString& newId);
     void updateName(const AtomicString& oldName, const AtomicString& newName);
-    void updateLabel(TreeScope*, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue);
+    void updateLabel(TreeScope&, const AtomicString& oldForAttributeValue, const AtomicString& newForAttributeValue);
 
     void scrollByUnits(int units, ScrollGranularity);
 
@@ -801,6 +800,12 @@
     return static_cast<const Element*>(node);
 }
 
+inline const Element& toElement(const Node& node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(node.isElementNode());
+    return static_cast<const Element&>(node);
+}
+
 // This will catch anyone doing an unnecessary cast.
 void toElement(const Element*);
 
@@ -884,12 +889,12 @@
     // with a non-null namespace, because it will return false, a false negative, if the prefixes
     // don't match but the local name and namespace both do. However, since this has been like this
     // for a while and the code paths may be hot, we'll have to measure performance if we fix it.
-    return attributeName == document()->idAttributeName();
+    return attributeName == document().idAttributeName();
 }
 
 inline const AtomicString& Element::getIdAttribute() const
 {
-    return hasID() ? fastGetAttribute(document()->idAttributeName()) : nullAtom;
+    return hasID() ? fastGetAttribute(document().idAttributeName()) : nullAtom;
 }
 
 inline const AtomicString& Element::getNameAttribute() const
@@ -908,7 +913,7 @@
 
 inline void Element::setIdAttribute(const AtomicString& value)
 {
-    setAttribute(document()->idAttributeName(), value);
+    setAttribute(document().idAttributeName(), value);
 }
 
 inline const SpaceSplitString& Element::classNames() const
@@ -981,7 +986,7 @@
     ASSERT(insertionPoint->inDocument() || isContainerNode());
     if (insertionPoint->inDocument())
         clearFlag(InDocumentFlag);
-    if (isInShadowTree() && !treeScope()->rootNode()->isShadowRoot())
+    if (isInShadowTree() && !treeScope().rootNode()->isShadowRoot())
         clearFlag(IsInShadowTreeFlag);
 }
 
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index 9af4c05..3de2173 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -36,7 +36,7 @@
     [PerWorldBindings] NodeList getElementsByTagName([Default=Undefined] optional DOMString name);
 
     [PerWorldBindings] readonly attribute NamedNodeMap     attributes;
-    boolean            hasAttributes();
+    [MeasureAs=HasAttributes] boolean hasAttributes();
 
     // DOM Level 2 Core
 
@@ -124,16 +124,16 @@
 
     // Mozilla version
     const unsigned short ALLOW_KEYBOARD_INPUT = 1;
-    [EnabledAtRuntime=fullscreen] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
+    [EnabledAtRuntime=Fullscreen] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
 
     // W3C version
-    [EnabledAtRuntime=fullscreen] void webkitRequestFullscreen();
+    [EnabledAtRuntime=Fullscreen] void webkitRequestFullscreen();
 
     void webkitRequestPointerLock();
 
     // CSS Regions API
-    [EnabledAtRuntime=cssRegions, PerWorldBindings] readonly attribute DOMString webkitRegionOverset;
-    [EnabledAtRuntime=cssRegions] sequence<Range> webkitGetRegionFlowRanges();
+    [EnabledAtRuntime=CSSRegions, PerWorldBindings] readonly attribute DOMString webkitRegionOverset;
+    [EnabledAtRuntime=CSSRegions] sequence<Range> webkitGetRegionFlowRanges();
 
     // Event handler DOM attributes
     [NotEnumerable, PerWorldBindings] attribute EventHandler onabort;
@@ -203,10 +203,10 @@
     [NotEnumerable, PerWorldBindings] attribute EventHandler onreset;
     [NotEnumerable, PerWorldBindings] attribute EventHandler onsearch;
     [NotEnumerable, PerWorldBindings] attribute EventHandler onselectstart;
-    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventHandler ontouchstart;
-    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventHandler ontouchmove;
-    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventHandler ontouchend;
-    [NotEnumerable, EnabledAtRuntime=touch, PerWorldBindings] attribute EventHandler ontouchcancel;
+    [NotEnumerable, EnabledAtRuntime=Touch, PerWorldBindings] attribute EventHandler ontouchstart;
+    [NotEnumerable, EnabledAtRuntime=Touch, PerWorldBindings] attribute EventHandler ontouchmove;
+    [NotEnumerable, EnabledAtRuntime=Touch, PerWorldBindings] attribute EventHandler ontouchend;
+    [NotEnumerable, EnabledAtRuntime=Touch, PerWorldBindings] attribute EventHandler ontouchcancel;
     [NotEnumerable, PerWorldBindings] attribute EventHandler onwebkitfullscreenchange;
     [NotEnumerable, PerWorldBindings] attribute EventHandler onwebkitfullscreenerror;
 };
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index dcc8564..7371c7a 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -272,7 +272,7 @@
     ASSERT(!element->nextSibling());
     ASSERT(!element->previousSibling());
 
-    element->document()->removeFromTopLayer(element);
+    element->document().removeFromTopLayer(element);
     element->setParentOrShadowHostNode(0);
 }
 
diff --git a/Source/core/dom/Entity.h b/Source/core/dom/Entity.h
index f49d26a..31e042a 100644
--- a/Source/core/dom/Entity.h
+++ b/Source/core/dom/Entity.h
@@ -36,10 +36,11 @@
 private:
     Entity() : ContainerNode(0)
     {
+        ASSERT_NOT_REACHED();
         ScriptWrappable::init(this);
     }
 };
 
-} //namespace
+} // namespace WebCore
 
 #endif
diff --git a/Source/core/dom/ErrorEvent.cpp b/Source/core/dom/ErrorEvent.cpp
index ecb3d4b..dc15aec 100644
--- a/Source/core/dom/ErrorEvent.cpp
+++ b/Source/core/dom/ErrorEvent.cpp
@@ -54,16 +54,18 @@
     , m_fileName(initializer.filename)
     , m_lineNumber(initializer.lineno)
     , m_columnNumber(initializer.colno)
+    , m_world(DOMWrapperWorld::current())
 {
     ScriptWrappable::init(this);
 }
 
-ErrorEvent::ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber)
+ErrorEvent::ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber, PassRefPtr<DOMWrapperWorld> world)
     : Event(eventNames().errorEvent, false, true)
     , m_sanitizedMessage(message)
     , m_fileName(fileName)
     , m_lineNumber(lineNumber)
     , m_columnNumber(columnNumber)
+    , m_world(world)
 {
     ScriptWrappable::init(this);
 }
diff --git a/Source/core/dom/ErrorEvent.h b/Source/core/dom/ErrorEvent.h
index 583f07f..34b8a42 100644
--- a/Source/core/dom/ErrorEvent.h
+++ b/Source/core/dom/ErrorEvent.h
@@ -31,7 +31,9 @@
 #ifndef ErrorEvent_h
 #define ErrorEvent_h
 
+#include "bindings/v8/DOMWrapperWorld.h"
 #include "core/dom/Event.h"
+#include "wtf/RefPtr.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -51,17 +53,17 @@
     {
         return adoptRef(new ErrorEvent);
     }
-    static PassRefPtr<ErrorEvent> create(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber)
+    static PassRefPtr<ErrorEvent> create(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber, PassRefPtr<DOMWrapperWorld> world)
     {
-        return adoptRef(new ErrorEvent(message, fileName, lineNumber, columnNumber));
+        return adoptRef(new ErrorEvent(message, fileName, lineNumber, columnNumber, world));
     }
     static PassRefPtr<ErrorEvent> create(const AtomicString& type, const ErrorEventInit& initializer)
     {
         return adoptRef(new ErrorEvent(type, initializer));
     }
-    static PassRefPtr<ErrorEvent> createSanitizedError()
+    static PassRefPtr<ErrorEvent> createSanitizedError(PassRefPtr<DOMWrapperWorld> world)
     {
-        return adoptRef(new ErrorEvent("Script error.", String(), 0, 0));
+        return adoptRef(new ErrorEvent("Script error.", String(), 0, 0, world));
     }
     virtual ~ErrorEvent();
 
@@ -76,11 +78,13 @@
 
     virtual const AtomicString& interfaceName() const;
 
+    PassRefPtr<DOMWrapperWorld> world() const { return m_world; }
+
     void setUnsanitizedMessage(const String&);
 
 private:
     ErrorEvent();
-    ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber);
+    ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber, PassRefPtr<DOMWrapperWorld>);
     ErrorEvent(const AtomicString&, const ErrorEventInit&);
 
     String m_unsanitizedMessage;
@@ -88,6 +92,8 @@
     String m_fileName;
     unsigned m_lineNumber;
     unsigned m_columnNumber;
+
+    RefPtr<DOMWrapperWorld> m_world;
 };
 
 } // namespace WebCore
diff --git a/Source/core/dom/Event.h b/Source/core/dom/Event.h
index f867528..56dd5f9 100644
--- a/Source/core/dom/Event.h
+++ b/Source/core/dom/Event.h
@@ -92,9 +92,9 @@
     {
         return adoptRef(new Event(type, true, false));
     }
-    static PassRefPtr<Event> create(const AtomicString& type, bool canBubble, bool cancelable)
+    static PassRefPtr<Event> createCancelableBubble(const AtomicString& type)
     {
-        return adoptRef(new Event(type, canBubble, cancelable));
+        return adoptRef(new Event(type, true, true));
     }
 
     static PassRefPtr<Event> create(const AtomicString& type, const EventInit& initializer)
diff --git a/Source/core/dom/EventContext.cpp b/Source/core/dom/EventContext.cpp
index 13bf7a8..b1d2fe8 100644
--- a/Source/core/dom/EventContext.cpp
+++ b/Source/core/dom/EventContext.cpp
@@ -133,7 +133,7 @@
 void TouchEventContext::checkReachability(TouchList* touchList) const
 {
     for (size_t i = 0; i < touchList->length(); ++i)
-        ASSERT(touchList->item(i)->target()->toNode()->treeScope()->isInclusiveAncestorOf(m_node->treeScope()));
+        ASSERT(touchList->item(i)->target()->toNode()->treeScope().isInclusiveAncestorOf(m_node->treeScope()));
 }
 #endif
 
diff --git a/Source/core/dom/EventContext.h b/Source/core/dom/EventContext.h
index 4d15ece..748fff0 100644
--- a/Source/core/dom/EventContext.h
+++ b/Source/core/dom/EventContext.h
@@ -112,7 +112,7 @@
 inline bool EventContext::isUnreachableNode(EventTarget* target)
 {
     // FIXME: Checks also for SVG elements.
-    return target && target->toNode() && !target->toNode()->isSVGElement() && !target->toNode()->treeScope()->isInclusiveAncestorOf(m_node->treeScope());
+    return target && target->toNode() && !target->toNode()->isSVGElement() && !target->toNode()->treeScope().isInclusiveAncestorOf(m_node->treeScope());
 }
 #endif
 
diff --git a/Source/core/dom/EventDispatcher.cpp b/Source/core/dom/EventDispatcher.cpp
index bf9f40b..9bcfb11 100644
--- a/Source/core/dom/EventDispatcher.cpp
+++ b/Source/core/dom/EventDispatcher.cpp
@@ -60,7 +60,7 @@
     ASSERT(node);
     ASSERT(m_event.get());
     ASSERT(!m_event->type().isNull()); // JavaScript code can create an event with an empty name, but not null.
-    m_view = node->document()->view();
+    m_view = node->document().view();
     EventRetargeter::ensureEventPath(m_node.get(), m_event.get());
 }
 
@@ -84,17 +84,17 @@
     gNodesDispatchingSimulatedClicks->add(node);
 
     if (mouseEventOptions == SendMouseOverUpDownEvents)
-        EventDispatcher(node, SimulatedMouseEvent::create(eventNames().mouseoverEvent, node->document()->defaultView(), underlyingEvent)).dispatch();
+        EventDispatcher(node, SimulatedMouseEvent::create(eventNames().mouseoverEvent, node->document().defaultView(), underlyingEvent)).dispatch();
 
     if (mouseEventOptions != SendNoEvents)
-        EventDispatcher(node, SimulatedMouseEvent::create(eventNames().mousedownEvent, node->document()->defaultView(), underlyingEvent)).dispatch();
+        EventDispatcher(node, SimulatedMouseEvent::create(eventNames().mousedownEvent, node->document().defaultView(), underlyingEvent)).dispatch();
     node->setActive(true, visualOptions == ShowPressedLook);
     if (mouseEventOptions != SendNoEvents)
-        EventDispatcher(node, SimulatedMouseEvent::create(eventNames().mouseupEvent, node->document()->defaultView(), underlyingEvent)).dispatch();
+        EventDispatcher(node, SimulatedMouseEvent::create(eventNames().mouseupEvent, node->document().defaultView(), underlyingEvent)).dispatch();
     node->setActive(false);
 
     // always send click
-    EventDispatcher(node, SimulatedMouseEvent::create(eventNames().clickEvent, node->document()->defaultView(), underlyingEvent)).dispatch();
+    EventDispatcher(node, SimulatedMouseEvent::create(eventNames().clickEvent, node->document().defaultView(), underlyingEvent)).dispatch();
 
     gNodesDispatchingSimulatedClicks->remove(node);
 }
@@ -111,7 +111,7 @@
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
     ASSERT(m_event->target());
     WindowEventContext windowEventContext(m_event.get(), m_node.get(), topEventContext());
-    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEvent(m_node->document(), *m_event, windowEventContext.window(), m_node.get(), m_event->eventPath());
+    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEvent(&m_node->document(), *m_event, windowEventContext.window(), m_node.get(), m_event->eventPath());
 
     void* preDispatchEventHandlerResult;
     if (dispatchEventPreProcess(preDispatchEventHandlerResult) == ContinueDispatching)
diff --git a/Source/core/dom/EventListener.h b/Source/core/dom/EventListener.h
index 33c4a34..cb4eaa0 100644
--- a/Source/core/dom/EventListener.h
+++ b/Source/core/dom/EventListener.h
@@ -39,7 +39,6 @@
             ConditionEventListenerType,
             GObjectEventListenerType,
             NativeEventListenerType,
-            SVGTRefTargetEventListenerType
         };
 
         virtual ~EventListener() { }
diff --git a/Source/core/dom/EventPathWalker.cpp b/Source/core/dom/EventPathWalker.cpp
index de1d4d0..aea6933 100644
--- a/Source/core/dom/EventPathWalker.cpp
+++ b/Source/core/dom/EventPathWalker.cpp
@@ -39,11 +39,7 @@
     , m_isVisitingInsertionPointInReprojection(false)
 {
     ASSERT(node);
-    // FIXME: It's not clear if we need this document check, but I think we do
-    // since DocType nodes from document.implementation.createDocumentType
-    // don't have a document().
-    if (Document* document = node->document())
-        document->updateDistributionForNodeIfNeeded(const_cast<Node*>(node));
+    node->document().updateDistributionForNodeIfNeeded(const_cast<Node*>(node));
 }
 
 Node* EventPathWalker::parent(const Node* node)
diff --git a/Source/core/dom/EventRetargeter.cpp b/Source/core/dom/EventRetargeter.cpp
index cf2d449..da3e829 100644
--- a/Source/core/dom/EventRetargeter.cpp
+++ b/Source/core/dom/EventRetargeter.cpp
@@ -40,14 +40,14 @@
 
 static inline bool inTheSameScope(ShadowRoot* shadowRoot, EventTarget* target)
 {
-    return target->toNode() && target->toNode()->treeScope()->rootNode() == shadowRoot;
+    return target->toNode() && target->toNode()->treeScope().rootNode() == shadowRoot;
 }
 
 static inline EventDispatchBehavior determineDispatchBehavior(Event* event, ShadowRoot* shadowRoot, EventTarget* target)
 {
     // Video-only full screen is a mode where we use the shadow DOM as an implementation
     // detail that should not be detectable by the web content.
-    if (Element* element = FullscreenElementStack::currentFullScreenElementFrom(target->toNode()->document())) {
+    if (Element* element = FullscreenElementStack::currentFullScreenElementFrom(&target->toNode()->document())) {
         // FIXME: We assume that if the full screen element is a media element that it's
         // the video-only full screen. Both here and elsewhere. But that is probably wrong.
         if (element->isMediaElement() && shadowRoot && shadowRoot->host() == element)
@@ -100,6 +100,8 @@
             eventPath.append(adoptPtr(new TouchEventContext(node, eventTargetRespectingTargetRules(node), targetStack.last())));
         else
             eventPath.append(adoptPtr(new EventContext(node, eventTargetRespectingTargetRules(node), targetStack.last())));
+        if (!inDocument)
+            break;
         if (!node->isShadowRoot())
             continue;
         if (determineDispatchBehavior(event, toShadowRoot(node), targetStack.last()) == StayInsideShadowDOM)
@@ -118,7 +120,7 @@
     TreeScope* lastScope = 0;
     size_t eventPathSize = eventPath.size();
     for (size_t i = 0; i < eventPathSize; ++i) {
-        TreeScope* currentScope = eventPath[i]->node()->treeScope();
+        TreeScope* currentScope = &eventPath[i]->node()->treeScope();
         if (currentScope == lastScope) {
             // Fast path.
             eventPath[i]->setEventPath(eventPath[i - 1]->eventPath());
@@ -128,7 +130,7 @@
         Vector<RefPtr<Node> > nodes;
         for (size_t j = 0; j < eventPathSize; ++j) {
             Node* node = eventPath[j]->node();
-            if (node->treeScope()->isInclusiveAncestorOf(currentScope))
+            if (node->treeScope().isInclusiveAncestorOf(*currentScope))
                 nodes.append(node);
         }
         eventPath[i]->adoptEventPath(nodes);
@@ -213,7 +215,7 @@
     TreeScope* lastTreeScope = 0;
     Node* adjustedNode = 0;
     for (EventPath::const_iterator iter = eventPath.begin(); iter < eventPath.end(); ++iter) {
-        TreeScope* scope = (*iter)->node()->treeScope();
+        TreeScope* scope = &(*iter)->node()->treeScope();
         if (scope == lastTreeScope) {
             // Re-use the previous adjustedRelatedTarget if treeScope does not change. Just for the performance optimization.
             adjustedNodes.append(adjustedNode);
@@ -225,7 +227,7 @@
         if (eventWithRelatedTargetDispatchBehavior == DoesNotStopAtBoundary)
             continue;
         if (targetIsIdenticalToToRelatedTarget) {
-            if (node->treeScope()->rootNode() == (*iter)->node()) {
+            if (node->treeScope().rootNode() == (*iter)->node()) {
                 eventPath.shrink(iter + 1 - eventPath.begin());
                 break;
             }
@@ -248,7 +250,7 @@
             relatedNodeStack.append(node);
         else if (walker.isVisitingInsertionPointInReprojection())
             relatedNodeStack.append(relatedNodeStack.last());
-        TreeScope* scope = node->treeScope();
+        TreeScope* scope = &node->treeScope();
         // Skips adding a node to the map if treeScope does not change. Just for the performance optimization.
         if (scope != lastTreeScope)
             relatedNodeMap.add(scope, relatedNodeStack.last());
diff --git a/Source/core/dom/EventRetargeter.h b/Source/core/dom/EventRetargeter.h
index c76c0be..ea5b36e 100644
--- a/Source/core/dom/EventRetargeter.h
+++ b/Source/core/dom/EventRetargeter.h
@@ -81,7 +81,7 @@
 
     // Spec: The event handling for the non-exposed tree works as if the referenced element had been textually included
     // as a deeply cloned child of the 'use' element, except that events are dispatched to the SVGElementInstance objects.
-    Node* rootNode = referenceNode->treeScope()->rootNode();
+    Node* rootNode = referenceNode->treeScope().rootNode();
     Element* shadowHostElement = rootNode->isShadowRoot() ? toShadowRoot(rootNode)->host() : 0;
     // At this time, SVG nodes are not supported in non-<use> shadow trees.
     if (!shadowHostElement || !shadowHostElement->hasTagName(SVGNames::useTag))
diff --git a/Source/core/dom/EventTarget.cpp b/Source/core/dom/EventTarget.cpp
index 991f785..5745d7f 100644
--- a/Source/core/dom/EventTarget.cpp
+++ b/Source/core/dom/EventTarget.cpp
@@ -313,6 +313,9 @@
             break;
 
         ScriptExecutionContext* context = scriptExecutionContext();
+        if (!context)
+            break;
+
         InspectorInstrumentationCookie cookie = InspectorInstrumentation::willHandleEvent(context, event);
         // To match Mozilla, the AT_TARGET phase fires both capturing and bubbling
         // event listeners, even though that violates some versions of the DOM spec.
diff --git a/Source/core/dom/EventTarget.h b/Source/core/dom/EventTarget.h
index b63c8fb..3a5dc0a 100644
--- a/Source/core/dom/EventTarget.h
+++ b/Source/core/dom/EventTarget.h
@@ -161,8 +161,8 @@
         void type::setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { setAttributeEventListener(eventNames().attribute##Event, listener, isolatedWorld); } \
 
     #define DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(attribute) \
-        EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return document()->getWindowAttributeEventListener(eventNames().attribute##Event, isolatedWorld); } \
-        void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { document()->setWindowAttributeEventListener(eventNames().attribute##Event, listener, isolatedWorld); } \
+        EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return document().getWindowAttributeEventListener(eventNames().attribute##Event, isolatedWorld); } \
+        void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { document().setWindowAttributeEventListener(eventNames().attribute##Event, listener, isolatedWorld); } \
 
     #define DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(attribute, eventName) \
         EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return getAttributeEventListener(eventNames().eventName##Event, isolatedWorld); } \
diff --git a/Source/core/dom/EventTargetFactory.in b/Source/core/dom/EventTargetFactory.in
index abe0c16..5227c79 100644
--- a/Source/core/dom/EventTargetFactory.in
+++ b/Source/core/dom/EventTargetFactory.in
@@ -36,7 +36,7 @@
 modules/mediastream/RTCDTMFSender
 modules/mediastream/RTCDataChannel
 modules/mediastream/RTCPeerConnection
-modules/notifications/Notification Conditional=NOTIFICATIONS
+modules/notifications/Notification
 modules/speech/SpeechRecognition
 modules/speech/SpeechSynthesisUtterance
 modules/webaudio/AudioContext Conditional=WEB_AUDIO
diff --git a/Source/core/dom/FullscreenElementStack.cpp b/Source/core/dom/FullscreenElementStack.cpp
index 43ee0a7..ae70534 100644
--- a/Source/core/dom/FullscreenElementStack.cpp
+++ b/Source/core/dom/FullscreenElementStack.cpp
@@ -52,7 +52,7 @@
     do {
         if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
             return false;
-    } while ((owner = owner->document()->ownerElement()));
+    } while ((owner = owner->document().ownerElement()));
     return true;
 }
 
@@ -134,7 +134,7 @@
 bool FullscreenElementStack::fullScreenIsAllowedForElement(Element* element) const
 {
     ASSERT(element);
-    return isAttributeOnAllOwners(allowfullscreenAttr, webkitallowfullscreenAttr, element->document()->ownerElement());
+    return isAttributeOnAllOwners(allowfullscreenAttr, webkitallowfullscreenAttr, element->document().ownerElement());
 }
 
 void FullscreenElementStack::requestFullScreenForElement(Element* element, unsigned short flags, FullScreenCheckType checkType)
@@ -199,7 +199,7 @@
 
         do {
             docs.prepend(currentDoc);
-            currentDoc = currentDoc->ownerElement() ? currentDoc->ownerElement()->document() : 0;
+            currentDoc = currentDoc->ownerElement() ? &currentDoc->ownerElement()->document() : 0;
         } while (currentDoc);
 
         // 4. For each document in docs, run these substeps:
@@ -304,7 +304,7 @@
         //    If doc's fullscreen element stack is non-empty and the element now at the top is either
         //    not in a document or its node document is not doc, repeat this substep.
         newTop = fullscreenElementFrom(currentDoc);
-        if (newTop && (!newTop->inDocument() || newTop->document() != currentDoc))
+        if (newTop && (!newTop->inDocument() || &newTop->document() != currentDoc))
             continue;
 
         // 2. Queue a task to fire an event named fullscreenchange with its bubbles attribute set to true
@@ -314,7 +314,7 @@
         // 3. If doc's fullscreen element stack is empty and doc's browsing context has a browsing context
         // container, set doc to that browsing context container's node document.
         if (!newTop && currentDoc->ownerElement()) {
-            currentDoc = currentDoc->ownerElement()->document();
+            currentDoc = &currentDoc->ownerElement()->document();
             continue;
         }
 
@@ -388,7 +388,7 @@
 
     m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
 
-    document()->recalcStyle(Node::Force);
+    document()->recalcStyle(Force);
 }
 
 void FullscreenElementStack::webkitDidEnterFullScreenForElement(Element*)
diff --git a/Source/core/dom/FullscreenElementStack.h b/Source/core/dom/FullscreenElementStack.h
index fcf9996..8e5e986 100644
--- a/Source/core/dom/FullscreenElementStack.h
+++ b/Source/core/dom/FullscreenElementStack.h
@@ -118,7 +118,7 @@
 
 inline bool FullscreenElementStack::isActiveFullScreenElement(const Element* element)
 {
-    FullscreenElementStack* controller = fromIfExists(element->document());
+    FullscreenElementStack* controller = fromIfExists(&element->document());
     if (!controller)
         return false;
     return controller->webkitIsFullScreen() && controller->webkitCurrentFullScreenElement() == element;
diff --git a/Source/core/dom/LiveNodeList.cpp b/Source/core/dom/LiveNodeList.cpp
index 33f04cd..abb485e 100644
--- a/Source/core/dom/LiveNodeList.cpp
+++ b/Source/core/dom/LiveNodeList.cpp
@@ -32,7 +32,7 @@
 Node* LiveNodeListBase::rootNode() const
 {
     if (isRootedAtDocument() && m_ownerNode->inDocument())
-        return m_ownerNode->document();
+        return &m_ownerNode->document();
     return m_ownerNode.get();
 }
 
@@ -73,7 +73,7 @@
     Node* rootNode = this->rootNode();
 
     if (rootNode->inDocument()) {
-        Element* element = rootNode->treeScope()->getElementById(elementId);
+        Element* element = rootNode->treeScope().getElementById(elementId);
         if (element && nodeMatches(element) && element->isDescendantOf(rootNode))
             return element;
         if (!element)
diff --git a/Source/core/dom/LiveNodeList.h b/Source/core/dom/LiveNodeList.h
index 06e6d8f..97dd515 100644
--- a/Source/core/dom/LiveNodeList.h
+++ b/Source/core/dom/LiveNodeList.h
@@ -68,13 +68,13 @@
         ASSERT(!m_overridesItemAfter || !isNodeList(collectionType));
 
         if (collectionType != ChildNodeListType)
-            document()->registerNodeList(this);
+            document().registerNodeList(this);
     }
 
     virtual ~LiveNodeListBase()
     {
         if (type() != ChildNodeListType)
-            document()->unregisterNodeList(this);
+            document().unregisterNodeList(this);
     }
 
     // DOM API
@@ -99,7 +99,7 @@
     static bool shouldInvalidateTypeOnAttributeChange(NodeListInvalidationType, const QualifiedName&);
 
 protected:
-    Document* document() const { return m_ownerNode->document(); }
+    Document& document() const { return m_ownerNode->document(); }
     Node* rootNode() const;
     ContainerNode* rootContainerNode() const;
     bool overridesItemAfter() const { return m_overridesItemAfter; }
diff --git a/Source/core/dom/MouseEvent.cpp b/Source/core/dom/MouseEvent.cpp
index 2d5f328..6ae78a2 100644
--- a/Source/core/dom/MouseEvent.cpp
+++ b/Source/core/dom/MouseEvent.cpp
@@ -27,9 +27,6 @@
 #include "core/dom/EventDispatcher.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/EventRetargeter.h"
-#include "core/html/HTMLIFrameElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
 #include "core/platform/PlatformMouseEvent.h"
 
 namespace WebCore {
@@ -58,7 +55,7 @@
     ASSERT(event.type() == PlatformEvent::MouseMoved || event.button() != NoButton);
 
     bool isMouseEnterOrLeave = eventType == eventNames().mouseenterEvent || eventType == eventNames().mouseleaveEvent;
-    bool isCancelable = eventType != eventNames().mousemoveEvent && !isMouseEnterOrLeave;
+    bool isCancelable = !isMouseEnterOrLeave;
     bool isBubbling = !isMouseEnterOrLeave;
 
     return MouseEvent::create(eventType, isBubbling, isCancelable, view,
diff --git a/Source/core/dom/MouseRelatedEvent.cpp b/Source/core/dom/MouseRelatedEvent.cpp
index 14a40aa..147ba2d 100644
--- a/Source/core/dom/MouseRelatedEvent.cpp
+++ b/Source/core/dom/MouseRelatedEvent.cpp
@@ -141,7 +141,7 @@
     m_offsetLocation = m_pageLocation;
 
     // Must have an updated render tree for this math to work correctly.
-    targetNode->document()->updateLayoutIgnorePendingStylesheets();
+    targetNode->document().updateLayoutIgnorePendingStylesheets();
 
     // Adjust offsetLocation to be relative to the target's position.
     if (RenderObject* r = targetNode->renderer()) {
diff --git a/Source/core/dom/MutationObserverInterestGroup.h b/Source/core/dom/MutationObserverInterestGroup.h
index 2de1070..4950f31 100644
--- a/Source/core/dom/MutationObserverInterestGroup.h
+++ b/Source/core/dom/MutationObserverInterestGroup.h
@@ -44,7 +44,7 @@
 public:
     static PassOwnPtr<MutationObserverInterestGroup> createForChildListMutation(Node* target)
     {
-        if (!target->document()->hasMutationObserversOfType(MutationObserver::ChildList))
+        if (!target->document().hasMutationObserversOfType(MutationObserver::ChildList))
             return nullptr;
 
         MutationRecordDeliveryOptions oldValueFlag = 0;
@@ -53,7 +53,7 @@
 
     static PassOwnPtr<MutationObserverInterestGroup> createForCharacterDataMutation(Node* target)
     {
-        if (!target->document()->hasMutationObserversOfType(MutationObserver::CharacterData))
+        if (!target->document().hasMutationObserversOfType(MutationObserver::CharacterData))
             return nullptr;
 
         return createIfNeeded(target, MutationObserver::CharacterData, MutationObserver::CharacterDataOldValue);
@@ -61,7 +61,7 @@
 
     static PassOwnPtr<MutationObserverInterestGroup> createForAttributesMutation(Node* target, const QualifiedName& attributeName)
     {
-        if (!target->document()->hasMutationObserversOfType(MutationObserver::Attributes))
+        if (!target->document().hasMutationObserversOfType(MutationObserver::Attributes))
             return nullptr;
 
         return createIfNeeded(target, MutationObserver::Attributes, MutationObserver::AttributeOldValue, &attributeName);
diff --git a/Source/core/dom/NamedFlow.cpp b/Source/core/dom/NamedFlow.cpp
index 00519a1..013b0eb 100644
--- a/Source/core/dom/NamedFlow.cpp
+++ b/Source/core/dom/NamedFlow.cpp
@@ -100,11 +100,19 @@
     const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
     if (regionList.isEmpty())
         return -1;
+
+    int countNonPseudoRegions = -1;
     RenderRegionList::const_iterator iter = regionList.begin();
     for (int index = 0; iter != regionList.end(); ++index, ++iter) {
         const RenderRegion* renderRegion = *iter;
+        // FIXME: Pseudo-elements are not included in the list.
+        // They will be included when we will properly support the Region interface
+        // http://dev.w3.org/csswg/css-regions/#the-region-interface
+        if (renderRegion->isPseudoElement())
+            continue;
+        countNonPseudoRegions++;
         if (renderRegion->regionOversetState() == RegionEmpty)
-            return index;
+            return countNonPseudoRegions;
     }
     return -1;
 }
@@ -128,8 +136,9 @@
         const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
         for (RenderRegionList::const_iterator iter = regionList.begin(); iter != regionList.end(); ++iter) {
             const RenderRegion* renderRegion = *iter;
-            // FIXME: Pseudo-elements are not included in the list.
-            if (!renderRegion->node())
+            // They will be included when we will properly support the Region interface
+            // http://dev.w3.org/csswg/css-regions/#the-region-interface
+            if (renderRegion->isPseudoElement())
                 continue;
             if (m_parentFlowThread->objectInFlowRegion(contentNode->renderer(), renderRegion))
                 regionNodes.append(renderRegion->node());
@@ -154,8 +163,9 @@
     const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
     for (RenderRegionList::const_iterator iter = regionList.begin(); iter != regionList.end(); ++iter) {
         const RenderRegion* renderRegion = *iter;
-        // FIXME: Pseudo-elements are not included in the list.
-        if (!renderRegion->node())
+        // They will be included when we will properly support the Region interface
+        // http://dev.w3.org/csswg/css-regions/#the-region-interface
+        if (renderRegion->isPseudoElement())
             continue;
         regionNodes.append(renderRegion->node());
     }
diff --git a/Source/core/dom/NamedNodeMap.cpp b/Source/core/dom/NamedNodeMap.cpp
index b24e12d..1e2d022 100644
--- a/Source/core/dom/NamedNodeMap.cpp
+++ b/Source/core/dom/NamedNodeMap.cpp
@@ -37,7 +37,7 @@
 
 static inline bool shouldIgnoreAttributeCase(const Element* e)
 {
-    return e && e->document()->isHTMLDocument() && e->isHTMLElement();
+    return e && e->document().isHTMLDocument() && e->isHTMLElement();
 }
 
 void NamedNodeMap::ref()
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 75e593c..0e3d2cb 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -66,6 +66,7 @@
 #include "core/dom/TreeScopeAdopter.h"
 #include "core/dom/UIEvent.h"
 #include "core/dom/UserActionElementSet.h"
+#include "core/dom/WheelController.h"
 #include "core/dom/WheelEvent.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/InsertionPoint.h"
@@ -264,68 +265,6 @@
 
 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, nodeCounter, ("WebCoreNode"));
 
-Node::StyleChange Node::diff(const RenderStyle* s1, const RenderStyle* s2, Document* doc)
-{
-    StyleChange ch = NoInherit;
-    EDisplay display1 = s1 ? s1->display() : NONE;
-    bool fl1 = s1 && s1->hasPseudoStyle(FIRST_LETTER);
-    EDisplay display2 = s2 ? s2->display() : NONE;
-    bool fl2 = s2 && s2->hasPseudoStyle(FIRST_LETTER);
-
-    // We just detach if a renderer acquires or loses a column-span, since spanning elements
-    // typically won't contain much content.
-    bool colSpan1 = s1 && s1->columnSpan();
-    bool colSpan2 = s2 && s2->columnSpan();
-
-    bool specifiesColumns1 = s1 && (!s1->hasAutoColumnCount() || !s1->hasAutoColumnWidth());
-    bool specifiesColumns2 = s2 && (!s2->hasAutoColumnCount() || !s2->hasAutoColumnWidth());
-
-    if (display1 != display2 || fl1 != fl2 || colSpan1 != colSpan2
-        || (specifiesColumns1 != specifiesColumns2 && doc->settings()->regionBasedColumnsEnabled())
-        || (s1 && s2 && !s1->contentDataEquivalent(s2)))
-        ch = Reattach;
-    else if (!s1 || !s2)
-        ch = Inherit;
-    else if (*s1 == *s2)
-        ch = NoChange;
-    else if (s1->inheritedNotEqual(s2))
-        ch = Inherit;
-    else if (s1->hasExplicitlyInheritedProperties() || s2->hasExplicitlyInheritedProperties())
-        ch = Inherit;
-
-    // If the pseudoStyles have changed, we want any StyleChange that is not NoChange
-    // because setStyle will do the right thing with anything else.
-    if (ch == NoChange && s1->hasAnyPublicPseudoStyles()) {
-        for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; ch == NoChange && pseudoId < FIRST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
-            if (s1->hasPseudoStyle(pseudoId)) {
-                RenderStyle* ps2 = s2->getCachedPseudoStyle(pseudoId);
-                if (!ps2)
-                    ch = NoInherit;
-                else {
-                    RenderStyle* ps1 = s1->getCachedPseudoStyle(pseudoId);
-                    ch = ps1 && *ps1 == *ps2 ? NoChange : NoInherit;
-                }
-            }
-        }
-    }
-
-    // When text-combine property has been changed, we need to prepare a separate renderer object.
-    // When text-combine is on, we use RenderCombineText, otherwise RenderText.
-    // https://bugs.webkit.org/show_bug.cgi?id=55069
-    if ((s1 && s2) && (s1->hasTextCombine() != s2->hasTextCombine()))
-        ch = Reattach;
-
-    // We need to reattach the node, so that it is moved to the correct RenderFlowThread.
-    if ((s1 && s2) && (s1->flowThread() != s2->flowThread()))
-        ch = Reattach;
-
-    // When the region thread has changed, we need to prepare a separate render region object.
-    if ((s1 && s2) && (s1->regionThread() != s2->regionThread()))
-        ch = Reattach;
-
-    return ch;
-}
-
 void Node::trackForDebugging()
 {
 #ifndef NDEBUG
@@ -350,8 +289,7 @@
     if (hasRareData())
         clearRareData();
 
-    if (renderer())
-        detach();
+    RELEASE_ASSERT(!renderer());
 
     if (!isContainerNode()) {
         if (Document* document = documentInternal())
@@ -600,7 +538,7 @@
             // Both non-empty text nodes. Merge them.
             unsigned offset = text->length();
             text->appendData(nextText->data());
-            document()->textNodesMerged(nextText.get(), offset);
+            document().textNodesMerged(nextText.get(), offset);
             nextText->remove(IGNORE_EXCEPTION);
         }
 
@@ -634,13 +572,13 @@
 
 bool Node::isContentEditable(UserSelectAllTreatment treatment)
 {
-    document()->updateStyleIfNeeded();
+    document().updateStyleIfNeeded();
     return rendererIsEditable(Editable, treatment);
 }
 
 bool Node::isContentRichlyEditable()
 {
-    document()->updateStyleIfNeeded();
+    document().updateStyleIfNeeded();
     return rendererIsEditable(RichlyEditable, UserSelectAllIsAlwaysNonEditable);
 }
 
@@ -684,14 +622,11 @@
     if (editableLevel == RichlyEditable)
         return false;
 
-    ASSERT(document());
     ASSERT(AXObjectCache::accessibilityEnabled());
-    ASSERT(document()->existingAXObjectCache());
+    ASSERT(document().existingAXObjectCache());
 
-    if (document()) {
-        if (AXObjectCache* cache = document()->existingAXObjectCache())
-            return cache->rootAXEditableElement(this);
-    }
+    if (AXObjectCache* cache = document().existingAXObjectCache())
+        return cache->rootAXEditableElement(this);
 
     return false;
 }
@@ -794,8 +729,8 @@
 {
     for (Node* node = this; node && !node->childNeedsDistributionRecalc(); node = node->parentOrShadowHostNode())
         node->setChildNeedsDistributionRecalc();
-    if (document()->childNeedsDistributionRecalc())
-        document()->scheduleStyleRecalc();
+    if (document().childNeedsDistributionRecalc())
+        document().scheduleStyleRecalc();
 }
 
 inline void Node::setStyleChange(StyleChangeType changeType)
@@ -808,8 +743,8 @@
     for (ContainerNode* p = parentOrShadowHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrShadowHostNode())
         p->setChildNeedsStyleRecalc();
 
-    if (document()->needsStyleRecalc() || document()->childNeedsStyleRecalc())
-        document()->scheduleStyleRecalc();
+    if (document().needsStyleRecalc() || document().childNeedsStyleRecalc())
+        document().scheduleStyleRecalc();
 }
 
 void Node::refEventTarget()
@@ -839,18 +774,16 @@
         markAncestorsWithChildNeedsStyleRecalc();
 }
 
-void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
+void Node::lazyAttach()
 {
     markAncestorsWithChildNeedsStyleRecalc();
     for (Node* node = this; node; node = NodeTraversal::next(node, this)) {
+        node->setAttached();
         node->setStyleChange(LazyAttachStyleChange);
         if (node->isContainerNode())
             node->setChildNeedsStyleRecalc();
-        // FIXME: This flag is only used by HTMLFrameElementBase and doesn't look needed.
-        if (shouldSetAttached == SetAttached)
-            node->setAttached();
         for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
-            root->lazyAttach(shouldSetAttached);
+            root->lazyAttach();
     }
 }
 
@@ -867,10 +800,10 @@
 
 bool Node::isInert() const
 {
-    const HTMLDialogElement* dialog = document()->activeModalDialog();
+    const HTMLDialogElement* dialog = document().activeModalDialog();
     if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
         return true;
-    return document()->ownerElement() && document()->ownerElement()->isInert();
+    return document().ownerElement() && document().ownerElement()->isInert();
 }
 
 unsigned Node::nodeIndex() const
@@ -927,10 +860,10 @@
     if (attrName && !attributeOwnerElement)
         return;
 
-    if (!document()->shouldInvalidateNodeListCaches(attrName))
+    if (!document().shouldInvalidateNodeListCaches(attrName))
         return;
 
-    document()->invalidateNodeListCaches(attrName);
+    document().invalidateNodeListCaches(attrName);
 
     for (Node* node = this; node; node = node->parentNode()) {
         if (!node->hasRareData())
@@ -977,7 +910,7 @@
     // Return true if other is an ancestor of this, otherwise false
     if (!other || !other->hasChildNodes() || inDocument() != other->inDocument())
         return false;
-    if (other->treeScope() != treeScope())
+    if (&other->treeScope() != &treeScope())
         return false;
     if (other->isTreeScope())
         return !isTreeScope();
@@ -1003,7 +936,7 @@
     if (this == node)
         return true;
 
-    if (document() != node->document())
+    if (&document() != &node->document())
         return false;
 
     if (inDocument() != node->inDocument())
@@ -1015,7 +948,7 @@
         return false;
 
     for (; node; node = node->shadowHost()) {
-        if (treeScope() == node->treeScope())
+        if (&treeScope() == &node->treeScope())
             return contains(node);
     }
 
@@ -1027,7 +960,7 @@
     while (node) {
         if (node == this)
             return true;
-        if (node->isDocumentFragment() && static_cast<const DocumentFragment*>(node)->isTemplateContent())
+        if (node->isDocumentFragment() && toDocumentFragment(node)->isTemplateContent())
             node = static_cast<const TemplateContentDocumentFragment*>(node)->host();
         else
             node = node->parentOrShadowHostNode();
@@ -1053,9 +986,6 @@
             continue;
         }
         // Handle normal reattaches from style recalc (ex. display type changes)
-        // or descendants of lazy attached nodes that got actually attached, for example,
-        // by innerHTML or editing.
-        // FIXME: innerHTML and editing should also lazyAttach.
         if (node->attached())
             node->detach(context);
         node = NodeTraversal::nextSkippingChildren(node, root);
@@ -1064,8 +994,6 @@
 
 void Node::reattach(const AttachContext& context)
 {
-    // FIXME: Text::updateTextRenderer calls reattach outside a style recalc.
-    ASSERT(document()->inStyleRecalc() || isTextNode());
     AttachContext reattachContext(context);
     reattachContext.performingReattach = true;
 
@@ -1075,30 +1003,10 @@
 
 void Node::attach(const AttachContext&)
 {
+    ASSERT(document().inStyleRecalc() || isDocumentNode());
     ASSERT(!attached());
     ASSERT(!renderer() || (renderer()->style() && (renderer()->parent() || renderer()->isRenderView())));
 
-    // If this node got a renderer it may be the previousRenderer() of sibling text nodes and thus affect the
-    // result of Text::textRendererIsNeeded() for those nodes.
-    // FIXME: This loop is no longer required once we lazy attach all the time.
-    if (renderer() && !document()->inStyleRecalc()) {
-        for (Node* next = nextSibling(); next; next = next->nextSibling()) {
-            if (next->renderer())
-                break;
-            if (!next->attached())
-                break; // Assume this means none of the following siblings are attached.
-            if (!next->isTextNode())
-                continue;
-            ASSERT(!next->renderer());
-            toText(next)->reattach();
-            // If we again decided not to create a renderer for next, we can bail out the loop,
-            // because it won't affect the result of Text::textRendererIsNeeded() for the rest
-            // of sibling nodes.
-            if (!next->renderer())
-                break;
-        }
-    }
-
     setAttached();
     clearNeedsStyleRecalc();
 
@@ -1131,13 +1039,13 @@
     // Do not remove the element's hovered and active status
     // if performing a reattach.
     if (!context.performingReattach) {
-        Document* doc = document();
+        Document& doc = document();
         if (isUserActionElement()) {
             if (hovered())
-                doc->hoveredNodeDetached(this);
+                doc.hoveredNodeDetached(this);
             if (inActiveChain())
-                doc->activeChainNodeDetached(this);
-            doc->userActionElements().didDetach(this);
+                doc.activeChainNodeDetached(this);
+            doc.userActionElements().didDetach(this);
         }
     }
 
@@ -1231,7 +1139,7 @@
 
 bool Node::isRegisteredWithNamedFlow() const
 {
-    return document()->renderView()->flowThreadController()->isContentNodeRegisteredWithAnyNamedFlow(this);
+    return document().renderView()->flowThreadController()->isContentNodeRegisteredWithAnyNamedFlow(this);
 }
 
 Element* Node::shadowHost() const
@@ -1251,7 +1159,7 @@
 
 ShadowRoot* Node::containingShadowRoot() const
 {
-    Node* root = treeScope()->rootNode();
+    Node* root = treeScope().rootNode();
     return root && root->isShadowRoot() ? toShadowRoot(root) : 0;
 }
 
@@ -1293,7 +1201,7 @@
 
 bool Node::isBlockFlowElement() const
 {
-    return isElementNode() && renderer() && renderer()->isBlockFlow();
+    return isElementNode() && renderer() && renderer()->isRenderBlockFlow();
 }
 
 Element *Node::enclosingBlockFlowElement() const
@@ -1321,7 +1229,7 @@
 Element* Node::rootEditableElement(EditableType editableType) const
 {
     if (editableType == HasEditableAXRole) {
-        if (AXObjectCache* cache = document()->existingAXObjectCache())
+        if (AXObjectCache* cache = document().existingAXObjectCache())
             return const_cast<Element*>(cache->rootAXEditableElement(this));
     }
 
@@ -1352,7 +1260,7 @@
     if (localName.isNull())
         return 0;
 
-    if (document()->isHTMLDocument())
+    if (document().isHTMLDocument())
         return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTagNodeList>(this, HTMLTagNodeListType, localName);
     return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<TagNodeList>(this, TagNodeListType, localName);
 }
@@ -1391,7 +1299,7 @@
         return 0;
     }
 
-    SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), es);
+    SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selectors, document(), es);
     if (!selectorQuery)
         return 0;
     return selectorQuery->queryFirst(this);
@@ -1404,15 +1312,15 @@
         return 0;
     }
 
-    SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), es);
+    SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selectors, document(), es);
     if (!selectorQuery)
         return 0;
     return selectorQuery->queryAll(this);
 }
 
-Document *Node::ownerDocument() const
+Document* Node::ownerDocument() const
 {
-    Document *doc = document();
+    Document* doc = &document();
     return doc == this ? 0 : doc;
 }
 
@@ -1463,8 +1371,8 @@
         return false;
 
     if (nodeType == DOCUMENT_TYPE_NODE) {
-        const DocumentType* documentTypeThis = static_cast<const DocumentType*>(this);
-        const DocumentType* documentTypeOther = static_cast<const DocumentType*>(other);
+        const DocumentType* documentTypeThis = toDocumentType(this);
+        const DocumentType* documentTypeOther = toDocumentType(other);
 
         if (documentTypeThis->publicId() != documentTypeOther->publicId())
             return false;
@@ -1653,12 +1561,12 @@
     case Node::CDATA_SECTION_NODE:
     case Node::COMMENT_NODE:
         isNullString = false;
-        content.append(static_cast<const CharacterData*>(node)->data());
+        content.append(toCharacterData(node)->data());
         break;
 
     case Node::PROCESSING_INSTRUCTION_NODE:
         isNullString = false;
-        content.append(static_cast<const ProcessingInstruction*>(node)->data());
+        content.append(toProcessingInstruction(node)->data());
         break;
 
     case Node::ELEMENT_NODE:
@@ -1712,7 +1620,7 @@
             ChildListMutationScope mutation(this);
             container->removeChildren();
             if (!text.isEmpty())
-                container->appendChild(document()->createTextNode(text), es);
+                container->appendChild(document().createTextNode(text), es);
             return;
         }
         case DOCUMENT_NODE:
@@ -1799,7 +1707,7 @@
     // If one node is in the document and the other is not, we must be disconnected.
     // If the nodes have different owning documents, they must be disconnected.  Note that we avoid
     // comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug).
-    if (start1->inDocument() != start2->inDocument() || (treatment == TreatShadowTreesAsDisconnected && start1->treeScope() != start2->treeScope())) {
+    if (start1->inDocument() != start2->inDocument() || (treatment == TreatShadowTreesAsDisconnected && &start1->treeScope() != &start2->treeScope())) {
         unsigned short direction = (this > otherNode) ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING;
         return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
     }
@@ -1820,7 +1728,7 @@
         return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
     }
 
-    unsigned connection = start1->treeScope() != start2->treeScope() ? DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC : 0;
+    unsigned connection = &start1->treeScope() != &start2->treeScope() ? DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC : 0;
 
     // Walk the two chains backwards and look for the first difference.
     for (unsigned i = min(index1, index2); i; --i) {
@@ -2062,8 +1970,8 @@
 static ContainerNode* parentOrShadowHostOrFrameOwner(const Node* node)
 {
     ContainerNode* parent = node->parentOrShadowHostNode();
-    if (!parent && node->document() && node->document()->frame())
-        parent = node->document()->frame()->ownerElement();
+    if (!parent && node->document().frame())
+        parent = node->document().frame()->ownerElement();
     return parent;
 }
 
@@ -2073,15 +1981,15 @@
         fputs("*", stderr);
     fputs(indent.utf8().data(), stderr);
     node->showNode();
-     if (node->isShadowRoot()) {
-         if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
-             showSubTreeAcrossFrame(youngerShadowRoot, markedNode, indent + "\t");
-     } else {
-         if (node->isFrameOwnerElement())
-             showSubTreeAcrossFrame(static_cast<const HTMLFrameOwnerElement*>(node)->contentDocument(), markedNode, indent + "\t");
-         if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
-             showSubTreeAcrossFrame(oldestShadowRoot, markedNode, indent + "\t");
-     }
+    if (node->isShadowRoot()) {
+        if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
+            showSubTreeAcrossFrame(youngerShadowRoot, markedNode, indent + "\t");
+    } else {
+        if (node->isFrameOwnerElement())
+            showSubTreeAcrossFrame(toHTMLFrameOwnerElement(node)->contentDocument(), markedNode, indent + "\t");
+        if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
+            showSubTreeAcrossFrame(oldestShadowRoot, markedNode, indent + "\t");
+    }
     for (Node* child = node->firstChild(); child; child = child->nextSibling())
         showSubTreeAcrossFrame(child, markedNode, indent + "\t");
 }
@@ -2136,7 +2044,7 @@
 
 ScriptExecutionContext* Node::scriptExecutionContext() const
 {
-    return document();
+    return document().contextDocument().get();
 }
 
 void Node::didMoveToNewDocument(Document* oldDocument)
@@ -2148,7 +2056,7 @@
         if (!listenerMap.isEmpty()) {
             Vector<AtomicString> types = listenerMap.eventTypes();
             for (unsigned i = 0; i < types.size(); ++i)
-                document()->addListenerTypeIfNeeded(types[i]);
+                document().addListenerTypeIfNeeded(types[i]);
         }
     }
 
@@ -2157,33 +2065,35 @@
             cache->remove(this);
 
     const EventListenerVector& mousewheelListeners = getEventListeners(eventNames().mousewheelEvent);
+    WheelController* oldController = WheelController::from(oldDocument);
+    WheelController* newController = WheelController::from(&document());
     for (size_t i = 0; i < mousewheelListeners.size(); ++i) {
-        oldDocument->didRemoveWheelEventHandler();
-        document()->didAddWheelEventHandler();
+        oldController->didRemoveWheelEventHandler(oldDocument);
+        newController->didAddWheelEventHandler(&document());
     }
 
     const EventListenerVector& wheelListeners = getEventListeners(eventNames().wheelEvent);
     for (size_t i = 0; i < wheelListeners.size(); ++i) {
-        oldDocument->didRemoveWheelEventHandler();
-        document()->didAddWheelEventHandler();
+        oldController->didRemoveWheelEventHandler(oldDocument);
+        newController->didAddWheelEventHandler(&document());
     }
 
     if (const TouchEventTargetSet* touchHandlers = oldDocument ? oldDocument->touchEventTargets() : 0) {
         while (touchHandlers->contains(this)) {
             oldDocument->didRemoveTouchEventHandler(this);
-            document()->didAddTouchEventHandler(this);
+            document().didAddTouchEventHandler(this);
         }
     }
 
     if (Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry()) {
         for (size_t i = 0; i < registry->size(); ++i) {
-            document()->addMutationObserverTypes(registry->at(i)->mutationTypes());
+            document().addMutationObserverTypes(registry->at(i)->mutationTypes());
         }
     }
 
     if (HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry()) {
         for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter) {
-            document()->addMutationObserverTypes((*iter)->mutationTypes());
+            document().addMutationObserverTypes((*iter)->mutationTypes());
         }
     }
 }
@@ -2193,13 +2103,12 @@
     if (!targetNode->EventTarget::addEventListener(eventType, listener, useCapture))
         return false;
 
-    if (Document* document = targetNode->document()) {
-        document->addListenerTypeIfNeeded(eventType);
-        if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
-            document->didAddWheelEventHandler();
-        else if (eventNames().isTouchEventType(eventType))
-            document->didAddTouchEventHandler(targetNode);
-    }
+    Document& document = targetNode->document();
+    document.addListenerTypeIfNeeded(eventType);
+    if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
+        WheelController::from(&document)->didAddWheelEventHandler(&document);
+    else if (eventNames().isTouchEventType(eventType))
+        document.didAddTouchEventHandler(targetNode);
 
     return true;
 }
@@ -2216,12 +2125,11 @@
 
     // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
     // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
-    if (Document* document = targetNode->document()) {
-        if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
-            document->didRemoveWheelEventHandler();
-        else if (eventNames().isTouchEventType(eventType))
-            document->didRemoveTouchEventHandler(targetNode);
-    }
+    Document& document = targetNode->document();
+    if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
+        WheelController::from(&document)->didAddWheelEventHandler(&document);
+    else if (eventNames().isTouchEventType(eventType))
+        document.didRemoveTouchEventHandler(targetNode);
 
     return true;
 }
@@ -2322,7 +2230,7 @@
         registration = registry.last().get();
     }
 
-    document()->addMutationObserverTypes(registration->mutationTypes());
+    document().addMutationObserverTypes(registration->mutationTypes());
 }
 
 void Node::unregisterMutationObserver(MutationObserverRegistration* registration)
@@ -2362,7 +2270,7 @@
 
 void Node::notifyMutationObserversNodeWillDetach()
 {
-    if (!document()->hasMutationObservers())
+    if (!document().hasMutationObservers())
         return;
 
     for (Node* node = parentNode(); node; node = node->parentNode()) {
@@ -2416,7 +2324,7 @@
 
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
 
-    if (!document()->hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
+    if (!document().hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
         return;
 
     dispatchScopedEvent(MutationEvent::create(eventNames().DOMSubtreeModifiedEvent, true));
@@ -2425,7 +2333,7 @@
 bool Node::dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent)
 {
     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
-    RefPtr<UIEvent> event = UIEvent::create(eventNames().DOMActivateEvent, true, true, document()->defaultView(), detail);
+    RefPtr<UIEvent> event = UIEvent::create(eventNames().DOMActivateEvent, true, true, document().defaultView(), detail);
     event->setUnderlyingEvent(underlyingEvent);
     dispatchScopedEvent(event);
     return event->defaultHandled();
@@ -2433,18 +2341,18 @@
 
 bool Node::dispatchKeyEvent(const PlatformKeyboardEvent& event)
 {
-    return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document()->defaultView())));
+    return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document().defaultView())));
 }
 
 bool Node::dispatchMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType,
     int detail, Node* relatedTarget)
 {
-    return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document()->defaultView(), event, detail, relatedTarget)));
+    return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document().defaultView(), event, detail, relatedTarget)));
 }
 
 bool Node::dispatchGestureEvent(const PlatformGestureEvent& event)
 {
-    RefPtr<GestureEvent> gestureEvent = GestureEvent::create(document()->defaultView(), event);
+    RefPtr<GestureEvent> gestureEvent = GestureEvent::create(document().defaultView(), event);
     if (!gestureEvent.get())
         return false;
     return EventDispatcher::dispatchEvent(this, GestureEventDispatchMediator::create(gestureEvent));
@@ -2462,7 +2370,7 @@
 
 bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
 {
-    if (!document()->hasListenerType(Document::BEFORELOAD_LISTENER))
+    if (!document().hasListenerType(Document::BEFORELOAD_LISTENER))
         return true;
 
     RefPtr<Node> protector(this);
@@ -2473,7 +2381,7 @@
 
 bool Node::dispatchWheelEvent(const PlatformWheelEvent& event)
 {
-    return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document()->defaultView()));
+    return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document().defaultView()));
 }
 
 void Node::dispatchChangeEvent()
@@ -2493,7 +2401,7 @@
     const AtomicString& eventType = event->type();
     if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
         if (event->isKeyboardEvent()) {
-            if (Frame* frame = document()->frame())
+            if (Frame* frame = document().frame())
                 frame->eventHandler()->defaultKeyboardEventHandler(toKeyboardEvent(event));
         }
     } else if (eventType == eventNames().clickEvent) {
@@ -2501,13 +2409,13 @@
         if (dispatchDOMActivateEvent(detail, event))
             event->setDefaultHandled();
     } else if (eventType == eventNames().contextmenuEvent) {
-        if (Page* page = document()->page())
+        if (Page* page = document().page())
             page->contextMenuController().handleContextMenuEvent(event);
     } else if (eventType == eventNames().textInputEvent) {
         if (event->hasInterface(eventNames().interfaceForTextEvent))
-            if (Frame* frame = document()->frame())
+            if (Frame* frame = document().frame())
                 frame->eventHandler()->defaultTextInputEventHandler(static_cast<TextEvent*>(event));
-#if OS(WINDOWS)
+#if OS(WIN)
     } else if (eventType == eventNames().mousedownEvent && event->isMouseEvent()) {
         MouseEvent* mouseEvent = toMouseEvent(event);
         if (mouseEvent->button() == MiddleButton) {
@@ -2519,7 +2427,7 @@
                 renderer = renderer->parent();
 
             if (renderer) {
-                if (Frame* frame = document()->frame())
+                if (Frame* frame = document().frame())
                     frame->eventHandler()->startPanScrolling(renderer);
             }
         }
@@ -2534,7 +2442,7 @@
             startNode = startNode->parentOrShadowHostNode();
 
         if (startNode && startNode->renderer())
-            if (Frame* frame = document()->frame())
+            if (Frame* frame = document().frame())
                 frame->eventHandler()->defaultWheelEventHandler(startNode, wheelEvent);
     } else if (event->type() == eventNames().webkitEditableContentChangedEvent) {
         dispatchInputEvent();
@@ -2599,7 +2507,7 @@
     // faster for non-Document nodes, and because the call to removedLastRef that is inlined
     // at all deref call sites is smaller if it's a non-virtual function.
     if (isTreeScope()) {
-        treeScope()->removedLastRefToScope();
+        treeScope().removedLastRefToScope();
         return;
     }
 
@@ -2656,7 +2564,7 @@
 
 PassRefPtr<NodeList> Node::getDestinationInsertionPoints()
 {
-    document()->updateDistributionForNodeIfNeeded(this);
+    document().updateDistributionForNodeIfNeeded(this);
     Vector<InsertionPoint*, 8> insertionPoints;
     collectInsertionPointsWhereNodeIsDistributed(this, insertionPoints);
     Vector<RefPtr<Node> > filteredInsertionPoints;
@@ -2693,44 +2601,41 @@
 
 void Node::setFocus(bool flag)
 {
-    if (Document* document = this->document())
-        document->userActionElements().setFocused(this, flag);
+    document().userActionElements().setFocused(this, flag);
 }
 
 void Node::setActive(bool flag, bool)
 {
-    if (Document* document = this->document())
-        document->userActionElements().setActive(this, flag);
+    document().userActionElements().setActive(this, flag);
 }
 
 void Node::setHovered(bool flag)
 {
-    if (Document* document = this->document())
-        document->userActionElements().setHovered(this, flag);
+    document().userActionElements().setHovered(this, flag);
 }
 
 bool Node::isUserActionElementActive() const
 {
     ASSERT(isUserActionElement());
-    return document()->userActionElements().isActive(this);
+    return document().userActionElements().isActive(this);
 }
 
 bool Node::isUserActionElementInActiveChain() const
 {
     ASSERT(isUserActionElement());
-    return document()->userActionElements().isInActiveChain(this);
+    return document().userActionElements().isInActiveChain(this);
 }
 
 bool Node::isUserActionElementHovered() const
 {
     ASSERT(isUserActionElement());
-    return document()->userActionElements().isHovered(this);
+    return document().userActionElements().isHovered(this);
 }
 
 bool Node::isUserActionElementFocused() const
 {
     ASSERT(isUserActionElement());
-    return document()->userActionElements().isFocused(this);
+    return document().userActionElements().isFocused(this);
 }
 
 void Node::setCustomElementState(CustomElementState newState)
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index 5831fdd..58738dc 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -100,11 +100,6 @@
     StyleChangeFromRenderer
 };
 
-enum AttachBehavior {
-    DeprecatedAttachNow,
-    AttachLazily,
-};
-
 class NodeRareDataBase {
 public:
     RenderObject* renderer() const { return m_renderer; }
@@ -166,9 +161,6 @@
     static bool isSupported(const String& feature, const String& version);
     static void dumpStatistics();
 
-    enum StyleChange { NoChange, NoInherit, Inherit, Force, Reattach };
-    static StyleChange diff(const RenderStyle*, const RenderStyle*, Document*);
-
     virtual ~Node();
     void willBeDeletedFrom(Document*);
 
@@ -273,7 +265,7 @@
     bool isStyledElement() const { return isHTMLElement() || isSVGElement(); }
 
     bool isDocumentNode() const;
-    bool isTreeScope() const { return treeScope()->rootNode() == this; }
+    bool isTreeScope() const { return treeScope().rootNode() == this; }
     bool isDocumentFragment() const { return getFlag(IsDocumentFragmentFlag); }
     bool isShadowRoot() const { return isDocumentFragment() && isTreeScope(); }
     bool isInsertionPoint() const { return getFlag(IsInsertionPointFlag); }
@@ -415,12 +407,8 @@
     bool isV8CollectableDuringMinorGC() const { return getFlag(V8CollectableDuringMinorGCFlag); }
     void setV8CollectableDuringMinorGC(bool flag) { setFlag(flag, V8CollectableDuringMinorGCFlag); }
 
-    enum ShouldSetAttached {
-        SetAttached,
-        DoNotSetAttached
-    };
-    void lazyAttach(ShouldSetAttached = SetAttached);
-    void lazyReattach(ShouldSetAttached = SetAttached);
+    void lazyAttach();
+    void lazyReattach();
 
     virtual void setFocus(bool flag);
     virtual void setActive(bool flag = true, bool pause = false);
@@ -481,21 +469,18 @@
     unsigned nodeIndex() const;
 
     // Returns the DOM ownerDocument attribute. This method never returns NULL, except in the case
-    // of (1) a Document node or (2) a DocumentType node that is not used with any Document yet.
+    // of a Document node.
     Document* ownerDocument() const;
 
-    // Returns the document associated with this node. This method never returns NULL, except in the case
-    // of a DocumentType node that is not used with any Document yet. A Document node returns itself.
-    Document* document() const
+    // Returns the document associated with this node. A Document node returns itself.
+    Document& document() const
     {
         ASSERT(this);
-        // FIXME: below ASSERT is useful, but prevents the use of document() in the constructor or destructor
-        // due to the virtual function call to nodeType().
-        ASSERT(documentInternal() || (nodeType() == DOCUMENT_TYPE_NODE && !inDocument()));
-        return documentInternal();
+        ASSERT(documentInternal());
+        return *documentInternal();
     }
 
-    TreeScope* treeScope() const { return m_treeScope; }
+    TreeScope& treeScope() const { return *m_treeScope; }
 
     // Returns true if this node is associated with a document and is in its associated document's
     // node tree, false otherwise.
@@ -592,9 +577,9 @@
     // Implementation can determine the type of subtree by seeing insertionPoint->inDocument().
     // For a performance reason, notifications are delivered only to ContainerNode subclasses if the insertionPoint is out of document.
     //
-    // There are another callback named didNotifyDescendantInsertions(), which is called after all the descendant is notified.
-    // Only a few subclasses actually need this. To utilize this, the node should return InsertionShouldCallDidNotifyDescendantInsertions
-    // from insrtedInto().
+    // There are another callback named didNotifySubtreeInsertionsToDocument(), which is called after all the descendant is notified,
+    // if this node was inserted into the document tree. Only a few subclasses actually need this. To utilize this, the node should
+    // return InsertionShouldCallDidNotifySubtreeInsertions from insrtedInto().
     //
     enum InsertionNotificationRequest {
         InsertionDone,
@@ -602,7 +587,7 @@
     };
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode* insertionPoint);
-    virtual void didNotifySubtreeInsertions(ContainerNode*) { }
+    virtual void didNotifySubtreeInsertionsToDocument() { }
 
     // Notifies the node that it is no longer part of the tree.
     //
@@ -820,7 +805,7 @@
 
     void setHasCustomStyleCallbacks() { setFlag(true, HasCustomStyleCallbacksFlag); }
 
-    Document* documentInternal() const { return treeScope()->documentScope(); }
+    Document* documentInternal() const { return treeScope().documentScope(); }
     void setTreeScope(TreeScope* scope) { m_treeScope = scope; }
 
 private:
@@ -924,7 +909,7 @@
         lazyReattach();
 }
 
-inline void Node::lazyReattach(ShouldSetAttached shouldSetAttached)
+inline void Node::lazyReattach()
 {
     if (styleChangeType() == LazyAttachStyleChange)
         return;
@@ -934,12 +919,12 @@
 
     if (attached())
         detach(context);
-    lazyAttach(shouldSetAttached);
+    lazyAttach();
 }
 
-inline bool shouldRecalcStyle(Node::StyleChange change, const Node* node)
+inline bool shouldRecalcStyle(StyleRecalcChange change, const Node* node)
 {
-    return change >= Node::Inherit || node->childNeedsStyleRecalc() || node->needsStyleRecalc();
+    return change >= Inherit || node->childNeedsStyleRecalc() || node->needsStyleRecalc();
 }
 
 } //namespace
diff --git a/Source/core/dom/NodeIterator.cpp b/Source/core/dom/NodeIterator.cpp
index 6bb4d9f..f2cb1e7 100644
--- a/Source/core/dom/NodeIterator.cpp
+++ b/Source/core/dom/NodeIterator.cpp
@@ -25,6 +25,7 @@
 #include "config.h"
 #include "core/dom/NodeIterator.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ScriptState.h"
 #include "core/dom/Document.h"
@@ -78,23 +79,19 @@
     , m_referenceNode(root(), true)
     , m_detached(false)
 {
-    // Document type nodes may have a null document. But since they can't have children, there is no need to listen for modifications to these.
-    ASSERT(root()->document() || root()->nodeType() == Node::DOCUMENT_TYPE_NODE);
     ScriptWrappable::init(this);
-    if (Document* ownerDocument = root()->document())
-        ownerDocument->attachNodeIterator(this);
+    root()->document().attachNodeIterator(this);
 }
 
 NodeIterator::~NodeIterator()
 {
-    if (Document* ownerDocument = root()->document())
-        ownerDocument->detachNodeIterator(this);
+    root()->document().detachNodeIterator(this);
 }
 
 PassRefPtr<Node> NodeIterator::nextNode(ScriptState* state, ExceptionState& es)
 {
     if (m_detached) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("nextNode", "NodeIterator", "The iterator is detached."));
         return 0;
     }
 
@@ -123,7 +120,7 @@
 PassRefPtr<Node> NodeIterator::previousNode(ScriptState* state, ExceptionState& es)
 {
     if (m_detached) {
-        es.throwDOMException(InvalidStateError);
+        es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("previousNode", "NodeIterator", "The iterator is detached."));
         return 0;
     }
 
@@ -151,8 +148,7 @@
 
 void NodeIterator::detach()
 {
-    if (Document* ownerDocument = root()->document())
-        ownerDocument->detachNodeIterator(this);
+    root()->document().detachNodeIterator(this);
     m_detached = true;
     m_referenceNode.node.clear();
 }
@@ -167,8 +163,7 @@
 {
     ASSERT(!m_detached);
     ASSERT(removedNode);
-    ASSERT(root()->document());
-    ASSERT(root()->document() == removedNode->document());
+    ASSERT(&root()->document() == &removedNode->document());
 
     // Iterator is not affected if the removed node is the reference node and is the root.
     // or if removed node is not the reference node, or the ancestor of the reference node.
diff --git a/Source/core/dom/NodeRenderingContext.cpp b/Source/core/dom/NodeRenderingContext.cpp
index a59c09e..da6f56f 100644
--- a/Source/core/dom/NodeRenderingContext.cpp
+++ b/Source/core/dom/NodeRenderingContext.cpp
@@ -79,7 +79,7 @@
         if (!element->isInTopLayer())
             return 0;
 
-        const Vector<RefPtr<Element> >& topLayerElements = element->document()->topLayerElements();
+        const Vector<RefPtr<Element> >& topLayerElements = element->document().topLayerElements();
         size_t position = topLayerElements.find(element);
         ASSERT(position != notFound);
         for (size_t i = position + 1; i < topLayerElements.size(); ++i) {
@@ -144,7 +144,7 @@
         // will prevent it.
         if (!m_renderingParent || !m_renderingParent->renderer())
             return 0;
-        return m_node->document()->renderView();
+        return m_node->document().renderView();
     }
 
     if (m_parentFlowRenderer)
@@ -162,7 +162,7 @@
         return false;
     if (!parentRenderer->canHaveChildren())
         return false;
-    if (!m_renderingParent->childShouldCreateRenderer(*this))
+    if (!m_renderingParent->childShouldCreateRenderer(*m_node))
         return false;
     return true;
 }
@@ -182,7 +182,7 @@
         elementInsideRegionNeedsRenderer = element->shouldMoveToFlowThread(m_style.get());
 
         // Children of this element will only be allowed to be flowed into other flow-threads if display is NOT none.
-        if (element->rendererIsNeeded(*this))
+        if (element->rendererIsNeeded(*m_style))
             element->setIsInsideRegion(true);
     }
 
@@ -199,8 +199,8 @@
     if (!element->shouldMoveToFlowThread(m_style.get()))
         return;
 
-    ASSERT(m_node->document()->renderView());
-    FlowThreadController* flowThreadController = m_node->document()->renderView()->flowThreadController();
+    ASSERT(m_node->document().renderView());
+    FlowThreadController* flowThreadController = m_node->document().renderView()->flowThreadController();
     m_parentFlowRenderer = flowThreadController->ensureRenderFlowThreadWithName(m_style->flowThread());
     flowThreadController->registerNamedFlowContentNode(m_node, m_parentFlowRenderer);
 }
@@ -224,7 +224,7 @@
 
     moveToFlowThreadIfNeeded();
 
-    if (!element->rendererIsNeeded(*this))
+    if (!element->rendererIsNeeded(*m_style))
         return;
 
     RenderObject* newRenderer = element->createRenderer(m_style.get());
@@ -247,7 +247,7 @@
     newRenderer->setAnimatableStyle(m_style.release()); // setAnimatableStyle() can depend on renderer() already being set.
 
     if (FullscreenElementStack::isActiveFullScreenElement(element)) {
-        newRenderer = RenderFullScreen::wrapRenderer(newRenderer, parentRenderer, element->document());
+        newRenderer = RenderFullScreen::wrapRenderer(newRenderer, parentRenderer, &element->document());
         if (!newRenderer)
             return;
     }
@@ -268,7 +268,7 @@
     RenderObject* parentRenderer = this->parentRenderer();
 
     if (m_parentDetails.resetStyleInheritance())
-        m_style = textNode->document()->styleResolver()->defaultStyleForElement();
+        m_style = textNode->document().styleResolver()->defaultStyleForElement();
     else
         m_style = parentRenderer->style();
 
diff --git a/Source/core/dom/NodeRenderingTraversal.cpp b/Source/core/dom/NodeRenderingTraversal.cpp
index 2563ccb..7353a13 100644
--- a/Source/core/dom/NodeRenderingTraversal.cpp
+++ b/Source/core/dom/NodeRenderingTraversal.cpp
@@ -50,7 +50,7 @@
 ContainerNode* parent(const Node* node, ParentDetails* details)
 {
     // FIXME: Once everything lazy attaches we should assert that we don't need a distribution recalc here.
-    ComposedTreeWalker walker(node, ComposedTreeWalker::CrossUpperBoundary, ComposedTreeWalker::CanStartFromShadowBoundary);
+    ComposedTreeWalker walker(node, ComposedTreeWalker::CanStartFromShadowBoundary);
     ContainerNode* found = toContainerNode(walker.traverseParent(walker.get(), details));
     return details->outOfComposition() ? 0 : found;
 }
@@ -93,34 +93,6 @@
     return 0;
 }
 
-Node* nextInScope(const Node* node)
-{
-    ComposedTreeWalker walker = ComposedTreeWalker(node, ComposedTreeWalker::DoNotCrossUpperBoundary);
-    walker.next();
-    return walker.get();
-}
-
-Node* previousInScope(const Node* node)
-{
-    ComposedTreeWalker walker = ComposedTreeWalker(node, ComposedTreeWalker::DoNotCrossUpperBoundary);
-    walker.previous();
-    return walker.get();
-}
-
-Node* parentInScope(const Node* node)
-{
-    ComposedTreeWalker walker = ComposedTreeWalker(node, ComposedTreeWalker::DoNotCrossUpperBoundary);
-    walker.parent();
-    return walker.get();
-}
-
-Node* lastChildInScope(const Node* node)
-{
-    ComposedTreeWalker walker = ComposedTreeWalker(node, ComposedTreeWalker::DoNotCrossUpperBoundary);
-    walker.lastChild();
-    return walker.get();
-}
-
 }
 
 } // namespace
diff --git a/Source/core/dom/NodeRenderingTraversal.h b/Source/core/dom/NodeRenderingTraversal.h
index 2db8aaf..135d866 100644
--- a/Source/core/dom/NodeRenderingTraversal.h
+++ b/Source/core/dom/NodeRenderingTraversal.h
@@ -69,11 +69,6 @@
 Node* nextSibling(const Node*);
 Node* previousSibling(const Node*);
 
-Node* nextInScope(const Node*);
-Node* previousInScope(const Node*);
-Node* parentInScope(const Node*);
-Node* lastChildInScope(const Node*);
-
 inline ContainerNode* parent(const Node* node)
 {
     ParentDetails unusedDetails;
diff --git a/Source/core/dom/Notation.cpp b/Source/core/dom/Notation.cpp
index 7636048..e635eab 100644
--- a/Source/core/dom/Notation.cpp
+++ b/Source/core/dom/Notation.cpp
@@ -29,6 +29,7 @@
     , m_publicId(publicId)
     , m_systemId(systemId)
 {
+    ASSERT_NOT_REACHED();
     ScriptWrappable::init(this);
 }
 
diff --git a/Source/core/dom/Position.cpp b/Source/core/dom/Position.cpp
index 02f46bc..646f305 100644
--- a/Source/core/dom/Position.cpp
+++ b/Source/core/dom/Position.cpp
@@ -37,6 +37,8 @@
 #include "core/editing/htmlediting.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLTableElement.h"
+#include "core/page/Frame.h"
+#include "core/page/Settings.h"
 #include "core/platform/Logging.h"
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/InlineTextBox.h"
@@ -149,7 +151,7 @@
         return m_anchorNode.get();
     case PositionIsBeforeAnchor:
     case PositionIsAfterAnchor:
-        return findParent(m_anchorNode.get());
+        return m_anchorNode->parentNode();
     }
     ASSERT_NOT_REACHED();
     return 0;
@@ -209,7 +211,7 @@
 
     // FIXME: This should only be necessary for legacy positions, but is also needed for positions before and after Tables
     if (m_offset <= 0 && (m_anchorType != PositionIsAfterAnchor && m_anchorType != PositionIsAfterChildren)) {
-        if (findParent(m_anchorNode.get()) && (editingIgnoresContent(m_anchorNode.get()) || isTableElement(m_anchorNode.get())))
+        if (m_anchorNode->parentNode() && (editingIgnoresContent(m_anchorNode.get()) || isTableElement(m_anchorNode.get())))
             return positionInParentBeforeNode(m_anchorNode.get());
         return Position(m_anchorNode.get(), 0, PositionIsOffsetInAnchor);
     }
@@ -294,17 +296,16 @@
 
 Position Position::previous(PositionMoveType moveType) const
 {
-    Node* n = deprecatedNode();
-    if (!n)
+    Node* node = deprecatedNode();
+    if (!node)
         return *this;
 
-    int o = deprecatedEditingOffset();
+    int offset = deprecatedEditingOffset();
     // FIXME: Negative offsets shouldn't be allowed. We should catch this earlier.
-    ASSERT(o >= 0);
+    ASSERT(offset >= 0);
 
-    if (o > 0) {
-        Node* child = n->childNode(o - 1);
-        if (child)
+    if (offset > 0) {
+        if (Node* child = node->childNode(offset - 1))
             return lastPositionInOrAfterNode(child);
 
         // There are two reasons child might be 0:
@@ -314,51 +315,46 @@
         //      Going from 1 to 0 is correct.
         switch (moveType) {
         case CodePoint:
-            return createLegacyEditingPosition(n, o - 1);
+            return createLegacyEditingPosition(node, offset - 1);
         case Character:
-            return createLegacyEditingPosition(n, uncheckedPreviousOffset(n, o));
+            return createLegacyEditingPosition(node, uncheckedPreviousOffset(node, offset));
         case BackwardDeletion:
-            return createLegacyEditingPosition(n, uncheckedPreviousOffsetForBackwardDeletion(n, o));
+            return createLegacyEditingPosition(node, uncheckedPreviousOffsetForBackwardDeletion(node, offset));
         }
     }
 
-    ContainerNode* parent = findParent(n);
-    if (!parent)
-        return *this;
-
-    return createLegacyEditingPosition(parent, n->nodeIndex());
+    if (ContainerNode* parent = node->parentNode())
+        return createLegacyEditingPosition(parent, node->nodeIndex());
+    return *this;
 }
 
 Position Position::next(PositionMoveType moveType) const
 {
     ASSERT(moveType != BackwardDeletion);
 
-    Node* n = deprecatedNode();
-    if (!n)
+    Node* node = deprecatedNode();
+    if (!node)
         return *this;
 
-    int o = deprecatedEditingOffset();
+    int offset = deprecatedEditingOffset();
     // FIXME: Negative offsets shouldn't be allowed. We should catch this earlier.
-    ASSERT(o >= 0);
+    ASSERT(offset >= 0);
 
-    Node* child = n->childNode(o);
-    if (child || (!n->hasChildNodes() && o < lastOffsetForEditing(n))) {
-        if (child)
-            return firstPositionInOrBeforeNode(child);
+    if (Node* child = node->childNode(offset))
+        return firstPositionInOrBeforeNode(child);
 
+    if (!node->hasChildNodes() && offset < lastOffsetForEditing(node)) {
         // There are two reasons child might be 0:
         //   1) The node is node like a text node that is not an element, and therefore has no children.
         //      Going forward one character at a time is correct.
         //   2) The new offset is a bogus offset like (<br>, 1), and there is no child.
         //      Going from 0 to 1 is correct.
-        return createLegacyEditingPosition(n, (moveType == Character) ? uncheckedNextOffset(n, o) : o + 1);
+        return createLegacyEditingPosition(node, (moveType == Character) ? uncheckedNextOffset(node, offset) : offset + 1);
     }
 
-    ContainerNode* parent = findParent(n);
-    if (!parent)
-        return *this;
-
-    return createLegacyEditingPosition(parent, n->nodeIndex() + 1);
+    if (ContainerNode* parent = node->parentNode())
+        return createLegacyEditingPosition(parent, node->nodeIndex() + 1);
+    return *this;
 }
 
 int Position::uncheckedPreviousOffset(const Node* n, int current)
@@ -428,10 +424,10 @@
 
 Node* Position::parentEditingBoundary() const
 {
-    if (!m_anchorNode || !m_anchorNode->document())
+    if (!m_anchorNode)
         return 0;
 
-    Node* documentElement = m_anchorNode->document()->documentElement();
+    Node* documentElement = m_anchorNode->document().documentElement();
     if (!documentElement)
         return 0;
 
@@ -447,14 +443,14 @@
 {
     if (isNull())
         return true;
-    return !findParent(deprecatedNode()) && m_offset <= 0;
+    return !deprecatedNode()->parentNode() && m_offset <= 0;
 }
 
 bool Position::atEndOfTree() const
 {
     if (isNull())
         return true;
-    return !findParent(deprecatedNode()) && m_offset >= lastOffsetForEditing(deprecatedNode());
+    return !deprecatedNode()->parentNode() && m_offset >= lastOffsetForEditing(deprecatedNode());
 }
 
 int Position::renderedOffset() const
@@ -847,11 +843,6 @@
     return node && node->renderer() && !node->renderer()->isSelectable();
 }
 
-ContainerNode* Position::findParent(const Node* node)
-{
-    return node->parentNode();
-}
-
 bool Position::nodeIsUserSelectAll(const Node* node)
 {
     return RuntimeEnabledFeatures::userSelectAllEnabled() && node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_ALL;
@@ -904,14 +895,17 @@
     if (isHTMLHtmlElement(m_anchorNode.get()))
         return false;
 
-    if (renderer->isBlockFlow()) {
+    if (renderer->isRenderBlockFlow()) {
         if (toRenderBlock(renderer)->logicalHeight() || m_anchorNode->hasTagName(bodyTag)) {
             if (!Position::hasRenderedNonAnonymousDescendantsWithHeight(renderer))
                 return atFirstEditingPositionForNode() && !Position::nodeIsUserSelectNone(deprecatedNode());
             return m_anchorNode->rendererIsEditable() && !Position::nodeIsUserSelectNone(deprecatedNode()) && atEditingBoundary();
         }
-    } else
-        return m_anchorNode->rendererIsEditable() && !Position::nodeIsUserSelectNone(deprecatedNode()) && atEditingBoundary();
+    } else {
+        Frame* frame = m_anchorNode->document().frame();
+        bool caretBrowsing = frame->settings() && frame->settings()->caretBrowsingEnabled();
+        return (caretBrowsing || m_anchorNode->rendererIsEditable()) && !Position::nodeIsUserSelectNone(deprecatedNode()) && atEditingBoundary();
+    }
 
     return false;
 }
@@ -1159,7 +1153,7 @@
 
     if (!renderer->isText()) {
         inlineBox = 0;
-        if (canHaveChildrenForEditing(deprecatedNode()) && renderer->isBlockFlow() && hasRenderedNonAnonymousDescendantsWithHeight(renderer)) {
+        if (canHaveChildrenForEditing(deprecatedNode()) && renderer->isRenderBlockFlow() && hasRenderedNonAnonymousDescendantsWithHeight(renderer)) {
             // Try a visually equivalent position with possibly opposite editability. This helps in case |this| is in
             // an editable block but surrounded by non-editable positions. It acts to negate the logic at the beginning
             // of RenderObject::createVisiblePosition().
@@ -1307,7 +1301,7 @@
 {
     TextDirection primaryDirection = LTR;
     for (const RenderObject* r = m_anchorNode->renderer(); r; r = r->parent()) {
-        if (r->isBlockFlow()) {
+        if (r->isRenderBlockFlow()) {
             primaryDirection = r->style()->direction();
             break;
         }
diff --git a/Source/core/dom/Position.h b/Source/core/dom/Position.h
index 4189054..d2b1d1e 100644
--- a/Source/core/dom/Position.h
+++ b/Source/core/dom/Position.h
@@ -127,7 +127,8 @@
     // will be treated as before ignoredNode (thus node() is really after the position, not containing it).
     Node* deprecatedNode() const { return m_anchorNode.get(); }
 
-    Document* document() const { return m_anchorNode ? m_anchorNode->document() : 0; }
+    Document* document() const { return m_anchorNode ? &m_anchorNode->document() : 0; }
+    bool inDocument() const { return m_anchorNode && m_anchorNode->inDocument(); }
     Element* rootEditableElement() const
     {
         Node* container = containerNode();
@@ -249,13 +250,13 @@
     // At least one caller currently hits this ASSERT though, which indicates
     // that the caller is trying to make a position relative to a disconnected node (which is likely an error)
     // Specifically, editing/deleting/delete-ligature-001.html crashes with ASSERT(node->parentNode())
-    return Position(Position::findParent(node), node->nodeIndex(), Position::PositionIsOffsetInAnchor);
+    return Position(node->parentNode(), node->nodeIndex(), Position::PositionIsOffsetInAnchor);
 }
 
 inline Position positionInParentAfterNode(const Node* node)
 {
-    ASSERT(Position::findParent(node));
-    return Position(Position::findParent(node), node->nodeIndex() + 1, Position::PositionIsOffsetInAnchor);
+    ASSERT(node->parentNode());
+    return Position(node->parentNode(), node->nodeIndex() + 1, Position::PositionIsOffsetInAnchor);
 }
 
 // positionBeforeNode and positionAfterNode return neighbor-anchored positions, construction is O(1)
diff --git a/Source/core/dom/PositionIterator.cpp b/Source/core/dom/PositionIterator.cpp
index 34328d6..5cc76b1 100644
--- a/Source/core/dom/PositionIterator.cpp
+++ b/Source/core/dom/PositionIterator.cpp
@@ -160,7 +160,7 @@
     if (isTableElement(m_anchorNode) || editingIgnoresContent(m_anchorNode))
         return (atStartOfNode() || atEndOfNode()) && !Position::nodeIsUserSelectNone(m_anchorNode->parentNode());
 
-    if (!isHTMLHtmlElement(m_anchorNode) && renderer->isBlockFlow()) {
+    if (!isHTMLHtmlElement(m_anchorNode) && renderer->isRenderBlockFlow()) {
         if (toRenderBlock(renderer)->logicalHeight() || m_anchorNode->hasTagName(bodyTag)) {
             if (!Position::hasRenderedNonAnonymousDescendantsWithHeight(renderer))
                 return atStartOfNode() && !Position::nodeIsUserSelectNone(m_anchorNode);
diff --git a/Source/core/dom/PostAttachCallbacks.cpp b/Source/core/dom/PostAttachCallbacks.cpp
new file mode 100644
index 0000000..b862396
--- /dev/null
+++ b/Source/core/dom/PostAttachCallbacks.cpp
@@ -0,0 +1,75 @@
+/*
+ * 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.
+ * 3. 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/dom/PostAttachCallbacks.h"
+
+#include "core/dom/Node.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+typedef std::pair<PostAttachCallbacks::Callback, RefPtr<Node> > CallbackInfo;
+typedef Vector<CallbackInfo> CallbackQueue;
+
+static size_t s_attachDepth;
+
+static CallbackQueue& callbackQueue()
+{
+    DEFINE_STATIC_LOCAL(CallbackQueue, callbackQueue, ());
+    return callbackQueue;
+}
+
+void PostAttachCallbacks::queueCallback(Callback callback, Node* node)
+{
+    callbackQueue().append(CallbackInfo(callback, node));
+}
+
+PostAttachCallbacks::SuspendScope::SuspendScope()
+{
+    ++s_attachDepth;
+}
+
+PostAttachCallbacks::SuspendScope::~SuspendScope()
+{
+    if (s_attachDepth == 1) {
+        // We recalculate size() each time through the loop because a callback
+        // can add more callbacks to the end of the queue.
+        CallbackQueue& queue = callbackQueue();
+        for (size_t i = 0; i < queue.size(); ++i) {
+            const CallbackInfo& info = queue[i];
+            info.first(info.second.get());
+        }
+        queue.clear();
+    }
+    --s_attachDepth;
+}
+
+} // namespace WebCore
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/dom/PostAttachCallbacks.h
similarity index 74%
copy from Source/core/loader/CachedMetadata.cpp
copy to Source/core/dom/PostAttachCallbacks.h
index f3f2a30..5684cb8 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/dom/PostAttachCallbacks.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * 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
@@ -7,10 +7,6 @@
  *
  *     * 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.
@@ -28,9 +24,29 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/loader/CachedMetadata.h"
+#ifndef PostAttachCallbacks_h
+#define PostAttachCallbacks_h
+
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
+class Node;
+
+class PostAttachCallbacks {
+public:
+    typedef void (*Callback)(Node*);
+    static void queueCallback(Callback, Node*);
+
+    class SuspendScope {
+    public:
+        SuspendScope();
+        ~SuspendScope();
+    };
+private:
+    PostAttachCallbacks();
+};
+
 } // namespace WebCore
+
+#endif // PostAttachCallbacks_h
diff --git a/Source/core/dom/ProcessingInstruction.cpp b/Source/core/dom/ProcessingInstruction.cpp
index a4ede16..94ee37e 100644
--- a/Source/core/dom/ProcessingInstruction.cpp
+++ b/Source/core/dom/ProcessingInstruction.cpp
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-inline ProcessingInstruction::ProcessingInstruction(Document* document, const String& target, const String& data)
+inline ProcessingInstruction::ProcessingInstruction(Document& document, const String& target, const String& data)
     : CharacterData(document, data, CreateOther)
     , m_target(target)
     , m_resource(0)
@@ -49,7 +49,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<ProcessingInstruction> ProcessingInstruction::create(Document* document, const String& target, const String& data)
+PassRefPtr<ProcessingInstruction> ProcessingInstruction::create(Document& document, const String& target, const String& data)
 {
     return adoptRef(new ProcessingInstruction(document, target, data));
 }
@@ -63,7 +63,7 @@
         m_resource->removeClient(this);
 
     if (inDocument())
-        document()->styleSheetCollections()->removeStyleSheetCandidateNode(this);
+        document().styleSheetCollections()->removeStyleSheetCandidateNode(this);
 }
 
 String ProcessingInstruction::nodeName() const
@@ -85,7 +85,7 @@
 
 void ProcessingInstruction::checkStyleSheet()
 {
-    if (m_target == "xml-stylesheet" && document()->frame() && parentNode() == document()) {
+    if (m_target == "xml-stylesheet" && document().frame() && parentNode() == &document()) {
         // see http://www.w3.org/TR/xml-stylesheet/
         // ### support stylesheet included in a fragment of this (or another) document
         // ### make sure this gets called when adding from javascript
@@ -128,30 +128,30 @@
                 m_resource = 0;
             }
 
-            String url = document()->completeURL(href).string();
+            String url = document().completeURL(href).string();
             if (!dispatchBeforeLoadEvent(url))
                 return;
 
             m_loading = true;
-            document()->styleSheetCollections()->addPendingSheet();
-            FetchRequest request(ResourceRequest(document()->completeURL(href)), FetchInitiatorTypeNames::processinginstruction);
+            document().styleSheetCollections()->addPendingSheet();
+            FetchRequest request(ResourceRequest(document().completeURL(href)), FetchInitiatorTypeNames::processinginstruction);
             if (m_isXSL)
-                m_resource = document()->fetcher()->fetchXSLStyleSheet(request);
+                m_resource = document().fetcher()->fetchXSLStyleSheet(request);
             else
             {
                 String charset = attrs.get("charset");
                 if (charset.isEmpty())
-                    charset = document()->charset();
+                    charset = document().charset();
                 request.setCharset(charset);
 
-                m_resource = document()->fetcher()->fetchCSSStyleSheet(request);
+                m_resource = document().fetcher()->fetchCSSStyleSheet(request);
             }
             if (m_resource)
                 m_resource->addClient(this);
             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().styleSheetCollections()->removePendingSheet(this);
             }
         }
     }
@@ -169,7 +169,7 @@
 bool ProcessingInstruction::sheetLoaded()
 {
     if (!isLoading()) {
-        document()->styleSheetCollections()->removePendingSheet(this);
+        document().styleSheetCollections()->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().styleSheetCollections()->addStyleSheetCandidateNode(this, m_createdByParser);
     checkStyleSheet();
     return InsertionDone;
 }
@@ -259,7 +259,7 @@
     if (!insertionPoint->inDocument())
         return;
 
-    document()->styleSheetCollections()->removeStyleSheetCandidateNode(this);
+    document().styleSheetCollections()->removeStyleSheetCandidateNode(this);
 
     RefPtr<StyleSheet> removedSheet = m_sheet;
 
@@ -270,8 +270,8 @@
     }
 
     // If we're in document teardown, then we don't need to do any notification of our sheet's removal.
-    if (document()->renderer())
-        document()->removedStyleSheet(removedSheet.get());
+    if (document().renderer())
+        document().removedStyleSheet(removedSheet.get());
 }
 
 void ProcessingInstruction::finishParsingChildren()
diff --git a/Source/core/dom/ProcessingInstruction.h b/Source/core/dom/ProcessingInstruction.h
index 7b216f0..7c8ace9 100644
--- a/Source/core/dom/ProcessingInstruction.h
+++ b/Source/core/dom/ProcessingInstruction.h
@@ -33,7 +33,7 @@
 
 class ProcessingInstruction FINAL : public CharacterData, private StyleSheetResourceClient {
 public:
-    static PassRefPtr<ProcessingInstruction> create(Document*, const String& target, const String& data);
+    static PassRefPtr<ProcessingInstruction> create(Document&, const String& target, const String& data);
     virtual ~ProcessingInstruction();
 
     const String& target() const { return m_target; }
@@ -53,7 +53,7 @@
 
 private:
     friend class CharacterData;
-    ProcessingInstruction(Document*, const String& target, const String& data);
+    ProcessingInstruction(Document&, const String& target, const String& data);
 
     virtual String nodeName() const;
     virtual NodeType nodeType() const;
@@ -91,6 +91,12 @@
     return static_cast<ProcessingInstruction*>(node);
 }
 
-} //namespace
+inline const ProcessingInstruction* toProcessingInstruction(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::PROCESSING_INSTRUCTION_NODE);
+    return static_cast<const ProcessingInstruction*>(node);
+}
+
+} // namespace WebCore
 
 #endif
diff --git a/Source/core/dom/Promise.idl b/Source/core/dom/Promise.idl
index d2fa864..3413c52 100644
--- a/Source/core/dom/Promise.idl
+++ b/Source/core/dom/Promise.idl
@@ -28,15 +28,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-// FIXME: |PromiseValue| should be changed to |Promise|. http://crbug.com/266700
-// IDLs using |Promise| should be written with "typedef any PromiseValue;" and |PromiseValue|.
-
 callback PromiseInit = void (PromiseResolver resolver);
 callback AnyCallback = any (optional any value);
 [
    GlobalContext=Window&WorkerGlobalScope,
    CustomConstructor(PromiseInit init),
-   EnabledAtRuntime=promise
+   EnabledAtRuntime=Promise
 ] interface Promise {
    [Custom] Promise then(optional AnyCallback fulfillCallback, optional AnyCallback rejectCallback);
    [Custom] Promise catch(optional AnyCallback rejectCallback);
diff --git a/Source/core/dom/PromiseResolver.idl b/Source/core/dom/PromiseResolver.idl
index b671070..ab417fa 100644
--- a/Source/core/dom/PromiseResolver.idl
+++ b/Source/core/dom/PromiseResolver.idl
@@ -30,7 +30,7 @@
 
 [
    GlobalContext=Window&WorkerGlobalScope,
-   EnabledAtRuntime=promise
+   EnabledAtRuntime=Promise
 ] interface PromiseResolver {
    [Custom] void fulfill(optional any value);
    [Custom] void resolve(optional any value);
diff --git a/Source/core/dom/PseudoElement.cpp b/Source/core/dom/PseudoElement.cpp
index 105ac7e..e397b9b 100644
--- a/Source/core/dom/PseudoElement.cpp
+++ b/Source/core/dom/PseudoElement.cpp
@@ -27,7 +27,6 @@
 #include "config.h"
 #include "core/dom/PseudoElement.h"
 
-#include "core/dom/NodeRenderingContext.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderQuote.h"
 #include "core/rendering/style/ContentData.h"
@@ -55,7 +54,7 @@
 }
 
 PseudoElement::PseudoElement(Element* parent, PseudoId pseudoId)
-    : Element(pseudoElementTagName(), parent->document(), CreatePseudoElement)
+    : Element(pseudoElementTagName(), &parent->document(), CreatePseudoElement)
     , m_pseudoId(pseudoId)
 {
     ASSERT(pseudoId != NOPSEUDO);
@@ -99,12 +98,12 @@
     }
 }
 
-bool PseudoElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool PseudoElement::rendererIsNeeded(const RenderStyle& style)
 {
-    return pseudoElementRendererIsNeeded(context.style());
+    return pseudoElementRendererIsNeeded(&style);
 }
 
-void PseudoElement::didRecalcStyle(StyleChange)
+void PseudoElement::didRecalcStyle(StyleRecalcChange)
 {
     if (!renderer())
         return;
diff --git a/Source/core/dom/PseudoElement.h b/Source/core/dom/PseudoElement.h
index 0f2ad66..0bd4984 100644
--- a/Source/core/dom/PseudoElement.h
+++ b/Source/core/dom/PseudoElement.h
@@ -43,7 +43,7 @@
 
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
     // As per http://dev.w3.org/csswg/css3-regions/#flow-into, pseudo-elements such as ::first-line, ::first-letter, ::before or ::after
     // cannot be directly collected into a named flow.
@@ -57,7 +57,7 @@
 private:
     PseudoElement(Element*, PseudoId);
 
-    virtual void didRecalcStyle(StyleChange) OVERRIDE;
+    virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE;
     virtual PseudoId customPseudoId() const OVERRIDE { return m_pseudoId; }
 
     PseudoId m_pseudoId;
diff --git a/Source/core/dom/Range.cpp b/Source/core/dom/Range.cpp
index ba27e67..7767ffd 100644
--- a/Source/core/dom/Range.cpp
+++ b/Source/core/dom/Range.cpp
@@ -50,7 +50,9 @@
 #include "wtf/Vector.h"
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
+#ifndef NDEBUG
 #include <stdio.h>
+#endif
 
 namespace WebCore {
 
@@ -59,8 +61,8 @@
 
 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, rangeCounter, ("Range"));
 
-inline Range::Range(PassRefPtr<Document> ownerDocument)
-    : m_ownerDocument(ownerDocument)
+inline Range::Range(Document& ownerDocument)
+    : m_ownerDocument(&ownerDocument)
     , m_start(m_ownerDocument)
     , m_end(m_ownerDocument)
 {
@@ -72,13 +74,13 @@
     m_ownerDocument->attachRange(this);
 }
 
-PassRefPtr<Range> Range::create(PassRefPtr<Document> ownerDocument)
+PassRefPtr<Range> Range::create(Document& ownerDocument)
 {
     return adoptRef(new Range(ownerDocument));
 }
 
-inline Range::Range(PassRefPtr<Document> ownerDocument, PassRefPtr<Node> startContainer, int startOffset, PassRefPtr<Node> endContainer, int endOffset)
-    : m_ownerDocument(ownerDocument)
+inline Range::Range(Document& ownerDocument, Node* startContainer, int startOffset, Node* endContainer, int endOffset)
+    : m_ownerDocument(&ownerDocument)
     , m_start(m_ownerDocument)
     , m_end(m_ownerDocument)
 {
@@ -95,12 +97,12 @@
     setEnd(endContainer, endOffset);
 }
 
-PassRefPtr<Range> Range::create(PassRefPtr<Document> ownerDocument, PassRefPtr<Node> startContainer, int startOffset, PassRefPtr<Node> endContainer, int endOffset)
+PassRefPtr<Range> Range::create(Document& ownerDocument, Node* startContainer, int startOffset, Node* endContainer, int endOffset)
 {
     return adoptRef(new Range(ownerDocument, startContainer, startOffset, endContainer, endOffset));
 }
 
-PassRefPtr<Range> Range::create(PassRefPtr<Document> ownerDocument, const Position& start, const Position& end)
+PassRefPtr<Range> Range::create(Document& ownerDocument, const Position& start, const Position& end)
 {
     return adoptRef(new Range(ownerDocument, start.containerNode(), start.computeOffsetInContainerNode(), end.containerNode(), end.computeOffsetInContainerNode()));
 }
@@ -115,14 +117,14 @@
 #endif
 }
 
-void Range::setDocument(Document* document)
+void Range::setDocument(Document& document)
 {
-    ASSERT(m_ownerDocument != document);
-    if (m_ownerDocument)
-        m_ownerDocument->detachRange(this);
-    m_ownerDocument = document;
-    m_start.setToStartOfNode(document);
-    m_end.setToStartOfNode(document);
+    ASSERT(m_ownerDocument != &document);
+    ASSERT(m_ownerDocument);
+    m_ownerDocument->detachRange(this);
+    m_ownerDocument = &document;
+    m_start.setToStartOfNode(&document);
+    m_end.setToStartOfNode(&document);
     m_ownerDocument->attachRange(this);
 }
 
@@ -222,7 +224,7 @@
     }
 
     bool didMoveDocument = false;
-    if (refNode->document() != m_ownerDocument) {
+    if (&refNode->document() != m_ownerDocument) {
         setDocument(refNode->document());
         didMoveDocument = true;
     }
@@ -250,7 +252,7 @@
     }
 
     bool didMoveDocument = false;
-    if (refNode->document() != m_ownerDocument) {
+    if (&refNode->document() != m_ownerDocument) {
         setDocument(refNode->document());
         didMoveDocument = true;
     }
@@ -302,7 +304,7 @@
         return false;
     }
 
-    if (!refNode->attached() || refNode->document() != m_ownerDocument) {
+    if (!refNode->attached() || &refNode->document() != m_ownerDocument) {
         return false;
     }
 
@@ -330,7 +332,7 @@
         return 0;
     }
 
-    if (!refNode->attached() || refNode->document() != m_ownerDocument) {
+    if (!refNode->attached() || &refNode->document() != m_ownerDocument) {
         es.throwDOMException(WrongDocumentError);
         return 0;
     }
@@ -375,7 +377,7 @@
         return NODE_BEFORE;
     }
 
-    if (refNode->document() != m_ownerDocument) {
+    if (&refNode->document() != m_ownerDocument) {
         // Firefox doesn't throw an exception for this case; it returns 0.
         return NODE_BEFORE;
     }
@@ -420,7 +422,7 @@
     if (es.hadException())
         return 0;
 
-    if (thisCont->document() != sourceCont->document()) {
+    if (&thisCont->document() != &sourceCont->document()) {
         es.throwDOMException(WrongDocumentError);
         return 0;
     }
@@ -579,7 +581,7 @@
         return false;
     }
 
-    if (!refNode->attached() || refNode->document() != m_ownerDocument) {
+    if (!refNode->attached() || &refNode->document() != m_ownerDocument) {
         // Firefox doesn't throw an exception for these cases; it returns false.
         return false;
     }
@@ -647,9 +649,9 @@
     case Node::TEXT_NODE:
     case Node::CDATA_SECTION_NODE:
     case Node::COMMENT_NODE:
-        return static_cast<CharacterData*>(node)->length();
+        return toCharacterData(node)->length();
     case Node::PROCESSING_INSTRUCTION_NODE:
-        return static_cast<ProcessingInstruction*>(node)->data().length();
+        return toProcessingInstruction(node)->data().length();
     case Node::ELEMENT_NODE:
     case Node::ATTRIBUTE_NODE:
     case Node::ENTITY_NODE:
@@ -670,7 +672,7 @@
 
     RefPtr<DocumentFragment> fragment;
     if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS)
-        fragment = DocumentFragment::create(m_ownerDocument.get());
+        fragment = DocumentFragment::create(*m_ownerDocument.get());
 
     if (collapsed(es))
         return fragment.release();
@@ -791,7 +793,7 @@
     case Node::TEXT_NODE:
     case Node::CDATA_SECTION_NODE:
     case Node::COMMENT_NODE:
-        ASSERT(endOffset <= static_cast<CharacterData*>(container)->length());
+        endOffset = std::min(endOffset, toCharacterData(container)->length());
         if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
             RefPtr<CharacterData> c = static_pointer_cast<CharacterData>(container->cloneNode(true));
             deleteCharacterData(c, startOffset, endOffset, es);
@@ -802,10 +804,10 @@
                 result = c.release();
         }
         if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS)
-            static_cast<CharacterData*>(container)->deleteData(startOffset, endOffset - startOffset, es);
+            toCharacterData(container)->deleteData(startOffset, endOffset - startOffset, es);
         break;
     case Node::PROCESSING_INSTRUCTION_NODE:
-        ASSERT(endOffset <= static_cast<ProcessingInstruction*>(container)->data().length());
+        endOffset = std::min(endOffset, toProcessingInstruction(container)->data().length());
         if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
             RefPtr<ProcessingInstruction> c = static_pointer_cast<ProcessingInstruction>(container->cloneNode(true));
             c->setData(c->data().substring(startOffset, endOffset - startOffset));
@@ -816,7 +818,7 @@
                 result = c.release();
         }
         if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) {
-            ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(container);
+            ProcessingInstruction* pi = toProcessingInstruction(container);
             String data(pi->data());
             data.remove(startOffset, endOffset - startOffset);
             pi->setData(data);
@@ -1062,7 +1064,7 @@
     Node* pastLast = pastLastNode();
     for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(n)) {
         if (n->nodeType() == Node::TEXT_NODE || n->nodeType() == Node::CDATA_SECTION_NODE) {
-            String data = static_cast<CharacterData*>(n)->data();
+            String data = toCharacterData(n)->data();
             int length = data.length();
             int start = (n == m_start.container()) ? min(max(0, m_start.offset()), length) : 0;
             int end = (n == m_end.container()) ? min(max(start, m_end.offset()), length) : length;
@@ -1085,7 +1087,7 @@
 
     // We need to update layout, since plainText uses line boxes in the render tree.
     // FIXME: As with innerText, we'd like this to work even if there are no render objects.
-    m_start.container()->document()->updateLayout();
+    m_start.container()->document().updateLayout();
 
     return plainText(this);
 }
@@ -1136,11 +1138,11 @@
         case Node::CDATA_SECTION_NODE:
         case Node::COMMENT_NODE:
         case Node::TEXT_NODE:
-            if (static_cast<unsigned>(offset) > static_cast<CharacterData*>(n)->length())
+            if (static_cast<unsigned>(offset) > toCharacterData(n)->length())
                 es.throwDOMException(IndexSizeError);
             return 0;
         case Node::PROCESSING_INSTRUCTION_NODE:
-            if (static_cast<unsigned>(offset) > static_cast<ProcessingInstruction*>(n)->data().length())
+            if (static_cast<unsigned>(offset) > toProcessingInstruction(n)->data().length())
                 es.throwDOMException(IndexSizeError);
             return 0;
         case Node::ATTRIBUTE_NODE:
@@ -1229,7 +1231,7 @@
         return 0;
     }
 
-    return Range::create(m_ownerDocument, m_start.container(), m_start.offset(), m_end.container(), m_end.offset());
+    return Range::create(*m_ownerDocument.get(), m_start.container(), m_start.offset(), m_end.container(), m_end.offset());
 }
 
 void Range::setStartAfter(Node* refNode, ExceptionState& es)
@@ -1317,7 +1319,7 @@
             return;
     }
 
-    if (m_ownerDocument != refNode->document())
+    if (m_ownerDocument != &refNode->document())
         setDocument(refNode->document());
 
     setStartBefore(refNode);
@@ -1358,7 +1360,7 @@
         }
     }
 
-    if (m_ownerDocument != refNode->document())
+    if (m_ownerDocument != &refNode->document())
         setDocument(refNode->document());
 
     m_start.setToStartOfNode(refNode);
@@ -1655,7 +1657,7 @@
 void Range::nodeChildrenChanged(ContainerNode* container)
 {
     ASSERT(container);
-    ASSERT(container->document() == m_ownerDocument);
+    ASSERT(&container->document() == m_ownerDocument);
     boundaryNodeChildrenChanged(m_start, container);
     boundaryNodeChildrenChanged(m_end, container);
 }
@@ -1680,7 +1682,7 @@
 void Range::nodeChildrenWillBeRemoved(ContainerNode* container)
 {
     ASSERT(container);
-    ASSERT(container->document() == m_ownerDocument);
+    ASSERT(&container->document() == m_ownerDocument);
     boundaryNodeChildrenWillBeRemoved(m_start, container);
     boundaryNodeChildrenWillBeRemoved(m_end, container);
 }
@@ -1703,9 +1705,13 @@
 void Range::nodeWillBeRemoved(Node* node)
 {
     ASSERT(node);
-    ASSERT(node->document() == m_ownerDocument);
+    ASSERT(&node->document() == m_ownerDocument);
     ASSERT(node != m_ownerDocument);
-    ASSERT(node->parentNode());
+
+    // FIXME: Once DOMNodeRemovedFromDocument mutation event removed, we
+    // should change following if-statement to ASSERT(!node->parentNode).
+    if (!node->parentNode())
+        return;
     boundaryNodeWillBeRemoved(m_start, node);
     boundaryNodeWillBeRemoved(m_end, node);
 }
@@ -1723,7 +1729,7 @@
 void Range::textInserted(Node* text, unsigned offset, unsigned length)
 {
     ASSERT(text);
-    ASSERT(text->document() == m_ownerDocument);
+    ASSERT(&text->document() == m_ownerDocument);
     boundaryTextInserted(m_start, text, offset, length);
     boundaryTextInserted(m_end, text, offset, length);
 }
@@ -1744,7 +1750,7 @@
 void Range::textRemoved(Node* text, unsigned offset, unsigned length)
 {
     ASSERT(text);
-    ASSERT(text->document() == m_ownerDocument);
+    ASSERT(&text->document() == m_ownerDocument);
     boundaryTextRemoved(m_start, text, offset, length);
     boundaryTextRemoved(m_end, text, offset, length);
 }
@@ -1760,7 +1766,7 @@
 void Range::textNodesMerged(NodeWithIndex& oldNode, unsigned offset)
 {
     ASSERT(oldNode.node());
-    ASSERT(oldNode.node()->document() == m_ownerDocument);
+    ASSERT(&oldNode.node()->document() == m_ownerDocument);
     ASSERT(oldNode.node()->parentNode());
     ASSERT(oldNode.node()->isTextNode());
     ASSERT(oldNode.node()->previousSibling());
@@ -1782,7 +1788,7 @@
 void Range::textNodeSplit(Text* oldNode)
 {
     ASSERT(oldNode);
-    ASSERT(oldNode->document() == m_ownerDocument);
+    ASSERT(&oldNode->document() == m_ownerDocument);
     ASSERT(oldNode->parentNode());
     ASSERT(oldNode->isTextNode());
     ASSERT(oldNode->nextSibling());
diff --git a/Source/core/dom/Range.h b/Source/core/dom/Range.h
index 5faaf9c..736b7a8 100644
--- a/Source/core/dom/Range.h
+++ b/Source/core/dom/Range.h
@@ -49,12 +49,12 @@
 
 class Range : public RefCounted<Range>, public ScriptWrappable {
 public:
-    static PassRefPtr<Range> create(PassRefPtr<Document>);
-    static PassRefPtr<Range> create(PassRefPtr<Document>, PassRefPtr<Node> startContainer, int startOffset, PassRefPtr<Node> endContainer, int endOffset);
-    static PassRefPtr<Range> create(PassRefPtr<Document>, const Position&, const Position&);
+    static PassRefPtr<Range> create(Document&);
+    static PassRefPtr<Range> create(Document&, Node* startContainer, int startOffset, Node* endContainer, int endOffset);
+    static PassRefPtr<Range> create(Document&, const Position&, const Position&);
     ~Range();
 
-    Document* ownerDocument() const { return m_ownerDocument.get(); }
+    Document& ownerDocument() const { ASSERT(m_ownerDocument); return *m_ownerDocument.get(); }
     Node* startContainer() const { return m_start.container(); }
     int startOffset() const { return m_start.offset(); }
     Node* endContainer() const { return m_end.container(); }
@@ -150,10 +150,10 @@
 #endif
 
 private:
-    explicit Range(PassRefPtr<Document>);
-    Range(PassRefPtr<Document>, PassRefPtr<Node> startContainer, int startOffset, PassRefPtr<Node> endContainer, int endOffset);
+    explicit Range(Document&);
+    Range(Document&, Node* startContainer, int startOffset, Node* endContainer, int endOffset);
 
-    void setDocument(Document*);
+    void setDocument(Document&);
 
     Node* checkNodeWOffset(Node*, int offset, ExceptionState&) const;
     void checkNodeBA(Node*, ExceptionState&, const char* methodName) const;
@@ -168,7 +168,7 @@
     enum ContentsProcessDirection { ProcessContentsForward, ProcessContentsBackward };
     static PassRefPtr<Node> processAncestorsAndTheirSiblings(ActionType, Node* container, ContentsProcessDirection, PassRefPtr<Node> clonedContainer, Node* commonRoot, ExceptionState&);
 
-    RefPtr<Document> m_ownerDocument;
+    RefPtr<Document> m_ownerDocument; // Cannot be null.
     RangeBoundaryPoint m_start;
     RangeBoundaryPoint m_end;
 };
diff --git a/Source/core/dom/ScriptExecutionContext.cpp b/Source/core/dom/ScriptExecutionContext.cpp
index 2cc9e4b..9ac54d9 100644
--- a/Source/core/dom/ScriptExecutionContext.cpp
+++ b/Source/core/dom/ScriptExecutionContext.cpp
@@ -241,7 +241,7 @@
 
     RefPtr<ErrorEvent> errorEvent = event;
     if (shouldSanitizeScriptError(errorEvent->filename(), corsStatus))
-        errorEvent = ErrorEvent::createSanitizedError();
+        errorEvent = ErrorEvent::createSanitizedError(errorEvent->world());
 
     ASSERT(!m_inDispatchErrorEvent);
     m_inDispatchErrorEvent = true;
diff --git a/Source/core/dom/ScriptExecutionContext.h b/Source/core/dom/ScriptExecutionContext.h
index 1bcf0ab..a595aa1 100644
--- a/Source/core/dom/ScriptExecutionContext.h
+++ b/Source/core/dom/ScriptExecutionContext.h
@@ -31,7 +31,7 @@
 #include "core/dom/ActiveDOMObject.h"
 #include "core/dom/ErrorEvent.h"
 #include "core/dom/SecurityContext.h"
-#include "core/loader/CrossOriginAccessControl.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/page/ConsoleTypes.h"
 #include "core/page/DOMTimer.h"
 #include "core/platform/LifecycleContext.h"
@@ -41,6 +41,10 @@
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 
+namespace WTF {
+class OrdinalNumber;
+}
+
 namespace WebCore {
 
 class ContextLifecycleNotifier;
diff --git a/Source/core/dom/ScriptLoader.cpp b/Source/core/dom/ScriptLoader.cpp
index 30f9de9..0345ad9 100644
--- a/Source/core/dom/ScriptLoader.cpp
+++ b/Source/core/dom/ScriptLoader.cpp
@@ -68,8 +68,8 @@
     , m_willExecuteInOrder(false)
 {
     ASSERT(m_element);
-    if (parserInserted && element->document()->scriptableDocumentParser() && !element->document()->isInDocumentWrite())
-        m_startLineNumber = element->document()->scriptableDocumentParser()->lineNumber();
+    if (parserInserted && element->document().scriptableDocumentParser() && !element->document().isInDocumentWrite())
+        m_startLineNumber = element->document().scriptableDocumentParser()->lineNumber();
 }
 
 ScriptLoader::~ScriptLoader()
@@ -77,9 +77,9 @@
     stopLoadRequest();
 }
 
-void ScriptLoader::insertedInto(ContainerNode* insertionPoint)
+void ScriptLoader::didNotifySubtreeInsertionsToDocument()
 {
-    if (insertionPoint->inDocument() && !m_parserInserted)
+    if (!m_parserInserted)
         prepareScript(); // FIXME: Provide a real starting line number here.
 }
 
@@ -166,14 +166,6 @@
     return false;
 }
 
-Document* ScriptLoader::executingDocument() const
-{
-    Document* document = m_element->document();
-    if (!document->import())
-        return document;
-    return document->import()->master();
-}
-
 // http://dev.w3.org/html5/spec/Overview.html#prepare-a-script
 bool ScriptLoader::prepareScript(const TextPosition& scriptStartPosition, LegacyTypeSupport supportLegacyTypes)
 {
@@ -211,16 +203,10 @@
     m_alreadyStarted = true;
 
     // FIXME: If script is parser inserted, verify it's still in the original document.
-    Document* executingDocument = this->executingDocument();
-    Document* elementDocument = m_element->document();
+    Document& elementDocument = m_element->document();
+    Document* contextDocument = elementDocument.contextDocument().get();
 
-    // FIXME: Eventually we'd like to evaluate scripts which are inserted into a
-    // viewless document but this'll do for now.
-    // See http://bugs.webkit.org/show_bug.cgi?id=5727
-    if (!executingDocument->frame())
-        return false;
-
-    if (!executingDocument->frame()->script()->canExecuteScripts(AboutToExecuteScript))
+    if (!contextDocument || !contextDocument->allowExecutingScripts(m_element))
         return false;
 
     if (!isScriptForEventSupported())
@@ -229,7 +215,7 @@
     if (!client->charsetAttributeValue().isEmpty())
         m_characterEncoding = client->charsetAttributeValue();
     else
-        m_characterEncoding = elementDocument->charset();
+        m_characterEncoding = elementDocument.charset();
 
     if (client->hasSourceAttribute()) {
         if (!fetchScript(client->sourceAttributeValue()))
@@ -241,20 +227,20 @@
         m_willBeParserExecuted = true;
     } else if (client->hasSourceAttribute() && m_parserInserted && !client->asyncAttributeValue()) {
         m_willBeParserExecuted = true;
-    } else if (!client->hasSourceAttribute() && m_parserInserted && !elementDocument->haveStylesheetsAndImportsLoaded()) {
+    } else if (!client->hasSourceAttribute() && m_parserInserted && !elementDocument.haveStylesheetsAndImportsLoaded()) {
         m_willBeParserExecuted = true;
         m_readyToBeParserExecuted = true;
     } else if (client->hasSourceAttribute() && !client->asyncAttributeValue() && !m_forceAsync) {
         m_willExecuteInOrder = true;
-        executingDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::IN_ORDER_EXECUTION);
+        contextDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::IN_ORDER_EXECUTION);
         m_resource->addClient(this);
     } else if (client->hasSourceAttribute()) {
-        executingDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::ASYNC_EXECUTION);
+        contextDocument->scriptRunner()->queueScriptForExecution(this, m_resource, ScriptRunner::ASYNC_EXECUTION);
         m_resource->addClient(this);
     } else {
         // Reset line numbering for nested writes.
-        TextPosition position = elementDocument->isInDocumentWrite() ? TextPosition() : scriptStartPosition;
-        KURL scriptURL = (!elementDocument->isInDocumentWrite() && m_parserInserted) ? elementDocument->url() : KURL();
+        TextPosition position = elementDocument.isInDocumentWrite() ? TextPosition() : scriptStartPosition;
+        KURL scriptURL = (!elementDocument.isInDocumentWrite() && m_parserInserted) ? elementDocument.url() : KURL();
         executeScript(ScriptSourceCode(scriptContent(), scriptURL, position));
     }
 
@@ -265,10 +251,10 @@
 {
     ASSERT(m_element);
 
-    RefPtr<Document> elementDocument = m_element->document();
+    RefPtr<Document> elementDocument = &m_element->document();
     if (!m_element->dispatchBeforeLoadEvent(sourceUrl))
         return false;
-    if (!m_element->inDocument() || m_element->document() != elementDocument)
+    if (!m_element->inDocument() || &m_element->document() != elementDocument)
         return false;
 
     ASSERT(!m_resource);
@@ -315,9 +301,12 @@
     if (sourceCode.isEmpty())
         return;
 
-    RefPtr<Document> executingDocument = this->executingDocument();
-    RefPtr<Document> elementDocument = m_element->document();
-    Frame* frame = executingDocument->frame();
+    RefPtr<Document> elementDocument = &m_element->document();
+    RefPtr<Document> contextDocument = elementDocument->contextDocument().get();
+    if (!contextDocument)
+        return;
+
+    Frame* frame = contextDocument->frame();
 
     bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script()->shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr));
 
@@ -325,18 +314,18 @@
         return;
 
     if (m_isExternalScript && m_resource && !m_resource->mimeTypeAllowedByNosniff()) {
-        executingDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_resource->url().elidedString() + "' because its MIME type ('" + m_resource->mimeType() + "') is not executable, and strict MIME type checking is enabled.");
+        contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_resource->url().elidedString() + "' because its MIME type ('" + m_resource->mimeType() + "') is not executable, and strict MIME type checking is enabled.");
         return;
     }
 
     if (frame) {
-        IgnoreDestructiveWriteCountIncrementer ignoreDesctructiveWriteCountIncrementer(m_isExternalScript ? executingDocument.get() : 0);
+        IgnoreDestructiveWriteCountIncrementer ignoreDesctructiveWriteCountIncrementer(m_isExternalScript ? contextDocument.get() : 0);
 
         if (isHTMLScriptLoader(m_element))
-            executingDocument->pushCurrentScript(toHTMLScriptElement(m_element));
+            contextDocument->pushCurrentScript(toHTMLScriptElement(m_element));
 
         AccessControlStatus corsCheck = NotSharableCrossOrigin;
-        if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document()->securityOrigin()))
+        if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin()))
             corsCheck = SharableCrossOrigin;
 
         // Create a script from the script element node, using the script
@@ -345,8 +334,8 @@
         frame->script()->executeScriptInMainWorld(sourceCode, corsCheck);
 
         if (isHTMLScriptLoader(m_element)) {
-            ASSERT(executingDocument->currentScript() == m_element);
-            executingDocument->popCurrentScript();
+            ASSERT(contextDocument->currentScript() == m_element);
+            contextDocument->popCurrentScript();
         }
     }
 }
@@ -377,8 +366,10 @@
 {
     ASSERT(!m_willBeParserExecuted);
 
-    RefPtr<Document> executingDocument = this->executingDocument();
-    RefPtr<Document> elementDocument = m_element->document();
+    RefPtr<Document> elementDocument = &m_element->document();
+    RefPtr<Document> contextDocument = elementDocument->contextDocument().get();
+    if (!contextDocument)
+        return;
 
     // Resource possibly invokes this notifyFinished() more than
     // once because ScriptLoader doesn't unsubscribe itself from
@@ -393,9 +384,9 @@
     }
 
     if (m_willExecuteInOrder)
-        executingDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::IN_ORDER_EXECUTION);
+        contextDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::IN_ORDER_EXECUTION);
     else
-        executingDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::ASYNC_EXECUTION);
+        contextDocument->scriptRunner()->notifyScriptReady(this, ScriptRunner::ASYNC_EXECUTION);
 
     m_resource = 0;
 }
diff --git a/Source/core/dom/ScriptLoader.h b/Source/core/dom/ScriptLoader.h
index cd180f0..e6ba8d3 100644
--- a/Source/core/dom/ScriptLoader.h
+++ b/Source/core/dom/ScriptLoader.h
@@ -67,7 +67,7 @@
     bool forceAsync() const { return m_forceAsync; }
 
     // Helper functions used by our parent classes.
-    void insertedInto(ContainerNode*);
+    void didNotifySubtreeInsertionsToDocument();
     void childrenChanged();
     void handleSourceAttribute(const String& sourceUrl);
     void handleAsyncAttribute();
@@ -82,7 +82,6 @@
     void stopLoadRequest();
 
     ScriptLoaderClient* client() const;
-    Document* executingDocument() const;
 
     // ResourceClient
     virtual void notifyFinished(Resource*) OVERRIDE;
diff --git a/Source/core/dom/SecurityPolicyViolationEvent.idl b/Source/core/dom/SecurityPolicyViolationEvent.idl
index 8eab91e..d067fab 100644
--- a/Source/core/dom/SecurityPolicyViolationEvent.idl
+++ b/Source/core/dom/SecurityPolicyViolationEvent.idl
@@ -23,7 +23,7 @@
  */
 
 [
-    EnabledAtRuntime=experimentalContentSecurityPolicyFeatures,
+    EnabledAtRuntime=ExperimentalContentSecurityPolicyFeatures,
     ConstructorTemplate=Event
 ] interface SecurityPolicyViolationEvent : Event {
     [InitializedByEventConstructor] readonly attribute DOMString documentURI;
diff --git a/Source/core/dom/SelectorQuery.cpp b/Source/core/dom/SelectorQuery.cpp
index db7afdf..82baa86 100644
--- a/Source/core/dom/SelectorQuery.cpp
+++ b/Source/core/dom/SelectorQuery.cpp
@@ -223,7 +223,7 @@
 
 inline bool SelectorDataList::canUseFastQuery(Node* rootNode) const
 {
-    return m_selectors.size() == 1 && rootNode->inDocument() && !rootNode->document()->inQuirksMode();
+    return m_selectors.size() == 1 && rootNode->inDocument() && !rootNode->document().inQuirksMode();
 }
 
 // If returns true, traversalRoots has the elements that may match the selector query.
@@ -245,8 +245,8 @@
     bool startFromParent = false;
 
     for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) {
-        if (selector->m_match == CSSSelector::Id && !rootNode->document()->containsMultipleElementsWithId(selector->value())) {
-            Element* element = rootNode->treeScope()->getElementById(selector->value());
+        if (selector->m_match == CSSSelector::Id && !rootNode->document().containsMultipleElementsWithId(selector->value())) {
+            Element* element = rootNode->treeScope().getElementById(selector->value());
             if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)))
                 rootNode = element;
             else if (!element || isRightmostSelector)
@@ -313,11 +313,11 @@
         switch (firstSelector->m_match) {
         case CSSSelector::Id:
             {
-                if (rootNode->document()->containsMultipleElementsWithId(firstSelector->value()))
+                if (rootNode->document().containsMultipleElementsWithId(firstSelector->value()))
                     break;
 
                 // Just the same as getElementById.
-                Element* element = rootNode->treeScope()->getElementById(firstSelector->value());
+                Element* element = rootNode->treeScope().getElementById(firstSelector->value());
                 if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)))
                     matchedElements.append(element);
                 return;
@@ -374,8 +374,8 @@
     bool matchSingleNode = true;
     bool startFromParent = false;
     for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) {
-        if (selector->m_match == CSSSelector::Id && !rootNode->document()->containsMultipleElementsWithId(selector->value())) {
-            Element* element = rootNode->treeScope()->getElementById(selector->value());
+        if (selector->m_match == CSSSelector::Id && !rootNode->document().containsMultipleElementsWithId(selector->value())) {
+            Element* element = rootNode->treeScope().getElementById(selector->value());
             if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)))
                 rootNode = element;
             else if (!element || matchSingleNode)
@@ -427,9 +427,9 @@
         switch (selector->m_match) {
         case CSSSelector::Id:
             {
-                if (rootNode->document()->containsMultipleElementsWithId(selector->value()))
+                if (rootNode->document().containsMultipleElementsWithId(selector->value()))
                     break;
-                Element* element = rootNode->treeScope()->getElementById(selector->value());
+                Element* element = rootNode->treeScope().getElementById(selector->value());
                 return element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)) ? element : 0;
             }
         case CSSSelector::Class:
@@ -480,7 +480,7 @@
     return m_selectors.queryFirst(rootNode);
 }
 
-SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, Document* document, ExceptionState& es)
+SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, const Document& document, ExceptionState& es)
 {
     HashMap<AtomicString, OwnPtr<SelectorQuery> >::iterator it = m_entries.find(selectors);
     if (it != m_entries.end())
@@ -491,13 +491,13 @@
     parser.parseSelector(selectors, selectorList);
 
     if (!selectorList.first()) {
-        es.throwDOMException(SyntaxError);
+        es.throwDOMException(SyntaxError, "Failed to execute query: '" + selectors + "' is not a valid selector.");
         return 0;
     }
 
     // throw a NamespaceError if the selector includes any namespace prefixes.
     if (selectorList.selectorsNeedNamespaceResolution()) {
-        es.throwDOMException(NamespaceError);
+        es.throwDOMException(NamespaceError, "Failed to execute query: '" + selectors + "' contains namespaces, which are not supported.");
         return 0;
     }
 
diff --git a/Source/core/dom/SelectorQuery.h b/Source/core/dom/SelectorQuery.h
index 66f12a6..2f654c4 100644
--- a/Source/core/dom/SelectorQuery.h
+++ b/Source/core/dom/SelectorQuery.h
@@ -88,7 +88,7 @@
 class SelectorQueryCache {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    SelectorQuery* add(const AtomicString&, Document*, ExceptionState&);
+    SelectorQuery* add(const AtomicString&, const Document&, ExceptionState&);
     void invalidate();
 
 private:
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
index ff29a77..a0d7c84 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
@@ -41,7 +41,7 @@
 
 using namespace HTMLNames;
 
-ShadowTreeStyleSheetCollection::ShadowTreeStyleSheetCollection(ShadowRoot* shadowRoot)
+ShadowTreeStyleSheetCollection::ShadowTreeStyleSheetCollection(ShadowRoot& shadowRoot)
     : StyleSheetCollection(shadowRoot)
 {
 }
@@ -65,7 +65,7 @@
         AtomicString title = element->getAttribute(titleAttr);
         bool enabledViaScript = false;
 
-        sheet = static_cast<HTMLStyleElement*>(node)->sheet();
+        sheet = toHTMLStyleElement(node)->sheet();
         if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
             activeSheet = static_cast<CSSStyleSheet*>(sheet);
 
diff --git a/Source/core/dom/ShadowTreeStyleSheetCollection.h b/Source/core/dom/ShadowTreeStyleSheetCollection.h
index 2e0a979..a849d68 100644
--- a/Source/core/dom/ShadowTreeStyleSheetCollection.h
+++ b/Source/core/dom/ShadowTreeStyleSheetCollection.h
@@ -41,7 +41,7 @@
 class ShadowTreeStyleSheetCollection FINAL : public StyleSheetCollection {
     WTF_MAKE_NONCOPYABLE(ShadowTreeStyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit ShadowTreeStyleSheetCollection(ShadowRoot*);
+    explicit ShadowTreeStyleSheetCollection(ShadowRoot&);
 
     bool updateActiveStyleSheets(StyleSheetCollections*, StyleResolverUpdateMode);
 
diff --git a/Source/core/dom/StyleElement.cpp b/Source/core/dom/StyleElement.cpp
index 683a8f2..8f8a151 100644
--- a/Source/core/dom/StyleElement.cpp
+++ b/Source/core/dom/StyleElement.cpp
@@ -55,22 +55,20 @@
         clearSheet();
 }
 
-void StyleElement::processStyleSheet(Document* document, Element* element)
+void StyleElement::processStyleSheet(Document& document, Element* element)
 {
-    ASSERT(document);
     ASSERT(element);
-    document->styleSheetCollections()->addStyleSheetCandidateNode(element, m_createdByParser);
+    document.styleSheetCollections()->addStyleSheetCandidateNode(element, m_createdByParser);
     if (m_createdByParser)
         return;
 
     process(element);
 }
 
-void StyleElement::removedFromDocument(Document* document, Element* element, ContainerNode* scopingNode)
+void StyleElement::removedFromDocument(Document& document, Element* element, ContainerNode* scopingNode)
 {
-    ASSERT(document);
     ASSERT(element);
-    document->styleSheetCollections()->removeStyleSheetCandidateNode(element, scopingNode);
+    document.styleSheetCollections()->removeStyleSheetCandidateNode(element, scopingNode);
 
     RefPtr<StyleSheet> removedSheet = m_sheet;
 
@@ -78,17 +76,17 @@
         clearSheet();
 
     // If we're in document teardown, then we don't need to do any notification of our sheet's removal.
-    if (document->renderer())
-        document->removedStyleSheet(removedSheet.get());
+    if (document.renderer())
+        document.removedStyleSheet(removedSheet.get());
 }
 
-void StyleElement::clearDocumentData(Document* document, Element* element)
+void StyleElement::clearDocumentData(Document& document, Element* element)
 {
     if (m_sheet)
         m_sheet->clearOwnerNode();
 
     if (element->inDocument())
-        document->styleSheetCollections()->removeStyleSheetCandidateNode(element, isHTMLStyleElement(element) ? toHTMLStyleElement(element)->scopingNode() :  0);
+        document.styleSheetCollections()->removeStyleSheetCandidateNode(element, isHTMLStyleElement(element) ? toHTMLStyleElement(element)->scopingNode() :  0);
 }
 
 void StyleElement::childrenChanged(Element* element)
@@ -124,26 +122,26 @@
 {
     ASSERT(e);
     ASSERT(e->inDocument());
-    Document* document = e->document();
+    Document& document = e->document();
     if (m_sheet) {
         if (m_sheet->isLoading())
-            document->styleSheetCollections()->removePendingSheet(e);
+            document.styleSheetCollections()->removePendingSheet(e);
         clearSheet();
     }
 
     // If type is empty or CSS, this is a CSS style sheet.
     const AtomicString& type = this->type();
-    if (document->contentSecurityPolicy()->allowInlineStyle(e->document()->url(), m_startPosition.m_line) && isCSS(e, type)) {
+    if (document.contentSecurityPolicy()->allowInlineStyle(e->document().url(), m_startPosition.m_line) && isCSS(e, type)) {
         RefPtr<MediaQuerySet> mediaQueries = MediaQuerySet::create(media());
 
         MediaQueryEvaluator screenEval("screen", true);
         MediaQueryEvaluator printEval("print", true);
         if (screenEval.eval(mediaQueries.get()) || printEval.eval(mediaQueries.get())) {
-            document->styleSheetCollections()->addPendingSheet();
+            document.styleSheetCollections()->addPendingSheet();
             m_loading = true;
 
             TextPosition startPosition = m_startPosition == TextPosition::belowRangePosition() ? TextPosition::minimumPosition() : m_startPosition;
-            m_sheet = CSSStyleSheet::createInline(e, KURL(), startPosition, document->inputEncoding());
+            m_sheet = CSSStyleSheet::createInline(e, KURL(), startPosition, document.inputEncoding());
             m_sheet->setMediaQueries(mediaQueries.release());
             m_sheet->setTitle(e->title());
             m_sheet->contents()->parseStringAtPosition(text, startPosition, m_createdByParser);
@@ -163,20 +161,18 @@
     return m_sheet ? m_sheet->isLoading() : false;
 }
 
-bool StyleElement::sheetLoaded(Document* document)
+bool StyleElement::sheetLoaded(Document& document)
 {
-    ASSERT(document);
     if (isLoading())
         return false;
 
-    document->styleSheetCollections()->removePendingSheet(m_sheet->ownerNode());
+    document.styleSheetCollections()->removePendingSheet(m_sheet->ownerNode());
     return true;
 }
 
-void StyleElement::startLoadingDynamicSheet(Document* document)
+void StyleElement::startLoadingDynamicSheet(Document& document)
 {
-    ASSERT(document);
-    document->styleSheetCollections()->addPendingSheet();
+    document.styleSheetCollections()->addPendingSheet();
 }
 
 }
diff --git a/Source/core/dom/StyleElement.h b/Source/core/dom/StyleElement.h
index 38ffd15..a26f5a5 100644
--- a/Source/core/dom/StyleElement.h
+++ b/Source/core/dom/StyleElement.h
@@ -42,12 +42,12 @@
     CSSStyleSheet* sheet() const { return m_sheet.get(); }
 
     bool isLoading() const;
-    bool sheetLoaded(Document*);
-    void startLoadingDynamicSheet(Document*);
+    bool sheetLoaded(Document&);
+    void startLoadingDynamicSheet(Document&);
 
-    void processStyleSheet(Document*, Element*);
-    void removedFromDocument(Document*, Element*, ContainerNode* scopingNode = 0);
-    void clearDocumentData(Document*, Element*);
+    void processStyleSheet(Document&, Element*);
+    void removedFromDocument(Document&, Element*, ContainerNode* scopingNode = 0);
+    void clearDocumentData(Document&, Element*);
     void childrenChanged(Element*);
     void finishParsingChildren(Element*);
 
diff --git a/Source/core/dom/StyleSheetCollection.cpp b/Source/core/dom/StyleSheetCollection.cpp
index 8a2b102..1edd2b8 100644
--- a/Source/core/dom/StyleSheetCollection.cpp
+++ b/Source/core/dom/StyleSheetCollection.cpp
@@ -39,7 +39,7 @@
 
 namespace WebCore {
 
-StyleSheetCollection::StyleSheetCollection(TreeScope* treeScope)
+StyleSheetCollection::StyleSheetCollection(TreeScope& treeScope)
     : m_treeScope(treeScope)
     , m_hadActiveLoadingStylesheet(false)
 {
@@ -160,7 +160,7 @@
         for (ListHashSet<Node*, 4>::iterator it = removedNodes->begin(); it != removedNodes->end(); ++it)
             styleResolver->resetAuthorStyle(toContainerNode(*it));
     }
-    styleResolver->resetAuthorStyle(toContainerNode(m_treeScope->rootNode()));
+    styleResolver->resetAuthorStyle(toContainerNode(m_treeScope.rootNode()));
 }
 
 static bool styleSheetsUseRemUnits(const Vector<RefPtr<CSSStyleSheet> >& sheets)
diff --git a/Source/core/dom/StyleSheetCollection.h b/Source/core/dom/StyleSheetCollection.h
index 5fc6111..0a89677 100644
--- a/Source/core/dom/StyleSheetCollection.h
+++ b/Source/core/dom/StyleSheetCollection.h
@@ -68,9 +68,9 @@
     ListHashSet<Node*, 4>* scopingNodesRemoved() { return m_scopingNodesForStyleScoped.scopingNodesRemoved(); }
 
 protected:
-    explicit StyleSheetCollection(TreeScope*);
+    explicit StyleSheetCollection(TreeScope&);
 
-    Document* document() { return m_treeScope->documentScope(); }
+    Document* document() { return m_treeScope.documentScope(); }
 
     enum StyleResolverUpdateType {
         Reconstruct,
@@ -89,7 +89,7 @@
     Vector<RefPtr<StyleSheet> > m_styleSheetsForStyleSheetList;
     Vector<RefPtr<CSSStyleSheet> > m_activeAuthorStyleSheets;
 
-    TreeScope* m_treeScope;
+    TreeScope& m_treeScope;
     bool m_hadActiveLoadingStylesheet;
     bool m_usesRemUnits;
 
diff --git a/Source/core/dom/StyleSheetCollections.cpp b/Source/core/dom/StyleSheetCollections.cpp
index 7a4ae2e..665c240 100644
--- a/Source/core/dom/StyleSheetCollections.cpp
+++ b/Source/core/dom/StyleSheetCollections.cpp
@@ -52,7 +52,7 @@
 
 using namespace HTMLNames;
 
-StyleSheetCollections::StyleSheetCollections(Document* document)
+StyleSheetCollections::StyleSheetCollections(Document& document)
     : m_document(document)
     , m_pendingStylesheets(0)
     , m_injectedStyleSheetCacheValid(false)
@@ -97,7 +97,7 @@
     do {
         --it;
         TreeScope* n = *it;
-        unsigned short position = n->comparePosition(treeScope);
+        unsigned short position = n->comparePosition(*treeScope);
         if (position & Node::DOCUMENT_POSITION_FOLLOWING) {
             treeScopes.insertBefore(followingTreeScope, treeScope);
             return;
@@ -108,23 +108,23 @@
     treeScopes.insertBefore(followingTreeScope, treeScope);
 }
 
-StyleSheetCollection* StyleSheetCollections::ensureStyleSheetCollectionFor(TreeScope* treeScope)
+StyleSheetCollection* StyleSheetCollections::ensureStyleSheetCollectionFor(TreeScope& treeScope)
 {
-    if (treeScope == m_document)
+    if (&treeScope == &m_document)
         return &m_documentStyleSheetCollection;
 
-    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::AddResult result = m_styleSheetCollectionMap.add(treeScope, nullptr);
+    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::AddResult result = m_styleSheetCollectionMap.add(&treeScope, nullptr);
     if (result.isNewEntry)
         result.iterator->value = adoptPtr(new ShadowTreeStyleSheetCollection(toShadowRoot(treeScope)));
     return result.iterator->value.get();
 }
 
-StyleSheetCollection* StyleSheetCollections::styleSheetCollectionFor(TreeScope* treeScope)
+StyleSheetCollection* StyleSheetCollections::styleSheetCollectionFor(TreeScope& treeScope)
 {
-    if (treeScope == m_document)
+    if (&treeScope == &m_document)
         return &m_documentStyleSheetCollection;
 
-    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::iterator it = m_styleSheetCollectionMap.find(treeScope);
+    HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::iterator it = m_styleSheetCollectionMap.find(&treeScope);
     if (it == m_styleSheetCollectionMap.end())
         return 0;
     return it->value.get();
@@ -171,7 +171,7 @@
     if (m_pageUserSheet)
         return m_pageUserSheet.get();
 
-    Page* owningPage = m_document->page();
+    Page* owningPage = m_document.page();
     if (!owningPage)
         return 0;
 
@@ -180,7 +180,7 @@
         return 0;
 
     // Parse the sheet and cache it.
-    m_pageUserSheet = CSSStyleSheet::createInline(m_document, m_document->settings()->userStyleSheetLocation());
+    m_pageUserSheet = CSSStyleSheet::createInline(&m_document, m_document.settings()->userStyleSheetLocation());
     m_pageUserSheet->contents()->setIsUserStyleSheet(true);
     m_pageUserSheet->contents()->parseString(userSheetText);
     return m_pageUserSheet.get();
@@ -191,7 +191,7 @@
     if (m_pageUserSheet) {
         RefPtr<StyleSheet> removedSheet = m_pageUserSheet;
         m_pageUserSheet = 0;
-        m_document->removedStyleSheet(removedSheet.get());
+        m_document.removedStyleSheet(removedSheet.get());
     }
 }
 
@@ -200,7 +200,7 @@
     clearPageUserSheet();
     // FIXME: Why is this immediately and not defer?
     if (StyleSheet* addedSheet = pageUserSheet())
-        m_document->addedStyleSheet(addedSheet, RecalcStyleImmediately);
+        m_document.addedStyleSheet(addedSheet, RecalcStyleImmediately);
 }
 
 const Vector<RefPtr<CSSStyleSheet> >& StyleSheetCollections::injectedUserStyleSheets() const
@@ -223,7 +223,7 @@
     m_injectedUserStyleSheets.clear();
     m_injectedAuthorStyleSheets.clear();
 
-    Page* owningPage = m_document->page();
+    Page* owningPage = m_document.page();
     if (!owningPage)
         return;
 
@@ -231,11 +231,11 @@
     const UserStyleSheetVector& sheets = pageGroup.userStyleSheets();
     for (unsigned i = 0; i < sheets.size(); ++i) {
         const UserStyleSheet* sheet = sheets[i].get();
-        if (sheet->injectedFrames() == InjectInTopFrameOnly && m_document->ownerElement())
+        if (sheet->injectedFrames() == InjectInTopFrameOnly && m_document.ownerElement())
             continue;
-        if (!UserContentURLPattern::matchesPatterns(m_document->url(), sheet->whitelist(), sheet->blacklist()))
+        if (!UserContentURLPattern::matchesPatterns(m_document.url(), sheet->whitelist(), sheet->blacklist()))
             continue;
-        RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(m_document), sheet->url());
+        RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(&m_document), sheet->url());
         bool isUserStyleSheet = sheet->level() == UserStyleUserLevel;
         if (isUserStyleSheet)
             m_injectedUserStyleSheets.append(groupSheet);
@@ -252,22 +252,22 @@
     m_needsDocumentStyleSheetsUpdate = true;
     // FIXME: updateInjectedStyleSheetCache is called inside StyleSheetCollection::updateActiveStyleSheets
     // and batch updates lots of sheets so we can't call addedStyleSheet() or removedStyleSheet().
-    m_document->styleResolverChanged(RecalcStyleDeferred);
+    m_document.styleResolverChanged(RecalcStyleDeferred);
 }
 
 void StyleSheetCollections::addAuthorSheet(PassRefPtr<StyleSheetContents> authorSheet)
 {
     ASSERT(!authorSheet->isUserStyleSheet());
-    m_authorStyleSheets.append(CSSStyleSheet::create(authorSheet, m_document));
-    m_document->addedStyleSheet(m_authorStyleSheets.last().get(), RecalcStyleImmediately);
+    m_authorStyleSheets.append(CSSStyleSheet::create(authorSheet, &m_document));
+    m_document.addedStyleSheet(m_authorStyleSheets.last().get(), RecalcStyleImmediately);
     m_needsDocumentStyleSheetsUpdate = true;
 }
 
 void StyleSheetCollections::addUserSheet(PassRefPtr<StyleSheetContents> userSheet)
 {
     ASSERT(userSheet->isUserStyleSheet());
-    m_userStyleSheets.append(CSSStyleSheet::create(userSheet, m_document));
-    m_document->addedStyleSheet(m_userStyleSheets.last().get(), RecalcStyleImmediately);
+    m_userStyleSheets.append(CSSStyleSheet::create(userSheet, &m_document));
+    m_document.addedStyleSheet(m_userStyleSheets.last().get(), RecalcStyleImmediately);
     m_needsDocumentStyleSheetsUpdate = true;
 }
 
@@ -279,8 +279,8 @@
 
     m_pendingStylesheets--;
 
-    TreeScope* treeScope = isHTMLStyleElement(styleSheetCandidateNode) ? styleSheetCandidateNode->treeScope() : m_document;
-    if (treeScope == m_document)
+    TreeScope* treeScope = isHTMLStyleElement(styleSheetCandidateNode) ? &styleSheetCandidateNode->treeScope() : &m_document;
+    if (treeScope == &m_document)
         m_needsDocumentStyleSheetsUpdate = true;
     else
         m_dirtyTreeScopes.add(treeScope);
@@ -289,13 +289,13 @@
         return;
 
     if (notification == RemovePendingSheetNotifyLater) {
-        m_document->setNeedsNotifyRemoveAllPendingStylesheet();
+        m_document.setNeedsNotifyRemoveAllPendingStylesheet();
         return;
     }
 
     // FIXME: We can't call addedStyleSheet or removedStyleSheet here because we don't know
     // what's new. We should track that to tell the style system what changed.
-    m_document->didRemoveAllPendingStylesheet();
+    m_document.didRemoveAllPendingStylesheet();
 }
 
 void StyleSheetCollections::addStyleSheetCandidateNode(Node* node, bool createdByParser)
@@ -303,37 +303,37 @@
     if (!node->inDocument())
         return;
 
-    TreeScope* treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
-    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+    TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
+    ASSERT(isHTMLStyleElement(node) || &treeScope == &m_document);
 
     StyleSheetCollection* collection = ensureStyleSheetCollectionFor(treeScope);
     ASSERT(collection);
     collection->addStyleSheetCandidateNode(node, createdByParser);
 
-    if (treeScope == m_document) {
+    if (&treeScope == &m_document) {
         m_needsDocumentStyleSheetsUpdate = true;
         return;
     }
 
-    insertTreeScopeInDocumentOrder(m_activeTreeScopes, treeScope);
-    m_dirtyTreeScopes.add(treeScope);
+    insertTreeScopeInDocumentOrder(m_activeTreeScopes, &treeScope);
+    m_dirtyTreeScopes.add(&treeScope);
 }
 
 void StyleSheetCollections::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
 {
-    TreeScope* treeScope = scopingNode ? scopingNode->treeScope() : m_document;
-    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+    TreeScope& treeScope = scopingNode ? scopingNode->treeScope() : m_document;
+    ASSERT(isHTMLStyleElement(node) || &treeScope == &m_document);
 
     StyleSheetCollection* collection = styleSheetCollectionFor(treeScope);
     ASSERT(collection);
     collection->removeStyleSheetCandidateNode(node, scopingNode);
 
-    if (treeScope == m_document) {
+    if (&treeScope == &m_document) {
         m_needsDocumentStyleSheetsUpdate = true;
         return;
     }
-    m_dirtyTreeScopes.add(treeScope);
-    m_activeTreeScopes.remove(treeScope);
+    m_dirtyTreeScopes.add(&treeScope);
+    m_activeTreeScopes.remove(&treeScope);
 }
 
 void StyleSheetCollections::modifiedStyleSheetCandidateNode(Node* node)
@@ -341,13 +341,13 @@
     if (!node->inDocument())
         return;
 
-    TreeScope* treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
-    ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
-    if (treeScope == m_document) {
+    TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
+    ASSERT(isHTMLStyleElement(node) || &treeScope == &m_document);
+    if (&treeScope == &m_document) {
         m_needsDocumentStyleSheetsUpdate = true;
         return;
     }
-    m_dirtyTreeScopes.add(treeScope);
+    m_dirtyTreeScopes.add(&treeScope);
 }
 
 bool StyleSheetCollections::shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode updateMode)
@@ -357,7 +357,7 @@
 
 bool StyleSheetCollections::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
 {
-    if (m_document->inStyleRecalc()) {
+    if (m_document.inStyleRecalc()) {
         // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
         // https://bugs.webkit.org/show_bug.cgi?id=54344
         // FIXME: This should be fixed in SVG and the call site replaced by ASSERT(!m_inStyleRecalc).
@@ -365,7 +365,7 @@
         return false;
 
     }
-    if (!m_document->renderer() || !m_document->attached())
+    if (!m_document.renderer() || !m_document.attached())
         return false;
 
     bool requiresFullStyleRecalc = false;
@@ -378,8 +378,8 @@
 
         for (TreeScopeSet::iterator it = treeScopes.begin(); it != treeScopes.end(); ++it) {
             TreeScope* treeScope = *it;
-            ASSERT(treeScope != m_document);
-            ShadowTreeStyleSheetCollection* collection = static_cast<ShadowTreeStyleSheetCollection*>(styleSheetCollectionFor(treeScope));
+            ASSERT(treeScope != &m_document);
+            ShadowTreeStyleSheetCollection* collection = static_cast<ShadowTreeStyleSheetCollection*>(styleSheetCollectionFor(*treeScope));
             ASSERT(collection);
             collection->updateActiveStyleSheets(this, updateMode);
             if (!collection->hasStyleSheetCandidateNodes())
@@ -391,7 +391,7 @@
         m_dirtyTreeScopes.clear();
     }
 
-    if (StyleResolver* styleResolver = m_document->styleResolverIfExists()) {
+    if (StyleResolver* styleResolver = m_document.styleResolverIfExists()) {
         styleResolver->finishAppendAuthorStyleSheets();
         resetCSSFeatureFlags(styleResolver->ruleFeatureSet());
     }
@@ -401,7 +401,7 @@
     m_usesRemUnits = m_documentStyleSheetCollection.usesRemUnits();
 
     if (m_needsDocumentStyleSheetsUpdate || updateMode == FullStyleUpdate) {
-        m_document->notifySeamlessChildDocumentsOfStylesheetUpdate();
+        m_document.notifySeamlessChildDocumentsOfStylesheetUpdate();
         m_needsDocumentStyleSheetsUpdate = false;
     }
 
@@ -411,7 +411,7 @@
 void StyleSheetCollections::activeStyleSheetsUpdatedForInspector()
 {
     if (m_activeTreeScopes.isEmpty()) {
-        InspectorInstrumentation::activeStyleSheetsUpdated(m_document, m_documentStyleSheetCollection.styleSheetsForStyleSheetList());
+        InspectorInstrumentation::activeStyleSheetsUpdated(&m_document, m_documentStyleSheetCollection.styleSheetsForStyleSheetList());
         return;
     }
     Vector<RefPtr<StyleSheet> > activeStyleSheets;
@@ -428,7 +428,7 @@
     // FIXME: Inspector needs a vector which has all active stylesheets.
     // However, creating such a large vector might cause performance regression.
     // Need to implement some smarter solution.
-    InspectorInstrumentation::activeStyleSheetsUpdated(m_document, activeStyleSheets);
+    InspectorInstrumentation::activeStyleSheetsUpdated(&m_document, activeStyleSheets);
 }
 
 void StyleSheetCollections::didRemoveShadowRoot(ShadowRoot* shadowRoot)
diff --git a/Source/core/dom/StyleSheetCollections.h b/Source/core/dom/StyleSheetCollections.h
index e934e51..978d1b0 100644
--- a/Source/core/dom/StyleSheetCollections.h
+++ b/Source/core/dom/StyleSheetCollections.h
@@ -51,7 +51,7 @@
 class StyleSheetCollections {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<StyleSheetCollections> create(Document* document) { return adoptPtr(new StyleSheetCollections(document)); }
+    static PassOwnPtr<StyleSheetCollections> create(Document& document) { return adoptPtr(new StyleSheetCollections(document)); }
 
     ~StyleSheetCollections();
 
@@ -112,17 +112,17 @@
     void getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const;
 
 private:
-    StyleSheetCollections(Document*);
+    StyleSheetCollections(Document&);
 
-    StyleSheetCollection* ensureStyleSheetCollectionFor(TreeScope*);
-    StyleSheetCollection* styleSheetCollectionFor(TreeScope*);
+    StyleSheetCollection* ensureStyleSheetCollectionFor(TreeScope&);
+    StyleSheetCollection* styleSheetCollectionFor(TreeScope&);
     void activeStyleSheetsUpdatedForInspector();
     bool shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode);
 
     typedef ListHashSet<TreeScope*, 16> TreeScopeSet;
     static void insertTreeScopeInDocumentOrder(TreeScopeSet&, TreeScope*);
 
-    Document* m_document;
+    Document& m_document;
 
     // Track the number of currently loading top-level stylesheets needed for rendering.
     // Sheets loaded using the @import directive are not included in this count.
@@ -161,4 +161,3 @@
 }
 
 #endif
-
diff --git a/Source/core/dom/TemplateContentDocumentFragment.h b/Source/core/dom/TemplateContentDocumentFragment.h
index 6ede6f3..6c44e60 100644
--- a/Source/core/dom/TemplateContentDocumentFragment.h
+++ b/Source/core/dom/TemplateContentDocumentFragment.h
@@ -33,16 +33,17 @@
 
 class TemplateContentDocumentFragment FINAL : public DocumentFragment {
 public:
-    static PassRefPtr<TemplateContentDocumentFragment> create(Document* document, const Element* host)
+    static PassRefPtr<TemplateContentDocumentFragment> create(Document& document, const Element* host)
     {
         return adoptRef(new TemplateContentDocumentFragment(document, host));
     }
 
     const Element* host() const { return m_host; }
+    void clearHost() { m_host = 0; }
 
 private:
-    TemplateContentDocumentFragment(Document* document, const Element* host)
-        : DocumentFragment(document, CreateDocumentFragment)
+    TemplateContentDocumentFragment(Document& document, const Element* host)
+        : DocumentFragment(&document, CreateDocumentFragment)
         , m_host(host)
     {
     }
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index 425aabd..90446f1 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -23,6 +23,7 @@
 #include "core/dom/Text.h"
 
 #include "SVGNames.h"
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/css/resolver/StyleResolver.h"
@@ -41,12 +42,12 @@
 
 namespace WebCore {
 
-PassRefPtr<Text> Text::create(Document* document, const String& data)
+PassRefPtr<Text> Text::create(Document& document, const String& data)
 {
     return adoptRef(new Text(document, data, CreateText));
 }
 
-PassRefPtr<Text> Text::createEditingText(Document* document, const String& data)
+PassRefPtr<Text> Text::createEditingText(Document& document, const String& data)
 {
     return adoptRef(new Text(document, data, CreateEditingText));
 }
@@ -56,7 +57,7 @@
     // IndexSizeError: Raised if the specified offset is negative or greater than
     // the number of 16-bit units in data.
     if (offset > length()) {
-        es.throwDOMException(IndexSizeError);
+        es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("splitText", "Text", "The offset " + String::number(offset) + " is larger than the Text node's length."));
         return 0;
     }
 
@@ -72,12 +73,12 @@
     if (es.hadException())
         return 0;
 
-    if (parentNode())
-        document()->textNodeSplit(this);
-
     if (renderer())
         toRenderText(renderer())->setTextWithOffset(dataImpl(), 0, oldStr.length());
 
+    if (parentNode())
+        document().textNodeSplit(this);
+
     return newText.release();
 }
 
@@ -87,7 +88,7 @@
     while ((n = n->previousSibling())) {
         Node::NodeType type = n->nodeType();
         if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) {
-            t = static_cast<const Text*>(n);
+            t = toText(n);
             continue;
         }
 
@@ -102,7 +103,7 @@
     while ((n = n->nextSibling())) {
         Node::NodeType type = n->nodeType();
         if (type == Node::TEXT_NODE || type == Node::CDATA_SECTION_NODE) {
-            t = static_cast<const Text*>(n);
+            t = toText(n);
             continue;
         }
 
@@ -121,8 +122,7 @@
     for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) {
         if (!n->isTextNode())
             continue;
-        const Text* t = static_cast<const Text*>(n);
-        const String& data = t->data();
+        const String& data = toText(n)->data();
         if (std::numeric_limits<unsigned>::max() - data.length() < resultLength)
             CRASH();
         resultLength += data.length();
@@ -132,8 +132,7 @@
     for (const Node* n = startText; n != onePastEndText; n = n->nextSibling()) {
         if (!n->isTextNode())
             continue;
-        const Text* t = static_cast<const Text*>(n);
-        result.append(t->data());
+        result.append(toText(n)->data());
     }
     ASSERT(result.length() == resultLength);
 
@@ -238,12 +237,6 @@
     return true;
 }
 
-static bool isSVGShadowText(Text* text)
-{
-    Node* parentNode = text->parentNode();
-    return parentNode->isShadowRoot() && toShadowRoot(parentNode)->host()->hasTagName(SVGNames::trefTag);
-}
-
 static bool isSVGText(Text* text)
 {
     Node* parentOrShadowHostNode = text->parentOrShadowHostNode();
@@ -252,7 +245,7 @@
 
 RenderText* Text::createTextRenderer(RenderStyle* style)
 {
-    if (isSVGText(this) || isSVGShadowText(this))
+    if (isSVGText(this))
         return new RenderSVGInlineText(this, dataImpl());
 
     if (style->hasTextCombine())
@@ -267,11 +260,11 @@
     CharacterData::attach(context);
 }
 
-bool Text::recalcTextStyle(StyleChange change)
+bool Text::recalcTextStyle(StyleRecalcChange change)
 {
     if (RenderText* renderer = toRenderText(this->renderer())) {
         if (change != NoChange || needsStyleRecalc())
-            renderer->setStyle(document()->styleResolver()->styleForText(this));
+            renderer->setStyle(document().styleResolver()->styleForText(this));
         if (needsStyleRecalc())
             renderer->setText(dataImpl());
         clearNeedsStyleRecalc();
@@ -292,16 +285,16 @@
     return false;
 }
 
-void Text::updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, AttachBehavior attachBehavior)
+void Text::updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, RecalcStyleBehavior recalcStyleBehavior)
 {
     if (!attached())
         return;
     RenderText* textRenderer = toRenderText(renderer());
     if (!textRenderer || !textRendererIsNeeded(NodeRenderingContext(this, textRenderer->style()))) {
-        if (attachBehavior == DeprecatedAttachNow)
-            reattach();
-        else
-            lazyReattach();
+        lazyReattach();
+        // FIXME: Editing should be updated so this is not neccesary.
+        if (recalcStyleBehavior == DeprecatedRecalcStyleImmediatlelyForEditing)
+            document().updateStyleIfNeeded();
         return;
     }
     textRenderer->setTextWithOffset(dataImpl(), offsetOfReplacedData, lengthOfReplacedData);
@@ -317,7 +310,7 @@
     return create(document(), data);
 }
 
-PassRefPtr<Text> Text::createWithLengthLimit(Document* document, const String& data, unsigned start, unsigned lengthLimit)
+PassRefPtr<Text> Text::createWithLengthLimit(Document& document, const String& data, unsigned start, unsigned lengthLimit)
 {
     unsigned dataLength = data.length();
 
diff --git a/Source/core/dom/Text.h b/Source/core/dom/Text.h
index 33a459a..b9929c9 100644
--- a/Source/core/dom/Text.h
+++ b/Source/core/dom/Text.h
@@ -35,9 +35,9 @@
 public:
     static const unsigned defaultLengthLimit = 1 << 16;
 
-    static PassRefPtr<Text> create(Document*, const String&);
-    static PassRefPtr<Text> createWithLengthLimit(Document*, const String&, unsigned positionInString, unsigned lengthLimit = defaultLengthLimit);
-    static PassRefPtr<Text> createEditingText(Document*, const String&);
+    static PassRefPtr<Text> create(Document&, const String&);
+    static PassRefPtr<Text> createWithLengthLimit(Document&, const String&, unsigned positionInString, unsigned lengthLimit = defaultLengthLimit);
+    static PassRefPtr<Text> createEditingText(Document&, const String&);
 
     PassRefPtr<Text> splitText(unsigned offset, ExceptionState&);
 
@@ -46,10 +46,10 @@
     String wholeText() const;
     PassRefPtr<Text> replaceWholeText(const String&);
 
-    bool recalcTextStyle(StyleChange);
+    bool recalcTextStyle(StyleRecalcChange);
     bool textRendererIsNeeded(const NodeRenderingContext&);
     virtual RenderText* createTextRenderer(RenderStyle*);
-    void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, AttachBehavior = AttachLazily);
+    void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, RecalcStyleBehavior = DoNotRecalcStyle);
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
 
@@ -57,7 +57,7 @@
     virtual NodeType nodeType() const OVERRIDE;
 
 protected:
-    Text(TreeScope* treeScope, const String& data, ConstructionType type)
+    Text(TreeScope& treeScope, const String& data, ConstructionType type)
         : CharacterData(treeScope, data, type)
     {
         ScriptWrappable::init(this);
@@ -83,6 +83,12 @@
     return static_cast<Text*>(node);
 }
 
+inline const Text* toText(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isTextNode());
+    return static_cast<const Text*>(node);
+}
+
 } // namespace WebCore
 
 #endif // Text_h
diff --git a/Source/core/dom/TextLinkColors.cpp b/Source/core/dom/TextLinkColors.cpp
index a48f731..42b61c7 100644
--- a/Source/core/dom/TextLinkColors.cpp
+++ b/Source/core/dom/TextLinkColors.cpp
@@ -44,17 +44,17 @@
 
 void TextLinkColors::resetLinkColor()
 {
-    m_linkColor = StyleColor(0, 0, 238);
+    m_linkColor = Color(0, 0, 238);
 }
 
 void TextLinkColors::resetVisitedLinkColor()
 {
-    m_visitedLinkColor = StyleColor(85, 26, 139);
+    m_visitedLinkColor = Color(85, 26, 139);
 }
 
 void TextLinkColors::resetActiveLinkColor()
 {
-    m_activeLinkColor = StyleColor(255, 0, 0);
+    m_activeLinkColor.setNamedColor("red");
 }
 
 static Color colorForCSSValue(CSSValueID cssValueId)
@@ -94,10 +94,10 @@
     return RenderTheme::theme().systemColor(cssValueId);
 }
 
-StyleColor TextLinkColors::colorFromPrimitiveValue(const CSSPrimitiveValue* value, bool forVisitedLink) const
+Color TextLinkColors::colorFromPrimitiveValue(const CSSPrimitiveValue* value, Color currentColor, bool forVisitedLink) const
 {
     if (value->isRGBColor())
-        return StyleColor(value->getRGBA32Value());
+        return Color(value->getRGBA32Value());
 
     CSSValueID valueID = value->getValueID();
     switch (valueID) {
@@ -112,7 +112,7 @@
     case CSSValueWebkitFocusRingColor:
         return RenderTheme::focusRingColor();
     case CSSValueCurrentcolor:
-        return StyleColor::currentColor();
+        return currentColor;
     default:
         return colorForCSSValue(valueID);
     }
diff --git a/Source/core/dom/TextLinkColors.h b/Source/core/dom/TextLinkColors.h
index fb223e8..6d2728c 100644
--- a/Source/core/dom/TextLinkColors.h
+++ b/Source/core/dom/TextLinkColors.h
@@ -28,7 +28,7 @@
 #ifndef TextLinkColors_h
 #define TextLinkColors_h
 
-#include "core/css/StyleColor.h"
+#include "core/platform/graphics/Color.h"
 #include "wtf/Noncopyable.h"
 
 namespace WebCore {
@@ -41,25 +41,25 @@
 public:
     TextLinkColors();
 
-    void setTextColor(const StyleColor& color) { m_textColor = color; }
-    StyleColor textColor() const { return m_textColor; }
+    void setTextColor(const Color& color) { m_textColor = color; }
+    Color textColor() const { return m_textColor; }
 
-    const StyleColor& linkColor() const { return m_linkColor; }
-    const StyleColor& visitedLinkColor() const { return m_visitedLinkColor; }
-    const StyleColor& activeLinkColor() const { return m_activeLinkColor; }
+    const Color& linkColor() const { return m_linkColor; }
+    const Color& visitedLinkColor() const { return m_visitedLinkColor; }
+    const Color& activeLinkColor() const { return m_activeLinkColor; }
     void setLinkColor(const Color& color) { m_linkColor = color; }
     void setVisitedLinkColor(const Color& color) { m_visitedLinkColor = color; }
     void setActiveLinkColor(const Color& color) { m_activeLinkColor = color; }
     void resetLinkColor();
     void resetVisitedLinkColor();
     void resetActiveLinkColor();
-    StyleColor colorFromPrimitiveValue(const CSSPrimitiveValue*, bool forVisitedLink = false) const;
+    Color colorFromPrimitiveValue(const CSSPrimitiveValue*, Color currentColor, bool forVisitedLink = false) const;
 private:
 
-    StyleColor m_textColor;
-    StyleColor m_linkColor;
-    StyleColor m_visitedLinkColor;
-    StyleColor m_activeLinkColor;
+    Color m_textColor;
+    Color m_linkColor;
+    Color m_visitedLinkColor;
+    Color m_activeLinkColor;
 };
 
 }
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index 2a4ae34..e20240f 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -170,7 +170,7 @@
 Node* TreeScope::ancestorInThisScope(Node* node) const
 {
     while (node) {
-        if (node->treeScope() == this)
+        if (&node->treeScope() == this)
             return node;
         if (!node->isInShadowTree())
             return 0;
@@ -209,7 +209,7 @@
         return 0;
     size_t hashPos = url.find('#');
     String name = (hashPos == notFound ? url : url.substring(hashPos + 1)).impl();
-    if (rootNode()->document()->isHTMLDocument())
+    if (rootNode()->document().isHTMLDocument())
         return toHTMLMapElement(m_imageMapsByName->getElementByLowercasedMapName(AtomicString(name.lower()).impl(), this));
     return toHTMLMapElement(m_imageMapsByName->getElementByMapName(AtomicString(name).impl(), this));
 }
@@ -242,7 +242,7 @@
 
 Element* TreeScope::elementFromPoint(int x, int y) const
 {
-    Node* node = nodeFromPoint(rootNode()->document(), x, y);
+    Node* node = nodeFromPoint(&rootNode()->document(), x, y);
     if (node && node->isTextNode())
         node = node->parentNode();
     ASSERT(!node || node->isElementNode() || node->isShadowRoot());
@@ -287,7 +287,7 @@
 
 DOMSelection* TreeScope::getSelection() const
 {
-    if (!rootNode()->document()->frame())
+    if (!rootNode()->document().frame())
         return 0;
 
     if (m_selection)
@@ -309,7 +309,7 @@
     for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::next(element)) {
         if (isHTMLAnchorElement(element)) {
             HTMLAnchorElement* anchor = toHTMLAnchorElement(element);
-            if (rootNode()->document()->inQuirksMode()) {
+            if (rootNode()->document().inQuirksMode()) {
                 // Quirks mode, case insensitive comparison of names.
                 if (equalIgnoringCase(anchor->name(), name))
                     return anchor;
@@ -350,10 +350,10 @@
 
 Element* TreeScope::adjustedFocusedElement()
 {
-    Document* document = rootNode()->document();
-    Element* element = document->focusedElement();
-    if (!element && document->page())
-        element = focusedFrameOwnerElement(document->page()->focusController().focusedFrame(), document->frame());
+    Document& document = rootNode()->document();
+    Element* element = document.focusedElement();
+    if (!element && document.page())
+        element = focusedFrameOwnerElement(document.page()->focusController().focusedFrame(), document.frame());
     if (!element)
         return 0;
     Vector<Node*> targetStack;
@@ -379,12 +379,9 @@
     return 0;
 }
 
-unsigned short TreeScope::comparePosition(const TreeScope* otherScope) const
+unsigned short TreeScope::comparePosition(const TreeScope& otherScope) const
 {
-    if (!otherScope)
-        return Node::DOCUMENT_POSITION_DISCONNECTED;
-
-    if (otherScope == this)
+    if (&otherScope == this)
         return Node::DOCUMENT_POSITION_EQUIVALENT;
 
     Vector<const TreeScope*, 16> chain1;
@@ -392,7 +389,7 @@
     const TreeScope* current;
     for (current = this; current; current = current->parentTreeScope())
         chain1.append(current);
-    for (current = otherScope; current; current = current->parentTreeScope())
+    for (current = &otherScope; current; current = current->parentTreeScope())
         chain2.append(current);
 
     unsigned index1 = chain1.size();
@@ -427,7 +424,7 @@
 static void listTreeScopes(Node* node, Vector<TreeScope*, 5>& treeScopes)
 {
     while (true) {
-        treeScopes.append(node->treeScope());
+        treeScopes.append(&node->treeScope());
         Element* ancestor = node->shadowHost();
         if (!ancestor)
             break;
@@ -440,8 +437,8 @@
     if (!nodeA || !nodeB)
         return 0;
 
-    if (nodeA->treeScope() == nodeB->treeScope())
-        return nodeA->treeScope();
+    if (&nodeA->treeScope() == &nodeB->treeScope())
+        return &nodeA->treeScope();
 
     Vector<TreeScope*, 5> treeScopesA;
     listTreeScopes(nodeA, treeScopesA);
@@ -477,11 +474,10 @@
     return 0;
 }
 
-bool TreeScope::isInclusiveAncestorOf(const TreeScope* scope) const
+bool TreeScope::isInclusiveAncestorOf(const TreeScope& scope) const
 {
-    ASSERT(scope);
-    for (; scope; scope = scope->parentTreeScope()) {
-        if (scope == this)
+    for (const TreeScope* current = &scope; current; current = current->parentTreeScope()) {
+        if (current == this)
             return true;
     }
     return false;
diff --git a/Source/core/dom/TreeScope.h b/Source/core/dom/TreeScope.h
index 9f2d412..ecfc830 100644
--- a/Source/core/dom/TreeScope.h
+++ b/Source/core/dom/TreeScope.h
@@ -124,8 +124,8 @@
 
     void removedLastRefToScope();
 
-    bool isInclusiveAncestorOf(const TreeScope*) const;
-    unsigned short comparePosition(const TreeScope*) const;
+    bool isInclusiveAncestorOf(const TreeScope&) const;
+    unsigned short comparePosition(const TreeScope&) const;
 
     Element* getElementByAccessKey(const String& key) const;
 
diff --git a/Source/core/dom/TreeScopeAdopter.cpp b/Source/core/dom/TreeScopeAdopter.cpp
index 0c3387c..be8670b 100644
--- a/Source/core/dom/TreeScopeAdopter.cpp
+++ b/Source/core/dom/TreeScopeAdopter.cpp
@@ -104,7 +104,7 @@
 inline void TreeScopeAdopter::updateTreeScope(Node* node) const
 {
     ASSERT(!node->isTreeScope());
-    ASSERT(node->treeScope() == m_oldScope);
+    ASSERT(&node->treeScope() == m_oldScope);
     m_newScope->guardRef();
     m_oldScope->guardDeref();
     node->setTreeScope(m_newScope);
diff --git a/Source/core/dom/TreeScopeAdopter.h b/Source/core/dom/TreeScopeAdopter.h
index a629e9d..4ad9760 100644
--- a/Source/core/dom/TreeScopeAdopter.h
+++ b/Source/core/dom/TreeScopeAdopter.h
@@ -55,10 +55,11 @@
     TreeScope* m_oldScope;
 };
 
+// FIXME: Should take |TreeScope&| instead of |TreeScope*|.
 inline TreeScopeAdopter::TreeScopeAdopter(Node* toAdopt, TreeScope* newScope)
     : m_toAdopt(toAdopt)
     , m_newScope(newScope)
-    , m_oldScope(toAdopt->treeScope())
+    , m_oldScope(&toAdopt->treeScope())
 {
     ASSERT(newScope);
 }
diff --git a/Source/core/dom/TreeWalker.cpp b/Source/core/dom/TreeWalker.cpp
index bc0b775..bec5c19 100644
--- a/Source/core/dom/TreeWalker.cpp
+++ b/Source/core/dom/TreeWalker.cpp
@@ -25,6 +25,7 @@
 #include "config.h"
 #include "core/dom/TreeWalker.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ScriptState.h"
 #include "core/dom/ContainerNode.h"
@@ -45,7 +46,7 @@
 void TreeWalker::setCurrentNode(PassRefPtr<Node> node, ExceptionState& es)
 {
     if (!node) {
-        es.throwDOMException(NotSupportedError);
+        es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("setCurrentNode", "TreeWalker", "The Node provided is invalid."));
         return;
     }
     m_current = node;
diff --git a/Source/core/dom/ViewportArguments.cpp b/Source/core/dom/ViewportArguments.cpp
index 0a2708d..48d56e4 100644
--- a/Source/core/dom/ViewportArguments.cpp
+++ b/Source/core/dom/ViewportArguments.cpp
@@ -29,6 +29,8 @@
 #include "core/dom/ViewportArguments.h"
 
 #include "core/dom/Document.h"
+#include "core/page/Page.h"
+#include "core/page/Settings.h"
 #include "wtf/text/WTFString.h"
 
 using namespace std;
@@ -48,9 +50,6 @@
 
 static inline float clampLengthValue(float value)
 {
-    ASSERT(value != ViewportArguments::ValueDeviceWidth);
-    ASSERT(value != ViewportArguments::ValueDeviceHeight);
-
     // Limits as defined in the css-device-adapt spec.
     if (value != ViewportArguments::ValueAuto)
         return min(float(10000), max(value, float(1)));
@@ -59,203 +58,142 @@
 
 static inline float clampScaleValue(float value)
 {
-    ASSERT(value != ViewportArguments::ValueDeviceWidth);
-    ASSERT(value != ViewportArguments::ValueDeviceHeight);
-
     // Limits as defined in the css-device-adapt spec.
     if (value != ViewportArguments::ValueAuto)
         return min(float(10), max(value, float(0.1)));
     return value;
 }
 
-PageScaleConstraints ViewportArguments::resolve(const FloatSize& initialViewportSize, int defaultWidth) const
+float ViewportArguments::resolveViewportLength(const Length& length, const FloatSize& initialViewportSize, Direction direction)
 {
-    float resultWidth = width;
-    float resultMaxWidth = maxWidth;
-    float resultMinWidth = minWidth;
-    float resultHeight = height;
-    float resultMinHeight = minHeight;
-    float resultMaxHeight = maxHeight;
+    if (length.isAuto())
+        return ViewportArguments::ValueAuto;
+
+    if (length.isFixed())
+        return length.getFloatValue();
+
+    if (length.type() == ExtendToZoom)
+        return ViewportArguments::ValueExtendToZoom;
+
+    if ((length.type() == Percent && direction == Horizontal) || length.type() == ViewportPercentageWidth)
+        return initialViewportSize.width() * length.getFloatValue() / 100.0f;
+
+    if ((length.type() == Percent && direction == Vertical) || length.type() == ViewportPercentageHeight)
+        return initialViewportSize.height() * length.getFloatValue() / 100.0f;
+
+    if (length.type() == ViewportPercentageMin)
+        return min(initialViewportSize.width(), initialViewportSize.height()) * length.viewportPercentageLength() / 100.0f;
+
+    if (length.type() == ViewportPercentageMax)
+        return max(initialViewportSize.width(), initialViewportSize.height()) * length.viewportPercentageLength() / 100.0f;
+
+    ASSERT_NOT_REACHED();
+    return ViewportArguments::ValueAuto;
+}
+
+PageScaleConstraints ViewportArguments::resolve(const FloatSize& initialViewportSize) const
+{
+    float resultWidth = ValueAuto;
+    float resultMaxWidth = resolveViewportLength(maxWidth, initialViewportSize, Horizontal);
+    float resultMinWidth = resolveViewportLength(minWidth, initialViewportSize, Horizontal);
+    float resultHeight = ValueAuto;
+    float resultMaxHeight = resolveViewportLength(maxHeight, initialViewportSize, Vertical);
+    float resultMinHeight = resolveViewportLength(minHeight, initialViewportSize, Vertical);
 
     float resultZoom = zoom;
     float resultMinZoom = minZoom;
     float resultMaxZoom = maxZoom;
     float resultUserZoom = userZoom;
 
-    if (type == ViewportArguments::CSSDeviceAdaptation) {
+    // 1. Resolve min-zoom and max-zoom values.
+    if (resultMinZoom != ViewportArguments::ValueAuto && resultMaxZoom != ViewportArguments::ValueAuto)
+        resultMaxZoom = max(resultMinZoom, resultMaxZoom);
 
-        // device-width/device-height not supported for @viewport.
-        ASSERT(resultMinWidth != ViewportArguments::ValueDeviceWidth);
-        ASSERT(resultMinWidth != ViewportArguments::ValueDeviceHeight);
-        ASSERT(resultMaxWidth != ViewportArguments::ValueDeviceWidth);
-        ASSERT(resultMaxWidth != ViewportArguments::ValueDeviceHeight);
-        ASSERT(resultMinHeight != ViewportArguments::ValueDeviceWidth);
-        ASSERT(resultMinHeight != ViewportArguments::ValueDeviceHeight);
-        ASSERT(resultMaxHeight != ViewportArguments::ValueDeviceWidth);
-        ASSERT(resultMaxHeight != ViewportArguments::ValueDeviceHeight);
+    // 2. Constrain zoom value to the [min-zoom, max-zoom] range.
+    if (resultZoom != ViewportArguments::ValueAuto)
+        resultZoom = compareIgnoringAuto(resultMinZoom, compareIgnoringAuto(resultMaxZoom, resultZoom, min), max);
 
-        // 1. Resolve min-zoom and max-zoom values.
-        if (resultMinZoom != ViewportArguments::ValueAuto && resultMaxZoom != ViewportArguments::ValueAuto)
-            resultMaxZoom = max(resultMinZoom, resultMaxZoom);
+    float extendZoom = compareIgnoringAuto(resultZoom, resultMaxZoom, min);
 
-        // 2. Constrain zoom value to the [min-zoom, max-zoom] range.
-        if (resultZoom != ViewportArguments::ValueAuto)
-            resultZoom = compareIgnoringAuto(resultMinZoom, compareIgnoringAuto(resultMaxZoom, resultZoom, min), max);
+    // 3. Resolve non-"auto" lengths to pixel lengths.
+    if (extendZoom == ViewportArguments::ValueAuto) {
+        if (resultMaxWidth == ViewportArguments::ValueExtendToZoom)
+            resultMaxWidth = ViewportArguments::ValueAuto;
 
-        float extendZoom = compareIgnoringAuto(resultZoom, resultMaxZoom, min);
+        if (resultMaxHeight == ViewportArguments::ValueExtendToZoom)
+            resultMaxHeight = ViewportArguments::ValueAuto;
 
-        if (extendZoom == ViewportArguments::ValueAuto) {
-            if (resultMaxWidth == ViewportArguments::ValueExtendToZoom)
-                resultMaxWidth = ViewportArguments::ValueAuto;
+        if (resultMinWidth == ViewportArguments::ValueExtendToZoom)
+            resultMinWidth = resultMaxWidth;
 
-            if (resultMaxHeight == ViewportArguments::ValueExtendToZoom)
-                resultMaxHeight = ViewportArguments::ValueAuto;
+        if (resultMinHeight == ViewportArguments::ValueExtendToZoom)
+            resultMinHeight = resultMaxHeight;
+    } else {
+        float extendWidth = initialViewportSize.width() / extendZoom;
+        float extendHeight = initialViewportSize.height() / extendZoom;
 
-            if (resultMinWidth == ViewportArguments::ValueExtendToZoom)
-                resultMinWidth = resultMaxWidth;
+        if (resultMaxWidth == ViewportArguments::ValueExtendToZoom)
+            resultMaxWidth = extendWidth;
 
-            if (resultMinHeight == ViewportArguments::ValueExtendToZoom)
-                resultMinHeight = resultMaxHeight;
-        } else {
-            float extendWidth = initialViewportSize.width() / extendZoom;
-            float extendHeight = initialViewportSize.height() / extendZoom;
+        if (resultMaxHeight == ViewportArguments::ValueExtendToZoom)
+            resultMaxHeight = extendHeight;
 
-            if (resultMaxWidth == ViewportArguments::ValueExtendToZoom)
-                resultMaxWidth = extendWidth;
+        if (resultMinWidth == ViewportArguments::ValueExtendToZoom)
+            resultMinWidth = compareIgnoringAuto(extendWidth, resultMaxWidth, max);
 
-            if (resultMaxHeight == ViewportArguments::ValueExtendToZoom)
-                resultMaxHeight = extendHeight;
-
-            if (resultMinWidth == ViewportArguments::ValueExtendToZoom)
-                resultMinWidth = compareIgnoringAuto(extendWidth, resultMaxWidth, max);
-
-            if (resultMinHeight == ViewportArguments::ValueExtendToZoom)
-                resultMinHeight = compareIgnoringAuto(extendHeight, resultMaxHeight, max);
-        }
-
-        // 4. Resolve initial width from min/max descriptors.
-        if (resultMinWidth != ViewportArguments::ValueAuto || resultMaxWidth != ViewportArguments::ValueAuto)
-            resultWidth = compareIgnoringAuto(resultMinWidth, compareIgnoringAuto(resultMaxWidth, initialViewportSize.width(), min), max);
-
-        // 5. Resolve initial height from min/max descriptors.
-        if (resultMinHeight != ViewportArguments::ValueAuto || resultMaxHeight != ViewportArguments::ValueAuto)
-            resultHeight = compareIgnoringAuto(resultMinHeight, compareIgnoringAuto(resultMaxHeight, initialViewportSize.height(), min), max);
-
-        // 6-7. Resolve width value.
-        if (resultWidth == ViewportArguments::ValueAuto) {
-            if (resultHeight == ViewportArguments::ValueAuto || !initialViewportSize .height())
-                resultWidth = initialViewportSize.width();
-            else
-                resultWidth = resultHeight * (initialViewportSize.width() / initialViewportSize.height());
-        }
-
-        // 8. Resolve height value.
-        if (resultHeight == ViewportArguments::ValueAuto) {
-            if (!initialViewportSize.width())
-                resultHeight = initialViewportSize.height();
-            else
-                resultHeight = resultWidth * initialViewportSize.height() / initialViewportSize.width();
-        }
-
-        PageScaleConstraints result;
-        result.minimumScale = resultMinZoom;
-        result.maximumScale = resultMaxZoom;
-        result.initialScale = resultZoom;
-        result.layoutSize.setWidth(resultWidth);
-        result.layoutSize.setHeight(resultHeight);
-        return result;
+        if (resultMinHeight == ViewportArguments::ValueExtendToZoom)
+            resultMinHeight = compareIgnoringAuto(extendHeight, resultMaxHeight, max);
     }
 
-    switch (static_cast<int>(resultWidth)) {
-    case ViewportArguments::ValueDeviceWidth:
-        resultWidth = initialViewportSize.width();
-        break;
-    case ViewportArguments::ValueDeviceHeight:
-        resultWidth = initialViewportSize.height();
-        break;
+    // 4. Resolve initial width from min/max descriptors.
+    if (resultMinWidth != ViewportArguments::ValueAuto || resultMaxWidth != ViewportArguments::ValueAuto)
+        resultWidth = compareIgnoringAuto(resultMinWidth, compareIgnoringAuto(resultMaxWidth, initialViewportSize.width(), min), max);
+
+    // 5. Resolve initial height from min/max descriptors.
+    if (resultMinHeight != ViewportArguments::ValueAuto || resultMaxHeight != ViewportArguments::ValueAuto)
+        resultHeight = compareIgnoringAuto(resultMinHeight, compareIgnoringAuto(resultMaxHeight, initialViewportSize.height(), min), max);
+
+    // 6-7. Resolve width value.
+    if (resultWidth == ViewportArguments::ValueAuto) {
+        if (resultHeight == ViewportArguments::ValueAuto || !initialViewportSize.height())
+            resultWidth = initialViewportSize.width();
+        else
+            resultWidth = resultHeight * (initialViewportSize.width() / initialViewportSize.height());
     }
 
-    switch (static_cast<int>(resultHeight)) {
-    case ViewportArguments::ValueDeviceWidth:
-        resultHeight = initialViewportSize.width();
-        break;
-    case ViewportArguments::ValueDeviceHeight:
-        resultHeight = initialViewportSize.height();
-        break;
+    // 8. Resolve height value.
+    if (resultHeight == ViewportArguments::ValueAuto) {
+        if (!initialViewportSize.width())
+            resultHeight = initialViewportSize.height();
+        else
+            resultHeight = resultWidth * initialViewportSize.height() / initialViewportSize.width();
     }
 
-    if (type != ViewportArguments::Implicit) {
-        // Clamp values to a valid range, but not for @viewport since is
-        // not mandated by the specification.
-        resultWidth = clampLengthValue(resultWidth);
-        resultHeight = clampLengthValue(resultHeight);
-        resultZoom = clampScaleValue(resultZoom);
-        resultMinZoom = clampScaleValue(resultMinZoom);
-        resultMaxZoom = clampScaleValue(resultMaxZoom);
-    }
-
-    PageScaleConstraints result;
-
-    // Resolve minimum-scale and maximum-scale values according to spec.
-    if (resultMinZoom == ViewportArguments::ValueAuto)
-        result.minimumScale = float(0.25);
-    else
-        result.minimumScale = resultMinZoom;
-
-    if (resultMaxZoom == ViewportArguments::ValueAuto) {
-        result.maximumScale = float(5.0);
-        result.minimumScale = min(float(5.0), result.minimumScale);
-    } else
-        result.maximumScale = resultMaxZoom;
-    result.maximumScale = max(result.minimumScale, result.maximumScale);
-
     // Resolve initial-scale value.
-    result.initialScale = resultZoom;
     if (resultZoom == ViewportArguments::ValueAuto) {
-        result.initialScale = initialViewportSize.width() / defaultWidth;
         if (resultWidth != ViewportArguments::ValueAuto && resultWidth > 0)
-            result.initialScale = initialViewportSize.width() / resultWidth;
+            resultZoom = initialViewportSize.width() / resultWidth;
         if (resultHeight != ViewportArguments::ValueAuto && resultHeight > 0) {
             // if 'auto', the initial-scale will be negative here and thus ignored.
-            result.initialScale = max<float>(result.initialScale, initialViewportSize.height() / resultHeight);
+            resultZoom = max<float>(resultZoom, initialViewportSize.height() / resultHeight);
         }
     }
 
-    // Constrain initial-scale value to minimum-scale/maximum-scale range.
-    result.initialScale = min(result.maximumScale, max(result.minimumScale, result.initialScale));
-
-    // Resolve width value.
-    if (resultWidth == ViewportArguments::ValueAuto) {
-        if (resultZoom == ViewportArguments::ValueAuto)
-            resultWidth = defaultWidth;
-        else if (resultHeight != ViewportArguments::ValueAuto)
-            resultWidth = resultHeight * (initialViewportSize.width() / initialViewportSize.height());
-        else
-            resultWidth = initialViewportSize.width() / result.initialScale;
-    }
-
-    // Resolve height value.
-    if (resultHeight == ViewportArguments::ValueAuto)
-        resultHeight = resultWidth * (initialViewportSize.height() / initialViewportSize.width());
-
-    if (type == ViewportArguments::ViewportMeta) {
-        // Extend width and height to fill the visual viewport for the resolved initial-scale.
-        resultWidth = max<float>(resultWidth, initialViewportSize.width() / result.initialScale);
-        resultHeight = max<float>(resultHeight, initialViewportSize.height() / result.initialScale);
-    }
-
-    result.layoutSize.setWidth(resultWidth);
-    result.layoutSize.setHeight(resultHeight);
-
     // If user-scalable = no, lock the min/max scale to the computed initial
     // scale.
     if (!resultUserZoom)
-        result.maximumScale = result.minimumScale = result.initialScale;
+        resultMinZoom = resultMaxZoom = resultZoom;
 
     // Only set initialScale to a value if it was explicitly set.
-    if (resultZoom == ViewportArguments::ValueAuto)
-        result.initialScale = ViewportArguments::ValueAuto;
+    if (zoom == ViewportArguments::ValueAuto)
+        resultZoom = ViewportArguments::ValueAuto;
 
+    PageScaleConstraints result;
+    result.minimumScale = resultMinZoom;
+    result.maximumScale = resultMaxZoom;
+    result.initialScale = resultZoom;
+    result.layoutSize.setWidth(resultWidth);
+    result.layoutSize.setHeight(resultHeight);
     return result;
 }
 
@@ -280,7 +218,7 @@
     return value;
 }
 
-static float findSizeValue(const String& keyString, const String& valueString, Document* document)
+static Length findSizeValue(const String& keyString, const String& valueString, Document* document)
 {
     // 1) Non-negative number values are translated to px lengths.
     // 2) Negative number values are translated to auto.
@@ -288,16 +226,23 @@
     // 4) Other keywords and unknown values translate to 0.0.
 
     if (equalIgnoringCase(valueString, "device-width"))
-        return ViewportArguments::ValueDeviceWidth;
+        return Length(100, ViewportPercentageWidth);
     if (equalIgnoringCase(valueString, "device-height"))
-        return ViewportArguments::ValueDeviceHeight;
+        return Length(100, ViewportPercentageHeight);
 
     float value = numericPrefix(keyString, valueString, document);
 
     if (value < 0)
-        return ViewportArguments::ValueAuto;
+        return Length(); // auto
 
-    return value;
+    if (!static_cast<int>(value) && document->page() && document->page()->settings().viewportMetaZeroValuesQuirk()) {
+        if (keyString == "width")
+            return Length(100, ViewportPercentageWidth);
+        if (keyString == "height")
+            return Length(100, ViewportPercentageHeight);
+    }
+
+    return Length(clampLengthValue(value), Fixed);
 }
 
 static float findScaleValue(const String& keyString, const String& valueString, Document* document)
@@ -325,7 +270,10 @@
     if (value > 10.0)
         reportViewportWarning(document, MaximumScaleTooLargeError, String(), String());
 
-    return value;
+    if (!static_cast<int>(value) && document->page() && document->page()->settings().viewportMetaZeroValuesQuirk() && (keyString == "minimum-scale" || keyString == "maximum-scale"))
+        return ViewportArguments::ValueAuto;
+
+    return clampScaleValue(value);
 }
 
 static float findUserScalableValue(const String& keyString, const String& valueString, Document* document)
@@ -374,29 +322,37 @@
 {
     ViewportArguments* arguments = static_cast<ViewportArguments*>(data);
 
-    if (keyString == "width")
-        arguments->width = findSizeValue(keyString, valueString, document);
-    else if (keyString == "height")
-        arguments->height = findSizeValue(keyString, valueString, document);
-    else if (keyString == "initial-scale")
+    if (keyString == "width") {
+        const Length& width = findSizeValue(keyString, valueString, document);
+        if (!width.isAuto()) {
+            arguments->minWidth = Length(ExtendToZoom);
+            arguments->maxWidth = width;
+        }
+    } else if (keyString == "height") {
+        const Length& height = findSizeValue(keyString, valueString, document);
+        if (!height.isAuto()) {
+            arguments->minHeight = Length(ExtendToZoom);
+            arguments->maxHeight = height;
+        }
+    } else if (keyString == "initial-scale") {
         arguments->zoom = findScaleValue(keyString, valueString, document);
-    else if (keyString == "minimum-scale")
+    } else if (keyString == "minimum-scale") {
         arguments->minZoom = findScaleValue(keyString, valueString, document);
-    else if (keyString == "maximum-scale")
+    } else if (keyString == "maximum-scale") {
         arguments->maxZoom = findScaleValue(keyString, valueString, document);
-    else if (keyString == "user-scalable")
+    } else if (keyString == "user-scalable") {
         arguments->userZoom = findUserScalableValue(keyString, valueString, document);
-    else if (keyString == "target-densitydpi") {
+    } else if (keyString == "target-densitydpi") {
         arguments->deprecatedTargetDensityDPI = findTargetDensityDPIValue(keyString, valueString, document);
         reportViewportWarning(document, TargetDensityDpiUnsupported, String(), String());
-    } else
+    } else {
         reportViewportWarning(document, UnrecognizedViewportArgumentKeyError, keyString, String());
+    }
 }
 
 static const char* viewportErrorMessageTemplate(ViewportErrorCode errorCode)
 {
     static const char* const errors[] = {
-        "Note that ';' is not a key-value pair separator. The list should be comma-separated.",
         "The key \"%replacement1\" is not recognized and ignored.",
         "The value \"%replacement1\" for key \"%replacement2\" is invalid, and has been ignored.",
         "The value \"%replacement1\" for key \"%replacement2\" was truncated to its numeric prefix.",
@@ -410,7 +366,6 @@
 static MessageLevel viewportErrorMessageLevel(ViewportErrorCode errorCode)
 {
     switch (errorCode) {
-    case InvalidKeyValuePairSeparatorError:
     case TruncatedViewportArgumentValueError:
     case TargetDensityDpiUnsupported:
         return WarningMessageLevel;
diff --git a/Source/core/dom/ViewportArguments.h b/Source/core/dom/ViewportArguments.h
index 6533441..e0722b8 100644
--- a/Source/core/dom/ViewportArguments.h
+++ b/Source/core/dom/ViewportArguments.h
@@ -29,6 +29,7 @@
 #define ViewportArguments_h
 
 #include "core/page/PageScaleConstraints.h"
+#include "core/platform/Length.h"
 #include "core/platform/graphics/FloatSize.h"
 #include "wtf/Forward.h"
 
@@ -37,7 +38,6 @@
 class Document;
 
 enum ViewportErrorCode {
-    InvalidKeyValuePairSeparatorError,
     UnrecognizedViewportArgumentKeyError,
     UnrecognizedViewportArgumentValueError,
     TruncatedViewportArgumentValueError,
@@ -49,12 +49,11 @@
 
     enum Type {
         // These are ordered in increasing importance.
-        Implicit,
-        XHTMLMobileProfile,
+        UserAgentStyleSheet,
         HandheldFriendlyMeta,
         MobileOptimizedMeta,
         ViewportMeta,
-        CSSDeviceAdaptation
+        AuthorStyleSheet
     } type;
 
     enum {
@@ -70,14 +69,8 @@
         ValueExtendToZoom = -10
     };
 
-    ViewportArguments(Type type = Implicit)
+    ViewportArguments(Type type = UserAgentStyleSheet)
         : type(type)
-        , width(ValueAuto)
-        , minWidth(ValueAuto)
-        , maxWidth(ValueAuto)
-        , height(ValueAuto)
-        , minHeight(ValueAuto)
-        , maxHeight(ValueAuto)
         , zoom(ValueAuto)
         , minZoom(ValueAuto)
         , maxZoom(ValueAuto)
@@ -88,14 +81,12 @@
     }
 
     // All arguments are in CSS units.
-    PageScaleConstraints resolve(const FloatSize& initialViewportSize, int defaultWidth) const;
+    PageScaleConstraints resolve(const FloatSize& initialViewportSize) const;
 
-    float width;
-    float minWidth;
-    float maxWidth;
-    float height;
-    float minHeight;
-    float maxHeight;
+    Length minWidth;
+    Length maxWidth;
+    Length minHeight;
+    Length maxHeight;
     float zoom;
     float minZoom;
     float maxZoom;
@@ -107,10 +98,8 @@
     {
         // Used for figuring out whether to reset the viewport or not,
         // thus we are not taking type into account.
-        return width == other.width
-            && minWidth == other.minWidth
+        return minWidth == other.minWidth
             && maxWidth == other.maxWidth
-            && height == other.height
             && minHeight == other.minHeight
             && maxHeight == other.maxHeight
             && zoom == other.zoom
@@ -125,6 +114,12 @@
     {
         return !(*this == other);
     }
+
+    bool isLegacyViewportType() const { return type >= HandheldFriendlyMeta && type <= ViewportMeta; }
+
+private:
+    enum Direction { Horizontal, Vertical };
+    static float resolveViewportLength(const Length&, const FloatSize& initialViewportSize, Direction);
 };
 
 void setViewportFeature(const String& keyString, const String& valueString, Document*, void* data);
diff --git a/Source/core/dom/WebKitNamedFlow.idl b/Source/core/dom/WebKitNamedFlow.idl
index a8f68dd..33cff65 100644
--- a/Source/core/dom/WebKitNamedFlow.idl
+++ b/Source/core/dom/WebKitNamedFlow.idl
@@ -29,7 +29,7 @@
 
 [
     NoInterfaceObject,
-    EnabledAtRuntime=cssRegions,
+    EnabledAtRuntime=CSSRegions,
     ImplementedAs=NamedFlow,
     GenerateIsReachable=ownerNode
 ] interface WebKitNamedFlow : EventTarget {
diff --git a/Source/core/dom/WebKitNamedFlowCollection.idl b/Source/core/dom/WebKitNamedFlowCollection.idl
index 65aa56d..92aec8e 100644
--- a/Source/core/dom/WebKitNamedFlowCollection.idl
+++ b/Source/core/dom/WebKitNamedFlowCollection.idl
@@ -29,7 +29,7 @@
 
 [
     NoInterfaceObject,
-    EnabledAtRuntime=cssRegions,
+    EnabledAtRuntime=CSSRegions,
     ImplementedAs=DOMNamedFlowCollection
 ] interface WebKitNamedFlowCollection {
     readonly attribute unsigned long length;
diff --git a/Source/core/dom/WheelController.cpp b/Source/core/dom/WheelController.cpp
new file mode 100644
index 0000000..48c14a7
--- /dev/null
+++ b/Source/core/dom/WheelController.cpp
@@ -0,0 +1,121 @@
+/*
+ * 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/WheelController.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/EventNames.h"
+#include "core/dom/WheelEvent.h"
+#include "core/page/Frame.h"
+#include "core/page/Page.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
+
+namespace WebCore {
+
+WheelController::WheelController(Document* document)
+    : DOMWindowLifecycleObserver(document->domWindow())
+    , m_wheelEventHandlerCount(0)
+{
+}
+
+WheelController::~WheelController()
+{
+}
+
+const char* WheelController::supplementName()
+{
+    return "WheelController";
+}
+
+WheelController* WheelController::from(Document* document)
+{
+    WheelController* controller = static_cast<WheelController*>(Supplement<ScriptExecutionContext>::from(document, supplementName()));
+    if (!controller) {
+        controller = new WheelController(document);
+        Supplement<ScriptExecutionContext>::provideTo(document, supplementName(), adoptPtr(controller));
+    }
+    return controller;
+}
+
+static void wheelEventHandlerCountChanged(Document* document)
+{
+    Page* page = document->page();
+    if (!page)
+        return;
+
+    ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator();
+    if (!scrollingCoordinator)
+        return;
+
+    FrameView* frameView = document->view();
+    if (!frameView)
+        return;
+
+    scrollingCoordinator->frameViewWheelEventHandlerCountChanged(frameView);
+}
+
+void WheelController::didAddWheelEventHandler(Document* document)
+{
+    ++m_wheelEventHandlerCount;
+    Page* page = document->page();
+    Frame* mainFrame = page ? page->mainFrame() : 0;
+    if (mainFrame)
+        mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
+
+    wheelEventHandlerCountChanged(document);
+}
+
+void WheelController::didRemoveWheelEventHandler(Document* document)
+{
+    ASSERT(m_wheelEventHandlerCount > 0);
+    --m_wheelEventHandlerCount;
+    Page* page = document->page();
+    Frame* mainFrame = page ? page->mainFrame() : 0;
+    if (mainFrame)
+        mainFrame->notifyChromeClientWheelEventHandlerCountChanged();
+
+    wheelEventHandlerCountChanged(document);
+}
+
+void WheelController::didAddEventListener(DOMWindow* window, const AtomicString& eventType)
+{
+    if (eventType != eventNames().wheelEvent && eventType != eventNames().mousewheelEvent)
+        return;
+
+    Document* document = window->document();
+    didAddWheelEventHandler(document);
+}
+
+void WheelController::didRemoveEventListener(DOMWindow* window, const AtomicString& eventType)
+{
+    if (eventType != eventNames().wheelEvent && eventType != eventNames().mousewheelEvent)
+        return;
+
+    Document* document = window->document();
+    didRemoveWheelEventHandler(document);
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/WheelController.h b/Source/core/dom/WheelController.h
new file mode 100644
index 0000000..13406ee
--- /dev/null
+++ b/Source/core/dom/WheelController.h
@@ -0,0 +1,62 @@
+/*
+ * 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 WheelController_h
+#define WheelController_h
+
+#include "core/dom/Event.h"
+#include "core/page/DOMWindowLifecycleObserver.h"
+#include "core/platform/Supplementable.h"
+
+namespace WebCore {
+
+class DOMWindow;
+
+class WheelController : public Supplement<ScriptExecutionContext>, public DOMWindowLifecycleObserver {
+
+public:
+    virtual ~WheelController();
+
+    static const char* supplementName();
+    static WheelController* from(Document*);
+
+    unsigned wheelEventHandlerCount() { return m_wheelEventHandlerCount; }
+
+    void didAddWheelEventHandler(Document*);
+    void didRemoveWheelEventHandler(Document*);
+
+    // Inherited from DOMWindowLifecycleObserver
+    virtual void didAddEventListener(DOMWindow*, const AtomicString&) OVERRIDE;
+    virtual void didRemoveEventListener(DOMWindow*, const AtomicString&) OVERRIDE;
+
+private:
+    explicit WheelController(Document*);
+
+    unsigned m_wheelEventHandlerCount;
+};
+
+} // namespace WebCore
+
+#endif // WheelController_h
diff --git a/Source/core/dom/shadow/ComposedTreeWalker.cpp b/Source/core/dom/shadow/ComposedTreeWalker.cpp
index 86f97ed..1e19ddc 100644
--- a/Source/core/dom/shadow/ComposedTreeWalker.cpp
+++ b/Source/core/dom/shadow/ComposedTreeWalker.cpp
@@ -60,14 +60,9 @@
 Node* ComposedTreeWalker::traverseChild(const Node* node, TraversalDirection direction) const
 {
     ASSERT(node);
-    if (canCrossUpperBoundary()) {
-        ElementShadow* shadow = shadowFor(node);
-        return shadow ? traverseLightChildren(shadow->youngestShadowRoot(), direction)
+    ElementShadow* shadow = shadowFor(node);
+    return shadow ? traverseLightChildren(shadow->youngestShadowRoot(), direction)
             : traverseLightChildren(node, direction);
-    }
-    if (isShadowHost(node))
-        return 0;
-    return traverseLightChildren(node, direction);
 }
 
 Node* ComposedTreeWalker::traverseLightChildren(const Node* node, TraversalDirection direction)
@@ -170,11 +165,6 @@
     if (node->isPseudoElement())
         return node->parentOrShadowHostNode();
 
-    if (!canCrossUpperBoundary() && node->isShadowRoot()) {
-        ASSERT(toShadowRoot(node)->isYoungest());
-        return 0;
-    }
-
     if (nodeCanBeDistributed(node)) {
         if (InsertionPoint* insertionPoint = resolveReprojection(node)) {
             if (details)
@@ -202,13 +192,9 @@
     ASSERT(!shadowRoot->insertionPoint());
 
     if (shadowRoot->isYoungest()) {
-        if (canCrossUpperBoundary()) {
-            if (details)
-                details->didTraverseShadowRoot(shadowRoot);
-            return shadowRoot->host();
-        }
-
-        return const_cast<ShadowRoot*>(shadowRoot);
+        if (details)
+            details->didTraverseShadowRoot(shadowRoot);
+        return shadowRoot->host();
     }
 
     return 0;
diff --git a/Source/core/dom/shadow/ComposedTreeWalker.h b/Source/core/dom/shadow/ComposedTreeWalker.h
index a75ac9e..2fb9cf3 100644
--- a/Source/core/dom/shadow/ComposedTreeWalker.h
+++ b/Source/core/dom/shadow/ComposedTreeWalker.h
@@ -42,17 +42,12 @@
 public:
     typedef NodeRenderingTraversal::ParentDetails ParentTraversalDetails;
 
-    enum Policy {
-        CrossUpperBoundary,
-        DoNotCrossUpperBoundary,
-    };
-
     enum StartPolicy {
         CanStartFromShadowBoundary,
         CannotStartFromShadowBoundary
     };
 
-    ComposedTreeWalker(const Node*, Policy = CrossUpperBoundary, StartPolicy = CannotStartFromShadowBoundary);
+    ComposedTreeWalker(const Node*, StartPolicy = CannotStartFromShadowBoundary);
 
     Node* get() const { return const_cast<Node*>(m_node); }
 
@@ -77,16 +72,11 @@
         TraversalDirectionBackward
     };
 
-    bool canCrossUpperBoundary() const { return m_policy == CrossUpperBoundary; }
-
     void assertPrecondition() const
     {
 #ifndef NDEBUG
         ASSERT(m_node);
-        if (canCrossUpperBoundary())
-            ASSERT(!m_node->isShadowRoot());
-        else
-            ASSERT(!m_node->isShadowRoot() || toShadowRoot(m_node)->isYoungest());
+        ASSERT(!m_node->isShadowRoot());
         ASSERT(!isActiveInsertionPoint(m_node));
 #endif
     }
@@ -123,12 +113,10 @@
     Node* traverseParentBackToYoungerShadowRootOrHost(const ShadowRoot*, ParentTraversalDetails* = 0) const;
 
     const Node* m_node;
-    Policy m_policy;
 };
 
-inline ComposedTreeWalker::ComposedTreeWalker(const Node* node, Policy policy, StartPolicy startPolicy)
+inline ComposedTreeWalker::ComposedTreeWalker(const Node* node, StartPolicy startPolicy)
     : m_node(node)
-    , m_policy(policy)
 {
     UNUSED_PARAM(startPolicy);
 #ifndef NDEBUG
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 1224962..455ad32 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -57,10 +57,10 @@
 
 ShadowRoot* ElementShadow::addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType type)
 {
-    RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(shadowHost->document(), type);
+    RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(&shadowHost->document(), type);
 
     shadowRoot->setParentOrShadowHostNode(shadowHost);
-    shadowRoot->setParentTreeScope(shadowHost->treeScope());
+    shadowRoot->setParentTreeScope(&shadowHost->treeScope());
     m_shadowRoots.push(shadowRoot.get());
     ChildNodeInsertionNotifier(shadowHost).notify(shadowRoot.get());
     setNeedsDistributionRecalc();
@@ -70,6 +70,7 @@
     // The youngest shadow root's apply-author-styles is default (false). So we can just set m_applyAuthorStyles false.
     m_applyAuthorStyles = false;
 
+    shadowHost->didAddShadowRoot(*shadowRoot);
     InspectorInstrumentation::didPushShadowRoot(shadowHost, shadowRoot.get());
 
     return shadowRoot.get();
@@ -82,14 +83,14 @@
 
     while (RefPtr<ShadowRoot> oldRoot = m_shadowRoots.head()) {
         InspectorInstrumentation::willPopShadowRoot(shadowHost, oldRoot.get());
-        shadowHost->document()->removeFocusedElementOfSubtree(oldRoot.get());
+        shadowHost->document().removeFocusedElementOfSubtree(oldRoot.get());
 
         if (oldRoot->attached())
             oldRoot->detach();
 
         m_shadowRoots.removeHead();
         oldRoot->setParentOrShadowHostNode(0);
-        oldRoot->setParentTreeScope(shadowHost->document());
+        oldRoot->setParentTreeScope(&shadowHost->document());
         oldRoot->setPrev(0);
         oldRoot->setNext(0);
         ChildNodeRemovalNotifier(shadowHost).notify(oldRoot.get());
diff --git a/Source/core/dom/shadow/InsertionPoint.cpp b/Source/core/dom/shadow/InsertionPoint.cpp
index 5d01a73..4c2b26d 100644
--- a/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/Source/core/dom/shadow/InsertionPoint.cpp
@@ -41,7 +41,7 @@
 
 using namespace HTMLNames;
 
-InsertionPoint::InsertionPoint(const QualifiedName& tagName, Document* document)
+InsertionPoint::InsertionPoint(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document, CreateInsertionPoint)
     , m_registeredWithShadowRoot(false)
 {
@@ -114,7 +114,7 @@
     HTMLElement::detach(context);
 }
 
-void InsertionPoint::willRecalcStyle(StyleChange change)
+void InsertionPoint::willRecalcStyle(StyleRecalcChange change)
 {
     if (change < Inherit)
         return;
@@ -143,7 +143,7 @@
 
 PassRefPtr<NodeList> InsertionPoint::getDistributedNodes()
 {
-    document()->updateDistributionForNodeIfNeeded(this);
+    document().updateDistributionForNodeIfNeeded(this);
 
     Vector<RefPtr<Node> > nodes;
     for (size_t i = 0; i < m_distribution.size(); ++i)
@@ -152,9 +152,9 @@
     return StaticNodeList::adopt(nodes);
 }
 
-bool InsertionPoint::rendererIsNeeded(const NodeRenderingContext& context)
+bool InsertionPoint::rendererIsNeeded(const RenderStyle& style)
 {
-    return !isActive() && HTMLElement::rendererIsNeeded(context);
+    return !isActive() && HTMLElement::rendererIsNeeded(style);
 }
 
 void InsertionPoint::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -173,7 +173,7 @@
     if (ShadowRoot* root = containingShadowRoot()) {
         if (ElementShadow* rootOwner = root->owner()) {
             rootOwner->setNeedsDistributionRecalc();
-            if (isActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope()->rootNode() == root) {
+            if (isActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
                 m_registeredWithShadowRoot = true;
                 root->addInsertionPoint(this);
                 rootOwner->didAffectApplyAuthorStyles();
@@ -203,7 +203,7 @@
     // Since this insertion point is no longer visible from the shadow subtree, it need to clean itself up.
     clearDistribution();
 
-    if (m_registeredWithShadowRoot && insertionPoint->treeScope()->rootNode() == root) {
+    if (m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
         ASSERT(root);
         m_registeredWithShadowRoot = false;
         root->removeInsertionPoint(this);
diff --git a/Source/core/dom/shadow/InsertionPoint.h b/Source/core/dom/shadow/InsertionPoint.h
index aeb3243..d12423b 100644
--- a/Source/core/dom/shadow/InsertionPoint.h
+++ b/Source/core/dom/shadow/InsertionPoint.h
@@ -67,13 +67,13 @@
     Node* previousTo(const Node* node) const { return m_distribution.previousTo(node); }
 
 protected:
-    InsertionPoint(const QualifiedName&, Document*);
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
+    InsertionPoint(const QualifiedName&, Document&);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual void childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void willRecalcStyle(StyleChange) OVERRIDE;
+    virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
 
 private:
 
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index 6269a5c..fa21b00 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -27,6 +27,7 @@
 #include "config.h"
 #include "core/dom/shadow/ShadowRoot.h"
 
+#include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ElementTraversal.h"
@@ -123,7 +124,7 @@
 
 PassRefPtr<Node> ShadowRoot::cloneNode(bool, ExceptionState& es)
 {
-    es.throwDOMException(DataCloneError);
+    es.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("cloneNode", "ShadowRoot", "ShadowRoot nodes are not clonable."));
     return 0;
 }
 
@@ -135,7 +136,7 @@
 void ShadowRoot::setInnerHTML(const String& markup, ExceptionState& es)
 {
     if (isOrphan()) {
-        es.throwDOMException(InvalidAccessError);
+        es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("setInnerHTML", "ShadowRoot", "The ShadowRoot does not have a host."));
         return;
     }
 
@@ -157,13 +158,13 @@
     }
 }
 
-void ShadowRoot::recalcStyle(StyleChange change)
+void ShadowRoot::recalcStyle(StyleRecalcChange change)
 {
     // ShadowRoot doesn't support custom callbacks.
     ASSERT(!hasCustomStyleCallbacks());
 
-    StyleResolver* styleResolver = document()->styleResolver();
-    styleResolver->pushParentShadowRoot(this);
+    StyleResolver* styleResolver = document().styleResolver();
+    styleResolver->pushParentShadowRoot(*this);
 
     if (!attached()) {
         attach();
@@ -196,7 +197,7 @@
         forceReattachOfAnyWhitespaceSibling = didReattach || forceReattachOfAnyWhitespaceSibling;
     }
 
-    styleResolver->popParentShadowRoot(this);
+    styleResolver->popParentShadowRoot(*this);
     clearNeedsStyleRecalc();
     clearChildNeedsStyleRecalc();
 }
@@ -252,10 +253,10 @@
 
 void ShadowRoot::attach(const AttachContext& context)
 {
-    StyleResolver* styleResolver = document()->styleResolver();
-    styleResolver->pushParentShadowRoot(this);
+    StyleResolver* styleResolver = document().styleResolver();
+    styleResolver->pushParentShadowRoot(*this);
     DocumentFragment::attach(context);
-    styleResolver->popParentShadowRoot(this);
+    styleResolver->popParentShadowRoot(*this);
 }
 
 Node::InsertionNotificationRequest ShadowRoot::insertedInto(ContainerNode* insertionPoint)
diff --git a/Source/core/dom/shadow/ShadowRoot.h b/Source/core/dom/shadow/ShadowRoot.h
index 018f8e8..99bdf97 100644
--- a/Source/core/dom/shadow/ShadowRoot.h
+++ b/Source/core/dom/shadow/ShadowRoot.h
@@ -58,7 +58,7 @@
         return adoptRef(new ShadowRoot(document, type));
     }
 
-    void recalcStyle(StyleChange);
+    void recalcStyle(StyleRecalcChange);
 
     bool applyAuthorStyles() const { return m_applyAuthorStyles; }
     void setApplyAuthorStyles(bool);
@@ -145,7 +145,7 @@
 
 inline Element* ShadowRoot::activeElement() const
 {
-    if (Element* element = treeScope()->adjustedFocusedElement())
+    if (Element* element = treeScope().adjustedFocusedElement())
         return element;
     return 0;
 }
@@ -161,6 +161,12 @@
     return const_cast<ShadowRoot*>(toShadowRoot(static_cast<const Node*>(node)));
 }
 
+inline const ShadowRoot& toShadowRoot(const Node& node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(node.isShadowRoot());
+    return static_cast<const ShadowRoot&>(node);
+}
+
 inline const ShadowRoot* toShadowRoot(const TreeScope* treeScope)
 {
     ASSERT_WITH_SECURITY_IMPLICATION(!treeScope || (treeScope->rootNode() && treeScope->rootNode()->isShadowRoot()));
@@ -172,6 +178,12 @@
     return const_cast<ShadowRoot*>(toShadowRoot(static_cast<const TreeScope*>(treeScope)));
 }
 
+inline ShadowRoot& toShadowRoot(TreeScope& treeScope)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(treeScope.rootNode() && treeScope.rootNode()->isShadowRoot());
+    return static_cast<ShadowRoot&>(treeScope);
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/editing/AppendNodeCommand.cpp b/Source/core/editing/AppendNodeCommand.cpp
index f72b893..e8047c9 100644
--- a/Source/core/editing/AppendNodeCommand.cpp
+++ b/Source/core/editing/AppendNodeCommand.cpp
@@ -59,12 +59,4 @@
     m_node->remove(IGNORE_EXCEPTION);
 }
 
-#ifndef NDEBUG
-void AppendNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_parent.get(), nodes);
-    addNodeAndDescendants(m_node.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/AppendNodeCommand.h b/Source/core/editing/AppendNodeCommand.h
index 5587d67..1f7a5ae 100644
--- a/Source/core/editing/AppendNodeCommand.h
+++ b/Source/core/editing/AppendNodeCommand.h
@@ -43,10 +43,6 @@
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<ContainerNode> m_parent;
     RefPtr<Node> m_node;
 };
diff --git a/Source/core/editing/ApplyBlockElementCommand.cpp b/Source/core/editing/ApplyBlockElementCommand.cpp
index 3fb54fc..938ee5b 100644
--- a/Source/core/editing/ApplyBlockElementCommand.cpp
+++ b/Source/core/editing/ApplyBlockElementCommand.cpp
@@ -29,6 +29,7 @@
 
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionState.h"
+#include "core/dom/NodeRenderStyle.h"
 #include "core/dom/Text.h"
 #include "core/editing/VisiblePosition.h"
 #include "core/editing/VisibleUnits.h"
@@ -41,14 +42,14 @@
 
 using namespace HTMLNames;
 
-ApplyBlockElementCommand::ApplyBlockElementCommand(Document* document, const QualifiedName& tagName, const AtomicString& inlineStyle)
+ApplyBlockElementCommand::ApplyBlockElementCommand(Document& document, const QualifiedName& tagName, const AtomicString& inlineStyle)
     : CompositeEditCommand(document)
     , m_tagName(tagName)
     , m_inlineStyle(inlineStyle)
 {
 }
 
-ApplyBlockElementCommand::ApplyBlockElementCommand(Document* document, const QualifiedName& tagName)
+ApplyBlockElementCommand::ApplyBlockElementCommand(Document& document, const QualifiedName& tagName)
     : CompositeEditCommand(document)
     , m_tagName(tagName)
 {
@@ -87,7 +88,7 @@
 
     formatSelection(startOfSelection, endOfSelection);
 
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     ASSERT(startScope == endScope);
     ASSERT(startIndex >= 0);
@@ -142,11 +143,11 @@
         // indentIntoBlockquote could move more than one paragraph if the paragraph
         // is in a list item or a table. As a result, endAfterSelection could refer to a position
         // no longer in the document.
-        if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().anchorNode()->inDocument())
+        if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument())
             break;
         // Sanity check: Make sure our moveParagraph calls didn't remove endOfNextParagraph.deepEquivalent().deprecatedNode()
         // If somehow we did, return to prevent crashes.
-        if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().anchorNode()->inDocument()) {
+        if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument()) {
             ASSERT_NOT_REACHED();
             return;
         }
@@ -171,12 +172,9 @@
 
 static RenderStyle* renderStyleOfEnclosingTextNode(const Position& position)
 {
-    if (position.anchorType() != Position::PositionIsOffsetInAnchor
-        || !position.containerNode()
-        || !position.containerNode()->isTextNode()
-        || !position.containerNode()->renderer())
+    if (position.anchorType() != Position::PositionIsOffsetInAnchor || !position.containerNode() || !position.containerNode()->isTextNode())
         return 0;
-    return position.containerNode()->renderer()->style();
+    return position.containerNode()->renderStyle();
 }
 
 void ApplyBlockElementCommand::rangeForParagraphSplittingTextNodesIfNeeded(const VisiblePosition& endOfCurrentParagraph, Position& start, Position& end)
@@ -184,6 +182,8 @@
     start = startOfParagraph(endOfCurrentParagraph).deepEquivalent();
     end = endOfCurrentParagraph.deepEquivalent();
 
+    document().updateStyleIfNeeded();
+
     bool isStartAndEndOnSameNode = false;
     if (RenderStyle* startStyle = renderStyleOfEnclosingTextNode(start)) {
         isStartAndEndOnSameNode = renderStyleOfEnclosingTextNode(end) && start.containerNode() == end.containerNode();
@@ -210,6 +210,8 @@
         }
     }
 
+    document().updateStyleIfNeeded();
+
     if (RenderStyle* endStyle = renderStyleOfEnclosingTextNode(end)) {
         bool isEndAndEndOfLastParagraphOnSameNode = renderStyleOfEnclosingTextNode(m_endOfLastParagraph) && end.deprecatedNode() == m_endOfLastParagraph.deprecatedNode();
         // Include \n at the end of line if we're at an empty paragraph
diff --git a/Source/core/editing/ApplyBlockElementCommand.h b/Source/core/editing/ApplyBlockElementCommand.h
index d1fe619..72fdc91 100644
--- a/Source/core/editing/ApplyBlockElementCommand.h
+++ b/Source/core/editing/ApplyBlockElementCommand.h
@@ -38,8 +38,8 @@
 
 class ApplyBlockElementCommand : public CompositeEditCommand {
 protected:
-    ApplyBlockElementCommand(Document*, const QualifiedName& tagName, const AtomicString& inlineStyle);
-    ApplyBlockElementCommand(Document*, const QualifiedName& tagName);
+    ApplyBlockElementCommand(Document&, const QualifiedName& tagName, const AtomicString& inlineStyle);
+    ApplyBlockElementCommand(Document&, const QualifiedName& tagName);
 
     virtual void formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection);
     PassRefPtr<Element> createBlockElement() const;
diff --git a/Source/core/editing/ApplyStyleCommand.cpp b/Source/core/editing/ApplyStyleCommand.cpp
index 6ea072b..43cc1dd 100644
--- a/Source/core/editing/ApplyStyleCommand.cpp
+++ b/Source/core/editing/ApplyStyleCommand.cpp
@@ -104,19 +104,19 @@
     return hasNoAttributeOrOnlyStyleAttribute(toHTMLElement(element), shouldStyleAttributeBeEmpty);
 }
 
-static PassRefPtr<Element> createFontElement(Document* document)
+static PassRefPtr<Element> createFontElement(Document& document)
 {
     RefPtr<Element> fontNode = createHTMLElement(document, fontTag);
     return fontNode.release();
 }
 
-PassRefPtr<HTMLElement> createStyleSpanElement(Document* document)
+PassRefPtr<HTMLElement> createStyleSpanElement(Document& document)
 {
     RefPtr<HTMLElement> styleElement = createHTMLElement(document, spanTag);
     return styleElement.release();
 }
 
-ApplyStyleCommand::ApplyStyleCommand(Document* document, const EditingStyle* style, EditAction editingAction, EPropertyLevel propertyLevel)
+ApplyStyleCommand::ApplyStyleCommand(Document& document, const EditingStyle* style, EditAction editingAction, EPropertyLevel propertyLevel)
     : CompositeEditCommand(document)
     , m_style(style->copy())
     , m_editingAction(editingAction)
@@ -130,7 +130,7 @@
 {
 }
 
-ApplyStyleCommand::ApplyStyleCommand(Document* document, const EditingStyle* style, const Position& start, const Position& end, EditAction editingAction, EPropertyLevel propertyLevel)
+ApplyStyleCommand::ApplyStyleCommand(Document& document, const EditingStyle* style, const Position& start, const Position& end, EditAction editingAction, EPropertyLevel propertyLevel)
     : CompositeEditCommand(document)
     , m_style(style->copy())
     , m_editingAction(editingAction)
@@ -158,7 +158,7 @@
 {
 }
 
-ApplyStyleCommand::ApplyStyleCommand(Document* document, const EditingStyle* style, IsInlineElementToRemoveFunction isInlineElementToRemoveFunction, EditAction editingAction)
+ApplyStyleCommand::ApplyStyleCommand(Document& document, const EditingStyle* style, IsInlineElementToRemoveFunction isInlineElementToRemoveFunction, EditAction editingAction)
     : CompositeEditCommand(document)
     , m_style(style->copy())
     , m_editingAction(editingAction)
@@ -232,7 +232,7 @@
     // update document layout once before removing styles
     // so that we avoid the expense of updating before each and every call
     // to check a computed style
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     // get positions we want to use for applying style
     Position start = startPosition();
@@ -252,7 +252,7 @@
     // Save and restore the selection endpoints using their indices in the document, since
     // addBlockStyleIfNeeded may moveParagraphs, which can remove these endpoints.
     // Calculate start and end indices from the start of the tree that they're in.
-    Node* scope = highestAncestor(visibleStart.deepEquivalent().deprecatedNode());
+    Node* scope = visibleStart.deepEquivalent().deprecatedNode()->highestAncestor();
     RefPtr<Range> startRange = Range::create(document(), firstPositionInNode(scope), visibleStart.deepEquivalent().parentAnchoredEquivalent());
     RefPtr<Range> endRange = Range::create(document(), firstPositionInNode(scope), visibleEnd.deepEquivalent().parentAnchoredEquivalent());
     int startIndex = TextIterator::rangeLength(startRange.get(), true);
@@ -543,7 +543,7 @@
     // update document layout once before removing styles
     // so that we avoid the expense of updating before each and every call
     // to check a computed style
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     // adjust to the positions we want to use for applying style
     Position start = startPosition();
@@ -637,7 +637,7 @@
     // update document layout once before running the rest of the function
     // so that we avoid the expense of updating before each and every call
     // to check a computed style
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     RefPtr<EditingStyle> styleToApply = style;
     if (hasTextDirection) {
@@ -741,7 +741,7 @@
     if (m_removeOnly)
         return;
 
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     Vector<InlineRunToApplyStyle> runs;
     RefPtr<Node> node = startNode;
@@ -801,7 +801,7 @@
         runs[i].positionForStyleComputation = positionToComputeInlineStyleChange(runs[i].start, runs[i].dummyElement);
     }
 
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     for (size_t i = 0; i < runs.size(); i++)
         runs[i].change = StyleChange(style, runs[i].positionForStyleComputation);
@@ -985,7 +985,7 @@
 {
     ASSERT(node);
 
-    node->document()->updateStyleIfNeeded();
+    node->document().updateStyleIfNeeded();
 
     if (!style || style->isEmpty() || !node->renderer())
         return;
@@ -998,7 +998,7 @@
 
     // Since addInlineStyleIfNeeded can't add styles to block-flow render objects, add style attribute instead.
     // FIXME: applyInlineStyleToRange should be used here instead.
-    if ((node->renderer()->isBlockFlow() || node->childNodeCount()) && node->isHTMLElement()) {
+    if ((node->renderer()->isRenderBlockFlow() || node->childNodeCount()) && node->isHTMLElement()) {
         setNodeAttribute(toHTMLElement(node), styleAttr, newInlineStyle->style()->asText());
         return;
     }
@@ -1067,8 +1067,8 @@
 {
     ASSERT(start.isNotNull());
     ASSERT(end.isNotNull());
-    ASSERT(start.anchorNode()->inDocument());
-    ASSERT(end.anchorNode()->inDocument());
+    ASSERT(start.inDocument());
+    ASSERT(end.inDocument());
     ASSERT(comparePositions(start, end) <= 0);
     // FIXME: We should assert that start/end are not in the middle of a text node.
 
@@ -1154,7 +1154,7 @@
     ASSERT(node->isElementNode());
 
     // The tree may have changed and Position::upstream() relies on an up-to-date layout.
-    node->document()->updateLayoutIgnorePendingStylesheets();
+    node->document().updateLayoutIgnorePendingStylesheets();
 
     return comparePositions(firstPositionInOrBeforeNode(node), start) >= 0
         && comparePositions(lastPositionInOrAfterNode(node).upstream(), end) <= 0;
diff --git a/Source/core/editing/ApplyStyleCommand.h b/Source/core/editing/ApplyStyleCommand.h
index 99d3490..363e09e 100644
--- a/Source/core/editing/ApplyStyleCommand.h
+++ b/Source/core/editing/ApplyStyleCommand.h
@@ -48,11 +48,11 @@
     enum EAddStyledElement { AddStyledElement, DoNotAddStyledElement };
     typedef bool (*IsInlineElementToRemoveFunction)(const Element*);
 
-    static PassRefPtr<ApplyStyleCommand> create(Document* document, const EditingStyle* style, EditAction action = EditActionChangeAttributes, EPropertyLevel level = PropertyDefault)
+    static PassRefPtr<ApplyStyleCommand> create(Document& document, const EditingStyle* style, EditAction action = EditActionChangeAttributes, EPropertyLevel level = PropertyDefault)
     {
         return adoptRef(new ApplyStyleCommand(document, style, action, level));
     }
-    static PassRefPtr<ApplyStyleCommand> create(Document* document, const EditingStyle* style, const Position& start, const Position& end, EditAction action = EditActionChangeAttributes, EPropertyLevel level = PropertyDefault)
+    static PassRefPtr<ApplyStyleCommand> create(Document& document, const EditingStyle* style, const Position& start, const Position& end, EditAction action = EditActionChangeAttributes, EPropertyLevel level = PropertyDefault)
     {
         return adoptRef(new ApplyStyleCommand(document, style, start, end, action, level));
     }
@@ -60,16 +60,16 @@
     {
         return adoptRef(new ApplyStyleCommand(element, removeOnly, action));
     }
-    static PassRefPtr<ApplyStyleCommand> create(Document* document, const EditingStyle* style, IsInlineElementToRemoveFunction isInlineElementToRemoveFunction, EditAction action = EditActionChangeAttributes)
+    static PassRefPtr<ApplyStyleCommand> create(Document& document, const EditingStyle* style, IsInlineElementToRemoveFunction isInlineElementToRemoveFunction, EditAction action = EditActionChangeAttributes)
     {
         return adoptRef(new ApplyStyleCommand(document, style, isInlineElementToRemoveFunction, action));
     }
 
 private:
-    ApplyStyleCommand(Document*, const EditingStyle*, EditAction, EPropertyLevel);
-    ApplyStyleCommand(Document*, const EditingStyle*, const Position& start, const Position& end, EditAction, EPropertyLevel);
+    ApplyStyleCommand(Document&, const EditingStyle*, EditAction, EPropertyLevel);
+    ApplyStyleCommand(Document&, const EditingStyle*, const Position& start, const Position& end, EditAction, EPropertyLevel);
     ApplyStyleCommand(PassRefPtr<Element>, bool removeOnly, EditAction);
-    ApplyStyleCommand(Document*, const EditingStyle*, bool (*isInlineElementToRemove)(const Element*), EditAction);
+    ApplyStyleCommand(Document&, const EditingStyle*, bool (*isInlineElementToRemove)(const Element*), EditAction);
 
     virtual void doApply();
     virtual EditAction editingAction() const;
@@ -136,7 +136,7 @@
 bool isEmptyFontTag(const Element*, ShouldStyleAttributeBeEmpty = StyleAttributeShouldBeEmpty);
 bool isLegacyAppleStyleSpan(const Node*);
 bool isStyleSpanOrSpanWithOnlyStyleAttribute(const Element*);
-PassRefPtr<HTMLElement> createStyleSpanElement(Document*);
+PassRefPtr<HTMLElement> createStyleSpanElement(Document&);
 
 } // namespace WebCore
 
diff --git a/Source/core/editing/BreakBlockquoteCommand.cpp b/Source/core/editing/BreakBlockquoteCommand.cpp
index f8c53f9..9064923 100644
--- a/Source/core/editing/BreakBlockquoteCommand.cpp
+++ b/Source/core/editing/BreakBlockquoteCommand.cpp
@@ -38,7 +38,7 @@
 
 using namespace HTMLNames;
 
-BreakBlockquoteCommand::BreakBlockquoteCommand(Document *document)
+BreakBlockquoteCommand::BreakBlockquoteCommand(Document& document)
     : CompositeEditCommand(document)
 {
 }
diff --git a/Source/core/editing/BreakBlockquoteCommand.h b/Source/core/editing/BreakBlockquoteCommand.h
index 31941d3..359777c 100644
--- a/Source/core/editing/BreakBlockquoteCommand.h
+++ b/Source/core/editing/BreakBlockquoteCommand.h
@@ -32,13 +32,13 @@
 
 class BreakBlockquoteCommand : public CompositeEditCommand {
 public:
-    static PassRefPtr<BreakBlockquoteCommand> create(Document* document)
+    static PassRefPtr<BreakBlockquoteCommand> create(Document& document)
     {
         return adoptRef(new BreakBlockquoteCommand(document));
     }
 
 private:
-    explicit BreakBlockquoteCommand(Document*);
+    explicit BreakBlockquoteCommand(Document&);
     virtual void doApply();
 };
 
diff --git a/Source/core/editing/Caret.cpp b/Source/core/editing/Caret.cpp
index c8b2f60..d1cb061 100644
--- a/Source/core/editing/Caret.cpp
+++ b/Source/core/editing/Caret.cpp
@@ -70,7 +70,7 @@
     Document* document = 0;
     if (Node* node = m_position.deepEquivalent().deprecatedNode()) {
         invalidateCaretRect(node);
-        document = node->document();
+        document = &node->document();
     }
     if (m_position.isNull() || m_position.isOrphan())
         clearCaretRect();
@@ -95,7 +95,7 @@
 
 static void clearRenderViewSelection(const Position& position)
 {
-    RefPtr<Document> document = position.anchorNode()->document();
+    RefPtr<Document> document = position.document();
     document->updateStyleIfNeeded();
     if (RenderView* view = document->renderView())
         view->clearSelection();
@@ -133,7 +133,7 @@
         return 0;
 
     // if caretNode is a block and caret is inside it then caret should be painted by that block
-    bool paintedByBlock = renderer->isBlockFlow() && caretRendersInsideNode(node);
+    bool paintedByBlock = renderer->isRenderBlock() && caretRendersInsideNode(node);
     return paintedByBlock ? renderer : renderer->containingBlock();
 }
 
@@ -209,8 +209,11 @@
 bool CaretBase::shouldRepaintCaret(const RenderView* view, bool isContentEditable) const
 {
     ASSERT(view);
-    Frame* frame = view->frameView() ? view->frameView()->frame() : 0; // The frame where the selection started.
-    bool caretBrowsing = frame && frame->settings() && frame->settings()->caretBrowsingEnabled();
+    bool caretBrowsing = false;
+    if (FrameView* frameView = view->frameView()) {
+        Frame& frame = frameView->frame(); // The frame where the selection started
+        caretBrowsing = frame.settings() && frame.settings()->caretBrowsingEnabled();
+    }
     return (caretBrowsing || isContentEditable);
 }
 
@@ -232,7 +235,7 @@
     if (caretRectChanged)
         return;
 
-    if (RenderView* view = node->document()->renderView()) {
+    if (RenderView* view = node->document().renderView()) {
         if (shouldRepaintCaret(view, node->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable)))
             repaintCaretForLocalRect(node, localCaretRectWithoutUpdate());
     }
@@ -268,7 +271,7 @@
 
 void DragCaretController::paintDragCaret(Frame* frame, GraphicsContext* p, const LayoutPoint& paintOffset, const LayoutRect& clipRect) const
 {
-    if (m_position.deepEquivalent().deprecatedNode()->document()->frame() == frame)
+    if (m_position.deepEquivalent().deprecatedNode()->document().frame() == frame)
         paintCaret(m_position.deepEquivalent().deprecatedNode(), p, paintOffset, clipRect);
 }
 
diff --git a/Source/core/editing/CompositeEditCommand.cpp b/Source/core/editing/CompositeEditCommand.cpp
index d0d2dd3..3da087c 100644
--- a/Source/core/editing/CompositeEditCommand.cpp
+++ b/Source/core/editing/CompositeEditCommand.cpp
@@ -144,21 +144,7 @@
     m_endingRootEditableElement = selection.rootEditableElement();
 }
 
-#ifndef NDEBUG
-void EditCommandComposition::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    size_t size = m_commands.size();
-    for (size_t i = 0; i < size; ++i)
-        m_commands[i]->getNodesInCommand(nodes);
-}
-#endif
-
-void applyCommand(PassRefPtr<CompositeEditCommand> command)
-{
-    command->apply();
-}
-
-CompositeEditCommand::CompositeEditCommand(Document *document)
+CompositeEditCommand::CompositeEditCommand(Document& document)
     : EditCommand(document)
 {
 }
@@ -189,10 +175,9 @@
     // Changes to the document may have been made since the last editing operation that require a layout, as in <rdar://problem/5658603>.
     // Low level operations, like RemoveNodeCommand, don't require a layout because the high level operations that use them perform one
     // if one is necessary (like for the creation of VisiblePositions).
-    ASSERT(document());
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     ASSERT(frame);
     {
         EventQueueScope scope;
@@ -212,7 +197,7 @@
     while (command && command->parent())
         command = command->parent();
     if (!command->m_composition)
-        command->m_composition = EditCommandComposition::create(document(), startingSelection(), endingSelection(), editingAction());
+        command->m_composition = EditCommandComposition::create(&document(), startingSelection(), endingSelection(), editingAction());
     return command->m_composition.get();
 }
 
@@ -518,11 +503,11 @@
 void CompositeEditCommand::replaceTextInNodePreservingMarkers(PassRefPtr<Text> prpNode, unsigned offset, unsigned count, const String& replacementText)
 {
     RefPtr<Text> node(prpNode);
-    DocumentMarkerController* markerController = document()->markers();
+    DocumentMarkerController* markerController = document().markers();
     Vector<DocumentMarker> markers;
-    copyMarkers(markerController->markersInRange(Range::create(document(), node, offset, node, offset + count).get(), DocumentMarker::AllMarkers()), markers);
+    copyMarkers(markerController->markersInRange(Range::create(document(), node.get(), offset, node.get(), offset + count).get(), DocumentMarker::AllMarkers()), markers);
     replaceTextInNode(node, offset, count, replacementText);
-    RefPtr<Range> newRange = Range::create(document(), node, offset, node, offset + replacementText.length());
+    RefPtr<Range> newRange = Range::create(document(), node.get(), offset, node.get(), offset + replacementText.length());
     for (size_t i = 0; i < markers.size(); ++i)
         markerController->addMarker(newRange.get(), markers[i].type(), markers[i].description());
 }
@@ -719,7 +704,7 @@
     if (!textNode || start >= end)
         return;
 
-    document()->updateLayout();
+    document().updateLayout();
 
     RenderText* textRenderer = toRenderText(textNode->renderer());
     if (!textRenderer)
@@ -830,9 +815,9 @@
     if (!container)
         return 0;
 
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
-    // Should assert isBlockFlow || isInlineFlow when deletion improves. See 4244964.
+    // Should assert isRenderBlockFlow || isInlineFlow when deletion improves. See 4244964.
     ASSERT(container->renderer());
 
     RefPtr<Node> placeholder = createBlockPlaceholderElement(document());
@@ -845,7 +830,7 @@
     if (pos.isNull())
         return 0;
 
-    // Should assert isBlockFlow || isInlineFlow when deletion improves.  See 4244964.
+    // Should assert isRenderBlockFlow || isInlineFlow when deletion improves. See 4244964.
     ASSERT(pos.deprecatedNode()->renderer());
 
     RefPtr<Node> placeholder = createBlockPlaceholderElement(document());
@@ -858,10 +843,10 @@
     if (!container)
         return 0;
 
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     RenderObject* renderer = container->renderer();
-    if (!renderer || !renderer->isBlockFlow())
+    if (!renderer || !renderer->isRenderBlockFlow())
         return 0;
 
     // append the placeholder to make sure it follows
@@ -902,7 +887,7 @@
     if (pos.isNull())
         return 0;
 
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     // It's strange that this function is responsible for verifying that pos has not been invalidated
     // by an earlier call to this function.  The caller, applyBlockStyle, should do this.
@@ -1196,7 +1181,7 @@
     RefPtr<EditingStyle> styleInEmptyParagraph;
     if (startOfParagraphToMove == endOfParagraphToMove && preserveStyle) {
         styleInEmptyParagraph = EditingStyle::create(startOfParagraphToMove.deepEquivalent());
-        styleInEmptyParagraph->mergeTypingStyle(document());
+        styleInEmptyParagraph->mergeTypingStyle(&document());
         // The moved paragraph should assume the block style of the destination.
         styleInEmptyParagraph->removeBlockProperties();
     }
@@ -1204,12 +1189,12 @@
     // FIXME (5098931): We should add a new insert action "WebViewInsertActionMoved" and call shouldInsertFragment here.
 
     setEndingSelection(VisibleSelection(start, end, DOWNSTREAM));
-    document()->frame()->editor().clearMisspellingsAndBadGrammar(endingSelection());
+    document().frame()->editor().clearMisspellingsAndBadGrammar(endingSelection());
     deleteSelection(false, false, false, false);
 
-    ASSERT(destination.deepEquivalent().anchorNode()->inDocument());
+    ASSERT(destination.deepEquivalent().inDocument());
     cleanupAfterDeletion(destination);
-    ASSERT(destination.deepEquivalent().anchorNode()->inDocument());
+    ASSERT(destination.deepEquivalent().inDocument());
 
     // Add a br if pruning an empty block level element caused a collapse. For example:
     // foo^
@@ -1224,10 +1209,10 @@
         // FIXME: Trim text between beforeParagraph and afterParagraph if they aren't equal.
         insertNodeAt(createBreakElement(document()), beforeParagraph.deepEquivalent());
         // Need an updateLayout here in case inserting the br has split a text node.
-        document()->updateLayoutIgnorePendingStylesheets();
+        document().updateLayoutIgnorePendingStylesheets();
     }
 
-    RefPtr<Range> startToDestinationRange(Range::create(document(), firstPositionInNode(document()->documentElement()), destination.deepEquivalent().parentAnchoredEquivalent()));
+    RefPtr<Range> startToDestinationRange(Range::create(document(), firstPositionInNode(document().documentElement()), destination.deepEquivalent().parentAnchoredEquivalent()));
     destinationIndex = TextIterator::rangeLength(startToDestinationRange.get(), true);
 
     setEndingSelection(VisibleSelection(destination, originalIsDirectional));
@@ -1237,7 +1222,7 @@
         options |= ReplaceSelectionCommand::MatchStyle;
     applyCommandToComposite(ReplaceSelectionCommand::create(document(), fragment, options));
 
-    document()->frame()->editor().markMisspellingsAndBadGrammar(endingSelection());
+    document().frame()->editor().markMisspellingsAndBadGrammar(endingSelection());
 
     // If the selection is in an empty paragraph, restore styles from the old empty paragraph to the new empty paragraph.
     bool selectionIsEmptyParagraph = endingSelection().isCaret() && isStartOfParagraph(endingSelection().visibleStart()) && isEndOfParagraph(endingSelection().visibleStart());
@@ -1250,8 +1235,8 @@
         // causes spaces to be collapsed during the move operation.  This results
         // in a call to rangeFromLocationAndLength with a location past the end
         // of the document (which will return null).
-        RefPtr<Range> start = TextIterator::rangeFromLocationAndLength(document()->documentElement(), destinationIndex + startIndex, 0, true);
-        RefPtr<Range> end = TextIterator::rangeFromLocationAndLength(document()->documentElement(), destinationIndex + endIndex, 0, true);
+        RefPtr<Range> start = TextIterator::rangeFromLocationAndLength(document().documentElement(), destinationIndex + startIndex, 0, true);
+        RefPtr<Range> end = TextIterator::rangeFromLocationAndLength(document().documentElement(), destinationIndex + endIndex, 0, true);
         if (start && end)
             setEndingSelection(VisibleSelection(start->startPosition(), end->startPosition(), DOWNSTREAM, originalIsDirectional));
     }
@@ -1265,7 +1250,7 @@
         return false;
 
     RefPtr<EditingStyle> style = EditingStyle::create(endingSelection().start());
-    style->mergeTypingStyle(document());
+    style->mergeTypingStyle(&document());
 
     RefPtr<ContainerNode> listNode = emptyListItem->parentNode();
     // FIXME: Can't we do something better when the immediate parent wasn't a list node?
@@ -1288,8 +1273,9 @@
                 newBlock = createListItemElement(document());
             }
             // If listNode does NOT appear at the end of the outer list item, then behave as if in a regular paragraph.
-        } else if (blockEnclosingList->hasTagName(olTag) || blockEnclosingList->hasTagName(ulTag))
+        } else if (blockEnclosingList->hasTagName(olTag) || blockEnclosingList->hasTagName(ulTag)) {
             newBlock = createListItemElement(document());
+        }
     }
     if (!newBlock)
         newBlock = createDefaultParagraphElement(document());
@@ -1464,9 +1450,9 @@
     return node.release();
 }
 
-PassRefPtr<Element> createBlockPlaceholderElement(Document* document)
+PassRefPtr<Element> createBlockPlaceholderElement(Document& document)
 {
-    RefPtr<Element> breakNode = document->createElement(brTag, false);
+    RefPtr<Element> breakNode = document.createElement(brTag, false);
     return breakNode.release();
 }
 
diff --git a/Source/core/editing/CompositeEditCommand.h b/Source/core/editing/CompositeEditCommand.h
index d791e53..cef79bb 100644
--- a/Source/core/editing/CompositeEditCommand.h
+++ b/Source/core/editing/CompositeEditCommand.h
@@ -55,10 +55,6 @@
     Element* startingRootEditableElement() const { return m_startingRootEditableElement.get(); }
     Element* endingRootEditableElement() const { return m_endingRootEditableElement.get(); }
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&);
-#endif
-
 private:
     EditCommandComposition(Document*, const VisibleSelection& startingSelection, const VisibleSelection& endingSelection, EditAction);
 
@@ -88,7 +84,7 @@
     virtual bool shouldStopCaretBlinking() const { return false; }
 
 protected:
-    explicit CompositeEditCommand(Document*);
+    explicit CompositeEditCommand(Document&);
 
     //
     // sugary-sweet convenience functions to help create and apply edit commands in composite commands
@@ -175,8 +171,6 @@
     RefPtr<EditCommandComposition> m_composition;
 };
 
-void applyCommand(PassRefPtr<CompositeEditCommand>);
-
 inline CompositeEditCommand* toCompositeEditCommand(EditCommand* command)
 {
     ASSERT(command);
diff --git a/Source/core/editing/CreateLinkCommand.cpp b/Source/core/editing/CreateLinkCommand.cpp
index d21924b..88f969e 100644
--- a/Source/core/editing/CreateLinkCommand.cpp
+++ b/Source/core/editing/CreateLinkCommand.cpp
@@ -31,7 +31,7 @@
 
 namespace WebCore {
 
-CreateLinkCommand::CreateLinkCommand(Document* document, const String& url)
+CreateLinkCommand::CreateLinkCommand(Document& document, const String& url)
     : CompositeEditCommand(document)
 {
     m_url = url;
diff --git a/Source/core/editing/CreateLinkCommand.h b/Source/core/editing/CreateLinkCommand.h
index cfe9c99..af489fe 100644
--- a/Source/core/editing/CreateLinkCommand.h
+++ b/Source/core/editing/CreateLinkCommand.h
@@ -32,7 +32,7 @@
 
 class CreateLinkCommand : public CompositeEditCommand {
 public:
-    static PassRefPtr<CreateLinkCommand> create(Document* document, const String& linkURL)
+    static PassRefPtr<CreateLinkCommand> create(Document& document, const String& linkURL)
     {
         return adoptRef(new CreateLinkCommand(document, linkURL));
     }
@@ -40,7 +40,7 @@
     bool isCreateLinkCommand() const { return true; }
 
 private:
-    CreateLinkCommand(Document*, const String& linkURL);
+    CreateLinkCommand(Document&, const String& linkURL);
 
     virtual void doApply();
     virtual EditAction editingAction() const { return EditActionCreateLink; }
diff --git a/Source/core/editing/DeleteFromTextNodeCommand.cpp b/Source/core/editing/DeleteFromTextNodeCommand.cpp
index 03fb87e0..2ca40f0 100644
--- a/Source/core/editing/DeleteFromTextNodeCommand.cpp
+++ b/Source/core/editing/DeleteFromTextNodeCommand.cpp
@@ -56,7 +56,7 @@
     if (es.hadException())
         return;
 
-    m_node->deleteData(m_offset, m_count, es, DeprecatedAttachNow);
+    m_node->deleteData(m_offset, m_count, es, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
 }
 
 void DeleteFromTextNodeCommand::doUnapply()
@@ -66,14 +66,7 @@
     if (!m_node->rendererIsEditable())
         return;
 
-    m_node->insertData(m_offset, m_text, IGNORE_EXCEPTION, DeprecatedAttachNow);
+    m_node->insertData(m_offset, m_text, IGNORE_EXCEPTION, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
 }
 
-#ifndef NDEBUG
-void DeleteFromTextNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_node.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/DeleteFromTextNodeCommand.h b/Source/core/editing/DeleteFromTextNodeCommand.h
index 688c117..192e8a9 100644
--- a/Source/core/editing/DeleteFromTextNodeCommand.h
+++ b/Source/core/editing/DeleteFromTextNodeCommand.h
@@ -45,10 +45,6 @@
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Text> m_node;
     unsigned m_offset;
     unsigned m_count;
diff --git a/Source/core/editing/DeleteSelectionCommand.cpp b/Source/core/editing/DeleteSelectionCommand.cpp
index cf7b3be..164437e 100644
--- a/Source/core/editing/DeleteSelectionCommand.cpp
+++ b/Source/core/editing/DeleteSelectionCommand.cpp
@@ -67,7 +67,7 @@
     return true;
 }
 
-DeleteSelectionCommand::DeleteSelectionCommand(Document *document, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
+DeleteSelectionCommand::DeleteSelectionCommand(Document& document, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
     : CompositeEditCommand(document)
     , m_hasSelectionToDelete(false)
     , m_smartDelete(smartDelete)
@@ -86,7 +86,7 @@
 }
 
 DeleteSelectionCommand::DeleteSelectionCommand(const VisibleSelection& selection, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup)
-    : CompositeEditCommand(selection.start().anchorNode()->document())
+    : CompositeEditCommand(*selection.start().document())
     , m_hasSelectionToDelete(true)
     , m_smartDelete(smartDelete)
     , m_mergeBlocksAfterDelete(mergeBlocksAfterDelete)
@@ -379,7 +379,7 @@
         }
 
         // Make sure empty cell has some height, if a placeholder can be inserted.
-        document()->updateLayoutIgnorePendingStylesheets();
+        document().updateLayoutIgnorePendingStylesheets();
         RenderObject *r = node->renderer();
         if (r && r->isTableCell() && toRenderTableCell(r)->contentHeight() <= 0) {
             Position firstEditablePosition = firstEditablePositionInNode(node.get());
@@ -532,7 +532,7 @@
             }
         }
 
-        if (m_downstreamEnd.deprecatedNode() != startNode && !m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode()) && m_downstreamEnd.anchorNode()->inDocument() && m_downstreamEnd.deprecatedEditingOffset() >= caretMinOffset(m_downstreamEnd.deprecatedNode())) {
+        if (m_downstreamEnd.deprecatedNode() != startNode && !m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode()) && m_downstreamEnd.inDocument() && m_downstreamEnd.deprecatedEditingOffset() >= caretMinOffset(m_downstreamEnd.deprecatedNode())) {
             if (m_downstreamEnd.atLastEditingPositionForNode() && !canHaveChildrenForEditing(m_downstreamEnd.deprecatedNode())) {
                 // The node itself is fully selected, not just its contents.  Delete it.
                 removeNode(m_downstreamEnd.deprecatedNode());
@@ -549,7 +549,7 @@
                 // know how many children to remove.
                 // FIXME: Make m_upstreamStart a position we update as we remove content, then we can
                 // always know which children to remove.
-                } else if (!(startNodeWasDescendantOfEndNode && !m_upstreamStart.anchorNode()->inDocument())) {
+                } else if (!(startNodeWasDescendantOfEndNode && !m_upstreamStart.inDocument())) {
                     int offset = 0;
                     if (m_upstreamStart.deprecatedNode()->isDescendantOf(m_downstreamEnd.deprecatedNode())) {
                         Node* n = m_upstreamStart.deprecatedNode();
@@ -568,7 +568,7 @@
 
 void DeleteSelectionCommand::fixupWhitespace()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     // FIXME: isRenderedCharacter should be removed, and we should use VisiblePosition::characterAfter and VisiblePosition::characterBefore
     if (m_leadingWhitespace.isNotNull() && !m_leadingWhitespace.isRenderedCharacter() && m_leadingWhitespace.deprecatedNode()->isTextNode()) {
         Text* textNode = toText(m_leadingWhitespace.deprecatedNode());
@@ -601,7 +601,7 @@
     ASSERT(!m_pruneStartBlockIfNecessary);
 
     // FIXME: Deletion should adjust selection endpoints as it removes nodes so that we never get into this state (4099839).
-    if (!m_downstreamEnd.anchorNode()->inDocument() || !m_upstreamStart.anchorNode()->inDocument())
+    if (!m_downstreamEnd.inDocument() || !m_upstreamStart.inDocument())
          return;
 
     // FIXME: The deletion algorithm shouldn't let this happen.
@@ -624,7 +624,7 @@
     }
 
     // We need to merge into m_upstreamStart's block, but it's been emptied out and collapsed by deletion.
-    if (!mergeDestination.deepEquivalent().deprecatedNode() || !mergeDestination.deepEquivalent().deprecatedNode()->isDescendantOf(enclosingBlock(m_upstreamStart.containerNode())) || m_startsAtEmptyLine) {
+    if (!mergeDestination.deepEquivalent().deprecatedNode() || (!mergeDestination.deepEquivalent().deprecatedNode()->isDescendantOf(enclosingBlock(m_upstreamStart.containerNode())) && (!mergeDestination.deepEquivalent().anchorNode()->firstChild() || !m_upstreamStart.containerNode()->firstChild())) || (m_startsAtEmptyLine && mergeDestination != startOfParagraphToMove)) {
         insertNodeAt(createBreakElement(document()).get(), m_upstreamStart);
         mergeDestination = VisiblePosition(m_upstreamStart);
     }
@@ -725,7 +725,7 @@
     // In this case if we start typing, the new characters should have the same style as the just deleted ones,
     // but, if we change the selection, come back and start typing that style should be lost.  Also see
     // preserveTypingStyle() below.
-    document()->frame()->selection()->setTypingStyle(m_typingStyle);
+    document().frame()->selection().setTypingStyle(m_typingStyle);
 }
 
 void DeleteSelectionCommand::clearTransientState()
@@ -774,10 +774,11 @@
     Position downstreamEnd = m_selectionToDelete.end().downstream();
     bool rootWillStayOpenWithoutPlaceholder = downstreamEnd.containerNode() == downstreamEnd.containerNode()->rootEditableElement()
         || (downstreamEnd.containerNode()->isTextNode() && downstreamEnd.containerNode()->parentNode() == downstreamEnd.containerNode()->rootEditableElement());
+    bool lineBreakAtEndOfSelectionToDelete = lineBreakExistsAtVisiblePosition(m_selectionToDelete.visibleEnd());
     m_needPlaceholder = !rootWillStayOpenWithoutPlaceholder
         && isStartOfParagraph(m_selectionToDelete.visibleStart(), CanCrossEditingBoundary)
         && isEndOfParagraph(m_selectionToDelete.visibleEnd(), CanCrossEditingBoundary)
-        && !lineBreakExistsAtVisiblePosition(m_selectionToDelete.visibleEnd());
+        && !lineBreakAtEndOfSelectionToDelete;
     if (m_needPlaceholder) {
         // Don't need a placeholder when deleting a selection that starts just before a table
         // and ends inside it (we do need placeholders to hold open empty cells, but that's
@@ -791,6 +792,8 @@
     // set up our state
     initializePositionData();
 
+    bool lineBreakBeforeStart = lineBreakExistsAtVisiblePosition(VisiblePosition(m_upstreamStart).previous());
+
     // Delete any text that may hinder our ability to fixup whitespace after the delete
     deleteInsignificantTextDownstream(m_trailingWhitespace);
 
@@ -816,10 +819,9 @@
 
     if (!m_needPlaceholder && rootWillStayOpenWithoutPlaceholder) {
         VisiblePosition visualEnding(m_endingPosition);
-        m_needPlaceholder = !isStartOfParagraph(visualEnding, CanCrossEditingBoundary)
-            && isEndOfParagraph(visualEnding, CanCrossEditingBoundary)
-            && lineBreakExistsAtVisiblePosition(visualEnding)
+        bool hasPlaceholder = lineBreakExistsAtVisiblePosition(visualEnding)
             && visualEnding.next(CannotCrossEditingBoundary).isNull();
+        m_needPlaceholder = hasPlaceholder && lineBreakBeforeStart && !lineBreakAtEndOfSelectionToDelete;
     }
 
     RefPtr<Node> placeholder = m_needPlaceholder ? createBreakElement(document()).get() : 0;
diff --git a/Source/core/editing/DeleteSelectionCommand.h b/Source/core/editing/DeleteSelectionCommand.h
index 22a5410..8234bb3 100644
--- a/Source/core/editing/DeleteSelectionCommand.h
+++ b/Source/core/editing/DeleteSelectionCommand.h
@@ -34,7 +34,7 @@
 
 class DeleteSelectionCommand : public CompositeEditCommand {
 public:
-    static PassRefPtr<DeleteSelectionCommand> create(Document* document, bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool replace = false, bool expandForSpecialElements = false, bool sanitizeMarkup = true)
+    static PassRefPtr<DeleteSelectionCommand> create(Document& document, bool smartDelete = false, bool mergeBlocksAfterDelete = true, bool replace = false, bool expandForSpecialElements = false, bool sanitizeMarkup = true)
     {
         return adoptRef(new DeleteSelectionCommand(document, smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements, sanitizeMarkup));
     }
@@ -44,7 +44,7 @@
     }
 
 private:
-    DeleteSelectionCommand(Document*, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool santizeMarkup);
+    DeleteSelectionCommand(Document&, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool santizeMarkup);
     DeleteSelectionCommand(const VisibleSelection&, bool smartDelete, bool mergeBlocksAfterDelete, bool replace, bool expandForSpecialElements, bool sanitizeMarkup);
 
     virtual void doApply();
diff --git a/Source/core/editing/EditCommand.cpp b/Source/core/editing/EditCommand.cpp
index 6105101..7fdf04e 100644
--- a/Source/core/editing/EditCommand.cpp
+++ b/Source/core/editing/EditCommand.cpp
@@ -34,13 +34,13 @@
 
 namespace WebCore {
 
-EditCommand::EditCommand(Document* document)
-    : m_document(document)
+EditCommand::EditCommand(Document& document)
+    : m_document(&document)
     , m_parent(0)
 {
     ASSERT(m_document);
     ASSERT(m_document->frame());
-    setStartingSelection(m_document->frame()->selection()->selection());
+    setStartingSelection(m_document->frame()->selection().selection());
     setEndingSelection(m_startingSelection);
 }
 
@@ -110,12 +110,4 @@
     doApply();
 }
 
-#ifndef NDEBUG
-void SimpleEditCommand::addNodeAndDescendants(Node* startNode, HashSet<Node*>& nodes)
-{
-    for (Node* node = startNode; node; node = NodeTraversal::next(node, startNode))
-        nodes.add(node);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/EditCommand.h b/Source/core/editing/EditCommand.h
index 99b5367..41d3edf 100644
--- a/Source/core/editing/EditCommand.h
+++ b/Source/core/editing/EditCommand.h
@@ -58,10 +58,10 @@
     virtual void doApply() = 0;
 
 protected:
-    explicit EditCommand(Document*);
+    explicit EditCommand(Document&);
     EditCommand(Document*, const VisibleSelection&, const VisibleSelection&);
 
-    Document* document() const { return m_document.get(); }
+    Document& document() const { return *m_document.get(); }
     CompositeEditCommand* parent() const { return m_parent; }
     void setStartingSelection(const VisibleSelection&);
     void setEndingSelection(const VisibleSelection&);
@@ -83,16 +83,8 @@
     virtual void doUnapply() = 0;
     virtual void doReapply(); // calls doApply()
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) = 0;
-#endif
-
 protected:
-    explicit SimpleEditCommand(Document* document) : EditCommand(document) { }
-
-#ifndef NDEBUG
-    void addNodeAndDescendants(Node*, HashSet<Node*>&);
-#endif
+    explicit SimpleEditCommand(Document& document) : EditCommand(document) { }
 
 private:
     virtual bool isSimpleEditCommand() const OVERRIDE { return true; }
diff --git a/Source/core/editing/EditingStyle.cpp b/Source/core/editing/EditingStyle.cpp
index bb9144e..a06a083 100644
--- a/Source/core/editing/EditingStyle.cpp
+++ b/Source/core/editing/EditingStyle.cpp
@@ -984,7 +984,7 @@
 {
     ASSERT(document);
 
-    RefPtr<EditingStyle> typingStyle = document->frame()->selection()->typingStyle();
+    RefPtr<EditingStyle> typingStyle = document->frame()->selection().typingStyle();
     if (!typingStyle || typingStyle == this)
         return;
 
@@ -1133,7 +1133,7 @@
 static PassRefPtr<MutableStylePropertySet> styleFromMatchedRulesForElement(Element* element, unsigned rulesToInclude)
 {
     RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
-    RefPtr<CSSRuleList> matchedRules = element->document()->styleResolver()->styleRulesForElement(element, rulesToInclude);
+    RefPtr<CSSRuleList> matchedRules = element->document().styleResolver()->styleRulesForElement(element, rulesToInclude);
     if (matchedRules) {
         for (unsigned i = 0; i < matchedRules->length(); i++) {
             if (matchedRules->item(i)->type() == CSSRule::STYLE_RULE)
@@ -1270,7 +1270,7 @@
         return 0;
 
     RefPtr<EditingStyle> style = EditingStyle::create(element, EditingStyle::AllProperties);
-    style->mergeTypingStyle(element->document());
+    style->mergeTypingStyle(&element->document());
 
     // If background color is transparent, traverse parent nodes until we hit a different value or document root
     // Also, if the selection is a range, ignore the background color at the start of selection,
@@ -1301,7 +1301,8 @@
     if (selection.isRange()) {
         end = selection.end().upstream();
 
-        Node* pastLast = Range::create(end.document(), position.parentAnchoredEquivalent(), end.parentAnchoredEquivalent())->pastLastNode();
+        ASSERT(end.document());
+        Node* pastLast = Range::create(*end.document(), position.parentAnchoredEquivalent(), end.parentAnchoredEquivalent())->pastLastNode();
         for (Node* n = node; n && n != pastLast; n = NodeTraversal::next(n)) {
             if (!n->isStyledElement())
                 continue;
@@ -1394,7 +1395,7 @@
     , m_applySubscript(false)
     , m_applySuperscript(false)
 {
-    Document* document = position.anchorNode() ? position.anchorNode()->document() : 0;
+    Document* document = position.document();
     if (!style || !style->style() || !document || !document->frame())
         return;
 
diff --git a/Source/core/editing/Editor.cpp b/Source/core/editing/Editor.cpp
index b487c8d..8b8c495 100644
--- a/Source/core/editing/Editor.cpp
+++ b/Source/core/editing/Editor.cpp
@@ -75,6 +75,7 @@
 #include "core/platform/KillRing.h"
 #include "core/platform/Pasteboard.h"
 #include "core/platform/Sound.h"
+#include "core/platform/chromium/ClipboardChromium.h"
 #include "core/platform/text/TextCheckerClient.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderBlock.h"
@@ -99,7 +100,7 @@
     ASSERT(m_editor->m_preventRevealSelection);
     --m_editor->m_preventRevealSelection;
     if (!m_editor->m_preventRevealSelection)
-        m_editor->m_frame->selection()->revealSelection(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
+        m_editor->m_frame->selection().revealSelection(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
 }
 
 namespace {
@@ -116,7 +117,7 @@
 // we should use the target control's selection for this editing operation.
 VisibleSelection Editor::selectionForCommand(Event* event)
 {
-    VisibleSelection selection = m_frame->selection()->selection();
+    VisibleSelection selection = m_frame->selection().selection();
     if (!event)
         return selection;
     // If the target is a text control, and the current selection is outside of its shadow tree,
@@ -189,12 +190,12 @@
 
 bool Editor::canEdit() const
 {
-    return m_frame->selection()->rootEditableElement();
+    return m_frame->selection().rootEditableElement();
 }
 
 bool Editor::canEditRichly() const
 {
-    return m_frame->selection()->isContentRichlyEditable();
+    return m_frame->selection().isContentRichlyEditable();
 }
 
 // WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items.  They
@@ -204,12 +205,12 @@
 
 bool Editor::canDHTMLCut()
 {
-    return !m_frame->selection()->isInPasswordField() && !dispatchCPPEvent(eventNames().beforecutEvent, ClipboardNumb);
+    return !m_frame->selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecutEvent, ClipboardNumb);
 }
 
 bool Editor::canDHTMLCopy()
 {
-    return !m_frame->selection()->isInPasswordField() && !dispatchCPPEvent(eventNames().beforecopyEvent, ClipboardNumb);
+    return !m_frame->selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecopyEvent, ClipboardNumb);
 }
 
 bool Editor::canDHTMLPaste()
@@ -245,8 +246,8 @@
 {
     if (imageElementFromImageDocument(m_frame->document()))
         return true;
-    FrameSelection* selection = m_frame->selection();
-    return selection->isRange() && !selection->isInPasswordField();
+    FrameSelection& selection = m_frame->selection();
+    return selection.isRange() && !selection.isInPasswordField();
 }
 
 bool Editor::canPaste() const
@@ -256,8 +257,8 @@
 
 bool Editor::canDelete() const
 {
-    FrameSelection* selection = m_frame->selection();
-    return selection->isRange() && selection->rootEditableElement();
+    FrameSelection& selection = m_frame->selection();
+    return selection.isRange() && selection.rootEditableElement();
 }
 
 bool Editor::canDeleteRange(Range* range) const
@@ -287,7 +288,7 @@
 
 bool Editor::canSmartCopyOrDelete()
 {
-    return client().smartInsertDeleteEnabled() && m_frame->selection()->granularity() == WordGranularity;
+    return client().smartInsertDeleteEnabled() && m_frame->selection().granularity() == WordGranularity;
 }
 
 bool Editor::isSelectTrailingWhitespaceEnabled()
@@ -300,9 +301,10 @@
     if (!canEdit())
         return false;
 
-    if (m_frame->selection()->isRange()) {
+    if (m_frame->selection().isRange()) {
         if (isTypingAction) {
-            TypingCommand::deleteKeyPressed(m_frame->document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
+            ASSERT(m_frame->document());
+            TypingCommand::deleteKeyPressed(*m_frame->document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
             revealSelectionAfterEditingOperation();
         } else {
             if (killRing)
@@ -319,11 +321,13 @@
         switch (direction) {
         case DirectionForward:
         case DirectionRight:
-            TypingCommand::forwardDeleteKeyPressed(m_frame->document(), options, granularity);
+            ASSERT(m_frame->document());
+            TypingCommand::forwardDeleteKeyPressed(*m_frame->document(), options, granularity);
             break;
         case DirectionBackward:
         case DirectionLeft:
-            TypingCommand::deleteKeyPressed(m_frame->document(), options, granularity);
+            ASSERT(m_frame->document());
+            TypingCommand::deleteKeyPressed(*m_frame->document(), options, granularity);
             break;
         }
         revealSelectionAfterEditingOperation();
@@ -340,10 +344,11 @@
 
 void Editor::deleteSelectionWithSmartDelete(bool smartDelete)
 {
-    if (m_frame->selection()->isNone())
+    if (m_frame->selection().isNone())
         return;
 
-    applyCommand(DeleteSelectionCommand::create(m_frame->document(), smartDelete));
+    ASSERT(m_frame->document());
+    DeleteSelectionCommand::create(*m_frame->document(), smartDelete)->apply();
 }
 
 void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
@@ -393,7 +398,7 @@
     if (fragment) {
         Node* child = fragment->firstChild();
         if (child && fragment->lastChild() == child && child->isCharacterDataNode())
-            return client().shouldInsertText(static_cast<CharacterData*>(child)->data(), replacingDOMRange.get(), givenAction);
+            return client().shouldInsertText(toCharacterData(child)->data(), replacingDOMRange.get(), givenAction);
     }
 
     return client().shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
@@ -401,7 +406,7 @@
 
 void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle)
 {
-    if (m_frame->selection()->isNone() || !m_frame->selection()->isContentEditable() || !fragment)
+    if (m_frame->selection().isNone() || !m_frame->selection().isContentEditable() || !fragment)
         return;
 
     ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::PreventNesting | ReplaceSelectionCommand::SanitizeFragment;
@@ -411,16 +416,17 @@
         options |= ReplaceSelectionCommand::SmartReplace;
     if (matchStyle)
         options |= ReplaceSelectionCommand::MatchStyle;
-    applyCommand(ReplaceSelectionCommand::create(m_frame->document(), fragment, options, EditActionPaste));
+    ASSERT(m_frame->document());
+    ReplaceSelectionCommand::create(*m_frame->document(), fragment, options, EditActionPaste)->apply();
     revealSelectionAfterEditingOperation();
 
-    if (m_frame->selection()->isInPasswordField() || !isContinuousSpellCheckingEnabled())
+    if (m_frame->selection().isInPasswordField() || !isContinuousSpellCheckingEnabled())
         return;
-    Node* nodeToCheck = m_frame->selection()->rootEditableElement();
+    Node* nodeToCheck = m_frame->selection().rootEditableElement();
     if (!nodeToCheck)
         return;
 
-    RefPtr<Range> rangeToCheck = Range::create(m_frame->document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
+    RefPtr<Range> rangeToCheck = Range::create(*m_frame->document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
     m_spellCheckRequester->requestCheckingFor(SpellCheckRequest::create(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
 }
 
@@ -433,7 +439,7 @@
 {
     if (!m_frame)
         return 0;
-    return m_frame->selection()->toNormalizedRange();
+    return m_frame->selection().toNormalizedRange();
 }
 
 bool Editor::shouldDeleteRange(Range* range) const
@@ -449,7 +455,7 @@
 
 bool Editor::tryDHTMLCopy()
 {
-    if (m_frame->selection()->isInPasswordField())
+    if (m_frame->selection().isInPasswordField())
         return false;
 
     return !dispatchCPPEvent(eventNames().copyEvent, ClipboardWritable);
@@ -457,7 +463,7 @@
 
 bool Editor::tryDHTMLCut()
 {
-    if (m_frame->selection()->isInPasswordField())
+    if (m_frame->selection().isInPasswordField())
         return false;
 
     return !dispatchCPPEvent(eventNames().cutEvent, ClipboardWritable);
@@ -493,12 +499,12 @@
 
 TriState Editor::selectionUnorderedListState() const
 {
-    if (m_frame->selection()->isCaret()) {
-        if (enclosingNodeWithTag(m_frame->selection()->selection().start(), ulTag))
+    if (m_frame->selection().isCaret()) {
+        if (enclosingNodeWithTag(m_frame->selection().selection().start(), ulTag))
             return TrueTriState;
-    } else if (m_frame->selection()->isRange()) {
-        Node* startNode = enclosingNodeWithTag(m_frame->selection()->selection().start(), ulTag);
-        Node* endNode = enclosingNodeWithTag(m_frame->selection()->selection().end(), ulTag);
+    } else if (m_frame->selection().isRange()) {
+        Node* startNode = enclosingNodeWithTag(m_frame->selection().selection().start(), ulTag);
+        Node* endNode = enclosingNodeWithTag(m_frame->selection().selection().end(), ulTag);
         if (startNode && endNode && startNode == endNode)
             return TrueTriState;
     }
@@ -508,12 +514,12 @@
 
 TriState Editor::selectionOrderedListState() const
 {
-    if (m_frame->selection()->isCaret()) {
-        if (enclosingNodeWithTag(m_frame->selection()->selection().start(), olTag))
+    if (m_frame->selection().isCaret()) {
+        if (enclosingNodeWithTag(m_frame->selection().selection().start(), olTag))
             return TrueTriState;
-    } else if (m_frame->selection()->isRange()) {
-        Node* startNode = enclosingNodeWithTag(m_frame->selection()->selection().start(), olTag);
-        Node* endNode = enclosingNodeWithTag(m_frame->selection()->selection().end(), olTag);
+    } else if (m_frame->selection().isRange()) {
+        Node* startNode = enclosingNodeWithTag(m_frame->selection().selection().start(), olTag);
+        Node* endNode = enclosingNodeWithTag(m_frame->selection().selection().end(), olTag);
         if (startNode && endNode && startNode == endNode)
             return TrueTriState;
     }
@@ -526,7 +532,8 @@
     if (!canEditRichly())
         return 0;
 
-    RefPtr<Node> newList = InsertListCommand::insertList(m_frame->document(), InsertListCommand::OrderedList);
+    ASSERT(m_frame->document());
+    RefPtr<Node> newList = InsertListCommand::insertList(*m_frame->document(), InsertListCommand::OrderedList);
     revealSelectionAfterEditingOperation();
     return newList;
 }
@@ -536,63 +543,71 @@
     if (!canEditRichly())
         return 0;
 
-    RefPtr<Node> newList = InsertListCommand::insertList(m_frame->document(), InsertListCommand::UnorderedList);
+    ASSERT(m_frame->document());
+    RefPtr<Node> newList = InsertListCommand::insertList(*m_frame->document(), InsertListCommand::UnorderedList);
     revealSelectionAfterEditingOperation();
     return newList;
 }
 
 bool Editor::canIncreaseSelectionListLevel()
 {
-    return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(m_frame->document());
+    ASSERT(m_frame->document());
+    return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(*m_frame->document());
 }
 
 bool Editor::canDecreaseSelectionListLevel()
 {
-    return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(m_frame->document());
+    ASSERT(m_frame->document());
+    return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(*m_frame->document());
 }
 
 PassRefPtr<Node> Editor::increaseSelectionListLevel()
 {
-    if (!canEditRichly() || m_frame->selection()->isNone())
+    if (!canEditRichly() || m_frame->selection().isNone())
         return 0;
 
-    RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(m_frame->document());
+    ASSERT(m_frame->document());
+    RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(*m_frame->document());
     revealSelectionAfterEditingOperation();
     return newList;
 }
 
 PassRefPtr<Node> Editor::increaseSelectionListLevelOrdered()
 {
-    if (!canEditRichly() || m_frame->selection()->isNone())
+    if (!canEditRichly() || m_frame->selection().isNone())
         return 0;
 
-    RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(m_frame->document());
+    ASSERT(m_frame->document());
+    RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(*m_frame->document());
     revealSelectionAfterEditingOperation();
     return newList.release();
 }
 
 PassRefPtr<Node> Editor::increaseSelectionListLevelUnordered()
 {
-    if (!canEditRichly() || m_frame->selection()->isNone())
+    if (!canEditRichly() || m_frame->selection().isNone())
         return 0;
 
-    RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(m_frame->document());
+    ASSERT(m_frame->document());
+    RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(*m_frame->document());
     revealSelectionAfterEditingOperation();
     return newList.release();
 }
 
 void Editor::decreaseSelectionListLevel()
 {
-    if (!canEditRichly() || m_frame->selection()->isNone())
+    if (!canEditRichly() || m_frame->selection().isNone())
         return;
 
-    DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(m_frame->document());
+    ASSERT(m_frame->document());
+    DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(*m_frame->document());
     revealSelectionAfterEditingOperation();
 }
 
 void Editor::removeFormattingAndStyle()
 {
-    applyCommand(RemoveFormatCommand::create(m_frame->document()));
+    ASSERT(m_frame->document());
+    RemoveFormatCommand::create(*m_frame->document())->apply();
 }
 
 void Editor::clearLastEditCommand()
@@ -613,8 +628,10 @@
     RefPtr<Event> evt = ClipboardEvent::create(eventType, true, true, clipboard);
     target->dispatchEvent(evt, IGNORE_EXCEPTION);
     bool noDefaultProcessing = evt->defaultPrevented();
-    if (noDefaultProcessing && policy == ClipboardWritable)
-        Pasteboard::generalPasteboard()->writeClipboard(clipboard.get());
+    if (noDefaultProcessing && policy == ClipboardWritable) {
+        RefPtr<ChromiumDataObject> dataObject = static_cast<ClipboardChromium*>(clipboard.get())->dataObject();
+        Pasteboard::generalPasteboard()->writeDataObject(dataObject.release());
+    }
 
     // invalidate clipboard here for security
     clipboard->setAccessPolicy(ClipboardNumb);
@@ -635,12 +652,12 @@
 
 Node* Editor::findEventTargetFromSelection() const
 {
-    return findEventTargetFrom(m_frame->selection()->selection());
+    return findEventTargetFrom(m_frame->selection().selection());
 }
 
 void Editor::applyStyle(StylePropertySet* style, EditAction editingAction)
 {
-    switch (m_frame->selection()->selectionType()) {
+    switch (m_frame->selection().selectionType()) {
     case VisibleSelection::NoSelection:
         // do nothing
         break;
@@ -648,8 +665,10 @@
         computeAndSetTypingStyle(style, editingAction);
         break;
     case VisibleSelection::RangeSelection:
-        if (style)
-            applyCommand(ApplyStyleCommand::create(m_frame->document(), EditingStyle::create(style).get(), editingAction));
+        if (style) {
+            ASSERT(m_frame->document());
+            ApplyStyleCommand::create(*m_frame->document(), EditingStyle::create(style).get(), editingAction)->apply();
+        }
         break;
     }
 }
@@ -661,14 +680,16 @@
 
 void Editor::applyParagraphStyle(StylePropertySet* style, EditAction editingAction)
 {
-    switch (m_frame->selection()->selectionType()) {
+    switch (m_frame->selection().selectionType()) {
     case VisibleSelection::NoSelection:
         // do nothing
         break;
     case VisibleSelection::CaretSelection:
     case VisibleSelection::RangeSelection:
-        if (style)
-            applyCommand(ApplyStyleCommand::create(m_frame->document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties));
+        if (style) {
+            ASSERT(m_frame->document());
+            ApplyStyleCommand::create(*m_frame->document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties)->apply();
+        }
         break;
     }
 }
@@ -678,7 +699,7 @@
     if (!style || style->isEmpty() || !canEditRichly())
         return;
 
-    if (client().shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
+    if (client().shouldApplyStyle(style, m_frame->selection().toNormalizedRange().get()))
         applyStyle(style, editingAction);
 }
 
@@ -687,24 +708,24 @@
     if (!style || style->isEmpty() || !canEditRichly())
         return;
 
-    if (client().shouldApplyStyle(style, m_frame->selection()->toNormalizedRange().get()))
+    if (client().shouldApplyStyle(style, m_frame->selection().toNormalizedRange().get()))
         applyParagraphStyle(style, editingAction);
 }
 
 bool Editor::selectionStartHasStyle(CSSPropertyID propertyID, const String& value) const
 {
     return EditingStyle::create(propertyID, value)->triStateOfStyle(
-        EditingStyle::styleAtSelectionStart(m_frame->selection()->selection(), propertyID == CSSPropertyBackgroundColor).get());
+        EditingStyle::styleAtSelectionStart(m_frame->selection().selection(), propertyID == CSSPropertyBackgroundColor).get());
 }
 
 TriState Editor::selectionHasStyle(CSSPropertyID propertyID, const String& value) const
 {
-    return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame->selection()->selection());
+    return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame->selection().selection());
 }
 
 String Editor::selectionStartCSSPropertyValue(CSSPropertyID propertyID)
 {
-    RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame->selection()->selection(),
+    RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame->selection().selection(),
         propertyID == CSSPropertyBackgroundColor);
     if (!selectionStyle || !selectionStyle->style())
         return String();
@@ -716,12 +737,14 @@
 
 void Editor::indent()
 {
-    applyCommand(IndentOutdentCommand::create(m_frame->document(), IndentOutdentCommand::Indent));
+    ASSERT(m_frame->document());
+    IndentOutdentCommand::create(*m_frame->document(), IndentOutdentCommand::Indent)->apply();
 }
 
 void Editor::outdent()
 {
-    applyCommand(IndentOutdentCommand::create(m_frame->document(), IndentOutdentCommand::Outdent));
+    ASSERT(m_frame->document());
+    IndentOutdentCommand::create(*m_frame->document(), IndentOutdentCommand::Outdent)->apply();
 }
 
 static void dispatchEditableContentChangedEvents(PassRefPtr<Element> startRoot, PassRefPtr<Element> endRoot)
@@ -745,7 +768,7 @@
     dispatchEditableContentChangedEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement());
 
     if (!cmd->preservesTypingStyle())
-        m_frame->selection()->clearTypingStyle();
+        m_frame->selection().clearTypingStyle();
 
     // Command will be equal to last edit command only in the case of typing
     if (m_lastEditCommand.get() == cmd)
@@ -838,18 +861,19 @@
     selection = selectionForCommand(triggeringEvent);
     if (selection.isContentEditable()) {
         if (Node* selectionStart = selection.start().deprecatedNode()) {
-            RefPtr<Document> document = selectionStart->document();
+            RefPtr<Document> document = &selectionStart->document();
+            ASSERT(document);
 
             // Insert the text
             TypingCommand::Options options = 0;
             if (selectInsertedText)
                 options |= TypingCommand::SelectInsertedText;
-            TypingCommand::insertText(document.get(), text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionConfirm : TypingCommand::TextCompositionNone);
+            TypingCommand::insertText(*document.get(), text, selection, options, triggeringEvent && triggeringEvent->isComposition() ? TypingCommand::TextCompositionConfirm : TypingCommand::TextCompositionNone);
 
             // Reveal the current selection
             if (Frame* editedFrame = document->frame()) {
                 if (Page* page = editedFrame->page())
-                    page->focusController().focusedOrMainFrame()->selection()->revealSelection(ScrollAlignment::alignCenterIfNeeded);
+                    page->focusController().focusedOrMainFrame()->selection().revealSelection(ScrollAlignment::alignCenterIfNeeded);
             }
         }
     }
@@ -862,12 +886,13 @@
     if (!canEdit())
         return false;
 
-    if (!shouldInsertText("\n", m_frame->selection()->toNormalizedRange().get(), EditorInsertActionTyped))
+    if (!shouldInsertText("\n", m_frame->selection().toNormalizedRange().get(), EditorInsertActionTyped))
         return true;
 
-    VisiblePosition caret = m_frame->selection()->selection().visibleStart();
+    VisiblePosition caret = m_frame->selection().selection().visibleStart();
     bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
-    TypingCommand::insertLineBreak(m_frame->document(), 0);
+    ASSERT(m_frame->document());
+    TypingCommand::insertLineBreak(*m_frame->document(), 0);
     revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
 
     return true;
@@ -881,12 +906,13 @@
     if (!canEditRichly())
         return insertLineBreak();
 
-    if (!shouldInsertText("\n", m_frame->selection()->toNormalizedRange().get(), EditorInsertActionTyped))
+    if (!shouldInsertText("\n", m_frame->selection().toNormalizedRange().get(), EditorInsertActionTyped))
         return true;
 
-    VisiblePosition caret = m_frame->selection()->selection().visibleStart();
+    VisiblePosition caret = m_frame->selection().selection().visibleStart();
     bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
-    TypingCommand::insertParagraphSeparator(m_frame->document(), 0);
+    ASSERT(m_frame->document());
+    TypingCommand::insertParagraphSeparator(*m_frame->document(), 0);
     revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
 
     return true;
@@ -904,7 +930,7 @@
     if (shouldDeleteRange(selection.get())) {
         updateMarkersForWordsAffectedByEditing(true);
         String plainText = m_frame->selectedTextForClipboard();
-        if (enclosingTextFormControl(m_frame->selection()->start())) {
+        if (enclosingTextFormControl(m_frame->selection().start())) {
             Pasteboard::generalPasteboard()->writePlainText(plainText,
                 canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
         } else {
@@ -923,7 +949,7 @@
         return;
     }
 
-    if (enclosingTextFormControl(m_frame->selection()->start())) {
+    if (enclosingTextFormControl(m_frame->selection().start())) {
         Pasteboard::generalPasteboard()->writePlainText(m_frame->selectedTextForClipboard(),
             canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
     } else {
@@ -945,7 +971,7 @@
     updateMarkersForWordsAffectedByEditing(false);
     ResourceFetcher* loader = m_frame->document()->fetcher();
     ResourceCacheValidationSuppressor validationSuppressor(loader);
-    if (m_frame->selection()->isContentRichlyEditable())
+    if (m_frame->selection().isContentRichlyEditable())
         pasteWithPasteboard(Pasteboard::generalPasteboard(), true);
     else
         pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
@@ -981,7 +1007,7 @@
     if (!startNode)
         return;
     if (endNode) {
-        if (startNode->document() != endNode->document())
+        if (&startNode->document() != &endNode->document())
             return;
         // check if start node is before endNode
         Node* node = startNode;
@@ -991,7 +1017,8 @@
             return;
     }
 
-    applyCommand(SimplifyMarkupCommand::create(m_frame->document(), startNode, (endNode) ? NodeTraversal::next(endNode) : 0));
+    ASSERT(m_frame->document());
+    SimplifyMarkupCommand::create(*m_frame->document(), startNode, endNode ? NodeTraversal::next(endNode) : 0)->apply();
 }
 
 void Editor::copyURL(const KURL& url, const String& title)
@@ -1123,7 +1150,7 @@
 {
     WritingDirection result = LeftToRightWritingDirection;
 
-    Position pos = m_frame->selection()->selection().visibleStart().deepEquivalent();
+    Position pos = m_frame->selection().selection().visibleStart().deepEquivalent();
     Node* node = pos.deprecatedNode();
     if (!node)
         return result;
@@ -1132,7 +1159,7 @@
     if (!renderer)
         return result;
 
-    if (!renderer->isBlockFlow()) {
+    if (!renderer->isRenderBlockFlow()) {
         renderer = renderer->containingBlock();
         if (!renderer)
             return result;
@@ -1154,8 +1181,7 @@
 
 void Editor::ignoreSpelling()
 {
-    RefPtr<Range> selectedRange = frame().selection()->toNormalizedRange();
-    if (selectedRange)
+    if (RefPtr<Range> selectedRange = frame().selection().toNormalizedRange())
         frame().document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
 }
 
@@ -1166,7 +1192,7 @@
 
     // Start at the end of the selection, search to edge of document.  Starting at the selection end makes
     // repeated "check spelling" commands work.
-    VisibleSelection selection(frame().selection()->selection());
+    VisibleSelection selection(frame().selection().selection());
     RefPtr<Range> spellingSearchRange(rangeOfContents(frame().document()));
 
     bool startedWithSelection = false;
@@ -1298,8 +1324,8 @@
 
         // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
         RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
-        frame().selection()->setSelection(VisibleSelection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
-        frame().selection()->revealSelection();
+        frame().selection().setSelection(VisibleSelection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
+        frame().selection().revealSelection();
 
         frame().document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
     } else if (!misspelledWord.isEmpty()) {
@@ -1307,8 +1333,8 @@
         // a marker so we draw the red squiggle later.
 
         RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
-        frame().selection()->setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
-        frame().selection()->revealSelection();
+        frame().selection().setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
+        frame().selection().revealSelection();
 
         client().updateSpellingUIWithMisspelledWord(misspelledWord);
         frame().document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
@@ -1320,7 +1346,7 @@
     if (!isContinuousSpellCheckingEnabled() || !clickedNode || !isSpellCheckingEnabledFor(clickedNode))
         return String();
 
-    VisibleSelection selection = m_frame->selection()->selection();
+    VisibleSelection selection = m_frame->selection().selection();
     if (!selection.isContentEditable() || selection.isNone())
         return String();
 
@@ -1411,10 +1437,10 @@
     // If autocorrected word is non empty, replace the misspelled word by this word.
     if (!autocorrectedString.isEmpty()) {
         VisibleSelection newSelection(misspellingRange.get(), DOWNSTREAM);
-        if (newSelection != frame().selection()->selection()) {
-            if (!frame().selection()->shouldChangeSelection(newSelection))
+        if (newSelection != frame().selection().selection()) {
+            if (!frame().selection().shouldChangeSelection(newSelection))
                 return;
-            frame().selection()->setSelection(newSelection);
+            frame().selection().setSelection(newSelection);
         }
 
         if (!frame().editor().shouldInsertText(autocorrectedString, misspellingRange.get(), EditorInsertActionTyped))
@@ -1422,8 +1448,8 @@
         frame().editor().replaceSelectionWithText(autocorrectedString, false, false);
 
         // Reset the charet one character further.
-        frame().selection()->moveTo(frame().selection()->end());
-        frame().selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
+        frame().selection().moveTo(frame().selection().end());
+        frame().selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
     }
 
     if (!isGrammarCheckingEnabled())
@@ -1474,7 +1500,7 @@
 
 bool Editor::isSpellCheckingEnabledInFocusedNode() const
 {
-    return isSpellCheckingEnabledFor(m_frame->selection()->start().deprecatedNode());
+    return isSpellCheckingEnabledFor(m_frame->selection().start().deprecatedNode());
 }
 
 void Editor::markMisspellings(const VisibleSelection& selection, RefPtr<Range>& firstMisspellingRange)
@@ -1575,9 +1601,9 @@
     bool adjustSelectionForParagraphBoundaries = false;
 
     if (shouldMarkSpelling) {
-        if (m_frame->selection()->selectionType() == VisibleSelection::CaretSelection) {
+        if (m_frame->selection().selectionType() == VisibleSelection::CaretSelection) {
             // Attempt to save the caret position so we can restore it later if needed
-            Position caretPosition = m_frame->selection()->end();
+            Position caretPosition = m_frame->selection().end();
             selectionOffset = paragraph.offsetTo(caretPosition, ASSERT_NO_EXCEPTION);
             restoreSelectionAfterChange = true;
             if (selectionOffset > 0 && (static_cast<unsigned>(selectionOffset) > paragraph.text().length() || paragraph.textCharAt(selectionOffset - 1) == newlineCharacter))
@@ -1602,7 +1628,7 @@
         if (shouldMarkSpelling && result->type == TextCheckingTypeSpelling && resultLocation >= paragraph.checkingStart() && resultLocation + resultLength <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
             ASSERT(resultLength > 0 && resultLocation >= 0);
             RefPtr<Range> misspellingRange = paragraph.subrange(resultLocation, resultLength);
-            misspellingRange->startContainer()->document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling, result->replacement, result->hash);
+            misspellingRange->startContainer()->document().markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling, result->replacement, result->hash);
         } else if (shouldMarkGrammar && result->type == TextCheckingTypeGrammar && paragraph.checkingRangeCovers(resultLocation, resultLength)) {
             ASSERT(resultLength > 0 && resultLocation >= 0);
             for (unsigned j = 0; j < result->details.size(); j++) {
@@ -1610,7 +1636,7 @@
                 ASSERT(detail->length > 0 && detail->location >= 0);
                 if (paragraph.checkingRangeCovers(resultLocation + detail->location, detail->length)) {
                     RefPtr<Range> badGrammarRange = paragraph.subrange(resultLocation + detail->location, detail->length);
-                    badGrammarRange->startContainer()->document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail->userDescription, result->hash);
+                    badGrammarRange->startContainer()->document().markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail->userDescription, result->hash);
                 }
             }
         }
@@ -1622,13 +1648,13 @@
         extendedParagraph.expandRangeToNextEnd();
         if (restoreSelectionAfterChange && selectionOffset >= 0 && selectionOffset <= extendedParagraph.rangeLength()) {
             RefPtr<Range> selectionRange = extendedParagraph.subrange(0, selectionOffset);
-            m_frame->selection()->moveTo(selectionRange->endPosition(), DOWNSTREAM);
+            m_frame->selection().moveTo(selectionRange->endPosition(), DOWNSTREAM);
             if (adjustSelectionForParagraphBoundaries)
-                m_frame->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
+                m_frame->selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
         } else {
             // If this fails for any reason, the fallback is to go one position beyond the last replacement
-            m_frame->selection()->moveTo(m_frame->selection()->end());
-            m_frame->selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
+            m_frame->selection().moveTo(m_frame->selection().end());
+            m_frame->selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
         }
     }
 }
@@ -1668,8 +1694,8 @@
     // Of course, if current selection is a range, we potentially will edit two words that fall on the boundaries of
     // selection, and remove words between the selection boundaries.
     //
-    VisiblePosition startOfSelection = frame().selection()->selection().start();
-    VisiblePosition endOfSelection = frame().selection()->selection().end();
+    VisiblePosition startOfSelection = frame().selection().selection().start();
+    VisiblePosition endOfSelection = frame().selection().selection().end();
     if (startOfSelection.isNull())
         return;
     // First word is the word that ends after or on the start of selection.
@@ -1717,7 +1743,8 @@
     // we would like to remove the marker from word "avant" and whitespace as well. So we need to get the continous range of
     // of marker that contains the word in question, and remove marker on that whole range.
     Document* document = m_frame->document();
-    RefPtr<Range> wordRange = Range::create(document, startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
+    ASSERT(document);
+    RefPtr<Range> wordRange = Range::create(*document, startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
 
     document->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling | DocumentMarker::Grammar, DocumentMarkerController::RemovePartiallyOverlappingMarker);
 }
@@ -1744,12 +1771,12 @@
     if (m_preventRevealSelection)
         return;
 
-    m_frame->selection()->revealSelection(alignment, revealExtentOption);
+    m_frame->selection().revealSelection(alignment, revealExtentOption);
 }
 
 bool Editor::setSelectionOffsets(int selectionStart, int selectionEnd)
 {
-    Element* rootEditableElement = m_frame->selection()->rootEditableElement();
+    Element* rootEditableElement = m_frame->selection().rootEditableElement();
     if (!rootEditableElement)
         return false;
 
@@ -1757,7 +1784,7 @@
     if (!range)
         return false;
 
-    return m_frame->selection()->setSelectedRange(range.get(), VP_DEFAULT_AFFINITY, true);
+    return m_frame->selection().setSelectedRange(range.get(), VP_DEFAULT_AFFINITY, true);
 }
 
 void Editor::transpose()
@@ -1765,9 +1792,9 @@
     if (!canEdit())
         return;
 
-     VisibleSelection selection = m_frame->selection()->selection();
-     if (!selection.isCaret())
-         return;
+    VisibleSelection selection = m_frame->selection().selection();
+    if (!selection.isCaret())
+        return;
 
     // Make a selection that goes back one character and forward two characters.
     VisiblePosition caret = selection.visibleStart();
@@ -1790,10 +1817,10 @@
     String transposed = text.right(1) + text.left(1);
 
     // Select the two characters.
-    if (newSelection != m_frame->selection()->selection()) {
-        if (!m_frame->selection()->shouldChangeSelection(newSelection))
+    if (newSelection != m_frame->selection().selection()) {
+        if (!m_frame->selection().shouldChangeSelection(newSelection))
             return;
-        m_frame->selection()->setSelection(newSelection);
+        m_frame->selection().setSelection(newSelection);
     }
 
     // Insert the transposed characters.
@@ -1825,9 +1852,9 @@
     // because there is work that it must do in this situation.
     // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
     // See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
-    bool selectionDidNotChangeDOMPosition = newSelection == m_frame->selection()->selection();
-    if (selectionDidNotChangeDOMPosition || m_frame->selection()->shouldChangeSelection(newSelection))
-        m_frame->selection()->setSelection(newSelection, options);
+    bool selectionDidNotChangeDOMPosition = newSelection == m_frame->selection().selection();
+    if (selectionDidNotChangeDOMPosition || m_frame->selection().shouldChangeSelection(newSelection))
+        m_frame->selection().setSelection(newSelection, options);
 
     // Some editing operations change the selection visually without affecting its position within the DOM.
     // For example when you press return in the following (the caret is marked by ^):
@@ -1877,27 +1904,29 @@
 void Editor::computeAndSetTypingStyle(StylePropertySet* style, EditAction editingAction)
 {
     if (!style || style->isEmpty()) {
-        m_frame->selection()->clearTypingStyle();
+        m_frame->selection().clearTypingStyle();
         return;
     }
 
     // Calculate the current typing style.
     RefPtr<EditingStyle> typingStyle;
-    if (m_frame->selection()->typingStyle()) {
-        typingStyle = m_frame->selection()->typingStyle()->copy();
+    if (m_frame->selection().typingStyle()) {
+        typingStyle = m_frame->selection().typingStyle()->copy();
         typingStyle->overrideWithStyle(style);
     } else
         typingStyle = EditingStyle::create(style);
 
-    typingStyle->prepareToApplyAt(m_frame->selection()->selection().visibleStart().deepEquivalent(), EditingStyle::PreserveWritingDirection);
+    typingStyle->prepareToApplyAt(m_frame->selection().selection().visibleStart().deepEquivalent(), EditingStyle::PreserveWritingDirection);
 
     // Handle block styles, substracting these from the typing style.
     RefPtr<EditingStyle> blockStyle = typingStyle->extractAndRemoveBlockProperties();
-    if (!blockStyle->isEmpty())
-        applyCommand(ApplyStyleCommand::create(m_frame->document(), blockStyle.get(), editingAction));
+    if (!blockStyle->isEmpty()) {
+        ASSERT(m_frame->document());
+        ApplyStyleCommand::create(*m_frame->document(), blockStyle.get(), editingAction)->apply();
+    }
 
     // Set the remaining style as the typing style.
-    m_frame->selection()->setTypingStyle(typingStyle);
+    m_frame->selection().setTypingStyle(typingStyle);
 }
 
 void Editor::textAreaOrTextFieldDidBeginEditing(Element* e)
@@ -1932,29 +1961,6 @@
     return client().doTextFieldCommandFromEvent(e, ke);
 }
 
-void Editor::applyEditingStyleToBodyElement() const
-{
-    RefPtr<NodeList> list = m_frame->document()->getElementsByTagName("body");
-    unsigned len = list->length();
-    for (unsigned i = 0; i < len; i++)
-        applyEditingStyleToElement(toElement(list->item(i)));
-}
-
-void Editor::applyEditingStyleToElement(Element* element) const
-{
-    if (!element)
-        return;
-    ASSERT(element->isStyledElement());
-    if (!element->isStyledElement())
-        return;
-
-    // Mutate using the CSSOM wrapper so we get the same event behavior as a script.
-    CSSStyleDeclaration* style = element->style();
-    style->setPropertyInternal(CSSPropertyWordWrap, "break-word", false, IGNORE_EXCEPTION);
-    style->setPropertyInternal(CSSPropertyWebkitLineBreak, "after-white-space", false, IGNORE_EXCEPTION);
-}
-
-// Searches from the beginning of the document if nothing is selected.
 bool Editor::findString(const String& target, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection)
 {
     FindOptions options = (forward ? 0 : Backwards) | (caseFlag ? 0 : CaseInsensitive) | (wrapFlag ? WrapAround : 0) | (startInSelection ? StartInSelection : 0);
@@ -1963,15 +1969,15 @@
 
 bool Editor::findString(const String& target, FindOptions options)
 {
-    VisibleSelection selection = m_frame->selection()->selection();
+    VisibleSelection selection = m_frame->selection().selection();
 
     RefPtr<Range> resultRange = rangeOfString(target, selection.firstRange().get(), options);
 
     if (!resultRange)
         return false;
 
-    m_frame->selection()->setSelection(VisibleSelection(resultRange.get(), DOWNSTREAM));
-    m_frame->selection()->revealSelection();
+    m_frame->selection().setSelection(VisibleSelection(resultRange.get(), DOWNSTREAM));
+    m_frame->selection().revealSelection();
     return true;
 }
 
@@ -2076,8 +2082,8 @@
         VisibleSelection newAdjacentWords;
         VisibleSelection newSelectedSentence;
         bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
-        if (m_frame->selection()->selection().isContentEditable() || caretBrowsing) {
-            VisiblePosition newStart(m_frame->selection()->selection().visibleStart());
+        if (m_frame->selection().selection().isContentEditable() || caretBrowsing) {
+            VisiblePosition newStart(m_frame->selection().selection().visibleStart());
             newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
             if (isContinuousGrammarCheckingEnabled)
                 newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
@@ -2092,8 +2098,7 @@
         if (shouldCheckSpellingAndGrammar
             && closeTyping
             && oldSelection.isContentEditable()
-            && oldSelection.start().deprecatedNode()
-            && oldSelection.start().anchorNode()->inDocument()
+            && oldSelection.start().inDocument()
             && !isSelectionInTextField(oldSelection)) {
             spellCheckOldSelection(oldSelection, newAdjacentWords, newSelectedSentence);
         }
@@ -2121,16 +2126,16 @@
 
 void Editor::spellCheckAfterBlur()
 {
-    if (!m_frame->selection()->selection().isContentEditable())
+    if (!m_frame->selection().selection().isContentEditable())
         return;
 
-    if (isSelectionInTextField(m_frame->selection()->selection())) {
+    if (isSelectionInTextField(m_frame->selection().selection())) {
         // textFieldDidEndEditing() and textFieldDidBeginEditing() handle this.
         return;
     }
 
     VisibleSelection empty;
-    spellCheckOldSelection(m_frame->selection()->selection(), empty, empty);
+    spellCheckOldSelection(m_frame->selection().selection(), empty, empty);
 }
 
 void Editor::spellCheckOldSelection(const VisibleSelection& oldSelection, const VisibleSelection& newAdjacentWords, const VisibleSelection& newSelectedSentence)
@@ -2167,7 +2172,7 @@
 
 bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
 {
-    Node* node = findFirstMarkable(m_frame->selection()->start().deprecatedNode());
+    Node* node = findFirstMarkable(m_frame->selection().start().deprecatedNode());
     if (!node)
         return false;
 
@@ -2205,7 +2210,7 @@
 void Editor::toggleOverwriteModeEnabled()
 {
     m_overwriteModeEnabled = !m_overwriteModeEnabled;
-    frame().selection()->setShouldShowBlockCursor(m_overwriteModeEnabled);
+    frame().selection().setShouldShowBlockCursor(m_overwriteModeEnabled);
 };
 
 } // namespace WebCore
diff --git a/Source/core/editing/Editor.h b/Source/core/editing/Editor.h
index ec2e11d..d0b419d 100644
--- a/Source/core/editing/Editor.h
+++ b/Source/core/editing/Editor.h
@@ -267,8 +267,6 @@
     void setMark(const VisibleSelection&);
 
     void computeAndSetTypingStyle(StylePropertySet* , EditAction = EditActionUnspecified);
-    void applyEditingStyleToBodyElement() const;
-    void applyEditingStyleToElement(Element*) const;
 
     IntRect firstRectForRange(Range*) const;
 
diff --git a/Source/core/editing/EditorCommand.cpp b/Source/core/editing/EditorCommand.cpp
index 6b087a0..8c86f04 100644
--- a/Source/core/editing/EditorCommand.cpp
+++ b/Source/core/editing/EditorCommand.cpp
@@ -96,7 +96,7 @@
     Node* node = event->target()->toNode();
     if (!node)
         return &frame;
-    return node->document()->frame();
+    return node->document().frame();
 }
 
 static bool applyCommandToFrame(Frame& frame, EditorCommandSource source, EditAction action, StylePropertySet* style)
@@ -134,7 +134,7 @@
 //        until https://bugs.webkit.org/show_bug.cgi?id=27818 is resolved.
 static bool executeToggleStyleInList(Frame& frame, EditorCommandSource source, EditAction action, CSSPropertyID propertyID, CSSValue* value)
 {
-    RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(frame.selection()->selection());
+    RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(frame.selection().selection());
     if (!selectionStyle || !selectionStyle->style())
         return false;
 
@@ -192,13 +192,15 @@
 
 static bool executeInsertFragment(Frame& frame, PassRefPtr<DocumentFragment> fragment)
 {
-    applyCommand(ReplaceSelectionCommand::create(frame.document(), fragment, ReplaceSelectionCommand::PreventNesting, EditActionUnspecified));
+    ASSERT(frame.document());
+    ReplaceSelectionCommand::create(*frame.document(), fragment, ReplaceSelectionCommand::PreventNesting, EditActionUnspecified)->apply();
     return true;
 }
 
 static bool executeInsertNode(Frame& frame, PassRefPtr<Node> content)
 {
-    RefPtr<DocumentFragment> fragment = DocumentFragment::create(frame.document());
+    ASSERT(frame.document());
+    RefPtr<DocumentFragment> fragment = DocumentFragment::create(*frame.document());
     TrackExceptionState es;
     fragment->appendChild(content, es);
     if (es.hadException())
@@ -208,18 +210,18 @@
 
 static bool expandSelectionToGranularity(Frame& frame, TextGranularity granularity)
 {
-    VisibleSelection selection = frame.selection()->selection();
+    VisibleSelection selection = frame.selection().selection();
     selection.expandUsingGranularity(granularity);
     RefPtr<Range> newRange = selection.toNormalizedRange();
     if (!newRange)
         return false;
     if (newRange->collapsed(IGNORE_EXCEPTION))
         return false;
-    RefPtr<Range> oldRange = frame.selection()->selection().toNormalizedRange();
-    EAffinity affinity = frame.selection()->affinity();
+    RefPtr<Range> oldRange = frame.selection().selection().toNormalizedRange();
+    EAffinity affinity = frame.selection().affinity();
     if (!frame.editor().client().shouldChangeSelectedRange(oldRange.get(), newRange.get(), affinity, false))
         return false;
-    frame.selection()->setSelectedRange(newRange.get(), affinity, true);
+    frame.selection().setSelectedRange(newRange.get(), affinity, true);
     return true;
 }
 
@@ -240,8 +242,8 @@
 static TriState stateTextWritingDirection(Frame& frame, WritingDirection direction)
 {
     bool hasNestedOrMultipleEmbeddings;
-    WritingDirection selectionDirection = EditingStyle::textDirectionForSelection(frame.selection()->selection(),
-        frame.selection()->typingStyle(), hasNestedOrMultipleEmbeddings);
+    WritingDirection selectionDirection = EditingStyle::textDirectionForSelection(frame.selection().selection(),
+        frame.selection().typingStyle(), hasNestedOrMultipleEmbeddings);
     // FXIME: We should be returning MixedTriState when selectionDirection == direction && hasNestedOrMultipleEmbeddings
     return (selectionDirection == direction && !hasNestedOrMultipleEmbeddings) ? TrueTriState : FalseTriState;
 }
@@ -289,7 +291,8 @@
     // FIXME: If userInterface is true, we should display a dialog box to let the user enter a URL.
     if (value.isEmpty())
         return false;
-    applyCommand(CreateLinkCommand::create(frame.document(), value));
+    ASSERT(frame.document());
+    CreateLinkCommand::create(*frame.document(), value)->apply();
     return true;
 }
 
@@ -327,7 +330,8 @@
     case CommandFromDOMWithUserInterface:
         // If the current selection is a caret, delete the preceding character. IE performs forwardDelete, but we currently side with Firefox.
         // Doesn't scroll to make the selection visible, or modify the kill ring (this time, siding with IE, not Firefox).
-        TypingCommand::deleteKeyPressed(frame.document(), frame.selection()->granularity() == WordGranularity ? TypingCommand::SmartDelete : 0);
+        ASSERT(frame.document());
+        TypingCommand::deleteKeyPressed(*frame.document(), frame.selection().granularity() == WordGranularity ? TypingCommand::SmartDelete : 0);
         return true;
     }
     ASSERT_NOT_REACHED();
@@ -385,14 +389,13 @@
 {
     RefPtr<Range> mark = frame.editor().mark().toNormalizedRange();
     if (mark) {
-        FrameSelection* selection = frame.selection();
-        bool selected = selection->setSelectedRange(unionDOMRanges(mark.get(), frame.editor().selectedRange().get()).get(), DOWNSTREAM, true);
+        bool selected = frame.selection().setSelectedRange(unionDOMRanges(mark.get(), frame.editor().selectedRange().get()).get(), DOWNSTREAM, true);
         ASSERT(selected);
         if (!selected)
             return false;
     }
     frame.editor().performDelete();
-    frame.editor().setMark(frame.selection()->selection());
+    frame.editor().setMark(frame.selection().selection());
     return true;
 }
 
@@ -447,8 +450,9 @@
         return false;
     QualifiedName qualifiedTagName(prefix, localName, xhtmlNamespaceURI);
 
-    RefPtr<FormatBlockCommand> command = FormatBlockCommand::create(frame.document(), qualifiedTagName);
-    applyCommand(command);
+    ASSERT(frame.document());
+    RefPtr<FormatBlockCommand> command = FormatBlockCommand::create(*frame.document(), qualifiedTagName);
+    command->apply();
     return command->didApply();
 }
 
@@ -463,7 +467,8 @@
         // Doesn't scroll to make the selection visible, or modify the kill ring.
         // ForwardDelete is not implemented in IE or Firefox, so this behavior is only needed for
         // backward compatibility with ourselves, and for consistency with Delete.
-        TypingCommand::forwardDeleteKeyPressed(frame.document());
+        ASSERT(frame.document());
+        TypingCommand::forwardDeleteKeyPressed(*frame.document());
         return true;
     }
     ASSERT_NOT_REACHED();
@@ -478,7 +483,8 @@
 
 static bool executeIndent(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    applyCommand(IndentOutdentCommand::create(frame.document(), IndentOutdentCommand::Indent));
+    ASSERT(frame.document());
+    IndentOutdentCommand::create(*frame.document(), IndentOutdentCommand::Indent)->apply();
     return true;
 }
 
@@ -489,7 +495,8 @@
 
 static bool executeInsertHorizontalRule(Frame& frame, Event*, EditorCommandSource, const String& value)
 {
-    RefPtr<HTMLHRElement> rule = HTMLHRElement::create(frame.document());
+    ASSERT(frame.document());
+    RefPtr<HTMLHRElement> rule = HTMLHRElement::create(*frame.document());
     if (!value.isEmpty())
         rule->setIdAttribute(value);
     return executeInsertNode(frame, rule.release());
@@ -497,13 +504,15 @@
 
 static bool executeInsertHTML(Frame& frame, Event*, EditorCommandSource, const String& value)
 {
-    return executeInsertFragment(frame, createFragmentFromMarkup(frame.document(), value, ""));
+    ASSERT(frame.document());
+    return executeInsertFragment(frame, createFragmentFromMarkup(*frame.document(), value, ""));
 }
 
 static bool executeInsertImage(Frame& frame, Event*, EditorCommandSource, const String& value)
 {
     // FIXME: If userInterface is true, we should display a dialog box and let the user choose a local image.
-    RefPtr<HTMLImageElement> image = HTMLImageElement::create(frame.document());
+    ASSERT(frame.document());
+    RefPtr<HTMLImageElement> image = HTMLImageElement::create(*frame.document());
     image->setSrc(value);
     return executeInsertNode(frame, image.release());
 }
@@ -518,7 +527,8 @@
         // Doesn't scroll to make the selection visible, or modify the kill ring.
         // InsertLineBreak is not implemented in IE or Firefox, so this behavior is only needed for
         // backward compatibility with ourselves, and for consistency with other commands.
-        TypingCommand::insertLineBreak(frame.document(), 0);
+        ASSERT(frame.document());
+        TypingCommand::insertLineBreak(*frame.document(), 0);
         return true;
     }
     ASSERT_NOT_REACHED();
@@ -533,19 +543,22 @@
 
 static bool executeInsertNewlineInQuotedContent(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    TypingCommand::insertParagraphSeparatorInQuotedContent(frame.document());
+    ASSERT(frame.document());
+    TypingCommand::insertParagraphSeparatorInQuotedContent(*frame.document());
     return true;
 }
 
 static bool executeInsertOrderedList(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    applyCommand(InsertListCommand::create(frame.document(), InsertListCommand::OrderedList));
+    ASSERT(frame.document());
+    InsertListCommand::create(*frame.document(), InsertListCommand::OrderedList)->apply();
     return true;
 }
 
 static bool executeInsertParagraph(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    TypingCommand::insertParagraphSeparator(frame.document(), 0);
+    ASSERT(frame.document());
+    TypingCommand::insertParagraphSeparator(*frame.document(), 0);
     return true;
 }
 
@@ -556,13 +569,15 @@
 
 static bool executeInsertText(Frame& frame, Event*, EditorCommandSource, const String& value)
 {
-    TypingCommand::insertText(frame.document(), value, 0);
+    ASSERT(frame.document());
+    TypingCommand::insertText(*frame.document(), value, 0);
     return true;
 }
 
 static bool executeInsertUnorderedList(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    applyCommand(InsertListCommand::create(frame.document(), InsertListCommand::UnorderedList));
+    ASSERT(frame.document());
+    InsertListCommand::create(*frame.document(), InsertListCommand::UnorderedList)->apply();
     return true;
 }
 
@@ -614,47 +629,47 @@
 
 static bool executeMoveBackward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionBackward, CharacterGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionBackward, CharacterGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveBackwardAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionBackward, CharacterGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionBackward, CharacterGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveDown(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.selection()->modify(FrameSelection::AlterationMove, DirectionForward, LineGranularity, UserTriggered);
+    return frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, LineGranularity, UserTriggered);
 }
 
 static bool executeMoveDownAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionForward, LineGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionForward, LineGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveForward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveForwardAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionForward, CharacterGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionForward, CharacterGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveLeft(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.selection()->modify(FrameSelection::AlterationMove, DirectionLeft, CharacterGranularity, UserTriggered);
+    return frame.selection().modify(FrameSelection::AlterationMove, DirectionLeft, CharacterGranularity, UserTriggered);
 }
 
 static bool executeMoveLeftAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionLeft, CharacterGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionLeft, CharacterGranularity, UserTriggered);
     return true;
 }
 
@@ -663,7 +678,7 @@
     unsigned distance = verticalScrollDistance(frame);
     if (!distance)
         return false;
-    return frame.selection()->modify(FrameSelection::AlterationMove, distance, FrameSelection::DirectionDown,
+    return frame.selection().modify(FrameSelection::AlterationMove, distance, FrameSelection::DirectionDown,
         UserTriggered, FrameSelection::AlignCursorOnScrollAlways);
 }
 
@@ -672,7 +687,7 @@
     unsigned distance = verticalScrollDistance(frame);
     if (!distance)
         return false;
-    return frame.selection()->modify(FrameSelection::AlterationExtend, distance, FrameSelection::DirectionDown,
+    return frame.selection().modify(FrameSelection::AlterationExtend, distance, FrameSelection::DirectionDown,
         UserTriggered, FrameSelection::AlignCursorOnScrollAlways);
 }
 
@@ -681,7 +696,7 @@
     unsigned distance = verticalScrollDistance(frame);
     if (!distance)
         return false;
-    return frame.selection()->modify(FrameSelection::AlterationMove, distance, FrameSelection::DirectionUp,
+    return frame.selection().modify(FrameSelection::AlterationMove, distance, FrameSelection::DirectionUp,
         UserTriggered, FrameSelection::AlignCursorOnScrollAlways);
 }
 
@@ -690,227 +705,228 @@
     unsigned distance = verticalScrollDistance(frame);
     if (!distance)
         return false;
-    return frame.selection()->modify(FrameSelection::AlterationExtend, distance, FrameSelection::DirectionUp,
+    return frame.selection().modify(FrameSelection::AlterationExtend, distance, FrameSelection::DirectionUp,
         UserTriggered, FrameSelection::AlignCursorOnScrollAlways);
 }
 
 static bool executeMoveRight(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.selection()->modify(FrameSelection::AlterationMove, DirectionRight, CharacterGranularity, UserTriggered);
+    return frame.selection().modify(FrameSelection::AlterationMove, DirectionRight, CharacterGranularity, UserTriggered);
 }
 
 static bool executeMoveRightAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionRight, CharacterGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionRight, CharacterGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveToBeginningOfDocument(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionBackward, DocumentBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionBackward, DocumentBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToBeginningOfDocumentAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionBackward, DocumentBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionBackward, DocumentBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToBeginningOfLine(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionBackward, LineBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionBackward, LineBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToBeginningOfLineAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionBackward, LineBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionBackward, LineBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToBeginningOfParagraph(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionBackward, ParagraphBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionBackward, ParagraphBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToBeginningOfParagraphAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionBackward, ParagraphBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionBackward, ParagraphBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToBeginningOfSentence(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionBackward, SentenceBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionBackward, SentenceBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToBeginningOfSentenceAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionBackward, SentenceBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionBackward, SentenceBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToEndOfDocument(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionForward, DocumentBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, DocumentBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToEndOfDocumentAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionForward, DocumentBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionForward, DocumentBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToEndOfSentence(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionForward, SentenceBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, SentenceBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToEndOfSentenceAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionForward, SentenceBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionForward, SentenceBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToEndOfLine(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionForward, LineBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, LineBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToEndOfLineAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionForward, LineBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionForward, LineBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToEndOfParagraph(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionForward, ParagraphBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, ParagraphBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToEndOfParagraphAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionForward, ParagraphBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionForward, ParagraphBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveParagraphBackward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionBackward, ParagraphGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionBackward, ParagraphGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveParagraphBackwardAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionBackward, ParagraphGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionBackward, ParagraphGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveParagraphForward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionForward, ParagraphGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, ParagraphGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveParagraphForwardAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionForward, ParagraphGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionForward, ParagraphGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveUp(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    return frame.selection()->modify(FrameSelection::AlterationMove, DirectionBackward, LineGranularity, UserTriggered);
+    return frame.selection().modify(FrameSelection::AlterationMove, DirectionBackward, LineGranularity, UserTriggered);
 }
 
 static bool executeMoveUpAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionBackward, LineGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionBackward, LineGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveWordBackward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionBackward, WordGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionBackward, WordGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveWordBackwardAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionBackward, WordGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionBackward, WordGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveWordForward(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionForward, WordGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, WordGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveWordForwardAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionForward, WordGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionForward, WordGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveWordLeft(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionLeft, WordGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionLeft, WordGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveWordLeftAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionLeft, WordGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionLeft, WordGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveWordRight(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionRight, WordGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionRight, WordGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveWordRightAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionRight, WordGranularity, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionRight, WordGranularity, UserTriggered);
     return true;
 }
 
 static bool executeMoveToLeftEndOfLine(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionLeft, LineBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionLeft, LineBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToLeftEndOfLineAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionLeft, LineBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionLeft, LineBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToRightEndOfLine(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationMove, DirectionRight, LineBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationMove, DirectionRight, LineBoundary, UserTriggered);
     return true;
 }
 
 static bool executeMoveToRightEndOfLineAndModifySelection(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->modify(FrameSelection::AlterationExtend, DirectionRight, LineBoundary, UserTriggered);
+    frame.selection().modify(FrameSelection::AlterationExtend, DirectionRight, LineBoundary, UserTriggered);
     return true;
 }
 
 static bool executeOutdent(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    applyCommand(IndentOutdentCommand::create(frame.document(), IndentOutdentCommand::Outdent));
+    ASSERT(frame.document());
+    IndentOutdentCommand::create(*frame.document(), IndentOutdentCommand::Outdent)->apply();
     return true;
 }
 
@@ -1020,7 +1036,7 @@
 
 static bool executeSelectAll(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->selectAll();
+    frame.selection().selectAll();
     return true;
 }
 
@@ -1047,7 +1063,7 @@
         systemBeep();
         return false;
     }
-    frame.selection()->setSelectedRange(unionDOMRanges(mark.get(), selection.get()).get(), DOWNSTREAM, true);
+    frame.selection().setSelectedRange(unionDOMRanges(mark.get(), selection.get()).get(), DOWNSTREAM, true);
     return true;
 }
 
@@ -1058,7 +1074,7 @@
 
 static bool executeSetMark(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.editor().setMark(frame.selection()->selection());
+    frame.editor().setMark(frame.selection().selection());
     return true;
 }
 
@@ -1093,12 +1109,12 @@
 static bool executeSwapWithMark(Frame& frame, Event*, EditorCommandSource, const String&)
 {
     const VisibleSelection& mark = frame.editor().mark();
-    const VisibleSelection& selection = frame.selection()->selection();
+    const VisibleSelection& selection = frame.selection().selection();
     if (mark.isNone() || selection.isNone()) {
         systemBeep();
         return false;
     }
-    frame.selection()->setSelection(mark);
+    frame.selection().setSelection(mark);
     frame.editor().setMark(selection);
     return true;
 }
@@ -1133,7 +1149,8 @@
 
 static bool executeUnlink(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    applyCommand(UnlinkCommand::create(frame.document()));
+    ASSERT(frame.document());
+    UnlinkCommand::create(*frame.document())->apply();
     return true;
 }
 
@@ -1144,7 +1161,7 @@
 
 static bool executeUnselect(Frame& frame, Event*, EditorCommandSource, const String&)
 {
-    frame.selection()->clear();
+    frame.selection().clear();
     return true;
 }
 
@@ -1272,7 +1289,7 @@
 
 static bool enabledInRichlyEditableText(Frame& frame, Event*, EditorCommandSource)
 {
-    return frame.selection()->isCaretOrRange() && frame.selection()->isContentRichlyEditable() && frame.selection()->rootEditableElement();
+    return frame.selection().isCaretOrRange() && frame.selection().isContentRichlyEditable() && frame.selection().rootEditableElement();
 }
 
 static bool enabledPaste(Frame& frame, Event*, EditorCommandSource)
@@ -1282,12 +1299,12 @@
 
 static bool enabledRangeInEditableText(Frame& frame, Event*, EditorCommandSource)
 {
-    return frame.selection()->isRange() && frame.selection()->isContentEditable();
+    return frame.selection().isRange() && frame.selection().isContentEditable();
 }
 
 static bool enabledRangeInRichlyEditableText(Frame& frame, Event*, EditorCommandSource)
 {
-    return frame.selection()->isRange() && frame.selection()->isContentRichlyEditable();
+    return frame.selection().isRange() && frame.selection().isContentRichlyEditable();
 }
 
 static bool enabledRedo(Frame& frame, Event*, EditorCommandSource)
@@ -1434,7 +1451,7 @@
 
 static String valueFormatBlock(Frame& frame, Event*)
 {
-    const VisibleSelection& selection = frame.selection()->selection();
+    const VisibleSelection& selection = frame.selection().selection();
     if (!selection.isNonOrphanedCaretOrRange() || !selection.isContentEditable())
         return "";
     Element* formatBlockElement = FormatBlockCommand::elementForFormatBlockCommand(selection.firstRange().get());
diff --git a/Source/core/editing/FormatBlockCommand.cpp b/Source/core/editing/FormatBlockCommand.cpp
index 8cdcf9c..8ea2e4d 100644
--- a/Source/core/editing/FormatBlockCommand.cpp
+++ b/Source/core/editing/FormatBlockCommand.cpp
@@ -44,7 +44,7 @@
     return node->isElementNode() && isElementForFormatBlock(toElement(node)->tagQName());
 }
 
-FormatBlockCommand::FormatBlockCommand(Document* document, const QualifiedName& tagName)
+FormatBlockCommand::FormatBlockCommand(Document& document, const QualifiedName& tagName)
     : ApplyBlockElementCommand(document, tagName)
     , m_didApply(false)
 {
diff --git a/Source/core/editing/FormatBlockCommand.h b/Source/core/editing/FormatBlockCommand.h
index c917832..da6add6 100644
--- a/Source/core/editing/FormatBlockCommand.h
+++ b/Source/core/editing/FormatBlockCommand.h
@@ -40,7 +40,7 @@
 
 class FormatBlockCommand : public ApplyBlockElementCommand {
 public:
-    static PassRefPtr<FormatBlockCommand> create(Document* document, const QualifiedName& tagName)
+    static PassRefPtr<FormatBlockCommand> create(Document& document, const QualifiedName& tagName)
     {
         return adoptRef(new FormatBlockCommand(document, tagName));
     }
@@ -51,7 +51,7 @@
     bool didApply() const { return m_didApply; }
 
 private:
-    FormatBlockCommand(Document*, const QualifiedName& tagName);
+    FormatBlockCommand(Document&, const QualifiedName& tagName);
 
     void formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection);
     void formatRange(const Position& start, const Position& end, const Position& endOfSelection, RefPtr<Element>&);
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index 026e1fa..7e82d30 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -37,6 +37,7 @@
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Range.h"
+#include "core/dom/Text.h"
 #include "core/editing/Editor.h"
 #include "core/editing/InputMethodController.h"
 #include "core/editing/RenderedPosition.h"
@@ -113,7 +114,7 @@
         return selectionRoot;
 
     Node* node = m_selection.base().containerNode();
-    return node ? node->treeScope()->rootNode() : 0;
+    return node ? node->treeScope().rootNode() : 0;
 }
 
 Element* FrameSelection::rootEditableElementRespectingShadowTree() const
@@ -241,10 +242,10 @@
     // <http://bugs.webkit.org/show_bug.cgi?id=23464>: Infinite recursion at FrameSelection::setSelection
     // if document->frame() == m_frame we can get into an infinite loop
     if (s.base().anchorNode()) {
-        Document* document = s.base().anchorNode()->document();
-        if (document && document->frame() && document->frame() != m_frame && document != m_frame->document()) {
-            RefPtr<Frame> guard = document->frame();
-            document->frame()->selection()->setSelection(s, options, align, granularity);
+        Document& document = *s.base().document();
+        if (document.frame() && document.frame() != m_frame && &document != m_frame->document()) {
+            RefPtr<Frame> guard = document.frame();
+            document.frame()->selection().setSelection(s, options, align, granularity);
             // It's possible that during the above set selection, this FrameSelection has been modified by
             // selectFrameElementInParentIfFullySelected, but that the selection is no longer valid since
             // the frame is about to be destroyed. If this is the case, clear our selection.
@@ -300,7 +301,7 @@
     }
 
     notifyAccessibilityForSelectionChange();
-    m_frame->document()->enqueueDocumentEvent(Event::create(eventNames().selectionchangeEvent, false, false));
+    m_frame->document()->enqueueDocumentEvent(Event::create(eventNames().selectionchangeEvent));
 }
 
 static bool removingNodeRemovesPosition(Node* node, const Position& position)
@@ -320,7 +321,7 @@
 
 static void clearRenderViewSelection(const Position& position)
 {
-    RefPtr<Document> document = position.anchorNode()->document();
+    RefPtr<Document> document = position.document();
     document->updateStyleIfNeeded();
     if (RenderView* view = document->renderView())
         view->clearSelection();
@@ -387,54 +388,80 @@
         setSelection(VisibleSelection(), DoNotSetFocus);
 }
 
-static void updatePositionAfterAdoptingTextReplacement(Position& position, CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)
+static Position updatePositionAfterAdoptingTextReplacement(const Position& position, CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)
 {
     if (!position.anchorNode() || position.anchorNode() != node || position.anchorType() != Position::PositionIsOffsetInAnchor)
-        return;
+        return position;
 
     // See: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Mutation
     ASSERT(position.offsetInContainerNode() >= 0);
     unsigned positionOffset = static_cast<unsigned>(position.offsetInContainerNode());
     // Replacing text can be viewed as a deletion followed by insertion.
     if (positionOffset >= offset && positionOffset <= offset + oldLength)
-        position.moveToOffset(offset);
+        positionOffset = offset;
 
     // Adjust the offset if the position is after the end of the deleted contents
     // (positionOffset > offset + oldLength) to avoid having a stale offset.
     if (positionOffset > offset + oldLength)
-        position.moveToOffset(positionOffset - oldLength + newLength);
+        positionOffset = positionOffset - oldLength + newLength;
 
-    ASSERT(static_cast<unsigned>(position.offsetInContainerNode()) <= node->length());
+    ASSERT(positionOffset <= node->length());
+    // CharacterNode in VisibleSelection must be Text node, because Comment
+    // and ProcessingInstruction node aren't visible.
+    return Position(toText(node), positionOffset);
 }
 
-static inline bool nodeIsDetachedFromDocument(Node* node)
+static inline bool nodeIsDetachedFromDocument(const Node& node)
 {
-    ASSERT(node);
-    Node* highest = highestAncestor(node);
+    Node* highest = node.highestAncestor();
     return highest->nodeType() == Node::DOCUMENT_FRAGMENT_NODE && !highest->isShadowRoot();
 }
 
 void FrameSelection::textWasReplaced(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))
+    if (isNone() || !node || nodeIsDetachedFromDocument(*node))
         return;
 
-    Position base = m_selection.base();
-    Position extent = m_selection.extent();
-    Position start = m_selection.start();
-    Position end = m_selection.end();
-    updatePositionAfterAdoptingTextReplacement(base, node, offset, oldLength, newLength);
-    updatePositionAfterAdoptingTextReplacement(extent, node, offset, oldLength, newLength);
-    updatePositionAfterAdoptingTextReplacement(start, node, offset, oldLength, newLength);
-    updatePositionAfterAdoptingTextReplacement(end, node, offset, oldLength, newLength);
+    Position base = updatePositionAfterAdoptingTextReplacement(m_selection.base(), node, offset, oldLength, newLength);
+    Position extent = updatePositionAfterAdoptingTextReplacement(m_selection.extent(), node, offset, oldLength, newLength);
+    Position start = updatePositionAfterAdoptingTextReplacement(m_selection.start(), node, offset, oldLength, newLength);
+    Position end = updatePositionAfterAdoptingTextReplacement(m_selection.end(), node, offset, oldLength, newLength);
+    updateSelectionIfNeeded(base, extent, start, end);
+}
 
-    if (base != m_selection.base() || extent != m_selection.extent() || start != m_selection.start() || end != m_selection.end()) {
-        VisibleSelection newSelection;
-        newSelection.setWithoutValidation(base, extent);
-        m_frame->document()->updateLayout();
-        setSelection(newSelection, DoNotSetFocus);
-    }
+static Position updatePostionAfterAdoptingTextNodeSplit(const Position& position, const Text& oldNode)
+{
+    if (!position.anchorNode() || position.anchorNode() != &oldNode || position.anchorType() != Position::PositionIsOffsetInAnchor)
+        return position;
+    // See: http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Mutation
+    ASSERT(position.offsetInContainerNode() >= 0);
+    unsigned positionOffset = static_cast<unsigned>(position.offsetInContainerNode());
+    unsigned oldLength = oldNode.length();
+    if (positionOffset <= oldLength)
+        return position;
+    return Position(toText(oldNode.nextSibling()), positionOffset - oldLength);
+}
+
+void FrameSelection::textNodeSplit(const Text& oldNode)
+{
+    if (isNone() || nodeIsDetachedFromDocument(oldNode))
+        return;
+    Position base = updatePostionAfterAdoptingTextNodeSplit(m_selection.base(), oldNode);
+    Position extent = updatePostionAfterAdoptingTextNodeSplit(m_selection.extent(), oldNode);
+    Position start = updatePostionAfterAdoptingTextNodeSplit(m_selection.start(), oldNode);
+    Position end = updatePostionAfterAdoptingTextNodeSplit(m_selection.end(), oldNode);
+    updateSelectionIfNeeded(base, extent, start, end);
+}
+
+void FrameSelection::updateSelectionIfNeeded(const Position& base, const Position& extent, const Position& start, const Position& end)
+{
+    if (base == m_selection.base() && extent == m_selection.extent() && start == m_selection.start() && end == m_selection.end())
+        return;
+    VisibleSelection newSelection;
+    newSelection.setWithoutValidation(base, extent);
+    m_frame->document()->updateLayout();
+    setSelection(newSelection, DoNotSetFocus);
 }
 
 TextDirection FrameSelection::directionOfEnclosingBlock()
@@ -576,9 +603,9 @@
     switch (granularity) {
     case CharacterGranularity:
         if (directionOfEnclosingBlock() == LTR)
-            pos = pos.next(CannotCrossEditingBoundary);
+            pos = pos.next(CanSkipOverEditingBoundary);
         else
-            pos = pos.previous(CannotCrossEditingBoundary);
+            pos = pos.previous(CanSkipOverEditingBoundary);
         break;
     case WordGranularity:
         if (directionOfEnclosingBlock() == LTR)
@@ -611,7 +638,7 @@
     VisiblePosition pos(m_selection.extent(), m_selection.affinity());
     switch (granularity) {
     case CharacterGranularity:
-        pos = pos.next(CannotCrossEditingBoundary);
+        pos = pos.next(CanSkipOverEditingBoundary);
         break;
     case WordGranularity:
         pos = nextWordPositionForPlatform(pos);
@@ -689,7 +716,7 @@
         if (isRange())
             pos = VisiblePosition(m_selection.end(), m_selection.affinity());
         else
-            pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).next(CannotCrossEditingBoundary);
+            pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).next(CanSkipOverEditingBoundary);
         break;
     case WordGranularity:
         pos = nextWordPositionForPlatform(VisiblePosition(m_selection.extent(), m_selection.affinity()));
@@ -740,9 +767,9 @@
     switch (granularity) {
     case CharacterGranularity:
         if (directionOfEnclosingBlock() == LTR)
-            pos = pos.previous(CannotCrossEditingBoundary);
+            pos = pos.previous(CanSkipOverEditingBoundary);
         else
-            pos = pos.next(CannotCrossEditingBoundary);
+            pos = pos.next(CanSkipOverEditingBoundary);
         break;
     case WordGranularity:
         if (directionOfEnclosingBlock() == LTR)
@@ -779,7 +806,7 @@
     // over everything.
     switch (granularity) {
     case CharacterGranularity:
-        pos = pos.previous(CannotCrossEditingBoundary);
+        pos = pos.previous(CanSkipOverEditingBoundary);
         break;
     case WordGranularity:
         pos = previousWordPosition(pos);
@@ -856,7 +883,7 @@
         if (isRange())
             pos = VisiblePosition(m_selection.start(), m_selection.affinity());
         else
-            pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).previous(CannotCrossEditingBoundary);
+            pos = VisiblePosition(m_selection.extent(), m_selection.affinity()).previous(CanSkipOverEditingBoundary);
         break;
     case WordGranularity:
         pos = previousWordPosition(VisiblePosition(m_selection.extent(), m_selection.affinity()));
@@ -1115,7 +1142,7 @@
         break;
     }
 
-    Frame* frame = pos.anchorNode()->document()->frame();
+    Frame* frame = pos.document()->frame();
     if (!frame)
         return x;
 
@@ -1407,9 +1434,9 @@
 
     // Focus on the parent frame, and then select from before this element to after.
     VisibleSelection newSelection(beforeOwnerElement, afterOwnerElement);
-    if (parent->selection()->shouldChangeSelection(newSelection)) {
+    if (parent->selection().shouldChangeSelection(newSelection)) {
         page->focusController().setFocusedFrame(parent);
-        parent->selection()->setSelection(newSelection);
+        parent->selection().setSelection(newSelection);
     }
 }
 
@@ -1445,7 +1472,7 @@
     if (!root)
         return;
 
-    if (selectStartTarget && !selectStartTarget->dispatchEvent(Event::create(eventNames().selectstartEvent, true, true)))
+    if (selectStartTarget && !selectStartTarget->dispatchEvent(Event::createCancelableBubble(eventNames().selectstartEvent)))
         return;
 
     VisibleSelection newSelection(VisibleSelection::selectionFromContentsOfNode(root.get()));
@@ -1461,7 +1488,7 @@
 {
     if (!range || !range->startContainer() || !range->endContainer())
         return false;
-    ASSERT(range->startContainer()->document() == range->endContainer()->document());
+    ASSERT(&range->startContainer()->document() == &range->endContainer()->document());
 
     m_frame->document()->updateLayoutIgnorePendingStylesheets();
 
@@ -1664,7 +1691,7 @@
     if (!root)
         return false;
 
-    Element* focusedElement = root->document()->focusedElement();
+    Element* focusedElement = root->document().focusedElement();
     if (!focusedElement)
         return false;
 
@@ -1890,7 +1917,7 @@
     if (!selectStartTarget)
         return true;
 
-    return selectStartTarget->dispatchEvent(Event::create(eventNames().selectstartEvent, true, true));
+    return selectStartTarget->dispatchEvent(Event::createCancelableBubble(eventNames().selectstartEvent));
 }
 
 inline bool FrameSelection::visualWordMovementEnabled() const
diff --git a/Source/core/editing/FrameSelection.h b/Source/core/editing/FrameSelection.h
index d6c76f1..91b8bde 100644
--- a/Source/core/editing/FrameSelection.h
+++ b/Source/core/editing/FrameSelection.h
@@ -46,6 +46,7 @@
 class RenderObject;
 class RenderView;
 class Settings;
+class Text;
 class VisiblePosition;
 
 enum EUserTriggered { NotUserTriggered = 0, UserTriggered = 1 };
@@ -155,6 +156,7 @@
 
     void nodeWillBeRemoved(Node*);
     void textWasReplaced(CharacterData*, unsigned offset, unsigned oldLength, unsigned newLength);
+    void textNodeSplit(const Text& oldNode);
 
     void setCaretVisible(bool caretIsVisible) { setCaretVisibility(caretIsVisible ? Visible : Hidden); }
     bool recomputeCaretRect();
@@ -248,6 +250,8 @@
 
     bool visualWordMovementEnabled() const;
 
+    void updateSelectionIfNeeded(const Position& base, const Position& extent, const Position& start, const Position& end);
+
     Frame* m_frame;
 
     LayoutUnit m_xPosForVerticalArrowNavigation;
diff --git a/Source/core/editing/IndentOutdentCommand.cpp b/Source/core/editing/IndentOutdentCommand.cpp
index da3dbb6..fae2f40 100644
--- a/Source/core/editing/IndentOutdentCommand.cpp
+++ b/Source/core/editing/IndentOutdentCommand.cpp
@@ -43,7 +43,7 @@
     return node && (node->hasTagName(ulTag) || node->hasTagName(olTag) || node->hasTagName(blockquoteTag));
 }
 
-IndentOutdentCommand::IndentOutdentCommand(Document* document, EIndentType typeOfAction, int marginInPixels)
+IndentOutdentCommand::IndentOutdentCommand(Document& document, EIndentType typeOfAction, int marginInPixels)
     : ApplyBlockElementCommand(document, blockquoteTag, "margin: 0 0 0 40px; border: none; padding: 0px;")
     , m_typeOfAction(typeOfAction)
     , m_marginInPixels(marginInPixels)
@@ -69,7 +69,7 @@
     Element* previousList = selectedListItem->previousElementSibling();
     Element* nextList = selectedListItem->nextElementSibling();
 
-    RefPtr<Element> newList = document()->createElement(listNode->tagQName(), false);
+    RefPtr<Element> newList = document().createElement(listNode->tagQName(), false);
     insertNodeBefore(newList, selectedListItem);
 
     moveParagraphWithClones(start, end, newList.get(), selectedListItem);
@@ -156,7 +156,7 @@
             }
         }
 
-        document()->updateLayoutIgnorePendingStylesheets();
+        document().updateLayoutIgnorePendingStylesheets();
         visibleStartOfParagraph = VisiblePosition(visibleStartOfParagraph.deepEquivalent());
         visibleEndOfParagraph = VisiblePosition(visibleEndOfParagraph.deepEquivalent());
         if (visibleStartOfParagraph.isNotNull() && !isStartOfParagraph(visibleStartOfParagraph))
@@ -206,10 +206,10 @@
         // outdentParagraph could move more than one paragraph if the paragraph
         // is in a list item. As a result, endAfterSelection and endOfNextParagraph
         // could refer to positions no longer in the document.
-        if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().anchorNode()->inDocument())
+        if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument())
             break;
 
-        if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().anchorNode()->inDocument()) {
+        if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument()) {
             endOfCurrentParagraph = endingSelection().end();
             endOfNextParagraph = endOfParagraph(endOfCurrentParagraph.next());
         }
diff --git a/Source/core/editing/IndentOutdentCommand.h b/Source/core/editing/IndentOutdentCommand.h
index 7a49ac5..b90d8ec 100644
--- a/Source/core/editing/IndentOutdentCommand.h
+++ b/Source/core/editing/IndentOutdentCommand.h
@@ -34,7 +34,7 @@
 class IndentOutdentCommand : public ApplyBlockElementCommand {
 public:
     enum EIndentType { Indent, Outdent };
-    static PassRefPtr<IndentOutdentCommand> create(Document* document, EIndentType type, int marginInPixels = 0)
+    static PassRefPtr<IndentOutdentCommand> create(Document& document, EIndentType type, int marginInPixels = 0)
     {
         return adoptRef(new IndentOutdentCommand(document, type, marginInPixels));
     }
@@ -42,7 +42,7 @@
     virtual bool preservesTypingStyle() const { return true; }
 
 private:
-    IndentOutdentCommand(Document*, EIndentType, int marginInPixels);
+    IndentOutdentCommand(Document&, EIndentType, int marginInPixels);
 
     virtual EditAction editingAction() const { return m_typeOfAction == Indent ? EditActionIndent : EditActionOutdent; }
 
diff --git a/Source/core/editing/InputMethodController.cpp b/Source/core/editing/InputMethodController.cpp
index 0a33f67..ed53479 100644
--- a/Source/core/editing/InputMethodController.cpp
+++ b/Source/core/editing/InputMethodController.cpp
@@ -120,7 +120,7 @@
     // See <http://bugs.webkit.org/show_bug.cgi?id=15781>
     VisibleSelection selection;
     selection.setWithoutValidation(range->startPosition(), range->endPosition());
-    m_frame->selection()->setSelection(selection, 0);
+    m_frame->selection().setSelection(selection, 0);
 }
 
 void InputMethodController::confirmComposition()
@@ -168,12 +168,12 @@
         return;
 
     // Check if selection start and selection end are valid.
-    Position start = m_frame->selection()->start();
-    Position end = m_frame->selection()->end();
+    Position start = m_frame->selection().start();
+    Position end = m_frame->selection().end();
     if (start.containerNode() == m_compositionNode
         && end.containerNode() == m_compositionNode
-        && static_cast<unsigned>(start.computeOffsetInContainerNode()) > m_compositionStart
-        && static_cast<unsigned>(end.computeOffsetInContainerNode()) < m_compositionEnd)
+        && static_cast<unsigned>(start.computeOffsetInContainerNode()) >= m_compositionStart
+        && static_cast<unsigned>(end.computeOffsetInContainerNode()) <= m_compositionEnd)
         return;
 
     cancelComposition();
@@ -192,7 +192,7 @@
     else
         selectComposition();
 
-    if (m_frame->selection()->isNone())
+    if (m_frame->selection().isNone())
         return;
 
     // Dispatch a compositionend event to the focused node.
@@ -205,8 +205,10 @@
 
     // If text is empty, then delete the old composition here. If text is non-empty, InsertTextCommand::input
     // will delete the old composition with an optimized replace operation.
-    if (text.isEmpty() && mode != CancelComposition)
-        TypingCommand::deleteSelection(m_frame->document(), 0);
+    if (text.isEmpty() && mode != CancelComposition) {
+        ASSERT(m_frame->document());
+        TypingCommand::deleteSelection(*m_frame->document(), 0);
+    }
 
     m_compositionNode = 0;
     m_customCompositionUnderlines.clear();
@@ -232,7 +234,7 @@
 
     selectComposition();
 
-    if (m_frame->selection()->isNone())
+    if (m_frame->selection().isNone())
         return;
 
     if (Element* target = m_frame->document()->focusedElement()) {
@@ -271,18 +273,21 @@
 
     // If text is empty, then delete the old composition here. If text is non-empty, InsertTextCommand::input
     // will delete the old composition with an optimized replace operation.
-    if (text.isEmpty())
-        TypingCommand::deleteSelection(m_frame->document(), TypingCommand::PreventSpellChecking);
+    if (text.isEmpty()) {
+        ASSERT(m_frame->document());
+        TypingCommand::deleteSelection(*m_frame->document(), TypingCommand::PreventSpellChecking);
+    }
 
     m_compositionNode = 0;
     m_customCompositionUnderlines.clear();
 
     if (!text.isEmpty()) {
-        TypingCommand::insertText(m_frame->document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
+        ASSERT(m_frame->document());
+        TypingCommand::insertText(*m_frame->document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
 
         // Find out what node has the composition now.
-        Position base = m_frame->selection()->base().downstream();
-        Position extent = m_frame->selection()->extent();
+        Position base = m_frame->selection().base().downstream();
+        Position extent = m_frame->selection().extent();
         Node* baseNode = base.deprecatedNode();
         unsigned baseOffset = base.deprecatedEditingOffset();
         Node* extentNode = extent.deprecatedNode();
@@ -304,15 +309,15 @@
             unsigned start = std::min(baseOffset + selectionStart, extentOffset);
             unsigned end = std::min(std::max(start, baseOffset + selectionEnd), extentOffset);
             RefPtr<Range> selectedRange = Range::create(baseNode->document(), baseNode, start, baseNode, end);
-            m_frame->selection()->setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
+            m_frame->selection().setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
         }
     }
 }
 
 void InputMethodController::setCompositionFromExistingText(const Vector<CompositionUnderline>& underlines, unsigned compositionStart, unsigned compositionEnd)
 {
-    Node* editable = m_frame->selection()->rootEditableElement();
-    Position base = m_frame->selection()->base().downstream();
+    Node* editable = m_frame->selection().rootEditableElement();
+    Position base = m_frame->selection().base().downstream();
     Node* baseNode = base.anchorNode();
     if (editable->firstChild() == baseNode && editable->lastChild() == baseNode && baseNode->isTextNode()) {
         m_compositionNode = 0;
@@ -320,7 +325,7 @@
 
         if (base.anchorType() != Position::PositionIsOffsetInAnchor)
             return;
-        if (!baseNode || baseNode != m_frame->selection()->extent().anchorNode())
+        if (!baseNode || baseNode != m_frame->selection().extent().anchorNode())
             return;
 
         m_compositionNode = toText(baseNode);
@@ -357,13 +362,13 @@
 
 PlainTextOffsets InputMethodController::getSelectionOffsets() const
 {
-    RefPtr<Range> range = m_frame->selection()->selection().firstRange();
+    RefPtr<Range> range = m_frame->selection().selection().firstRange();
     if (!range)
         return PlainTextOffsets();
     size_t location;
     size_t length;
     // FIXME: We should change TextIterator::getLocationAndLengthFromRange() returns PlainTextOffsets.
-    if (TextIterator::getLocationAndLengthFromRange(m_frame->selection()->rootEditableElementOrTreeScopeRootNode(), range.get(), location, length))
+    if (TextIterator::getLocationAndLengthFromRange(m_frame->selection().rootEditableElementOrTreeScopeRootNode(), range.get(), location, length))
         return PlainTextOffsets(location, location + length);
     return PlainTextOffsets();
 }
diff --git a/Source/core/editing/InsertIntoTextNodeCommand.cpp b/Source/core/editing/InsertIntoTextNodeCommand.cpp
index e67c6ce..906274b 100644
--- a/Source/core/editing/InsertIntoTextNodeCommand.cpp
+++ b/Source/core/editing/InsertIntoTextNodeCommand.cpp
@@ -47,9 +47,9 @@
 
 void InsertIntoTextNodeCommand::doApply()
 {
-    bool passwordEchoEnabled = document()->settings() && document()->settings()->passwordEchoEnabled();
+    bool passwordEchoEnabled = document().settings() && document().settings()->passwordEchoEnabled();
     if (passwordEchoEnabled)
-        document()->updateLayoutIgnorePendingStylesheets();
+        document().updateLayoutIgnorePendingStylesheets();
 
     if (!m_node->rendererIsEditable())
         return;
@@ -60,7 +60,7 @@
             renderText->momentarilyRevealLastTypedCharacter(m_offset + m_text.length() - 1);
     }
 
-    m_node->insertData(m_offset, m_text, IGNORE_EXCEPTION, DeprecatedAttachNow);
+    m_node->insertData(m_offset, m_text, IGNORE_EXCEPTION, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
 }
 
 void InsertIntoTextNodeCommand::doUnapply()
@@ -68,14 +68,7 @@
     if (!m_node->rendererIsEditable())
         return;
 
-    m_node->deleteData(m_offset, m_text.length(), IGNORE_EXCEPTION, DeprecatedAttachNow);
+    m_node->deleteData(m_offset, m_text.length(), IGNORE_EXCEPTION, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
 }
 
-#ifndef NDEBUG
-void InsertIntoTextNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_node.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/InsertIntoTextNodeCommand.h b/Source/core/editing/InsertIntoTextNodeCommand.h
index d8eea7a..9764aa8 100644
--- a/Source/core/editing/InsertIntoTextNodeCommand.h
+++ b/Source/core/editing/InsertIntoTextNodeCommand.h
@@ -45,10 +45,6 @@
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Text> m_node;
     unsigned m_offset;
     String m_text;
diff --git a/Source/core/editing/InsertLineBreakCommand.cpp b/Source/core/editing/InsertLineBreakCommand.cpp
index 22d9ff2..659c42d 100644
--- a/Source/core/editing/InsertLineBreakCommand.cpp
+++ b/Source/core/editing/InsertLineBreakCommand.cpp
@@ -43,7 +43,7 @@
 
 using namespace HTMLNames;
 
-InsertLineBreakCommand::InsertLineBreakCommand(Document* document)
+InsertLineBreakCommand::InsertLineBreakCommand(Document& document)
     : CompositeEditCommand(document)
 {
 }
@@ -110,7 +110,7 @@
     if (shouldUseBreakElement(pos))
         nodeToInsert = createBreakElement(document());
     else
-        nodeToInsert = document()->createTextNode("\n");
+        nodeToInsert = document().createTextNode("\n");
 
     // FIXME: Need to merge text nodes when inserting just after or before text.
 
@@ -145,7 +145,7 @@
         Position endingPosition = firstPositionInNode(textNode);
 
         // Handle whitespace that occurs after the split
-        document()->updateLayoutIgnorePendingStylesheets();
+        document().updateLayoutIgnorePendingStylesheets();
         if (!endingPosition.isRenderedCharacter()) {
             Position positionBeforeTextNode(positionInParentBeforeNode(textNode));
             // Clear out all whitespace and insert one non-breaking space
@@ -155,7 +155,7 @@
             if (textNode->inDocument())
                 insertTextIntoNode(textNode, 0, nonBreakingSpaceString());
             else {
-                RefPtr<Text> nbspNode = document()->createTextNode(nonBreakingSpaceString());
+                RefPtr<Text> nbspNode = document().createTextNode(nonBreakingSpaceString());
                 insertNodeAt(nbspNode.get(), positionBeforeTextNode);
                 endingPosition = firstPositionInNode(nbspNode.get());
             }
@@ -166,7 +166,7 @@
 
     // Handle the case where there is a typing style.
 
-    RefPtr<EditingStyle> typingStyle = document()->frame()->selection()->typingStyle();
+    RefPtr<EditingStyle> typingStyle = document().frame()->selection().typingStyle();
 
     if (typingStyle && !typingStyle->isEmpty()) {
         // Apply the typing style to the inserted line break, so that if the selection
diff --git a/Source/core/editing/InsertLineBreakCommand.h b/Source/core/editing/InsertLineBreakCommand.h
index f1f5d6b..6eee0e0 100644
--- a/Source/core/editing/InsertLineBreakCommand.h
+++ b/Source/core/editing/InsertLineBreakCommand.h
@@ -32,13 +32,13 @@
 
 class InsertLineBreakCommand : public CompositeEditCommand {
 public:
-    static PassRefPtr<InsertLineBreakCommand> create(Document* document)
+    static PassRefPtr<InsertLineBreakCommand> create(Document& document)
     {
         return adoptRef(new InsertLineBreakCommand(document));
     }
 
 private:
-    explicit InsertLineBreakCommand(Document*);
+    explicit InsertLineBreakCommand(Document&);
 
     virtual void doApply();
 
diff --git a/Source/core/editing/InsertListCommand.cpp b/Source/core/editing/InsertListCommand.cpp
index 3645f77..9a70258 100644
--- a/Source/core/editing/InsertListCommand.cpp
+++ b/Source/core/editing/InsertListCommand.cpp
@@ -46,7 +46,7 @@
     return listChild;
 }
 
-PassRefPtr<HTMLElement> InsertListCommand::insertList(Document* document, Type type)
+PassRefPtr<HTMLElement> InsertListCommand::insertList(Document& document, Type type)
 {
     RefPtr<InsertListCommand> insertCommand = create(document, type);
     insertCommand->apply();
@@ -99,7 +99,7 @@
     return true;
 }
 
-InsertListCommand::InsertListCommand(Document* document, Type type)
+InsertListCommand::InsertListCommand(Document& document, Type type)
     : CompositeEditCommand(document), m_type(type)
 {
 }
@@ -144,7 +144,7 @@
                 // infinite loop and because there is no more work to be done.
                 // FIXME(<rdar://problem/5983974>): The endingSelection() may be incorrect here.  Compute
                 // the new location of endOfSelection and use it as the end of the new selection.
-                if (!startOfLastParagraph.deepEquivalent().anchorNode()->inDocument())
+                if (!startOfLastParagraph.deepEquivalent().inDocument())
                     return;
                 setEndingSelection(startOfCurrentParagraph);
 
@@ -378,7 +378,7 @@
         // Layout is necessary since start's node's inline renderers may have been destroyed by the insertion
         // The end of the content may have changed after the insertion and layout so update it as well.
         if (insertionPos == start.deepEquivalent()) {
-            listElement->document()->updateLayoutIgnorePendingStylesheets();
+            listElement->document().updateLayoutIgnorePendingStylesheets();
             start = startOfParagraph(originalStart, CanSkipOverEditingBoundary);
             end = endOfParagraph(start, CanSkipOverEditingBoundary);
         }
diff --git a/Source/core/editing/InsertListCommand.h b/Source/core/editing/InsertListCommand.h
index 13526e1..80933b2 100644
--- a/Source/core/editing/InsertListCommand.h
+++ b/Source/core/editing/InsertListCommand.h
@@ -36,17 +36,17 @@
 public:
     enum Type { OrderedList, UnorderedList };
 
-    static PassRefPtr<InsertListCommand> create(Document* document, Type listType)
+    static PassRefPtr<InsertListCommand> create(Document& document, Type listType)
     {
         return adoptRef(new InsertListCommand(document, listType));
     }
 
-    static PassRefPtr<HTMLElement> insertList(Document*, Type);
+    static PassRefPtr<HTMLElement> insertList(Document&, Type);
 
     virtual bool preservesTypingStyle() const { return true; }
 
 private:
-    InsertListCommand(Document*, Type);
+    InsertListCommand(Document&, Type);
 
     virtual void doApply();
     virtual EditAction editingAction() const { return EditActionInsertList; }
diff --git a/Source/core/editing/InsertNodeBeforeCommand.cpp b/Source/core/editing/InsertNodeBeforeCommand.cpp
index f6872e7..16ff925 100644
--- a/Source/core/editing/InsertNodeBeforeCommand.cpp
+++ b/Source/core/editing/InsertNodeBeforeCommand.cpp
@@ -64,12 +64,4 @@
     m_insertChild->remove(IGNORE_EXCEPTION);
 }
 
-#ifndef NDEBUG
-void InsertNodeBeforeCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_insertChild.get(), nodes);
-    addNodeAndDescendants(m_refChild.get(), nodes);
-}
-#endif
-
 }
diff --git a/Source/core/editing/InsertNodeBeforeCommand.h b/Source/core/editing/InsertNodeBeforeCommand.h
index 8e4b440..6fc3b3c 100644
--- a/Source/core/editing/InsertNodeBeforeCommand.h
+++ b/Source/core/editing/InsertNodeBeforeCommand.h
@@ -44,10 +44,6 @@
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Node> m_insertChild;
     RefPtr<Node> m_refChild;
     ShouldAssumeContentIsAlwaysEditable m_shouldAssumeContentIsAlwaysEditable;
diff --git a/Source/core/editing/InsertParagraphSeparatorCommand.cpp b/Source/core/editing/InsertParagraphSeparatorCommand.cpp
index 84f830e..475bb8a 100644
--- a/Source/core/editing/InsertParagraphSeparatorCommand.cpp
+++ b/Source/core/editing/InsertParagraphSeparatorCommand.cpp
@@ -58,7 +58,7 @@
     return curBlock;
 }
 
-InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(Document *document, bool mustUseDefaultParagraphElement, bool pasteBlockqutoeIntoUnquotedArea)
+InsertParagraphSeparatorCommand::InsertParagraphSeparatorCommand(Document& document, bool mustUseDefaultParagraphElement, bool pasteBlockqutoeIntoUnquotedArea)
     : CompositeEditCommand(document)
     , m_mustUseDefaultParagraphElement(mustUseDefaultParagraphElement)
     , m_pasteBlockqutoeIntoUnquotedArea(pasteBlockqutoeIntoUnquotedArea)
@@ -81,7 +81,7 @@
 
     ASSERT(pos.isNotNull());
     m_style = EditingStyle::create(pos);
-    m_style->mergeTypingStyle(pos.anchorNode()->document());
+    m_style->mergeTypingStyle(pos.document());
 }
 
 void InsertParagraphSeparatorCommand::applyStyleAfterInsertion(Node* originalEnclosingBlock)
@@ -203,10 +203,11 @@
     if (startBlock->isRootEditableElement()) {
         blockToInsert = createDefaultParagraphElement(document());
         nestNewBlock = true;
-    } else if (shouldUseDefaultParagraphElement(startBlock.get()))
+    } else if (shouldUseDefaultParagraphElement(startBlock.get())) {
         blockToInsert = createDefaultParagraphElement(document());
-    else
+    } else {
         blockToInsert = startBlock->cloneElementWithoutChildren();
+    }
 
     //---------------------------------------------------------------------
     // Handle case when position is in the last visible position in its block,
@@ -359,7 +360,7 @@
     else
         insertNodeAfter(blockToInsert.get(), startBlock);
 
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     // If the paragraph separator was inserted at the end of a paragraph, an empty line must be
     // created.  All of the nodes, starting at visiblePos, are about to be added to the new paragraph
@@ -391,7 +392,7 @@
 
     // Handle whitespace that occurs after the split
     if (positionAfterSplit.isNotNull()) {
-        document()->updateLayoutIgnorePendingStylesheets();
+        document().updateLayoutIgnorePendingStylesheets();
         if (!positionAfterSplit.isRenderedCharacter()) {
             // Clear out all whitespace and insert one non-breaking space
             ASSERT(!positionAfterSplit.containerNode()->renderer() || positionAfterSplit.containerNode()->renderer()->style()->collapseWhiteSpace());
diff --git a/Source/core/editing/InsertParagraphSeparatorCommand.h b/Source/core/editing/InsertParagraphSeparatorCommand.h
index 006c76c..57f32b3 100644
--- a/Source/core/editing/InsertParagraphSeparatorCommand.h
+++ b/Source/core/editing/InsertParagraphSeparatorCommand.h
@@ -34,13 +34,13 @@
 
 class InsertParagraphSeparatorCommand : public CompositeEditCommand {
 public:
-    static PassRefPtr<InsertParagraphSeparatorCommand> create(Document* document, bool useDefaultParagraphElement = false, bool pasteBlockqutoeIntoUnquotedArea = false)
+    static PassRefPtr<InsertParagraphSeparatorCommand> create(Document& document, bool useDefaultParagraphElement = false, bool pasteBlockqutoeIntoUnquotedArea = false)
     {
         return adoptRef(new InsertParagraphSeparatorCommand(document, useDefaultParagraphElement, pasteBlockqutoeIntoUnquotedArea));
     }
 
 private:
-    InsertParagraphSeparatorCommand(Document*, bool useDefaultParagraphElement, bool pasteBlockqutoeIntoUnquotedArea);
+    InsertParagraphSeparatorCommand(Document&, bool useDefaultParagraphElement, bool pasteBlockqutoeIntoUnquotedArea);
 
     virtual void doApply();
 
diff --git a/Source/core/editing/InsertTextCommand.cpp b/Source/core/editing/InsertTextCommand.cpp
index 092578c..2e3c45f 100644
--- a/Source/core/editing/InsertTextCommand.cpp
+++ b/Source/core/editing/InsertTextCommand.cpp
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-InsertTextCommand::InsertTextCommand(Document* document, const String& text, bool selectInsertedText, RebalanceType rebalanceType)
+InsertTextCommand::InsertTextCommand(Document& document, const String& text, bool selectInsertedText, RebalanceType rebalanceType)
     : CompositeEditCommand(document)
     , m_text(text)
     , m_selectInsertedText(selectInsertedText)
@@ -44,7 +44,7 @@
 {
 }
 
-InsertTextCommand::InsertTextCommand(Document* document, const String& text, PassRefPtr<TextInsertionMarkerSupplier> markerSupplier)
+InsertTextCommand::InsertTextCommand(Document& document, const String& text, PassRefPtr<TextInsertionMarkerSupplier> markerSupplier)
     : CompositeEditCommand(document)
     , m_text(text)
     , m_selectInsertedText(false)
@@ -57,7 +57,7 @@
 {
     Position pos = p;
     if (isTabSpanTextNode(pos.anchorNode())) {
-        RefPtr<Node> textNode = document()->createEditingTextNode("");
+        RefPtr<Node> textNode = document().createEditingTextNode("");
         insertNodeAtTabSpanPosition(textNode.get(), pos);
         return firstPositionInNode(textNode.get());
     }
@@ -65,7 +65,7 @@
     // Prepare for text input by looking at the specified position.
     // It may be necessary to insert a text node to receive characters.
     if (!pos.containerNode()->isTextNode()) {
-        RefPtr<Node> textNode = document()->createEditingTextNode("");
+        RefPtr<Node> textNode = document().createEditingTextNode("");
         insertNodeAt(textNode.get(), pos);
         return firstPositionInNode(textNode.get());
     }
@@ -145,7 +145,7 @@
         // anything other than NoSelection. The rest of this function requires a real endingSelection, so bail out.
         if (endingSelection().isNone())
             return;
-    } else if (document()->frame()->editor().isOverwriteModeEnabled()) {
+    } else if (document().frame()->editor().isOverwriteModeEnabled()) {
         if (performOverwrite(m_text, m_selectInsertedText))
             return;
     }
@@ -175,7 +175,7 @@
     // and so deleteInsignificantText could remove it.  Save the position before the node in case that happens.
     Position positionBeforeStartNode(positionInParentBeforeNode(startPosition.containerNode()));
     deleteInsignificantText(startPosition.upstream(), startPosition.downstream());
-    if (!startPosition.anchorNode()->inDocument())
+    if (!startPosition.inDocument())
         startPosition = positionBeforeStartNode;
     if (!startPosition.isCandidate())
         startPosition = startPosition.downstream();
@@ -221,7 +221,7 @@
     setEndingSelectionWithoutValidation(startPosition, endPosition);
 
     // Handle the case where there is a typing style.
-    if (RefPtr<EditingStyle> typingStyle = document()->frame()->selection()->typingStyle()) {
+    if (RefPtr<EditingStyle> typingStyle = document().frame()->selection().typingStyle()) {
         typingStyle->prepareToApplyAt(endPosition, EditingStyle::PreserveWritingDirection);
         if (!typingStyle->isEmpty())
             applyStyle(typingStyle.get());
diff --git a/Source/core/editing/InsertTextCommand.h b/Source/core/editing/InsertTextCommand.h
index 3663bc4..10c8d80 100644
--- a/Source/core/editing/InsertTextCommand.h
+++ b/Source/core/editing/InsertTextCommand.h
@@ -48,21 +48,21 @@
         RebalanceAllWhitespaces
     };
 
-    static PassRefPtr<InsertTextCommand> create(Document* document, const String& text, bool selectInsertedText = false,
+    static PassRefPtr<InsertTextCommand> create(Document& document, const String& text, bool selectInsertedText = false,
         RebalanceType rebalanceType = RebalanceLeadingAndTrailingWhitespaces)
     {
         return adoptRef(new InsertTextCommand(document, text, selectInsertedText, rebalanceType));
     }
 
-    static PassRefPtr<InsertTextCommand> createWithMarkerSupplier(Document* document, const String& text, PassRefPtr<TextInsertionMarkerSupplier> markerSupplier)
+    static PassRefPtr<InsertTextCommand> createWithMarkerSupplier(Document& document, const String& text, PassRefPtr<TextInsertionMarkerSupplier> markerSupplier)
     {
         return adoptRef(new InsertTextCommand(document, text, markerSupplier));
     }
 
 private:
 
-    InsertTextCommand(Document*, const String& text, bool selectInsertedText, RebalanceType);
-    InsertTextCommand(Document*, const String& text, PassRefPtr<TextInsertionMarkerSupplier>);
+    InsertTextCommand(Document&, const String& text, bool selectInsertedText, RebalanceType);
+    InsertTextCommand(Document&, const String& text, PassRefPtr<TextInsertionMarkerSupplier>);
 
     void deleteCharacter();
 
diff --git a/Source/core/editing/MarkupAccumulator.cpp b/Source/core/editing/MarkupAccumulator.cpp
index cd5b7cf..1ccbc83 100644
--- a/Source/core/editing/MarkupAccumulator.cpp
+++ b/Source/core/editing/MarkupAccumulator.cpp
@@ -138,7 +138,7 @@
     if (!childrenOnly)
         appendStartTag(targetNode, &namespaceHash);
 
-    if (!(targetNode->document()->isHTMLDocument() && elementCannotHaveEndTag(targetNode))) {
+    if (!(targetNode->document().isHTMLDocument() && elementCannotHaveEndTag(targetNode))) {
         Node* current = targetNode->hasTagName(templateTag) ? toHTMLTemplateElement(targetNode)->content()->firstChild() : targetNode->firstChild();
         for ( ; current; current = current->nextSibling())
             serializeNodesWithNamespaces(current, IncludeNode, &namespaceHash, tagNamesToSkip);
@@ -152,11 +152,11 @@
 {
     switch (m_resolveURLsMethod) {
     case ResolveAllURLs:
-        return element->document()->completeURL(urlString).string();
+        return element->document().completeURL(urlString).string();
 
     case ResolveNonLocalURLs:
-        if (!element->document()->url().isLocalFile())
-            return element->document()->completeURL(urlString).string();
+        if (!element->document().url().isLocalFile())
+            return element->document().completeURL(urlString).string();
         break;
 
     case DoNotResolveURLs:
@@ -310,7 +310,7 @@
     if (parentName && (*parentName == scriptTag || *parentName == styleTag || *parentName == xmpTag))
         return EntityMaskInCDATA;
 
-    return text->document()->isHTMLDocument() ? EntityMaskInHTMLPCDATA : EntityMaskInPCDATA;
+    return text->document().isHTMLDocument() ? EntityMaskInHTMLPCDATA : EntityMaskInPCDATA;
 }
 
 void MarkupAccumulator::appendText(StringBuilder& result, Text* text)
@@ -412,7 +412,7 @@
 {
     result.append('<');
     result.append(element->nodeNamePreservingCase());
-    if (!element->document()->isHTMLDocument() && namespaces && shouldAddNamespaceElement(element))
+    if (!element->document().isHTMLDocument() && namespaces && shouldAddNamespaceElement(element))
         appendNamespace(result, element->prefix(), element->namespaceURI(), *namespaces);
 }
 
@@ -435,7 +435,7 @@
 
 void MarkupAccumulator::appendAttribute(StringBuilder& result, Element* element, const Attribute& attribute, Namespaces* namespaces)
 {
-    bool documentIsHTML = element->document()->isHTMLDocument();
+    bool documentIsHTML = element->document().isHTMLDocument();
 
     result.append(' ');
 
@@ -485,7 +485,7 @@
         appendText(result, toText(const_cast<Node*>(node)));
         break;
     case Node::COMMENT_NODE:
-        appendComment(result, static_cast<const Comment*>(node)->data());
+        appendComment(result, toComment(node)->data());
         break;
     case Node::DOCUMENT_NODE:
         appendXMLDeclaration(result, toDocument(node));
@@ -493,16 +493,16 @@
     case Node::DOCUMENT_FRAGMENT_NODE:
         break;
     case Node::DOCUMENT_TYPE_NODE:
-        appendDocumentType(result, static_cast<const DocumentType*>(node));
+        appendDocumentType(result, toDocumentType(node));
         break;
     case Node::PROCESSING_INSTRUCTION_NODE:
-        appendProcessingInstruction(result, static_cast<const ProcessingInstruction*>(node)->target(), static_cast<const ProcessingInstruction*>(node)->data());
+        appendProcessingInstruction(result, toProcessingInstruction(node)->target(), toProcessingInstruction(node)->data());
         break;
     case Node::ELEMENT_NODE:
         appendElement(result, toElement(const_cast<Node*>(node)), namespaces);
         break;
     case Node::CDATA_SECTION_NODE:
-        appendCDATASection(result, static_cast<const CDATASection*>(node)->data());
+        appendCDATASection(result, toCDATASection(node)->data());
         break;
     case Node::ATTRIBUTE_NODE:
     case Node::ENTITY_NODE:
@@ -520,7 +520,7 @@
 // 4. Other elements self-close.
 bool MarkupAccumulator::shouldSelfClose(const Node* node)
 {
-    if (node->document()->isHTMLDocument())
+    if (node->document().isHTMLDocument())
         return false;
     if (node->hasChildNodes())
         return false;
@@ -538,7 +538,7 @@
     // ieForbidsInsertHTML is used to disallow setting innerHTML/outerHTML
     // or createContextualFragment.  It does not necessarily align with
     // which elements should be serialized w/o end tags.
-    return static_cast<const HTMLElement*>(node)->ieForbidsInsertHTML();
+    return toHTMLElement(node)->ieForbidsInsertHTML();
 }
 
 void MarkupAccumulator::appendEndMarkup(StringBuilder& result, const Node* node)
diff --git a/Source/core/editing/MergeIdenticalElementsCommand.cpp b/Source/core/editing/MergeIdenticalElementsCommand.cpp
index e94a7fb..2ae2dbb 100644
--- a/Source/core/editing/MergeIdenticalElementsCommand.cpp
+++ b/Source/core/editing/MergeIdenticalElementsCommand.cpp
@@ -86,12 +86,4 @@
         m_element1->appendChild(children[i].release(), es);
 }
 
-#ifndef NDEBUG
-void MergeIdenticalElementsCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_element1.get(), nodes);
-    addNodeAndDescendants(m_element2.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/MergeIdenticalElementsCommand.h b/Source/core/editing/MergeIdenticalElementsCommand.h
index 0b1003d..42dd8a8 100644
--- a/Source/core/editing/MergeIdenticalElementsCommand.h
+++ b/Source/core/editing/MergeIdenticalElementsCommand.h
@@ -43,10 +43,6 @@
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Element> m_element1;
     RefPtr<Element> m_element2;
     RefPtr<Node> m_atChild;
diff --git a/Source/core/editing/ModifySelectionListLevel.cpp b/Source/core/editing/ModifySelectionListLevel.cpp
index f0e5f64..671abea 100644
--- a/Source/core/editing/ModifySelectionListLevel.cpp
+++ b/Source/core/editing/ModifySelectionListLevel.cpp
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-ModifySelectionListLevelCommand::ModifySelectionListLevelCommand(Document* document)
+ModifySelectionListLevelCommand::ModifySelectionListLevelCommand(Document& document)
     : CompositeEditCommand(document)
 {
 }
@@ -134,7 +134,7 @@
     }
 }
 
-IncreaseSelectionListLevelCommand::IncreaseSelectionListLevelCommand(Document* document, Type listType)
+IncreaseSelectionListLevelCommand::IncreaseSelectionListLevelCommand(Document& document, Type listType)
     : ModifySelectionListLevelCommand(document)
     , m_listType(listType)
 {
@@ -202,38 +202,37 @@
     }
 }
 
-bool IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(Document* document)
+bool IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(Document& document)
 {
     Node* startListChild;
     Node* endListChild;
-    return canIncreaseListLevel(document->frame()->selection()->selection(), startListChild, endListChild);
+    return canIncreaseListLevel(document.frame()->selection().selection(), startListChild, endListChild);
 }
 
-PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevel(Document* document, Type type)
+PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevel(Document& document, Type type)
 {
-    ASSERT(document);
-    ASSERT(document->frame());
+    ASSERT(document.frame());
     RefPtr<IncreaseSelectionListLevelCommand> command = create(document, type);
     command->apply();
     return command->m_listElement.release();
 }
 
-PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevel(Document* document)
+PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevel(Document& document)
 {
     return increaseSelectionListLevel(document, InheritedListType);
 }
 
-PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(Document* document)
+PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(Document& document)
 {
     return increaseSelectionListLevel(document, OrderedList);
 }
 
-PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(Document* document)
+PassRefPtr<Node> IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(Document& document)
 {
     return increaseSelectionListLevel(document, UnorderedList);
 }
 
-DecreaseSelectionListLevelCommand::DecreaseSelectionListLevelCommand(Document* document)
+DecreaseSelectionListLevelCommand::DecreaseSelectionListLevelCommand(Document& document)
     : ModifySelectionListLevelCommand(document)
 {
 }
@@ -278,18 +277,17 @@
     }
 }
 
-bool DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(Document* document)
+bool DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(Document& document)
 {
     Node* startListChild;
     Node* endListChild;
-    return canDecreaseListLevel(document->frame()->selection()->selection(), startListChild, endListChild);
+    return canDecreaseListLevel(document.frame()->selection().selection(), startListChild, endListChild);
 }
 
-void DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(Document* document)
+void DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(Document& document)
 {
-    ASSERT(document);
-    ASSERT(document->frame());
-    applyCommand(create(document));
+    ASSERT(document.frame());
+    create(document)->apply();
 }
 
 }
diff --git a/Source/core/editing/ModifySelectionListLevel.h b/Source/core/editing/ModifySelectionListLevel.h
index 9c2f5e7..b870728 100644
--- a/Source/core/editing/ModifySelectionListLevel.h
+++ b/Source/core/editing/ModifySelectionListLevel.h
@@ -35,7 +35,7 @@
 // It is not used on its own.
 class ModifySelectionListLevelCommand : public CompositeEditCommand {
 protected:
-    explicit ModifySelectionListLevelCommand(Document*);
+    explicit ModifySelectionListLevelCommand(Document&);
 
     void appendSiblingNodeRange(Node* startNode, Node* endNode, Element* newParent);
     void insertSiblingNodeRangeBefore(Node* startNode, Node* endNode, Node* refNode);
@@ -48,21 +48,21 @@
 // IncreaseSelectionListLevelCommand moves the selected list items one level deeper.
 class IncreaseSelectionListLevelCommand : public ModifySelectionListLevelCommand {
 public:
-    static bool canIncreaseSelectionListLevel(Document*);
-    static PassRefPtr<Node> increaseSelectionListLevel(Document*);
-    static PassRefPtr<Node> increaseSelectionListLevelOrdered(Document*);
-    static PassRefPtr<Node> increaseSelectionListLevelUnordered(Document*);
+    static bool canIncreaseSelectionListLevel(Document&);
+    static PassRefPtr<Node> increaseSelectionListLevel(Document&);
+    static PassRefPtr<Node> increaseSelectionListLevelOrdered(Document&);
+    static PassRefPtr<Node> increaseSelectionListLevelUnordered(Document&);
 
 private:
     enum Type { InheritedListType, OrderedList, UnorderedList };
-    static PassRefPtr<Node> increaseSelectionListLevel(Document*, Type);
+    static PassRefPtr<Node> increaseSelectionListLevel(Document&, Type);
 
-    static PassRefPtr<IncreaseSelectionListLevelCommand> create(Document* document, Type type)
+    static PassRefPtr<IncreaseSelectionListLevelCommand> create(Document& document, Type type)
     {
         return adoptRef(new IncreaseSelectionListLevelCommand(document, type));
     }
 
-    IncreaseSelectionListLevelCommand(Document*, Type);
+    IncreaseSelectionListLevelCommand(Document&, Type);
 
     virtual void doApply();
 
@@ -73,16 +73,16 @@
 // DecreaseSelectionListLevelCommand moves the selected list items one level shallower.
 class DecreaseSelectionListLevelCommand : public ModifySelectionListLevelCommand {
 public:
-    static bool canDecreaseSelectionListLevel(Document*);
-    static void decreaseSelectionListLevel(Document*);
+    static bool canDecreaseSelectionListLevel(Document&);
+    static void decreaseSelectionListLevel(Document&);
 
 private:
-    static PassRefPtr<DecreaseSelectionListLevelCommand> create(Document* document)
+    static PassRefPtr<DecreaseSelectionListLevelCommand> create(Document& document)
     {
         return adoptRef(new DecreaseSelectionListLevelCommand(document));
     }
 
-    explicit DecreaseSelectionListLevelCommand(Document*);
+    explicit DecreaseSelectionListLevelCommand(Document&);
 
     virtual void doApply();
 };
diff --git a/Source/core/editing/MoveSelectionCommand.cpp b/Source/core/editing/MoveSelectionCommand.cpp
index 4fad6f0..7d45d37 100644
--- a/Source/core/editing/MoveSelectionCommand.cpp
+++ b/Source/core/editing/MoveSelectionCommand.cpp
@@ -32,7 +32,7 @@
 namespace WebCore {
 
 MoveSelectionCommand::MoveSelectionCommand(PassRefPtr<DocumentFragment> fragment, const Position& position, bool smartInsert, bool smartDelete)
-    : CompositeEditCommand(position.anchorNode()->document()), m_fragment(fragment), m_position(position), m_smartInsert(smartInsert), m_smartDelete(smartDelete)
+    : CompositeEditCommand(*position.document()), m_fragment(fragment), m_position(position), m_smartInsert(smartInsert), m_smartDelete(smartDelete)
 {
     ASSERT(m_fragment);
 }
@@ -62,13 +62,13 @@
     // set the destination to the ending point after the deletion.
     // Fixes: <rdar://problem/3910425> REGRESSION (Mail): Crash in ReplaceSelectionCommand;
     //        selection is empty, leading to null deref
-    if (!pos.anchorNode()->inDocument())
+    if (!pos.inDocument())
         pos = endingSelection().start();
 
     cleanupAfterDeletion(pos);
 
     setEndingSelection(VisibleSelection(pos, endingSelection().affinity(), endingSelection().isDirectional()));
-    if (!pos.anchorNode()->inDocument()) {
+    if (!pos.inDocument()) {
         // Document was modified out from under us.
         return;
     }
diff --git a/Source/core/editing/RemoveCSSPropertyCommand.cpp b/Source/core/editing/RemoveCSSPropertyCommand.cpp
index ebb6d0b..6daa841 100644
--- a/Source/core/editing/RemoveCSSPropertyCommand.cpp
+++ b/Source/core/editing/RemoveCSSPropertyCommand.cpp
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(Document* document, PassRefPtr<Element> element, CSSPropertyID property)
+RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(Document& document, PassRefPtr<Element> element, CSSPropertyID property)
     : SimpleEditCommand(document)
     , m_element(element)
     , m_property(property)
@@ -63,11 +63,4 @@
     m_element->style()->setPropertyInternal(m_property, m_oldValue, m_important, IGNORE_EXCEPTION);
 }
 
-#ifndef NDEBUG
-void RemoveCSSPropertyCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_element.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/RemoveCSSPropertyCommand.h b/Source/core/editing/RemoveCSSPropertyCommand.h
index 7bdf5ad..85d6156 100644
--- a/Source/core/editing/RemoveCSSPropertyCommand.h
+++ b/Source/core/editing/RemoveCSSPropertyCommand.h
@@ -35,22 +35,18 @@
 
 class RemoveCSSPropertyCommand : public SimpleEditCommand {
 public:
-    static PassRefPtr<RemoveCSSPropertyCommand> create(Document* document, PassRefPtr<Element> element, CSSPropertyID property)
+    static PassRefPtr<RemoveCSSPropertyCommand> create(Document& document, PassRefPtr<Element> element, CSSPropertyID property)
     {
         return adoptRef(new RemoveCSSPropertyCommand(document, element, property));
     }
 
 private:
-    RemoveCSSPropertyCommand(Document*, PassRefPtr<Element>, CSSPropertyID);
+    RemoveCSSPropertyCommand(Document&, PassRefPtr<Element>, CSSPropertyID);
     ~RemoveCSSPropertyCommand();
 
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Element> m_element;
     CSSPropertyID m_property;
     String m_oldValue;
diff --git a/Source/core/editing/RemoveFormatCommand.cpp b/Source/core/editing/RemoveFormatCommand.cpp
index 3644d32..48bff2b 100644
--- a/Source/core/editing/RemoveFormatCommand.cpp
+++ b/Source/core/editing/RemoveFormatCommand.cpp
@@ -40,7 +40,7 @@
 
 using namespace HTMLNames;
 
-RemoveFormatCommand::RemoveFormatCommand(Document* document)
+RemoveFormatCommand::RemoveFormatCommand(Document& document)
     : CompositeEditCommand(document)
 {
 }
@@ -79,14 +79,14 @@
 
 void RemoveFormatCommand::doApply()
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
 
-    if (!frame->selection()->selection().isNonOrphanedCaretOrRange())
+    if (!frame->selection().selection().isNonOrphanedCaretOrRange())
         return;
 
     // Get the default style for this editable root, it's the style that we'll give the
     // content that we're operating on.
-    Node* root = frame->selection()->rootEditableElement();
+    Node* root = frame->selection().rootEditableElement();
     RefPtr<EditingStyle> defaultStyle = EditingStyle::create(root);
 
     // We want to remove everything but transparent background.
diff --git a/Source/core/editing/RemoveFormatCommand.h b/Source/core/editing/RemoveFormatCommand.h
index d8032ea..f6d030d 100644
--- a/Source/core/editing/RemoveFormatCommand.h
+++ b/Source/core/editing/RemoveFormatCommand.h
@@ -32,13 +32,13 @@
 
 class RemoveFormatCommand : public CompositeEditCommand {
 public:
-    static PassRefPtr<RemoveFormatCommand> create(Document* document)
+    static PassRefPtr<RemoveFormatCommand> create(Document& document)
     {
         return adoptRef(new RemoveFormatCommand(document));
     }
 
 private:
-    explicit RemoveFormatCommand(Document*);
+    explicit RemoveFormatCommand(Document&);
 
     virtual void doApply();
     virtual EditAction editingAction() const { return EditActionUnspecified; }
diff --git a/Source/core/editing/RemoveNodeCommand.cpp b/Source/core/editing/RemoveNodeCommand.cpp
index 8f269ef..0640559 100644
--- a/Source/core/editing/RemoveNodeCommand.cpp
+++ b/Source/core/editing/RemoveNodeCommand.cpp
@@ -65,13 +65,4 @@
     parent->insertBefore(m_node.get(), refChild.get(), IGNORE_EXCEPTION);
 }
 
-#ifndef NDEBUG
-void RemoveNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_parent.get(), nodes);
-    addNodeAndDescendants(m_refChild.get(), nodes);
-    addNodeAndDescendants(m_node.get(), nodes);
-}
-#endif
-
 }
diff --git a/Source/core/editing/RemoveNodeCommand.h b/Source/core/editing/RemoveNodeCommand.h
index d34fe2e..5d15512 100644
--- a/Source/core/editing/RemoveNodeCommand.h
+++ b/Source/core/editing/RemoveNodeCommand.h
@@ -43,10 +43,6 @@
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Node> m_node;
     RefPtr<ContainerNode> m_parent;
     RefPtr<Node> m_refChild;
diff --git a/Source/core/editing/ReplaceNodeWithSpanCommand.cpp b/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
index e09b6a1..6274c07 100644
--- a/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
+++ b/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
@@ -81,12 +81,4 @@
     swapInNodePreservingAttributesAndChildren(m_elementToReplace.get(), m_spanElement.get());
 }
 
-#ifndef NDEBUG
-void ReplaceNodeWithSpanCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_elementToReplace.get(), nodes);
-    addNodeAndDescendants(m_spanElement.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/ReplaceNodeWithSpanCommand.h b/Source/core/editing/ReplaceNodeWithSpanCommand.h
index 4282b2c..e9e8afe 100644
--- a/Source/core/editing/ReplaceNodeWithSpanCommand.h
+++ b/Source/core/editing/ReplaceNodeWithSpanCommand.h
@@ -53,10 +53,6 @@
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<HTMLElement> m_elementToReplace;
     RefPtr<HTMLElement> m_spanElement;
 };
diff --git a/Source/core/editing/ReplaceSelectionCommand.cpp b/Source/core/editing/ReplaceSelectionCommand.cpp
index 8e97453..16b7262 100644
--- a/Source/core/editing/ReplaceSelectionCommand.cpp
+++ b/Source/core/editing/ReplaceSelectionCommand.cpp
@@ -105,8 +105,7 @@
 static bool isInterchangeConvertedSpaceSpan(const Node *node)
 {
     DEFINE_STATIC_LOCAL(String, convertedSpaceSpanClassString, (AppleConvertedSpace));
-    return node->isHTMLElement() &&
-           static_cast<const HTMLElement *>(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
+    return node->isHTMLElement() && toHTMLElement(node)->getAttribute(classAttr) == convertedSpaceSpanClassString;
 }
 
 static Position positionAvoidingPrecedingNodes(Position pos)
@@ -246,7 +245,8 @@
 
 PassRefPtr<Element> ReplacementFragment::insertFragmentForTestRendering(Node* rootEditableElement)
 {
-    RefPtr<Element> holder = createDefaultParagraphElement(m_document.get());
+    ASSERT(m_document);
+    RefPtr<Element> holder = createDefaultParagraphElement(*m_document.get());
 
     holder->appendChild(m_fragment);
     rootEditableElement->appendChild(holder.get());
@@ -360,7 +360,7 @@
         m_lastNodeInserted = newNode;
 }
 
-ReplaceSelectionCommand::ReplaceSelectionCommand(Document* document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
+ReplaceSelectionCommand::ReplaceSelectionCommand(Document& document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
     : CompositeEditCommand(document)
     , m_selectReplacement(options & SelectReplacement)
     , m_smartReplace(options & SmartReplace)
@@ -503,7 +503,7 @@
             // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
             Node* blockquoteNode = !context || isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
             if (blockquoteNode)
-                newInlineStyle->removeStyleFromRulesAndContext(element, document()->documentElement());
+                newInlineStyle->removeStyleFromRulesAndContext(element, document().documentElement());
 
             newInlineStyle->removeStyleFromRulesAndContext(element, context);
         }
@@ -665,7 +665,7 @@
 
 void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds(InsertedNodes& insertedNodes)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     Node* lastLeafInserted = insertedNodes.lastLeafInserted();
     if (lastLeafInserted && lastLeafInserted->isTextNode() && !nodeHasVisibleRenderText(toText(lastLeafInserted))
@@ -774,7 +774,7 @@
     // styles from blockquoteNode are allowed to override those from the source document, see <rdar://problem/4930986> and <rdar://problem/5089327>.
     Node* blockquoteNode = isMailPasteAsQuotationNode(context) ? context : enclosingNodeOfType(firstPositionInNode(context), isMailBlockquote, CanCrossEditingBoundary);
     if (blockquoteNode)
-        context = document()->documentElement();
+        context = document().documentElement();
 
     // This operation requires that only editing styles to be removed from sourceDocumentStyle.
     style->prepareToApplyAt(firstPositionInNode(context));
@@ -863,7 +863,7 @@
 
     // We can skip over elements whose class attribute is
     // one of our internal classes.
-    const HTMLElement* element = static_cast<const HTMLElement*>(node);
+    const HTMLElement* element = toHTMLElement(node);
     const AtomicString& classAttributeValue = element->getAttribute(classAttr);
     if (classAttributeValue == AppleTabSpanClass
         || classAttributeValue == AppleConvertedSpace
@@ -890,7 +890,7 @@
     if (!selection.rootEditableElement())
         return;
 
-    ReplacementFragment fragment(document(), m_documentFragment.get(), selection);
+    ReplacementFragment fragment(&document(), m_documentFragment.get(), selection);
     if (performTrivialReplace(fragment))
         return;
 
@@ -901,7 +901,7 @@
 
     if (m_matchStyle) {
         m_insertionStyle = EditingStyle::create(selection.start());
-        m_insertionStyle->mergeTypingStyle(document());
+        m_insertionStyle->mergeTypingStyle(&document());
     }
 
     VisiblePosition visibleStart = selection.visibleStart();
@@ -1010,8 +1010,8 @@
 
     // FIXME: Can this wait until after the operation has been performed?  There doesn't seem to be
     // any work performed after this that queries or uses the typing style.
-    if (Frame* frame = document()->frame())
-        frame->selection()->clearTypingStyle();
+    if (Frame* frame = document().frame())
+        frame->selection().clearTypingStyle();
 
     removeHeadContents(fragment);
 
@@ -1164,7 +1164,7 @@
         if (startOfParagraph(endOfInsertedContent) == startOfParagraphToMove) {
             insertNodeAt(createBreakElement(document()).get(), endOfInsertedContent.deepEquivalent());
             // Mutation events (bug 22634) triggered by inserting the <br> might have removed the content we're about to move
-            if (!startOfParagraphToMove.deepEquivalent().anchorNode()->inDocument())
+            if (!startOfParagraphToMove.deepEquivalent().inDocument())
                 return;
         }
 
@@ -1234,7 +1234,7 @@
         return false;
 
     // Remove the br if it is collapsed away and so is unnecessary.
-    if (!document()->inNoQuirksMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
+    if (!document().inNoQuirksMode() && isEndOfBlock(visiblePos) && !isStartOfParagraph(visiblePos))
         return true;
 
     // A br that was originally holding a line open should be displaced by inserted content or turned into a line break.
@@ -1280,13 +1280,13 @@
             if (m_endOfInsertedContent.containerNode() == endNode)
                 m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
         } else {
-            RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
+            RefPtr<Node> node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
             insertNodeAfter(node, endNode);
             updateNodesInserted(node.get());
         }
     }
 
-    document()->updateLayout();
+    document().updateLayout();
 
     Position startDownstream = startOfInsertedContent.deepEquivalent().downstream();
     Node* startNode = startDownstream.computeNodeAfterPosition();
@@ -1304,7 +1304,7 @@
             if (m_endOfInsertedContent.containerNode() == startNode && m_endOfInsertedContent.offsetInContainerNode())
                 m_endOfInsertedContent.moveToOffset(m_endOfInsertedContent.offsetInContainerNode() + 1);
         } else {
-            RefPtr<Node> node = document()->createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
+            RefPtr<Node> node = document().createEditingTextNode(collapseWhiteSpace ? nonBreakingSpaceString() : " ");
             // Don't updateNodesInserted. Doing so would set m_endOfInsertedContent to be the node containing the leading space,
             // but m_endOfInsertedContent is supposed to mark the end of pasted content.
             insertNodeBefore(node, startNode);
diff --git a/Source/core/editing/ReplaceSelectionCommand.h b/Source/core/editing/ReplaceSelectionCommand.h
index fce407d..b6eacc7 100644
--- a/Source/core/editing/ReplaceSelectionCommand.h
+++ b/Source/core/editing/ReplaceSelectionCommand.h
@@ -47,13 +47,13 @@
 
     typedef unsigned CommandOptions;
 
-    static PassRefPtr<ReplaceSelectionCommand> create(Document* document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction action = EditActionPaste)
+    static PassRefPtr<ReplaceSelectionCommand> create(Document& document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction action = EditActionPaste)
     {
         return adoptRef(new ReplaceSelectionCommand(document, fragment, options, action));
     }
 
 private:
-    ReplaceSelectionCommand(Document*, PassRefPtr<DocumentFragment>, CommandOptions, EditAction);
+    ReplaceSelectionCommand(Document&, PassRefPtr<DocumentFragment>, CommandOptions, EditAction);
 
     virtual void doApply();
     virtual EditAction editingAction() const;
diff --git a/Source/core/editing/SetNodeAttributeCommand.cpp b/Source/core/editing/SetNodeAttributeCommand.cpp
index 1218e02..b4bd12f 100644
--- a/Source/core/editing/SetNodeAttributeCommand.cpp
+++ b/Source/core/editing/SetNodeAttributeCommand.cpp
@@ -54,11 +54,4 @@
     m_oldValue = nullString;
 }
 
-#ifndef NDEBUG
-void SetNodeAttributeCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_element.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/SetNodeAttributeCommand.h b/Source/core/editing/SetNodeAttributeCommand.h
index 6c218c5..5716b61 100644
--- a/Source/core/editing/SetNodeAttributeCommand.h
+++ b/Source/core/editing/SetNodeAttributeCommand.h
@@ -44,10 +44,6 @@
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Element> m_element;
     QualifiedName m_attribute;
     AtomicString m_value;
diff --git a/Source/core/editing/SetSelectionCommand.cpp b/Source/core/editing/SetSelectionCommand.cpp
index acf7e24..48c86bf 100644
--- a/Source/core/editing/SetSelectionCommand.cpp
+++ b/Source/core/editing/SetSelectionCommand.cpp
@@ -32,7 +32,7 @@
 namespace WebCore {
 
 SetSelectionCommand::SetSelectionCommand(const VisibleSelection& selection, FrameSelection::SetSelectionOptions options)
-    : SimpleEditCommand(selection.base().anchorNode()->document())
+    : SimpleEditCommand(*selection.base().document())
     , m_options(options)
     , m_selectionToSet(selection)
 {
@@ -40,22 +40,18 @@
 
 void SetSelectionCommand::doApply()
 {
-    FrameSelection* selection = document()->frame()->selection();
-    ASSERT(selection);
-
-    if (selection->shouldChangeSelection(m_selectionToSet) && m_selectionToSet.isNonOrphanedCaretOrRange()) {
-        selection->setSelection(m_selectionToSet, m_options);
+    FrameSelection& selection = document().frame()->selection();
+    if (selection.shouldChangeSelection(m_selectionToSet) && m_selectionToSet.isNonOrphanedCaretOrRange()) {
+        selection.setSelection(m_selectionToSet, m_options);
         setEndingSelection(m_selectionToSet);
     }
 }
 
 void SetSelectionCommand::doUnapply()
 {
-    FrameSelection* selection = document()->frame()->selection();
-    ASSERT(selection);
-
-    if (selection->shouldChangeSelection(startingSelection()) && startingSelection().isNonOrphanedCaretOrRange())
-        selection->setSelection(startingSelection(), m_options);
+    FrameSelection& selection = document().frame()->selection();
+    if (selection.shouldChangeSelection(startingSelection()) && startingSelection().isNonOrphanedCaretOrRange())
+        selection.setSelection(startingSelection(), m_options);
 }
 
 } // namespace WebCore
diff --git a/Source/core/editing/SetSelectionCommand.h b/Source/core/editing/SetSelectionCommand.h
index 2ba2014..b4f09af 100644
--- a/Source/core/editing/SetSelectionCommand.h
+++ b/Source/core/editing/SetSelectionCommand.h
@@ -44,10 +44,6 @@
     virtual void doApply() OVERRIDE;
     virtual void doUnapply() OVERRIDE;
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE { }
-#endif
-
     FrameSelection::SetSelectionOptions m_options;
     VisibleSelection m_selectionToSet;
 };
diff --git a/Source/core/editing/SimplifyMarkupCommand.cpp b/Source/core/editing/SimplifyMarkupCommand.cpp
index 67defe9..4e5fdf7 100644
--- a/Source/core/editing/SimplifyMarkupCommand.cpp
+++ b/Source/core/editing/SimplifyMarkupCommand.cpp
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-SimplifyMarkupCommand::SimplifyMarkupCommand(Document* document, Node* firstNode, Node* nodeAfterLast)
+SimplifyMarkupCommand::SimplifyMarkupCommand(Document& document, Node* firstNode, Node* nodeAfterLast)
     : CompositeEditCommand(document), m_firstNode(firstNode), m_nodeAfterLast(nodeAfterLast)
 {
 }
diff --git a/Source/core/editing/SimplifyMarkupCommand.h b/Source/core/editing/SimplifyMarkupCommand.h
index 8cb3f36..3da2a62 100644
--- a/Source/core/editing/SimplifyMarkupCommand.h
+++ b/Source/core/editing/SimplifyMarkupCommand.h
@@ -32,13 +32,13 @@
 
 class SimplifyMarkupCommand : public CompositeEditCommand {
 public:
-    static PassRefPtr<SimplifyMarkupCommand> create(Document* document, Node* firstNode, Node* nodeAfterLast)
+    static PassRefPtr<SimplifyMarkupCommand> create(Document& document, Node* firstNode, Node* nodeAfterLast)
     {
         return adoptRef(new SimplifyMarkupCommand(document, firstNode, nodeAfterLast));
     }
 
 private:
-    SimplifyMarkupCommand(Document*, Node* firstNode, Node* nodeAfterLast);
+    SimplifyMarkupCommand(Document&, Node* firstNode, Node* nodeAfterLast);
 
     virtual void doApply();
     int pruneSubsequentAncestorsToRemove(Vector<RefPtr<Node> >& nodesToRemove, size_t startNodeIndex);
diff --git a/Source/core/editing/SpellCheckRequester.cpp b/Source/core/editing/SpellCheckRequester.cpp
index f68d89e..5bc37bf 100644
--- a/Source/core/editing/SpellCheckRequester.cpp
+++ b/Source/core/editing/SpellCheckRequester.cpp
@@ -71,7 +71,7 @@
     if (!text.length())
         return PassRefPtr<SpellCheckRequest>();
 
-    const Vector<DocumentMarker*>& markers = checkingRange->ownerDocument()->markers()->markersInRange(checkingRange.get(), DocumentMarker::Spelling | DocumentMarker::Grammar);
+    const Vector<DocumentMarker*>& markers = checkingRange->ownerDocument().markers()->markersInRange(checkingRange.get(), DocumentMarker::Spelling | DocumentMarker::Grammar);
     Vector<uint32_t> hashes(markers.size());
     Vector<unsigned> offsets(markers.size());
     for (size_t i = 0; i < markers.size(); i++) {
diff --git a/Source/core/editing/SpellingCorrectionCommand.cpp b/Source/core/editing/SpellingCorrectionCommand.cpp
index 07bf705..e89b81a 100644
--- a/Source/core/editing/SpellingCorrectionCommand.cpp
+++ b/Source/core/editing/SpellingCorrectionCommand.cpp
@@ -48,7 +48,7 @@
     if (!m_corrected.length())
         return;
 
-    if (!document()->frame()->selection()->shouldChangeSelection(m_selectionToBeCorrected))
+    if (!document().frame()->selection().shouldChangeSelection(m_selectionToBeCorrected))
         return;
 
     applyCommandToComposite(SetSelectionCommand::create(m_selectionToBeCorrected, FrameSelection::SpellCorrectionTriggered | FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle));
diff --git a/Source/core/editing/SplitElementCommand.cpp b/Source/core/editing/SplitElementCommand.cpp
index 11ec640..e4227ca 100644
--- a/Source/core/editing/SplitElementCommand.cpp
+++ b/Source/core/editing/SplitElementCommand.cpp
@@ -107,13 +107,4 @@
     executeApply();
 }
 
-#ifndef NDEBUG
-void SplitElementCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_element1.get(), nodes);
-    addNodeAndDescendants(m_element2.get(), nodes);
-    addNodeAndDescendants(m_atChild.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/SplitElementCommand.h b/Source/core/editing/SplitElementCommand.h
index c873826..a87b5a2 100644
--- a/Source/core/editing/SplitElementCommand.h
+++ b/Source/core/editing/SplitElementCommand.h
@@ -45,10 +45,6 @@
     virtual void doReapply() OVERRIDE;
     void executeApply();
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Element> m_element1;
     RefPtr<Element> m_element2;
     RefPtr<Node> m_atChild;
diff --git a/Source/core/editing/SplitTextNodeCommand.cpp b/Source/core/editing/SplitTextNodeCommand.cpp
index 0a57ef7..b28147b 100644
--- a/Source/core/editing/SplitTextNodeCommand.cpp
+++ b/Source/core/editing/SplitTextNodeCommand.cpp
@@ -62,7 +62,7 @@
 
     m_text1 = Text::create(document(), prefixText);
     ASSERT(m_text1);
-    document()->markers()->copyMarkers(m_text2.get(), 0, m_offset, m_text1.get(), 0);
+    document().markers()->copyMarkers(m_text2.get(), 0, m_offset, m_text1.get(), 0);
 
     insertText1AndTrimText2();
 }
@@ -72,13 +72,13 @@
     if (!m_text1 || !m_text1->rendererIsEditable())
         return;
 
-    ASSERT(m_text1->document() == document());
+    ASSERT(&m_text1->document() == &document());
 
     String prefixText = m_text1->data();
 
-    m_text2->insertData(0, prefixText, ASSERT_NO_EXCEPTION, DeprecatedAttachNow);
+    m_text2->insertData(0, prefixText, ASSERT_NO_EXCEPTION, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
 
-    document()->markers()->copyMarkers(m_text1.get(), 0, prefixText.length(), m_text2.get(), 0);
+    document().markers()->copyMarkers(m_text1.get(), 0, prefixText.length(), m_text2.get(), 0);
     m_text1->remove(ASSERT_NO_EXCEPTION);
 }
 
@@ -100,15 +100,7 @@
     m_text2->parentNode()->insertBefore(m_text1.get(), m_text2.get(), es);
     if (es.hadException())
         return;
-    m_text2->deleteData(0, m_offset, es, DeprecatedAttachNow);
+    m_text2->deleteData(0, m_offset, es, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
 }
 
-#ifndef NDEBUG
-void SplitTextNodeCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_text1.get(), nodes);
-    addNodeAndDescendants(m_text2.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/SplitTextNodeCommand.h b/Source/core/editing/SplitTextNodeCommand.h
index 36503c1..27e0cb4 100644
--- a/Source/core/editing/SplitTextNodeCommand.h
+++ b/Source/core/editing/SplitTextNodeCommand.h
@@ -47,10 +47,6 @@
     virtual void doReapply() OVERRIDE;
     void insertText1AndTrimText2();
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Text> m_text1;
     RefPtr<Text> m_text2;
     unsigned m_offset;
diff --git a/Source/core/editing/SurroundingText.cpp b/Source/core/editing/SurroundingText.cpp
index aaa1d63..e90e9e7 100644
--- a/Source/core/editing/SurroundingText.cpp
+++ b/Source/core/editing/SurroundingText.cpp
@@ -52,8 +52,9 @@
 
     Position position = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
     Document* document = position.document();
+    ASSERT(document);
     RefPtr<Range> forwardRange = forwardIterator.range();
-    if (!forwardRange || !Range::create(document, position, forwardRange->startPosition())->text().length()) {
+    if (!forwardRange || !Range::create(*document, position, forwardRange->startPosition())->text().length()) {
         ASSERT(forwardRange);
         return;
     }
@@ -68,8 +69,8 @@
         return;
     }
 
-    m_positionOffsetInContent = Range::create(document, backwardsRange->endPosition(), position)->text().length();
-    m_contentRange = Range::create(document, backwardsRange->endPosition(), forwardRange->startPosition());
+    m_positionOffsetInContent = Range::create(*document, backwardsRange->endPosition(), position)->text().length();
+    m_contentRange = Range::create(*document, backwardsRange->endPosition(), forwardRange->startPosition());
     ASSERT(m_contentRange);
 }
 
@@ -92,7 +93,8 @@
     ASSERT(iterator.range());
     Position end = iterator.range()->startPosition();
 
-    return Range::create(start.document(), start, end);
+    ASSERT(start.document());
+    return Range::create(*start.document(), start, end);
 }
 
 String SurroundingText::content() const
diff --git a/Source/core/editing/TextCheckingHelper.cpp b/Source/core/editing/TextCheckingHelper.cpp
index c6e89bd..33471b3 100644
--- a/Source/core/editing/TextCheckingHelper.cpp
+++ b/Source/core/editing/TextCheckingHelper.cpp
@@ -270,7 +270,7 @@
                 }
 
                 // Store marker for misspelled word.
-                misspellingRange->startContainer()->document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
+                misspellingRange->startContainer()->document().markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
 
                 // Bail out if we're marking only the first misspelling, and not all instances.
                 if (!markAll)
@@ -431,7 +431,7 @@
 
         if (markAll) {
             RefPtr<Range> badGrammarRange = TextIterator::subrange(m_range.get(), badGrammarPhraseLocation - startOffset + detail->location, detail->length);
-            badGrammarRange->startContainer()->document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail->userDescription);
+            badGrammarRange->startContainer()->document().markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail->userDescription);
         }
 
         // Remember this detail only if it's earlier than our current candidate (the details aren't in a guaranteed order)
@@ -525,11 +525,8 @@
     if (!m_range)
         return false;
 
-    Document* doc = m_range->ownerDocument();
-    if (!doc)
-        return false;
-
-    return WebCore::unifiedTextCheckerEnabled(doc->frame());
+    Document& doc = m_range->ownerDocument();
+    return WebCore::unifiedTextCheckerEnabled(doc.frame());
 }
 
 void checkTextOfParagraph(TextCheckerClient& client, const String& text, TextCheckingTypeMask checkingTypes, Vector<TextCheckingResult>& results)
diff --git a/Source/core/editing/TextInsertionBaseCommand.cpp b/Source/core/editing/TextInsertionBaseCommand.cpp
index e5feda2..380b27f 100644
--- a/Source/core/editing/TextInsertionBaseCommand.cpp
+++ b/Source/core/editing/TextInsertionBaseCommand.cpp
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-TextInsertionBaseCommand::TextInsertionBaseCommand(Document* document)
+TextInsertionBaseCommand::TextInsertionBaseCommand(Document& document)
     : CompositeEditCommand(document)
 {
 }
@@ -47,10 +47,10 @@
         command->setStartingSelection(selectionForInsertion);
         command->setEndingSelection(selectionForInsertion);
     }
-    applyCommand(command);
+    command->apply();
     if (changeSelection) {
         command->setEndingSelection(endingSelection);
-        frame->selection()->setSelection(endingSelection);
+        frame->selection().setSelection(endingSelection);
     }
 }
 
diff --git a/Source/core/editing/TextInsertionBaseCommand.h b/Source/core/editing/TextInsertionBaseCommand.h
index 7b7cfc1..aa10fcf 100644
--- a/Source/core/editing/TextInsertionBaseCommand.h
+++ b/Source/core/editing/TextInsertionBaseCommand.h
@@ -39,7 +39,7 @@
     virtual ~TextInsertionBaseCommand() { };
 
 protected:
-    explicit TextInsertionBaseCommand(Document*);
+    explicit TextInsertionBaseCommand(Document&);
     static void applyTextInsertionCommand(Frame*, PassRefPtr<TextInsertionBaseCommand>, const VisibleSelection& selectionForInsertion, const VisibleSelection& endingSelection);
 };
 
diff --git a/Source/core/editing/TextIterator.cpp b/Source/core/editing/TextIterator.cpp
index 837b488..2b4b8e5 100644
--- a/Source/core/editing/TextIterator.cpp
+++ b/Source/core/editing/TextIterator.cpp
@@ -905,7 +905,7 @@
     // Additionally, if the range we are iterating over contains huge sections of unrendered content,
     // we would create VisiblePositions on every call to this function without this check.
     if (!m_node->renderer() || m_node->renderer()->style()->visibility() != VISIBLE
-        || (m_node->renderer()->isBlockFlow() && !toRenderBlock(m_node->renderer())->height() && !m_node->hasTagName(bodyTag)))
+        || (m_node->renderer()->isRenderBlockFlow() && !toRenderBlock(m_node->renderer())->height() && !m_node->hasTagName(bodyTag)))
         return false;
 
     // The startPos.isNotNull() check is needed because the start could be before the body,
@@ -2233,7 +2233,7 @@
 
 PassRefPtr<Range> TextIterator::rangeFromLocationAndLength(ContainerNode* scope, int rangeLocation, int rangeLength, bool forSelectionPreservation)
 {
-    RefPtr<Range> resultRange = scope->document()->createRange();
+    RefPtr<Range> resultRange = scope->document().createRange();
 
     int docTextPosition = 0;
     int rangeEnd = rangeLocation + rangeLength;
@@ -2266,7 +2266,7 @@
             // FIXME: This is a workaround for the fact that the end of a run is often at the wrong
             // position for emitted '\n's.
             if (len == 1 && it.characterAt(0) == '\n') {
-                scope->document()->updateLayoutIgnorePendingStylesheets();
+                scope->document().updateLayoutIgnorePendingStylesheets();
                 it.advance();
                 if (!it.atEnd()) {
                     RefPtr<Range> range = it.range();
@@ -2371,8 +2371,8 @@
 
     String result = builder.toString();
 
-    if (isDisplayString && r->ownerDocument())
-        r->ownerDocument()->displayStringModifiedByEncoding(result);
+    if (isDisplayString)
+        r->ownerDocument().displayStringModifiedByEncoding(result);
 
     return result;
 }
@@ -2393,7 +2393,7 @@
 
     if (buffer.needsMoreContext()) {
         RefPtr<Range> startRange = it.range();
-        RefPtr<Range> beforeStartRange = startRange->ownerDocument()->createRange();
+        RefPtr<Range> beforeStartRange = startRange->ownerDocument().createRange();
         beforeStartRange->setEnd(startRange->startContainer(), startRange->startOffset(), IGNORE_EXCEPTION);
         for (SimplifiedBackwardsTextIterator backwardsIterator(beforeStartRange.get()); !backwardsIterator.atEnd(); backwardsIterator.advance()) {
             Vector<UChar, 1024> characters;
@@ -2433,7 +2433,7 @@
 PassRefPtr<Range> findPlainText(const Range* range, const String& target, FindOptions options)
 {
     // CharacterIterator requires renderers to be up-to-date
-    range->ownerDocument()->updateLayout();
+    range->ownerDocument().updateLayout();
 
     // First, find the text.
     size_t matchStart;
diff --git a/Source/core/editing/TypingCommand.cpp b/Source/core/editing/TypingCommand.cpp
index a860d5d..fac993b 100644
--- a/Source/core/editing/TypingCommand.cpp
+++ b/Source/core/editing/TypingCommand.cpp
@@ -73,7 +73,7 @@
     const String& m_text;
 };
 
-TypingCommand::TypingCommand(Document *document, ETypingCommand commandType, const String &textToInsert, Options options, TextGranularity granularity, TextCompositionType compositionType)
+TypingCommand::TypingCommand(Document& document, ETypingCommand commandType, const String &textToInsert, Options options, TextGranularity granularity, TextCompositionType compositionType)
     : TextInsertionBaseCommand(document)
     , m_commandType(commandType)
     , m_textToInsert(textToInsert)
@@ -90,14 +90,12 @@
     updatePreservesTypingStyle(m_commandType);
 }
 
-void TypingCommand::deleteSelection(Document* document, Options options)
+void TypingCommand::deleteSelection(Document& document, Options options)
 {
-    ASSERT(document);
-
-    Frame* frame = document->frame();
+    Frame* frame = document.frame();
     ASSERT(frame);
 
-    if (!frame->selection()->isRange())
+    if (!frame->selection().isRange())
         return;
 
     if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame)) {
@@ -109,12 +107,11 @@
     TypingCommand::create(document, DeleteSelection, "", options)->apply();
 }
 
-void TypingCommand::deleteKeyPressed(Document *document, Options options, TextGranularity granularity)
+void TypingCommand::deleteKeyPressed(Document& document, Options options, TextGranularity granularity)
 {
-    ASSERT(document);
     if (granularity == CharacterGranularity) {
-        if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document->frame())) {
-            updateSelectionIfDifferentFromCurrentSelection(lastTypingCommand.get(), document->frame());
+        if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document.frame())) {
+            updateSelectionIfDifferentFromCurrentSelection(lastTypingCommand.get(), document.frame());
             lastTypingCommand->setShouldPreventSpellChecking(options & PreventSpellChecking);
             lastTypingCommand->deleteKeyPressed(granularity, options & KillRing);
             return;
@@ -124,11 +121,10 @@
     TypingCommand::create(document, DeleteKey, "", options, granularity)->apply();
 }
 
-void TypingCommand::forwardDeleteKeyPressed(Document *document, Options options, TextGranularity granularity)
+void TypingCommand::forwardDeleteKeyPressed(Document& document, Options options, TextGranularity granularity)
 {
     // FIXME: Forward delete in TextEdit appears to open and close a new typing command.
-    ASSERT(document);
-    Frame* frame = document->frame();
+    Frame* frame = document.frame();
     if (granularity == CharacterGranularity) {
         if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame)) {
             updateSelectionIfDifferentFromCurrentSelection(lastTypingCommand.get(), frame);
@@ -144,7 +140,7 @@
 void TypingCommand::updateSelectionIfDifferentFromCurrentSelection(TypingCommand* typingCommand, Frame* frame)
 {
     ASSERT(frame);
-    VisibleSelection currentSelection = frame->selection()->selection();
+    VisibleSelection currentSelection = frame->selection().selection();
     if (currentSelection == typingCommand->endingSelection())
         return;
 
@@ -152,28 +148,24 @@
     typingCommand->setEndingSelection(currentSelection);
 }
 
-void TypingCommand::insertText(Document* document, const String& text, Options options, TextCompositionType composition)
+void TypingCommand::insertText(Document& document, const String& text, Options options, TextCompositionType composition)
 {
-    ASSERT(document);
-
-    Frame* frame = document->frame();
+    Frame* frame = document.frame();
     ASSERT(frame);
 
     if (!text.isEmpty())
-        document->frame()->editor().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
+        document.frame()->editor().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
 
-    insertText(document, text, frame->selection()->selection(), options, composition);
+    insertText(document, text, frame->selection().selection(), options, composition);
 }
 
 // FIXME: We shouldn't need to take selectionForInsertion. It should be identical to FrameSelection's current selection.
-void TypingCommand::insertText(Document* document, const String& text, const VisibleSelection& selectionForInsertion, Options options, TextCompositionType compositionType)
+void TypingCommand::insertText(Document& document, const String& text, const VisibleSelection& selectionForInsertion, Options options, TextCompositionType compositionType)
 {
-    ASSERT(document);
-
-    RefPtr<Frame> frame = document->frame();
+    RefPtr<Frame> frame = document.frame();
     ASSERT(frame);
 
-    VisibleSelection currentSelection = frame->selection()->selection();
+    VisibleSelection currentSelection = frame->selection().selection();
 
     String newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion, compositionType == TextCompositionUpdate);
 
@@ -197,39 +189,36 @@
     applyTextInsertionCommand(frame.get(), cmd, selectionForInsertion, currentSelection);
 }
 
-void TypingCommand::insertLineBreak(Document *document, Options options)
+void TypingCommand::insertLineBreak(Document& document, Options options)
 {
-    ASSERT(document);
-    if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document->frame())) {
+    if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document.frame())) {
         lastTypingCommand->setShouldRetainAutocorrectionIndicator(options & RetainAutocorrectionIndicator);
         lastTypingCommand->insertLineBreak();
         return;
     }
 
-    applyCommand(TypingCommand::create(document, InsertLineBreak, "", options));
+    TypingCommand::create(document, InsertLineBreak, "", options)->apply();
 }
 
-void TypingCommand::insertParagraphSeparatorInQuotedContent(Document *document)
+void TypingCommand::insertParagraphSeparatorInQuotedContent(Document& document)
 {
-    ASSERT(document);
-    if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document->frame())) {
+    if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document.frame())) {
         lastTypingCommand->insertParagraphSeparatorInQuotedContent();
         return;
     }
 
-    applyCommand(TypingCommand::create(document, InsertParagraphSeparatorInQuotedContent));
+    TypingCommand::create(document, InsertParagraphSeparatorInQuotedContent)->apply();
 }
 
-void TypingCommand::insertParagraphSeparator(Document *document, Options options)
+void TypingCommand::insertParagraphSeparator(Document& document, Options options)
 {
-    ASSERT(document);
-    if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document->frame())) {
+    if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document.frame())) {
         lastTypingCommand->setShouldRetainAutocorrectionIndicator(options & RetainAutocorrectionIndicator);
         lastTypingCommand->insertParagraphSeparator();
         return;
     }
 
-    applyCommand(TypingCommand::create(document, InsertParagraphSeparator, "", options));
+    TypingCommand::create(document, InsertParagraphSeparator, "", options)->apply();
 }
 
 PassRefPtr<TypingCommand> TypingCommand::lastTypingCommandIfStillOpenForTyping(Frame* frame)
@@ -292,7 +281,7 @@
 
 void TypingCommand::markMisspellingsAfterTyping(ETypingCommand commandType)
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
@@ -317,7 +306,7 @@
 
 void TypingCommand::typingAddedToOpenCommand(ETypingCommand commandTypeForAddedTyping)
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
@@ -388,7 +377,7 @@
 
     if (root->firstChild() == root->lastChild() && root->firstElementChild() && root->firstElementChild()->hasTagName(brTag)) {
         // If there is a single child and it could be a placeholder, leave it alone.
-        if (root->renderer() && root->renderer()->isBlockFlow())
+        if (root->renderer() && root->renderer()->isRenderBlockFlow())
             return false;
     }
 
@@ -403,7 +392,7 @@
 
 void TypingCommand::deleteKeyPressed(TextGranularity granularity, bool killRing)
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
@@ -490,7 +479,7 @@
     if (selectionToDelete.isNone())
         return;
 
-    if (selectionToDelete.isCaret() || !frame->selection()->shouldDeleteSelection(selectionToDelete))
+    if (selectionToDelete.isCaret() || !frame->selection().shouldDeleteSelection(selectionToDelete))
         return;
 
     if (killRing)
@@ -507,7 +496,7 @@
 
 void TypingCommand::forwardDeleteKeyPressed(TextGranularity granularity, bool killRing)
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
@@ -583,7 +572,7 @@
     if (selectionToDelete.isNone())
         return;
 
-    if (selectionToDelete.isCaret() || !frame->selection()->shouldDeleteSelection(selectionToDelete))
+    if (selectionToDelete.isCaret() || !frame->selection().shouldDeleteSelection(selectionToDelete))
         return;
 
     if (killRing)
diff --git a/Source/core/editing/TypingCommand.h b/Source/core/editing/TypingCommand.h
index 70136e2..90a86b9 100644
--- a/Source/core/editing/TypingCommand.h
+++ b/Source/core/editing/TypingCommand.h
@@ -57,14 +57,14 @@
     };
     typedef unsigned Options;
 
-    static void deleteSelection(Document*, Options = 0);
-    static void deleteKeyPressed(Document*, Options = 0, TextGranularity = CharacterGranularity);
-    static void forwardDeleteKeyPressed(Document*, Options = 0, TextGranularity = CharacterGranularity);
-    static void insertText(Document*, const String&, Options, TextCompositionType = TextCompositionNone);
-    static void insertText(Document*, const String&, const VisibleSelection&, Options, TextCompositionType = TextCompositionNone);
-    static void insertLineBreak(Document*, Options);
-    static void insertParagraphSeparator(Document*, Options);
-    static void insertParagraphSeparatorInQuotedContent(Document*);
+    static void deleteSelection(Document&, Options = 0);
+    static void deleteKeyPressed(Document&, Options = 0, TextGranularity = CharacterGranularity);
+    static void forwardDeleteKeyPressed(Document&, Options = 0, TextGranularity = CharacterGranularity);
+    static void insertText(Document&, const String&, Options, TextCompositionType = TextCompositionNone);
+    static void insertText(Document&, const String&, const VisibleSelection&, Options, TextCompositionType = TextCompositionNone);
+    static void insertLineBreak(Document&, Options);
+    static void insertParagraphSeparator(Document&, Options);
+    static void insertParagraphSeparatorInQuotedContent(Document&);
     static void closeTyping(Frame*);
 
     void insertText(const String &text, bool selectInsertedText);
@@ -78,17 +78,17 @@
     void setCompositionType(TextCompositionType type) { m_compositionType = type; }
 
 private:
-    static PassRefPtr<TypingCommand> create(Document* document, ETypingCommand command, const String& text = "", Options options = 0, TextGranularity granularity = CharacterGranularity)
+    static PassRefPtr<TypingCommand> create(Document& document, ETypingCommand command, const String& text = "", Options options = 0, TextGranularity granularity = CharacterGranularity)
     {
         return adoptRef(new TypingCommand(document, command, text, options, granularity, TextCompositionNone));
     }
 
-    static PassRefPtr<TypingCommand> create(Document* document, ETypingCommand command, const String& text, Options options, TextCompositionType compositionType)
+    static PassRefPtr<TypingCommand> create(Document& document, ETypingCommand command, const String& text, Options options, TextCompositionType compositionType)
     {
         return adoptRef(new TypingCommand(document, command, text, options, CharacterGranularity, compositionType));
     }
 
-    TypingCommand(Document*, ETypingCommand, const String& text, Options, TextGranularity, TextCompositionType);
+    TypingCommand(Document&, ETypingCommand, const String& text, Options, TextGranularity, TextCompositionType);
 
     bool smartDelete() const { return m_smartDelete; }
     void setSmartDelete(bool smartDelete) { m_smartDelete = smartDelete; }
diff --git a/Source/core/editing/UnlinkCommand.cpp b/Source/core/editing/UnlinkCommand.cpp
index 0341fb5..3704a92 100644
--- a/Source/core/editing/UnlinkCommand.cpp
+++ b/Source/core/editing/UnlinkCommand.cpp
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-UnlinkCommand::UnlinkCommand(Document* document)
+UnlinkCommand::UnlinkCommand(Document& document)
     : CompositeEditCommand(document)
 {
 }
diff --git a/Source/core/editing/UnlinkCommand.h b/Source/core/editing/UnlinkCommand.h
index 6295d60..d6b8d17 100644
--- a/Source/core/editing/UnlinkCommand.h
+++ b/Source/core/editing/UnlinkCommand.h
@@ -32,13 +32,13 @@
 
 class UnlinkCommand : public CompositeEditCommand {
 public:
-    static PassRefPtr<UnlinkCommand> create(Document* document)
+    static PassRefPtr<UnlinkCommand> create(Document& document)
     {
         return adoptRef(new UnlinkCommand(document));
     }
 
 private:
-    explicit UnlinkCommand(Document*);
+    explicit UnlinkCommand(Document&);
 
     virtual void doApply();
     virtual EditAction editingAction() const { return EditActionUnlink; }
diff --git a/Source/core/editing/VisiblePosition.cpp b/Source/core/editing/VisiblePosition.cpp
index bad9886..e863568 100644
--- a/Source/core/editing/VisiblePosition.cpp
+++ b/Source/core/editing/VisiblePosition.cpp
@@ -27,7 +27,6 @@
 #include "config.h"
 #include "core/editing/VisiblePosition.h"
 
-#include <stdio.h>
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/Document.h"
@@ -42,6 +41,10 @@
 #include "core/rendering/RootInlineBox.h"
 #include "wtf/text/CString.h"
 
+#ifndef NDEBUG
+#include <stdio.h>
+#endif
+
 namespace WebCore {
 
 using namespace HTMLNames;
@@ -69,21 +72,22 @@
 
 VisiblePosition VisiblePosition::next(EditingBoundaryCrossingRule rule) const
 {
-    // FIXME: Support CanSkipEditingBoundary
-    ASSERT(rule == CanCrossEditingBoundary || rule == CannotCrossEditingBoundary);
     VisiblePosition next(nextVisuallyDistinctCandidate(m_deepPosition), m_affinity);
 
-    if (rule == CanCrossEditingBoundary)
+    switch (rule) {
+    case CanCrossEditingBoundary:
         return next;
-
+    case CannotCrossEditingBoundary:
+        return honorEditingBoundaryAtOrAfter(next);
+    case CanSkipOverEditingBoundary:
+        return skipToEndOfEditingBoundary(next);
+    }
+    ASSERT_NOT_REACHED();
     return honorEditingBoundaryAtOrAfter(next);
 }
 
 VisiblePosition VisiblePosition::previous(EditingBoundaryCrossingRule rule) const
 {
-    // FIXME: Support CanSkipEditingBoundary
-    ASSERT(rule == CanCrossEditingBoundary || rule == CannotCrossEditingBoundary);
-    // find first previous DOM position that is visible
     Position pos = previousVisuallyDistinctCandidate(m_deepPosition);
 
     // return null visible position if there is no previous visible position
@@ -103,9 +107,16 @@
     }
 #endif
 
-    if (rule == CanCrossEditingBoundary)
+    switch (rule) {
+    case CanCrossEditingBoundary:
         return prev;
+    case CannotCrossEditingBoundary:
+        return honorEditingBoundaryAtOrBefore(prev);
+    case CanSkipOverEditingBoundary:
+        return skipToStartOfEditingBoundary(prev);
+    }
 
+    ASSERT_NOT_REACHED();
     return honorEditingBoundaryAtOrBefore(prev);
 }
 
@@ -494,6 +505,46 @@
     return firstEditablePositionAfterPositionInRoot(pos.deepEquivalent(), highestRoot);
 }
 
+VisiblePosition VisiblePosition::skipToStartOfEditingBoundary(const VisiblePosition &pos) const
+{
+    if (pos.isNull())
+        return pos;
+
+    Node* highestRoot = highestEditableRoot(deepEquivalent());
+    Node* highestRootOfPos = highestEditableRoot(pos.deepEquivalent());
+
+    // Return pos itself if the two are from the very same editable region, or both are non-editable.
+    if (highestRootOfPos == highestRoot)
+        return pos;
+
+    // If |pos| has an editable root, skip to the start
+    if (highestRootOfPos)
+        return previousVisuallyDistinctCandidate(Position(highestRootOfPos, Position::PositionIsBeforeAnchor).parentAnchoredEquivalent());
+
+    // That must mean that |pos| is not editable. Return the last position before pos that is in the same editable region as this position
+    return lastEditablePositionBeforePositionInRoot(pos.deepEquivalent(), highestRoot);
+}
+
+VisiblePosition VisiblePosition::skipToEndOfEditingBoundary(const VisiblePosition &pos) const
+{
+    if (pos.isNull())
+        return pos;
+
+    Node* highestRoot = highestEditableRoot(deepEquivalent());
+    Node* highestRootOfPos = highestEditableRoot(pos.deepEquivalent());
+
+    // Return pos itself if the two are from the very same editable region, or both are non-editable.
+    if (highestRootOfPos == highestRoot)
+        return pos;
+
+    // If |pos| has an editable root, skip to the end
+    if (highestRootOfPos)
+        return Position(highestRootOfPos, Position::PositionIsAfterAnchor).parentAnchoredEquivalent();
+
+    // That must mean that |pos| is not editable. Return the next position after pos that is in the same editable region as this position
+    return firstEditablePositionAfterPositionInRoot(pos.deepEquivalent(), highestRoot);
+}
+
 static Position canonicalizeCandidate(const Position& candidate)
 {
     if (candidate.isNull())
@@ -541,7 +592,7 @@
 
     // The new position must be in the same editable element. Enforce that first.
     // Unless the descent is from a non-editable html element to an editable body.
-    if (node && isHTMLHtmlElement(node) && !node->rendererIsEditable() && node->document()->body() && node->document()->body()->rendererIsEditable())
+    if (node && isHTMLHtmlElement(node) && !node->rendererIsEditable() && node->document().body() && node->document().body()->rendererIsEditable())
         return next.isNotNull() ? next : prev;
 
     Node* editingRoot = editableRootForPosition(position);
diff --git a/Source/core/editing/VisiblePosition.h b/Source/core/editing/VisiblePosition.h
index 85b6bac..6c3e93b 100644
--- a/Source/core/editing/VisiblePosition.h
+++ b/Source/core/editing/VisiblePosition.h
@@ -73,6 +73,8 @@
     VisiblePosition previous(EditingBoundaryCrossingRule = CanCrossEditingBoundary) const;
     VisiblePosition honorEditingBoundaryAtOrBefore(const VisiblePosition&) const;
     VisiblePosition honorEditingBoundaryAtOrAfter(const VisiblePosition&) const;
+    VisiblePosition skipToStartOfEditingBoundary(const VisiblePosition&) const;
+    VisiblePosition skipToEndOfEditingBoundary(const VisiblePosition&) const;
 
     VisiblePosition left(bool stayInEditableContent = false) const;
     VisiblePosition right(bool stayInEditableContent = false) const;
diff --git a/Source/core/editing/VisibleSelection.cpp b/Source/core/editing/VisibleSelection.cpp
index 66afd40..96ae7ec 100644
--- a/Source/core/editing/VisibleSelection.cpp
+++ b/Source/core/editing/VisibleSelection.cpp
@@ -40,7 +40,10 @@
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
 #include "wtf/unicode/CharacterNames.h"
+
+#ifndef NDEBUG
 #include <stdio.h>
+#endif
 
 namespace WebCore {
 
@@ -133,7 +136,7 @@
         return 0;
     Position start = m_start.parentAnchoredEquivalent();
     Position end = m_end.parentAnchoredEquivalent();
-    return Range::create(start.anchorNode()->document(), start, end);
+    return Range::create(*start.document(), start, end);
 }
 
 PassRefPtr<Range> VisibleSelection::toNormalizedRange() const
@@ -145,7 +148,7 @@
     // in the course of running edit commands which modify the DOM.
     // Failing to call this can result in equivalentXXXPosition calls returning
     // incorrect results.
-    m_start.anchorNode()->document()->updateLayout();
+    m_start.document()->updateLayout();
 
     // Check again, because updating layout can clear the selection.
     if (isNone())
@@ -189,7 +192,7 @@
 
     // VisibleSelections are supposed to always be valid.  This constructor will ASSERT
     // if a valid range could not be created, which is fine for this callsite.
-    return Range::create(s.anchorNode()->document(), s, e);
+    return Range::create(*s.document(), s, e);
 }
 
 bool VisibleSelection::expandUsingGranularity(TextGranularity granularity)
@@ -206,8 +209,8 @@
     Node* n = pos.deprecatedNode();
     if (!n)
         return 0;
-    Document* d = n->document();
-    Node* de = d->documentElement();
+    Document& d = n->document();
+    Node* de = d.documentElement();
     if (!de)
         return 0;
     Node* boundary = n->enclosingBlockFlowElement();
@@ -467,17 +470,17 @@
 
 static Position adjustPositionForEnd(const Position& currentPosition, Node* startContainerNode)
 {
-    TreeScope* treeScope = startContainerNode->treeScope();
+    TreeScope& treeScope = startContainerNode->treeScope();
 
-    ASSERT(currentPosition.containerNode()->treeScope() != treeScope);
+    ASSERT(&currentPosition.containerNode()->treeScope() != &treeScope);
 
-    if (Node* ancestor = treeScope->ancestorInThisScope(currentPosition.containerNode())) {
+    if (Node* ancestor = treeScope.ancestorInThisScope(currentPosition.containerNode())) {
         if (ancestor->contains(startContainerNode))
             return positionAfterNode(ancestor);
         return positionBeforeNode(ancestor);
     }
 
-    if (Node* lastChild = treeScope->rootNode()->lastChild())
+    if (Node* lastChild = treeScope.rootNode()->lastChild())
         return positionAfterNode(lastChild);
 
     return Position();
@@ -485,17 +488,17 @@
 
 static Position adjustPositionForStart(const Position& currentPosition, Node* endContainerNode)
 {
-    TreeScope* treeScope = endContainerNode->treeScope();
+    TreeScope& treeScope = endContainerNode->treeScope();
 
-    ASSERT(currentPosition.containerNode()->treeScope() != treeScope);
+    ASSERT(&currentPosition.containerNode()->treeScope() != &treeScope);
 
-    if (Node* ancestor = treeScope->ancestorInThisScope(currentPosition.containerNode())) {
+    if (Node* ancestor = treeScope.ancestorInThisScope(currentPosition.containerNode())) {
         if (ancestor->contains(endContainerNode))
             return positionBeforeNode(ancestor);
         return positionAfterNode(ancestor);
     }
 
-    if (Node* firstChild = treeScope->rootNode()->firstChild())
+    if (Node* firstChild = treeScope.rootNode()->firstChild())
         return positionBeforeNode(firstChild);
 
     return Position();
@@ -506,7 +509,7 @@
     if (m_base.isNull() || m_start.isNull() || m_end.isNull())
         return;
 
-    if (m_start.anchorNode()->treeScope() == m_end.anchorNode()->treeScope())
+    if (&m_start.anchorNode()->treeScope() == &m_end.anchorNode()->treeScope())
         return;
 
     if (m_baseIsFirst) {
@@ -517,7 +520,7 @@
         m_start = m_extent;
     }
 
-    ASSERT(m_start.anchorNode()->treeScope() == m_end.anchorNode()->treeScope());
+    ASSERT(&m_start.anchorNode()->treeScope() == &m_end.anchorNode()->treeScope());
 }
 
 void VisibleSelection::adjustSelectionToAvoidCrossingEditingBoundaries()
diff --git a/Source/core/editing/VisibleUnits.cpp b/Source/core/editing/VisibleUnits.cpp
index 7ad6c88..92f8be8 100644
--- a/Source/core/editing/VisibleUnits.cpp
+++ b/Source/core/editing/VisibleUnits.cpp
@@ -452,7 +452,7 @@
     if (!boundary)
         return VisiblePosition();
 
-    Document* d = boundary->document();
+    Document& d = boundary->document();
     Position start = createLegacyEditingPosition(boundary, 0).parentAnchoredEquivalent();
     Position end = pos.parentAnchoredEquivalent();
     RefPtr<Range> searchRange = Range::create(d);
@@ -462,7 +462,7 @@
 
     TrackExceptionState es;
     if (requiresContextForWordBoundary(c.characterBefore())) {
-        RefPtr<Range> forwardsScanRange(d->createRange());
+        RefPtr<Range> forwardsScanRange(d.createRange());
         forwardsScanRange->setEndAfter(boundary, es);
         forwardsScanRange->setStart(end.deprecatedNode(), end.deprecatedEditingOffset(), es);
         TextIterator forwardsIterator(forwardsScanRange.get());
@@ -533,15 +533,15 @@
     if (!boundary)
         return VisiblePosition();
 
-    Document* d = boundary->document();
-    RefPtr<Range> searchRange(d->createRange());
+    Document& d = boundary->document();
+    RefPtr<Range> searchRange(d.createRange());
     Position start(pos.parentAnchoredEquivalent());
 
     Vector<UChar, 1024> string;
     unsigned prefixLength = 0;
 
     if (requiresContextForWordBoundary(c.characterAfter())) {
-        RefPtr<Range> backwardsScanRange(d->createRange());
+        RefPtr<Range> backwardsScanRange(d.createRange());
         backwardsScanRange->setEnd(start.deprecatedNode(), start.deprecatedEditingOffset(), IGNORE_EXCEPTION);
         SimplifiedBackwardsTextIterator backwardsIterator(backwardsScanRange.get());
         while (!backwardsIterator.atEnd()) {
@@ -931,7 +931,7 @@
     if (!node)
         return VisiblePosition();
 
-    node->document()->updateLayoutIgnorePendingStylesheets();
+    node->document().updateLayoutIgnorePendingStylesheets();
 
     RenderObject* renderer = node->renderer();
     if (!renderer)
@@ -972,7 +972,7 @@
     // Could not find a previous line. This means we must already be on the first line.
     // Move to the start of the content in this block, which effectively moves us
     // to the start of the line we're on.
-    Element* rootElement = node->rendererIsEditable(editableType) ? node->rootEditableElement(editableType) : node->document()->documentElement();
+    Element* rootElement = node->rendererIsEditable(editableType) ? node->rootEditableElement(editableType) : node->document().documentElement();
     if (!rootElement)
         return VisiblePosition();
     return VisiblePosition(firstPositionInNode(rootElement), DOWNSTREAM);
@@ -986,7 +986,7 @@
     if (!node)
         return VisiblePosition();
 
-    node->document()->updateLayoutIgnorePendingStylesheets();
+    node->document().updateLayoutIgnorePendingStylesheets();
 
     RenderObject* renderer = node->renderer();
     if (!renderer)
@@ -1030,7 +1030,7 @@
     // Could not find a next line. This means we must already be on the last line.
     // Move to the end of the content in this block, which effectively moves us
     // to the end of the line we're on.
-    Element* rootElement = node->rendererIsEditable(editableType) ? node->rootEditableElement(editableType) : node->document()->documentElement();
+    Element* rootElement = node->rendererIsEditable(editableType) ? node->rootEditableElement(editableType) : node->document().documentElement();
     if (!rootElement)
         return VisiblePosition();
     return VisiblePosition(lastPositionInNode(rootElement), DOWNSTREAM);
@@ -1329,10 +1329,10 @@
 
 VisiblePosition startOfDocument(const Node* node)
 {
-    if (!node || !node->document() || !node->document()->documentElement())
+    if (!node || !node->document().documentElement())
         return VisiblePosition();
 
-    return VisiblePosition(firstPositionInNode(node->document()->documentElement()), DOWNSTREAM);
+    return VisiblePosition(firstPositionInNode(node->document().documentElement()), DOWNSTREAM);
 }
 
 VisiblePosition startOfDocument(const VisiblePosition &c)
@@ -1342,10 +1342,10 @@
 
 VisiblePosition endOfDocument(const Node* node)
 {
-    if (!node || !node->document() || !node->document()->documentElement())
+    if (!node || !node->document().documentElement())
         return VisiblePosition();
 
-    Element* doc = node->document()->documentElement();
+    Element* doc = node->document().documentElement();
     return VisiblePosition(lastPositionInNode(doc), DOWNSTREAM);
 }
 
@@ -1365,7 +1365,7 @@
     if (an == bn)
         return true;
 
-    return an->document() == bn->document();
+    return &an->document() == &bn->document();
 }
 
 bool isStartOfDocument(const VisiblePosition &p)
diff --git a/Source/core/editing/WrapContentsInDummySpanCommand.cpp b/Source/core/editing/WrapContentsInDummySpanCommand.cpp
index 67b029f..dc52909 100644
--- a/Source/core/editing/WrapContentsInDummySpanCommand.cpp
+++ b/Source/core/editing/WrapContentsInDummySpanCommand.cpp
@@ -87,12 +87,4 @@
     executeApply();
 }
 
-#ifndef NDEBUG
-void WrapContentsInDummySpanCommand::getNodesInCommand(HashSet<Node*>& nodes)
-{
-    addNodeAndDescendants(m_element.get(), nodes);
-    addNodeAndDescendants(m_dummySpan.get(), nodes);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/editing/WrapContentsInDummySpanCommand.h b/Source/core/editing/WrapContentsInDummySpanCommand.h
index 514f305..be7f4b6 100644
--- a/Source/core/editing/WrapContentsInDummySpanCommand.h
+++ b/Source/core/editing/WrapContentsInDummySpanCommand.h
@@ -47,10 +47,6 @@
     virtual void doReapply() OVERRIDE;
     void executeApply();
 
-#ifndef NDEBUG
-    virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
-#endif
-
     RefPtr<Element> m_element;
     RefPtr<HTMLElement> m_dummySpan;
 };
diff --git a/Source/core/editing/htmlediting.cpp b/Source/core/editing/htmlediting.cpp
index a8bbe1d..858d2e4 100644
--- a/Source/core/editing/htmlediting.cpp
+++ b/Source/core/editing/htmlediting.cpp
@@ -159,7 +159,7 @@
     if (!node)
         return false;
     if (updateStyle == UpdateStyle)
-        node->document()->updateLayoutIgnorePendingStylesheets();
+        node->document().updateLayoutIgnorePendingStylesheets();
     else
         ASSERT(updateStyle == DoNotUpdateStyle);
 
@@ -268,8 +268,8 @@
 
     Position p = position;
 
-    if (position.deprecatedNode()->treeScope() != highestRoot->treeScope()) {
-        Node* shadowAncestor = highestRoot->treeScope()->ancestorInThisScope(p.deprecatedNode());
+    if (&position.deprecatedNode()->treeScope() != &highestRoot->treeScope()) {
+        Node* shadowAncestor = highestRoot->treeScope().ancestorInThisScope(p.deprecatedNode());
         if (!shadowAncestor)
             return VisiblePosition();
 
@@ -293,8 +293,8 @@
 
     Position p = position;
 
-    if (position.deprecatedNode()->treeScope() != highestRoot->treeScope()) {
-        Node* shadowAncestor = highestRoot->treeScope()->ancestorInThisScope(p.deprecatedNode());
+    if (&position.deprecatedNode()->treeScope() != &highestRoot->treeScope()) {
+        Node* shadowAncestor = highestRoot->treeScope().ancestorInThisScope(p.deprecatedNode());
         if (!shadowAncestor)
             return VisiblePosition();
 
@@ -527,9 +527,9 @@
 }
 
 // Create a range object with two visible positions, start and end.
-// create(PassRefPtr<Document>, const Position&, const Position&); will use deprecatedEditingOffset
+// create(Document*, const Position&, const Position&); will use deprecatedEditingOffset
 // Use this function instead of create a regular range object (avoiding editing offset).
-PassRefPtr<Range> createRange(PassRefPtr<Document> document, const VisiblePosition& start, const VisiblePosition& end, ExceptionState& es)
+PassRefPtr<Range> createRange(Document& document, const VisiblePosition& start, const VisiblePosition& end, ExceptionState& es)
 {
     RefPtr<Range> selectedRange = Range::create(document);
     selectedRange->setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), es);
@@ -755,15 +755,6 @@
     // Make sure there is no visible content between this li and the previous list
 }
 
-Node* highestAncestor(Node* node)
-{
-    ASSERT(node);
-    Node* parent = node;
-    while ((node = node->parentNode()))
-        parent = node;
-    return parent;
-}
-
 // FIXME: do not require renderer, so that this can be used within fragments, or rename to isRenderedTable()
 bool isTableElement(Node* n)
 {
@@ -816,9 +807,9 @@
     return !childRenderer->nextSibling();
 }
 
-PassRefPtr<HTMLElement> createDefaultParagraphElement(Document* document)
+PassRefPtr<HTMLElement> createDefaultParagraphElement(Document& document)
 {
-    switch (document->frame()->editor().defaultParagraphSeparator()) {
+    switch (document.frame()->editor().defaultParagraphSeparator()) {
     case EditorParagraphSeparatorIsDiv:
         return HTMLDivElement::create(document);
     case EditorParagraphSeparatorIsP:
@@ -829,32 +820,32 @@
     return 0;
 }
 
-PassRefPtr<HTMLElement> createBreakElement(Document* document)
+PassRefPtr<HTMLElement> createBreakElement(Document& document)
 {
     return HTMLBRElement::create(document);
 }
 
-PassRefPtr<HTMLElement> createOrderedListElement(Document* document)
+PassRefPtr<HTMLElement> createOrderedListElement(Document& document)
 {
     return HTMLOListElement::create(document);
 }
 
-PassRefPtr<HTMLElement> createUnorderedListElement(Document* document)
+PassRefPtr<HTMLElement> createUnorderedListElement(Document& document)
 {
     return HTMLUListElement::create(document);
 }
 
-PassRefPtr<HTMLElement> createListItemElement(Document* document)
+PassRefPtr<HTMLElement> createListItemElement(Document& document)
 {
     return HTMLLIElement::create(document);
 }
 
-PassRefPtr<HTMLElement> createHTMLElement(Document* document, const QualifiedName& name)
+PassRefPtr<HTMLElement> createHTMLElement(Document& document, const QualifiedName& name)
 {
-    return HTMLElementFactory::createHTMLElement(name, document, 0, false);
+    return HTMLElementFactory::createHTMLElement(name, &document, 0, false);
 }
 
-PassRefPtr<HTMLElement> createHTMLElement(Document* document, const AtomicString& tagName)
+PassRefPtr<HTMLElement> createHTMLElement(Document& document, const AtomicString& tagName)
 {
     return createHTMLElement(document, QualifiedName(nullAtom, tagName, xhtmlNamespaceURI));
 }
@@ -888,30 +879,30 @@
     return positionInParentBeforeNode(node);
 }
 
-PassRefPtr<Element> createTabSpanElement(Document* document, PassRefPtr<Node> prpTabTextNode)
+PassRefPtr<Element> createTabSpanElement(Document& document, PassRefPtr<Node> prpTabTextNode)
 {
     RefPtr<Node> tabTextNode = prpTabTextNode;
 
     // Make the span to hold the tab.
-    RefPtr<Element> spanElement = document->createElement(spanTag, false);
+    RefPtr<Element> spanElement = document.createElement(spanTag, false);
     spanElement->setAttribute(classAttr, AppleTabSpanClass);
     spanElement->setAttribute(styleAttr, "white-space:pre");
 
     // Add tab text to that span.
     if (!tabTextNode)
-        tabTextNode = document->createEditingTextNode("\t");
+        tabTextNode = document.createEditingTextNode("\t");
 
     spanElement->appendChild(tabTextNode.release());
 
     return spanElement.release();
 }
 
-PassRefPtr<Element> createTabSpanElement(Document* document, const String& tabText)
+PassRefPtr<Element> createTabSpanElement(Document& document, const String& tabText)
 {
-    return createTabSpanElement(document, document->createTextNode(tabText));
+    return createTabSpanElement(document, document.createTextNode(tabText));
 }
 
-PassRefPtr<Element> createTabSpanElement(Document* document)
+PassRefPtr<Element> createTabSpanElement(Document& document)
 {
     return createTabSpanElement(document, PassRefPtr<Node>());
 }
@@ -1058,13 +1049,13 @@
         return 0;
 
     Position p(visiblePosition.deepEquivalent());
-    Document* document = p.anchorNode()->document();
+    Document& document = *p.document();
     ShadowRoot* shadowRoot = p.anchorNode()->containingShadowRoot();
 
     if (shadowRoot)
         scope = shadowRoot;
     else
-        scope = document->documentElement();
+        scope = document.documentElement();
 
     RefPtr<Range> range = Range::create(document, firstPositionInNode(scope.get()), p.parentAnchoredEquivalent());
 
diff --git a/Source/core/editing/htmlediting.h b/Source/core/editing/htmlediting.h
index e8bd156..7821ebe 100644
--- a/Source/core/editing/htmlediting.h
+++ b/Source/core/editing/htmlediting.h
@@ -53,7 +53,6 @@
 
 // Functions returning Node
 
-Node* highestAncestor(Node*);
 Node* highestEditableRoot(const Position&, EditableType = ContentIsEditable);
 
 Node* highestEnclosingNodeOfType(const Position&, bool (*nodeIsOfType)(const Node*),
@@ -188,7 +187,7 @@
 
 // Functions returning Range
 
-PassRefPtr<Range> createRange(PassRefPtr<Document>, const VisiblePosition& start, const VisiblePosition& end, ExceptionState&);
+PassRefPtr<Range> createRange(Document&, const VisiblePosition& start, const VisiblePosition& end, ExceptionState&);
 
 // -------------------------------------------------------------------------
 // HTMLElement
@@ -196,13 +195,13 @@
 
 // Functions returning HTMLElement
 
-PassRefPtr<HTMLElement> createDefaultParagraphElement(Document*);
-PassRefPtr<HTMLElement> createBreakElement(Document*);
-PassRefPtr<HTMLElement> createOrderedListElement(Document*);
-PassRefPtr<HTMLElement> createUnorderedListElement(Document*);
-PassRefPtr<HTMLElement> createListItemElement(Document*);
-PassRefPtr<HTMLElement> createHTMLElement(Document*, const QualifiedName&);
-PassRefPtr<HTMLElement> createHTMLElement(Document*, const AtomicString&);
+PassRefPtr<HTMLElement> createDefaultParagraphElement(Document&);
+PassRefPtr<HTMLElement> createBreakElement(Document&);
+PassRefPtr<HTMLElement> createOrderedListElement(Document&);
+PassRefPtr<HTMLElement> createUnorderedListElement(Document&);
+PassRefPtr<HTMLElement> createListItemElement(Document&);
+PassRefPtr<HTMLElement> createHTMLElement(Document&, const QualifiedName&);
+PassRefPtr<HTMLElement> createHTMLElement(Document&, const AtomicString&);
 
 HTMLElement* enclosingList(Node*);
 HTMLElement* outermostEnclosingList(Node*, Node* rootList = 0);
@@ -214,10 +213,10 @@
 
 // Functions returning Element
 
-PassRefPtr<Element> createTabSpanElement(Document*);
-PassRefPtr<Element> createTabSpanElement(Document*, PassRefPtr<Node> tabTextNode);
-PassRefPtr<Element> createTabSpanElement(Document*, const String& tabText);
-PassRefPtr<Element> createBlockPlaceholderElement(Document*);
+PassRefPtr<Element> createTabSpanElement(Document&);
+PassRefPtr<Element> createTabSpanElement(Document&, PassRefPtr<Node> tabTextNode);
+PassRefPtr<Element> createTabSpanElement(Document&, const String& tabText);
+PassRefPtr<Element> createBlockPlaceholderElement(Document&);
 
 Element* editableRootForPosition(const Position&, EditableType = ContentIsEditable);
 Element* unsplittableElementForPosition(const Position&);
diff --git a/Source/core/editing/markup.cpp b/Source/core/editing/markup.cpp
index f505c54..36dac24 100644
--- a/Source/core/editing/markup.cpp
+++ b/Source/core/editing/markup.cpp
@@ -225,7 +225,7 @@
         // FIXME: Should this be included in forceInline?
         wrappingStyle->style()->setProperty(CSSPropertyFloat, CSSValueNone);
 
-        appendStyleNodeOpenTag(out, wrappingStyle->style(), text->document());
+        appendStyleNodeOpenTag(out, wrappingStyle->style(), &text->document());
     }
 
     if (!shouldAnnotate() || parentIsTextarea)
@@ -247,7 +247,7 @@
     if (!node->isTextNode())
         return String();
 
-    const Text* textNode = static_cast<const Text*>(node);
+    const Text* textNode = toText(node);
     unsigned startOffset = 0;
     unsigned endOffset = textNode->length();
 
@@ -276,7 +276,7 @@
 
 void StyledMarkupAccumulator::appendElement(StringBuilder& out, Element* element, bool addDisplayInline, RangeFullySelectsNode rangeFullySelectsNode)
 {
-    const bool documentIsHTML = element->document()->isHTMLDocument();
+    const bool documentIsHTML = element->document().isHTMLDocument();
     appendOpenTag(out, element, 0);
 
     const unsigned length = element->hasAttributes() ? element->attributeCount() : 0;
@@ -483,7 +483,7 @@
 
     // FIXME: Having to const_cast here is ugly, but it is quite a bit of work to untangle
     // the non-const-ness of styleFromMatchedRulesForElement.
-    HTMLElement* element = const_cast<HTMLElement*>(static_cast<const HTMLElement*>(node));
+    HTMLElement* element = const_cast<HTMLElement*>(toHTMLElement(node));
     RefPtr<EditingStyle> style = EditingStyle::create(element->inlineStyle());
     style->mergeStyleFromRules(element);
     return style.release();
@@ -542,10 +542,9 @@
 
 // FIXME: Shouldn't we omit style info when annotate == DoNotAnnotateForInterchange?
 // FIXME: At least, annotation and style info should probably not be included in range.markupString()
-static String createMarkupInternal(Document* document, const Range* range, const Range* updatedRange, Vector<Node*>* nodes,
+static String createMarkupInternal(Document& document, const Range* range, const Range* updatedRange, Vector<Node*>* nodes,
     EAnnotateForInterchange shouldAnnotate, bool convertBlocksToInlines, EAbsoluteURLs shouldResolveURLs, Node* constrainingAncestor)
 {
-    ASSERT(document);
     ASSERT(range);
     ASSERT(updatedRange);
     DEFINE_STATIC_LOCAL(const String, interchangeNewlineString, ("<br class=\"" AppleInterchangeNewline "\">"));
@@ -557,7 +556,7 @@
     if (!commonAncestor)
         return emptyString();
 
-    document->updateLayoutIgnorePendingStylesheets();
+    document.updateLayoutIgnorePendingStylesheets();
 
     Node* body = enclosingNodeWithTag(firstPositionInNode(commonAncestor), bodyTag);
     Node* fullySelectedRoot = 0;
@@ -604,7 +603,7 @@
                         fullySelectedRootStyle->style()->setProperty(CSSPropertyTextDecoration, CSSValueNone);
                     if (!propertyMissingOrEqualToNone(fullySelectedRootStyle->style(), CSSPropertyWebkitTextDecorationsInEffect))
                         fullySelectedRootStyle->style()->setProperty(CSSPropertyWebkitTextDecorationsInEffect, CSSValueNone);
-                    accumulator.wrapWithStyleNode(fullySelectedRootStyle->style(), document, true);
+                    accumulator.wrapWithStyleNode(fullySelectedRootStyle->style(), &document, true);
                 }
             } else {
                 // Since this node and all the other ancestors are not in the selection we want to set RangeFullySelectsNode to DoesNotFullySelectNode
@@ -633,16 +632,13 @@
     if (!range)
         return emptyString();
 
-    Document* document = range->ownerDocument();
-    if (!document)
-        return emptyString();
-
+    Document& document = range->ownerDocument();
     const Range* updatedRange = range;
 
     return createMarkupInternal(document, range, updatedRange, nodes, shouldAnnotate, convertBlocksToInlines, shouldResolveURLs, constrainingAncestor);
 }
 
-PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document* document, const String& markup, const String& baseURL, ParserContentPolicy parserContentPolicy)
+PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document& document, const String& markup, const String& baseURL, ParserContentPolicy parserContentPolicy)
 {
     // We use a fake body element here to trick the HTML parser to using the InBody insertion mode.
     RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(document);
@@ -650,7 +646,7 @@
 
     fragment->parseHTML(markup, fakeBody.get(), parserContentPolicy);
 
-    if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document->baseURL())
+    if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document.baseURL())
         completeURLs(fragment.get(), baseURL);
 
     return fragment.release();
@@ -661,7 +657,7 @@
 static bool findNodesSurroundingContext(Document* document, RefPtr<Node>& nodeBeforeContext, RefPtr<Node>& nodeAfterContext)
 {
     for (Node* node = document->firstChild(); node; node = NodeTraversal::next(node)) {
-        if (node->nodeType() == Node::COMMENT_NODE && static_cast<CharacterData*>(node)->data() == fragmentMarkerTag) {
+        if (node->nodeType() == Node::COMMENT_NODE && toCharacterData(node)->data() == fragmentMarkerTag) {
             if (!nodeBeforeContext)
                 nodeBeforeContext = node;
             else {
@@ -695,7 +691,7 @@
     }
 }
 
-PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document* document, const String& markup, unsigned fragmentStart, unsigned fragmentEnd,
+PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document& document, const String& markup, unsigned fragmentStart, unsigned fragmentEnd,
     const String& baseURL, ParserContentPolicy parserContentPolicy)
 {
     // FIXME: Need to handle the case where the markup already contains these markers.
@@ -709,7 +705,7 @@
 
     RefPtr<DocumentFragment> taggedFragment = createFragmentFromMarkup(document, taggedMarkup.toString(), baseURL, parserContentPolicy);
     RefPtr<Document> taggedDocument = Document::create();
-    taggedDocument->setContextFeatures(document->contextFeatures());
+    taggedDocument->setContextFeatures(document.contextFeatures());
     taggedDocument->takeAllChildrenFrom(taggedFragment.get());
 
     RefPtr<Node> nodeBeforeContext;
@@ -717,7 +713,7 @@
     if (!findNodesSurroundingContext(taggedDocument.get(), nodeBeforeContext, nodeAfterContext))
         return 0;
 
-    RefPtr<Range> range = Range::create(taggedDocument.get(),
+    RefPtr<Range> range = Range::create(*taggedDocument.get(),
         positionAfterNode(nodeBeforeContext.get()).parentAnchoredEquivalent(),
         positionBeforeNode(nodeAfterContext.get()).parentAnchoredEquivalent());
 
@@ -749,7 +745,7 @@
 
 static void fillContainerFromString(ContainerNode* paragraph, const String& string)
 {
-    Document* document = paragraph->document();
+    Document& document = paragraph->document();
 
     if (string.isEmpty()) {
         paragraph->appendChild(createBlockPlaceholderElement(document));
@@ -772,7 +768,7 @@
                 paragraph->appendChild(createTabSpanElement(document, tabText));
                 tabText = emptyString();
             }
-            RefPtr<Node> textNode = document->createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
+            RefPtr<Node> textNode = document.createTextNode(stringWithRebalancedWhitespace(s, first, i + 1 == numEntries));
             paragraph->appendChild(textNode.release());
         }
 
@@ -818,8 +814,8 @@
     if (!context)
         return 0;
 
-    Document* document = context->ownerDocument();
-    RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
+    Document& document = context->ownerDocument();
+    RefPtr<DocumentFragment> fragment = document.createDocumentFragment();
 
     if (text.isEmpty())
         return fragment.release();
@@ -829,7 +825,7 @@
     string.replace('\r', '\n');
 
     if (shouldPreserveNewline(*context)) {
-        fragment->appendChild(document->createTextNode(string));
+        fragment->appendChild(document.createTextNode(string));
         if (string.endsWith('\n')) {
             RefPtr<Element> element = createBreakElement(document);
             element->setAttribute(classAttr, AppleInterchangeNewline);
@@ -889,7 +885,7 @@
 
     size_t size = nodes.size();
     for (size_t i = 0; i < size; ++i) {
-        RefPtr<Element> element = createDefaultParagraphElement(document);
+        RefPtr<Element> element = createDefaultParagraphElement(*document);
         element->appendChild(nodes[i]);
         fragment->appendChild(element.release());
     }
@@ -902,11 +898,7 @@
     if (!node)
         return String();
 
-    Document* document = node->document();
-    if (!document)
-        return String();
-
-    Frame* frame = document->frame();
+    Frame* frame = node->document().frame();
     if (!frame)
         return String();
 
@@ -928,11 +920,7 @@
     if (!node)
         return String();
 
-    Document* document = node->document();
-    if (!document)
-        return String();
-
-    Frame* frame = document->frame();
+    Frame* frame = node->document().frame();
     if (!frame)
         return String();
 
@@ -953,10 +941,10 @@
 
 PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, ExceptionState& es)
 {
-    Document* document = contextElement->hasTagName(templateTag) ? contextElement->document()->ensureTemplateDocument() : contextElement->document();
+    Document& document = contextElement->hasTagName(templateTag) ? contextElement->document().ensureTemplateDocument() : contextElement->document();
     RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
 
-    if (document->isHTMLDocument()) {
+    if (document.isHTMLDocument()) {
         fragment->parseHTML(markup, contextElement, parserContentPolicy);
         return fragment;
     }
@@ -969,9 +957,9 @@
     return fragment.release();
 }
 
-PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String& sourceString, const String& sourceMIMEType, Document* outputDoc)
+PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String& sourceString, const String& sourceMIMEType, Document& outputDoc)
 {
-    RefPtr<DocumentFragment> fragment = outputDoc->createDocumentFragment();
+    RefPtr<DocumentFragment> fragment = outputDoc.createDocumentFragment();
 
     if (sourceMIMEType == "text/html") {
         // As far as I can tell, there isn't a spec for how transformToFragment is supposed to work.
@@ -980,9 +968,9 @@
         // We achieve that effect here by passing in a fake body element as context for the fragment.
         RefPtr<HTMLBodyElement> fakeBody = HTMLBodyElement::create(outputDoc);
         fragment->parseHTML(sourceString, fakeBody.get());
-    } else if (sourceMIMEType == "text/plain")
+    } else if (sourceMIMEType == "text/plain") {
         fragment->parserAppendChild(Text::create(outputDoc, sourceString));
-    else {
+    } else {
         bool successfulParse = fragment->parseXML(sourceString, 0);
         if (!successfulParse)
             return 0;
diff --git a/Source/core/editing/markup.h b/Source/core/editing/markup.h
index 2b80d11..b293441 100644
--- a/Source/core/editing/markup.h
+++ b/Source/core/editing/markup.h
@@ -48,11 +48,11 @@
 enum EAbsoluteURLs { DoNotResolveURLs, ResolveAllURLs, ResolveNonLocalURLs };
 
 PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text);
-PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document*, const String& markup, const String& baseURL, ParserContentPolicy = AllowScriptingContent);
-PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document*, const String& markup, unsigned fragmentStart, unsigned fragmentEnd, const String& baseURL, ParserContentPolicy);
+PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document&, const String& markup, const String& baseURL, ParserContentPolicy = AllowScriptingContent);
+PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document&, const String& markup, unsigned fragmentStart, unsigned fragmentEnd, const String& baseURL, ParserContentPolicy);
 PassRefPtr<DocumentFragment> createFragmentFromNodes(Document*, const Vector<Node*>&);
 PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String&, Element*, ParserContentPolicy, ExceptionState&);
-PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String&, const String& sourceMIMEType, Document* outputDoc);
+PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String&, const String& sourceMIMEType, Document& outputDoc);
 PassRefPtr<DocumentFragment> createContextualFragment(const String&, HTMLElement*, ParserContentPolicy, ExceptionState&);
 
 bool isPlainTextMarkup(Node*);
diff --git a/Source/core/features.gypi b/Source/core/features.gypi
index 40a89de..e5d8d6b 100644
--- a/Source/core/features.gypi
+++ b/Source/core/features.gypi
@@ -61,7 +61,6 @@
           'ENABLE_INPUT_SPEECH=0',
           'ENABLE_LEGACY_NOTIFICATIONS=0',
           'ENABLE_MEDIA_CAPTURE=1',
-          'ENABLE_NOTIFICATIONS=0',
           'ENABLE_ORIENTATION_EVENTS=1',
           'ENABLE_NAVIGATOR_CONTENT_UTILS=0',
           'WTF_USE_NATIVE_FULLSCREEN_VIDEO=1',
@@ -75,7 +74,6 @@
           'ENABLE_LEGACY_NOTIFICATIONS=1',
           'ENABLE_MEDIA_CAPTURE=0',
           'ENABLE_NAVIGATOR_CONTENT_UTILS=1',
-          'ENABLE_NOTIFICATIONS=1',
           'ENABLE_ORIENTATION_EVENTS=0',
           'ENABLE_WEB_AUDIO=1',
         ],
@@ -104,11 +102,6 @@
           'ENABLE_RUBBER_BANDING=1',
         ],
       }],
-      ['OS=="linux" or OS=="android"', {
-        'feature_defines': [
-          'WTF_USE_HARFBUZZ=1',
-        ],
-      }],
       ['use_default_render_theme==1', {
         'feature_defines': [
           'ENABLE_DEFAULT_RENDER_THEME=1',
diff --git a/Source/core/fetch/CSSStyleSheetResource.cpp b/Source/core/fetch/CSSStyleSheetResource.cpp
index 20be517..78a3455 100644
--- a/Source/core/fetch/CSSStyleSheetResource.cpp
+++ b/Source/core/fetch/CSSStyleSheetResource.cpp
@@ -30,7 +30,7 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/fetch/ResourceClientWalker.h"
 #include "core/fetch/StyleSheetResourceClient.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/network/HTTPParsers.h"
 #include "wtf/CurrentTime.h"
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/fetch/CachedMetadata.cpp
similarity index 97%
rename from Source/core/loader/CachedMetadata.cpp
rename to Source/core/fetch/CachedMetadata.cpp
index f3f2a30..7edcac5 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/fetch/CachedMetadata.cpp
@@ -29,7 +29,7 @@
  */
 
 #include "config.h"
-#include "core/loader/CachedMetadata.h"
+#include "core/fetch/CachedMetadata.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/CachedMetadata.h b/Source/core/fetch/CachedMetadata.h
similarity index 100%
rename from Source/core/loader/CachedMetadata.h
rename to Source/core/fetch/CachedMetadata.h
diff --git a/Source/core/loader/CrossOriginAccessControl.cpp b/Source/core/fetch/CrossOriginAccessControl.cpp
similarity index 99%
rename from Source/core/loader/CrossOriginAccessControl.cpp
rename to Source/core/fetch/CrossOriginAccessControl.cpp
index edfbb62..2647a8e 100644
--- a/Source/core/loader/CrossOriginAccessControl.cpp
+++ b/Source/core/fetch/CrossOriginAccessControl.cpp
@@ -25,7 +25,7 @@
  */
 
 #include "config.h"
-#include "core/loader/CrossOriginAccessControl.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 
 #include "core/platform/network/HTTPParsers.h"
 #include "core/platform/network/ResourceRequest.h"
diff --git a/Source/core/loader/CrossOriginAccessControl.h b/Source/core/fetch/CrossOriginAccessControl.h
similarity index 100%
rename from Source/core/loader/CrossOriginAccessControl.h
rename to Source/core/fetch/CrossOriginAccessControl.h
diff --git a/Source/core/fetch/DocumentResource.h b/Source/core/fetch/DocumentResource.h
index 58b8ac0..efa77d9 100644
--- a/Source/core/fetch/DocumentResource.h
+++ b/Source/core/fetch/DocumentResource.h
@@ -26,7 +26,7 @@
 #include "core/fetch/Resource.h"
 #include "core/fetch/ResourceClient.h"
 #include "core/fetch/ResourcePtr.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/fetch/FetchContext.cpp b/Source/core/fetch/FetchContext.cpp
new file mode 100644
index 0000000..037e629
--- /dev/null
+++ b/Source/core/fetch/FetchContext.cpp
@@ -0,0 +1,88 @@
+/*
+ * 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/fetch/FetchContext.h"
+
+
+namespace WebCore {
+
+FetchContext& FetchContext::nullInstance()
+{
+    DEFINE_STATIC_LOCAL(FetchContext, instance, ());
+    return instance;
+}
+
+void FetchContext::dispatchDidChangeResourcePriority(unsigned long, ResourceLoadPriority)
+{
+}
+
+void FetchContext::reportLocalLoadFailed(const KURL&)
+{
+}
+
+void FetchContext::addAdditionalRequestHeaders(Document&, ResourceRequest&, Resource::Type)
+{
+}
+
+CachePolicy FetchContext::cachePolicy(Resource::Type) const
+{
+    return CachePolicyVerify;
+}
+
+void FetchContext::dispatchWillSendRequest(DocumentLoader*, unsigned long, ResourceRequest&, const ResourceResponse&, const FetchInitiatorInfo&)
+{
+}
+
+void FetchContext::dispatchDidLoadResourceFromMemoryCache(const ResourceRequest&, const ResourceResponse&)
+{
+}
+
+void FetchContext::dispatchDidReceiveResponse(DocumentLoader*, unsigned long, const ResourceResponse&, ResourceLoader*)
+{
+}
+
+void FetchContext::dispatchDidReceiveData(DocumentLoader*, unsigned long, const char*, int, int)
+{
+}
+
+void FetchContext::dispatchDidFinishLoading(DocumentLoader*, unsigned long, double)
+{
+}
+
+void FetchContext::dispatchDidFail(DocumentLoader*, unsigned long, const ResourceError&)
+{
+}
+
+void FetchContext::sendRemainingDelegateMessages(DocumentLoader*, unsigned long, const ResourceResponse&, const char*, int, int, const ResourceError&)
+{
+}
+
+} // namespace WebCore
diff --git a/Source/core/fetch/FetchContext.h b/Source/core/fetch/FetchContext.h
new file mode 100644
index 0000000..1eb5596
--- /dev/null
+++ b/Source/core/fetch/FetchContext.h
@@ -0,0 +1,75 @@
+/*
+ * 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 FetchContext_h
+#define FetchContext_h
+
+#include "core/fetch/CachePolicy.h"
+#include "core/fetch/FetchInitiatorInfo.h"
+#include "core/fetch/Resource.h"
+#include "core/platform/network/ResourceLoadPriority.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class DocumentLoader;
+class Frame;
+class KURL;
+class Page;
+class ResourceError;
+class ResourceLoader;
+class ResourceResponse;
+class ResourceRequest;
+
+class FetchContext {
+    WTF_MAKE_NONCOPYABLE(FetchContext);
+public:
+    static FetchContext& nullInstance();
+
+    FetchContext() { }
+    virtual ~FetchContext() { }
+
+    virtual void reportLocalLoadFailed(const KURL&);
+    virtual void addAdditionalRequestHeaders(Document&, ResourceRequest&, Resource::Type);
+    virtual CachePolicy cachePolicy(Resource::Type) const;
+
+    virtual void dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority);
+    virtual void dispatchWillSendRequest(DocumentLoader*, unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& = FetchInitiatorInfo());
+    virtual void dispatchDidLoadResourceFromMemoryCache(const ResourceRequest&, const ResourceResponse&);
+    virtual void dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse&, ResourceLoader* = 0);
+    virtual void dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength);
+    virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier, double finishTime);
+    virtual void dispatchDidFail(DocumentLoader*, unsigned long identifier, const ResourceError&);
+    virtual void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, const char* data, int dataLength, int encodedDataLength, const ResourceError&);
+};
+
+}
+
+#endif
diff --git a/Source/core/fetch/FetchRequest.cpp b/Source/core/fetch/FetchRequest.cpp
index ba22c78..d8d9512 100644
--- a/Source/core/fetch/FetchRequest.cpp
+++ b/Source/core/fetch/FetchRequest.cpp
@@ -27,9 +27,9 @@
 #include "core/fetch/FetchRequest.h"
 
 #include "core/dom/Element.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/FetchInitiatorInfo.h"
 #include "core/fetch/ResourceFetcher.h"
-#include "core/loader/CrossOriginAccessControl.h"
 
 namespace WebCore {
 
diff --git a/Source/core/fetch/FontResource.cpp b/Source/core/fetch/FontResource.cpp
index 23eb76a..d4db35a 100644
--- a/Source/core/fetch/FontResource.cpp
+++ b/Source/core/fetch/FontResource.cpp
@@ -29,10 +29,12 @@
 
 #include "core/fetch/ResourceClient.h"
 #include "core/fetch/ResourceClientWalker.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
+#include "core/platform/HistogramSupport.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/graphics/FontCustomPlatformData.h"
 #include "core/platform/graphics/FontPlatformData.h"
+#include "wtf/CurrentTime.h"
 
 #if ENABLE(SVG_FONTS)
 #include "SVGNames.h"
@@ -77,6 +79,7 @@
         ResourceClientWalker<FontResourceClient> walker(m_clients);
         while (FontResourceClient* client = walker.next())
             client->didStartFontLoad(this);
+        m_histograms.loadStarted();
     }
 }
 
@@ -162,4 +165,36 @@
         c->fontLoaded(this);
 }
 
+void FontResource::willUseFontData()
+{
+    if (!isLoaded())
+        m_histograms.willUseFontData();
+}
+
+FontResource::FontResourceHistograms::~FontResourceHistograms()
+{
+    if (m_styledTime > 0)
+        HistogramSupport::histogramEnumeration("WebFont.Resource.UsageType", StyledButNotUsed, UsageTypeMax);
+}
+
+void FontResource::FontResourceHistograms::willUseFontData()
+{
+    if (!m_styledTime)
+        m_styledTime = currentTimeMS();
+}
+
+void FontResource::FontResourceHistograms::loadStarted()
+{
+    if (m_styledTime < 0)
+        return;
+    if (!m_styledTime) {
+        HistogramSupport::histogramEnumeration("WebFont.Resource.UsageType", NotStyledButUsed, UsageTypeMax);
+    } else {
+        int duration = static_cast<int>(currentTimeMS() - m_styledTime);
+        HistogramSupport::histogramCustomCounts("WebFont.Resource.StyleRecalcToDownloadLatency", duration, 0, 10000, 50);
+        HistogramSupport::histogramEnumeration("WebFont.Resource.UsageType", StyledAndUsed, UsageTypeMax);
+    }
+    m_styledTime = -1;
+}
+
 }
diff --git a/Source/core/fetch/FontResource.h b/Source/core/fetch/FontResource.h
index 42b4f70..a910f8e 100644
--- a/Source/core/fetch/FontResource.h
+++ b/Source/core/fetch/FontResource.h
@@ -50,6 +50,7 @@
     virtual void didAddClient(ResourceClient*);
 
     virtual void allClientsRemoved();
+    void willUseFontData();
     void beginLoadIfNeeded(ResourceFetcher* dl);
     bool stillNeedsLoad() const { return !m_loadInitiated; }
 
@@ -69,6 +70,22 @@
 #if ENABLE(SVG_FONTS)
     RefPtr<WebCore::SVGDocument> m_externalSVGDocument;
 #endif
+    class FontResourceHistograms {
+    public:
+        enum UsageType {
+            StyledAndUsed,
+            StyledButNotUsed,
+            NotStyledButUsed,
+            UsageTypeMax
+        };
+        FontResourceHistograms() : m_styledTime(0) { }
+        ~FontResourceHistograms();
+        void willUseFontData();
+        void loadStarted();
+    private:
+        double m_styledTime;
+    };
+    FontResourceHistograms m_histograms;
 
     friend class MemoryCache;
 };
diff --git a/Source/core/fetch/MemoryCache.cpp b/Source/core/fetch/MemoryCache.cpp
index 9b141c5..af4809e 100644
--- a/Source/core/fetch/MemoryCache.cpp
+++ b/Source/core/fetch/MemoryCache.cpp
@@ -41,7 +41,6 @@
 #include "wtf/MathExtras.h"
 #include "wtf/TemporaryChange.h"
 #include "wtf/text/CString.h"
-#include <stdio.h>
 
 using namespace std;
 
diff --git a/Source/core/fetch/MockImageResourceClient.h b/Source/core/fetch/MockImageResourceClient.h
index 676c95a..4499396 100644
--- a/Source/core/fetch/MockImageResourceClient.h
+++ b/Source/core/fetch/MockImageResourceClient.h
@@ -32,8 +32,6 @@
 #define MockImageResourceClient_h
 
 #include "core/fetch/ImageResourceClient.h"
-#include "core/page/Frame.h"
-#include "core/platform/graphics/Image.h"
 
 #include <gtest/gtest.h>
 
diff --git a/Source/core/fetch/Resource.cpp b/Source/core/fetch/Resource.cpp
index c5abd6f..0a38f04 100644
--- a/Source/core/fetch/Resource.cpp
+++ b/Source/core/fetch/Resource.cpp
@@ -24,6 +24,8 @@
 #include "config.h"
 #include "core/fetch/Resource.h"
 
+#include "core/fetch/CachedMetadata.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/MemoryCache.h"
 #include "core/fetch/ResourceClient.h"
 #include "core/fetch/ResourceClientWalker.h"
@@ -31,8 +33,6 @@
 #include "core/fetch/ResourceLoader.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/CachedMetadata.h"
-#include "core/loader/CrossOriginAccessControl.h"
 #include "core/platform/Logging.h"
 #include "core/platform/PurgeableBuffer.h"
 #include "core/platform/SharedBuffer.h"
@@ -81,11 +81,11 @@
 static inline bool shouldUpdateHeaderAfterRevalidation(const AtomicString& header)
 {
     for (size_t i = 0; i < WTF_ARRAY_LENGTH(headersToIgnoreAfterRevalidation); i++) {
-        if (header == headersToIgnoreAfterRevalidation[i])
+        if (equalIgnoringCase(header, headersToIgnoreAfterRevalidation[i]))
             return false;
     }
     for (size_t i = 0; i < WTF_ARRAY_LENGTH(headerPrefixesToIgnoreAfterRevalidation); i++) {
-        if (header.startsWith(headerPrefixesToIgnoreAfterRevalidation[i]))
+        if (header.startsWith(headerPrefixesToIgnoreAfterRevalidation[i], false))
             return false;
     }
     return true;
diff --git a/Source/core/fetch/Resource.h b/Source/core/fetch/Resource.h
index ec640d8..6d5526b 100644
--- a/Source/core/fetch/Resource.h
+++ b/Source/core/fetch/Resource.h
@@ -146,7 +146,7 @@
     void setLoading(bool b) { m_loading = b; }
     virtual bool stillNeedsLoad() const { return false; }
 
-    ResourceLoader* loader() { return m_loader.get(); }
+    ResourceLoader* loader() const { return m_loader.get(); }
 
     virtual bool isImage() const { return false; }
     bool ignoreForRequestCount() const
diff --git a/Source/core/fetch/ResourceFetcher.cpp b/Source/core/fetch/ResourceFetcher.cpp
index 28ffda0..6059672 100644
--- a/Source/core/fetch/ResourceFetcher.cpp
+++ b/Source/core/fetch/ResourceFetcher.cpp
@@ -31,11 +31,14 @@
 #include "core/dom/Document.h"
 #include "core/fetch/CSSStyleSheetResource.h"
 #include "core/fetch/DocumentResource.h"
+#include "core/fetch/FetchContext.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/FontResource.h"
 #include "core/fetch/ImageResource.h"
 #include "core/fetch/MemoryCache.h"
 #include "core/fetch/RawResource.h"
+#include "core/fetch/ResourceLoader.h"
+#include "core/fetch/ResourceLoaderSet.h"
 #include "core/fetch/ScriptResource.h"
 #include "core/fetch/ShaderResource.h"
 #include "core/fetch/TextTrackResource.h"
@@ -201,6 +204,29 @@
     return 0;
 }
 
+FetchContext& ResourceFetcher::context() const
+{
+    if (Frame* frame = this->frame())
+        return frame->fetchContext();
+    return FetchContext::nullInstance();
+}
+
+unsigned long ResourceFetcher::fetchSynchronously(const ResourceRequest& passedRequest, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
+{
+    ASSERT(document());
+    ResourceRequest request(passedRequest);
+    request.setTimeoutInterval(10);
+    addAdditionalRequestHeaders(request, Resource::Raw);
+
+    unsigned long identifier = createUniqueIdentifier();
+    context().dispatchWillSendRequest(m_documentLoader, identifier, request, ResourceResponse());
+    documentLoader()->applicationCacheHost()->willStartLoadingSynchronously(request);
+    ResourceLoader::loadResourceSynchronously(request, storedCredentials, error, response, data);
+    int encodedDataLength = response.resourceLoadInfo() ? static_cast<int>(response.resourceLoadInfo()->encodedDataLength) : -1;
+    context().sendRemainingDelegateMessages(m_documentLoader, identifier, response, data.data(), data.size(), encodedDataLength, error);
+    return identifier;
+}
+
 ResourcePtr<ImageResource> ResourceFetcher::fetchImage(FetchRequest& request)
 {
     if (Frame* f = frame()) {
@@ -302,40 +328,50 @@
     return static_cast<RawResource*>(requestResource(Resource::MainResource, request).get());
 }
 
-bool ResourceFetcher::checkInsecureContent(Resource::Type type, const KURL& url) const
+bool ResourceFetcher::checkInsecureContent(Resource::Type type, const KURL& url, MixedContentBlockingTreatment treatment) const
 {
-    switch (type) {
-    case Resource::Script:
-    case Resource::XSLStyleSheet:
-    case Resource::SVGDocument:
-    case Resource::CSSStyleSheet:
-    case Resource::ImportResource:
-        // These resource can inject script into the current document (Script,
-        // XSL) or exfiltrate the content of the current document (CSS).
+    if (treatment == TreatAsDefaultForType) {
+        switch (type) {
+        case Resource::Script:
+        case Resource::XSLStyleSheet:
+        case Resource::SVGDocument:
+        case Resource::CSSStyleSheet:
+        case Resource::ImportResource:
+            // These resource can inject script into the current document (Script,
+            // XSL) or exfiltrate the content of the current document (CSS).
+            treatment = TreatAsActiveContent;
+            break;
+
+        case Resource::TextTrack:
+        case Resource::Shader:
+        case Resource::Raw:
+        case Resource::Image:
+        case Resource::Font:
+            // These resources can corrupt only the frame's pixels.
+            treatment = TreatAsPassiveContent;
+            break;
+
+        case Resource::MainResource:
+        case Resource::LinkPrefetch:
+        case Resource::LinkSubresource:
+            // These cannot affect the current document.
+            treatment = TreatAsAlwaysAllowedContent;
+            break;
+        }
+    }
+    if (treatment == TreatAsActiveContent) {
         if (Frame* f = frame()) {
             if (!f->loader()->mixedContentChecker()->canRunInsecureContent(m_document->securityOrigin(), url))
                 return false;
         }
-
-        break;
-    case Resource::TextTrack:
-    case Resource::Shader:
-    case Resource::Raw:
-    case Resource::Image:
-    case Resource::Font: {
-        // These resources can corrupt only the frame's pixels.
+    } else if (treatment == TreatAsPassiveContent) {
         if (Frame* f = frame()) {
             Frame* top = f->tree()->top();
             if (!top->loader()->mixedContentChecker()->canDisplayInsecureContent(top->document()->securityOrigin(), url))
                 return false;
         }
-        break;
-    }
-    case Resource::MainResource:
-    case Resource::LinkPrefetch:
-    case Resource::LinkSubresource:
-        // Prefetch cannot affect the current document.
-        break;
+    } else {
+        ASSERT(treatment == TreatAsAlwaysAllowedContent);
     }
     return true;
 }
@@ -344,7 +380,7 @@
 {
     if (document() && !document()->securityOrigin()->canDisplay(url)) {
         if (!forPreload)
-            FrameLoader::reportLocalLoadFailed(frame(), url.elidedString());
+            context().reportLocalLoadFailed(url);
         LOG(ResourceLoading, "ResourceFetcher::requestResource URL was not allowed by SecurityOrigin::canDisplay");
         return 0;
     }
@@ -435,7 +471,7 @@
     // They'll still get a warning in the console about CSP blocking the load.
 
     // FIXME: Should we consider forPreload here?
-    if (!checkInsecureContent(type, url))
+    if (!checkInsecureContent(type, url, options.mixedContentBlockingTreatment))
         return false;
 
     return true;
@@ -624,11 +660,11 @@
     if (type == Resource::MainResource) {
         FrameLoadType frameLoadType = frame()->loader()->loadType();
         bool isReload = frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin;
-        if (request.httpMethod() == "POST" && (isReload || frameLoadType == FrameLoadTypeBackForward))
+        if (request.httpMethod() == "POST" && frameLoadType == FrameLoadTypeBackForward)
             return ReturnCacheDataDontLoad;
         if (!m_documentLoader->overrideEncoding().isEmpty() || frameLoadType == FrameLoadTypeBackForward)
             return ReturnCacheDataElseLoad;
-        if (isReload || frameLoadType == FrameLoadTypeSame || request.isConditional())
+        if (isReload || frameLoadType == FrameLoadTypeSame || request.isConditional() || request.httpMethod() == "POST")
             return ReloadIgnoringCacheData;
         return UseProtocolCachePolicy;
     }
@@ -652,37 +688,14 @@
     if (!frame())
         return;
 
-    bool isMainResource = type == Resource::MainResource;
-
-    FrameLoader* frameLoader = frame()->loader();
-
-    if (!isMainResource) {
-        String outgoingReferrer;
-        String outgoingOrigin;
-        if (request.httpReferrer().isNull()) {
-            outgoingReferrer = frameLoader->outgoingReferrer();
-            outgoingOrigin = frameLoader->outgoingOrigin();
-        } else {
-            outgoingReferrer = request.httpReferrer();
-            outgoingOrigin = SecurityOrigin::createFromString(outgoingReferrer)->toString();
-        }
-
-        outgoingReferrer = SecurityPolicy::generateReferrerHeader(document()->referrerPolicy(), request.url(), outgoingReferrer);
-        if (outgoingReferrer.isEmpty())
-            request.clearHTTPReferrer();
-        else if (!request.httpReferrer())
-            request.setHTTPReferrer(outgoingReferrer);
-
-        FrameLoader::addHTTPOriginIfNeeded(request, outgoingOrigin);
-    }
-
     if (request.cachePolicy() == UseProtocolCachePolicy)
         request.setCachePolicy(resourceRequestCachePolicy(request, type));
     if (request.targetType() == ResourceRequest::TargetIsUnspecified)
         determineTargetType(request, type);
     if (type == Resource::LinkPrefetch || type == Resource::LinkSubresource)
         request.setHTTPHeaderField("Purpose", "prefetch");
-    frameLoader->addExtraFieldsToRequest(request);
+
+    context().addAdditionalRequestHeaders(*document(), request, type);
 }
 
 ResourcePtr<Resource> ResourceFetcher::revalidateResource(const FetchRequest& request, Resource* resource)
@@ -699,8 +712,8 @@
     const String& lastModified = resource->response().httpHeaderField("Last-Modified");
     const String& eTag = resource->response().httpHeaderField("ETag");
     if (!lastModified.isEmpty() || !eTag.isEmpty()) {
-        ASSERT(cachePolicy(resource->type()) != CachePolicyReload);
-        if (cachePolicy(resource->type()) == CachePolicyRevalidate)
+        ASSERT(context().cachePolicy(resource->type()) != CachePolicyReload);
+        if (context().cachePolicy(resource->type()) == CachePolicyRevalidate)
             revalidatingRequest.setHTTPHeaderField("Cache-Control", "max-age=0");
         if (!lastModified.isEmpty())
             revalidatingRequest.setHTTPHeaderField("If-Modified-Since", lastModified);
@@ -797,7 +810,7 @@
         return Use;
 
     // CachePolicyHistoryBuffer uses the cache no matter what.
-    if (cachePolicy(type) == CachePolicyHistoryBuffer)
+    if (context().cachePolicy(type) == CachePolicyHistoryBuffer)
         return Use;
 
     // Don't reuse resources with Cache-control: no-store.
@@ -822,7 +835,7 @@
         return Use;
 
     // CachePolicyReload always reloads
-    if (cachePolicy(type) == CachePolicyReload) {
+    if (context().cachePolicy(type) == CachePolicyReload) {
         LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to CachePolicyReload.");
         return Reload;
     }
@@ -838,7 +851,7 @@
         return Use;
 
     // Check if the cache headers requires us to revalidate (cache expiration for example).
-    if (existingResource->mustRevalidateDueToCacheHeaders(cachePolicy(type))) {
+    if (existingResource->mustRevalidateDueToCacheHeaders(context().cachePolicy(type))) {
         // See if the resource has usable ETag or Last-modified headers.
         if (existingResource->canUseCacheValidator())
             return Revalidate;
@@ -914,19 +927,6 @@
     }
 }
 
-CachePolicy ResourceFetcher::cachePolicy(Resource::Type type) const
-{
-    if (!frame())
-        return CachePolicyVerify;
-
-    if (type != Resource::MainResource)
-        return frame()->loader()->subresourceCachePolicy();
-
-    if (frame()->loader()->loadType() == FrameLoadTypeReloadFromOrigin || frame()->loader()->loadType() == FrameLoadTypeReload)
-        return CachePolicyReload;
-    return CachePolicyVerify;
-}
-
 void ResourceFetcher::redirectReceived(Resource* resource, const ResourceResponse& redirectResponse)
 {
     ResourceTimingInfoMap::iterator it = m_resourceTimingInfoMap.find(resource);
@@ -997,11 +997,18 @@
 
 void ResourceFetcher::notifyLoadedFromMemoryCache(Resource* resource)
 {
-    if (!frame() || resource->status() != Resource::Cached || m_validatedURLs.contains(resource->url()))
+    if (!frame() || !frame()->page() || resource->status() != Resource::Cached || m_validatedURLs.contains(resource->url()))
+        return;
+    if (!resource->shouldSendResourceLoadCallbacks())
         return;
 
-    // FIXME: If the WebKit client changes or cancels the request, WebCore does not respect this and continues the load.
-    frame()->loader()->loadedResourceFromMemoryCache(resource);
+    ResourceRequest request(resource->url());
+    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());
+    InspectorInstrumentation::markResourceAsCached(frame()->page(), identifier);
+    context().sendRemainingDelegateMessages(m_documentLoader, identifier, resource->response(), 0, resource->encodedSize(), 0, ResourceError());
 }
 
 void ResourceFetcher::incrementRequestCount(const Resource* res)
@@ -1122,27 +1129,18 @@
     m_pendingPreloads.clear();
 }
 
-inline FrameLoader* ResourceFetcher::frameLoader()
-{
-    if (Frame* frame = this->frame())
-        return frame->loader();
-    return 0;
-}
-
 void ResourceFetcher::didFinishLoading(const Resource* resource, double finishTime, const ResourceLoaderOptions& options)
 {
     TRACE_EVENT_ASYNC_END0("net", "Resource", resource);
     if (options.sendLoadCallbacks != SendCallbacks)
         return;
-    if (FrameLoader* loader = frameLoader())
-        loader->notifier()->dispatchDidFinishLoading(m_documentLoader, resource->identifier(), finishTime);
+    context().dispatchDidFinishLoading(m_documentLoader, resource->identifier(), finishTime);
 }
 
 void ResourceFetcher::didChangeLoadingPriority(const Resource* resource, ResourceLoadPriority loadPriority)
 {
     TRACE_EVENT_ASYNC_STEP1("net", "Resource", resource, "ChangePriority", "priority", loadPriority);
-    if (FrameLoader* loader = frameLoader())
-        loader->client()->dispatchDidChangeResourcePriority(resource->identifier(), loadPriority);
+    context().dispatchDidChangeResourcePriority(resource->identifier(), loadPriority);
 }
 
 void ResourceFetcher::didFailLoading(const Resource* resource, const ResourceError& error, const ResourceLoaderOptions& options)
@@ -1150,26 +1148,22 @@
     TRACE_EVENT_ASYNC_END0("net", "Resource", resource);
     if (options.sendLoadCallbacks != SendCallbacks)
         return;
-    if (FrameLoader* loader = frameLoader())
-        loader->notifier()->dispatchDidFail(m_documentLoader, resource->identifier(), error);
+    context().dispatchDidFail(m_documentLoader, resource->identifier(), error);
 }
 
 void ResourceFetcher::willSendRequest(const Resource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse, const ResourceLoaderOptions& options)
 {
-    if (options.sendLoadCallbacks == SendCallbacks) {
-        if (FrameLoader* loader = frameLoader())
-            loader->notifier()->dispatchWillSendRequest(m_documentLoader, resource->identifier(), request, redirectResponse, options.initiatorInfo);
-    } else {
+    if (options.sendLoadCallbacks == SendCallbacks)
+        context().dispatchWillSendRequest(m_documentLoader, resource->identifier(), request, redirectResponse, options.initiatorInfo);
+    else
         InspectorInstrumentation::willSendRequest(frame(), resource->identifier(), m_documentLoader, request, redirectResponse, options.initiatorInfo);
-    }
 }
 
 void ResourceFetcher::didReceiveResponse(const Resource* resource, const ResourceResponse& response, const ResourceLoaderOptions& options)
 {
     if (options.sendLoadCallbacks != SendCallbacks)
         return;
-    if (FrameLoader* loader = frameLoader())
-        loader->notifier()->dispatchDidReceiveResponse(m_documentLoader, resource->identifier(), response);
+    context().dispatchDidReceiveResponse(m_documentLoader, resource->identifier(), response, resource->loader());
 }
 
 void ResourceFetcher::didReceiveData(const Resource* resource, const char* data, int dataLength, int encodedDataLength, const ResourceLoaderOptions& options)
@@ -1178,27 +1172,37 @@
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceData(frame(), resource->identifier(), encodedDataLength);
     if (options.sendLoadCallbacks != SendCallbacks)
         return;
-    if (FrameLoader* loader = frameLoader())
-        loader->notifier()->dispatchDidReceiveData(m_documentLoader, resource->identifier(), data, dataLength, encodedDataLength);
+    context().dispatchDidReceiveData(m_documentLoader, resource->identifier(), data, dataLength, encodedDataLength);
     InspectorInstrumentation::didReceiveResourceData(cookie);
 }
 
 void ResourceFetcher::subresourceLoaderFinishedLoadingOnePart(ResourceLoader* loader)
 {
-    if (m_documentLoader)
-        m_documentLoader->subresourceLoaderFinishedLoadingOnePart(loader);
+    if (m_multipartLoaders)
+        m_multipartLoaders->add(loader);
+    if (m_loaders)
+        m_loaders->remove(loader);
+    if (Frame* frame = this->frame())
+        return frame->loader()->checkLoadComplete(m_documentLoader);
 }
 
 void ResourceFetcher::didInitializeResourceLoader(ResourceLoader* loader)
 {
-    if (m_documentLoader)
-        m_documentLoader->addResourceLoader(loader);
+    if (!m_document)
+        return;
+    if (!m_loaders)
+        m_loaders = adoptPtr(new ResourceLoaderSet());
+    ASSERT(!m_loaders->contains(loader));
+    m_loaders->add(loader);
 }
 
 void ResourceFetcher::willTerminateResourceLoader(ResourceLoader* loader)
 {
-    if (m_documentLoader)
-        m_documentLoader->removeResourceLoader(loader);
+    if (!m_loaders || !m_loaders->contains(loader))
+        return;
+    m_loaders->remove(loader);
+    if (Frame* frame = this->frame())
+        frame->loader()->checkLoadComplete(m_documentLoader);
 }
 
 void ResourceFetcher::willStartLoadingResource(ResourceRequest& request)
@@ -1207,6 +1211,25 @@
         m_documentLoader->applicationCacheHost()->willStartLoadingResource(request);
 }
 
+void ResourceFetcher::stopFetching()
+{
+    if (m_multipartLoaders)
+        m_multipartLoaders->cancelAll();
+    if (m_loaders)
+        m_loaders->cancelAll();
+}
+
+bool ResourceFetcher::isFetching() const
+{
+    return m_loaders && !m_loaders->isEmpty();
+}
+
+void ResourceFetcher::setDefersLoading(bool defers)
+{
+    if (m_loaders)
+        m_loaders->setAllDefersLoading(defers);
+}
+
 bool ResourceFetcher::defersLoading() const
 {
     if (Frame* frame = this->frame())
diff --git a/Source/core/fetch/ResourceFetcher.h b/Source/core/fetch/ResourceFetcher.h
index 93626ab..5f1b975 100644
--- a/Source/core/fetch/ResourceFetcher.h
+++ b/Source/core/fetch/ResourceFetcher.h
@@ -31,6 +31,7 @@
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/Resource.h"
 #include "core/fetch/ResourceLoaderHost.h"
+#include "core/fetch/ResourceLoaderOptions.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/platform/Timer.h"
 #include "wtf/Deque.h"
@@ -43,6 +44,7 @@
 
 class CSSStyleSheetResource;
 class DocumentResource;
+class FetchContext;
 class FontResource;
 class ImageResource;
 class RawResource;
@@ -57,6 +59,7 @@
 class ImageLoader;
 class KURL;
 class ResourceTimingInfo;
+class ResourceLoaderSet;
 
 // The ResourceFetcher provides a per-context interface to the MemoryCache
 // and enforces a bunch of security checks and rules for resource revalidation.
@@ -78,6 +81,8 @@
     using RefCounted<ResourceFetcher>::ref;
     using RefCounted<ResourceFetcher>::deref;
 
+    unsigned long fetchSynchronously(const ResourceRequest&, StoredCredentials, ResourceError&, ResourceResponse&, Vector<char>&);
+
     ResourcePtr<ImageResource> fetchImage(FetchRequest&);
     ResourcePtr<CSSStyleSheetResource> fetchCSSStyleSheet(FetchRequest&);
     ResourcePtr<CSSStyleSheetResource> fetchUserCSSStyleSheet(FetchRequest&);
@@ -108,9 +113,8 @@
 
     bool shouldDeferImageLoad(const KURL&) const;
 
-    CachePolicy cachePolicy(Resource::Type) const;
-
     Frame* frame() const; // Can be null
+    FetchContext& context() const;
     Document* document() const { return m_document; } // Can be null
     void setDocument(Document* document) { m_document = document; }
 
@@ -129,6 +133,11 @@
     void printPreloadStats();
     bool canRequest(Resource::Type, const KURL&, const ResourceLoaderOptions&, bool forPreload = false);
     bool canAccess(Resource*);
+    bool checkInsecureContent(Resource::Type, const KURL&, MixedContentBlockingTreatment) const;
+
+    void setDefersLoading(bool);
+    void stopFetching();
+    bool isFetching() const;
 
     // ResourceLoaderHost
     virtual void incrementRequestCount(const Resource*) OVERRIDE;
@@ -156,7 +165,6 @@
 
     explicit ResourceFetcher(DocumentLoader*);
 
-    FrameLoader* frameLoader();
     bool shouldLoadNewResource() const;
 
     ResourcePtr<Resource> requestResource(Resource::Type, FetchRequest&);
@@ -174,7 +182,6 @@
     void addAdditionalRequestHeaders(ResourceRequest&, Resource::Type);
 
     void notifyLoadedFromMemoryCache(Resource*);
-    bool checkInsecureContent(Resource::Type, const KURL&) const;
 
     void garbageCollectDocumentResourcesTimerFired(Timer<ResourceFetcher>*);
     void performPostLoadActions();
@@ -202,6 +209,9 @@
     typedef HashMap<Resource*, RefPtr<ResourceTimingInfo> > ResourceTimingInfoMap;
     ResourceTimingInfoMap m_resourceTimingInfoMap;
 
+    OwnPtr<ResourceLoaderSet> m_loaders;
+    OwnPtr<ResourceLoaderSet> m_multipartLoaders;
+
     // 29 bits left
     bool m_autoLoadImages : 1;
     bool m_imagesEnabled : 1;
diff --git a/Source/core/fetch/ResourceLoadNotifier.cpp b/Source/core/fetch/ResourceLoadNotifier.cpp
deleted file mode 100644
index 4e6b266..0000000
--- a/Source/core/fetch/ResourceLoadNotifier.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
- /*
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- *
- * 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE 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 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/fetch/ResourceLoadNotifier.h"
-
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/DocumentLoader.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/loader/ProgressTracker.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-
-namespace WebCore {
-
-ResourceLoadNotifier::ResourceLoadNotifier(Frame* frame)
-    : m_frame(frame)
-{
-}
-
-
-// FIXME(http://crbug.com/274173):
-// |loader| can be null if the resource is loaded from imported document.
-// This means inspector, which uses DocumentLoader as an grouping entity,
-// cannot see imported documents.
-inline DocumentLoader* ResourceLoadNotifier::ensureLoader(DocumentLoader* loader)
-{
-    return loader ? loader : m_frame->loader()->activeDocumentLoader();
-}
-
-void ResourceLoadNotifier::dispatchWillSendRequest(DocumentLoader* loader, unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& initiatorInfo)
-{
-    m_frame->loader()->applyUserAgent(request);
-    m_frame->loader()->client()->dispatchWillSendRequest(loader, identifier, request, redirectResponse);
-    InspectorInstrumentation::willSendRequest(m_frame, identifier, ensureLoader(loader), request, redirectResponse, initiatorInfo);
-}
-
-void ResourceLoadNotifier::dispatchDidReceiveResponse(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, ResourceLoader* resourceLoader)
-{
-    if (Page* page = m_frame->page())
-        page->progress().incrementProgress(identifier, r);
-    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_frame, identifier, r);
-    m_frame->loader()->client()->dispatchDidReceiveResponse(loader, identifier, r);
-    InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, ensureLoader(loader), r, resourceLoader);
-}
-
-void ResourceLoadNotifier::dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength)
-{
-    if (Page* page = m_frame->page())
-        page->progress().incrementProgress(identifier, data, dataLength);
-    InspectorInstrumentation::didReceiveData(m_frame, identifier, data, dataLength, encodedDataLength);
-}
-
-void ResourceLoadNotifier::dispatchDidFinishLoading(DocumentLoader* loader, unsigned long identifier, double finishTime)
-{
-    if (Page* page = m_frame->page())
-        page->progress().completeProgress(identifier);
-    m_frame->loader()->client()->dispatchDidFinishLoading(loader, identifier);
-
-    InspectorInstrumentation::didFinishLoading(m_frame, identifier, ensureLoader(loader), finishTime);
-}
-
-void ResourceLoadNotifier::dispatchDidFail(DocumentLoader* loader, unsigned long identifier, const ResourceError& error)
-{
-    if (Page* page = m_frame->page())
-        page->progress().completeProgress(identifier);
-    InspectorInstrumentation::didFailLoading(m_frame, identifier, ensureLoader(loader), error);
-}
-
-void ResourceLoadNotifier::sendRemainingDelegateMessages(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& response, const char* data, int dataLength, int encodedDataLength, const ResourceError& error)
-{
-    if (!response.isNull())
-        dispatchDidReceiveResponse(ensureLoader(loader), identifier, response);
-
-    if (dataLength > 0)
-        dispatchDidReceiveData(ensureLoader(loader), identifier, data, dataLength, encodedDataLength);
-
-    if (error.isNull())
-        dispatchDidFinishLoading(ensureLoader(loader), identifier, 0);
-    else
-        dispatchDidFail(ensureLoader(loader), identifier, error);
-}
-
-} // namespace WebCore
diff --git a/Source/core/fetch/ResourceLoadNotifier.h b/Source/core/fetch/ResourceLoadNotifier.h
deleted file mode 100644
index 6dd11d8..0000000
--- a/Source/core/fetch/ResourceLoadNotifier.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- *
- * 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.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE 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 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.
- */
-
-#ifndef ResourceLoadNotifier_h
-#define ResourceLoadNotifier_h
-
-#include "core/fetch/FetchInitiatorInfo.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class DocumentLoader;
-class Frame;
-class Page;
-class ResourceError;
-class ResourceLoader;
-class ResourceResponse;
-class ResourceRequest;
-
-class ResourceLoadNotifier {
-    WTF_MAKE_NONCOPYABLE(ResourceLoadNotifier);
-public:
-    ResourceLoadNotifier(Frame*);
-
-    void dispatchWillSendRequest(DocumentLoader*, unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& = FetchInitiatorInfo());
-    void dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse&, ResourceLoader* = 0);
-    void dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength);
-    void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier, double finishTime);
-    void dispatchDidFail(DocumentLoader*, unsigned long identifier, const ResourceError&);
-
-    void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, const char* data, int dataLength, int encodedDataLength, const ResourceError&);
-
-private:
-    inline DocumentLoader* ensureLoader(DocumentLoader*);
-
-    Frame* m_frame;
-};
-
-} // namespace WebCore
-
-#endif // ResourceLoadNotifier_h
diff --git a/Source/core/fetch/ResourceLoaderOptions.h b/Source/core/fetch/ResourceLoaderOptions.h
index 187efc3..be960d3 100644
--- a/Source/core/fetch/ResourceLoaderOptions.h
+++ b/Source/core/fetch/ResourceLoaderOptions.h
@@ -90,6 +90,13 @@
     ClientDidNotRequestCredentials
 };
 
+enum MixedContentBlockingTreatment {
+    TreatAsDefaultForType,
+    TreatAsPassiveContent,
+    TreatAsActiveContent,
+    TreatAsAlwaysAllowedContent
+};
+
 struct ResourceLoaderOptions {
     ResourceLoaderOptions()
         : sendLoadCallbacks(DoNotSendCallbacks)
@@ -102,6 +109,7 @@
         , contentSecurityPolicyOption(CheckContentSecurityPolicy)
         , requestOriginPolicy(UseDefaultOriginRestrictionsForType)
         , requestInitiatorContext(DocumentContext)
+        , mixedContentBlockingTreatment(TreatAsDefaultForType)
     {
     }
 
@@ -126,8 +134,10 @@
         , contentSecurityPolicyOption(contentSecurityPolicyOption)
         , requestOriginPolicy(requestOriginPolicy)
         , requestInitiatorContext(requestInitiatorContext)
+        , mixedContentBlockingTreatment(TreatAsDefaultForType)
     {
     }
+
     SendCallbackPolicy sendLoadCallbacks;
     ContentSniffingPolicy sniffContent;
     DataBufferingPolicy dataBufferingPolicy;
@@ -139,6 +149,7 @@
     FetchInitiatorInfo initiatorInfo;
     RequestOriginPolicy requestOriginPolicy;
     RequestInitiatorContext requestInitiatorContext;
+    MixedContentBlockingTreatment mixedContentBlockingTreatment;
 };
 
 } // namespace WebCore
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/fetch/ResourceLoaderSet.cpp
similarity index 70%
copy from Source/core/loader/CachedMetadata.cpp
copy to Source/core/fetch/ResourceLoaderSet.cpp
index f3f2a30..f4671ea 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/fetch/ResourceLoaderSet.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * 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
@@ -29,8 +29,28 @@
  */
 
 #include "config.h"
-#include "core/loader/CachedMetadata.h"
+#include "core/fetch/ResourceLoaderSet.h"
+
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
-} // namespace WebCore
+void ResourceLoaderSet::cancelAll()
+{
+    Vector<RefPtr<ResourceLoader> > loadersCopy;
+    copyToVector(m_set, loadersCopy);
+    size_t size = loadersCopy.size();
+    for (size_t i = 0; i < size; ++i)
+        loadersCopy[i]->cancel();
+}
+
+void ResourceLoaderSet::setAllDefersLoading(bool defers)
+{
+    Vector<RefPtr<ResourceLoader> > loadersCopy;
+    copyToVector(m_set, loadersCopy);
+    size_t size = loadersCopy.size();
+    for (size_t i = 0; i < size; ++i)
+        loadersCopy[i]->setDefersLoading(defers);
+}
+
+}
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/fetch/ResourceLoaderSet.h
similarity index 69%
copy from Source/core/loader/CachedMetadata.cpp
copy to Source/core/fetch/ResourceLoaderSet.h
index f3f2a30..d499917 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/fetch/ResourceLoaderSet.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * 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
@@ -28,9 +28,29 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/loader/CachedMetadata.h"
+#ifndef ResourceLoaderSet_h
+#define ResourceLoaderSet_h
+
+#include "core/fetch/ResourceLoader.h"
+#include "wtf/HashSet.h"
 
 namespace WebCore {
 
-} // namespace WebCore
+class ResourceLoaderSet {
+public:
+    typedef HashSet<RefPtr<ResourceLoader> > SetType;
+
+    void add(const RefPtr<ResourceLoader>& loader) { m_set.add(loader); }
+    void remove(const RefPtr<ResourceLoader>& loader) { m_set.remove(loader); }
+    bool isEmpty() const { return m_set.isEmpty(); }
+    bool contains(const RefPtr<ResourceLoader>& loader) const { return m_set.contains(loader); }
+    void cancelAll();
+    void setAllDefersLoading(bool);
+
+private:
+    SetType m_set;
+};
+
+}
+
+#endif
diff --git a/Source/core/fetch/ScriptResource.cpp b/Source/core/fetch/ScriptResource.cpp
index 330a1bf..7bbfdeb 100644
--- a/Source/core/fetch/ScriptResource.cpp
+++ b/Source/core/fetch/ScriptResource.cpp
@@ -27,7 +27,7 @@
 #include "config.h"
 #include "core/fetch/ScriptResource.h"
 
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/network/HTTPParsers.h"
diff --git a/Source/core/fetch/ShaderResource.cpp b/Source/core/fetch/ShaderResource.cpp
index bacaef9..cbd25df 100644
--- a/Source/core/fetch/ShaderResource.cpp
+++ b/Source/core/fetch/ShaderResource.cpp
@@ -30,7 +30,7 @@
 #include "config.h"
 #include "core/fetch/ShaderResource.h"
 
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/platform/SharedBuffer.h"
 #include "wtf/text/StringBuilder.h"
 
diff --git a/Source/core/loader/TextResourceDecoder.cpp b/Source/core/fetch/TextResourceDecoder.cpp
similarity index 86%
rename from Source/core/loader/TextResourceDecoder.cpp
rename to Source/core/fetch/TextResourceDecoder.cpp
index 139fcf1..b6759bf 100644
--- a/Source/core/loader/TextResourceDecoder.cpp
+++ b/Source/core/fetch/TextResourceDecoder.cpp
@@ -21,7 +21,7 @@
 
 
 #include "config.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 
 #include "HTMLNames.h"
 #include "core/dom/DOMImplementation.h"
@@ -175,9 +175,9 @@
     while (i < size) {
         if (ptr[i] == ESC && (size - i >= 3)) {
             if (bytesEqual(str + i + 1, '$', 'B')
-                    || bytesEqual(str + i + 1, '(', 'B')
-                    || bytesEqual(str + i + 1, '$', '@')
-                    || bytesEqual(str + i + 1, '(', 'J')) {
+                || bytesEqual(str + i + 1, '(', 'B')
+                || bytesEqual(str + i + 1, '$', '@')
+                || bytesEqual(str + i + 1, '(', 'J')) {
                 code = JIS;
                 goto breakBreak;
             }
@@ -195,11 +195,10 @@
                 bfk = 0;
                 /* ?? check kudokuten ?? && ?? hiragana ?? */
                 if ((i >= 2) && (ptr[i - 2] == 0x81)
-                        && (0x41 <= ptr[i - 1] && ptr[i - 1] <= 0x49)) {
+                    && (0x41 <= ptr[i - 1] && ptr[i - 1] <= 0x49)) {
                     code = SJIS;
                     sjis += 100;        /* kudokuten */
-                } else if ((i >= 2) && (ptr[i - 2] == 0xa1)
-                        && (0xa2 <= ptr[i - 1] && ptr[i - 1] <= 0xaa)) {
+                } else if ((i >= 2) && (ptr[i - 2] == 0xa1) && (0xa2 <= ptr[i - 1] && ptr[i - 1] <= 0xaa)) {
                     code = EUC;
                     euc += 100;         /* kudokuten */
                 } else if ((i >= 2) && (ptr[i - 2] == 0x82) && (0xa0 <= ptr[i - 1])) {
@@ -211,8 +210,7 @@
                 /* ?? check hiragana or katana ?? */
                 if ((size - i > 1) && (ptr[i] == 0x82) && (0xa0 <= ptr[i + 1])) {
                     sjis++;     /* hiragana */
-                } else if ((size - i > 1) && (ptr[i] == 0x83)
-                         && (0x40 <= ptr[i + 1] && ptr[i + 1] <= 0x9f)) {
+                } else if ((size - i > 1) && (ptr[i] == 0x83) && (0x40 <= ptr[i + 1] && ptr[i + 1] <= 0x9f)) {
                     sjis++;     /* katakana */
                 } else if ((size - i > 1) && (ptr[i] == 0xa4) && (0xa0 <= ptr[i + 1])) {
                     euc++;      /* hiragana */
@@ -223,39 +221,50 @@
                     if ((i >= 1) && (0x40 <= ptr[i] && ptr[i] <= 0xa0) && ISkanji(ptr[i - 1])) {
                         code = SJIS;
                         goto breakBreak;
-                    } else if ((i >= 1) && (0x81 <= ptr[i - 1] && ptr[i - 1] <= 0x9f) && ((0x40 <= ptr[i] && ptr[i] < 0x7e) || (0x7e < ptr[i] && ptr[i] <= 0xfc))) {
-                        code = SJIS;
-                        goto breakBreak;
-                    } else if ((i >= 1) && (0xfd <= ptr[i] && ptr[i] <= 0xfe) && (0xa1 <= ptr[i - 1] && ptr[i - 1] <= 0xfe)) {
-                        code = EUC;
-                        goto breakBreak;
-                    } else if ((i >= 1) && (0xfd <= ptr[i - 1] && ptr[i - 1] <= 0xfe) && (0xa1 <= ptr[i] && ptr[i] <= 0xfe)) {
-                        code = EUC;
-                        goto breakBreak;
-                    } else if ((i >= 1) && (ptr[i] < 0xa0 || 0xdf < ptr[i]) && (0x8e == ptr[i - 1])) {
-                        code = SJIS;
-                        goto breakBreak;
-                    } else if (ptr[i] <= 0x7f) {
-                        code = SJIS;
-                        goto breakBreak;
-                    } else {
-                        if (0xa1 <= ptr[i] && ptr[i] <= 0xa6) {
-                            euc++;      /* sjis hankaku kana kigo */
-                        } else if (0xa1 <= ptr[i] && ptr[i] <= 0xdf) {
-                            ;           /* sjis hankaku kana */
-                        } else if (0xa1 <= ptr[i] && ptr[i] <= 0xfe) {
-                            euc++;
-                        } else if (0x8e == ptr[i]) {
-                            euc++;
-                        } else if (0x20 <= ptr[i] && ptr[i] <= 0x7f) {
-                            sjis++;
-                        }
-                        bfr = false;
-                        bfk = 0;
                     }
+
+                    if ((i >= 1) && (0x81 <= ptr[i - 1] && ptr[i - 1] <= 0x9f) && ((0x40 <= ptr[i] && ptr[i] < 0x7e) || (0x7e < ptr[i] && ptr[i] <= 0xfc))) {
+                        code = SJIS;
+                        goto breakBreak;
+                    }
+
+                    if ((i >= 1) && (0xfd <= ptr[i] && ptr[i] <= 0xfe) && (0xa1 <= ptr[i - 1] && ptr[i - 1] <= 0xfe)) {
+                        code = EUC;
+                        goto breakBreak;
+                    }
+
+                    if ((i >= 1) && (0xfd <= ptr[i - 1] && ptr[i - 1] <= 0xfe) && (0xa1 <= ptr[i] && ptr[i] <= 0xfe)) {
+                        code = EUC;
+                        goto breakBreak;
+                    }
+
+                    if ((i >= 1) && (ptr[i] < 0xa0 || 0xdf < ptr[i]) && (0x8e == ptr[i - 1])) {
+                        code = SJIS;
+                        goto breakBreak;
+                    }
+
+                    if (ptr[i] <= 0x7f) {
+                        code = SJIS;
+                        goto breakBreak;
+                    }
+
+                    if (0xa1 <= ptr[i] && ptr[i] <= 0xa6) {
+                        euc++;      /* sjis hankaku kana kigo */
+                    } else if (0xa1 <= ptr[i] && ptr[i] <= 0xdf) {
+                        /* sjis hankaku kana */
+                    } else if (0xa1 <= ptr[i] && ptr[i] <= 0xfe) {
+                        euc++;
+                    } else if (0x8e == ptr[i]) {
+                        euc++;
+                    } else if (0x20 <= ptr[i] && ptr[i] <= 0x7f) {
+                        sjis++;
+                    }
+
+                    bfr = false;
+                    bfk = 0;
                 } else if (0x8e == ptr[i]) {
                     if (size - i <= 1) {
-                        ;
+
                     } else if (0xa1 <= ptr[i + 1] && ptr[i + 1] <= 0xdf) {
                         /* EUC KANA or SJIS KANJI */
                         if (bfk == 1) {
@@ -271,20 +280,15 @@
                 } else if (0x81 <= ptr[i] && ptr[i] <= 0x9f) {
                     /* SJIS only */
                     code = SJIS;
-                    if ((size - i >= 1)
-                            && ((0x40 <= ptr[i + 1] && ptr[i + 1] <= 0x7e)
-                            || (0x80 <= ptr[i + 1] && ptr[i + 1] <= 0xfc))) {
+                    if ((size - i >= 1) && ((0x40 <= ptr[i + 1] && ptr[i + 1] <= 0x7e) || (0x80 <= ptr[i + 1] && ptr[i + 1] <= 0xfc)))
                         goto breakBreak;
-                    }
                 } else if (0xfd <= ptr[i] && ptr[i] <= 0xfe) {
                     /* EUC only */
                     code = EUC;
-                    if ((size - i >= 1)
-                            && (0xa1 <= ptr[i + 1] && ptr[i + 1] <= 0xfe)) {
+                    if ((size - i >= 1) && (0xa1 <= ptr[i + 1] && ptr[i + 1] <= 0xfe))
                         goto breakBreak;
-                    }
                 } else if (ptr[i] <= 0x7f) {
-                    ;
+
                 } else {
                     bfr = true;
                     bfk = 0;
@@ -353,7 +357,7 @@
 
     // When encoding comes from meta tag (i.e. it cannot be XML files sent via XHR),
     // treat x-user-defined as windows-1252 (bug 18270)
-    if (source == EncodingFromMetaTag && strcasecmp(encoding.name(), "x-user-defined") == 0)
+    if (source == EncodingFromMetaTag && !strcasecmp(encoding.name(), "x-user-defined"))
         m_encoding = "windows-1252";
     else if (source == EncodingFromMetaTag || source == EncodingFromXMLHeader || source == EncodingFromCSSCharset)
         m_encoding = encoding.closestByteBasedEquivalent();
@@ -433,7 +437,7 @@
 
     // Check for the BOM.
     if (c1 == 0xFF && c2 == 0xFE) {
-        if (c3 != 0 || c4 != 0) {
+        if (c3 || c4) {
             setEncoding(UTF16LittleEndianEncoding(), AutoDetectedEncoding);
             lengthOfBOM = 2;
         } else {
@@ -446,7 +450,7 @@
     } else if (c1 == 0xFE && c2 == 0xFF) {
         setEncoding(UTF16BigEndianEncoding(), AutoDetectedEncoding);
         lengthOfBOM = 2;
-    } else if (c1 == 0 && c2 == 0 && c3 == 0xFE && c4 == 0xFF) {
+    } else if (!c1 && !c2 && c3 == 0xFE && c4 == 0xFF) {
         setEncoding(UTF32BigEndianEncoding(), AutoDetectedEncoding);
         lengthOfBOM = 4;
     }
@@ -534,14 +538,15 @@
         if (pos != -1)
             setEncoding(findTextEncoding(ptr + pos, len), EncodingFromXMLHeader);
         // continue looking for a charset - it may be specified in an HTTP-Equiv meta
-    } else if (bytesEqual(ptr, '<', 0, '?', 0, 'x', 0))
+    } else if (bytesEqual(ptr, '<', 0, '?', 0, 'x', 0)) {
         setEncoding(UTF16LittleEndianEncoding(), AutoDetectedEncoding);
-    else if (bytesEqual(ptr, 0, '<', 0, '?', 0, 'x'))
+    } else if (bytesEqual(ptr, 0, '<', 0, '?', 0, 'x')) {
         setEncoding(UTF16BigEndianEncoding(), AutoDetectedEncoding);
-    else if (bytesEqual(ptr, '<', 0, 0, 0, '?', 0, 0, 0))
+    } else if (bytesEqual(ptr, '<', 0, 0, 0, '?', 0, 0, 0)) {
         setEncoding(UTF32LittleEndianEncoding(), AutoDetectedEncoding);
-    else if (bytesEqual(ptr, 0, 0, 0, '<', 0, 0, 0, '?'))
+    } else if (bytesEqual(ptr, 0, 0, 0, '<', 0, 0, 0, '?')) {
         setEncoding(UTF32BigEndianEncoding(), AutoDetectedEncoding);
+    }
 
     m_checkedForXMLCharset = true;
     return true;
@@ -569,19 +574,19 @@
 void TextResourceDecoder::detectJapaneseEncoding(const char* data, size_t len)
 {
     switch (KanjiCode::judge(data, len)) {
-        case KanjiCode::JIS:
-            setEncoding("ISO-2022-JP", EncodingFromContentSniffing);
-            break;
-        case KanjiCode::EUC:
-            setEncoding("EUC-JP", EncodingFromContentSniffing);
-            break;
-        case KanjiCode::SJIS:
-            setEncoding("Shift_JIS", EncodingFromContentSniffing);
-            break;
-        case KanjiCode::ASCII:
-        case KanjiCode::UTF16:
-        case KanjiCode::UTF8:
-            break;
+    case KanjiCode::JIS:
+        setEncoding("ISO-2022-JP", EncodingFromContentSniffing);
+        break;
+    case KanjiCode::EUC:
+        setEncoding("EUC-JP", EncodingFromContentSniffing);
+        break;
+    case KanjiCode::SJIS:
+        setEncoding("Shift_JIS", EncodingFromContentSniffing);
+        break;
+    case KanjiCode::ASCII:
+    case KanjiCode::UTF16:
+    case KanjiCode::UTF8:
+        break;
     }
 }
 
@@ -610,20 +615,22 @@
 
     bool movedDataToBuffer = false;
 
-    if (m_contentType == CSS && !m_checkedForCSSCharset)
+    if (m_contentType == CSS && !m_checkedForCSSCharset) {
         if (!checkForCSSCharset(data, len, movedDataToBuffer))
             return emptyString();
+    }
 
-    if ((m_contentType == HTML || m_contentType == XML) && !m_checkedForXMLCharset)
+    if ((m_contentType == HTML || m_contentType == XML) && !m_checkedForXMLCharset) {
         if (!checkForXMLCharset(data, len, movedDataToBuffer))
             return emptyString();
+    }
 
     // FIXME: It would be more efficient to move this logic below checkForMetaCharset because
     //        checkForMetaCharset can overrule these detections.
     if (shouldAutoDetect()) {
-        if (m_encoding.isJapanese())
+        if (m_encoding.isJapanese()) {
             detectJapaneseEncoding(data, len); // FIXME: We should use detectTextEncoding() for all languages.
-        else {
+        } else {
             WTF::TextEncoding detectedEncoding;
             if (detectTextEncoding(data, len, m_hintEncoding, &detectedEncoding))
                 setEncoding(detectedEncoding, EncodingFromContentSniffing);
@@ -660,9 +667,9 @@
 
 String TextResourceDecoder::flush()
 {
-   // If we can not identify the encoding even after a document is completely
-   // loaded, we need to detect the encoding if other conditions for
-   // autodetection is satisfied.
+    // If we can not identify the encoding even after a document is completely
+    // loaded, we need to detect the encoding if other conditions for
+    // autodetection is satisfied.
     if (m_buffer.size() && shouldAutoDetect()
         && ((!m_checkedForXMLCharset && (m_contentType == HTML || m_contentType == XML)) || (!m_checkedForCSSCharset && (m_contentType == CSS)))) {
         WTF::TextEncoding detectedEncoding;
diff --git a/Source/core/loader/TextResourceDecoder.h b/Source/core/fetch/TextResourceDecoder.h
similarity index 100%
rename from Source/core/loader/TextResourceDecoder.h
rename to Source/core/fetch/TextResourceDecoder.h
diff --git a/Source/core/fetch/XSLStyleSheetResource.cpp b/Source/core/fetch/XSLStyleSheetResource.cpp
index 7a165b7..6179a47 100644
--- a/Source/core/fetch/XSLStyleSheetResource.cpp
+++ b/Source/core/fetch/XSLStyleSheetResource.cpp
@@ -29,7 +29,7 @@
 
 #include "core/fetch/ResourceClientWalker.h"
 #include "core/fetch/StyleSheetResourceClient.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/platform/SharedBuffer.h"
 #include "wtf/Vector.h"
 
diff --git a/Source/core/fileapi/File.idl b/Source/core/fileapi/File.idl
index bfdf6b1..2d2ea18 100644
--- a/Source/core/fileapi/File.idl
+++ b/Source/core/fileapi/File.idl
@@ -26,6 +26,6 @@
 interface File : Blob {
     readonly attribute DOMString name;
     readonly attribute Date lastModifiedDate;
-    [EnabledAtRuntime=directoryUpload] readonly attribute DOMString webkitRelativePath;
+    [EnabledAtRuntime=DirectoryUpload] readonly attribute DOMString webkitRelativePath;
 };
 
diff --git a/Source/core/fileapi/FileReader.cpp b/Source/core/fileapi/FileReader.cpp
index 612c072..6568c2f 100644
--- a/Source/core/fileapi/FileReader.cpp
+++ b/Source/core/fileapi/FileReader.cpp
@@ -70,7 +70,7 @@
 FileReader::FileReader(ScriptExecutionContext* context)
     : ActiveDOMObject(context)
     , m_state(EMPTY)
-    , m_aborting(false)
+    , m_loadingState(LoadingStateNone)
     , m_readType(FileReaderLoader::ReadAsBinaryString)
     , m_lastProgressNotificationTimeMS(0)
 {
@@ -157,6 +157,7 @@
     m_blob = blob;
     m_readType = type;
     m_state = LOADING;
+    m_loadingState = LoadingStateLoading;
     m_error = 0;
 
     m_loader = adoptPtr(new FileReaderLoader(m_readType, this));
@@ -174,9 +175,9 @@
 {
     LOG(FileAPI, "FileReader: aborting\n");
 
-    if (m_aborting || m_state != LOADING)
+    if (m_loadingState != LoadingStateLoading)
         return;
-    m_aborting = true;
+    m_loadingState = LoadingStateAborted;
 
     // Schedule to have the abort done later since abort() might be called from the event handler and we do not want the resource loading code to be in the stack.
     scriptExecutionContext()->postTask(
@@ -188,7 +189,6 @@
     ASSERT(m_state != DONE);
 
     terminate();
-    m_aborting = false;
 
     m_error = FileError::create(FileError::ABORT_ERR);
 
@@ -207,6 +207,7 @@
         m_loader = nullptr;
     }
     m_state = DONE;
+    m_loadingState = LoadingStateNone;
 }
 
 void FileReader::didStartLoading()
@@ -228,8 +229,14 @@
 
 void FileReader::didFinishLoading()
 {
-    if (m_aborting)
+    if (m_loadingState == LoadingStateAborted)
         return;
+    ASSERT(m_loadingState == LoadingStateLoading);
+
+    // It's important that we change m_loadingState before firing any events
+    // since any of the events could call abort(), which internally checks
+    // if we're still loading (therefore we need abort process) or not.
+    m_loadingState = LoadingStateNone;
 
     fireEvent(eventNames().progressEvent);
 
@@ -245,9 +252,10 @@
 
 void FileReader::didFail(FileError::ErrorCode errorCode)
 {
-    // If we're aborting, do not proceed with normal error handling since it is covered in aborting code.
-    if (m_aborting)
+    if (m_loadingState == LoadingStateAborted)
         return;
+    ASSERT(m_loadingState == LoadingStateLoading);
+    m_loadingState = LoadingStateNone;
 
     ASSERT(m_state != DONE);
     m_state = DONE;
diff --git a/Source/core/fileapi/FileReader.h b/Source/core/fileapi/FileReader.h
index feefa8e..aabd5d5 100644
--- a/Source/core/fileapi/FileReader.h
+++ b/Source/core/fileapi/FileReader.h
@@ -113,7 +113,16 @@
     void fireEvent(const AtomicString& type);
 
     ReadyState m_state;
-    bool m_aborting;
+
+    // Internal loading state, which could differ from ReadyState as it's
+    // for script-visible state while this one's for internal state.
+    enum LoadingState {
+        LoadingStateNone,
+        LoadingStateLoading,
+        LoadingStateAborted
+    };
+    LoadingState m_loadingState;
+
     EventTargetData m_eventTargetData;
 
     RefPtr<Blob> m_blob;
diff --git a/Source/core/fileapi/FileReaderLoader.cpp b/Source/core/fileapi/FileReaderLoader.cpp
index 1cd33de..b078247 100644
--- a/Source/core/fileapi/FileReaderLoader.cpp
+++ b/Source/core/fileapi/FileReaderLoader.cpp
@@ -33,12 +33,12 @@
 #include "core/fileapi/FileReaderLoader.h"
 
 #include "core/dom/ScriptExecutionContext.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/fileapi/Blob.h"
 #include "core/fileapi/BlobRegistry.h"
 #include "core/fileapi/BlobURL.h"
 #include "core/fileapi/FileReaderLoaderClient.h"
 #include "core/fileapi/Stream.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/loader/ThreadableLoader.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "core/platform/network/ResourceResponse.h"
diff --git a/Source/core/fileapi/Stream.cpp b/Source/core/fileapi/Stream.cpp
index 9dab48e..da28e23 100644
--- a/Source/core/fileapi/Stream.cpp
+++ b/Source/core/fileapi/Stream.cpp
@@ -62,6 +62,11 @@
     BlobRegistry::finalizeStream(m_internalURL);
 }
 
+void Stream::abort()
+{
+    BlobRegistry::abortStream(m_internalURL);
+}
+
 Stream::~Stream()
 {
     BlobRegistry::unregisterStreamURL(m_internalURL);
diff --git a/Source/core/fileapi/Stream.h b/Source/core/fileapi/Stream.h
index 71d9d81..d80cc24 100644
--- a/Source/core/fileapi/Stream.h
+++ b/Source/core/fileapi/Stream.h
@@ -58,6 +58,9 @@
     // Mark this stream finalized so that a reader of this stream is notified
     // of EOF.
     void finalize();
+    // Mark this stream finalized due to an error so that a reader of this
+    // stream is notified of EOF due to the error.
+    void abort();
 
     // Allow an external reader class to mark this object neutered so that they
     // won't load the corresponding stream again. All stream objects are
diff --git a/Source/core/fileapi/Stream.idl b/Source/core/fileapi/Stream.idl
index 7caf013..6ead757 100644
--- a/Source/core/fileapi/Stream.idl
+++ b/Source/core/fileapi/Stream.idl
@@ -37,7 +37,7 @@
 // FIXME: Make the Blob a subclass of the Stream.
 
 [
-    EnabledAtRuntime=stream
+    EnabledAtRuntime=Stream
 ] interface Stream {
     readonly attribute DOMString type;
 };
diff --git a/Source/core/history/HistoryItem.cpp b/Source/core/history/HistoryItem.cpp
index 4db012d..a61fc2c 100644
--- a/Source/core/history/HistoryItem.cpp
+++ b/Source/core/history/HistoryItem.cpp
@@ -26,13 +26,16 @@
 #include "config.h"
 #include "core/history/HistoryItem.h"
 
-#include <stdio.h>
 #include "bindings/v8/SerializedScriptValue.h"
 #include "core/dom/Document.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/text/CString.h"
 
+#ifndef NDEBUG
+#include <stdio.h>
+#endif
+
 namespace WebCore {
 
 static long long generateSequenceNumber()
diff --git a/Source/core/html/BaseButtonInputType.cpp b/Source/core/html/BaseButtonInputType.cpp
index fda94da..e0e07d4 100644
--- a/Source/core/html/BaseButtonInputType.cpp
+++ b/Source/core/html/BaseButtonInputType.cpp
@@ -44,7 +44,7 @@
 using namespace HTMLNames;
 
 class NonSelectableText : public Text {
-    inline NonSelectableText(Document* document, const String& data)
+    inline NonSelectableText(Document& document, const String& data)
         : Text(document, data, CreateText)
     {
     }
@@ -55,7 +55,7 @@
     }
 
 public:
-    static inline PassRefPtr<NonSelectableText> create(Document* document, const String& data)
+    static inline PassRefPtr<NonSelectableText> create(Document& document, const String& data)
     {
         return adoptRef(new NonSelectableText(document, data));
     }
diff --git a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
index ae80ddb..39eab63 100644
--- a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
@@ -49,12 +49,12 @@
 
     if (m_dateTimeChooser)
         return;
-    if (!element()->document()->page())
+    if (!element()->document().page())
         return;
     DateTimeChooserParameters parameters;
     if (!element()->setupDateTimeChooserParameters(parameters))
         return;
-    m_dateTimeChooser = element()->document()->page()->chrome().openDateTimeChooser(this, parameters);
+    m_dateTimeChooser = element()->document().page()->chrome().openDateTimeChooser(this, parameters);
 }
 
 void BaseChooserOnlyDateAndTimeInputType::createShadowSubtree()
diff --git a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
index 873857d..3d8f21e 100644
--- a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
@@ -150,7 +150,7 @@
 
 inline bool BaseMultipleFieldsDateAndTimeInputType::containsFocusedShadowElement() const
 {
-    return element()->userAgentShadowRoot()->contains(element()->document()->focusedElement());
+    return element()->userAgentShadowRoot()->contains(element()->document().focusedElement());
 }
 
 void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
@@ -273,14 +273,11 @@
     , m_isDestroyingShadowSubtree(false)
     , m_pickerIndicatorIsVisible(false)
     , m_pickerIndicatorIsAlwaysVisible(false)
-    , m_didCreateShadowElements(false)
 {
 }
 
 BaseMultipleFieldsDateAndTimeInputType::~BaseMultipleFieldsDateAndTimeInputType()
 {
-    if (!m_didCreateShadowElements)
-        return;
     if (SpinButtonElement* element = spinButtonElement())
         element->removeSpinButtonOwner();
     if (ClearButtonElement* element = clearButtonElement())
@@ -330,7 +327,7 @@
     // FIXME: This code should not depend on such craziness.
     ASSERT(!element()->renderer());
 
-    Document* document = element()->document();
+    Document& document = element()->document();
     ContainerNode* container = element()->userAgentShadowRoot();
 
     container->appendChild(DateTimeEditElement::create(document, *this));
@@ -350,7 +347,6 @@
         m_pickerIndicatorIsVisible = true;
         updatePickerIndicatorVisibility();
     }
-    m_didCreateShadowElements = true;
 }
 
 void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree()
@@ -381,8 +377,8 @@
     if (!edit || m_isDestroyingShadowSubtree)
         return;
     if (direction == FocusDirectionBackward) {
-        if (element()->document()->page())
-            element()->document()->page()->focusController().advanceFocus(direction);
+        if (element()->document().page())
+            element()->document().page()->focusController().advanceFocus(direction);
     } else if (direction == FocusDirectionNone || direction == FocusDirectionMouse || direction == FocusDirectionPage) {
         edit->focusByOwner(oldFocusedElement);
     } else
@@ -417,7 +413,6 @@
 
 void BaseMultipleFieldsDateAndTimeInputType::handleKeydownEvent(KeyboardEvent* event)
 {
-    Document* document = element()->document();
     if (m_pickerIndicatorIsVisible
         && ((event->keyIdentifier() == "Down" && event->getModifierState("Alt")) || (RenderTheme::theme().shouldOpenPickerWithF4Key() && event->keyIdentifier() == "F4"))) {
         if (PickerIndicatorElement* element = pickerIndicatorElement())
diff --git a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.h b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.h
index c80389b..0f990e6 100644
--- a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.h
+++ b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.h
@@ -122,7 +122,6 @@
     bool m_isDestroyingShadowSubtree;
     bool m_pickerIndicatorIsVisible;
     bool m_pickerIndicatorIsAlwaysVisible;
-    bool m_didCreateShadowElements;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/ClassList.cpp b/Source/core/html/ClassList.cpp
index c12b38a..4f435e3 100644
--- a/Source/core/html/ClassList.cpp
+++ b/Source/core/html/ClassList.cpp
@@ -63,7 +63,7 @@
 const SpaceSplitString& ClassList::classNames() const
 {
     ASSERT(m_element->hasClass());
-    if (m_element->document()->inQuirksMode()) {
+    if (m_element->document().inQuirksMode()) {
         if (!m_classNamesForQuirksMode)
             m_classNamesForQuirksMode = adoptPtr(new SpaceSplitString(value(), false));
         return *m_classNamesForQuirksMode.get();
diff --git a/Source/core/html/ClassList.h b/Source/core/html/ClassList.h
index ab5220a..cc2217f 100644
--- a/Source/core/html/ClassList.h
+++ b/Source/core/html/ClassList.h
@@ -26,9 +26,9 @@
 #define ClassList_h
 
 #include "HTMLNames.h"
+#include "core/dom/DOMTokenList.h"
 #include "core/dom/Element.h"
 #include "core/dom/SpaceSplitString.h"
-#include "core/html/DOMTokenList.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 
diff --git a/Source/core/html/ColorInputType.cpp b/Source/core/html/ColorInputType.cpp
index 734ccc6..16a85e2 100644
--- a/Source/core/html/ColorInputType.cpp
+++ b/Source/core/html/ColorInputType.cpp
@@ -62,7 +62,7 @@
     // We don't accept #rgb and #aarrggbb formats.
     if (value.length() != 7)
         return false;
-    StyleColor color(value);
+    Color color(value);
     return color.isValid() && !color.hasAlpha();
 }
 
@@ -109,16 +109,16 @@
     return proposedValue.lower();
 }
 
-StyleColor ColorInputType::valueAsColor() const
+Color ColorInputType::valueAsColor() const
 {
-    return StyleColor(element()->value());
+    return Color(element()->value());
 }
 
 void ColorInputType::createShadowSubtree()
 {
     ASSERT(element()->shadow());
 
-    Document* document = element()->document();
+    Document& document = element()->document();
     RefPtr<HTMLDivElement> wrapperElement = HTMLDivElement::create(document);
     wrapperElement->setPart(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
     RefPtr<HTMLDivElement> colorSwatch = HTMLDivElement::create(document);
@@ -138,7 +138,7 @@
 
     updateColorSwatch();
     if (m_chooser)
-        m_chooser->setSelectedColor(valueAsColor().color());
+        m_chooser->setSelectedColor(valueAsColor());
 }
 
 void ColorInputType::handleDOMActivateEvent(Event* event)
@@ -151,7 +151,7 @@
 
     Chrome* chrome = this->chrome();
     if (chrome && !m_chooser)
-        m_chooser = chrome->createColorChooser(this, valueAsColor().color());
+        m_chooser = chrome->createColorChooser(this, valueAsColor());
 
     event->setDefaultHandled();
 }
@@ -208,12 +208,12 @@
 
 IntRect ColorInputType::elementRectRelativeToRootView() const
 {
-    return element()->document()->view()->contentsToRootView(element()->pixelSnappedBoundingBox());
+    return element()->document().view()->contentsToRootView(element()->pixelSnappedBoundingBox());
 }
 
 Color ColorInputType::currentColor()
 {
-    return valueAsColor().color();
+    return valueAsColor();
 }
 
 bool ColorInputType::shouldShowSuggestions() const
@@ -234,10 +234,10 @@
             for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); i++) {
                 if (!element()->isValidValue(option->value()))
                     continue;
-                StyleColor color(option->value());
+                Color color(option->value());
                 if (!color.isValid())
                     continue;
-                suggestions.append(color.color());
+                suggestions.append(color);
             }
         }
     }
diff --git a/Source/core/html/ColorInputType.h b/Source/core/html/ColorInputType.h
index 220f27e..309ceff 100644
--- a/Source/core/html/ColorInputType.h
+++ b/Source/core/html/ColorInputType.h
@@ -64,7 +64,7 @@
     virtual bool shouldRespectListAttribute() OVERRIDE;
     virtual bool typeMismatchFor(const String&) const OVERRIDE;
 
-    StyleColor valueAsColor() const;
+    Color valueAsColor() const;
     void endColorChooser();
     void updateColorSwatch();
     HTMLElement* shadowColorSwatch() const;
diff --git a/Source/core/html/FileInputType.cpp b/Source/core/html/FileInputType.cpp
index d1e533e..cdf4735 100644
--- a/Source/core/html/FileInputType.cpp
+++ b/Source/core/html/FileInputType.cpp
@@ -153,7 +153,7 @@
 #if ENABLE(MEDIA_CAPTURE)
         settings.useMediaCapture = input->capture();
 #endif
-        chrome->runOpenPanel(input->document()->frame(), newFileChooser(settings));
+        chrome->runOpenPanel(input->document().frame(), newFileChooser(settings));
     }
     event->setDefaultHandled();
 }
@@ -168,16 +168,6 @@
     return false;
 }
 
-bool FileInputType::canChangeFromAnotherType() const
-{
-    // Don't allow the type to be changed to file after the first type change.
-    // In other engines this might mean a JavaScript programmer could set a text
-    // field's value to something like /etc/passwd and then change it to a file input.
-    // I don't think this would actually occur in WebKit, but this rule still may be
-    // important for compatibility.
-    return false;
-}
-
 FileList* FileInputType::files()
 {
     return m_fileList.get();
diff --git a/Source/core/html/FileInputType.h b/Source/core/html/FileInputType.h
index d83f795..1f3c014 100644
--- a/Source/core/html/FileInputType.h
+++ b/Source/core/html/FileInputType.h
@@ -57,7 +57,6 @@
     virtual void handleDOMActivateEvent(Event*) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual bool canSetStringValue() const OVERRIDE;
-    virtual bool canChangeFromAnotherType() const OVERRIDE;
     virtual FileList* files() OVERRIDE;
     virtual void setFiles(PassRefPtr<FileList>) OVERRIDE;
     virtual bool canSetValue(const String&) OVERRIDE;
diff --git a/Source/core/html/FormAssociatedElement.cpp b/Source/core/html/FormAssociatedElement.cpp
index 58f6654..e800826 100644
--- a/Source/core/html/FormAssociatedElement.cpp
+++ b/Source/core/html/FormAssociatedElement.cpp
@@ -55,7 +55,7 @@
 
 FormAssociatedElement::~FormAssociatedElement()
 {
-    setForm(0);
+    // We can't call setForm here because it contains virtual calls.
 }
 
 ValidityState* FormAssociatedElement::validity()
@@ -107,7 +107,7 @@
         // the value of form attribute, so we put the result of
         // treeScope()->getElementById() over the given element.
         HTMLFormElement* newForm = 0;
-        Element* newFormCandidate = element->treeScope()->getElementById(formId);
+        Element* newFormCandidate = element->treeScope().getElementById(formId);
         if (newFormCandidate && newFormCandidate->hasTagName(formTag))
             newForm = toHTMLFormElement(newFormCandidate);
         return newForm;
@@ -163,7 +163,7 @@
     setForm(findAssociatedForm(toHTMLElement(this), m_form));
     HTMLElement* element = toHTMLElement(this);
     if (m_form && m_form != originalForm && m_form->inDocument())
-        element->document()->didAssociateFormControl(element);
+        element->document().didAssociateFormControl(element);
 }
 
 void FormAssociatedElement::formAttributeChanged()
@@ -175,7 +175,7 @@
         setForm(element->findFormAncestor());
         HTMLElement* element = toHTMLElement(this);
         if (m_form && m_form != originalForm && m_form->inDocument())
-            element->document()->didAssociateFormControl(element);
+            element->document().didAssociateFormControl(element);
         m_formAttributeTargetObserver = nullptr;
     } else {
         resetFormOwner();
@@ -277,11 +277,9 @@
 const HTMLElement* toHTMLElement(const FormAssociatedElement* associatedElement)
 {
     if (associatedElement->isFormControlElement())
-        return static_cast<const HTMLFormControlElement*>(associatedElement);
+        return toHTMLFormControlElement(associatedElement);
     // Assumes the element is an HTMLObjectElement
-    const HTMLElement* element = static_cast<const HTMLObjectElement*>(associatedElement);
-    ASSERT(element->hasTagName(objectTag));
-    return element;
+    return toHTMLObjectElement(associatedElement);
 }
 
 HTMLElement* toHTMLElement(FormAssociatedElement* associatedElement)
@@ -295,7 +293,7 @@
 }
 
 FormAttributeTargetObserver::FormAttributeTargetObserver(const AtomicString& id, FormAssociatedElement* element)
-    : IdTargetObserver(toHTMLElement(element)->treeScope()->idTargetObserverRegistry(), id)
+    : IdTargetObserver(toHTMLElement(element)->treeScope().idTargetObserverRegistry(), id)
     , m_element(element)
 {
 }
diff --git a/Source/core/html/FormController.cpp b/Source/core/html/FormController.cpp
index 942ab0e..8da69a8 100644
--- a/Source/core/html/FormController.cpp
+++ b/Source/core/html/FormController.cpp
@@ -314,7 +314,7 @@
     for (size_t i = 0, namedControls = 0; i < controls.size() && namedControls < namedControlsToBeRecorded; ++i) {
         if (!controls[i]->isFormControlElementWithState())
             continue;
-        HTMLFormControlElementWithState* control = static_cast<HTMLFormControlElementWithState*>(controls[i]);
+        HTMLFormControlElementWithState* control = toHTMLFormControlElementWithState(controls[i]);
         if (!ownerFormForState(*control))
             continue;
         AtomicString name = control->name();
@@ -491,7 +491,7 @@
     for (size_t i = 0; i < elements.size(); ++i) {
         if (!elements[i]->isFormControlElementWithState())
             continue;
-        HTMLFormControlElementWithState* control = static_cast<HTMLFormControlElementWithState*>(elements[i]);
+        HTMLFormControlElementWithState* control = toHTMLFormControlElementWithState(elements[i]);
         if (!control->shouldSaveAndRestoreFormControlState())
             continue;
         if (ownerFormForState(*control) != &form)
diff --git a/Source/core/html/HTMLAnchorElement.cpp b/Source/core/html/HTMLAnchorElement.cpp
index ca3767e..5fa5a2b 100644
--- a/Source/core/html/HTMLAnchorElement.cpp
+++ b/Source/core/html/HTMLAnchorElement.cpp
@@ -109,7 +109,7 @@
 
 using namespace HTMLNames;
 
-HTMLAnchorElement::HTMLAnchorElement(const QualifiedName& tagName, Document* document)
+HTMLAnchorElement::HTMLAnchorElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_hasRootEditableElementForSelectionOnMouseDown(false)
     , m_wasShiftKeyDownOnMouseDown(false)
@@ -119,12 +119,12 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLAnchorElement> HTMLAnchorElement::create(Document* document)
+PassRefPtr<HTMLAnchorElement> HTMLAnchorElement::create(Document& document)
 {
     return adoptRef(new HTMLAnchorElement(aTag, document));
 }
 
-PassRefPtr<HTMLAnchorElement> HTMLAnchorElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLAnchorElement> HTMLAnchorElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLAnchorElement(tagName, document));
 }
@@ -163,23 +163,14 @@
 
 bool HTMLAnchorElement::isKeyboardFocusable() const
 {
-    if (!isLink())
-        return HTMLElement::isKeyboardFocusable();
-
-    if (!isFocusable())
-        return false;
-
-    Page* page = document()->page();
-    if (!page)
-        return false;
-
-    if (!page->chrome().client().tabsToLinks())
-        return false;
-
-    if (isInCanvasSubtree())
-        return true;
-
-    return hasNonEmptyBoundingBox();
+    if (isLink()) {
+        Page* page = document().page();
+        if (!page)
+            return false;
+        if (!page->chrome().client().tabsToLinks())
+            return false;
+    }
+    return HTMLElement::isKeyboardFocusable();
 }
 
 static void appendServerMapMousePosition(StringBuilder& url, Event* event)
@@ -231,8 +222,8 @@
         if (rendererIsEditable()) {
             // This keeps track of the editable block that the selection was in (if it was in one) just before the link was clicked
             // for the LiveWhenNotFocused editable link behavior
-            if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() != RightButton && document()->frame() && document()->frame()->selection()) {
-                setRootEditableElementForSelectionOnMouseDown(document()->frame()->selection()->rootEditableElement());
+            if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() != RightButton && document().frame()) {
+                setRootEditableElementForSelectionOnMouseDown(document().frame()->selection().rootEditableElement());
                 m_wasShiftKeyDownOnMouseDown = toMouseEvent(event)->shiftKey();
             } else if (event->type() == eventNames().mouseoverEvent) {
                 // These are cleared on mouseover and not mouseout because their values are needed for drag events,
@@ -250,7 +241,7 @@
 {
     if (rendererIsEditable()) {
         EditableLinkBehavior editableLinkBehavior = EditableLinkDefaultBehavior;
-        if (Settings* settings = document()->settings())
+        if (Settings* settings = document().settings())
             editableLinkBehavior = settings->editableLinkBehavior();
 
         switch (editableLinkBehavior) {
@@ -265,7 +256,7 @@
             // Don't set the link to be active if the current selection is in the same editable block as
             // this link
             case EditableLinkLiveWhenNotFocused:
-                if (down && document()->frame() && document()->frame()->selection()->rootEditableElement() == rootEditableElement())
+                if (down && document().frame() && document().frame()->selection().rootEditableElement() == rootEditableElement())
                     return;
                 break;
 
@@ -285,17 +276,17 @@
         setIsLink(!value.isNull());
         if (wasLink != isLink()) {
             didAffectSelector(AffectedSelectorLink | AffectedSelectorVisited | AffectedSelectorEnabled);
-            if (wasLink && treeScope()->adjustedFocusedElement() == this) {
+            if (wasLink && treeScope().adjustedFocusedElement() == this) {
                 // We might want to call blur(), but it's dangerous to dispatch
                 // events here.
-                document()->setNeedsFocusedElementCheck();
+                document().setNeedsFocusedElementCheck();
             }
         }
         if (isLink()) {
             String parsedURL = stripLeadingAndTrailingHTMLSpaces(value);
-            if (document()->isDNSPrefetchEnabled()) {
+            if (document().isDNSPrefetchEnabled()) {
                 if (protocolIs(parsedURL, "http") || protocolIs(parsedURL, "https") || parsedURL.startsWith("//"))
-                    prefetchDNS(document()->completeURL(parsedURL).host());
+                    prefetchDNS(document().completeURL(parsedURL).host());
             }
 
             if (wasLink)
@@ -341,7 +332,7 @@
 
 KURL HTMLAnchorElement::href() const
 {
-    return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(hrefAttr)));
+    return document().completeURL(stripLeadingAndTrailingHTMLSpaces(getAttribute(hrefAttr)));
 }
 
 void HTMLAnchorElement::setHref(const AtomicString& value)
@@ -560,40 +551,40 @@
 
 void HTMLAnchorElement::sendPings(const KURL& destinationURL)
 {
-    if (!hasAttribute(pingAttr) || !document()->settings() || !document()->settings()->hyperlinkAuditingEnabled())
+    if (!hasAttribute(pingAttr) || !document().settings() || !document().settings()->hyperlinkAuditingEnabled())
         return;
 
     SpaceSplitString pingURLs(getAttribute(pingAttr), false);
     for (unsigned i = 0; i < pingURLs.size(); i++)
-        PingLoader::sendPing(document()->frame(), document()->completeURL(pingURLs[i]), destinationURL);
+        PingLoader::sendPing(document().frame(), document().completeURL(pingURLs[i]), destinationURL);
 }
 
 void HTMLAnchorElement::handleClick(Event* event)
 {
     event->setDefaultHandled();
 
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
     StringBuilder url;
     url.append(stripLeadingAndTrailingHTMLSpaces(fastGetAttribute(hrefAttr)));
     appendServerMapMousePosition(url, event);
-    KURL completedURL = document()->completeURL(url.toString());
+    KURL completedURL = document().completeURL(url.toString());
 
     ResourceRequest request(completedURL);
     if (prefetchEventHandler()->hasIssuedPreconnect())
         frame->loader()->client()->dispatchWillRequestAfterPreconnect(request);
     if (hasAttribute(downloadAttr)) {
         if (!hasRel(RelationNoReferrer)) {
-            String referrer = SecurityPolicy::generateReferrerHeader(document()->referrerPolicy(), completedURL, frame->loader()->outgoingReferrer());
+            String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), completedURL, frame->loader()->outgoingReferrer());
             if (!referrer.isEmpty())
                 request.setHTTPReferrer(referrer);
         }
 
         frame->loader()->client()->loadURLExternally(request, NavigationPolicyDownload, fastGetAttribute(downloadAttr));
     } else {
-        FrameLoadRequest frameRequest(document()->securityOrigin(), request, target());
+        FrameLoadRequest frameRequest(document().securityOrigin(), request, target());
         frameRequest.setTriggeringEvent(event);
         if (hasRel(RelationNoReferrer))
             frameRequest.setShouldSendReferrer(NeverSendReferrer);
@@ -615,7 +606,7 @@
     if (!rendererIsEditable())
         return true;
 
-    Settings* settings = document()->settings();
+    Settings* settings = document().settings();
     if (!settings)
         return true;
 
@@ -822,17 +813,15 @@
     if (!url.protocolIsInHTTPFamily())
         return false;
 
-    Document* document = m_anchorElement->document();
-    if (!document)
+    Document& document = m_anchorElement->document();
+
+    if (!document.securityOrigin()->canDisplay(url))
         return false;
 
-    if (!document->securityOrigin()->canDisplay(url))
+    if (url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(document.url(), url))
         return false;
 
-    if (url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(document->url(), url))
-        return false;
-
-    Frame* frame = document->frame();
+    Frame* frame = document.frame();
     if (!frame)
         return false;
 
diff --git a/Source/core/html/HTMLAnchorElement.h b/Source/core/html/HTMLAnchorElement.h
index a118e5d..a3410b5 100644
--- a/Source/core/html/HTMLAnchorElement.h
+++ b/Source/core/html/HTMLAnchorElement.h
@@ -55,8 +55,8 @@
 
 class HTMLAnchorElement : public HTMLElement {
 public:
-    static PassRefPtr<HTMLAnchorElement> create(Document*);
-    static PassRefPtr<HTMLAnchorElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLAnchorElement> create(Document&);
+    static PassRefPtr<HTMLAnchorElement> create(const QualifiedName&, Document&);
 
     virtual ~HTMLAnchorElement();
 
@@ -103,7 +103,7 @@
     void invalidateCachedVisitedLinkHash() { m_cachedVisitedLinkHash = 0; }
 
 protected:
-    HTMLAnchorElement(const QualifiedName&, Document*);
+    HTMLAnchorElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
@@ -149,7 +149,7 @@
 inline LinkHash HTMLAnchorElement::visitedLinkHash() const
 {
     if (!m_cachedVisitedLinkHash)
-        m_cachedVisitedLinkHash = WebCore::visitedLinkHash(document()->baseURL(), fastGetAttribute(HTMLNames::hrefAttr));
+        m_cachedVisitedLinkHash = WebCore::visitedLinkHash(document().baseURL(), fastGetAttribute(HTMLNames::hrefAttr));
     return m_cachedVisitedLinkHash;
 }
 
diff --git a/Source/core/html/HTMLAppletElement.cpp b/Source/core/html/HTMLAppletElement.cpp
index 3cb4757..7475688 100644
--- a/Source/core/html/HTMLAppletElement.cpp
+++ b/Source/core/html/HTMLAppletElement.cpp
@@ -39,7 +39,7 @@
 
 using namespace HTMLNames;
 
-HTMLAppletElement::HTMLAppletElement(const QualifiedName& tagName, Document* document, bool createdByParser)
+HTMLAppletElement::HTMLAppletElement(const QualifiedName& tagName, Document& document, bool createdByParser)
     : HTMLPlugInImageElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
 {
     ASSERT(hasTagName(appletTag));
@@ -48,7 +48,7 @@
     m_serviceType = "application/x-java-applet";
 }
 
-PassRefPtr<HTMLAppletElement> HTMLAppletElement::create(const QualifiedName& tagName, Document* document, bool createdByParser)
+PassRefPtr<HTMLAppletElement> HTMLAppletElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
 {
     return adoptRef(new HTMLAppletElement(tagName, document, createdByParser));
 }
@@ -68,11 +68,11 @@
     HTMLPlugInImageElement::parseAttribute(name, value);
 }
 
-bool HTMLAppletElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLAppletElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (!fastHasAttribute(codeAttr))
         return false;
-    return HTMLPlugInImageElement::rendererIsNeeded(context);
+    return HTMLPlugInImageElement::rendererIsNeeded(style);
 }
 
 RenderObject* HTMLAppletElement::createRenderer(RenderStyle* style)
@@ -104,7 +104,7 @@
 
     RenderEmbeddedObject* renderer = renderEmbeddedObject();
 
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     ASSERT(frame);
 
     LayoutUnit contentWidth = renderer->style()->width().isFixed() ? LayoutUnit(renderer->style()->width().value()) :
@@ -120,20 +120,20 @@
 
     const AtomicString& codeBase = getAttribute(codebaseAttr);
     if (!codeBase.isNull()) {
-        KURL codeBaseURL = document()->completeURL(codeBase);
-        if (!document()->securityOrigin()->canDisplay(codeBaseURL)) {
+        KURL codeBaseURL = document().completeURL(codeBase);
+        if (!document().securityOrigin()->canDisplay(codeBaseURL)) {
             FrameLoader::reportLocalLoadFailed(frame, codeBaseURL.string());
             return;
         }
         const char javaAppletMimeType[] = "application/x-java-applet";
-        if (!document()->contentSecurityPolicy()->allowObjectFromSource(codeBaseURL)
-            || !document()->contentSecurityPolicy()->allowPluginType(javaAppletMimeType, javaAppletMimeType, codeBaseURL))
+        if (!document().contentSecurityPolicy()->allowObjectFromSource(codeBaseURL)
+            || !document().contentSecurityPolicy()->allowPluginType(javaAppletMimeType, javaAppletMimeType, codeBaseURL))
             return;
         paramNames.append("codeBase");
         paramValues.append(codeBase.string());
     }
 
-    const AtomicString& name = document()->isHTMLDocument() ? getNameAttribute() : getIdAttribute();
+    const AtomicString& name = document().isHTMLDocument() ? getNameAttribute() : getIdAttribute();
     if (!name.isNull()) {
         paramNames.append("name");
         paramValues.append(name.string());
@@ -146,7 +146,7 @@
     }
 
     paramNames.append("baseURL");
-    KURL baseURL = document()->baseURL();
+    KURL baseURL = document().baseURL();
     paramValues.append(baseURL.string());
 
     const AtomicString& mayScript = getAttribute(mayscriptAttr);
@@ -159,7 +159,7 @@
         if (!child->hasTagName(paramTag))
             continue;
 
-        HTMLParamElement* param = static_cast<HTMLParamElement*>(child);
+        HTMLParamElement* param = toHTMLParamElement(child);
         if (param->name().isEmpty())
             continue;
 
@@ -182,10 +182,10 @@
 
 bool HTMLAppletElement::canEmbedJava() const
 {
-    if (document()->isSandboxed(SandboxPlugins))
+    if (document().isSandboxed(SandboxPlugins))
         return false;
 
-    Settings* settings = document()->settings();
+    Settings* settings = document().settings();
     if (!settings)
         return false;
 
diff --git a/Source/core/html/HTMLAppletElement.h b/Source/core/html/HTMLAppletElement.h
index 892c854..0408a3b 100644
--- a/Source/core/html/HTMLAppletElement.h
+++ b/Source/core/html/HTMLAppletElement.h
@@ -29,17 +29,17 @@
 
 class HTMLAppletElement FINAL : public HTMLPlugInImageElement {
 public:
-    static PassRefPtr<HTMLAppletElement> create(const QualifiedName&, Document*, bool createdByParser);
+    static PassRefPtr<HTMLAppletElement> create(const QualifiedName&, Document&, bool createdByParser);
 
 protected:
     virtual RenderWidget* renderWidgetForJSBindings() const OVERRIDE;
 
 private:
-    HTMLAppletElement(const QualifiedName&, Document*, bool createdByParser);
+    HTMLAppletElement(const QualifiedName&, Document&, bool createdByParser);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     virtual RenderWidget* existingRenderWidget() const OVERRIDE;
diff --git a/Source/core/html/HTMLAreaElement.cpp b/Source/core/html/HTMLAreaElement.cpp
index 780e412..46ee04a 100644
--- a/Source/core/html/HTMLAreaElement.cpp
+++ b/Source/core/html/HTMLAreaElement.cpp
@@ -37,7 +37,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLAreaElement::HTMLAreaElement(const QualifiedName& tagName, Document* document)
+inline HTMLAreaElement::HTMLAreaElement(const QualifiedName& tagName, Document& document)
     : HTMLAnchorElement(tagName, document)
     , m_lastSize(-1, -1)
     , m_shape(Unknown)
@@ -46,7 +46,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLAreaElement> HTMLAreaElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLAreaElement> HTMLAreaElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLAreaElement(tagName, document));
 }
@@ -142,7 +142,7 @@
     }
 
     Path path;
-    RenderView* renderView = document()->renderView();
+    RenderView* renderView = document().renderView();
     switch (shape) {
         case Poly:
             if (m_coords.size() >= 6) {
diff --git a/Source/core/html/HTMLAreaElement.h b/Source/core/html/HTMLAreaElement.h
index f00dde1..2fc4ceb 100644
--- a/Source/core/html/HTMLAreaElement.h
+++ b/Source/core/html/HTMLAreaElement.h
@@ -34,7 +34,7 @@
 
 class HTMLAreaElement FINAL : public HTMLAnchorElement {
 public:
-    static PassRefPtr<HTMLAreaElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLAreaElement> create(const QualifiedName&, Document&);
 
     bool isDefault() const { return m_shape == Default; }
 
@@ -47,7 +47,7 @@
     HTMLImageElement* imageElement() const;
 
 private:
-    HTMLAreaElement(const QualifiedName&, Document*);
+    HTMLAreaElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool supportsFocus() const;
diff --git a/Source/core/html/HTMLAttributeNames.in b/Source/core/html/HTMLAttributeNames.in
index fc59f67..dc3b049 100644
--- a/Source/core/html/HTMLAttributeNames.in
+++ b/Source/core/html/HTMLAttributeNames.in
@@ -169,6 +169,9 @@
 nowrap
 object
 onabort
+onanimationstart
+onanimationiteration
+onanimationend
 onautocomplete
 onautocompleteerror
 onbeforecopy
diff --git a/Source/core/html/HTMLAudioElement.cpp b/Source/core/html/HTMLAudioElement.cpp
index f3084ab..c83650a 100644
--- a/Source/core/html/HTMLAudioElement.cpp
+++ b/Source/core/html/HTMLAudioElement.cpp
@@ -32,21 +32,21 @@
 
 using namespace HTMLNames;
 
-HTMLAudioElement::HTMLAudioElement(const QualifiedName& tagName, Document* document, bool createdByParser)
+HTMLAudioElement::HTMLAudioElement(const QualifiedName& tagName, Document& document, bool createdByParser)
     : HTMLMediaElement(tagName, document, createdByParser)
 {
     ASSERT(hasTagName(audioTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLAudioElement> HTMLAudioElement::create(const QualifiedName& tagName, Document* document, bool createdByParser)
+PassRefPtr<HTMLAudioElement> HTMLAudioElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
 {
     RefPtr<HTMLAudioElement> audioElement(adoptRef(new HTMLAudioElement(tagName, document, createdByParser)));
     audioElement->suspendIfNeeded();
     return audioElement.release();
 }
 
-PassRefPtr<HTMLAudioElement> HTMLAudioElement::createForJSConstructor(Document* document, const String& src)
+PassRefPtr<HTMLAudioElement> HTMLAudioElement::createForJSConstructor(Document& document, const String& src)
 {
     RefPtr<HTMLAudioElement> audio = adoptRef(new HTMLAudioElement(audioTag, document, false));
     audio->setPreload("auto");
diff --git a/Source/core/html/HTMLAudioElement.h b/Source/core/html/HTMLAudioElement.h
index 131f450..131891e 100644
--- a/Source/core/html/HTMLAudioElement.h
+++ b/Source/core/html/HTMLAudioElement.h
@@ -35,11 +35,11 @@
 
 class HTMLAudioElement FINAL : public HTMLMediaElement {
 public:
-    static PassRefPtr<HTMLAudioElement> create(const QualifiedName&, Document*, bool);
-    static PassRefPtr<HTMLAudioElement> createForJSConstructor(Document*, const String& src);
+    static PassRefPtr<HTMLAudioElement> create(const QualifiedName&, Document&, bool);
+    static PassRefPtr<HTMLAudioElement> createForJSConstructor(Document&, const String& src);
 
 private:
-    HTMLAudioElement(const QualifiedName&, Document*, bool);
+    HTMLAudioElement(const QualifiedName&, Document&, bool);
 
     virtual bool isVideo() const { return false; }
 };
diff --git a/Source/core/html/HTMLAudioElement.idl b/Source/core/html/HTMLAudioElement.idl
index ce003cf..cbed9d6 100644
--- a/Source/core/html/HTMLAudioElement.idl
+++ b/Source/core/html/HTMLAudioElement.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=media,
+    EnabledAtRuntime=Media,
     NamedConstructor=Audio([Default=NullString] optional DOMString src)
 ] interface HTMLAudioElement : HTMLMediaElement {
 };
diff --git a/Source/core/html/HTMLBDIElement.h b/Source/core/html/HTMLBDIElement.h
index 94a41b9..d72e4a0 100644
--- a/Source/core/html/HTMLBDIElement.h
+++ b/Source/core/html/HTMLBDIElement.h
@@ -27,13 +27,13 @@
 
 class HTMLBDIElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLBDIElement> create(const QualifiedName& name, Document* document)
+    static PassRefPtr<HTMLBDIElement> create(const QualifiedName& name, Document& document)
     {
         return adoptRef(new HTMLBDIElement(name, document));
     }
 
 private:
-    HTMLBDIElement(const QualifiedName& name, Document* document)
+    HTMLBDIElement(const QualifiedName& name, Document& document)
         : HTMLElement(name, document)
     {
         // FIXME: Rename setSelfOrAncestorHasDirAutoAttribute to reflect the fact bdi also uses this flag.
diff --git a/Source/core/html/HTMLBRElement.cpp b/Source/core/html/HTMLBRElement.cpp
index a869c87..d92ac0c 100644
--- a/Source/core/html/HTMLBRElement.cpp
+++ b/Source/core/html/HTMLBRElement.cpp
@@ -32,19 +32,19 @@
 
 using namespace HTMLNames;
 
-HTMLBRElement::HTMLBRElement(const QualifiedName& tagName, Document* document)
+HTMLBRElement::HTMLBRElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(brTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLBRElement> HTMLBRElement::create(Document* document)
+PassRefPtr<HTMLBRElement> HTMLBRElement::create(Document& document)
 {
     return adoptRef(new HTMLBRElement(brTag, document));
 }
 
-PassRefPtr<HTMLBRElement> HTMLBRElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLBRElement> HTMLBRElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLBRElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLBRElement.h b/Source/core/html/HTMLBRElement.h
index 8825e17..fc6d5c4 100644
--- a/Source/core/html/HTMLBRElement.h
+++ b/Source/core/html/HTMLBRElement.h
@@ -30,13 +30,13 @@
 
 class HTMLBRElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLBRElement> create(Document*);
-    static PassRefPtr<HTMLBRElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLBRElement> create(Document&);
+    static PassRefPtr<HTMLBRElement> create(const QualifiedName&, Document&);
 
     virtual bool canContainRangeEndPoint() const { return false; }
 
 private:
-    HTMLBRElement(const QualifiedName&, Document*);
+    HTMLBRElement(const QualifiedName&, Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLBaseElement.cpp b/Source/core/html/HTMLBaseElement.cpp
index 6b3bf7c..34e5de2 100644
--- a/Source/core/html/HTMLBaseElement.cpp
+++ b/Source/core/html/HTMLBaseElement.cpp
@@ -26,21 +26,21 @@
 #include "HTMLNames.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/Document.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/TextResourceDecoder.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
-inline HTMLBaseElement::HTMLBaseElement(const QualifiedName& tagName, Document* document)
+inline HTMLBaseElement::HTMLBaseElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(baseTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLBaseElement> HTMLBaseElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLBaseElement> HTMLBaseElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLBaseElement(tagName, document));
 }
@@ -48,7 +48,7 @@
 void HTMLBaseElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (name == hrefAttr || name == targetAttr)
-        document()->processBaseElement();
+        document().processBaseElement();
     else
         HTMLElement::parseAttribute(name, value);
 }
@@ -57,7 +57,7 @@
 {
     HTMLElement::insertedInto(insertionPoint);
     if (insertionPoint->inDocument())
-        document()->processBaseElement();
+        document().processBaseElement();
     return InsertionDone;
 }
 
@@ -65,7 +65,7 @@
 {
     HTMLElement::removedFrom(insertionPoint);
     if (insertionPoint->inDocument())
-        document()->processBaseElement();
+        document().processBaseElement();
 }
 
 bool HTMLBaseElement::isURLAttribute(const Attribute& attribute) const
@@ -86,11 +86,11 @@
 
     const AtomicString& attributeValue = fastGetAttribute(hrefAttr);
     if (attributeValue.isNull())
-        return document()->url();
+        return document().url();
 
-    KURL url = document()->encoding().isValid() ?
-        KURL(document()->url(), stripLeadingAndTrailingHTMLSpaces(attributeValue)) :
-        KURL(document()->url(), stripLeadingAndTrailingHTMLSpaces(attributeValue), document()->encoding());
+    KURL url = document().encoding().isValid() ?
+        KURL(document().url(), stripLeadingAndTrailingHTMLSpaces(attributeValue)) :
+        KURL(document().url(), stripLeadingAndTrailingHTMLSpaces(attributeValue), document().encoding());
 
     if (!url.isValid())
         return KURL();
diff --git a/Source/core/html/HTMLBaseElement.h b/Source/core/html/HTMLBaseElement.h
index d8d5b45..7a52c37 100644
--- a/Source/core/html/HTMLBaseElement.h
+++ b/Source/core/html/HTMLBaseElement.h
@@ -29,13 +29,13 @@
 
 class HTMLBaseElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLBaseElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLBaseElement> create(const QualifiedName&, Document&);
 
     KURL href() const;
     void setHref(const AtomicString&);
 
 private:
-    HTMLBaseElement(const QualifiedName&, Document*);
+    HTMLBaseElement(const QualifiedName&, Document&);
 
     virtual String target() const;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
diff --git a/Source/core/html/HTMLBaseFontElement.cpp b/Source/core/html/HTMLBaseFontElement.cpp
index 39dfd65..a12f10f 100644
--- a/Source/core/html/HTMLBaseFontElement.cpp
+++ b/Source/core/html/HTMLBaseFontElement.cpp
@@ -29,14 +29,14 @@
 
 using namespace HTMLNames;
 
-inline HTMLBaseFontElement::HTMLBaseFontElement(const QualifiedName& tagName, Document* document)
+inline HTMLBaseFontElement::HTMLBaseFontElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(basefontTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLBaseFontElement> HTMLBaseFontElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLBaseFontElement> HTMLBaseFontElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLBaseFontElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLBaseFontElement.h b/Source/core/html/HTMLBaseFontElement.h
index 94a8d58..e66cc11 100644
--- a/Source/core/html/HTMLBaseFontElement.h
+++ b/Source/core/html/HTMLBaseFontElement.h
@@ -29,10 +29,10 @@
 
 class HTMLBaseFontElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLBaseFontElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLBaseFontElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLBaseFontElement(const QualifiedName&, Document*);
+    HTMLBaseFontElement(const QualifiedName&, Document&);
 };
 
 } // namespace
diff --git a/Source/core/html/HTMLBodyElement.cpp b/Source/core/html/HTMLBodyElement.cpp
index 1d4e702..b373e9a 100644
--- a/Source/core/html/HTMLBodyElement.cpp
+++ b/Source/core/html/HTMLBodyElement.cpp
@@ -41,19 +41,19 @@
 
 using namespace HTMLNames;
 
-HTMLBodyElement::HTMLBodyElement(const QualifiedName& tagName, Document* document)
+HTMLBodyElement::HTMLBodyElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(bodyTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLBodyElement> HTMLBodyElement::create(Document* document)
+PassRefPtr<HTMLBodyElement> HTMLBodyElement::create(Document& document)
 {
     return adoptRef(new HTMLBodyElement(bodyTag, document));
 }
 
-PassRefPtr<HTMLBodyElement> HTMLBodyElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLBodyElement> HTMLBodyElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLBodyElement(tagName, document));
 }
@@ -74,7 +74,7 @@
     if (name == backgroundAttr) {
         String url = stripLeadingAndTrailingHTMLSpaces(value);
         if (!url.isEmpty()) {
-            RefPtr<CSSImageValue> imageValue = CSSImageValue::create(document()->completeURL(url).string());
+            RefPtr<CSSImageValue> imageValue = CSSImageValue::create(document().completeURL(url).string());
             imageValue->setInitiator(localName());
             style->setProperty(CSSProperty(CSSPropertyBackgroundImage, imageValue.release()));
         }
@@ -100,58 +100,58 @@
     if (name == vlinkAttr || name == alinkAttr || name == linkAttr) {
         if (value.isNull()) {
             if (name == linkAttr)
-                document()->textLinkColors().resetLinkColor();
+                document().textLinkColors().resetLinkColor();
             else if (name == vlinkAttr)
-                document()->textLinkColors().resetVisitedLinkColor();
+                document().textLinkColors().resetVisitedLinkColor();
             else
-                document()->textLinkColors().resetActiveLinkColor();
+                document().textLinkColors().resetActiveLinkColor();
         } else {
             RGBA32 color;
-            if (CSSParser::parseColor(color, value, !document()->inQuirksMode())) {
+            if (CSSParser::parseColor(color, value, !document().inQuirksMode())) {
                 if (name == linkAttr)
-                    document()->textLinkColors().setLinkColor(color);
+                    document().textLinkColors().setLinkColor(color);
                 else if (name == vlinkAttr)
-                    document()->textLinkColors().setVisitedLinkColor(color);
+                    document().textLinkColors().setVisitedLinkColor(color);
                 else
-                    document()->textLinkColors().setActiveLinkColor(color);
+                    document().textLinkColors().setActiveLinkColor(color);
             }
         }
 
         setNeedsStyleRecalc();
     } else if (name == onloadAttr)
-        document()->setWindowAttributeEventListener(eventNames().loadEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().loadEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onbeforeunloadAttr)
-        document()->setWindowAttributeEventListener(eventNames().beforeunloadEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().beforeunloadEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onunloadAttr)
-        document()->setWindowAttributeEventListener(eventNames().unloadEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().unloadEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onpagehideAttr)
-        document()->setWindowAttributeEventListener(eventNames().pagehideEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().pagehideEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onpageshowAttr)
-        document()->setWindowAttributeEventListener(eventNames().pageshowEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().pageshowEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onpopstateAttr)
-        document()->setWindowAttributeEventListener(eventNames().popstateEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().popstateEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onblurAttr)
-        document()->setWindowAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onfocusAttr)
-        document()->setWindowAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(document().frame(), name, value));
 #if ENABLE(ORIENTATION_EVENTS)
     else if (name == onorientationchangeAttr)
-        document()->setWindowAttributeEventListener(eventNames().orientationchangeEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().orientationchangeEvent, createAttributeEventListener(document().frame(), name, value));
 #endif
     else if (name == onhashchangeAttr)
-        document()->setWindowAttributeEventListener(eventNames().hashchangeEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().hashchangeEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onresizeAttr)
-        document()->setWindowAttributeEventListener(eventNames().resizeEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().resizeEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onscrollAttr)
-        document()->setWindowAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onselectionchangeAttr)
-        document()->setAttributeEventListener(eventNames().selectionchangeEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setAttributeEventListener(eventNames().selectionchangeEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onstorageAttr)
-        document()->setWindowAttributeEventListener(eventNames().storageEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().storageEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == ononlineAttr)
-        document()->setWindowAttributeEventListener(eventNames().onlineEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().onlineEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onofflineAttr)
-        document()->setWindowAttributeEventListener(eventNames().offlineEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().offlineEvent, createAttributeEventListener(document().frame(), name, value));
     else
         HTMLElement::parseAttribute(name, value);
 }
@@ -163,7 +163,7 @@
         // FIXME: It's surprising this is web compatible since it means a marginwidth
         // and marginheight attribute can magically appear on the <body> of all documents
         // embedded through <iframe> or <frame>.
-        Element* ownerElement = document()->ownerElement();
+        Element* ownerElement = document().ownerElement();
         if (ownerElement && ownerElement->isFrameElementBase()) {
             HTMLFrameElementBase* ownerFrameElement = toHTMLFrameElementBase(ownerElement);
             int marginWidth = ownerFrameElement->marginWidth();
@@ -254,17 +254,17 @@
 int HTMLBodyElement::scrollLeft()
 {
     // Update the document's layout.
-    Document* document = this->document();
-    document->updateLayoutIgnorePendingStylesheets();
-    FrameView* view = document->view();
-    return view ? adjustForZoom(view->scrollX(), document) : 0;
+    Document& document = this->document();
+    document.updateLayoutIgnorePendingStylesheets();
+    FrameView* view = document.view();
+    return view ? adjustForZoom(view->scrollX(), &document) : 0;
 }
 
 void HTMLBodyElement::setScrollLeft(int scrollLeft)
 {
-    Document* document = this->document();
-    document->updateLayoutIgnorePendingStylesheets();
-    Frame* frame = document->frame();
+    Document& document = this->document();
+    document.updateLayoutIgnorePendingStylesheets();
+    Frame* frame = document.frame();
     if (!frame)
         return;
     FrameView* view = frame->view();
@@ -276,17 +276,17 @@
 int HTMLBodyElement::scrollTop()
 {
     // Update the document's layout.
-    Document* document = this->document();
-    document->updateLayoutIgnorePendingStylesheets();
-    FrameView* view = document->view();
-    return view ? adjustForZoom(view->scrollY(), document) : 0;
+    Document& document = this->document();
+    document.updateLayoutIgnorePendingStylesheets();
+    FrameView* view = document.view();
+    return view ? adjustForZoom(view->scrollY(), &document) : 0;
 }
 
 void HTMLBodyElement::setScrollTop(int scrollTop)
 {
-    Document* document = this->document();
-    document->updateLayoutIgnorePendingStylesheets();
-    Frame* frame = document->frame();
+    Document& document = this->document();
+    document.updateLayoutIgnorePendingStylesheets();
+    Frame* frame = document.frame();
     if (!frame)
         return;
     FrameView* view = frame->view();
@@ -298,26 +298,26 @@
 int HTMLBodyElement::scrollHeight()
 {
     // Update the document's layout.
-    Document* document = this->document();
-    document->updateLayoutIgnorePendingStylesheets();
-    FrameView* view = document->view();
-    return view ? adjustForZoom(view->contentsHeight(), document) : 0;
+    Document& document = this->document();
+    document.updateLayoutIgnorePendingStylesheets();
+    FrameView* view = document.view();
+    return view ? adjustForZoom(view->contentsHeight(), &document) : 0;
 }
 
 int HTMLBodyElement::scrollWidth()
 {
     // Update the document's layout.
-    Document* document = this->document();
-    document->updateLayoutIgnorePendingStylesheets();
-    FrameView* view = document->view();
-    return view ? adjustForZoom(view->contentsWidth(), document) : 0;
+    Document& document = this->document();
+    document.updateLayoutIgnorePendingStylesheets();
+    FrameView* view = document.view();
+    return view ? adjustForZoom(view->contentsWidth(), &document) : 0;
 }
 
 void HTMLBodyElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
 {
     HTMLElement::addSubresourceAttributeURLs(urls);
 
-    addSubresourceURL(urls, document()->completeURL(getAttribute(backgroundAttr)));
+    addSubresourceURL(urls, document().completeURL(getAttribute(backgroundAttr)));
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLBodyElement.h b/Source/core/html/HTMLBodyElement.h
index 8a88238..fd1a960 100644
--- a/Source/core/html/HTMLBodyElement.h
+++ b/Source/core/html/HTMLBodyElement.h
@@ -32,8 +32,8 @@
 
 class HTMLBodyElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLBodyElement> create(Document*);
-    static PassRefPtr<HTMLBodyElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLBodyElement> create(Document&);
+    static PassRefPtr<HTMLBodyElement> create(const QualifiedName&, Document&);
     virtual ~HTMLBodyElement();
 
     String aLink() const;
@@ -68,7 +68,7 @@
 #endif
 
 private:
-    HTMLBodyElement(const QualifiedName&, Document*);
+    HTMLBodyElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLButtonElement.cpp b/Source/core/html/HTMLButtonElement.cpp
index 0f55e0e..b1ee00a 100644
--- a/Source/core/html/HTMLButtonElement.cpp
+++ b/Source/core/html/HTMLButtonElement.cpp
@@ -39,7 +39,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLButtonElement::HTMLButtonElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+inline HTMLButtonElement::HTMLButtonElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
     : HTMLFormControlElement(tagName, document, form)
     , m_type(SUBMIT)
     , m_isActivatedSubmit(false)
@@ -48,7 +48,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLButtonElement> HTMLButtonElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+PassRefPtr<HTMLButtonElement> HTMLButtonElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
 {
     return adoptRef(new HTMLButtonElement(tagName, document, form));
 }
diff --git a/Source/core/html/HTMLButtonElement.h b/Source/core/html/HTMLButtonElement.h
index e31e41d..dbfedaa 100644
--- a/Source/core/html/HTMLButtonElement.h
+++ b/Source/core/html/HTMLButtonElement.h
@@ -30,7 +30,7 @@
 
 class HTMLButtonElement FINAL : public HTMLFormControlElement {
 public:
-    static PassRefPtr<HTMLButtonElement> create(const QualifiedName&, Document*, HTMLFormElement*);
+    static PassRefPtr<HTMLButtonElement> create(const QualifiedName&, Document&, HTMLFormElement*);
 
     void setType(const AtomicString&);
 
@@ -39,7 +39,7 @@
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
-    HTMLButtonElement(const QualifiedName& tagName, Document*, HTMLFormElement*);
+    HTMLButtonElement(const QualifiedName& tagName, Document&, HTMLFormElement*);
 
     enum Type { SUBMIT, RESET, BUTTON };
 
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index bb12fa4..b75b296 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -66,7 +66,7 @@
 //In Skia, we will also limit width/height to 32767.
 static const float MaxSkiaDim = 32767.0F; // Maximum width/height in CSS pixels.
 
-HTMLCanvasElement::HTMLCanvasElement(const QualifiedName& tagName, Document* document)
+HTMLCanvasElement::HTMLCanvasElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_size(DefaultWidth, DefaultHeight)
     , m_rendererIsCanvas(false)
@@ -82,12 +82,12 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(Document* document)
+PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(Document& document)
 {
     return adoptRef(new HTMLCanvasElement(canvasTag, document));
 }
 
-PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLCanvasElement(tagName, document));
 }
@@ -111,7 +111,7 @@
 
 RenderObject* HTMLCanvasElement::createRenderer(RenderStyle* style)
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
         m_rendererIsCanvas = true;
         return new RenderHTMLCanvas(this);
@@ -170,14 +170,14 @@
             return 0;
         if (!m_context) {
             HistogramSupport::histogramEnumeration("Canvas.ContextType", Context2d, ContextTypeCount);
-            m_context = CanvasRenderingContext2D::create(this, RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled() ? static_cast<Canvas2DContextAttributes*>(attrs) : 0, document()->inQuirksMode());
+            m_context = CanvasRenderingContext2D::create(this, RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled() ? static_cast<Canvas2DContextAttributes*>(attrs) : 0, document().inQuirksMode());
             if (m_context)
                 scheduleLayerUpdate();
         }
         return m_context.get();
     }
 
-    Settings* settings = document()->settings();
+    Settings* settings = document().settings();
     if (settings && settings->webGLEnabled()) {
         // Accept the legacy "webkit-3d" name as well as the provisional "experimental-webgl" name.
         // Now that WebGL is ratified, we will also accept "webgl" as the context name in Chrome.
@@ -318,7 +318,7 @@
         return;
 
     if (m_context) {
-        if (!paintsIntoCanvasBuffer() && !document()->printing())
+        if (!paintsIntoCanvasBuffer() && !document().printing())
             return;
         m_context->paintRenderingResultsToCanvas();
     }
@@ -444,12 +444,12 @@
 
 SecurityOrigin* HTMLCanvasElement::securityOrigin() const
 {
-    return document()->securityOrigin();
+    return document().securityOrigin();
 }
 
 StyleResolver* HTMLCanvasElement::styleResolver()
 {
-    return document()->styleResolver();
+    return document().styleResolver();
 }
 
 bool HTMLCanvasElement::shouldAccelerate(const IntSize& size) const
@@ -460,7 +460,7 @@
     if (m_accelerationDisabled)
         return false;
 
-    Settings* settings = document()->settings();
+    Settings* settings = document().settings();
     if (!settings || !settings->accelerated2dCanvasEnabled())
         return false;
 
@@ -503,7 +503,7 @@
         return;
     setExternallyAllocatedMemory(4 * width() * height());
     m_imageBuffer->context()->setImageInterpolationQuality(DefaultInterpolationQuality);
-    if (document()->settings() && !document()->settings()->antialiased2dCanvasEnabled())
+    if (document().settings() && !document().settings()->antialiased2dCanvasEnabled())
         m_imageBuffer->context()->setShouldAntialias(false);
     // GraphicsContext's defaults don't always agree with the 2d canvas spec.
     // See CanvasRenderingContext2D::State::State() for more information.
diff --git a/Source/core/html/HTMLCanvasElement.h b/Source/core/html/HTMLCanvasElement.h
index 1ff23b2..a9daa99 100644
--- a/Source/core/html/HTMLCanvasElement.h
+++ b/Source/core/html/HTMLCanvasElement.h
@@ -58,8 +58,8 @@
 
 class HTMLCanvasElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLCanvasElement> create(Document*);
-    static PassRefPtr<HTMLCanvasElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLCanvasElement> create(Document&);
+    static PassRefPtr<HTMLCanvasElement> create(const QualifiedName&, Document&);
     virtual ~HTMLCanvasElement();
 
     void addObserver(CanvasObserver*);
@@ -135,7 +135,7 @@
     InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
 
 private:
-    HTMLCanvasElement(const QualifiedName&, Document*);
+    HTMLCanvasElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*);
diff --git a/Source/core/html/HTMLDListElement.cpp b/Source/core/html/HTMLDListElement.cpp
index 673ff41..4b14c69 100644
--- a/Source/core/html/HTMLDListElement.cpp
+++ b/Source/core/html/HTMLDListElement.cpp
@@ -29,14 +29,14 @@
 
 using namespace HTMLNames;
 
-inline HTMLDListElement::HTMLDListElement(const QualifiedName& tagName, Document* document)
+inline HTMLDListElement::HTMLDListElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(dlTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLDListElement> HTMLDListElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLDListElement> HTMLDListElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLDListElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLDListElement.h b/Source/core/html/HTMLDListElement.h
index 77aca94..1909af6 100644
--- a/Source/core/html/HTMLDListElement.h
+++ b/Source/core/html/HTMLDListElement.h
@@ -29,10 +29,10 @@
 
 class HTMLDListElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDListElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLDListElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLDListElement(const QualifiedName&, Document*);
+    HTMLDListElement(const QualifiedName&, Document&);
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLDataListElement.cpp b/Source/core/html/HTMLDataListElement.cpp
index 4c17fc6..42e2d68 100644
--- a/Source/core/html/HTMLDataListElement.cpp
+++ b/Source/core/html/HTMLDataListElement.cpp
@@ -37,15 +37,15 @@
 
 namespace WebCore {
 
-inline HTMLDataListElement::HTMLDataListElement(const QualifiedName& tagName, Document* document)
+inline HTMLDataListElement::HTMLDataListElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLDataListElement> HTMLDataListElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLDataListElement> HTMLDataListElement::create(const QualifiedName& tagName, Document& document)
 {
-    UseCounter::count(document, UseCounter::DataListElement);
+    UseCounter::count(&document, UseCounter::DataListElement);
     return adoptRef(new HTMLDataListElement(tagName, document));
 }
 
@@ -56,7 +56,7 @@
 
 void HTMLDataListElement::optionElementChildrenChanged()
 {
-    treeScope()->idTargetObserverRegistry().notifyObservers(getIdAttribute());
+    treeScope().idTargetObserverRegistry().notifyObservers(getIdAttribute());
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLDataListElement.h b/Source/core/html/HTMLDataListElement.h
index 793a991..7deb03a 100644
--- a/Source/core/html/HTMLDataListElement.h
+++ b/Source/core/html/HTMLDataListElement.h
@@ -39,16 +39,22 @@
 
 class HTMLDataListElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDataListElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLDataListElement> create(const QualifiedName&, Document&);
 
     PassRefPtr<HTMLCollection> options();
 
     void optionElementChildrenChanged();
 
 private:
-    HTMLDataListElement(const QualifiedName&, Document*);
+    HTMLDataListElement(const QualifiedName&, Document&);
 };
 
+inline HTMLDataListElement* toHTMLDataListElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::datalistTag));
+    return static_cast<HTMLDataListElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // HTMLDataListElement_h
diff --git a/Source/core/html/HTMLDetailsElement.cpp b/Source/core/html/HTMLDetailsElement.cpp
index 0db492d..5c987f9 100644
--- a/Source/core/html/HTMLDetailsElement.cpp
+++ b/Source/core/html/HTMLDetailsElement.cpp
@@ -23,26 +23,25 @@
 
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLSummaryElement.h"
 #include "core/html/shadow/HTMLContentElement.h"
 #include "core/platform/LocalizedStrings.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
-PassRefPtr<HTMLDetailsElement> HTMLDetailsElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLDetailsElement> HTMLDetailsElement::create(const QualifiedName& tagName, Document& document)
 {
     RefPtr<HTMLDetailsElement> details = adoptRef(new HTMLDetailsElement(tagName, document));
     details->ensureUserAgentShadowRoot();
     return details.release();
 }
 
-HTMLDetailsElement::HTMLDetailsElement(const QualifiedName& tagName, Document* document)
+HTMLDetailsElement::HTMLDetailsElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_isOpen(false)
 {
@@ -52,7 +51,7 @@
 
 RenderObject* HTMLDetailsElement::createRenderer(RenderStyle*)
 {
-    return new RenderBlock(this);
+    return new RenderBlockFlow(this);
 }
 
 void HTMLDetailsElement::didAddUserAgentShadowRoot(ShadowRoot* root)
@@ -93,13 +92,14 @@
         HTMLElement::parseAttribute(name, value);
 }
 
-bool HTMLDetailsElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool HTMLDetailsElement::childShouldCreateRenderer(const Node& child) const
 {
+    // FIXME: These checks do not look correct, we should just use insertion points instead.
     if (m_isOpen)
-        return HTMLElement::childShouldCreateRenderer(childContext);
-    if (!childContext.node()->hasTagName(summaryTag))
+        return HTMLElement::childShouldCreateRenderer(child);
+    if (!child.hasTagName(summaryTag))
         return false;
-    return childContext.node() == findMainSummary() && HTMLElement::childShouldCreateRenderer(childContext);
+    return &child == findMainSummary() && HTMLElement::childShouldCreateRenderer(child);
 }
 
 void HTMLDetailsElement::toggleOpen()
diff --git a/Source/core/html/HTMLDetailsElement.h b/Source/core/html/HTMLDetailsElement.h
index a1158f2..a6087ad 100644
--- a/Source/core/html/HTMLDetailsElement.h
+++ b/Source/core/html/HTMLDetailsElement.h
@@ -27,16 +27,16 @@
 
 class HTMLDetailsElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDetailsElement> create(const QualifiedName& tagName, Document* document);
+    static PassRefPtr<HTMLDetailsElement> create(const QualifiedName& tagName, Document&);
     void toggleOpen();
 
     Element* findMainSummary() const;
 
 private:
-    HTMLDetailsElement(const QualifiedName&, Document*);
+    HTMLDetailsElement(const QualifiedName&, Document&);
 
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
+    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
 
diff --git a/Source/core/html/HTMLDialogElement.cpp b/Source/core/html/HTMLDialogElement.cpp
index 7fd2454..2f03013 100644
--- a/Source/core/html/HTMLDialogElement.cpp
+++ b/Source/core/html/HTMLDialogElement.cpp
@@ -41,7 +41,7 @@
     return style->position() == AbsolutePosition && style->hasAutoTopAndBottom();
 }
 
-HTMLDialogElement::HTMLDialogElement(const QualifiedName& tagName, Document* document)
+HTMLDialogElement::HTMLDialogElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_topIsValid(false)
     , m_top(0)
@@ -52,7 +52,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLDialogElement> HTMLDialogElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLDialogElement> HTMLDialogElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLDialogElement(tagName, document));
 }
@@ -69,7 +69,7 @@
 void HTMLDialogElement::closeDialog(const String& returnValue)
 {
     setBooleanAttribute(openAttr, false);
-    document()->removeFromTopLayer(this);
+    document().removeFromTopLayer(this);
     m_topIsValid = false;
 
     if (!returnValue.isNull())
@@ -93,7 +93,7 @@
 void HTMLDialogElement::reposition()
 {
     // Layout because we need to know our ancestors' positions and our own height.
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     RenderBox* box = renderBox();
     if (!box || !needsCenteredPositioning(box->style()))
@@ -101,7 +101,7 @@
 
     // Set up dialog's position to be safe-centered in the viewport.
     // FIXME: Figure out what to do in vertical writing mode.
-    FrameView* frameView = document()->view();
+    FrameView* frameView = document().view();
     int scrollTop = frameView->scrollOffset().height();
     int visibleHeight = frameView->visibleContentRect(ScrollableArea::IncludeScrollbars).height();
     m_top = scrollTop;
@@ -126,7 +126,7 @@
         es.throwDOMException(InvalidStateError);
         return;
     }
-    document()->addToTopLayer(this);
+    document().addToTopLayer(this);
     setBooleanAttribute(openAttr, true);
     reposition();
 }
diff --git a/Source/core/html/HTMLDialogElement.h b/Source/core/html/HTMLDialogElement.h
index b871159..f17bc84 100644
--- a/Source/core/html/HTMLDialogElement.h
+++ b/Source/core/html/HTMLDialogElement.h
@@ -36,7 +36,7 @@
 
 class HTMLDialogElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDialogElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLDialogElement> create(const QualifiedName&, Document&);
 
     void close(const String& returnValue, ExceptionState&);
     void show();
@@ -46,7 +46,7 @@
     void setReturnValue(const String& returnValue) { m_returnValue = returnValue; }
 
 private:
-    HTMLDialogElement(const QualifiedName&, Document*);
+    HTMLDialogElement(const QualifiedName&, Document&);
 
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -61,6 +61,12 @@
     String m_returnValue;
 };
 
+inline HTMLDialogElement* toHTMLDialogElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::dialogTag));
+    return static_cast<HTMLDialogElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/html/HTMLDialogElement.idl b/Source/core/html/HTMLDialogElement.idl
index d95f10f..41732ab 100644
--- a/Source/core/html/HTMLDialogElement.idl
+++ b/Source/core/html/HTMLDialogElement.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=dialogElement
+    EnabledAtRuntime=DialogElement
 ] interface HTMLDialogElement : HTMLElement {
     [Reflect] attribute boolean open;
     attribute DOMString returnValue;
diff --git a/Source/core/html/HTMLDirectoryElement.cpp b/Source/core/html/HTMLDirectoryElement.cpp
index 1a14d6e..0068dfa 100644
--- a/Source/core/html/HTMLDirectoryElement.cpp
+++ b/Source/core/html/HTMLDirectoryElement.cpp
@@ -29,14 +29,14 @@
 
 using namespace HTMLNames;
 
-inline HTMLDirectoryElement::HTMLDirectoryElement(const QualifiedName& tagName, Document* document)
+inline HTMLDirectoryElement::HTMLDirectoryElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(dirTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLDirectoryElement> HTMLDirectoryElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLDirectoryElement> HTMLDirectoryElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLDirectoryElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLDirectoryElement.h b/Source/core/html/HTMLDirectoryElement.h
index 9b77575..99efc0d 100644
--- a/Source/core/html/HTMLDirectoryElement.h
+++ b/Source/core/html/HTMLDirectoryElement.h
@@ -29,10 +29,10 @@
 
 class HTMLDirectoryElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDirectoryElement> create(const QualifiedName& tagName, Document*);
+    static PassRefPtr<HTMLDirectoryElement> create(const QualifiedName& tagName, Document&);
 
 private:
-    HTMLDirectoryElement(const QualifiedName&, Document*);
+    HTMLDirectoryElement(const QualifiedName&, Document&);
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLDivElement.cpp b/Source/core/html/HTMLDivElement.cpp
index b59b428..8ed60f1 100644
--- a/Source/core/html/HTMLDivElement.cpp
+++ b/Source/core/html/HTMLDivElement.cpp
@@ -31,19 +31,19 @@
 
 using namespace HTMLNames;
 
-HTMLDivElement::HTMLDivElement(const QualifiedName& tagName, Document* document)
+HTMLDivElement::HTMLDivElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(divTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLDivElement> HTMLDivElement::create(Document* document)
+PassRefPtr<HTMLDivElement> HTMLDivElement::create(Document& document)
 {
     return adoptRef(new HTMLDivElement(divTag, document));
 }
 
-PassRefPtr<HTMLDivElement> HTMLDivElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLDivElement> HTMLDivElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLDivElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLDivElement.h b/Source/core/html/HTMLDivElement.h
index ab96714..72b1153 100644
--- a/Source/core/html/HTMLDivElement.h
+++ b/Source/core/html/HTMLDivElement.h
@@ -29,11 +29,11 @@
 
 class HTMLDivElement : public HTMLElement {
 public:
-    static PassRefPtr<HTMLDivElement> create(Document*);
-    static PassRefPtr<HTMLDivElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLDivElement> create(Document&);
+    static PassRefPtr<HTMLDivElement> create(const QualifiedName&, Document&);
 
 protected:
-    HTMLDivElement(const QualifiedName&, Document*);
+    HTMLDivElement(const QualifiedName&, Document&);
 
 private:
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLDocument.cpp b/Source/core/html/HTMLDocument.cpp
index 0280bdf..26c4671 100644
--- a/Source/core/html/HTMLDocument.cpp
+++ b/Source/core/html/HTMLDocument.cpp
@@ -111,7 +111,7 @@
 
 Element* HTMLDocument::activeElement()
 {
-    if (Element* element = treeScope()->adjustedFocusedElement())
+    if (Element* element = treeScope().adjustedFocusedElement())
         return element;
     return body();
 }
diff --git a/Source/core/html/HTMLDocument.h b/Source/core/html/HTMLDocument.h
index 6990a78..181b942 100644
--- a/Source/core/html/HTMLDocument.h
+++ b/Source/core/html/HTMLDocument.h
@@ -112,6 +112,18 @@
     return static_cast<const HTMLDocument*>(document);
 }
 
+inline HTMLDocument& toHTMLDocument(Document& document)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(document.isHTMLDocument());
+    return static_cast<HTMLDocument&>(document);
+}
+
+inline const HTMLDocument& toHTMLDocument(const Document& document)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(document.isHTMLDocument());
+    return static_cast<const HTMLDocument&>(document);
+}
+
 // This will catch anyone doing an unnecessary cast.
 void toHTMLDocument(const HTMLDocument*);
 
diff --git a/Source/core/html/HTMLElement.cpp b/Source/core/html/HTMLElement.cpp
index 1200546..d82d6d5 100644
--- a/Source/core/html/HTMLElement.cpp
+++ b/Source/core/html/HTMLElement.cpp
@@ -64,7 +64,7 @@
 using std::min;
 using std::max;
 
-PassRefPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLElement> HTMLElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLElement(tagName, document));
 }
@@ -74,7 +74,7 @@
     // FIXME: Would be nice to have an atomicstring lookup based off uppercase
     // chars that does not have to copy the string on a hit in the hash.
     // FIXME: We should have a way to detect XHTML elements and replace the hasPrefix() check with it.
-    if (document()->isHTMLDocument() && !tagQName().hasPrefix())
+    if (document().isHTMLDocument() && !tagQName().hasPrefix())
         return tagQName().localNameUpper();
     return Element::nodeName();
 }
@@ -202,6 +202,9 @@
     typedef HashMap<AtomicString, AtomicString> StringToStringMap;
     DEFINE_STATIC_LOCAL(StringToStringMap, attributeNameToEventNameMap, ());
     if (!attributeNameToEventNameMap.size()) {
+        attributeNameToEventNameMap.set(onanimationstartAttr.localName(), eventNames().animationstartEvent);
+        attributeNameToEventNameMap.set(onanimationiterationAttr.localName(), eventNames().animationiterationEvent);
+        attributeNameToEventNameMap.set(onanimationendAttr.localName(), eventNames().animationendEvent);
         attributeNameToEventNameMap.set(onclickAttr.localName(), eventNames().clickEvent);
         attributeNameToEventNameMap.set(oncontextmenuAttr.localName(), eventNames().contextmenuEvent);
         attributeNameToEventNameMap.set(ondblclickAttr.localName(), eventNames().dblclickEvent);
@@ -292,10 +295,10 @@
         int tabindex = 0;
         if (value.isEmpty()) {
             clearTabIndexExplicitlyIfNeeded();
-            if (treeScope()->adjustedFocusedElement() == this) {
+            if (treeScope().adjustedFocusedElement() == this) {
                 // We might want to call blur(), but it's dangerous to dispatch
                 // events here.
-                document()->setNeedsFocusedElementCheck();
+                document().setNeedsFocusedElementCheck();
             }
         } else if (parseHTMLInteger(value, tabindex)) {
             // Clamp tabindex to the range of 'short' to match Firefox's behavior.
@@ -574,7 +577,7 @@
 
 void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionState& es)
 {
-    RefPtr<Text> textNode = document()->createTextNode(text);
+    RefPtr<Text> textNode = document().createTextNode(text);
     insertAdjacent(where, textNode.get(), es);
 }
 
@@ -626,7 +629,7 @@
     // This is the way to make it possible to navigate to (focus) elements
     // which web designer meant for being active (made them respond to click events).
 
-    if (!document()->settings() || !document()->settings()->spatialNavigationEnabled())
+    if (!document().settings() || !document().settings()->spatialNavigationEnabled())
         return false;
     EventTarget* target = const_cast<HTMLElement*>(this);
     return target->hasEventListeners(eventNames().clickEvent)
@@ -742,7 +745,7 @@
 {
     for (const Node* n = this; n; n = n->parentNode()) {
         if (n->isHTMLElement()) {
-            TranslateAttributeMode mode = static_cast<const HTMLElement*>(n)->translateAttributeMode();
+            TranslateAttributeMode mode = toHTMLElement(n)->translateAttributeMode();
             if (mode != TranslateAttributeInherit) {
                 ASSERT(mode == TranslateAttributeYes || mode == TranslateAttributeNo);
                 return mode == TranslateAttributeYes;
@@ -759,18 +762,18 @@
     setAttribute(translateAttr, enable ? "yes" : "no");
 }
 
-bool HTMLElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (hasLocalName(noscriptTag)) {
-        Frame* frame = document()->frame();
+        Frame* frame = document().frame();
         if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript))
             return false;
     } else if (hasLocalName(noembedTag)) {
-        Frame* frame = document()->frame();
+        Frame* frame = document().frame();
         if (frame && frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
             return false;
     }
-    return Element::rendererIsNeeded(context);
+    return Element::rendererIsNeeded(style);
 }
 
 RenderObject* HTMLElement::createRenderer(RenderStyle* style)
@@ -929,7 +932,7 @@
 
 void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
 {
-    if ((!document() || document()->renderer()) && childCountDelta < 0) {
+    if (document().renderer() && childCountDelta < 0) {
         Node* node = beforeChange ? NodeTraversal::nextSkippingChildren(beforeChange) : 0;
         for (int counter = 0; node && counter < childCountDelta; counter++, node = NodeTraversal::nextSkippingChildren(node)) {
             if (elementAffectsDirectionality(node))
@@ -1060,9 +1063,9 @@
         return;
 
     // If the string is a named CSS color or a 3/6-digit hex color, use that.
-    StyleColor parsedColor(colorString);
+    Color parsedColor(colorString);
     if (!parsedColor.isValid())
-        parsedColor = parseColorStringWithCrazyLegacyRules(colorString);
+        parsedColor.setRGB(parseColorStringWithCrazyLegacyRules(colorString));
 
     style->setProperty(propertyID, cssValuePool().createColorValue(parsedColor.rgb()));
 }
@@ -1080,7 +1083,7 @@
 
 void HTMLElement::handleKeypressEvent(KeyboardEvent* event)
 {
-    if (!document()->settings() || !document()->settings()->spatialNavigationEnabled() || !supportsFocus())
+    if (!document().settings() || !document().settings()->spatialNavigationEnabled() || !supportsFocus())
         return;
     // if the element is a text form control (like <input type=text> or <textarea>)
     // or has contentEditable attribute on, we should enter a space or newline
diff --git a/Source/core/html/HTMLElement.h b/Source/core/html/HTMLElement.h
index 40eafa3..1b2204f 100644
--- a/Source/core/html/HTMLElement.h
+++ b/Source/core/html/HTMLElement.h
@@ -40,7 +40,7 @@
 
 class HTMLElement : public Element {
 public:
-    static PassRefPtr<HTMLElement> create(const QualifiedName& tagName, Document*);
+    static PassRefPtr<HTMLElement> create(const QualifiedName& tagName, Document&);
 
     virtual String title() const OVERRIDE FINAL;
 
@@ -79,7 +79,7 @@
 
     bool ieForbidsInsertHTML() const;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
     virtual RenderObject* createRenderer(RenderStyle*);
 
     HTMLFormElement* form() const { return virtualForm(); }
@@ -96,7 +96,7 @@
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
 protected:
-    HTMLElement(const QualifiedName& tagName, Document*, ConstructionType);
+    HTMLElement(const QualifiedName& tagName, Document&, ConstructionType);
 
     void addHTMLLengthToStyle(MutableStylePropertySet*, CSSPropertyID, const String& value);
     void addHTMLColorToStyle(MutableStylePropertySet*, CSSPropertyID, const String& color);
@@ -150,8 +150,8 @@
 // This will catch anyone doing an unnecessary cast.
 void toHTMLElement(const HTMLElement*);
 
-inline HTMLElement::HTMLElement(const QualifiedName& tagName, Document* document, ConstructionType type = CreateHTMLElement)
-    : Element(tagName, document, type)
+inline HTMLElement::HTMLElement(const QualifiedName& tagName, Document& document, ConstructionType type = CreateHTMLElement)
+    : Element(tagName, &document, type)
 {
     ASSERT(tagName.localName().impl());
     ScriptWrappable::init(this);
diff --git a/Source/core/html/HTMLElement.idl b/Source/core/html/HTMLElement.idl
index d728075..d65a413 100644
--- a/Source/core/html/HTMLElement.idl
+++ b/Source/core/html/HTMLElement.idl
@@ -38,14 +38,14 @@
              [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString outerHTML;
              [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString outerText;
 
-    [RaisesException, CustomElementCallbacks=Enable] Element insertAdjacentElement([Default=Undefined] optional DOMString where,
+    [RaisesException, CustomElementCallbacks=Enable, MeasureAs=InsertAdjacentElement] Element insertAdjacentElement([Default=Undefined] optional DOMString where,
                                   [Default=Undefined] optional Element element);
     [CustomElementCallbacks=Enable, RaisesException] void insertAdjacentHTML([Default=Undefined] optional DOMString where,
                             [Default=Undefined] optional DOMString html);
-    [RaisesException] void insertAdjacentText([Default=Undefined] optional DOMString where,
+    [RaisesException, MeasureAs=InsertAdjacentText] void insertAdjacentText([Default=Undefined] optional DOMString where,
                             [Default=Undefined] optional DOMString text);
 
-    [EnabledAtRuntime=imeAPI] readonly attribute InputMethodContext inputMethodContext;
+    [EnabledAtRuntime=IMEAPI] readonly attribute InputMethodContext inputMethodContext;
 
     [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString contentEditable;
     readonly attribute boolean isContentEditable;
diff --git a/Source/core/html/HTMLEmbedElement.cpp b/Source/core/html/HTMLEmbedElement.cpp
index 8ba2a67..4d7d978 100644
--- a/Source/core/html/HTMLEmbedElement.cpp
+++ b/Source/core/html/HTMLEmbedElement.cpp
@@ -31,8 +31,6 @@
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/PluginDocument.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 #include "core/rendering/RenderWidget.h"
 
@@ -40,19 +38,19 @@
 
 using namespace HTMLNames;
 
-inline HTMLEmbedElement::HTMLEmbedElement(const QualifiedName& tagName, Document* document, bool createdByParser)
+inline HTMLEmbedElement::HTMLEmbedElement(const QualifiedName& tagName, Document& document, bool createdByParser)
     : HTMLPlugInImageElement(tagName, document, createdByParser, ShouldPreferPlugInsForImages)
 {
     ASSERT(hasTagName(embedTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(const QualifiedName& tagName, Document* document, bool createdByParser)
+PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
 {
     return adoptRef(new HTMLEmbedElement(tagName, document, createdByParser));
 }
 
-PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(Document* document)
+PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(Document& document)
 {
     return create(embedTag, document, false);
 }
@@ -158,11 +156,11 @@
     RefPtr<HTMLEmbedElement> protect(this); // Loading the plugin might remove us from the document.
     bool beforeLoadAllowedLoad = dispatchBeforeLoadEvent(m_url);
     if (!beforeLoadAllowedLoad) {
-        if (document()->isPluginDocument()) {
+        if (document().isPluginDocument()) {
             // Plugins inside plugin documents load differently than other plugins. By the time
             // we are here in a plugin document, the load of the plugin (which is the plugin document's
             // main resource) has already started. We need to explicitly cancel the main resource load here.
-            toPluginDocument(document())->cancelManualPluginLoad();
+            toPluginDocument(document()).cancelManualPluginLoad();
         }
         return;
     }
@@ -173,12 +171,12 @@
     requestObject(m_url, m_serviceType, paramNames, paramValues);
 }
 
-bool HTMLEmbedElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLEmbedElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (isImageType())
-        return HTMLPlugInImageElement::rendererIsNeeded(context);
+        return HTMLPlugInImageElement::rendererIsNeeded(style);
 
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return false;
 
@@ -192,7 +190,7 @@
             return false;
         }
     }
-    return HTMLPlugInImageElement::rendererIsNeeded(context);
+    return HTMLPlugInImageElement::rendererIsNeeded(style);
 }
 
 bool HTMLEmbedElement::isURLAttribute(const Attribute& attribute) const
@@ -200,7 +198,7 @@
     return attribute.name() == srcAttr || HTMLPlugInImageElement::isURLAttribute(attribute);
 }
 
-const AtomicString& HTMLEmbedElement::imageSourceURL() const
+const AtomicString HTMLEmbedElement::imageSourceURL() const
 {
     return getAttribute(srcAttr);
 }
@@ -209,7 +207,7 @@
 {
     HTMLPlugInImageElement::addSubresourceAttributeURLs(urls);
 
-    addSubresourceURL(urls, document()->completeURL(getAttribute(srcAttr)));
+    addSubresourceURL(urls, document().completeURL(getAttribute(srcAttr)));
 }
 
 }
diff --git a/Source/core/html/HTMLEmbedElement.h b/Source/core/html/HTMLEmbedElement.h
index aa113ae..1041bb5 100644
--- a/Source/core/html/HTMLEmbedElement.h
+++ b/Source/core/html/HTMLEmbedElement.h
@@ -29,20 +29,20 @@
 
 class HTMLEmbedElement FINAL : public HTMLPlugInImageElement {
 public:
-    static PassRefPtr<HTMLEmbedElement> create(Document*);
-    static PassRefPtr<HTMLEmbedElement> create(const QualifiedName&, Document*, bool createdByParser);
+    static PassRefPtr<HTMLEmbedElement> create(Document&);
+    static PassRefPtr<HTMLEmbedElement> create(const QualifiedName&, Document&, bool createdByParser);
 
 private:
-    HTMLEmbedElement(const QualifiedName&, Document*, bool createdByParser);
+    HTMLEmbedElement(const QualifiedName&, Document&, bool createdByParser);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
-    virtual const AtomicString& imageSourceURL() const OVERRIDE;
+    virtual const AtomicString imageSourceURL() const OVERRIDE;
 
     virtual RenderWidget* existingRenderWidget() const OVERRIDE;
 
diff --git a/Source/core/html/HTMLFieldSetElement.cpp b/Source/core/html/HTMLFieldSetElement.cpp
index 083b0cb..66ef537 100644
--- a/Source/core/html/HTMLFieldSetElement.cpp
+++ b/Source/core/html/HTMLFieldSetElement.cpp
@@ -37,7 +37,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLFieldSetElement::HTMLFieldSetElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+inline HTMLFieldSetElement::HTMLFieldSetElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
     : HTMLFormControlElement(tagName, document, form)
     , m_documentVersion(0)
 {
@@ -45,7 +45,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLFieldSetElement> HTMLFieldSetElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+PassRefPtr<HTMLFieldSetElement> HTMLFieldSetElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
 {
     return adoptRef(new HTMLFieldSetElement(tagName, document, form));
 }
@@ -94,7 +94,7 @@
 {
     for (Element* child = ElementTraversal::firstWithin(this); child; child = ElementTraversal::nextSkippingChildren(child, this)) {
         if (child->hasTagName(legendTag))
-            return static_cast<HTMLLegendElement*>(child);
+            return toHTMLLegendElement(child);
     }
     return 0;
 }
@@ -106,7 +106,7 @@
 
 void HTMLFieldSetElement::refreshElementsIfNeeded() const
 {
-    uint64_t docVersion = document()->domTreeVersion();
+    uint64_t docVersion = document().domTreeVersion();
     if (m_documentVersion == docVersion)
         return;
 
diff --git a/Source/core/html/HTMLFieldSetElement.h b/Source/core/html/HTMLFieldSetElement.h
index c63444f..2d522f2 100644
--- a/Source/core/html/HTMLFieldSetElement.h
+++ b/Source/core/html/HTMLFieldSetElement.h
@@ -33,7 +33,7 @@
 
 class HTMLFieldSetElement FINAL : public HTMLFormControlElement {
 public:
-    static PassRefPtr<HTMLFieldSetElement> create(const QualifiedName&, Document*, HTMLFormElement*);
+    static PassRefPtr<HTMLFieldSetElement> create(const QualifiedName&, Document&, HTMLFormElement*);
     HTMLLegendElement* legend() const;
 
     PassRefPtr<HTMLCollection> elements();
@@ -45,7 +45,7 @@
     virtual void disabledAttributeChanged() OVERRIDE;
 
 private:
-    HTMLFieldSetElement(const QualifiedName&, Document*, HTMLFormElement*);
+    HTMLFieldSetElement(const QualifiedName&, Document&, HTMLFormElement*);
 
     virtual bool isEnumeratable() const { return true; }
     virtual bool supportsFocus() const;
@@ -63,6 +63,12 @@
     mutable uint64_t m_documentVersion;
 };
 
+inline HTMLFieldSetElement* toHTMLFieldSetElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::fieldsetTag));
+    return static_cast<HTMLFieldSetElement*>(node);
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/html/HTMLFontElement.cpp b/Source/core/html/HTMLFontElement.cpp
index ab8a2b2..9f706c4 100644
--- a/Source/core/html/HTMLFontElement.cpp
+++ b/Source/core/html/HTMLFontElement.cpp
@@ -38,14 +38,14 @@
 
 using namespace HTMLNames;
 
-HTMLFontElement::HTMLFontElement(const QualifiedName& tagName, Document* document)
+HTMLFontElement::HTMLFontElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(fontTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLFontElement> HTMLFontElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLFontElement> HTMLFontElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLFontElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLFontElement.h b/Source/core/html/HTMLFontElement.h
index 212c5ab..7c85f6f 100644
--- a/Source/core/html/HTMLFontElement.h
+++ b/Source/core/html/HTMLFontElement.h
@@ -30,12 +30,12 @@
 
 class HTMLFontElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLFontElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLFontElement> create(const QualifiedName&, Document&);
 
     static bool cssValueFromFontSizeNumber(const String&, CSSValueID&);
 
 private:
-    HTMLFontElement(const QualifiedName&, Document*);
+    HTMLFontElement(const QualifiedName&, Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLFormControlElement.cpp b/Source/core/html/HTMLFormControlElement.cpp
index b875094..82ee82d 100644
--- a/Source/core/html/HTMLFormControlElement.cpp
+++ b/Source/core/html/HTMLFormControlElement.cpp
@@ -27,6 +27,7 @@
 
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
+#include "core/dom/PostAttachCallbacks.h"
 #include "core/html/HTMLFieldSetElement.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLInputElement.h"
@@ -44,7 +45,7 @@
 using namespace HTMLNames;
 using namespace std;
 
-HTMLFormControlElement::HTMLFormControlElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+HTMLFormControlElement::HTMLFormControlElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
     : LabelableElement(tagName, document)
     , m_disabled(false)
     , m_isReadOnly(false)
@@ -65,6 +66,7 @@
 
 HTMLFormControlElement::~HTMLFormControlElement()
 {
+    setForm(0);
 }
 
 String HTMLFormControlElement::formEnctype() const
@@ -106,7 +108,7 @@
         if (!legendAncestor && ancestor->hasTagName(legendTag))
             legendAncestor = ancestor;
         if (ancestor->hasTagName(fieldsetTag)) {
-            fieldSetAncestor = static_cast<HTMLFieldSetElement*>(ancestor);
+            fieldSetAncestor = toHTMLFieldSetElement(ancestor);
             break;
         }
     }
@@ -123,7 +125,7 @@
 {
     if (name == formAttr) {
         formAttributeChanged();
-        UseCounter::count(document(), UseCounter::FormAttribute);
+        UseCounter::count(&document(), UseCounter::FormAttribute);
     } else if (name == disabledAttr) {
         bool oldDisabled = m_disabled;
         m_disabled = !value.isNull();
@@ -143,10 +145,10 @@
         m_isRequired = !value.isNull();
         if (wasRequired != m_isRequired)
             requiredAttributeChanged();
-        UseCounter::count(document(), UseCounter::RequiredAttribute);
+        UseCounter::count(&document(), UseCounter::RequiredAttribute);
     } else if (name == autofocusAttr) {
         HTMLElement::parseAttribute(name, value);
-        UseCounter::count(document(), UseCounter::AutoFocusAttribute);
+        UseCounter::count(&document(), UseCounter::AutoFocusAttribute);
     } else
         HTMLElement::parseAttribute(name, value);
 }
@@ -157,10 +159,10 @@
     didAffectSelector(AffectedSelectorDisabled | AffectedSelectorEnabled);
     if (renderer() && renderer()->style()->hasAppearance())
         RenderTheme::theme().stateChanged(renderer(), EnabledState);
-    if (isDisabledFormControl() && treeScope()->adjustedFocusedElement() == this) {
+    if (isDisabledFormControl() && treeScope().adjustedFocusedElement() == this) {
         // We might want to call blur(), but it's dangerous to dispatch events
         // here.
-        document()->setNeedsFocusedElementCheck();
+        document().setNeedsFocusedElementCheck();
     }
 }
 
@@ -178,11 +180,11 @@
         return false;
     if (!element->renderer())
         return false;
-    if (element->document()->ignoreAutofocus())
+    if (element->document().ignoreAutofocus())
         return false;
-    if (element->document()->isSandboxed(SandboxAutomaticFeatures)) {
+    if (element->document().isSandboxed(SandboxAutomaticFeatures)) {
         // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
-        element->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked autofocusing on a form control because the form's frame is sandboxed and the 'allow-scripts' permission is not set.");
+        element->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked autofocusing on a form control because the form's frame is sandboxed and the 'allow-scripts' permission is not set.");
         return false;
     }
     if (element->hasAutofocused())
@@ -212,8 +214,6 @@
 
 void HTMLFormControlElement::attach(const AttachContext& context)
 {
-    PostAttachCallbackDisabler disabler(this);
-
     HTMLElement::attach(context);
 
     // The call to updateFromElement() needs to go after the call through
@@ -225,7 +225,7 @@
     if (shouldAutofocus(this)) {
         setAutofocused();
         ref();
-        queuePostAttachCallback(focusPostAttach, this);
+        PostAttachCallbacks::queueCallback(focusPostAttach, this);
     }
 }
 
@@ -299,12 +299,12 @@
         renderer->updateFromElement();
 }
 
-void HTMLFormControlElement::didRecalcStyle(StyleChange)
+void HTMLFormControlElement::didRecalcStyle(StyleRecalcChange)
 {
     // updateFromElement() can cause the selection to change, and in turn
     // trigger synchronous layout, so it must not be called during style recalc.
     if (renderer())
-        queuePostAttachCallback(updateFromElementCallback, this);
+        PostAttachCallbacks::queueCallback(updateFromElementCallback, this);
 }
 
 bool HTMLFormControlElement::supportsFocus() const
@@ -312,15 +312,6 @@
     return !isDisabledFormControl();
 }
 
-bool HTMLFormControlElement::rendererIsFocusable() const
-{
-    // If there's a renderer, make sure the size isn't empty, but if there's no renderer,
-    // it might still be focusable if it's in a canvas subtree (handled in Element::rendererIsFocusable).
-    if (renderer() && (!renderer()->isBox() || toRenderBox(renderer())->size().isEmpty()))
-        return false;
-    return HTMLElement::rendererIsFocusable();
-}
-
 bool HTMLFormControlElement::isKeyboardFocusable() const
 {
     // Skip tabIndex check in a parent class.
@@ -412,7 +403,7 @@
 
 void HTMLFormControlElement::updateVisibleValidationMessage()
 {
-    Page* page = document()->page();
+    Page* page = document().page();
     if (!page)
         return;
     String message;
@@ -437,9 +428,9 @@
         return false;
     // An event handler can deref this object.
     RefPtr<HTMLFormControlElement> protector(this);
-    RefPtr<Document> originalDocument(document());
+    RefPtr<Document> originalDocument(&document());
     bool needsDefaultAction = dispatchEvent(Event::createCancelable(eventNames().invalidEvent));
-    if (needsDefaultAction && unhandledInvalidControls && inDocument() && originalDocument == document())
+    if (needsDefaultAction && unhandledInvalidControls && inDocument() && originalDocument == &document())
         unhandledInvalidControls->append(this);
     return false;
 }
diff --git a/Source/core/html/HTMLFormControlElement.h b/Source/core/html/HTMLFormControlElement.h
index a58d61c..2189f95 100644
--- a/Source/core/html/HTMLFormControlElement.h
+++ b/Source/core/html/HTMLFormControlElement.h
@@ -106,7 +106,7 @@
     using Node::deref;
 
 protected:
-    HTMLFormControlElement(const QualifiedName& tagName, Document*, HTMLFormElement*);
+    HTMLFormControlElement(const QualifiedName& tagName, Document&, HTMLFormElement*);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void requiredAttributeChanged();
@@ -117,7 +117,6 @@
     virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
 
     virtual bool supportsFocus() const OVERRIDE;
-    virtual bool rendererIsFocusable() const OVERRIDE;
     virtual bool isKeyboardFocusable() const OVERRIDE;
     virtual bool shouldShowFocusRingOnMouseFocus() const;
     virtual bool shouldHaveFocusAppearance() const OVERRIDE;
@@ -125,7 +124,7 @@
     virtual void dispatchBlurEvent(Element* newFocusedElement) OVERRIDE;
     virtual void willCallDefaultEventHandler(const Event&) OVERRIDE;
 
-    virtual void didRecalcStyle(StyleChange) OVERRIDE;
+    virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE;
 
     // This must be called any time the result of willValidate() has changed.
     void setNeedsWillValidateCheck();
@@ -183,6 +182,12 @@
     return static_cast<HTMLFormControlElement*>(control);
 }
 
+inline const HTMLFormControlElement* toHTMLFormControlElement(const FormAssociatedElement* control)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!control || control->isFormControlElement());
+    return static_cast<const HTMLFormControlElement*>(control);
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/html/HTMLFormControlElementWithState.cpp b/Source/core/html/HTMLFormControlElementWithState.cpp
index 9e862f5..2dc33c6 100644
--- a/Source/core/html/HTMLFormControlElementWithState.cpp
+++ b/Source/core/html/HTMLFormControlElementWithState.cpp
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-HTMLFormControlElementWithState::HTMLFormControlElementWithState(const QualifiedName& tagName, Document* doc, HTMLFormElement* f)
+HTMLFormControlElementWithState::HTMLFormControlElementWithState(const QualifiedName& tagName, Document& doc, HTMLFormElement* f)
     : HTMLFormControlElement(tagName, doc, f)
 {
 }
@@ -46,14 +46,14 @@
 Node::InsertionNotificationRequest HTMLFormControlElementWithState::insertedInto(ContainerNode* insertionPoint)
 {
     if (insertionPoint->inDocument() && !containingShadowRoot())
-        document()->formController()->registerFormElementWithState(this);
+        document().formController()->registerFormElementWithState(this);
     return HTMLFormControlElement::insertedInto(insertionPoint);
 }
 
 void HTMLFormControlElementWithState::removedFrom(ContainerNode* insertionPoint)
 {
     if (insertionPoint->inDocument() && !containingShadowRoot() && !insertionPoint->containingShadowRoot())
-        document()->formController()->unregisterFormElementWithState(this);
+        document().formController()->unregisterFormElementWithState(this);
     HTMLFormControlElement::removedFrom(insertionPoint);
 }
 
@@ -66,7 +66,7 @@
 
 void HTMLFormControlElementWithState::notifyFormStateChanged()
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
@@ -88,7 +88,7 @@
 void HTMLFormControlElementWithState::finishParsingChildren()
 {
     HTMLFormControlElement::finishParsingChildren();
-    document()->formController()->restoreControlStateFor(*this);
+    document().formController()->restoreControlStateFor(*this);
 }
 
 bool HTMLFormControlElementWithState::isFormControlElementWithState() const
diff --git a/Source/core/html/HTMLFormControlElementWithState.h b/Source/core/html/HTMLFormControlElementWithState.h
index e25dc12..57bd66a 100644
--- a/Source/core/html/HTMLFormControlElementWithState.h
+++ b/Source/core/html/HTMLFormControlElementWithState.h
@@ -43,7 +43,7 @@
     void notifyFormStateChanged();
 
 protected:
-    HTMLFormControlElementWithState(const QualifiedName& tagName, Document*, HTMLFormElement*);
+    HTMLFormControlElementWithState(const QualifiedName& tagName, Document&, HTMLFormElement*);
 
     virtual bool shouldAutocomplete() const;
     virtual void finishParsingChildren();
@@ -52,6 +52,12 @@
     virtual bool isFormControlElementWithState() const OVERRIDE;
 };
 
+inline HTMLFormControlElementWithState* toHTMLFormControlElementWithState(FormAssociatedElement* element)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isFormControlElementWithState());
+    return static_cast<HTMLFormControlElementWithState*>(element);
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/html/HTMLFormControlsCollection.cpp b/Source/core/html/HTMLFormControlsCollection.cpp
index a432b1b..972bb75 100644
--- a/Source/core/html/HTMLFormControlsCollection.cpp
+++ b/Source/core/html/HTMLFormControlsCollection.cpp
@@ -57,7 +57,7 @@
     ASSERT(ownerNode()->hasTagName(formTag) || ownerNode()->hasTagName(fieldsetTag));
     if (ownerNode()->hasTagName(formTag))
         return toHTMLFormElement(ownerNode())->associatedElements();
-    return static_cast<HTMLFieldSetElement*>(ownerNode())->associatedElements();
+    return toHTMLFieldSetElement(ownerNode())->associatedElements();
 }
 
 const Vector<HTMLImageElement*>& HTMLFormControlsCollection::formImageElements() const
diff --git a/Source/core/html/HTMLFormControlsCollection.idl b/Source/core/html/HTMLFormControlsCollection.idl
index 3030738..e7b757e 100644
--- a/Source/core/html/HTMLFormControlsCollection.idl
+++ b/Source/core/html/HTMLFormControlsCollection.idl
@@ -22,7 +22,7 @@
     GenerateIsReachable=ownerNode,
     DependentLifetime
 ] interface HTMLFormControlsCollection : HTMLCollection {
-    [ImplementedAs=item] getter Node([Default=Undefined] optional unsigned long index);
+    [ImplementedAs=item] getter Node(unsigned long index);
     [Custom] Node namedItem([Default=Undefined] optional DOMString name);
     [ImplementedAs=namedGetter, NotEnumerable] getter (RadioNodeList or Node)(DOMString name);
 };
diff --git a/Source/core/html/HTMLFormElement.cpp b/Source/core/html/HTMLFormElement.cpp
index d86650c..42b095f 100644
--- a/Source/core/html/HTMLFormElement.cpp
+++ b/Source/core/html/HTMLFormElement.cpp
@@ -36,11 +36,11 @@
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/NamedNodesCollection.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/html/FormController.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
+#include "core/html/HTMLObjectElement.h"
 #include "core/html/HTMLTableElement.h"
 #include "core/loader/FormState.h"
 #include "core/loader/FrameLoader.h"
@@ -56,7 +56,7 @@
 
 using namespace HTMLNames;
 
-HTMLFormElement::HTMLFormElement(const QualifiedName& tagName, Document* document)
+HTMLFormElement::HTMLFormElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_associatedElementsBeforeIndex(0)
     , m_associatedElementsAfterIndex(0)
@@ -71,21 +71,21 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLFormElement> HTMLFormElement::create(Document* document)
+PassRefPtr<HTMLFormElement> HTMLFormElement::create(Document& document)
 {
-    UseCounter::count(document, UseCounter::FormElement);
+    UseCounter::count(&document, UseCounter::FormElement);
     return adoptRef(new HTMLFormElement(formTag, document));
 }
 
-PassRefPtr<HTMLFormElement> HTMLFormElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLFormElement> HTMLFormElement::create(const QualifiedName& tagName, Document& document)
 {
-    UseCounter::count(document, UseCounter::FormElement);
+    UseCounter::count(&document, UseCounter::FormElement);
     return adoptRef(new HTMLFormElement(tagName, document));
 }
 
 HTMLFormElement::~HTMLFormElement()
 {
-    document()->formController()->willDeleteForm(this);
+    document().formController()->willDeleteForm(this);
 
     for (unsigned i = 0; i < m_associatedElements.size(); ++i)
         m_associatedElements[i]->formWillBeDestroyed();
@@ -95,17 +95,18 @@
 
 bool HTMLFormElement::formWouldHaveSecureSubmission(const String& url)
 {
-    return document()->completeURL(url).protocolIs("https");
+    return document().completeURL(url).protocolIs("https");
 }
 
-bool HTMLFormElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLFormElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (!m_wasDemoted)
-        return HTMLElement::rendererIsNeeded(context);
+        return HTMLElement::rendererIsNeeded(style);
 
     ContainerNode* node = parentNode();
     RenderObject* parentRenderer = node->renderer();
     // FIXME: Shouldn't we also check for table caption (see |formIsTablePart| below).
+    // FIXME: This check is not correct for Shadow DOM.
     bool parentIsTableElementPart = (parentRenderer->isTable() && isHTMLTableElement(node))
         || (parentRenderer->isTableRow() && node->hasTagName(trTag))
         || (parentRenderer->isTableSection() && node->hasTagName(tbodyTag))
@@ -115,7 +116,7 @@
     if (!parentIsTableElementPart)
         return true;
 
-    EDisplay display = context.style()->display();
+    EDisplay display = style.display();
     bool formIsTablePart = display == TABLE || display == INLINE_TABLE || display == TABLE_ROW_GROUP
         || display == TABLE_HEADER_GROUP || display == TABLE_FOOTER_GROUP || display == TABLE_ROW
         || display == TABLE_COLUMN_GROUP || display == TABLE_COLUMN || display == TABLE_CELL
@@ -128,7 +129,7 @@
 {
     HTMLElement::insertedInto(insertionPoint);
     if (insertionPoint->inDocument())
-        this->document()->didAssociateFormControl(this);
+        this->document().didAssociateFormControl(this);
     return InsertionDone;
 }
 
@@ -205,7 +206,7 @@
 bool HTMLFormElement::validateInteractively(Event* event)
 {
     ASSERT(event);
-    if (!document()->page() || noValidate())
+    if (!document().page() || noValidate())
         return true;
 
     HTMLFormControlElement* submitElement = submitElementFromEvent(event);
@@ -225,7 +226,7 @@
 
     // Needs to update layout now because we'd like to call isFocusable(), which
     // has !renderer()->needsLayout() assertion.
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     RefPtr<HTMLFormElement> protector(this);
     // Focus on the first focusable control and show a validation message.
@@ -241,7 +242,7 @@
         }
     }
     // Warn about all of unfocusable controls.
-    if (document()->frame()) {
+    if (document().frame()) {
         for (unsigned i = 0; i < unhandledInvalidControls.size(); ++i) {
             FormAssociatedElement* unhandledAssociatedElement = unhandledInvalidControls[i].get();
             HTMLElement* unhandled = toHTMLElement(unhandledAssociatedElement);
@@ -249,7 +250,7 @@
                 continue;
             String message("An invalid form control with name='%name' is not focusable.");
             message.replace("%name", unhandledAssociatedElement->name());
-            document()->addConsoleMessage(RenderingMessageSource, ErrorMessageLevel, message);
+            document().addConsoleMessage(RenderingMessageSource, ErrorMessageLevel, message);
         }
     }
     return false;
@@ -257,7 +258,7 @@
 
 bool HTMLFormElement::prepareForSubmission(Event* event)
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (m_isSubmittingOrPreparingForSubmission || !frame)
         return m_isSubmittingOrPreparingForSubmission;
 
@@ -272,10 +273,10 @@
 
     StringPairVector controlNamesAndValues;
     getTextFieldValues(controlNamesAndValues);
-    RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, document(), NotSubmittedByJavaScript);
+    RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), NotSubmittedByJavaScript);
     frame->loader()->client()->dispatchWillSendSubmitEvent(formState.release());
 
-    if (dispatchEvent(Event::create(eventNames().submitEvent, true, true)))
+    if (dispatchEvent(Event::createCancelableBubble(eventNames().submitEvent)))
         m_shouldSubmit = true;
 
     m_isSubmittingOrPreparingForSubmission = false;
@@ -317,8 +318,8 @@
 
 void HTMLFormElement::submit(Event* event, bool activateSubmitButton, bool processingUserGesture, FormSubmissionTrigger formSubmissionTrigger)
 {
-    FrameView* view = document()->view();
-    Frame* frame = document()->frame();
+    FrameView* view = document().view();
+    Frame* frame = document().frame();
     if (!view || !frame || !frame->page())
         return;
 
@@ -365,33 +366,33 @@
     ASSERT(submission->state());
     if (submission->action().isEmpty())
         return;
-    if (document()->isSandboxed(SandboxForms)) {
+    if (document().isSandboxed(SandboxForms)) {
         // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
-        document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked form submission to '" + submission->action().elidedString() + "' because the form's frame is sandboxed and the 'allow-forms' permission is not set.");
+        document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked form submission to '" + submission->action().elidedString() + "' because the form's frame is sandboxed and the 'allow-forms' permission is not set.");
         return;
     }
 
     if (protocolIsJavaScript(submission->action())) {
-        if (!document()->contentSecurityPolicy()->allowFormAction(KURL(submission->action())))
+        if (!document().contentSecurityPolicy()->allowFormAction(KURL(submission->action())))
             return;
-        document()->frame()->script()->executeScriptIfJavaScriptURL(submission->action());
+        document().frame()->script()->executeScriptIfJavaScriptURL(submission->action());
         return;
     }
-    submission->setReferrer(document()->frame()->loader()->outgoingReferrer());
-    submission->setOrigin(document()->frame()->loader()->outgoingOrigin());
+    submission->setReferrer(document().frame()->loader()->outgoingReferrer());
+    submission->setOrigin(document().frame()->loader()->outgoingOrigin());
 
-    document()->frame()->navigationScheduler()->scheduleFormSubmission(submission);
+    document().frame()->navigationScheduler()->scheduleFormSubmission(submission);
 }
 
 void HTMLFormElement::reset()
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (m_isInResetFunction || !frame)
         return;
 
     m_isInResetFunction = true;
 
-    if (!dispatchEvent(Event::create(eventNames().resetEvent, true, true))) {
+    if (!dispatchEvent(Event::createCancelableBubble(eventNames().resetEvent))) {
         m_isInResetFunction = false;
         return;
     }
@@ -406,7 +407,7 @@
 
 void HTMLFormElement::requestAutocomplete()
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
@@ -417,7 +418,7 @@
 
     StringPairVector controlNamesAndValues;
     getTextFieldValues(controlNamesAndValues);
-    RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, document(), SubmittedByJavaScript);
+    RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), SubmittedByJavaScript);
     frame->loader()->client()->didRequestAutocomplete(formState.release());
 }
 
@@ -425,7 +426,7 @@
 {
     RefPtr<Event> event;
     if (result == AutocompleteResultSuccess)
-        event = Event::create(eventNames().autocompleteEvent, false, false);
+        event = Event::create(eventNames().autocompleteEvent);
     else if (result == AutocompleteResultErrorDisabled)
         event = AutocompleteErrorEvent::create("disabled");
     else if (result == AutocompleteResultErrorCancel)
@@ -566,6 +567,7 @@
         --m_associatedElementsBeforeIndex;
     if (index < m_associatedElementsAfterIndex)
         --m_associatedElementsAfterIndex;
+    removeFromPastNamesMap(*toHTMLElement(e));
     removeFromVector(m_associatedElements, e);
 }
 
@@ -583,6 +585,7 @@
 void HTMLFormElement::removeImgElement(HTMLImageElement* e)
 {
     ASSERT(m_imageElements.find(e) != notFound);
+    removeFromPastNamesMap(*e);
     removeFromVector(m_imageElements, e);
 }
 
@@ -683,36 +686,58 @@
     return hasInvalidControls;
 }
 
-Node* HTMLFormElement::elementForAlias(const AtomicString& alias)
+Node* HTMLFormElement::elementFromPastNamesMap(const AtomicString& pastName) const
 {
-    if (alias.isEmpty() || !m_elementAliases)
+    if (pastName.isEmpty() || !m_pastNamesMap)
         return 0;
-    return m_elementAliases->get(alias.impl());
+    Node* node = m_pastNamesMap->get(pastName.impl());
+#if !ASSERT_DISABLED
+    if (!node)
+        return 0;
+    ASSERT_WITH_SECURITY_IMPLICATION(toHTMLElement(node)->form() == this);
+    if (node->hasTagName(imgTag)) {
+        ASSERT_WITH_SECURITY_IMPLICATION(m_imageElements.find(node) != notFound);
+    } else if (node->hasTagName(objectTag)) {
+        ASSERT_WITH_SECURITY_IMPLICATION(m_associatedElements.find(toHTMLObjectElement(node)) != notFound);
+    } else {
+        ASSERT_WITH_SECURITY_IMPLICATION(m_associatedElements.find(toHTMLFormControlElement(node)) != notFound);
+    }
+#endif
+    return node;
 }
 
-void HTMLFormElement::addElementAlias(Node* element, const AtomicString& alias)
+void HTMLFormElement::addToPastNamesMap(Node* element, const AtomicString& pastName)
 {
-    if (alias.isEmpty())
+    if (pastName.isEmpty())
         return;
-    if (!m_elementAliases)
-        m_elementAliases = adoptPtr(new AliasMap);
-    m_elementAliases->set(alias.impl(), element);
+    if (!m_pastNamesMap)
+        m_pastNamesMap = adoptPtr(new PastNamesMap);
+    m_pastNamesMap->set(pastName.impl(), element);
+}
+
+void HTMLFormElement::removeFromPastNamesMap(HTMLElement& element)
+{
+    if (!m_pastNamesMap)
+        return;
+    PastNamesMap::iterator end = m_pastNamesMap->end();
+    for (PastNamesMap::iterator it = m_pastNamesMap->begin(); it != end; ++it) {
+        if (it->value.get() == &element) {
+            it->value = 0;
+            // Keep looping. Single element can have multiple names.
+        }
+    }
 }
 
 void HTMLFormElement::getNamedElements(const AtomicString& name, Vector<RefPtr<Node> >& namedItems)
 {
+    // http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#dom-form-nameditem
     elements()->namedItems(name, namedItems);
 
-    Node* aliasElement = elementForAlias(name);
-    if (aliasElement) {
-        if (namedItems.find(aliasElement) == notFound) {
-            // We have seen it before but it is gone now. Still, we need to return it.
-            // FIXME: The above comment is not clear enough; it does not say why we need to do this.
-            namedItems.append(aliasElement);
-        }
-    }
-    if (namedItems.size() && namedItems.first() != aliasElement)
-        addElementAlias(namedItems.first().get(), name);
+    Node* elementFromPast = elementFromPastNamesMap(name);
+    if (namedItems.size() && namedItems.first() != elementFromPast)
+        addToPastNamesMap(namedItems.first().get(), name);
+    else if (elementFromPast && namedItems.isEmpty())
+        namedItems.append(elementFromPast);
 }
 
 bool HTMLFormElement::shouldAutocomplete() const
@@ -723,7 +748,7 @@
 void HTMLFormElement::finishParsingChildren()
 {
     HTMLElement::finishParsingChildren();
-    document()->formController()->restoreControlStateIn(*this);
+    document().formController()->restoreControlStateIn(*this);
 }
 
 void HTMLFormElement::copyNonAttributePropertiesFromElement(const Element& source)
@@ -763,7 +788,7 @@
 void HTMLFormElement::setDemoted(bool demoted)
 {
     if (demoted)
-        UseCounter::count(document(), UseCounter::DemotedFormElement);
+        UseCounter::count(&document(), UseCounter::DemotedFormElement);
     m_wasDemoted = demoted;
 }
 
diff --git a/Source/core/html/HTMLFormElement.h b/Source/core/html/HTMLFormElement.h
index 47acf26..184fa30 100644
--- a/Source/core/html/HTMLFormElement.h
+++ b/Source/core/html/HTMLFormElement.h
@@ -46,8 +46,8 @@
 
 class HTMLFormElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLFormElement> create(Document*);
-    static PassRefPtr<HTMLFormElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLFormElement> create(Document&);
+    static PassRefPtr<HTMLFormElement> create(const QualifiedName&, Document&);
     virtual ~HTMLFormElement();
 
     PassRefPtr<HTMLCollection> elements();
@@ -116,9 +116,6 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(autocomplete);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(autocompleteerror);
 
-    Node* elementForAlias(const AtomicString&);
-    void addElementAlias(Node*, const AtomicString& alias);
-
     CheckedRadioButtons& checkedRadioButtons() { return m_checkedRadioButtons; }
 
     const Vector<FormAssociatedElement*>& associatedElements() const { return m_associatedElements; }
@@ -128,9 +125,9 @@
     void anonymousNamedGetter(const AtomicString& name, bool&, RefPtr<NodeList>&, bool&, RefPtr<Node>&);
 
 private:
-    HTMLFormElement(const QualifiedName&, Document*);
+    HTMLFormElement(const QualifiedName&, Document&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void finishParsingChildren() OVERRIDE;
@@ -159,10 +156,14 @@
     // are any invalid controls in this form.
     bool checkInvalidControlsAndCollectUnhandled(Vector<RefPtr<FormAssociatedElement> >*, HTMLFormControlElement::CheckValidityDispatchEvents = HTMLFormControlElement::CheckValidityDispatchEventsAllowed);
 
-    typedef HashMap<AtomicString, RefPtr<Node> > AliasMap;
+    Node* elementFromPastNamesMap(const AtomicString&) const;
+    void addToPastNamesMap(Node*, const AtomicString& pastName);
+    void removeFromPastNamesMap(HTMLElement&);
+
+    typedef HashMap<AtomicString, RefPtr<Node> > PastNamesMap;
 
     FormSubmission::Attributes m_attributes;
-    OwnPtr<AliasMap> m_elementAliases;
+    OwnPtr<PastNamesMap> m_pastNamesMap;
 
     CheckedRadioButtons m_checkedRadioButtons;
 
diff --git a/Source/core/html/HTMLFormElement.idl b/Source/core/html/HTMLFormElement.idl
index 11c8bf5..f1bcb0e 100644
--- a/Source/core/html/HTMLFormElement.idl
+++ b/Source/core/html/HTMLFormElement.idl
@@ -38,7 +38,7 @@
     [CustomElementCallbacks=Enable] void reset();
     boolean checkValidity();
 
-    [EnabledAtRuntime=requestAutocomplete] void requestAutocomplete();
-    [EnabledAtRuntime=requestAutocomplete,NotEnumerable] attribute EventHandler onautocomplete;
-    [EnabledAtRuntime=requestAutocomplete,NotEnumerable] attribute EventHandler onautocompleteerror;
+    [EnabledAtRuntime=RequestAutocomplete] void requestAutocomplete();
+    [EnabledAtRuntime=RequestAutocomplete, NotEnumerable] attribute EventHandler onautocomplete;
+    [EnabledAtRuntime=RequestAutocomplete, NotEnumerable] attribute EventHandler onautocompleteerror;
 };
diff --git a/Source/core/html/HTMLFrameElement.cpp b/Source/core/html/HTMLFrameElement.cpp
index 16216b1..38e82ca 100644
--- a/Source/core/html/HTMLFrameElement.cpp
+++ b/Source/core/html/HTMLFrameElement.cpp
@@ -32,7 +32,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLFrameElement::HTMLFrameElement(const QualifiedName& tagName, Document* document)
+inline HTMLFrameElement::HTMLFrameElement(const QualifiedName& tagName, Document& document)
     : HTMLFrameElementBase(tagName, document)
     , m_frameBorder(true)
     , m_frameBorderSet(false)
@@ -41,12 +41,12 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLFrameElement> HTMLFrameElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLFrameElement> HTMLFrameElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLFrameElement(tagName, document));
 }
 
-bool HTMLFrameElement::rendererIsNeeded(const NodeRenderingContext&)
+bool HTMLFrameElement::rendererIsNeeded(const RenderStyle&)
 {
     // For compatibility, frames render even when display: none is set.
     return isURLAllowed();
diff --git a/Source/core/html/HTMLFrameElement.h b/Source/core/html/HTMLFrameElement.h
index 70c0b6a..1cd3ab0 100644
--- a/Source/core/html/HTMLFrameElement.h
+++ b/Source/core/html/HTMLFrameElement.h
@@ -30,18 +30,18 @@
 
 class HTMLFrameElement FINAL : public HTMLFrameElementBase {
 public:
-    static PassRefPtr<HTMLFrameElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLFrameElement> create(const QualifiedName&, Document&);
 
     bool hasFrameBorder() const { return m_frameBorder; }
 
     bool noResize() const;
 
 private:
-    HTMLFrameElement(const QualifiedName&, Document*);
+    HTMLFrameElement(const QualifiedName&, Document&);
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
     virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -52,6 +52,12 @@
     bool m_frameBorderSet;
 };
 
+inline HTMLFrameElement* toHTMLFrameElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::frameTag));
+    return static_cast<HTMLFrameElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // HTMLFrameElement_h
diff --git a/Source/core/html/HTMLFrameElementBase.cpp b/Source/core/html/HTMLFrameElementBase.cpp
index d04a479..3b9925b 100644
--- a/Source/core/html/HTMLFrameElementBase.cpp
+++ b/Source/core/html/HTMLFrameElementBase.cpp
@@ -42,7 +42,7 @@
 
 using namespace HTMLNames;
 
-HTMLFrameElementBase::HTMLFrameElementBase(const QualifiedName& tagName, Document* document)
+HTMLFrameElementBase::HTMLFrameElementBase(const QualifiedName& tagName, Document& document)
     : HTMLFrameOwnerElement(tagName, document)
     , m_scrolling(ScrollbarAuto)
     , m_marginWidth(-1)
@@ -55,7 +55,7 @@
     if (m_URL.isEmpty())
         return true;
 
-    const KURL& completeURL = document()->completeURL(m_URL);
+    const KURL& completeURL = document().completeURL(m_URL);
 
     if (protocolIsJavaScript(completeURL)) {
         Document* contentDoc = this->contentDocument();
@@ -63,7 +63,7 @@
             return false;
     }
 
-    Frame* parentFrame = document()->frame();
+    Frame* parentFrame = document().frame();
     if (parentFrame)
         return parentFrame->isURLAllowed(completeURL);
 
@@ -78,13 +78,13 @@
     if (m_URL.isEmpty())
         m_URL = blankURL().string();
 
-    Frame* parentFrame = document()->frame();
+    Frame* parentFrame = document().frame();
     if (!parentFrame)
         return;
 
     // Support for <frame src="javascript:string">
     KURL scriptURL;
-    KURL url = document()->completeURL(m_URL);
+    KURL url = document().completeURL(m_URL);
     if (protocolIsJavaScript(m_URL)) {
         scriptURL = url;
         url = blankURL();
@@ -145,31 +145,17 @@
 Node::InsertionNotificationRequest HTMLFrameElementBase::insertedInto(ContainerNode* insertionPoint)
 {
     HTMLFrameOwnerElement::insertedInto(insertionPoint);
-    if (insertionPoint->inDocument())
-        return InsertionShouldCallDidNotifySubtreeInsertions;
-    return InsertionDone;
+    return InsertionShouldCallDidNotifySubtreeInsertions;
 }
 
-void HTMLFrameElementBase::didNotifySubtreeInsertions(ContainerNode*)
+void HTMLFrameElementBase::didNotifySubtreeInsertionsToDocument()
 {
-    if (!inDocument())
-        return;
-
-    // DocumentFragments don't kick of any loads.
-    if (!document()->frame())
+    if (!document().frame())
         return;
 
     if (!SubframeLoadingDisabler::canLoadFrame(this))
         return;
 
-    // JavaScript in src=javascript: and beforeonload can access the renderer
-    // during attribute parsing *before* the normal parser machinery would
-    // attach the element. To support this, we lazyAttach here, but only
-    // if we don't already have a renderer (if we're inserted
-    // as part of a DocumentFragment, insertedInto from an earlier element
-    // could have forced a style resolve and already attached us).
-    if (!renderer())
-        lazyAttach(DoNotSetAttached);
     setNameAndOpenURL();
 }
 
@@ -187,7 +173,7 @@
 {
     if (fastHasAttribute(srcdocAttr))
         return KURL(ParsedURLString, "about:srcdoc");
-    return document()->completeURL(getAttribute(srcAttr));
+    return document().completeURL(getAttribute(srcAttr));
 }
 
 void HTMLFrameElementBase::setLocation(const String& str)
@@ -206,7 +192,7 @@
 void HTMLFrameElementBase::setFocus(bool received)
 {
     HTMLFrameOwnerElement::setFocus(received);
-    if (Page* page = document()->page()) {
+    if (Page* page = document().page()) {
         if (received)
             page->focusController().setFocusedFrame(contentFrame());
         else if (page->focusController().focusedFrame() == contentFrame()) // Focus may have already been given to another frame, don't take it away.
@@ -226,7 +212,7 @@
 
 int HTMLFrameElementBase::width()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     if (!renderBox())
         return 0;
     return renderBox()->width();
@@ -234,7 +220,7 @@
 
 int HTMLFrameElementBase::height()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     if (!renderBox())
         return 0;
     return renderBox()->height();
diff --git a/Source/core/html/HTMLFrameElementBase.h b/Source/core/html/HTMLFrameElementBase.h
index 3bfcb33..a384652 100644
--- a/Source/core/html/HTMLFrameElementBase.h
+++ b/Source/core/html/HTMLFrameElementBase.h
@@ -45,13 +45,13 @@
     virtual bool canContainRangeEndPoint() const { return false; }
 
 protected:
-    HTMLFrameElementBase(const QualifiedName&, Document*);
+    HTMLFrameElementBase(const QualifiedName&, Document&);
 
     bool isURLAllowed() const;
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    virtual void didNotifySubtreeInsertions(ContainerNode*) OVERRIDE;
+    virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
 
 private:
diff --git a/Source/core/html/HTMLFrameOwnerElement.cpp b/Source/core/html/HTMLFrameOwnerElement.cpp
index 0a5d70e..dbcbd5e 100644
--- a/Source/core/html/HTMLFrameOwnerElement.cpp
+++ b/Source/core/html/HTMLFrameOwnerElement.cpp
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-HTMLFrameOwnerElement::HTMLFrameOwnerElement(const QualifiedName& tagName, Document* document)
+HTMLFrameOwnerElement::HTMLFrameOwnerElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_contentFrame(0)
     , m_sandboxFlags(SandboxNone)
@@ -125,13 +125,13 @@
 
 bool HTMLFrameOwnerElement::loadOrRedirectSubframe(const KURL& url, const AtomicString& frameName, bool lockBackForwardList)
 {
-    RefPtr<Frame> parentFrame = document()->frame();
+    RefPtr<Frame> parentFrame = document().frame();
     if (contentFrame()) {
-        contentFrame()->navigationScheduler()->scheduleLocationChange(document()->securityOrigin(), url.string(), parentFrame->loader()->outgoingReferrer(), lockBackForwardList);
+        contentFrame()->navigationScheduler()->scheduleLocationChange(document().securityOrigin(), url.string(), parentFrame->loader()->outgoingReferrer(), lockBackForwardList);
         return true;
     }
 
-    if (!document()->securityOrigin()->canDisplay(url)) {
+    if (!document().securityOrigin()->canDisplay(url)) {
         FrameLoader::reportLocalLoadFailed(parentFrame.get(), url.string());
         return false;
     }
@@ -139,7 +139,7 @@
     if (!SubframeLoadingDisabler::canLoadFrame(this))
         return false;
 
-    String referrer = SecurityPolicy::generateReferrerHeader(document()->referrerPolicy(), url, parentFrame->loader()->outgoingReferrer());
+    String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), url, parentFrame->loader()->outgoingReferrer());
     RefPtr<Frame> childFrame = parentFrame->loader()->client()->createFrame(url, frameName, referrer, this);
 
     if (!childFrame)  {
diff --git a/Source/core/html/HTMLFrameOwnerElement.h b/Source/core/html/HTMLFrameOwnerElement.h
index 2b4ec42..ed1b7ab 100644
--- a/Source/core/html/HTMLFrameOwnerElement.h
+++ b/Source/core/html/HTMLFrameOwnerElement.h
@@ -59,8 +59,12 @@
     virtual bool loadedNonEmptyDocument() const { return false; }
     virtual void didLoadNonEmptyDocument() { }
 
+    virtual void renderFallbackContent() { }
+
+    virtual bool isObjectElement() const { return false; }
+
 protected:
-    HTMLFrameOwnerElement(const QualifiedName& tagName, Document*);
+    HTMLFrameOwnerElement(const QualifiedName& tagName, Document&);
     void setSandboxFlags(SandboxFlags);
 
     bool loadOrRedirectSubframe(const KURL&, const AtomicString& frameName, bool lockBackForwardList);
@@ -79,6 +83,12 @@
     return static_cast<HTMLFrameOwnerElement*>(node);
 }
 
+inline const HTMLFrameOwnerElement* toHTMLFrameOwnerElement(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isFrameOwnerElement());
+    return static_cast<const HTMLFrameOwnerElement*>(node);
+}
+
 class SubframeLoadingDisabler {
 public:
     explicit SubframeLoadingDisabler(Node* root)
diff --git a/Source/core/html/HTMLFrameSetElement.cpp b/Source/core/html/HTMLFrameSetElement.cpp
index c434346..e805553 100644
--- a/Source/core/html/HTMLFrameSetElement.cpp
+++ b/Source/core/html/HTMLFrameSetElement.cpp
@@ -31,7 +31,6 @@
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/MouseEvent.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLDimension.h"
 #include "core/html/HTMLFrameElement.h"
@@ -43,7 +42,7 @@
 
 using namespace HTMLNames;
 
-HTMLFrameSetElement::HTMLFrameSetElement(const QualifiedName& tagName, Document* document)
+HTMLFrameSetElement::HTMLFrameSetElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_border(6)
     , m_borderSet(false)
@@ -57,7 +56,7 @@
     setHasCustomStyleCallbacks();
 }
 
-PassRefPtr<HTMLFrameSetElement> HTMLFrameSetElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLFrameSetElement> HTMLFrameSetElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLFrameSetElement(tagName, document));
 }
@@ -112,46 +111,46 @@
     } else if (name == bordercolorAttr)
         m_borderColorSet = !value.isEmpty();
     else if (name == onloadAttr)
-        document()->setWindowAttributeEventListener(eventNames().loadEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().loadEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onbeforeunloadAttr)
-        document()->setWindowAttributeEventListener(eventNames().beforeunloadEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().beforeunloadEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onunloadAttr)
-        document()->setWindowAttributeEventListener(eventNames().unloadEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().unloadEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onblurAttr)
-        document()->setWindowAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onfocusAttr)
-        document()->setWindowAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onfocusinAttr)
-        document()->setWindowAttributeEventListener(eventNames().focusinEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().focusinEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onfocusoutAttr)
-        document()->setWindowAttributeEventListener(eventNames().focusoutEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().focusoutEvent, createAttributeEventListener(document().frame(), name, value));
 #if ENABLE(ORIENTATION_EVENTS)
     else if (name == onorientationchangeAttr)
-        document()->setWindowAttributeEventListener(eventNames().orientationchangeEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().orientationchangeEvent, createAttributeEventListener(document().frame(), name, value));
 #endif
     else if (name == onhashchangeAttr)
-        document()->setWindowAttributeEventListener(eventNames().hashchangeEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().hashchangeEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onresizeAttr)
-        document()->setWindowAttributeEventListener(eventNames().resizeEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().resizeEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onscrollAttr)
-        document()->setWindowAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onstorageAttr)
-        document()->setWindowAttributeEventListener(eventNames().storageEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().storageEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == ononlineAttr)
-        document()->setWindowAttributeEventListener(eventNames().onlineEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().onlineEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onofflineAttr)
-        document()->setWindowAttributeEventListener(eventNames().offlineEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().offlineEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == onpopstateAttr)
-        document()->setWindowAttributeEventListener(eventNames().popstateEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().popstateEvent, createAttributeEventListener(document().frame(), name, value));
     else
         HTMLElement::parseAttribute(name, value);
 }
 
-bool HTMLFrameSetElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLFrameSetElement::rendererIsNeeded(const RenderStyle& style)
 {
     // For compatibility, frames render even when display: none is set.
     // However, we delay creating a renderer until stylesheets have loaded.
-    return context.style()->isStyleAvailable();
+    return style.isStyleAvailable();
 }
 
 RenderObject* HTMLFrameSetElement::createRenderer(RenderStyle *style)
@@ -199,14 +198,14 @@
 
 Node::InsertionNotificationRequest HTMLFrameSetElement::insertedInto(ContainerNode* insertionPoint)
 {
-    if (insertionPoint->inDocument() && document()->frame()) {
+    if (insertionPoint->inDocument() && document().frame()) {
         // A document using <frameset> likely won't literally have a body, but as far as the client is concerned, the frameset is effectively the body.
-        document()->frame()->loader()->client()->dispatchWillInsertBody();
+        document().frame()->loader()->client()->dispatchWillInsertBody();
     }
     return HTMLElement::insertedInto(insertionPoint);
 }
 
-void HTMLFrameSetElement::willRecalcStyle(StyleChange)
+void HTMLFrameSetElement::willRecalcStyle(StyleRecalcChange)
 {
     if (needsStyleRecalc() && renderer()) {
         renderer()->setNeedsLayout();
@@ -219,7 +218,7 @@
     Node* frameNode = children()->namedItem(name);
     if (!frameNode || !frameNode->hasTagName(HTMLNames::frameTag))
         return 0;
-    Document* document = static_cast<HTMLFrameElement*>(frameNode)->contentDocument();
+    Document* document = toHTMLFrameElement(frameNode)->contentDocument();
     if (!document || !document->frame())
         return 0;
     return document->domWindow();
diff --git a/Source/core/html/HTMLFrameSetElement.h b/Source/core/html/HTMLFrameSetElement.h
index 3aa3745..9c3b4f7 100644
--- a/Source/core/html/HTMLFrameSetElement.h
+++ b/Source/core/html/HTMLFrameSetElement.h
@@ -31,7 +31,7 @@
 
 class HTMLFrameSetElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLFrameSetElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLFrameSetElement> create(const QualifiedName&, Document&);
 
     bool hasFrameBorder() const { return m_frameborder; }
     bool noResize() const { return m_noresize; }
@@ -67,20 +67,20 @@
 #endif
 
 private:
-    HTMLFrameSetElement(const QualifiedName&, Document*);
+    HTMLFrameSetElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
     virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual void defaultEventHandler(Event*);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    virtual void willRecalcStyle(StyleChange) OVERRIDE;
+    virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
 
     Vector<HTMLDimension> m_rowLengths;
     Vector<HTMLDimension> m_colLengths;
diff --git a/Source/core/html/HTMLHRElement.cpp b/Source/core/html/HTMLHRElement.cpp
index 0c3e9f3..a71a4d3 100644
--- a/Source/core/html/HTMLHRElement.cpp
+++ b/Source/core/html/HTMLHRElement.cpp
@@ -33,19 +33,19 @@
 
 using namespace HTMLNames;
 
-HTMLHRElement::HTMLHRElement(const QualifiedName& tagName, Document* document)
+HTMLHRElement::HTMLHRElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(hrTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLHRElement> HTMLHRElement::create(Document* document)
+PassRefPtr<HTMLHRElement> HTMLHRElement::create(Document& document)
 {
     return adoptRef(new HTMLHRElement(hrTag, document));
 }
 
-PassRefPtr<HTMLHRElement> HTMLHRElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLHRElement> HTMLHRElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLHRElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLHRElement.h b/Source/core/html/HTMLHRElement.h
index b4498e7..7fc185d 100644
--- a/Source/core/html/HTMLHRElement.h
+++ b/Source/core/html/HTMLHRElement.h
@@ -29,13 +29,13 @@
 
 class HTMLHRElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLHRElement> create(Document*);
-    static PassRefPtr<HTMLHRElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLHRElement> create(Document&);
+    static PassRefPtr<HTMLHRElement> create(const QualifiedName&, Document&);
 
     virtual bool canContainRangeEndPoint() const { return hasChildNodes(); }
 
 private:
-    HTMLHRElement(const QualifiedName&, Document*);
+    HTMLHRElement(const QualifiedName&, Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLHeadElement.cpp b/Source/core/html/HTMLHeadElement.cpp
index feda0cc..a0afa30 100644
--- a/Source/core/html/HTMLHeadElement.cpp
+++ b/Source/core/html/HTMLHeadElement.cpp
@@ -30,19 +30,19 @@
 
 using namespace HTMLNames;
 
-HTMLHeadElement::HTMLHeadElement(const QualifiedName& tagName, Document* document)
+HTMLHeadElement::HTMLHeadElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(headTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLHeadElement> HTMLHeadElement::create(Document* document)
+PassRefPtr<HTMLHeadElement> HTMLHeadElement::create(Document& document)
 {
     return adoptRef(new HTMLHeadElement(headTag, document));
 }
 
-PassRefPtr<HTMLHeadElement> HTMLHeadElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLHeadElement> HTMLHeadElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLHeadElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLHeadElement.h b/Source/core/html/HTMLHeadElement.h
index 54c7fe8..8a5040c 100644
--- a/Source/core/html/HTMLHeadElement.h
+++ b/Source/core/html/HTMLHeadElement.h
@@ -30,13 +30,19 @@
 
 class HTMLHeadElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLHeadElement> create(Document*);
-    static PassRefPtr<HTMLHeadElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLHeadElement> create(Document&);
+    static PassRefPtr<HTMLHeadElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLHeadElement(const QualifiedName&, Document*);
+    HTMLHeadElement(const QualifiedName&, Document&);
 };
 
+inline HTMLHeadElement* toHTMLHeadElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::headTag));
+    return static_cast<HTMLHeadElement*>(node);
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/html/HTMLHeadingElement.cpp b/Source/core/html/HTMLHeadingElement.cpp
index 36f8a66..7e9c986 100644
--- a/Source/core/html/HTMLHeadingElement.cpp
+++ b/Source/core/html/HTMLHeadingElement.cpp
@@ -25,13 +25,13 @@
 
 namespace WebCore {
 
-inline HTMLHeadingElement::HTMLHeadingElement(const QualifiedName& tagName, Document* document)
+inline HTMLHeadingElement::HTMLHeadingElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLHeadingElement> HTMLHeadingElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLHeadingElement> HTMLHeadingElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLHeadingElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLHeadingElement.h b/Source/core/html/HTMLHeadingElement.h
index c04bcfe..e99bac5 100644
--- a/Source/core/html/HTMLHeadingElement.h
+++ b/Source/core/html/HTMLHeadingElement.h
@@ -29,10 +29,10 @@
 
 class HTMLHeadingElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLHeadingElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLHeadingElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLHeadingElement(const QualifiedName&, Document*);
+    HTMLHeadingElement(const QualifiedName&, Document&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLHtmlElement.cpp b/Source/core/html/HTMLHtmlElement.cpp
index 704dde1..87d00e9 100644
--- a/Source/core/html/HTMLHtmlElement.cpp
+++ b/Source/core/html/HTMLHtmlElement.cpp
@@ -36,19 +36,19 @@
 
 using namespace HTMLNames;
 
-HTMLHtmlElement::HTMLHtmlElement(const QualifiedName& tagName, Document* document)
+HTMLHtmlElement::HTMLHtmlElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(htmlTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLHtmlElement> HTMLHtmlElement::create(Document* document)
+PassRefPtr<HTMLHtmlElement> HTMLHtmlElement::create(Document& document)
 {
     return adoptRef(new HTMLHtmlElement(htmlTag, document));
 }
 
-PassRefPtr<HTMLHtmlElement> HTMLHtmlElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLHtmlElement> HTMLHtmlElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLHtmlElement(tagName, document));
 }
@@ -61,13 +61,13 @@
 void HTMLHtmlElement::insertedByParser()
 {
     // When parsing a fragment, its dummy document has a null parser.
-    if (!document()->parser() || !document()->parser()->documentWasLoadedAsPartOfNavigation())
+    if (!document().parser() || !document().parser()->documentWasLoadedAsPartOfNavigation())
         return;
 
-    if (!document()->frame())
+    if (!document().frame())
         return;
 
-    DocumentLoader* documentLoader = document()->frame()->loader()->documentLoader();
+    DocumentLoader* documentLoader = document().frame()->loader()->documentLoader();
     if (!documentLoader)
         return;
 
@@ -75,7 +75,7 @@
     if (manifest.isEmpty())
         documentLoader->applicationCacheHost()->selectCacheWithoutManifest();
     else
-        documentLoader->applicationCacheHost()->selectCacheWithManifest(document()->completeURL(manifest));
+        documentLoader->applicationCacheHost()->selectCacheWithManifest(document().completeURL(manifest));
 }
 
 }
diff --git a/Source/core/html/HTMLHtmlElement.h b/Source/core/html/HTMLHtmlElement.h
index 3dad999..e66f061 100644
--- a/Source/core/html/HTMLHtmlElement.h
+++ b/Source/core/html/HTMLHtmlElement.h
@@ -30,13 +30,13 @@
 
 class HTMLHtmlElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLHtmlElement> create(Document*);
-    static PassRefPtr<HTMLHtmlElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLHtmlElement> create(Document&);
+    static PassRefPtr<HTMLHtmlElement> create(const QualifiedName&, Document&);
 
     void insertedByParser();
 
 private:
-    HTMLHtmlElement(const QualifiedName&, Document*);
+    HTMLHtmlElement(const QualifiedName&, Document&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 };
diff --git a/Source/core/html/HTMLIFrameElement.cpp b/Source/core/html/HTMLIFrameElement.cpp
index 1fac054..0a15bae 100644
--- a/Source/core/html/HTMLIFrameElement.cpp
+++ b/Source/core/html/HTMLIFrameElement.cpp
@@ -27,7 +27,6 @@
 
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/html/HTMLDocument.h"
 #include "core/rendering/RenderIFrame.h"
 
@@ -35,7 +34,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLIFrameElement::HTMLIFrameElement(const QualifiedName& tagName, Document* document)
+inline HTMLIFrameElement::HTMLIFrameElement(const QualifiedName& tagName, Document& document)
     : HTMLFrameElementBase(tagName, document)
     , m_didLoadNonEmptyDocument(false)
 {
@@ -44,7 +43,7 @@
     setHasCustomStyleCallbacks();
 }
 
-PassRefPtr<HTMLIFrameElement> HTMLIFrameElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLIFrameElement> HTMLIFrameElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLIFrameElement(tagName, document));
 }
@@ -78,17 +77,17 @@
 void HTMLIFrameElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (name == nameAttr) {
-        if (inDocument() && document()->isHTMLDocument() && !isInShadowTree()) {
-            HTMLDocument* document = toHTMLDocument(this->document());
-            document->removeExtraNamedItem(m_name);
-            document->addExtraNamedItem(value);
+        if (inDocument() && document().isHTMLDocument() && !isInShadowTree()) {
+            HTMLDocument& document = toHTMLDocument(this->document());
+            document.removeExtraNamedItem(m_name);
+            document.addExtraNamedItem(value);
         }
         m_name = value;
     } else if (name == sandboxAttr) {
         String invalidTokens;
         setSandboxFlags(value.isNull() ? SandboxNone : SecurityContext::parseSandboxPolicy(value, invalidTokens));
         if (!invalidTokens.isNull())
-            document()->addConsoleMessage(OtherMessageSource, ErrorMessageLevel, "Error while parsing the 'sandbox' attribute: " + invalidTokens);
+            document().addConsoleMessage(OtherMessageSource, ErrorMessageLevel, "Error while parsing the 'sandbox' attribute: " + invalidTokens);
     } else if (name == seamlessAttr) {
         // If we're adding or removing the seamless attribute, we need to force the content document to recalculate its StyleResolver.
         if (contentDocument())
@@ -97,9 +96,9 @@
         HTMLFrameElementBase::parseAttribute(name, value);
 }
 
-bool HTMLIFrameElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLIFrameElement::rendererIsNeeded(const RenderStyle& style)
 {
-    return isURLAllowed() && context.style()->display() != NONE;
+    return isURLAllowed() && HTMLElement::rendererIsNeeded(style);
 }
 
 RenderObject* HTMLIFrameElement::createRenderer(RenderStyle*)
@@ -110,16 +109,16 @@
 Node::InsertionNotificationRequest HTMLIFrameElement::insertedInto(ContainerNode* insertionPoint)
 {
     InsertionNotificationRequest result = HTMLFrameElementBase::insertedInto(insertionPoint);
-    if (insertionPoint->inDocument() && document()->isHTMLDocument() && !insertionPoint->isInShadowTree())
-        toHTMLDocument(document())->addExtraNamedItem(m_name);
+    if (insertionPoint->inDocument() && document().isHTMLDocument() && !insertionPoint->isInShadowTree())
+        toHTMLDocument(document()).addExtraNamedItem(m_name);
     return result;
 }
 
 void HTMLIFrameElement::removedFrom(ContainerNode* insertionPoint)
 {
     HTMLFrameElementBase::removedFrom(insertionPoint);
-    if (insertionPoint->inDocument() && document()->isHTMLDocument() && !insertionPoint->isInShadowTree())
-        toHTMLDocument(document())->removeExtraNamedItem(m_name);
+    if (insertionPoint->inDocument() && document().isHTMLDocument() && !insertionPoint->isInShadowTree())
+        toHTMLDocument(document()).removeExtraNamedItem(m_name);
 }
 
 bool HTMLIFrameElement::shouldDisplaySeamlessly() const
@@ -127,7 +126,7 @@
     return contentDocument() && contentDocument()->shouldDisplaySeamlesslyWithParent();
 }
 
-void HTMLIFrameElement::didRecalcStyle(StyleChange styleChange)
+void HTMLIFrameElement::didRecalcStyle(StyleRecalcChange styleChange)
 {
     if (!shouldDisplaySeamlessly())
         return;
diff --git a/Source/core/html/HTMLIFrameElement.h b/Source/core/html/HTMLIFrameElement.h
index 9aa74ae..d7e9879 100644
--- a/Source/core/html/HTMLIFrameElement.h
+++ b/Source/core/html/HTMLIFrameElement.h
@@ -30,12 +30,12 @@
 
 class HTMLIFrameElement FINAL : public HTMLFrameElementBase {
 public:
-    static PassRefPtr<HTMLIFrameElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLIFrameElement> create(const QualifiedName&, Document&);
 
     bool shouldDisplaySeamlessly() const;
 
 private:
-    HTMLIFrameElement(const QualifiedName&, Document*);
+    HTMLIFrameElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -44,10 +44,10 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
     virtual RenderObject* createRenderer(RenderStyle*);
 
-    virtual void didRecalcStyle(StyleChange) OVERRIDE;
+    virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE;
 
     virtual bool loadedNonEmptyDocument() const OVERRIDE { return m_didLoadNonEmptyDocument; }
     virtual void didLoadNonEmptyDocument() OVERRIDE { m_didLoadNonEmptyDocument = true; }
diff --git a/Source/core/html/HTMLIFrameElement.idl b/Source/core/html/HTMLIFrameElement.idl
index bc93aa3..d47b1b7 100644
--- a/Source/core/html/HTMLIFrameElement.idl
+++ b/Source/core/html/HTMLIFrameElement.idl
@@ -27,7 +27,7 @@
     [Reflect] attribute DOMString marginWidth;
     [Reflect] attribute DOMString name;
     [Reflect] attribute DOMString sandbox;
-    [Reflect, EnabledAtRuntime=seamlessIFrames] attribute boolean seamless;
+    [Reflect, EnabledAtRuntime=SeamlessIFrames] attribute boolean seamless;
     [Reflect] attribute DOMString scrolling;
     [Reflect, URL] attribute DOMString src;
     [Reflect] attribute DOMString srcdoc;
diff --git a/Source/core/html/HTMLImageElement.cpp b/Source/core/html/HTMLImageElement.cpp
index 4b96259..30c8668 100644
--- a/Source/core/html/HTMLImageElement.cpp
+++ b/Source/core/html/HTMLImageElement.cpp
@@ -40,7 +40,7 @@
 
 using namespace HTMLNames;
 
-HTMLImageElement::HTMLImageElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+HTMLImageElement::HTMLImageElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
     : HTMLElement(tagName, document)
     , m_imageLoader(this)
     , m_form(form)
@@ -52,12 +52,12 @@
         form->registerImgElement(this);
 }
 
-PassRefPtr<HTMLImageElement> HTMLImageElement::create(Document* document)
+PassRefPtr<HTMLImageElement> HTMLImageElement::create(Document& document)
 {
     return adoptRef(new HTMLImageElement(imgTag, document));
 }
 
-PassRefPtr<HTMLImageElement> HTMLImageElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+PassRefPtr<HTMLImageElement> HTMLImageElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
 {
     return adoptRef(new HTMLImageElement(tagName, document, form));
 }
@@ -68,7 +68,7 @@
         m_form->removeImgElement(this);
 }
 
-PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document* document, const int* optionalWidth, const int* optionalHeight)
+PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document& document, const int* optionalWidth, const int* optionalHeight)
 {
     RefPtr<HTMLImageElement> image = adoptRef(new HTMLImageElement(imgTag, document));
     if (optionalWidth)
@@ -222,9 +222,9 @@
     }
 
     if (ignorePendingStylesheets)
-        document()->updateLayoutIgnorePendingStylesheets();
+        document().updateLayoutIgnorePendingStylesheets();
     else
-        document()->updateLayout();
+        document().updateLayout();
 
     RenderBox* box = renderBox();
     return box ? adjustForAbsoluteZoom(box->contentBoxRect().pixelSnappedWidth(), box) : 0;
@@ -245,9 +245,9 @@
     }
 
     if (ignorePendingStylesheets)
-        document()->updateLayoutIgnorePendingStylesheets();
+        document().updateLayoutIgnorePendingStylesheets();
     else
-        document()->updateLayout();
+        document().updateLayout();
 
     RenderBox* box = renderBox();
     return box ? adjustForAbsoluteZoom(box->contentBoxRect().pixelSnappedHeight(), box) : 0;
@@ -296,7 +296,7 @@
 
 KURL HTMLImageElement::src() const
 {
-    return document()->completeURL(getAttribute(srcAttr));
+    return document().completeURL(getAttribute(srcAttr));
 }
 
 void HTMLImageElement::setSrc(const String& value)
@@ -342,7 +342,7 @@
 
     addSubresourceURL(urls, src());
     // FIXME: What about when the usemap attribute begins with "#"?
-    addSubresourceURL(urls, document()->completeURL(getAttribute(usemapAttr)));
+    addSubresourceURL(urls, document().completeURL(getAttribute(usemapAttr)));
 }
 
 void HTMLImageElement::didMoveToNewDocument(Document* oldDocument)
@@ -362,7 +362,7 @@
     if (usemap.string()[0] == '#')
         return false;
 
-    return document()->completeURL(stripLeadingAndTrailingHTMLSpaces(usemap)).isEmpty();
+    return document().completeURL(stripLeadingAndTrailingHTMLSpaces(usemap)).isEmpty();
 }
 
 Image* HTMLImageElement::imageContents()
diff --git a/Source/core/html/HTMLImageElement.h b/Source/core/html/HTMLImageElement.h
index 590b0ec..f8acd66 100644
--- a/Source/core/html/HTMLImageElement.h
+++ b/Source/core/html/HTMLImageElement.h
@@ -35,9 +35,9 @@
 class HTMLImageElement FINAL : public HTMLElement {
     friend class HTMLFormElement;
 public:
-    static PassRefPtr<HTMLImageElement> create(Document*);
-    static PassRefPtr<HTMLImageElement> create(const QualifiedName&, Document*, HTMLFormElement*);
-    static PassRefPtr<HTMLImageElement> createForJSConstructor(Document*, const int* optionalWidth, const int* optionalHeight);
+    static PassRefPtr<HTMLImageElement> create(Document&);
+    static PassRefPtr<HTMLImageElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+    static PassRefPtr<HTMLImageElement> createForJSConstructor(Document&, const int* optionalWidth, const int* optionalHeight);
 
     virtual ~HTMLImageElement();
 
@@ -80,7 +80,7 @@
     void removeClient(ImageLoaderClient* client) { m_imageLoader.removeClient(client); }
 
 protected:
-    HTMLImageElement(const QualifiedName&, Document*, HTMLFormElement* = 0);
+    HTMLImageElement(const QualifiedName&, Document&, HTMLFormElement* = 0);
 
     virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
 
diff --git a/Source/core/html/HTMLImportLoader.cpp b/Source/core/html/HTMLImportLoader.cpp
index 7cfbd29..b4a0942 100644
--- a/Source/core/html/HTMLImportLoader.cpp
+++ b/Source/core/html/HTMLImportLoader.cpp
@@ -31,6 +31,7 @@
 #include "config.h"
 #include "core/html/HTMLImportLoader.h"
 
+#include "core/dom/CustomElementRegistrationContext.h"
 #include "core/dom/Document.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLDocument.h"
@@ -115,7 +116,9 @@
     if (!m_parent->document()->fetcher()->canAccess(m_resource.get()))
         return StateError;
 
-    m_importedDocument = HTMLDocument::create(DocumentInit(response.url(), 0, this).withRegistrationContext(root()->document()->registrationContext()));
+    DocumentInit init = DocumentInit(response.url(), 0, root()->document()->contextDocument(), this)
+        .withRegistrationContext(root()->document()->registrationContext());
+    m_importedDocument = HTMLDocument::create(init);
     m_importedDocument->initContentSecurityPolicy(ContentSecurityPolicyResponseHeaders(response));
     m_writer = DocumentWriter::create(m_importedDocument.get(), response.mimeType(), response.textEncodingName());
 
diff --git a/Source/core/html/HTMLInputElement.cpp b/Source/core/html/HTMLInputElement.cpp
index b22ecd8..d5766b5 100644
--- a/Source/core/html/HTMLInputElement.cpp
+++ b/Source/core/html/HTMLInputElement.cpp
@@ -94,11 +94,11 @@
 // large. However, due to https://bugs.webkit.org/show_bug.cgi?id=14536 things
 // get rather sluggish when a text field has a larger number of characters than
 // this, even when just clicking in the text field.
-const int HTMLInputElement::maximumLength = 524288;
+const unsigned HTMLInputElement::maximumLength = 524288;
 const int defaultSize = 20;
 const int maxSavedResults = 256;
 
-HTMLInputElement::HTMLInputElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form, bool createdByParser)
+HTMLInputElement::HTMLInputElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
     : HTMLTextFormControlElement(tagName, document, form)
     , m_size(defaultSize)
     , m_maxLength(maximumLength)
@@ -127,7 +127,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLInputElement> HTMLInputElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLInputElement> HTMLInputElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
 {
     RefPtr<HTMLInputElement> inputElement = adoptRef(new HTMLInputElement(tagName, document, form, createdByParser));
     inputElement->ensureUserAgentShadowRoot();
@@ -146,6 +146,13 @@
     m_inputType->createShadowSubtree();
 }
 
+void HTMLInputElement::didAddShadowRoot(ShadowRoot& root)
+{
+    if (!root.isOldestAuthorShadowRoot())
+        return;
+    m_inputTypeView = InputTypeView::create(this);
+}
+
 HTMLInputElement::~HTMLInputElement()
 {
     // Need to remove form association while this is still an HTMLInputElement
@@ -154,9 +161,9 @@
     // setForm(0) may register this to a document-level radio button group.
     // We should unregister it to avoid accessing a deleted object.
     if (isRadioButton())
-        document()->formController()->checkedRadioButtons().removeButton(this);
+        document().formController()->checkedRadioButtons().removeButton(this);
     if (m_hasTouchEventHandler)
-        document()->didRemoveEventTargetNode(this);
+        document().didRemoveEventTargetNode(this);
 }
 
 const AtomicString& HTMLInputElement::name() const
@@ -352,8 +359,8 @@
             select();
         else
             restoreCachedSelection();
-        if (document()->frame())
-            document()->frame()->selection()->revealSelection();
+        if (document().frame())
+            document().frame()->selection().revealSelection();
     } else
         HTMLTextFormControlElement::updateFocusAppearance(restorePreviousSelection);
 }
@@ -363,7 +370,7 @@
     if (!isTextField())
         return;
 
-    if (Frame* frame = document()->frame())
+    if (Frame* frame = document().frame())
         frame->editor().textAreaOrTextFieldDidBeginEditing(this);
 }
 
@@ -372,7 +379,7 @@
     if (!isTextField())
         return;
 
-    if (Frame* frame = document()->frame())
+    if (Frame* frame = document().frame())
         frame->editor().textFieldDidEndEditing(this);
 }
 
@@ -407,19 +414,20 @@
 
 void HTMLInputElement::updateType()
 {
-    RefPtr<InputType> newType = InputType::create(this, fastGetAttribute(typeAttr));
+    const AtomicString& newTypeName = InputType::normalizeTypeName(fastGetAttribute(typeAttr));
     bool hadType = m_hasType;
     m_hasType = true;
-    if (m_inputType->formControlType() == newType->formControlType())
+    if (m_inputType->formControlType() == newTypeName)
         return;
 
-    if (hadType && !newType->canChangeFromAnotherType()) {
+    if (hadType && !InputType::canChangeFromAnotherType(newTypeName)) {
         // Set the attribute back to the old value.
         // Useful in case we were called from inside parseAttribute.
         setAttribute(typeAttr, type());
         return;
     }
 
+    RefPtr<InputType> newType = InputType::create(this, newTypeName);
     removeFromRadioButtonGroup();
 
     bool didStoreValue = m_inputType->storesValueSeparateFromAttribute();
@@ -432,15 +440,18 @@
         detach();
 
     m_inputType = newType.release();
-    m_inputTypeView = m_inputType;
+    if (hasAuthorShadowRoot())
+        m_inputTypeView = InputTypeView::create(this);
+    else
+        m_inputTypeView = m_inputType;
     m_inputType->createShadowSubtree();
 
     bool hasTouchEventHandler = m_inputTypeView->hasTouchEventHandler();
     if (hasTouchEventHandler != m_hasTouchEventHandler) {
         if (hasTouchEventHandler)
-            document()->didAddTouchEventHandler(this);
+            document().didAddTouchEventHandler(this);
         else
-            document()->didRemoveTouchEventHandler(this);
+            document().didRemoveTouchEventHandler(this);
         m_hasTouchEventHandler = hasTouchEventHandler;
     }
 
@@ -475,8 +486,8 @@
 
     if (wasAttached) {
         lazyAttach();
-        if (document()->focusedElement() == this)
-            document()->updateFocusAppearanceSoon(true /* restore selection */);
+        if (document().focusedElement() == this)
+            document().updateFocusAppearanceSoon(true /* restore selection */);
     }
 
     setChangedSinceLastFormControlChangeEvent(false);
@@ -698,32 +709,32 @@
         if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0))
             lazyReattachIfAttached();
         setNeedsStyleRecalc();
-        UseCounter::count(document(), UseCounter::ResultsAttribute);
+        UseCounter::count(&document(), UseCounter::ResultsAttribute);
     } else if (name == incrementalAttr) {
         setNeedsStyleRecalc();
-        UseCounter::count(document(), UseCounter::IncrementalAttribute);
+        UseCounter::count(&document(), UseCounter::IncrementalAttribute);
     } else if (name == minAttr) {
         m_inputTypeView->minOrMaxAttributeChanged();
         m_inputType->sanitizeValueInResponseToMinOrMaxAttributeChange();
         setNeedsValidityCheck();
-        UseCounter::count(document(), UseCounter::MinAttribute);
+        UseCounter::count(&document(), UseCounter::MinAttribute);
     } else if (name == maxAttr) {
         m_inputTypeView->minOrMaxAttributeChanged();
         setNeedsValidityCheck();
-        UseCounter::count(document(), UseCounter::MaxAttribute);
+        UseCounter::count(&document(), UseCounter::MaxAttribute);
     } else if (name == multipleAttr) {
         m_inputTypeView->multipleAttributeChanged();
         setNeedsValidityCheck();
     } else if (name == stepAttr) {
         m_inputTypeView->stepAttributeChanged();
         setNeedsValidityCheck();
-        UseCounter::count(document(), UseCounter::StepAttribute);
+        UseCounter::count(&document(), UseCounter::StepAttribute);
     } else if (name == patternAttr) {
         setNeedsValidityCheck();
-        UseCounter::count(document(), UseCounter::PatternAttribute);
+        UseCounter::count(&document(), UseCounter::PatternAttribute);
     } else if (name == precisionAttr) {
         setNeedsValidityCheck();
-        UseCounter::count(document(), UseCounter::PrecisionAttribute);
+        UseCounter::count(&document(), UseCounter::PrecisionAttribute);
     } else if (name == disabledAttr) {
         HTMLTextFormControlElement::parseAttribute(name, value);
         m_inputTypeView->disabledAttributeChanged();
@@ -736,7 +747,7 @@
             resetListAttributeTargetObserver();
             listAttributeTargetChanged();
         }
-        UseCounter::count(document(), UseCounter::ListAttribute);
+        UseCounter::count(&document(), UseCounter::ListAttribute);
     }
 #if ENABLE(INPUT_SPEECH)
     else if (name == webkitspeechAttr) {
@@ -750,13 +761,13 @@
             m_inputType->createShadowSubtree();
             setFormControlValueMatchesRenderer(false);
         }
-        UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute);
+        UseCounter::count(&document(), UseCounter::PrefixedSpeechAttribute);
     } else if (name == onwebkitspeechchangeAttr)
         setAttributeEventListener(eventNames().webkitspeechchangeEvent, createAttributeEventListener(this, name, value));
 #endif
     else if (name == webkitdirectoryAttr) {
         HTMLTextFormControlElement::parseAttribute(name, value);
-        UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute);
+        UseCounter::count(&document(), UseCounter::PrefixedDirectoryAttribute);
     }
     else
         HTMLTextFormControlElement::parseAttribute(name, value);
@@ -775,9 +786,9 @@
     }
 }
 
-bool HTMLInputElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLInputElement::rendererIsNeeded(const RenderStyle& style)
 {
-    return m_inputType->rendererIsNeeded() && HTMLTextFormControlElement::rendererIsNeeded(context);
+    return m_inputType->rendererIsNeeded() && HTMLTextFormControlElement::rendererIsNeeded(style);
 }
 
 RenderObject* HTMLInputElement::createRenderer(RenderStyle* style)
@@ -787,8 +798,6 @@
 
 void HTMLInputElement::attach(const AttachContext& context)
 {
-    PostAttachCallbackDisabler disabler(this);
-
     if (!m_hasType)
         updateType();
 
@@ -797,8 +806,8 @@
     m_inputTypeView->attach();
     m_inputType->countUsage();
 
-    if (document()->focusedElement() == this)
-        document()->updateFocusAppearanceSoon(true /* restore selection */);
+    if (document().focusedElement() == this)
+        document().updateFocusAppearanceSoon(true /* restore selection */);
 }
 
 void HTMLInputElement::detach(const AttachContext& context)
@@ -886,7 +895,7 @@
     // RenderTextView), but it's not possible to do it at the moment
     // because of the way the code is structured.
     if (renderer()) {
-        if (AXObjectCache* cache = renderer()->document()->existingAXObjectCache())
+        if (AXObjectCache* cache = renderer()->document().existingAXObjectCache())
             cache->checkedStateChanged(this);
     }
 
@@ -1028,8 +1037,12 @@
     setLastChangeWasNotUserEdit();
     setFormControlValueMatchesRenderer(false);
     m_suggestedValue = String(); // Prevent TextFieldInputType::setValue from using the suggested value.
+
     m_inputType->setValue(sanitizedValue, valueChanged, eventBehavior);
 
+    if (valueChanged && eventBehavior == DispatchNoEvent)
+        setTextAsOfLastFormControlChangeEvent(sanitizedValue);
+
     if (!valueChanged)
         return;
 
@@ -1321,7 +1334,7 @@
 
 KURL HTMLInputElement::src() const
 {
-    return document()->completeURL(fastGetAttribute(srcAttr));
+    return document().completeURL(fastGetAttribute(srcAttr));
 }
 
 void HTMLInputElement::setAutofilled(bool autofilled)
@@ -1467,7 +1480,7 @@
     }
 
     if (m_hasTouchEventHandler)
-        document()->didAddTouchEventHandler(this);
+        document().didAddTouchEventHandler(this);
 
     HTMLTextFormControlElement::didMoveToNewDocument(oldDocument);
 }
@@ -1512,13 +1525,13 @@
     if (!m_inputType->shouldRespectListAttribute())
         return 0;
 
-    Element* element = treeScope()->getElementById(fastGetAttribute(listAttr));
+    Element* element = treeScope().getElementById(fastGetAttribute(listAttr));
     if (!element)
         return 0;
     if (!element->hasTagName(datalistTag))
         return 0;
 
-    return static_cast<HTMLDataListElement*>(element);
+    return toHTMLDataListElement(element);
 }
 
 void HTMLInputElement::resetListAttributeTargetObserver()
@@ -1723,9 +1736,9 @@
     // supposed to be used as a boolean.
     bool hasDeprecatedUsage = !fastGetAttribute(captureAttr).isNull();
     if (hasDeprecatedUsage)
-        UseCounter::countDeprecation(document(), UseCounter::CaptureAttributeAsEnum);
+        UseCounter::countDeprecation(&document(), UseCounter::CaptureAttributeAsEnum);
     else
-        UseCounter::count(document(), UseCounter::CaptureAttributeAsEnum);
+        UseCounter::count(&document(), UseCounter::CaptureAttributeAsEnum);
 
     return true;
 }
@@ -1753,7 +1766,7 @@
     if (HTMLFormElement* formElement = form())
         return &formElement->checkedRadioButtons();
     if (inDocument())
-        return &document()->formController()->checkedRadioButtons();
+        return &document().formController()->checkedRadioButtons();
     return 0;
 }
 
@@ -1795,7 +1808,7 @@
 }
 
 ListAttributeTargetObserver::ListAttributeTargetObserver(const AtomicString& id, HTMLInputElement* element)
-    : IdTargetObserver(element->treeScope()->idTargetObserverRegistry(), id)
+    : IdTargetObserver(element->treeScope().idTargetObserverRegistry(), id)
     , m_element(element)
 {
 }
@@ -1827,7 +1840,7 @@
 
 bool HTMLInputElement::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
 {
-    if (!document()->view())
+    if (!document().view())
         return false;
 
     parameters.type = type();
@@ -1850,7 +1863,7 @@
         parameters.stepBase = 0;
     }
 
-    parameters.anchorRectInRootView = document()->view()->contentsToRootView(pixelSnappedBoundingBox());
+    parameters.anchorRectInRootView = document().view()->contentsToRootView(pixelSnappedBoundingBox());
     parameters.currentValue = value();
     parameters.isAnchorElementRTL = computedStyle()->direction() == RTL;
     if (RuntimeEnabledFeatures::dataListElementEnabled()) {
diff --git a/Source/core/html/HTMLInputElement.h b/Source/core/html/HTMLInputElement.h
index 67fde5f..684508f 100644
--- a/Source/core/html/HTMLInputElement.h
+++ b/Source/core/html/HTMLInputElement.h
@@ -47,7 +47,7 @@
 
 class HTMLInputElement : public HTMLTextFormControlElement {
 public:
-    static PassRefPtr<HTMLInputElement> create(const QualifiedName&, Document*, HTMLFormElement*, bool createdByParser);
+    static PassRefPtr<HTMLInputElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
     virtual ~HTMLInputElement();
 
     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitspeechchange);
@@ -180,7 +180,7 @@
     void setSelectionRangeForBinding(int start, int end, ExceptionState&);
     void setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionState&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
 
@@ -257,7 +257,7 @@
     bool capture() const;
 #endif
 
-    static const int maximumLength;
+    static const unsigned maximumLength;
 
     unsigned height() const;
     unsigned width() const;
@@ -287,7 +287,7 @@
     bool supportsInputModeAttribute() const;
 
 protected:
-    HTMLInputElement(const QualifiedName&, Document*, HTMLFormElement*, bool createdByParser);
+    HTMLInputElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
 
     virtual void defaultEventHandler(Event*);
 
@@ -295,6 +295,7 @@
     enum AutoCompleteSetting { Uninitialized, On, Off };
 
     virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+    virtual void didAddShadowRoot(ShadowRoot&) OVERRIDE;
 
     virtual void willChangeForm() OVERRIDE;
     virtual void didChangeForm() OVERRIDE;
diff --git a/Source/core/html/HTMLInputElement.idl b/Source/core/html/HTMLInputElement.idl
index fd17406..fd6151d 100644
--- a/Source/core/html/HTMLInputElement.idl
+++ b/Source/core/html/HTMLInputElement.idl
@@ -59,7 +59,7 @@
     [TreatNullAs=NullString, SetterRaisesException, CustomElementCallbacks=Enable] attribute DOMString value;
     [SetterRaisesException, CustomElementCallbacks=Enable] attribute Date valueAsDate;
     [SetterRaisesException, CustomElementCallbacks=Enable] attribute double valueAsNumber;
-    [EnabledAtRuntime=inputModeAttribute, Reflect] attribute DOMString inputMode;
+    [EnabledAtRuntime=InputModeAttribute, Reflect] attribute DOMString inputMode;
 
     [RaisesException, CustomElementCallbacks=Enable] void stepUp(optional long n);
     [RaisesException, CustomElementCallbacks=Enable] void stepDown(optional long n);
@@ -91,11 +91,11 @@
 
     // Non-standard attributes
     [Reflect] attribute DOMString align;
-    [Reflect, EnabledAtRuntime=directoryUpload] attribute boolean webkitdirectory;
+    [Reflect, EnabledAtRuntime=DirectoryUpload] attribute boolean webkitdirectory;
     [Reflect] attribute DOMString useMap;
     [Reflect] attribute boolean incremental;
-    [Conditional=INPUT_SPEECH, Reflect, EnabledAtRuntime=speechInput] attribute boolean webkitSpeech;
-    [Conditional=INPUT_SPEECH, Reflect, EnabledAtRuntime=speechInput] attribute boolean webkitGrammar;
+    [Conditional=INPUT_SPEECH, Reflect, EnabledAtRuntime=SpeechInput] attribute boolean webkitSpeech;
+    [Conditional=INPUT_SPEECH, Reflect, EnabledAtRuntime=SpeechInput] attribute boolean webkitGrammar;
     [Conditional=INPUT_SPEECH, NotEnumerable] attribute EventHandler onwebkitspeechchange;
 
     // See http://www.w3.org/TR/html-media-capture/
diff --git a/Source/core/html/HTMLKeygenElement.cpp b/Source/core/html/HTMLKeygenElement.cpp
index 18e1494..61a304b 100644
--- a/Source/core/html/HTMLKeygenElement.cpp
+++ b/Source/core/html/HTMLKeygenElement.cpp
@@ -42,7 +42,7 @@
 
 using namespace HTMLNames;
 
-HTMLKeygenElement::HTMLKeygenElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+HTMLKeygenElement::HTMLKeygenElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
     : HTMLFormControlElementWithState(tagName, document, form)
 {
     ASSERT(hasTagName(keygenTag));
@@ -84,7 +84,7 @@
     const AtomicString& keyType = fastGetAttribute(keytypeAttr);
     if (!keyType.isNull() && !equalIgnoringCase(keyType, "rsa"))
         return false;
-    String value = signedPublicKeyAndChallengeString(shadowSelect()->selectedIndex(), fastGetAttribute(challengeAttr), document()->baseURL());
+    String value = signedPublicKeyAndChallengeString(shadowSelect()->selectedIndex(), fastGetAttribute(challengeAttr), document().baseURL());
     if (value.isNull())
         return false;
     encoding.appendData(name(), value.utf8());
diff --git a/Source/core/html/HTMLKeygenElement.h b/Source/core/html/HTMLKeygenElement.h
index 6b12e19..69965f6 100644
--- a/Source/core/html/HTMLKeygenElement.h
+++ b/Source/core/html/HTMLKeygenElement.h
@@ -32,7 +32,7 @@
 
 class HTMLKeygenElement FINAL : public HTMLFormControlElementWithState {
 public:
-    static PassRefPtr<HTMLKeygenElement> create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+    static PassRefPtr<HTMLKeygenElement> create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
     {
         return adoptRef(new HTMLKeygenElement(tagName, document, form));
     }
@@ -40,7 +40,7 @@
     virtual bool willValidate() const OVERRIDE { return false; }
 
 private:
-    HTMLKeygenElement(const QualifiedName&, Document*, HTMLFormElement*);
+    HTMLKeygenElement(const QualifiedName&, Document&, HTMLFormElement*);
 
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
 
diff --git a/Source/core/html/HTMLLIElement.cpp b/Source/core/html/HTMLLIElement.cpp
index 5e05061..fac3830 100644
--- a/Source/core/html/HTMLLIElement.cpp
+++ b/Source/core/html/HTMLLIElement.cpp
@@ -32,19 +32,19 @@
 
 using namespace HTMLNames;
 
-HTMLLIElement::HTMLLIElement(const QualifiedName& tagName, Document* document)
+HTMLLIElement::HTMLLIElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(liTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLLIElement> HTMLLIElement::create(Document* document)
+PassRefPtr<HTMLLIElement> HTMLLIElement::create(Document& document)
 {
     return adoptRef(new HTMLLIElement(liTag, document));
 }
 
-PassRefPtr<HTMLLIElement> HTMLLIElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLLIElement> HTMLLIElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLLIElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLLIElement.h b/Source/core/html/HTMLLIElement.h
index 32e6c4c..969a938 100644
--- a/Source/core/html/HTMLLIElement.h
+++ b/Source/core/html/HTMLLIElement.h
@@ -29,11 +29,11 @@
 
 class HTMLLIElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLLIElement> create(Document*);
-    static PassRefPtr<HTMLLIElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLLIElement> create(Document&);
+    static PassRefPtr<HTMLLIElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLLIElement(const QualifiedName&, Document*);
+    HTMLLIElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLLabelElement.cpp b/Source/core/html/HTMLLabelElement.cpp
index 1de8acd..f02c4a0 100644
--- a/Source/core/html/HTMLLabelElement.cpp
+++ b/Source/core/html/HTMLLabelElement.cpp
@@ -44,14 +44,14 @@
     return toLabelableElement(element)->supportLabels();
 }
 
-inline HTMLLabelElement::HTMLLabelElement(const QualifiedName& tagName, Document* document)
+inline HTMLLabelElement::HTMLLabelElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(labelTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLLabelElement> HTMLLabelElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLLabelElement> HTMLLabelElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLLabelElement(tagName, document));
 }
@@ -78,7 +78,7 @@
         return 0;
     }
 
-    if (Element* element = treeScope()->getElementById(controlId)) {
+    if (Element* element = treeScope().getElementById(controlId)) {
         if (supportsLabels(element))
             return toLabelableElement(element);
     }
@@ -131,7 +131,7 @@
 
         processingClick = true;
 
-        document()->updateLayoutIgnorePendingStylesheets();
+        document().updateLayoutIgnorePendingStylesheets();
         if (element->isMouseFocusable())
             element->focus(true, FocusDirectionMouse);
 
diff --git a/Source/core/html/HTMLLabelElement.h b/Source/core/html/HTMLLabelElement.h
index 4c11115..1b0007a 100644
--- a/Source/core/html/HTMLLabelElement.h
+++ b/Source/core/html/HTMLLabelElement.h
@@ -31,7 +31,7 @@
 
 class HTMLLabelElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLLabelElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLLabelElement> create(const QualifiedName&, Document&);
 
     LabelableElement* control();
     HTMLFormElement* form() const;
@@ -39,7 +39,7 @@
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
-    HTMLLabelElement(const QualifiedName&, Document*);
+    HTMLLabelElement(const QualifiedName&, Document&);
 
     virtual bool rendererIsFocusable() const OVERRIDE;
 
diff --git a/Source/core/html/HTMLLegendElement.cpp b/Source/core/html/HTMLLegendElement.cpp
index 118238e..5159326 100644
--- a/Source/core/html/HTMLLegendElement.cpp
+++ b/Source/core/html/HTMLLegendElement.cpp
@@ -35,14 +35,14 @@
 using namespace HTMLNames;
 
 
-inline HTMLLegendElement::HTMLLegendElement(const QualifiedName& tagName, Document* document)
+inline HTMLLegendElement::HTMLLegendElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(legendTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLLegendElement> HTMLLegendElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLLegendElement> HTMLLegendElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLLegendElement(tagName, document));
 }
@@ -92,7 +92,7 @@
     if (!fieldset || !fieldset->hasTagName(fieldsetTag))
         return 0;
 
-    return static_cast<HTMLFieldSetElement*>(fieldset)->form();
+    return toHTMLFieldSetElement(fieldset)->form();
 }
 
 } // namespace
diff --git a/Source/core/html/HTMLLegendElement.h b/Source/core/html/HTMLLegendElement.h
index 0917175..4ee68b2 100644
--- a/Source/core/html/HTMLLegendElement.h
+++ b/Source/core/html/HTMLLegendElement.h
@@ -32,10 +32,10 @@
 
 class HTMLLegendElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLLegendElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLLegendElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLLegendElement(const QualifiedName&, Document*);
+    HTMLLegendElement(const QualifiedName&, Document&);
 
     // Control in the legend's fieldset that gets focus and access key.
     HTMLFormControlElement* associatedControl();
@@ -45,6 +45,12 @@
     virtual HTMLFormElement* virtualForm() const OVERRIDE;
 };
 
+inline HTMLLegendElement* toHTMLLegendElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::legendTag));
+    return static_cast<HTMLLegendElement*>(node);
+}
+
 } //namespace
 
 #endif
diff --git a/Source/core/html/HTMLLinkElement.cpp b/Source/core/html/HTMLLinkElement.cpp
index 0427f4a..cbc8b9a 100644
--- a/Source/core/html/HTMLLinkElement.cpp
+++ b/Source/core/html/HTMLLinkElement.cpp
@@ -58,7 +58,7 @@
     return sharedLoadEventSender;
 }
 
-inline HTMLLinkElement::HTMLLinkElement(const QualifiedName& tagName, Document* document, bool createdByParser)
+inline HTMLLinkElement::HTMLLinkElement(const QualifiedName& tagName, Document& document, bool createdByParser)
     : HTMLElement(tagName, document)
     , m_linkLoader(this)
     , m_sizes(DOMSettableTokenList::create())
@@ -70,7 +70,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLLinkElement> HTMLLinkElement::create(const QualifiedName& tagName, Document* document, bool createdByParser)
+PassRefPtr<HTMLLinkElement> HTMLLinkElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
 {
     return adoptRef(new HTMLLinkElement(tagName, document, createdByParser));
 }
@@ -80,7 +80,7 @@
     m_link.clear();
 
     if (inDocument())
-        document()->styleSheetCollections()->removeStyleSheetCandidateNode(this);
+        document().styleSheetCollections()->removeStyleSheetCandidateNode(this);
 
     linkLoadEventSender().cancelEvent(this);
 }
@@ -119,13 +119,13 @@
 bool HTMLLinkElement::shouldLoadLink()
 {
     bool continueLoad = true;
-    RefPtr<Document> originalDocument = document();
+    RefPtr<Document> originalDocument = &document();
     int recursionRank = ++m_beforeLoadRecurseCount;
     if (!dispatchBeforeLoadEvent(getNonEmptyURLAttribute(hrefAttr)))
         continueLoad = false;
 
     // A beforeload handler might have removed us from the document or changed the document.
-    if (continueLoad && (!inDocument() || document() != originalDocument))
+    if (continueLoad && (!inDocument() || &document() != originalDocument))
         continueLoad = false;
 
     // If the beforeload handler recurses into the link element by mutating it, we should only
@@ -198,7 +198,7 @@
     if (m_isInShadowTree)
         return InsertionDone;
 
-    document()->styleSheetCollections()->addStyleSheetCandidateNode(this, m_createdByParser);
+    document().styleSheetCollections()->addStyleSheetCandidateNode(this, m_createdByParser);
 
     process();
     return InsertionDone;
@@ -216,15 +216,15 @@
         ASSERT(!linkStyle() || !linkStyle()->hasSheet());
         return;
     }
-    document()->styleSheetCollections()->removeStyleSheetCandidateNode(this);
+    document().styleSheetCollections()->removeStyleSheetCandidateNode(this);
 
     RefPtr<StyleSheet> removedSheet = sheet();
 
     if (m_link)
         m_link->ownerRemoved();
 
-    if (document()->renderer())
-        document()->removedStyleSheet(removedSheet.get());
+    if (document().renderer())
+        document().removedStyleSheet(removedSheet.get());
 }
 
 void HTMLLinkElement::finishParsingChildren()
@@ -313,7 +313,7 @@
 
 KURL HTMLLinkElement::href() const
 {
-    return document()->completeURL(getAttribute(hrefAttr));
+    return document().completeURL(getAttribute(hrefAttr));
 }
 
 String HTMLLinkElement::rel() const
@@ -395,7 +395,7 @@
         m_resource->removeClient(this);
 }
 
-Document* LinkStyle::document()
+Document& LinkStyle::document()
 {
     return m_owner->document();
 }
@@ -436,7 +436,7 @@
     m_sheet->setMediaQueries(MediaQuerySet::create(m_owner->media()));
     m_sheet->setTitle(m_owner->title());
 
-    styleSheet->parseAuthorStyleSheet(cachedStyleSheet, m_owner->document()->securityOrigin());
+    styleSheet->parseAuthorStyleSheet(cachedStyleSheet, m_owner->document().securityOrigin());
 
     m_loading = false;
     styleSheet->notifyLoadedSheet(cachedStyleSheet);
@@ -496,7 +496,7 @@
 
     if (m_pendingSheetType == NonBlocking)
         return;
-    m_owner->document()->styleSheetCollections()->addPendingSheet();
+    m_owner->document().styleSheetCollections()->addPendingSheet();
 }
 
 void LinkStyle::removePendingSheet(RemovePendingSheetNotificationType notification)
@@ -508,15 +508,15 @@
         return;
     if (type == NonBlocking) {
         // Tell StyleSheetCollections to re-compute styleSheets of this m_owner's treescope.
-        m_owner->document()->styleSheetCollections()->modifiedStyleSheetCandidateNode(m_owner);
+        m_owner->document().styleSheetCollections()->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().
-        m_owner->document()->styleResolverChanged(RecalcStyleImmediately);
+        m_owner->document().styleResolverChanged(RecalcStyleImmediately);
         return;
     }
 
-    m_owner->document()->styleSheetCollections()->removePendingSheet(m_owner,
+    m_owner->document().styleSheetCollections()->removePendingSheet(m_owner,
         notification == RemovePendingSheetNotifyImmediately
         ? StyleSheetCollections::RemovePendingSheetNotifyImmediately
         : StyleSheetCollections::RemovePendingSheetNotifyLater);
@@ -559,7 +559,7 @@
                 process();
         } else {
             // FIXME: We don't have enough knowledge here to know if we should call addedStyleSheet() or removedStyleSheet().
-            m_owner->document()->styleResolverChanged(RecalcStyleDeferred);
+            m_owner->document().styleResolverChanged(RecalcStyleDeferred);
         }
     }
 }
@@ -573,19 +573,19 @@
     if (m_owner->relAttribute().iconType() != InvalidIcon && builder.url().isValid() && !builder.url().isEmpty()) {
         if (!m_owner->shouldLoadLink())
             return;
-        if (!document()->securityOrigin()->canDisplay(builder.url()))
+        if (!document().securityOrigin()->canDisplay(builder.url()))
             return;
-        if (!document()->contentSecurityPolicy()->allowImageFromSource(builder.url()))
+        if (!document().contentSecurityPolicy()->allowImageFromSource(builder.url()))
             return;
-        if (document()->frame())
-            document()->frame()->loader()->client()->dispatchDidChangeIcons(m_owner->relAttribute().iconType());
+        if (document().frame())
+            document().frame()->loader()->client()->dispatchDidChangeIcons(m_owner->relAttribute().iconType());
     }
 
     if (!m_owner->loadLink(type, builder.url()))
         return;
 
     if ((m_disabledState != Disabled) && m_owner->relAttribute().isStyleSheet()
-        && document()->frame() && builder.url().isValid()) {
+        && document().frame() && builder.url().isValid()) {
 
         if (m_resource) {
             removePendingSheet();
@@ -602,7 +602,7 @@
         if (!m_owner->media().isEmpty()) {
             RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(document());
             RefPtr<MediaQuerySet> media = MediaQuerySet::create(m_owner->media());
-            MediaQueryEvaluator evaluator(document()->frame()->view()->mediaType(), document()->frame(), documentStyle.get());
+            MediaQueryEvaluator evaluator(document().frame()->view()->mediaType(), document().frame(), documentStyle.get());
             mediaQueryMatches = evaluator.eval(media.get());
         }
 
@@ -613,7 +613,7 @@
 
         // Load stylesheets that are not needed for the rendering immediately with low priority.
         FetchRequest request = builder.build(blocking);
-        m_resource = document()->fetcher()->fetchCSSStyleSheet(request);
+        m_resource = document().fetcher()->fetchCSSStyleSheet(request);
 
         if (m_resource)
             m_resource->addClient(this);
@@ -626,7 +626,7 @@
         // we no longer contain a stylesheet, e.g. perhaps rel or type was changed
         RefPtr<StyleSheet> removedSheet = m_sheet;
         clearSheet();
-        document()->removedStyleSheet(removedSheet.get());
+        document().removedStyleSheet(removedSheet.get());
     }
 }
 
diff --git a/Source/core/html/HTMLLinkElement.h b/Source/core/html/HTMLLinkElement.h
index 213a40d..ba8bb73 100644
--- a/Source/core/html/HTMLLinkElement.h
+++ b/Source/core/html/HTMLLinkElement.h
@@ -25,10 +25,10 @@
 #define HTMLLinkElement_h
 
 #include "core/css/CSSStyleSheet.h"
+#include "core/dom/DOMSettableTokenList.h"
 #include "core/dom/IconURL.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/fetch/StyleSheetResourceClient.h"
-#include "core/html/DOMSettableTokenList.h"
 #include "core/html/HTMLElement.h"
 #include "core/html/LinkRelAttribute.h"
 #include "core/html/LinkResource.h"
@@ -106,7 +106,7 @@
     void clearSheet();
     void addPendingSheet(PendingSheetType);
     void removePendingSheet(RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
-    Document* document();
+    Document& document();
 
     ResourcePtr<CSSStyleSheetResource> m_resource;
     RefPtr<CSSStyleSheet> m_sheet;
@@ -120,7 +120,7 @@
 
 class HTMLLinkElement FINAL : public HTMLElement, public LinkLoaderClient {
 public:
-    static PassRefPtr<HTMLLinkElement> create(const QualifiedName&, Document*, bool createdByParser);
+    static PassRefPtr<HTMLLinkElement> create(const QualifiedName&, Document&, bool createdByParser);
     virtual ~HTMLLinkElement();
 
     KURL href() const;
@@ -189,7 +189,7 @@
     virtual void didSendDOMContentLoadedForLinkPrerender() OVERRIDE;
 
 private:
-    HTMLLinkElement(const QualifiedName&, Document*, bool createdByParser);
+    HTMLLinkElement(const QualifiedName&, Document&, bool createdByParser);
 
     RefPtr<LinkResource> m_link;
     LinkLoader m_linkLoader;
diff --git a/Source/core/html/HTMLLinkElement.idl b/Source/core/html/HTMLLinkElement.idl
index 0d5ee7d..25e900a 100644
--- a/Source/core/html/HTMLLinkElement.idl
+++ b/Source/core/html/HTMLLinkElement.idl
@@ -34,6 +34,6 @@
     // DOM Level 2 Style
     readonly attribute StyleSheet sheet;
 
-    [EnabledAtRuntime=htmlImports] readonly attribute Document import;
+    [EnabledAtRuntime=HTMLImports] readonly attribute Document import;
 };
 
diff --git a/Source/core/html/HTMLMapElement.cpp b/Source/core/html/HTMLMapElement.cpp
index ee6b009..bdded68 100644
--- a/Source/core/html/HTMLMapElement.cpp
+++ b/Source/core/html/HTMLMapElement.cpp
@@ -36,19 +36,19 @@
 
 using namespace HTMLNames;
 
-HTMLMapElement::HTMLMapElement(const QualifiedName& tagName, Document* document)
+HTMLMapElement::HTMLMapElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(mapTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLMapElement> HTMLMapElement::create(Document* document)
+PassRefPtr<HTMLMapElement> HTMLMapElement::create(Document& document)
 {
     return adoptRef(new HTMLMapElement(mapTag, document));
 }
 
-PassRefPtr<HTMLMapElement> HTMLMapElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLMapElement> HTMLMapElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLMapElement(tagName, document));
 }
@@ -81,7 +81,7 @@
 
 HTMLImageElement* HTMLMapElement::imageElement()
 {
-    RefPtr<HTMLCollection> images = document()->images();
+    RefPtr<HTMLCollection> images = document().images();
     for (unsigned i = 0; Node* curr = images->item(i); i++) {
         if (!curr->hasTagName(imgTag))
             continue;
@@ -106,17 +106,17 @@
         if (isIdAttributeName(name)) {
             // Call base class so that hasID bit gets set.
             HTMLElement::parseAttribute(name, value);
-            if (document()->isHTMLDocument())
+            if (document().isHTMLDocument())
                 return;
         }
         if (inDocument())
-            treeScope()->removeImageMap(this);
+            treeScope().removeImageMap(this);
         String mapName = value;
         if (mapName[0] == '#')
             mapName = mapName.substring(1);
-        m_name = document()->isHTMLDocument() ? mapName.lower() : mapName;
+        m_name = document().isHTMLDocument() ? mapName.lower() : mapName;
         if (inDocument())
-            treeScope()->addImageMap(this);
+            treeScope().addImageMap(this);
 
         return;
     }
@@ -132,14 +132,14 @@
 Node::InsertionNotificationRequest HTMLMapElement::insertedInto(ContainerNode* insertionPoint)
 {
     if (insertionPoint->inDocument())
-        treeScope()->addImageMap(this);
+        treeScope().addImageMap(this);
     return HTMLElement::insertedInto(insertionPoint);
 }
 
 void HTMLMapElement::removedFrom(ContainerNode* insertionPoint)
 {
     if (insertionPoint->inDocument())
-        treeScope()->removeImageMap(this);
+        treeScope().removeImageMap(this);
     HTMLElement::removedFrom(insertionPoint);
 }
 
diff --git a/Source/core/html/HTMLMapElement.h b/Source/core/html/HTMLMapElement.h
index 7ded16e..dedcef2 100644
--- a/Source/core/html/HTMLMapElement.h
+++ b/Source/core/html/HTMLMapElement.h
@@ -32,8 +32,8 @@
 
 class HTMLMapElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLMapElement> create(Document*);
-    static PassRefPtr<HTMLMapElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLMapElement> create(Document&);
+    static PassRefPtr<HTMLMapElement> create(const QualifiedName&, Document&);
     virtual ~HTMLMapElement();
 
     const AtomicString& getName() const { return m_name; }
@@ -44,7 +44,7 @@
     PassRefPtr<HTMLCollection> areas();
 
 private:
-    HTMLMapElement(const QualifiedName&, Document*);
+    HTMLMapElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
diff --git a/Source/core/html/HTMLMarqueeElement.cpp b/Source/core/html/HTMLMarqueeElement.cpp
index e4c0347..fb472d3 100644
--- a/Source/core/html/HTMLMarqueeElement.cpp
+++ b/Source/core/html/HTMLMarqueeElement.cpp
@@ -34,15 +34,15 @@
 
 using namespace HTMLNames;
 
-inline HTMLMarqueeElement::HTMLMarqueeElement(const QualifiedName& tagName, Document* document)
+inline HTMLMarqueeElement::HTMLMarqueeElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
-    , ActiveDOMObject(document)
+    , ActiveDOMObject(&document)
 {
     ASSERT(hasTagName(marqueeTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLMarqueeElement> HTMLMarqueeElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLMarqueeElement> HTMLMarqueeElement::create(const QualifiedName& tagName, Document& document)
 {
     RefPtr<HTMLMarqueeElement> marqueeElement(adoptRef(new HTMLMarqueeElement(tagName, document)));
     marqueeElement->suspendIfNeeded();
diff --git a/Source/core/html/HTMLMarqueeElement.h b/Source/core/html/HTMLMarqueeElement.h
index c1bc4b8..9169908 100644
--- a/Source/core/html/HTMLMarqueeElement.h
+++ b/Source/core/html/HTMLMarqueeElement.h
@@ -33,7 +33,7 @@
 
 class HTMLMarqueeElement FINAL : public HTMLElement, private ActiveDOMObject {
 public:
-    static PassRefPtr<HTMLMarqueeElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLMarqueeElement> create(const QualifiedName&, Document&);
 
     int minimumDelay() const;
 
@@ -52,7 +52,7 @@
     void setLoop(int, ExceptionState&);
 
 private:
-    HTMLMarqueeElement(const QualifiedName&, Document*);
+    HTMLMarqueeElement(const QualifiedName&, Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
@@ -67,6 +67,12 @@
     RenderMarquee* renderMarquee() const;
 };
 
+inline HTMLMarqueeElement* toHTMLMarqueeElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::marqueeTag));
+    return static_cast<HTMLMarqueeElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // HTMLMarqueeElement_h
diff --git a/Source/core/html/HTMLMediaElement.cpp b/Source/core/html/HTMLMediaElement.cpp
index 626022e..587f75a 100644
--- a/Source/core/html/HTMLMediaElement.cpp
+++ b/Source/core/html/HTMLMediaElement.cpp
@@ -39,7 +39,6 @@
 #include "core/dom/EventNames.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/FullscreenElementStack.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLMediaSource.h"
 #include "core/html/HTMLSourceElement.h"
@@ -238,9 +237,9 @@
     return WebKit::Platform::current()->mimeRegistry()->supportsMediaMIMEType(type, typeCodecs, system);
 }
 
-HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document* document, bool createdByParser)
+HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& document, bool createdByParser)
     : HTMLElement(tagName, document)
-    , ActiveDOMObject(document)
+    , ActiveDOMObject(&document)
     , m_loadTimer(this, &HTMLMediaElement::loadTimerFired)
     , m_progressEventTimer(this, &HTMLMediaElement::progressEventTimerFired)
     , m_playbackProgressTimer(this, &HTMLMediaElement::playbackProgressTimerFired)
@@ -259,7 +258,7 @@
     , m_lastTimeUpdateEventWallTime(0)
     , m_lastTimeUpdateEventMovieTime(numeric_limits<double>::max())
     , m_loadState(WaitingForSource)
-    , m_restrictions(RequireUserGestureForFullscreenRestriction | RequirePageConsentToLoadMediaRestriction)
+    , m_restrictions(RequirePageConsentToLoadMediaRestriction)
     , m_preload(MediaPlayer::Auto)
     , m_displayMode(Unknown)
     , m_cachedTime(MediaPlayer::invalidTime())
@@ -301,13 +300,18 @@
     LOG(Media, "HTMLMediaElement::HTMLMediaElement");
     ScriptWrappable::init(this);
 
-    if (document->settings() && document->settings()->mediaPlaybackRequiresUserGesture()) {
-        addBehaviorRestriction(RequireUserGestureForRateChangeRestriction);
-        addBehaviorRestriction(RequireUserGestureForLoadRestriction);
+    if (document.settings()) {
+        if (document.settings()->mediaPlaybackRequiresUserGesture()) {
+            addBehaviorRestriction(RequireUserGestureForRateChangeRestriction);
+            addBehaviorRestriction(RequireUserGestureForLoadRestriction);
+        }
+        if (document.settings()->mediaFullscreenRequiresUserGesture()) {
+            addBehaviorRestriction(RequireUserGestureForFullscreenRestriction);
+        }
     }
 
     setHasCustomStyleCallbacks();
-    addElementToDocumentMap(this, document);
+    addElementToDocumentMap(this, &document);
 
 }
 
@@ -334,7 +338,7 @@
     setMediaKeys(0);
 #endif
 
-    removeElementFromDocumentMap(this, document());
+    removeElementFromDocumentMap(this, &document());
 
     // Destroying the player may cause a resource load to be canceled,
     // which could result in userCancelledLoad() being called back.
@@ -343,6 +347,10 @@
     // See http://crbug.com/233654 for more details.
     m_completelyLoaded = true;
     m_player.clear();
+#if ENABLE(WEB_AUDIO)
+    if (audioSourceProvider())
+        audioSourceProvider()->setClient(0);
+#endif
 }
 
 void HTMLMediaElement::didMoveToNewDocument(Document* oldDocument)
@@ -352,13 +360,13 @@
     if (m_shouldDelayLoadEvent) {
         if (oldDocument)
             oldDocument->decrementLoadEventDelayCount();
-        document()->incrementLoadEventDelayCount();
+        document().incrementLoadEventDelayCount();
     }
 
     if (oldDocument)
         removeElementFromDocumentMap(this, oldDocument);
 
-    addElementToDocumentMap(this, document());
+    addElementToDocumentMap(this, &document());
 
     // FIXME: This is a temporary fix to prevent this object from causing the
     // MediaPlayer to dereference Frame and FrameLoader pointers from the
@@ -482,9 +490,9 @@
     }
 }
 
-bool HTMLMediaElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLMediaElement::rendererIsNeeded(const RenderStyle& style)
 {
-    return controls() ? HTMLElement::rendererIsNeeded(context) : false;
+    return controls() ? HTMLElement::rendererIsNeeded(style) : false;
 }
 
 RenderObject* HTMLMediaElement::createRenderer(RenderStyle*)
@@ -492,9 +500,9 @@
     return new RenderMedia(this);
 }
 
-bool HTMLMediaElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool HTMLMediaElement::childShouldCreateRenderer(const Node& child) const
 {
-    return hasMediaControls() && HTMLElement::childShouldCreateRenderer(childContext);
+    return hasMediaControls() && HTMLElement::childShouldCreateRenderer(child);
 }
 
 Node::InsertionNotificationRequest HTMLMediaElement::insertedInto(ContainerNode* insertionPoint)
@@ -537,7 +545,7 @@
         renderer()->updateFromElement();
 }
 
-void HTMLMediaElement::didRecalcStyle(StyleChange)
+void HTMLMediaElement::didRecalcStyle(StyleRecalcChange)
 {
     if (renderer())
         renderer()->updateFromElement();
@@ -840,24 +848,18 @@
     loadResource(mediaURL, contentType, keySystem);
 }
 
-void HTMLMediaElement::loadResource(const KURL& initialURL, ContentType& contentType, const String& keySystem)
+void HTMLMediaElement::loadResource(const KURL& url, ContentType& contentType, const String& keySystem)
 {
-    ASSERT(isSafeToLoadURL(initialURL, Complain));
+    ASSERT(isSafeToLoadURL(url, Complain));
 
-    LOG(Media, "HTMLMediaElement::loadResource(%s, %s, %s)", urlForLoggingMedia(initialURL).utf8().data(), contentType.raw().utf8().data(), keySystem.utf8().data());
+    LOG(Media, "HTMLMediaElement::loadResource(%s, %s, %s)", urlForLoggingMedia(url).utf8().data(), contentType.raw().utf8().data(), keySystem.utf8().data());
 
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame) {
         mediaLoadingFailed(MediaPlayer::FormatError);
         return;
     }
 
-    KURL url = initialURL;
-    if (!frame->loader()->willLoadMediaElementURL(url)) {
-        mediaLoadingFailed(MediaPlayer::FormatError);
-        return;
-    }
-
     // The resource fetch algorithm
     m_networkState = NETWORK_LOADING;
 
@@ -1119,18 +1121,18 @@
         // correctly identifies the type of the event, if the startTime is
         // less than the endTime in the cue.
         if (eventTasks[i].second->startTime() >= eventTasks[i].second->endTime()) {
-            event = Event::create(eventNames().enterEvent, false, false);
+            event = Event::create(eventNames().enterEvent);
             event->setTarget(eventTasks[i].second);
             m_asyncEventQueue->enqueueEvent(event.release());
 
-            event = Event::create(eventNames().exitEvent, false, false);
+            event = Event::create(eventNames().exitEvent);
             event->setTarget(eventTasks[i].second);
             m_asyncEventQueue->enqueueEvent(event.release());
         } else {
             if (eventTasks[i].first == eventTasks[i].second->startTime())
-                event = Event::create(eventNames().enterEvent, false, false);
+                event = Event::create(eventNames().enterEvent);
             else
-                event = Event::create(eventNames().exitEvent, false, false);
+                event = Event::create(eventNames().exitEvent);
 
             event->setTarget(eventTasks[i].second);
             m_asyncEventQueue->enqueueEvent(event.release());
@@ -1144,7 +1146,7 @@
     // 15 - For each text track in affected tracks, in the list order, queue a
     // task to fire a simple event named cuechange at the TextTrack object, and, ...
     for (size_t i = 0; i < affectedTracks.size(); ++i) {
-        RefPtr<Event> event = Event::create(eventNames().cuechangeEvent, false, false);
+        RefPtr<Event> event = Event::create(eventNames().cuechangeEvent);
         event->setTarget(affectedTracks[i]);
 
         m_asyncEventQueue->enqueueEvent(event.release());
@@ -1152,7 +1154,7 @@
         // ... if the text track has a corresponding track element, to then fire a
         // simple event named cuechange at the track element as well.
         if (affectedTracks[i]->trackType() == TextTrack::TrackElement) {
-            RefPtr<Event> event = Event::create(eventNames().cuechangeEvent, false, false);
+            RefPtr<Event> event = Event::create(eventNames().cuechangeEvent);
             HTMLTrackElement* trackElement = static_cast<LoadableTextTrack*>(affectedTracks[i])->trackElement();
             ASSERT(trackElement);
             event->setTarget(trackElement);
@@ -1220,7 +1222,7 @@
         for (Node* node = firstChild(); node; node = node->nextSibling()) {
             if (!node->hasTagName(trackTag))
                 continue;
-            HTMLTrackElement* trackElement = static_cast<HTMLTrackElement*>(node);
+            HTMLTrackElement* trackElement = toHTMLTrackElement(node);
             if (trackElement->track() != track)
                 continue;
 
@@ -1324,15 +1326,15 @@
         return false;
     }
 
-    Frame* frame = document()->frame();
-    if (!frame || !document()->securityOrigin()->canDisplay(url)) {
+    Frame* frame = document().frame();
+    if (!frame || !document().securityOrigin()->canDisplay(url)) {
         if (actionIfInvalid == Complain)
             FrameLoader::reportLocalLoadFailed(frame, url.elidedString());
         LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> FALSE rejected by SecurityOrigin", urlForLoggingMedia(url).utf8().data());
         return false;
     }
 
-    if (!document()->contentSecurityPolicy()->allowMediaFromSource(url)) {
+    if (!document().contentSecurityPolicy()->allowMediaFromSource(url)) {
         LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> rejected by Content Security Policy", urlForLoggingMedia(url).utf8().data());
         return false;
     }
@@ -1443,7 +1445,7 @@
 
     for (Node* node = firstChild(); node; node = node->nextSibling()) {
         if (node->hasTagName(sourceTag))
-            static_cast<HTMLSourceElement*>(node)->cancelPendingErrorEvent();
+            toHTMLSourceElement(node)->cancelPendingErrorEvent();
     }
 }
 
@@ -1637,7 +1639,7 @@
         if (isPotentiallyPlaying && oldState <= HAVE_CURRENT_DATA)
             scheduleEvent(eventNames().playingEvent);
 
-        if (m_autoplaying && m_paused && autoplay() && !document()->isSandboxed(SandboxAutomaticFeatures) && !userGestureRequiredForRateChange()) {
+        if (m_autoplaying && m_paused && autoplay() && !document().isSandboxed(SandboxAutomaticFeatures) && !userGestureRequiredForRateChange()) {
             m_paused = false;
             invalidateCachedTime();
             scheduleEvent(eventNames().playEvent);
@@ -2153,12 +2155,12 @@
     if (ScriptController::processingUserGesture())
         removeBehaviorsRestrictionsAfterFirstUserGesture();
 
-    Settings* settings = document()->settings();
+    Settings* settings = document().settings();
     if (settings && settings->needsSiteSpecificQuirks() && m_dispatchingCanPlayEvent && !m_loadInitiatedByUserGesture) {
         // It should be impossible to be processing the canplay event while handling a user gesture
         // since it is dispatched asynchronously.
         ASSERT(!ScriptController::processingUserGesture());
-        String host = document()->baseURL().host();
+        String host = document().baseURL().host();
         if (host.endsWith(".npr.org", false) || equalIgnoringCase(host, "npr.org"))
             return;
     }
@@ -2330,7 +2332,7 @@
 
 bool HTMLMediaElement::controls() const
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
 
     // always show controls when scripting is disabled
     if (frame && !frame->script()->canExecuteScripts(NotAboutToExecuteScript))
@@ -2748,7 +2750,7 @@
 
     LOG(Media, "HTMLMediaElement::configureTextTrackGroup(%d)", group.kind);
 
-    Page* page = document()->page();
+    Page* page = document().page();
     Settings* settings = page ? &page->settings() : 0;
 
     // First, find the track in the group that should be enabled (if any).
@@ -2932,7 +2934,7 @@
         if (node->parentNode() != this)
             continue;
 
-        source = static_cast<HTMLSourceElement*>(node);
+        source = toHTMLSourceElement(node);
 
         // If candidate does not have a src attribute, or if its src attribute's value is the empty string ... jump down to the failed step below
         mediaURL = source->getNonEmptyURLAttribute(srcAttr);
@@ -2944,7 +2946,7 @@
             goto check_again;
 
         if (source->fastHasAttribute(mediaAttr)) {
-            MediaQueryEvaluator screenEval("screen", document()->frame(), renderer() ? renderer()->style() : 0);
+            MediaQueryEvaluator screenEval("screen", document().frame(), renderer() ? renderer()->style() : 0);
             RefPtr<MediaQuerySet> media = MediaQuerySet::create(source->media());
 #if !LOG_DISABLED
             if (shouldLog)
@@ -3454,6 +3456,10 @@
     closeMediaSource();
 
     m_player.clear();
+#if ENABLE(WEB_AUDIO)
+    if (audioSourceProvider())
+        audioSourceProvider()->setClient(0);
+#endif
     stopPeriodicTimers();
     m_loadTimer.stop();
 
@@ -3539,16 +3545,16 @@
 {
     LOG(Media, "HTMLMediaElement::enterFullscreen");
 
-    if (document()->settings() && document()->settings()->fullScreenEnabled())
-        FullscreenElementStack::from(document())->requestFullScreenForElement(this, 0, FullscreenElementStack::ExemptIFrameAllowFullScreenRequirement);
+    if (document().settings() && document().settings()->fullScreenEnabled())
+        FullscreenElementStack::from(&document())->requestFullScreenForElement(this, 0, FullscreenElementStack::ExemptIFrameAllowFullScreenRequirement);
 }
 
 void HTMLMediaElement::exitFullscreen()
 {
     LOG(Media, "HTMLMediaElement::exitFullscreen");
 
-    if (document()->settings() && document()->settings()->fullScreenEnabled() && isFullscreen())
-        FullscreenElementStack::from(document())->webkitCancelFullScreen();
+    if (document().settings() && document().settings()->fullScreenEnabled() && isFullscreen())
+        FullscreenElementStack::from(&document())->webkitCancelFullScreen();
 }
 
 void HTMLMediaElement::didBecomeFullscreenElement()
@@ -3660,9 +3666,9 @@
 
     m_shouldDelayLoadEvent = shouldDelay;
     if (shouldDelay)
-        document()->incrementLoadEventDelayCount();
+        document().incrementLoadEventDelayCount();
     else
-        document()->decrementLoadEventDelayCount();
+        document().decrementLoadEventDelayCount();
 }
 
 
@@ -3843,7 +3849,7 @@
 
     // 4. If there is another media element whose Document is the same as m's Document (even if one or both
     // of these elements are not actually in the Document),
-    HashSet<HTMLMediaElement*> elements = documentToElementSetMap().get(document());
+    HashSet<HTMLMediaElement*> elements = documentToElementSetMap().get(&document());
     for (HashSet<HTMLMediaElement*>::iterator i = elements.begin(); i != elements.end(); ++i) {
         if (*i == this)
             continue;
diff --git a/Source/core/html/HTMLMediaElement.h b/Source/core/html/HTMLMediaElement.h
index 6d562ce..86bc891 100644
--- a/Source/core/html/HTMLMediaElement.h
+++ b/Source/core/html/HTMLMediaElement.h
@@ -289,7 +289,7 @@
     virtual bool dispatchEvent(PassRefPtr<Event>) OVERRIDE;
 
 protected:
-    HTMLMediaElement(const QualifiedName&, Document*, bool);
+    HTMLMediaElement(const QualifiedName&, Document&, bool);
     virtual ~HTMLMediaElement();
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -336,12 +336,12 @@
     virtual bool hasCustomFocusLogic() const OVERRIDE;
     virtual bool supportsFocus() const;
     virtual bool isMouseFocusable() const;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
+    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
-    virtual void didRecalcStyle(StyleChange);
+    virtual void didRecalcStyle(StyleRecalcChange);
 
     virtual void didBecomeFullscreenElement();
     virtual void willStopBeingFullscreenElement();
diff --git a/Source/core/html/HTMLMediaElement.idl b/Source/core/html/HTMLMediaElement.idl
index 6e811ee..873aeeb 100644
--- a/Source/core/html/HTMLMediaElement.idl
+++ b/Source/core/html/HTMLMediaElement.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=media,
+    EnabledAtRuntime=Media,
     ActiveDOMObject
 ] interface HTMLMediaElement : HTMLElement {
 
@@ -88,19 +88,19 @@
 readonly attribute unsigned long webkitVideoDecodedByteCount;
 
 // FIXME: add DeprecateAs=PrefixedMediaGenerateKeyRequest when MediaKeys is ready.
-[EnabledAtRuntime=legacyEncryptedMedia, RaisesException] void webkitGenerateKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, optional Uint8Array initData);
-[EnabledAtRuntime=legacyEncryptedMedia, RaisesException] void webkitAddKey([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, Uint8Array key, optional Uint8Array initData, [Default=NullString] optional DOMString sessionId);
-[EnabledAtRuntime=legacyEncryptedMedia, RaisesException] void webkitCancelKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, [Default=NullString] optional DOMString sessionId);
+[EnabledAtRuntime=LegacyEncryptedMedia, RaisesException] void webkitGenerateKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, optional Uint8Array initData);
+[EnabledAtRuntime=LegacyEncryptedMedia, RaisesException] void webkitAddKey([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, Uint8Array key, optional Uint8Array initData, [Default=NullString] optional DOMString sessionId);
+[EnabledAtRuntime=LegacyEncryptedMedia, RaisesException] void webkitCancelKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, [Default=NullString] optional DOMString sessionId);
 
-[EnabledAtRuntime=legacyEncryptedMedia] attribute EventHandler onwebkitkeyadded;
-[EnabledAtRuntime=legacyEncryptedMedia] attribute EventHandler onwebkitkeyerror;
-[EnabledAtRuntime=legacyEncryptedMedia] attribute EventHandler onwebkitkeymessage;
-[EnabledAtRuntime=legacyEncryptedMedia] attribute EventHandler onwebkitneedkey;
+[EnabledAtRuntime=LegacyEncryptedMedia] attribute EventHandler onwebkitkeyadded;
+[EnabledAtRuntime=LegacyEncryptedMedia] attribute EventHandler onwebkitkeyerror;
+[EnabledAtRuntime=LegacyEncryptedMedia] attribute EventHandler onwebkitkeymessage;
+[EnabledAtRuntime=LegacyEncryptedMedia] attribute EventHandler onwebkitneedkey;
 
-[EnabledAtRuntime=encryptedMedia, Conditional=ENCRYPTED_MEDIA_V2] attribute MediaKeys mediaKeys;
+[EnabledAtRuntime=EncryptedMedia, Conditional=ENCRYPTED_MEDIA_V2] attribute MediaKeys mediaKeys;
 
-[EnabledAtRuntime=videoTrack, RaisesException] TextTrack addTextTrack(DOMString kind, optional DOMString label, optional DOMString language);
-[EnabledAtRuntime=videoTrack] readonly attribute TextTrackList textTracks;
+[EnabledAtRuntime=VideoTrack, RaisesException] TextTrack addTextTrack(DOMString kind, optional DOMString label, optional DOMString language);
+[EnabledAtRuntime=VideoTrack] readonly attribute TextTrackList textTracks;
 
 [Reflect, TreatNullAs=NullString] attribute DOMString mediaGroup;
 [CustomSetter] attribute MediaController controller;
diff --git a/Source/core/html/HTMLMenuElement.cpp b/Source/core/html/HTMLMenuElement.cpp
index 57e1cd1..dd110d4 100644
--- a/Source/core/html/HTMLMenuElement.cpp
+++ b/Source/core/html/HTMLMenuElement.cpp
@@ -29,14 +29,14 @@
 
 using namespace HTMLNames;
 
-inline HTMLMenuElement::HTMLMenuElement(const QualifiedName& tagName, Document* document)
+inline HTMLMenuElement::HTMLMenuElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(menuTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLMenuElement> HTMLMenuElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLMenuElement> HTMLMenuElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLMenuElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLMenuElement.h b/Source/core/html/HTMLMenuElement.h
index e853a8e..af7070d 100644
--- a/Source/core/html/HTMLMenuElement.h
+++ b/Source/core/html/HTMLMenuElement.h
@@ -29,10 +29,10 @@
 
 class HTMLMenuElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLMenuElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLMenuElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLMenuElement(const QualifiedName&, Document*);
+    HTMLMenuElement(const QualifiedName&, Document&);
 };
 
 } //namespace
diff --git a/Source/core/html/HTMLMetaElement.cpp b/Source/core/html/HTMLMetaElement.cpp
index a93e2ce..4218d13 100644
--- a/Source/core/html/HTMLMetaElement.cpp
+++ b/Source/core/html/HTMLMetaElement.cpp
@@ -30,19 +30,19 @@
 
 using namespace HTMLNames;
 
-inline HTMLMetaElement::HTMLMetaElement(const QualifiedName& tagName, Document* document)
+inline HTMLMetaElement::HTMLMetaElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(metaTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLMetaElement> HTMLMetaElement::create(Document* document)
+PassRefPtr<HTMLMetaElement> HTMLMetaElement::create(Document& document)
 {
     return adoptRef(new HTMLMetaElement(metaTag, document));
 }
 
-PassRefPtr<HTMLMetaElement> HTMLMetaElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLMetaElement> HTMLMetaElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLMetaElement(tagName, document));
 }
@@ -77,19 +77,19 @@
         return;
 
     if (equalIgnoringCase(name(), "viewport"))
-        document()->processViewport(contentValue, ViewportArguments::ViewportMeta);
+        document().processViewport(contentValue, ViewportArguments::ViewportMeta);
     else if (equalIgnoringCase(name(), "referrer"))
-        document()->processReferrerPolicy(contentValue);
+        document().processReferrerPolicy(contentValue);
     else if (equalIgnoringCase(name(), "handheldfriendly") && equalIgnoringCase(contentValue, "true"))
-        document()->processViewport("width=device-width", ViewportArguments::HandheldFriendlyMeta);
+        document().processViewport("width=device-width", ViewportArguments::HandheldFriendlyMeta);
     else if (equalIgnoringCase(name(), "mobileoptimized"))
-        document()->processViewport("width=device-width, initial-scale=1", ViewportArguments::MobileOptimizedMeta);
+        document().processViewport("width=device-width, initial-scale=1", ViewportArguments::MobileOptimizedMeta);
 
     // Get the document to process the tag, but only if we're actually part of DOM tree (changing a meta tag while
     // it's not in the tree shouldn't have any effect on the document)
     const AtomicString& httpEquivValue = fastGetAttribute(http_equivAttr);
     if (!httpEquivValue.isNull())
-        document()->processHttpEquiv(httpEquivValue, contentValue);
+        document().processHttpEquiv(httpEquivValue, contentValue);
 }
 
 String HTMLMetaElement::content() const
diff --git a/Source/core/html/HTMLMetaElement.h b/Source/core/html/HTMLMetaElement.h
index f9255b1..4d2db88 100644
--- a/Source/core/html/HTMLMetaElement.h
+++ b/Source/core/html/HTMLMetaElement.h
@@ -29,15 +29,15 @@
 
 class HTMLMetaElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLMetaElement> create(Document*);
-    static PassRefPtr<HTMLMetaElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLMetaElement> create(Document&);
+    static PassRefPtr<HTMLMetaElement> create(const QualifiedName&, Document&);
 
     String content() const;
     String httpEquiv() const;
     String name() const;
 
 private:
-    HTMLMetaElement(const QualifiedName&, Document*);
+    HTMLMetaElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
@@ -45,6 +45,18 @@
     void process();
 };
 
-} //namespace
+inline HTMLMetaElement* toHTMLMetaElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::metaTag));
+    return static_cast<HTMLMetaElement*>(node);
+}
+
+inline const HTMLMetaElement* toHTMLMetaElement(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::metaTag));
+    return static_cast<const HTMLMetaElement*>(node);
+}
+
+} // namespace WebCore
 
 #endif
diff --git a/Source/core/html/HTMLMeterElement.cpp b/Source/core/html/HTMLMeterElement.cpp
index 0f4a998..0944dcf 100644
--- a/Source/core/html/HTMLMeterElement.cpp
+++ b/Source/core/html/HTMLMeterElement.cpp
@@ -26,7 +26,6 @@
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/MeterShadowElement.h"
@@ -38,7 +37,7 @@
 
 using namespace HTMLNames;
 
-HTMLMeterElement::HTMLMeterElement(const QualifiedName& tagName, Document* document)
+HTMLMeterElement::HTMLMeterElement(const QualifiedName& tagName, Document& document)
     : LabelableElement(tagName, document)
 {
     ASSERT(hasTagName(meterTag));
@@ -49,7 +48,7 @@
 {
 }
 
-PassRefPtr<HTMLMeterElement> HTMLMeterElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLMeterElement> HTMLMeterElement::create(const QualifiedName& tagName, Document& document)
 {
     RefPtr<HTMLMeterElement> meter = adoptRef(new HTMLMeterElement(tagName, document));
     meter->ensureUserAgentShadowRoot();
diff --git a/Source/core/html/HTMLMeterElement.h b/Source/core/html/HTMLMeterElement.h
index 67aecbe..2e1d6b6 100644
--- a/Source/core/html/HTMLMeterElement.h
+++ b/Source/core/html/HTMLMeterElement.h
@@ -31,7 +31,7 @@
 
 class HTMLMeterElement FINAL : public LabelableElement {
 public:
-    static PassRefPtr<HTMLMeterElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLMeterElement> create(const QualifiedName&, Document&);
 
     enum GaugeRegion {
         GaugeRegionOptimum,
@@ -63,7 +63,7 @@
     bool canContainRangeEndPoint() const { return false; }
 
 private:
-    HTMLMeterElement(const QualifiedName&, Document*);
+    HTMLMeterElement(const QualifiedName&, Document&);
     virtual ~HTMLMeterElement();
 
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
diff --git a/Source/core/html/HTMLModElement.cpp b/Source/core/html/HTMLModElement.cpp
index cbe20a3..e609ef5 100644
--- a/Source/core/html/HTMLModElement.cpp
+++ b/Source/core/html/HTMLModElement.cpp
@@ -29,13 +29,13 @@
 
 using namespace HTMLNames;
 
-inline HTMLModElement::HTMLModElement(const QualifiedName& tagName, Document* document)
+inline HTMLModElement::HTMLModElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLModElement> HTMLModElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLModElement> HTMLModElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLModElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLModElement.h b/Source/core/html/HTMLModElement.h
index 158a9c3..7fcc7c9 100644
--- a/Source/core/html/HTMLModElement.h
+++ b/Source/core/html/HTMLModElement.h
@@ -30,10 +30,10 @@
 
 class HTMLModElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLModElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLModElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLModElement(const QualifiedName&, Document*);
+    HTMLModElement(const QualifiedName&, Document&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 };
diff --git a/Source/core/html/HTMLOListElement.cpp b/Source/core/html/HTMLOListElement.cpp
index 6feab4d..8ad5bbb 100644
--- a/Source/core/html/HTMLOListElement.cpp
+++ b/Source/core/html/HTMLOListElement.cpp
@@ -32,7 +32,7 @@
 
 using namespace HTMLNames;
 
-HTMLOListElement::HTMLOListElement(const QualifiedName& tagName, Document* document)
+HTMLOListElement::HTMLOListElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_start(0xBADBEEF)
     , m_itemCount(0)
@@ -44,12 +44,12 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLOListElement> HTMLOListElement::create(Document* document)
+PassRefPtr<HTMLOListElement> HTMLOListElement::create(Document& document)
 {
     return adoptRef(new HTMLOListElement(olTag, document));
 }
 
-PassRefPtr<HTMLOListElement> HTMLOListElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLOListElement> HTMLOListElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLOListElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLOListElement.h b/Source/core/html/HTMLOListElement.h
index 7685900..130a794 100644
--- a/Source/core/html/HTMLOListElement.h
+++ b/Source/core/html/HTMLOListElement.h
@@ -29,8 +29,8 @@
 
 class HTMLOListElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLOListElement> create(Document*);
-    static PassRefPtr<HTMLOListElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLOListElement> create(Document&);
+    static PassRefPtr<HTMLOListElement> create(const QualifiedName&, Document&);
 
     int start() const { return m_hasExplicitStart ? m_start : (m_isReversed ? itemCount() : 1); }
     void setStart(int);
@@ -40,7 +40,7 @@
     void itemCountChanged() { m_shouldRecalculateItemCount = true; }
 
 private:
-    HTMLOListElement(const QualifiedName&, Document*);
+    HTMLOListElement(const QualifiedName&, Document&);
 
     void updateItemValues();
 
diff --git a/Source/core/html/HTMLObjectElement.cpp b/Source/core/html/HTMLObjectElement.cpp
index 01d8b11..9c41b41 100644
--- a/Source/core/html/HTMLObjectElement.cpp
+++ b/Source/core/html/HTMLObjectElement.cpp
@@ -38,7 +38,6 @@
 #include "core/html/HTMLMetaElement.h"
 #include "core/html/HTMLParamElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
 #include "core/platform/MIMETypeRegistry.h"
@@ -50,7 +49,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLObjectElement::HTMLObjectElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form, bool createdByParser)
+inline HTMLObjectElement::HTMLObjectElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
     : HTMLPlugInImageElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
     , m_docNamedItem(true)
     , m_useFallbackContent(false)
@@ -62,9 +61,10 @@
 
 inline HTMLObjectElement::~HTMLObjectElement()
 {
+    setForm(0);
 }
 
-PassRefPtr<HTMLObjectElement> HTMLObjectElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLObjectElement> HTMLObjectElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
 {
     return adoptRef(new HTMLObjectElement(tagName, document, form, createdByParser));
 }
@@ -150,7 +150,7 @@
         if (!child->hasTagName(paramTag))
             continue;
 
-        HTMLParamElement* p = static_cast<HTMLParamElement*>(child);
+        HTMLParamElement* p = toHTMLParamElement(child);
         String name = p->name();
         if (name.isEmpty())
             continue;
@@ -201,7 +201,7 @@
     // resource's URL to be given by a param named "src", "movie", "code" or "url"
     // if we know that resource points to a plug-in.
     if (url.isEmpty() && !urlParameter.isEmpty()) {
-        KURL completedURL = document()->completeURL(urlParameter);
+        KURL completedURL = document().completeURL(urlParameter);
         bool useFallback;
         if (shouldUsePlugin(completedURL, serviceType, false, useFallback))
             url = urlParameter;
@@ -230,17 +230,17 @@
     // 'generator' meta tag is present. Only apply this quirk if there is no
     // fallback content, which ensures the quirk will disable itself if Wiki
     // Server is updated to generate an alternate embed tag as fallback content.
-    if (!document()->page()
-        || !document()->page()->settings().needsSiteSpecificQuirks()
+    if (!document().page()
+        || !document().page()->settings().needsSiteSpecificQuirks()
         || hasFallbackContent()
         || !equalIgnoringCase(classId(), "clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"))
         return false;
 
-    RefPtr<NodeList> metaElements = document()->getElementsByTagName(HTMLNames::metaTag.localName());
+    RefPtr<NodeList> metaElements = document().getElementsByTagName(HTMLNames::metaTag.localName());
     unsigned length = metaElements->length();
     for (unsigned i = 0; i < length; ++i) {
         ASSERT(metaElements->item(i)->isHTMLElement());
-        HTMLMetaElement* metaElement = static_cast<HTMLMetaElement*>(metaElements->item(i));
+        HTMLMetaElement* metaElement = toHTMLMetaElement(metaElements->item(i));
         if (equalIgnoringCase(metaElement->name(), "generator") && metaElement->content().startsWith("Mac OS X Server Web Services Server", false))
             return true;
     }
@@ -312,14 +312,14 @@
         renderFallbackContent();
 }
 
-bool HTMLObjectElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLObjectElement::rendererIsNeeded(const RenderStyle& style)
 {
     // FIXME: This check should not be needed, detached documents never render!
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return false;
 
-    return HTMLPlugInImageElement::rendererIsNeeded(context);
+    return HTMLPlugInImageElement::rendererIsNeeded(style);
 }
 
 Node::InsertionNotificationRequest HTMLObjectElement::insertedInto(ContainerNode* insertionPoint)
@@ -350,7 +350,7 @@
     return attribute.name() == dataAttr || (attribute.name() == usemapAttr && attribute.value().string()[0] != '#') || HTMLPlugInImageElement::isURLAttribute(attribute);
 }
 
-const AtomicString& HTMLObjectElement::imageSourceURL() const
+const AtomicString HTMLObjectElement::imageSourceURL() const
 {
     return getAttribute(dataAttr);
 }
@@ -360,7 +360,7 @@
 {
     // This can happen inside of attach() in the middle of a recalcStyle so we need to
     // reattach synchronously here.
-    if (document()->inStyleRecalc())
+    if (document().inStyleRecalc())
         reattach();
     else
         lazyReattach();
@@ -437,14 +437,14 @@
             isNamedItem = false;
         child = child->nextSibling();
     }
-    if (isNamedItem != wasNamedItem && document()->isHTMLDocument()) {
-        HTMLDocument* document = toHTMLDocument(this->document());
+    if (isNamedItem != wasNamedItem && document().isHTMLDocument()) {
+        HTMLDocument& document = toHTMLDocument(this->document());
         if (isNamedItem) {
-            document->addNamedItem(getNameAttribute());
-            document->addExtraNamedItem(getIdAttribute());
+            document.addNamedItem(getNameAttribute());
+            document.addExtraNamedItem(getIdAttribute());
         } else {
-            document->removeNamedItem(getNameAttribute());
-            document->removeExtraNamedItem(getIdAttribute());
+            document.removeNamedItem(getNameAttribute());
+            document.removeExtraNamedItem(getIdAttribute());
         }
     }
     m_docNamedItem = isNamedItem;
@@ -473,13 +473,13 @@
 {
     HTMLPlugInImageElement::addSubresourceAttributeURLs(urls);
 
-    addSubresourceURL(urls, document()->completeURL(getAttribute(dataAttr)));
+    addSubresourceURL(urls, document().completeURL(getAttribute(dataAttr)));
 
     // FIXME: Passing a string that starts with "#" to the completeURL function does
     // not seem like it would work. The image element has similar but not identical code.
     const AtomicString& useMap = getAttribute(usemapAttr);
     if (useMap.startsWith('#'))
-        addSubresourceURL(urls, document()->completeURL(useMap));
+        addSubresourceURL(urls, document().completeURL(useMap));
 }
 
 void HTMLObjectElement::didMoveToNewDocument(Document* oldDocument)
diff --git a/Source/core/html/HTMLObjectElement.h b/Source/core/html/HTMLObjectElement.h
index 1e28504..99a12ba 100644
--- a/Source/core/html/HTMLObjectElement.h
+++ b/Source/core/html/HTMLObjectElement.h
@@ -32,7 +32,7 @@
 
 class HTMLObjectElement FINAL : public HTMLPlugInImageElement, public FormAssociatedElement {
 public:
-    static PassRefPtr<HTMLObjectElement> create(const QualifiedName&, Document*, HTMLFormElement*, bool createdByParser);
+    static PassRefPtr<HTMLObjectElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
     virtual ~HTMLObjectElement();
 
     bool isDocNamedItem() const { return m_docNamedItem; }
@@ -42,7 +42,7 @@
     bool containsJavaApplet() const;
 
     virtual bool useFallbackContent() const { return m_useFallbackContent; }
-    void renderFallbackContent();
+    virtual void renderFallbackContent() OVERRIDE;
 
     // Implementations of FormAssociatedElement
     HTMLFormElement* form() const { return FormAssociatedElement::form(); }
@@ -52,6 +52,8 @@
     virtual bool isEnumeratable() const { return true; }
     virtual bool appendFormData(FormDataList&, bool);
 
+    virtual bool isObjectElement() const OVERRIDE { return true; }
+
     // Implementations of constraint validation API.
     // Note that the object elements are always barred from constraint validation.
     virtual String validationMessage() const OVERRIDE { return String(); }
@@ -64,7 +66,7 @@
     virtual bool canContainRangeEndPoint() const { return useFallbackContent(); }
 
 private:
-    HTMLObjectElement(const QualifiedName&, Document*, HTMLFormElement*, bool createdByParser);
+    HTMLObjectElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -73,13 +75,13 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
     virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
 
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
-    virtual const AtomicString& imageSourceURL() const OVERRIDE;
+    virtual const AtomicString imageSourceURL() const OVERRIDE;
 
     virtual RenderWidget* existingRenderWidget() const OVERRIDE;
 
@@ -117,6 +119,16 @@
     return static_cast<HTMLObjectElement*>(node);
 }
 
+inline const HTMLObjectElement* toHTMLObjectElement(const FormAssociatedElement* element)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!element || !element->isFormControlElement());
+    const HTMLObjectElement* objectElement = static_cast<const HTMLObjectElement*>(element);
+    // We need to assert after the cast because FormAssociatedElement doesn't
+    // have hasTagName.
+    ASSERT_WITH_SECURITY_IMPLICATION(!objectElement || objectElement->hasTagName(HTMLNames::objectTag));
+    return objectElement;
+}
+
 }
 
 #endif
diff --git a/Source/core/html/HTMLOptGroupElement.cpp b/Source/core/html/HTMLOptGroupElement.cpp
index e88a4fd..e7823e2 100644
--- a/Source/core/html/HTMLOptGroupElement.cpp
+++ b/Source/core/html/HTMLOptGroupElement.cpp
@@ -35,7 +35,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLOptGroupElement::HTMLOptGroupElement(const QualifiedName& tagName, Document* document)
+inline HTMLOptGroupElement::HTMLOptGroupElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(optgroupTag));
@@ -43,7 +43,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLOptGroupElement> HTMLOptGroupElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLOptGroupElement> HTMLOptGroupElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLOptGroupElement(tagName, document));
 }
@@ -125,7 +125,7 @@
 
 String HTMLOptGroupElement::groupLabelText() const
 {
-    String itemText = document()->displayStringModifiedByEncoding(getAttribute(labelAttr));
+    String itemText = document().displayStringModifiedByEncoding(getAttribute(labelAttr));
 
     // In WinIE, leading and trailing whitespace is ignored in options and optgroups. We match this behavior.
     itemText = itemText.stripWhiteSpace();
diff --git a/Source/core/html/HTMLOptGroupElement.h b/Source/core/html/HTMLOptGroupElement.h
index 116763e..b759218 100644
--- a/Source/core/html/HTMLOptGroupElement.h
+++ b/Source/core/html/HTMLOptGroupElement.h
@@ -32,7 +32,7 @@
 
 class HTMLOptGroupElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLOptGroupElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLOptGroupElement> create(const QualifiedName&, Document&);
 
     virtual bool isDisabledFormControl() const OVERRIDE;
     HTMLSelectElement* ownerSelectElement() const;
@@ -40,12 +40,12 @@
     String groupLabelText() const;
 
 private:
-    HTMLOptGroupElement(const QualifiedName&, Document*);
+    HTMLOptGroupElement(const QualifiedName&, Document&);
 
     virtual const AtomicString& formControlType() const;
     virtual bool rendererIsFocusable() const OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
 
diff --git a/Source/core/html/HTMLOptionElement.cpp b/Source/core/html/HTMLOptionElement.cpp
index 9bb2250..3642f40 100644
--- a/Source/core/html/HTMLOptionElement.cpp
+++ b/Source/core/html/HTMLOptionElement.cpp
@@ -46,7 +46,7 @@
 
 using namespace HTMLNames;
 
-HTMLOptionElement::HTMLOptionElement(const QualifiedName& tagName, Document* document)
+HTMLOptionElement::HTMLOptionElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_disabled(false)
     , m_isSelected(false)
@@ -56,17 +56,17 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLOptionElement> HTMLOptionElement::create(Document* document)
+PassRefPtr<HTMLOptionElement> HTMLOptionElement::create(Document& document)
 {
     return adoptRef(new HTMLOptionElement(optionTag, document));
 }
 
-PassRefPtr<HTMLOptionElement> HTMLOptionElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLOptionElement> HTMLOptionElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLOptionElement(tagName, document));
 }
 
-PassRefPtr<HTMLOptionElement> HTMLOptionElement::createForJSConstructor(Document* document, const String& data, const String& value,
+PassRefPtr<HTMLOptionElement> HTMLOptionElement::createForJSConstructor(Document& document, const String& data, const String& value,
     bool defaultSelected, bool selected, ExceptionState& es)
 {
     RefPtr<HTMLOptionElement> element = adoptRef(new HTMLOptionElement(optionTag, document));
@@ -110,11 +110,11 @@
 
 String HTMLOptionElement::text() const
 {
-    Document* document = this->document();
+    Document& document = this->document();
     String text;
 
     // WinIE does not use the label attribute, so as a quirk, we ignore it.
-    if (!document->inQuirksMode())
+    if (!document.inQuirksMode())
         text = fastGetAttribute(labelAttr);
 
     // FIXME: The following treats an element with the label attribute set to
@@ -125,7 +125,7 @@
 
     // FIXME: Is displayStringModifiedByEncoding helpful here?
     // If it's correct here, then isn't it needed in the value and label functions too?
-    return document->displayStringModifiedByEncoding(text).stripWhiteSpace(isHTMLSpace).simplifyWhiteSpace(isHTMLSpace);
+    return document.displayStringModifiedByEncoding(text).stripWhiteSpace(isHTMLSpace).simplifyWhiteSpace(isHTMLSpace);
 }
 
 void HTMLOptionElement::setText(const String &text, ExceptionState& es)
@@ -268,7 +268,7 @@
 {
     for (ContainerNode* parent = parentNode(); parent ; parent = parent->parentNode()) {
         if (parent->hasTagName(datalistTag))
-            return static_cast<HTMLDataListElement*>(parent);
+            return toHTMLDataListElement(parent);
     }
     return 0;
 }
@@ -316,7 +316,7 @@
     return m_style;
 }
 
-void HTMLOptionElement::didRecalcStyle(StyleChange)
+void HTMLOptionElement::didRecalcStyle(StyleRecalcChange)
 {
     // FIXME: This is nasty, we ask our owner select to repaint even if the new
     // style is exactly the same.
diff --git a/Source/core/html/HTMLOptionElement.h b/Source/core/html/HTMLOptionElement.h
index f1cb609..c2e55a3 100644
--- a/Source/core/html/HTMLOptionElement.h
+++ b/Source/core/html/HTMLOptionElement.h
@@ -35,9 +35,9 @@
 
 class HTMLOptionElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLOptionElement> create(Document*);
-    static PassRefPtr<HTMLOptionElement> create(const QualifiedName&, Document*);
-    static PassRefPtr<HTMLOptionElement> createForJSConstructor(Document*, const String& data, const String& value,
+    static PassRefPtr<HTMLOptionElement> create(Document&);
+    static PassRefPtr<HTMLOptionElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLOptionElement> createForJSConstructor(Document&, const String& data, const String& value,
         bool defaultSelected, bool selected, ExceptionState&);
 
     virtual String text() const;
@@ -66,10 +66,10 @@
     void setSelectedState(bool);
 
 private:
-    HTMLOptionElement(const QualifiedName&, Document*);
+    HTMLOptionElement(const QualifiedName&, Document&);
 
     virtual bool rendererIsFocusable() const OVERRIDE;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
 
@@ -85,7 +85,7 @@
     virtual RenderStyle* nonRendererStyle() const OVERRIDE;
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
 
-    void didRecalcStyle(StyleChange) OVERRIDE;
+    void didRecalcStyle(StyleRecalcChange) OVERRIDE;
 
     String collectOptionInnerText() const;
 
diff --git a/Source/core/html/HTMLOptionsCollection.idl b/Source/core/html/HTMLOptionsCollection.idl
index 8e5a3b9..aa47617 100644
--- a/Source/core/html/HTMLOptionsCollection.idl
+++ b/Source/core/html/HTMLOptionsCollection.idl
@@ -33,7 +33,7 @@
 
     [Custom, RaisesException] void add([Default=Undefined] optional HTMLOptionElement option,
                       optional unsigned long index);
-    void remove([Default=Undefined] optional unsigned long index);
+    void remove(unsigned long index);
     void remove(HTMLOptionElement option); // Non standard.
 };
 
diff --git a/Source/core/html/HTMLOutputElement.cpp b/Source/core/html/HTMLOutputElement.cpp
index ab75b43..4990e99 100644
--- a/Source/core/html/HTMLOutputElement.cpp
+++ b/Source/core/html/HTMLOutputElement.cpp
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-inline HTMLOutputElement::HTMLOutputElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+inline HTMLOutputElement::HTMLOutputElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
     : HTMLFormControlElement(tagName, document, form)
     , m_isDefaultValueMode(true)
     , m_isSetTextContentInProgress(false)
@@ -46,7 +46,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLOutputElement> HTMLOutputElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+PassRefPtr<HTMLOutputElement> HTMLOutputElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
 {
     return adoptRef(new HTMLOutputElement(tagName, document, form));
 }
diff --git a/Source/core/html/HTMLOutputElement.h b/Source/core/html/HTMLOutputElement.h
index d0338d6..9f198f4 100644
--- a/Source/core/html/HTMLOutputElement.h
+++ b/Source/core/html/HTMLOutputElement.h
@@ -31,14 +31,14 @@
 #ifndef HTMLOutputElement_h
 #define HTMLOutputElement_h
 
-#include "core/html/DOMSettableTokenList.h"
+#include "core/dom/DOMSettableTokenList.h"
 #include "core/html/HTMLFormControlElement.h"
 
 namespace WebCore {
 
 class HTMLOutputElement FINAL : public HTMLFormControlElement {
 public:
-    static PassRefPtr<HTMLOutputElement> create(const QualifiedName&, Document*, HTMLFormElement*);
+    static PassRefPtr<HTMLOutputElement> create(const QualifiedName&, Document&, HTMLFormElement*);
 
     virtual bool willValidate() const { return false; }
 
@@ -52,7 +52,7 @@
     virtual bool canContainRangeEndPoint() const { return false; }
 
 private:
-    HTMLOutputElement(const QualifiedName&, Document*, HTMLFormElement*);
+    HTMLOutputElement(const QualifiedName&, Document&, HTMLFormElement*);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual const AtomicString& formControlType() const;
diff --git a/Source/core/html/HTMLParagraphElement.cpp b/Source/core/html/HTMLParagraphElement.cpp
index 52dcae9..626e8d5 100644
--- a/Source/core/html/HTMLParagraphElement.cpp
+++ b/Source/core/html/HTMLParagraphElement.cpp
@@ -31,19 +31,19 @@
 
 using namespace HTMLNames;
 
-inline HTMLParagraphElement::HTMLParagraphElement(const QualifiedName& tagName, Document* document)
+inline HTMLParagraphElement::HTMLParagraphElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(pTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLParagraphElement> HTMLParagraphElement::create(Document* document)
+PassRefPtr<HTMLParagraphElement> HTMLParagraphElement::create(Document& document)
 {
     return adoptRef(new HTMLParagraphElement(pTag, document));
 }
 
-PassRefPtr<HTMLParagraphElement> HTMLParagraphElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLParagraphElement> HTMLParagraphElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLParagraphElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLParagraphElement.h b/Source/core/html/HTMLParagraphElement.h
index fd0110b..9e80fda 100644
--- a/Source/core/html/HTMLParagraphElement.h
+++ b/Source/core/html/HTMLParagraphElement.h
@@ -29,11 +29,11 @@
 
 class HTMLParagraphElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLParagraphElement> create(Document*);
-    static PassRefPtr<HTMLParagraphElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLParagraphElement> create(Document&);
+    static PassRefPtr<HTMLParagraphElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLParagraphElement(const QualifiedName&, Document*);
+    HTMLParagraphElement(const QualifiedName&, Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLParamElement.cpp b/Source/core/html/HTMLParamElement.cpp
index d5ddc38..cf55848 100644
--- a/Source/core/html/HTMLParamElement.cpp
+++ b/Source/core/html/HTMLParamElement.cpp
@@ -31,14 +31,14 @@
 
 using namespace HTMLNames;
 
-inline HTMLParamElement::HTMLParamElement(const QualifiedName& tagName, Document* document)
+inline HTMLParamElement::HTMLParamElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(paramTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLParamElement> HTMLParamElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLParamElement> HTMLParamElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLParamElement(tagName, document));
 }
@@ -47,7 +47,7 @@
 {
     if (hasName())
         return getNameAttribute();
-    return document()->isHTMLDocument() ? emptyAtom : getIdAttribute();
+    return document().isHTMLDocument() ? emptyAtom : getIdAttribute();
 }
 
 String HTMLParamElement::value() const
@@ -74,7 +74,7 @@
     if (!isURLParameter(name()))
         return;
 
-    addSubresourceURL(urls, document()->completeURL(value()));
+    addSubresourceURL(urls, document().completeURL(value()));
 }
 
 }
diff --git a/Source/core/html/HTMLParamElement.h b/Source/core/html/HTMLParamElement.h
index b855d84..55953fe 100644
--- a/Source/core/html/HTMLParamElement.h
+++ b/Source/core/html/HTMLParamElement.h
@@ -29,7 +29,7 @@
 
 class HTMLParamElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLParamElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLParamElement> create(const QualifiedName&, Document&);
 
     String name() const;
     String value() const;
@@ -37,13 +37,19 @@
     static bool isURLParameter(const String&);
 
 private:
-    HTMLParamElement(const QualifiedName&, Document*);
+    HTMLParamElement(const QualifiedName&, Document&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 
     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
 };
 
+inline HTMLParamElement* toHTMLParamElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::paramTag));
+    return static_cast<HTMLParamElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/html/HTMLPlugInElement.cpp b/Source/core/html/HTMLPlugInElement.cpp
index 8d23225..c6ed4a5 100644
--- a/Source/core/html/HTMLPlugInElement.cpp
+++ b/Source/core/html/HTMLPlugInElement.cpp
@@ -42,7 +42,7 @@
 
 using namespace HTMLNames;
 
-HTMLPlugInElement::HTMLPlugInElement(const QualifiedName& tagName, Document* doc)
+HTMLPlugInElement::HTMLPlugInElement(const QualifiedName& tagName, Document& doc)
     : HTMLFrameOwnerElement(tagName, doc)
     , m_NPObject(0)
     , m_isCapturingMouseEvents(false)
@@ -63,7 +63,7 @@
 
 bool HTMLPlugInElement::canProcessDrag() const
 {
-    const PluginView* plugin = pluginWidget() && pluginWidget()->isPluginView() ? static_cast<const PluginView*>(pluginWidget()) : 0;
+    const PluginView* plugin = pluginWidget() && pluginWidget()->isPluginView() ? toPluginView(pluginWidget()) : 0;
     return plugin ? plugin->canProcessDrag() : false;
 }
 
@@ -93,7 +93,7 @@
     m_instance.clear();
 
     if (m_isCapturingMouseEvents) {
-        if (Frame* frame = document()->frame())
+        if (Frame* frame = document().frame())
             frame->eventHandler()->setCapturingMouseEventsNode(0);
         m_isCapturingMouseEvents = false;
     }
@@ -113,7 +113,7 @@
 
 PassScriptInstance HTMLPlugInElement::getInstance()
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return 0;
 
@@ -211,16 +211,16 @@
 
 RenderWidget* HTMLPlugInElement::renderWidgetForJSBindings() const
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     return existingRenderWidget();
 }
 
 bool HTMLPlugInElement::isKeyboardFocusable() const
 {
-    if (!document()->page())
+    if (!document().page())
         return false;
 
-    const PluginView* plugin = pluginWidget() && pluginWidget()->isPluginView() ? static_cast<const PluginView*>(pluginWidget()) : 0;
+    const PluginView* plugin = pluginWidget() && pluginWidget()->isPluginView() ? toPluginView(pluginWidget()) : 0;
     if (plugin)
         return plugin->supportsKeyboardFocus();
 
@@ -244,9 +244,9 @@
 
 NPObject* HTMLPlugInElement::getNPObject()
 {
-    ASSERT(document()->frame());
+    ASSERT(document().frame());
     if (!m_NPObject)
-        m_NPObject = document()->frame()->script()->createScriptObjectForPluginElement(this);
+        m_NPObject = document().frame()->script()->createScriptObjectForPluginElement(this);
     return m_NPObject;
 }
 
diff --git a/Source/core/html/HTMLPlugInElement.h b/Source/core/html/HTMLPlugInElement.h
index 1601cdb..0647dfd 100644
--- a/Source/core/html/HTMLPlugInElement.h
+++ b/Source/core/html/HTMLPlugInElement.h
@@ -69,7 +69,7 @@
     virtual void removeAllEventListeners() OVERRIDE FINAL;
 
 protected:
-    HTMLPlugInElement(const QualifiedName& tagName, Document*);
+    HTMLPlugInElement(const QualifiedName& tagName, Document&);
 
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLPlugInImageElement.cpp b/Source/core/html/HTMLPlugInImageElement.cpp
index b1ed56d..51e2342 100644
--- a/Source/core/html/HTMLPlugInImageElement.cpp
+++ b/Source/core/html/HTMLPlugInImageElement.cpp
@@ -22,6 +22,7 @@
 #include "core/html/HTMLPlugInImageElement.h"
 
 #include "bindings/v8/ScriptController.h"
+#include "core/dom/PostAttachCallbacks.h"
 #include "core/html/HTMLImageLoader.h"
 #include "core/html/PluginDocument.h"
 #include "core/loader/FrameLoader.h"
@@ -52,7 +53,7 @@
 static const float sizingFullPageAreaRatioThreshold = 0.96;
 static const float autostartSoonAfterUserGestureThreshold = 5.0;
 
-HTMLPlugInImageElement::HTMLPlugInImageElement(const QualifiedName& tagName, Document* document, bool createdByParser, PreferPlugInsForImagesOption preferPlugInsForImagesOption)
+HTMLPlugInImageElement::HTMLPlugInImageElement(const QualifiedName& tagName, Document& document, bool createdByParser, PreferPlugInsForImagesOption preferPlugInsForImagesOption)
     : HTMLPlugInElement(tagName, document)
     // m_needsWidgetUpdate(!createdByParser) allows HTMLObjectElement to delay
     // widget updates until after all children are parsed.  For HTMLEmbedElement
@@ -88,8 +89,8 @@
     if (m_serviceType.isEmpty() && protocolIs(m_url, "data"))
         m_serviceType = mimeTypeFromDataURL(m_url);
 
-    if (Frame* frame = document()->frame()) {
-        KURL completedURL = document()->completeURL(m_url);
+    if (Frame* frame = document().frame()) {
+        KURL completedURL = document().completeURL(m_url);
         return frame->loader()->client()->objectContentType(completedURL, m_serviceType, shouldPreferPlugInsForImages()) == ObjectContentImage;
     }
 
@@ -100,26 +101,25 @@
 // depending on <param> values.
 bool HTMLPlugInImageElement::allowedToLoadFrameURL(const String& url)
 {
-    KURL completeURL = document()->completeURL(url);
+    KURL completeURL = document().completeURL(url);
 
     if (contentFrame() && protocolIsJavaScript(completeURL)
-        && !document()->securityOrigin()->canAccess(contentDocument()->securityOrigin()))
+        && !document().securityOrigin()->canAccess(contentDocument()->securityOrigin()))
         return false;
 
-    return document()->frame()->isURLAllowed(completeURL);
+    return document().frame()->isURLAllowed(completeURL);
 }
 
 // We don't use m_url, or m_serviceType as they may not be the final values
 // that <object> uses depending on <param> values.
 bool HTMLPlugInImageElement::wouldLoadAsNetscapePlugin(const String& url, const String& serviceType)
 {
-    ASSERT(document());
-    ASSERT(document()->frame());
+    ASSERT(document().frame());
     KURL completedURL;
     if (!url.isEmpty())
-        completedURL = document()->completeURL(url);
+        completedURL = document().completeURL(url);
 
-    FrameLoader* frameLoader = document()->frame()->loader();
+    FrameLoader* frameLoader = document().frame()->loader();
     ASSERT(frameLoader);
     if (frameLoader->client()->objectContentType(completedURL, serviceType, shouldPreferPlugInsForImages()) == ObjectContentNetscapePlugin)
         return true;
@@ -143,7 +143,7 @@
     return new RenderEmbeddedObject(this);
 }
 
-void HTMLPlugInImageElement::willRecalcStyle(StyleChange)
+void HTMLPlugInImageElement::willRecalcStyle(StyleRecalcChange)
 {
     // FIXME: Why is this necessary?  Manual re-attach is almost always wrong.
     if (!useFallbackContent() && needsWidgetUpdate() && renderer() && !isImageType())
@@ -152,12 +152,10 @@
 
 void HTMLPlugInImageElement::attach(const AttachContext& context)
 {
-    PostAttachCallbackDisabler disabler(this);
-
     bool isImage = isImageType();
 
     if (!isImage)
-        queuePostAttachCallback(&HTMLPlugInImageElement::updateWidgetCallback, this);
+        PostAttachCallbacks::queueCallback(HTMLPlugInImageElement::updateWidgetCallback, this);
 
     HTMLPlugInElement::attach(context);
 
@@ -181,7 +179,7 @@
 
 void HTMLPlugInImageElement::updateWidgetIfNecessary()
 {
-    document()->updateStyleIfNeeded();
+    document().updateStyleIfNeeded();
 
     if (!needsWidgetUpdate() || useFallbackContent() || isImageType())
         return;
@@ -226,7 +224,7 @@
     if (!renderer)
         return false;
 
-    KURL completedURL = document()->completeURL(url);
+    KURL completedURL = document().completeURL(url);
 
     bool useFallback;
     if (shouldUsePlugin(completedURL, mimeType, renderer->hasFallbackContent(), useFallback)) {
@@ -242,7 +240,7 @@
 
 bool HTMLPlugInImageElement::loadPlugin(const KURL& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback)
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
 
     if (!frame->loader()->allowPlugins(AboutToInstantiatePlugin))
         return false;
@@ -261,7 +259,7 @@
     m_loadedUrl = url;
 
     IntSize contentSize = roundedIntSize(LayoutSize(renderer->contentWidth(), renderer->contentHeight()));
-    bool loadManually = document()->isPluginDocument() && !frame->loader()->containsPlugins() && toPluginDocument(document())->shouldLoadPluginManually();
+    bool loadManually = document().isPluginDocument() && !frame->loader()->containsPlugins() && toPluginDocument(document()).shouldLoadPluginManually();
     RefPtr<Widget> widget = frame->loader()->client()->createPlugin(contentSize, this, url, paramNames, paramValues, mimeType, loadManually);
 
     if (!widget) {
@@ -280,14 +278,14 @@
 {
     // Allow other plug-ins to win over QuickTime because if the user has installed a plug-in that
     // can handle TIFF (which QuickTime can also handle) they probably intended to override QT.
-    if (document()->frame()->page() && (mimeType == "image/tiff" || mimeType == "image/tif" || mimeType == "image/x-tiff")) {
-        const PluginData* pluginData = document()->frame()->page()->pluginData();
+    if (document().frame()->page() && (mimeType == "image/tiff" || mimeType == "image/tif" || mimeType == "image/x-tiff")) {
+        const PluginData* pluginData = document().frame()->page()->pluginData();
         String pluginName = pluginData ? pluginData->pluginNameForMimeType(mimeType) : String();
         if (!pluginName.isEmpty() && !pluginName.contains("QuickTime", false))
             return true;
     }
 
-    ObjectContentType objectType = document()->frame()->loader()->client()->objectContentType(url, mimeType, shouldPreferPlugInsForImages());
+    ObjectContentType objectType = document().frame()->loader()->client()->objectContentType(url, mimeType, shouldPreferPlugInsForImages());
     // If an object's content can't be handled and it has no fallback, let
     // it be handled as a plugin to show the broken plugin icon.
     useFallback = objectType == ObjectContentNone && hasFallback;
@@ -297,7 +295,7 @@
 
 bool HTMLPlugInImageElement::pluginIsLoadable(const KURL& url, const String& mimeType)
 {
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     Settings* settings = frame->settings();
     if (!settings)
         return false;
@@ -307,24 +305,24 @@
             return false;
     }
 
-    if (document()->isSandboxed(SandboxPlugins))
+    if (document().isSandboxed(SandboxPlugins))
         return false;
 
-    if (!document()->securityOrigin()->canDisplay(url)) {
+    if (!document().securityOrigin()->canDisplay(url)) {
         FrameLoader::reportLocalLoadFailed(frame, url.string());
         return false;
     }
 
-    String declaredMimeType = document()->isPluginDocument() && document()->ownerElement() ?
-        document()->ownerElement()->fastGetAttribute(HTMLNames::typeAttr) :
+    String declaredMimeType = document().isPluginDocument() && document().ownerElement() ?
+        document().ownerElement()->fastGetAttribute(HTMLNames::typeAttr) :
         fastGetAttribute(HTMLNames::typeAttr);
-    if (!document()->contentSecurityPolicy()->allowObjectFromSource(url)
-        || !document()->contentSecurityPolicy()->allowPluginType(mimeType, declaredMimeType, url)) {
+    if (!document().contentSecurityPolicy()->allowObjectFromSource(url)
+        || !document().contentSecurityPolicy()->allowPluginType(mimeType, declaredMimeType, url)) {
         renderEmbeddedObject()->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy);
         return false;
     }
 
-    if (frame->loader() && !frame->loader()->mixedContentChecker()->canRunInsecureContent(document()->securityOrigin(), url))
+    if (frame->loader() && !frame->loader()->mixedContentChecker()->canRunInsecureContent(document().securityOrigin(), url))
         return false;
     return true;
 }
diff --git a/Source/core/html/HTMLPlugInImageElement.h b/Source/core/html/HTMLPlugInImageElement.h
index 65d11e0..f994810 100644
--- a/Source/core/html/HTMLPlugInImageElement.h
+++ b/Source/core/html/HTMLPlugInImageElement.h
@@ -75,7 +75,7 @@
     void setNeedsWidgetUpdate(bool needsWidgetUpdate) { m_needsWidgetUpdate = needsWidgetUpdate; }
 
 protected:
-    HTMLPlugInImageElement(const QualifiedName& tagName, Document*, bool createdByParser, PreferPlugInsForImagesOption);
+    HTMLPlugInImageElement(const QualifiedName& tagName, Document&, bool createdByParser, PreferPlugInsForImagesOption);
 
     bool isImageType();
 
@@ -98,7 +98,7 @@
 
 private:
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual void willRecalcStyle(StyleChange) OVERRIDE FINAL;
+    virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE FINAL;
 
     virtual void finishParsingChildren();
 
diff --git a/Source/core/html/HTMLPreElement.cpp b/Source/core/html/HTMLPreElement.cpp
index 052b274..830f015 100644
--- a/Source/core/html/HTMLPreElement.cpp
+++ b/Source/core/html/HTMLPreElement.cpp
@@ -32,13 +32,13 @@
 
 using namespace HTMLNames;
 
-inline HTMLPreElement::HTMLPreElement(const QualifiedName& tagName, Document* document)
+inline HTMLPreElement::HTMLPreElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLPreElement> HTMLPreElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLPreElement> HTMLPreElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLPreElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLPreElement.h b/Source/core/html/HTMLPreElement.h
index 4c544d9..408475f4 100644
--- a/Source/core/html/HTMLPreElement.h
+++ b/Source/core/html/HTMLPreElement.h
@@ -29,10 +29,10 @@
 
 class HTMLPreElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLPreElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLPreElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLPreElement(const QualifiedName&, Document*);
+    HTMLPreElement(const QualifiedName&, Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLProgressElement.cpp b/Source/core/html/HTMLProgressElement.cpp
index ccf931f..ded3d07 100644
--- a/Source/core/html/HTMLProgressElement.cpp
+++ b/Source/core/html/HTMLProgressElement.cpp
@@ -26,7 +26,6 @@
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/ProgressShadowElement.h"
@@ -39,7 +38,7 @@
 const double HTMLProgressElement::IndeterminatePosition = -1;
 const double HTMLProgressElement::InvalidPosition = -2;
 
-HTMLProgressElement::HTMLProgressElement(const QualifiedName& tagName, Document* document)
+HTMLProgressElement::HTMLProgressElement(const QualifiedName& tagName, Document& document)
     : LabelableElement(tagName, document)
     , m_value(0)
 {
@@ -51,7 +50,7 @@
 {
 }
 
-PassRefPtr<HTMLProgressElement> HTMLProgressElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLProgressElement> HTMLProgressElement::create(const QualifiedName& tagName, Document& document)
 {
     RefPtr<HTMLProgressElement> progress = adoptRef(new HTMLProgressElement(tagName, document));
     progress->ensureUserAgentShadowRoot();
@@ -151,11 +150,14 @@
     ASSERT(!m_value);
 
     RefPtr<ProgressInnerElement> inner = ProgressInnerElement::create(document());
+    inner->setPart(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
     root->appendChild(inner);
 
     RefPtr<ProgressBarElement> bar = ProgressBarElement::create(document());
+    bar->setPart(AtomicString("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
     RefPtr<ProgressValueElement> value = ProgressValueElement::create(document());
     m_value = value.get();
+    m_value->setPart(AtomicString("-webkit-progress-value", AtomicString::ConstructFromLiteral));
     m_value->setWidthPercentage(HTMLProgressElement::IndeterminatePosition * 100);
     bar->appendChild(m_value);
 
diff --git a/Source/core/html/HTMLProgressElement.h b/Source/core/html/HTMLProgressElement.h
index 5a4d6f1..e9f624e 100644
--- a/Source/core/html/HTMLProgressElement.h
+++ b/Source/core/html/HTMLProgressElement.h
@@ -34,7 +34,7 @@
     static const double IndeterminatePosition;
     static const double InvalidPosition;
 
-    static PassRefPtr<HTMLProgressElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLProgressElement> create(const QualifiedName&, Document&);
 
     double value() const;
     void setValue(double, ExceptionState&);
@@ -47,7 +47,7 @@
     virtual bool canContainRangeEndPoint() const { return false; }
 
 private:
-    HTMLProgressElement(const QualifiedName&, Document*);
+    HTMLProgressElement(const QualifiedName&, Document&);
     virtual ~HTMLProgressElement();
 
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
diff --git a/Source/core/html/HTMLQuoteElement.cpp b/Source/core/html/HTMLQuoteElement.cpp
index 1b1563c..47f1cd9 100644
--- a/Source/core/html/HTMLQuoteElement.cpp
+++ b/Source/core/html/HTMLQuoteElement.cpp
@@ -31,14 +31,14 @@
 
 using namespace HTMLNames;
 
-inline HTMLQuoteElement::HTMLQuoteElement(const QualifiedName& tagName, Document* document)
+inline HTMLQuoteElement::HTMLQuoteElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(qTag) || hasTagName(blockquoteTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLQuoteElement> HTMLQuoteElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLQuoteElement> HTMLQuoteElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLQuoteElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLQuoteElement.h b/Source/core/html/HTMLQuoteElement.h
index 4664872..bfdc9ee 100644
--- a/Source/core/html/HTMLQuoteElement.h
+++ b/Source/core/html/HTMLQuoteElement.h
@@ -31,10 +31,10 @@
 
 class HTMLQuoteElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLQuoteElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLQuoteElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLQuoteElement(const QualifiedName&, Document*);
+    HTMLQuoteElement(const QualifiedName&, Document&);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
 };
diff --git a/Source/core/html/HTMLScriptElement.cpp b/Source/core/html/HTMLScriptElement.cpp
index 846d27b..4f59a67 100644
--- a/Source/core/html/HTMLScriptElement.cpp
+++ b/Source/core/html/HTMLScriptElement.cpp
@@ -37,7 +37,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLScriptElement::HTMLScriptElement(const QualifiedName& tagName, Document* document, bool wasInsertedByParser, bool alreadyStarted)
+inline HTMLScriptElement::HTMLScriptElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser, bool alreadyStarted)
     : HTMLElement(tagName, document)
     , m_loader(ScriptLoader::create(this, wasInsertedByParser, alreadyStarted))
 {
@@ -45,7 +45,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLScriptElement> HTMLScriptElement::create(const QualifiedName& tagName, Document* document, bool wasInsertedByParser, bool alreadyStarted)
+PassRefPtr<HTMLScriptElement> HTMLScriptElement::create(const QualifiedName& tagName, Document& document, bool wasInsertedByParser, bool alreadyStarted)
 {
     return adoptRef(new HTMLScriptElement(tagName, document, wasInsertedByParser, alreadyStarted));
 }
@@ -76,8 +76,12 @@
 Node::InsertionNotificationRequest HTMLScriptElement::insertedInto(ContainerNode* insertionPoint)
 {
     HTMLElement::insertedInto(insertionPoint);
-    m_loader->insertedInto(insertionPoint);
-    return InsertionDone;
+    return InsertionShouldCallDidNotifySubtreeInsertions;
+}
+
+void HTMLScriptElement::didNotifySubtreeInsertionsToDocument()
+{
+    m_loader->didNotifySubtreeInsertionsToDocument();
 }
 
 void HTMLScriptElement::setText(const String &value)
@@ -90,7 +94,7 @@
     }
 
     removeChildren();
-    appendChild(document()->createTextNode(value.impl()), IGNORE_EXCEPTION);
+    appendChild(document().createTextNode(value.impl()), IGNORE_EXCEPTION);
 }
 
 void HTMLScriptElement::setAsync(bool async)
@@ -106,7 +110,7 @@
 
 KURL HTMLScriptElement::src() const
 {
-    return document()->completeURL(sourceAttributeValue());
+    return document().completeURL(sourceAttributeValue());
 }
 
 void HTMLScriptElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
diff --git a/Source/core/html/HTMLScriptElement.h b/Source/core/html/HTMLScriptElement.h
index 704b77e..3340cfd 100644
--- a/Source/core/html/HTMLScriptElement.h
+++ b/Source/core/html/HTMLScriptElement.h
@@ -33,7 +33,7 @@
 
 class HTMLScriptElement FINAL : public HTMLElement, public ScriptLoaderClient {
 public:
-    static PassRefPtr<HTMLScriptElement> create(const QualifiedName&, Document*, bool wasInsertedByParser, bool alreadyStarted = false);
+    static PassRefPtr<HTMLScriptElement> create(const QualifiedName&, Document&, bool wasInsertedByParser, bool alreadyStarted = false);
 
     String text() { return textFromChildren(); }
     void setText(const String&);
@@ -46,10 +46,11 @@
     ScriptLoader* loader() const { return m_loader.get(); }
 
 private:
-    HTMLScriptElement(const QualifiedName&, Document*, bool wasInsertedByParser, bool alreadyStarted);
+    HTMLScriptElement(const QualifiedName&, Document&, bool wasInsertedByParser, bool alreadyStarted);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
+    virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
diff --git a/Source/core/html/HTMLScriptElement.idl b/Source/core/html/HTMLScriptElement.idl
index cb8a909..ef68a4d 100644
--- a/Source/core/html/HTMLScriptElement.idl
+++ b/Source/core/html/HTMLScriptElement.idl
@@ -27,5 +27,5 @@
     [Reflect, URL] attribute DOMString src;
     [Reflect] attribute DOMString type;
     [Reflect] attribute DOMString crossOrigin;
-    [Reflect, EnabledAtRuntime=experimentalContentSecurityPolicyFeatures] attribute DOMString nonce;
+    [Reflect, EnabledAtRuntime=ExperimentalContentSecurityPolicyFeatures] attribute DOMString nonce;
 };
diff --git a/Source/core/html/HTMLSelectElement.cpp b/Source/core/html/HTMLSelectElement.cpp
index c516473..6107fc5 100644
--- a/Source/core/html/HTMLSelectElement.cpp
+++ b/Source/core/html/HTMLSelectElement.cpp
@@ -37,7 +37,6 @@
 #include "core/dom/EventNames.h"
 #include "core/dom/KeyboardEvent.h"
 #include "core/dom/MouseEvent.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/html/FormController.h"
 #include "core/html/FormDataList.h"
@@ -65,7 +64,7 @@
 // Upper limit agreed upon with representatives of Opera and Mozilla.
 static const unsigned maxSelectItems = 10000;
 
-HTMLSelectElement::HTMLSelectElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form, bool createdByParser)
+HTMLSelectElement::HTMLSelectElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
     : HTMLFormControlElementWithState(tagName, document, form)
     , m_typeAhead(this)
     , m_size(0)
@@ -82,12 +81,12 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(Document* document)
+PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(Document& document)
 {
     return adoptRef(new HTMLSelectElement(selectTag, document, 0, false));
 }
 
-PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
 {
     ASSERT(tagName.matches(selectTag));
     return adoptRef(new HTMLSelectElement(tagName, document, form, createdByParser));
@@ -335,12 +334,12 @@
     return new RenderListBox(this);
 }
 
-bool HTMLSelectElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool HTMLSelectElement::childShouldCreateRenderer(const Node& child) const
 {
-    if (!HTMLFormControlElementWithState::childShouldCreateRenderer(childContext))
+    if (!HTMLFormControlElementWithState::childShouldCreateRenderer(child))
         return false;
     if (!usesMenuList())
-        return childContext.node()->hasTagName(HTMLNames::optionTag) || isHTMLOptGroupElement(childContext.node());
+        return child.hasTagName(HTMLNames::optionTag) || isHTMLOptGroupElement(&child);
     return false;
 }
 
@@ -378,7 +377,7 @@
     setNeedsValidityCheck();
 
     if (renderer()) {
-        if (AXObjectCache* cache = renderer()->document()->existingAXObjectCache())
+        if (AXObjectCache* cache = renderer()->document().existingAXObjectCache())
             cache->childrenChanged(this);
     }
 }
@@ -446,7 +445,7 @@
 
     if (diff < 0) { // Add dummy elements.
         do {
-            RefPtr<Element> option = document()->createElement(optionTag, false);
+            RefPtr<Element> option = document().createElement(optionTag, false);
             ASSERT(option);
             add(toHTMLElement(option.get()), 0, es);
             if (es.hadException())
@@ -721,7 +720,7 @@
         invalidateSelectedItems();
 
     if (renderer()) {
-        if (AXObjectCache* cache = renderer()->document()->existingAXObjectCache())
+        if (AXObjectCache* cache = renderer()->document().existingAXObjectCache())
             cache->childrenChanged(this);
     }
 }
@@ -1059,13 +1058,13 @@
     setNeedsValidityCheck();
 }
 
-#if !OS(WINDOWS)
+#if !OS(WIN)
 bool HTMLSelectElement::platformHandleKeydownEvent(KeyboardEvent* event)
 {
     if (!RenderTheme::theme().popsMenuByArrowKeys())
         return false;
 
-    if (!isSpatialNavigationEnabled(document()->frame())) {
+    if (!isSpatialNavigationEnabled(document().frame())) {
         if (event->keyIdentifier() == "Down" || event->keyIdentifier() == "Up") {
             focus();
             // Calling focus() may cause us to lose our renderer. Return true so
@@ -1104,7 +1103,7 @@
         // When using spatial navigation, we want to be able to navigate away
         // from the select element when the user hits any of the arrow keys,
         // instead of changing the selection.
-        if (isSpatialNavigationEnabled(document()->frame())) {
+        if (isSpatialNavigationEnabled(document().frame())) {
             if (!m_activeSelectionState)
                 return;
         }
@@ -1145,7 +1144,7 @@
         int keyCode = toKeyboardEvent(event)->keyCode();
         bool handled = false;
 
-        if (keyCode == ' ' && isSpatialNavigationEnabled(document()->frame())) {
+        if (keyCode == ' ' && isSpatialNavigationEnabled(document().frame())) {
             // Use space to toggle arrow key handling for selection change or spatial navigation.
             m_activeSelectionState = !m_activeSelectionState;
             event->setDefaultHandled();
@@ -1292,13 +1291,13 @@
         int listIndex = toRenderListBox(renderer())->listIndexAtOffset(toIntSize(localOffset));
         if (listIndex >= 0) {
             if (!isDisabledFormControl()) {
-#if OS(DARWIN)
+#if OS(MACOSX)
                 updateSelectedState(listIndex, mouseEvent->metaKey(), mouseEvent->shiftKey());
 #else
                 updateSelectedState(listIndex, mouseEvent->ctrlKey(), mouseEvent->shiftKey());
 #endif
             }
-            if (Frame* frame = document()->frame())
+            if (Frame* frame = document().frame())
                 frame->eventHandler()->setMouseDownMayStartAutoscroll();
 
             event->setDefaultHandled();
@@ -1383,7 +1382,7 @@
             handled = true;
         }
 
-        if (isSpatialNavigationEnabled(document()->frame()))
+        if (isSpatialNavigationEnabled(document().frame()))
             // Check if the selection moves to the boundary.
             if (keyIdentifier == "Left" || keyIdentifier == "Right" || ((keyIdentifier == "Down" || keyIdentifier == "Up") && endIndex == m_activeSelectionEndIndex))
                 return;
@@ -1397,7 +1396,7 @@
             ASSERT_UNUSED(listItems, !listItems.size() || static_cast<size_t>(endIndex) < listItems.size());
             setActiveSelectionEndIndex(endIndex);
 
-            bool selectNewItem = !m_multiple || toKeyboardEvent(event)->shiftKey() || !isSpatialNavigationEnabled(document()->frame());
+            bool selectNewItem = !m_multiple || toKeyboardEvent(event)->shiftKey() || !isSpatialNavigationEnabled(document().frame());
             if (selectNewItem)
                 m_activeSelectionState = true;
             // If the anchor is unitialized, or if we're going to deselect all
@@ -1427,7 +1426,7 @@
             if (form())
                 form()->submitImplicitly(event, false);
             event->setDefaultHandled();
-        } else if (m_multiple && keyCode == ' ' && isSpatialNavigationEnabled(document()->frame())) {
+        } else if (m_multiple && keyCode == ' ' && isSpatialNavigationEnabled(document().frame())) {
             // Use space to toggle selection change.
             m_activeSelectionState = !m_activeSelectionState;
             updateSelectedState(listToOptionIndex(m_activeSelectionEndIndex), true /*multi*/, false /*shift*/);
diff --git a/Source/core/html/HTMLSelectElement.h b/Source/core/html/HTMLSelectElement.h
index 33d419a..74fb89c 100644
--- a/Source/core/html/HTMLSelectElement.h
+++ b/Source/core/html/HTMLSelectElement.h
@@ -39,8 +39,8 @@
 
 class HTMLSelectElement FINAL : public HTMLFormControlElementWithState, public TypeAheadDataSource {
 public:
-    static PassRefPtr<HTMLSelectElement> create(Document*);
-    static PassRefPtr<HTMLSelectElement> create(const QualifiedName&, Document*, HTMLFormElement*, bool createdByParser);
+    static PassRefPtr<HTMLSelectElement> create(Document&);
+    static PassRefPtr<HTMLSelectElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
 
     int selectedIndex() const;
     void setSelectedIndex(int);
@@ -115,7 +115,7 @@
     bool anonymousIndexedSetterRemove(unsigned, ExceptionState&);
 
 protected:
-    HTMLSelectElement(const QualifiedName&, Document*, HTMLFormElement*, bool createdByParser);
+    HTMLSelectElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
 
 private:
     virtual const AtomicString& formControlType() const;
@@ -136,7 +136,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
 
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
+    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle *);
     virtual bool appendFormData(FormDataList&, bool);
 
diff --git a/Source/core/html/HTMLSelectElementWin.cpp b/Source/core/html/HTMLSelectElementWin.cpp
index 4b0b944..1c4be11 100644
--- a/Source/core/html/HTMLSelectElementWin.cpp
+++ b/Source/core/html/HTMLSelectElementWin.cpp
@@ -26,7 +26,7 @@
 #include "config.h"
 #include "core/html/HTMLSelectElement.h"
 
-#if OS(WINDOWS)
+#if OS(WIN)
 
 #include "core/dom/Element.h"
 #include "core/dom/KeyboardEvent.h"
diff --git a/Source/core/html/HTMLSourceElement.cpp b/Source/core/html/HTMLSourceElement.cpp
index 48e15eb..733ac99 100644
--- a/Source/core/html/HTMLSourceElement.cpp
+++ b/Source/core/html/HTMLSourceElement.cpp
@@ -38,7 +38,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLSourceElement::HTMLSourceElement(const QualifiedName& tagName, Document* document)
+inline HTMLSourceElement::HTMLSourceElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_errorEventTimer(this, &HTMLSourceElement::errorEventTimerFired)
 {
@@ -47,7 +47,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLSourceElement> HTMLSourceElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLSourceElement> HTMLSourceElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLSourceElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLSourceElement.h b/Source/core/html/HTMLSourceElement.h
index 1d13a9e..02378cc 100644
--- a/Source/core/html/HTMLSourceElement.h
+++ b/Source/core/html/HTMLSourceElement.h
@@ -33,8 +33,8 @@
 
 class HTMLSourceElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLSourceElement> create(Document* document) { return create(HTMLNames::sourceTag, document); }
-    static PassRefPtr<HTMLSourceElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLSourceElement> create(Document& document) { return create(HTMLNames::sourceTag, document); }
+    static PassRefPtr<HTMLSourceElement> create(const QualifiedName&, Document&);
 
     String media() const;
     String type() const;
@@ -46,7 +46,7 @@
     void cancelPendingErrorEvent();
 
 private:
-    HTMLSourceElement(const QualifiedName&, Document*);
+    HTMLSourceElement(const QualifiedName&, Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -57,6 +57,12 @@
     Timer<HTMLSourceElement> m_errorEventTimer;
 };
 
-} //namespace
+inline HTMLSourceElement* toHTMLSourceElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::sourceTag));
+    return static_cast<HTMLSourceElement*>(node);
+}
+
+} // namespace WebCore
 
 #endif
diff --git a/Source/core/html/HTMLSourceElement.idl b/Source/core/html/HTMLSourceElement.idl
index 0cad1e5..5adb052 100644
--- a/Source/core/html/HTMLSourceElement.idl
+++ b/Source/core/html/HTMLSourceElement.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=media
+    EnabledAtRuntime=Media
 ] interface HTMLSourceElement : HTMLElement {
 [Reflect, URL] attribute DOMString src;
     attribute DOMString type;
diff --git a/Source/core/html/HTMLSpanElement.cpp b/Source/core/html/HTMLSpanElement.cpp
index 560ffb4..e648e3e 100644
--- a/Source/core/html/HTMLSpanElement.cpp
+++ b/Source/core/html/HTMLSpanElement.cpp
@@ -32,14 +32,14 @@
 
 using namespace HTMLNames;
 
-HTMLSpanElement::HTMLSpanElement(const QualifiedName& tagName, Document* document)
+HTMLSpanElement::HTMLSpanElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(spanTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLSpanElement> HTMLSpanElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLSpanElement> HTMLSpanElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLSpanElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLSpanElement.h b/Source/core/html/HTMLSpanElement.h
index 27c2eb4..cf1df97 100644
--- a/Source/core/html/HTMLSpanElement.h
+++ b/Source/core/html/HTMLSpanElement.h
@@ -32,10 +32,10 @@
 
 class HTMLSpanElement : public HTMLElement {
 public:
-    static PassRefPtr<HTMLSpanElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLSpanElement> create(const QualifiedName&, Document&);
 
 protected:
-    HTMLSpanElement(const QualifiedName&, Document*);
+    HTMLSpanElement(const QualifiedName&, Document&);
 };
 
 }
diff --git a/Source/core/html/HTMLStyleElement.cpp b/Source/core/html/HTMLStyleElement.cpp
index b82268c..ee324da 100644
--- a/Source/core/html/HTMLStyleElement.cpp
+++ b/Source/core/html/HTMLStyleElement.cpp
@@ -44,9 +44,9 @@
     return sharedLoadEventSender;
 }
 
-inline HTMLStyleElement::HTMLStyleElement(const QualifiedName& tagName, Document* document, bool createdByParser)
+inline HTMLStyleElement::HTMLStyleElement(const QualifiedName& tagName, Document& document, bool createdByParser)
     : HTMLElement(tagName, document)
-    , StyleElement(document, createdByParser)
+    , StyleElement(&document, createdByParser)
     , m_firedLoad(false)
     , m_loadedSheet(false)
     , m_scopedStyleRegistrationState(NotRegistered)
@@ -64,7 +64,7 @@
     styleLoadEventSender().cancelEvent(this);
 }
 
-PassRefPtr<HTMLStyleElement> HTMLStyleElement::create(const QualifiedName& tagName, Document* document, bool createdByParser)
+PassRefPtr<HTMLStyleElement> HTMLStyleElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
 {
     return adoptRef(new HTMLStyleElement(tagName, document, createdByParser));
 }
@@ -73,12 +73,12 @@
 {
     if (name == titleAttr && m_sheet) {
         m_sheet->setTitle(value);
-    } else if (name == scopedAttr && ContextFeatures::styleScopedEnabled(document())) {
+    } else if (name == scopedAttr && ContextFeatures::styleScopedEnabled(&document())) {
         scopedAttributeChanged(!value.isNull());
-    } else if (name == mediaAttr && inDocument() && document()->renderer() && m_sheet) {
+    } else if (name == mediaAttr && inDocument() && document().renderer() && m_sheet) {
         m_sheet->setMediaQueries(MediaQuerySet::create(value));
         // FIXME: This shold be RecalcStyleDeferred.
-        document()->modifiedStyleSheet(m_sheet.get(), RecalcStyleImmediately);
+        document().modifiedStyleSheet(m_sheet.get(), RecalcStyleImmediately);
     } else {
         HTMLElement::parseAttribute(name, value);
     }
@@ -86,7 +86,7 @@
 
 void HTMLStyleElement::scopedAttributeChanged(bool scoped)
 {
-    ASSERT(ContextFeatures::styleScopedEnabled(document()));
+    ASSERT(ContextFeatures::styleScopedEnabled(&document()));
 
     if (!inDocument())
         return;
@@ -102,11 +102,11 @@
             scopingNode = containingShadowRoot();
             unregisterWithScopingNode(scopingNode);
         }
-        document()->styleSheetCollections()->removeStyleSheetCandidateNode(this, scopingNode);
+        document().styleSheetCollections()->removeStyleSheetCandidateNode(this, scopingNode);
         registerWithScopingNode(true);
 
-        document()->styleSheetCollections()->addStyleSheetCandidateNode(this, false);
-        document()->modifiedStyleSheet(sheet());
+        document().styleSheetCollections()->addStyleSheetCandidateNode(this, false);
+        document().modifiedStyleSheet(sheet());
         return;
     }
 
@@ -115,7 +115,7 @@
     if (m_scopedStyleRegistrationState != RegisteredAsScoped)
         return;
 
-    document()->styleSheetCollections()->removeStyleSheetCandidateNode(this, parentNode());
+    document().styleSheetCollections()->removeStyleSheetCandidateNode(this, parentNode());
     unregisterWithScopingNode(parentNode());
 
     // As any <style> in a shadow tree is treated as "scoped",
@@ -123,8 +123,8 @@
     if (isInShadowTree())
         registerWithScopingNode(false);
 
-    document()->styleSheetCollections()->addStyleSheetCandidateNode(this, false);
-    document()->modifiedStyleSheet(sheet());
+    document().styleSheetCollections()->addStyleSheetCandidateNode(this, false);
+    document().modifiedStyleSheet(sheet());
 }
 
 void HTMLStyleElement::finishParsingChildren()
@@ -157,7 +157,7 @@
 
 void HTMLStyleElement::unregisterWithScopingNode(ContainerNode* scope)
 {
-    ASSERT(m_scopedStyleRegistrationState != NotRegistered || !ContextFeatures::styleScopedEnabled(document()));
+    ASSERT(m_scopedStyleRegistrationState != NotRegistered || !ContextFeatures::styleScopedEnabled(&document()));
     if (!isRegisteredAsScoped())
         return;
 
@@ -176,10 +176,8 @@
     if (insertionPoint->inDocument()) {
         if (m_scopedStyleRegistrationState == NotRegistered && (scoped() || isInShadowTree()))
             registerWithScopingNode(scoped());
-        return InsertionShouldCallDidNotifySubtreeInsertions;
     }
-
-    return InsertionDone;
+    return InsertionShouldCallDidNotifySubtreeInsertions;
 }
 
 void HTMLStyleElement::removedFrom(ContainerNode* insertionPoint)
@@ -205,7 +203,7 @@
         StyleElement::removedFromDocument(document(), this, scope);
 }
 
-void HTMLStyleElement::didNotifySubtreeInsertions(ContainerNode* insertionPoint)
+void HTMLStyleElement::didNotifySubtreeInsertionsToDocument()
 {
     StyleElement::processStyleSheet(document(), this);
 }
@@ -228,7 +226,7 @@
 
 bool HTMLStyleElement::scoped() const
 {
-    return fastHasAttribute(scopedAttr) && ContextFeatures::styleScopedEnabled(document());
+    return fastHasAttribute(scopedAttr) && ContextFeatures::styleScopedEnabled(&document());
 }
 
 void HTMLStyleElement::setScoped(bool scopedValue)
@@ -242,7 +240,7 @@
         return 0;
 
     if (!isRegisteredAsScoped())
-        return document();
+        return &document();
 
     if (isRegisteredInShadowRoot())
         return containingShadowRoot();
diff --git a/Source/core/html/HTMLStyleElement.h b/Source/core/html/HTMLStyleElement.h
index 27c0ca7..252d441 100644
--- a/Source/core/html/HTMLStyleElement.h
+++ b/Source/core/html/HTMLStyleElement.h
@@ -36,7 +36,7 @@
 
 class HTMLStyleElement FINAL : public HTMLElement, private StyleElement {
 public:
-    static PassRefPtr<HTMLStyleElement> create(const QualifiedName&, Document*, bool createdByParser);
+    static PassRefPtr<HTMLStyleElement> create(const QualifiedName&, Document&, bool createdByParser);
     virtual ~HTMLStyleElement();
 
     void setType(const AtomicString&);
@@ -67,12 +67,12 @@
     static void dispatchPendingLoadEvents();
 
 private:
-    HTMLStyleElement(const QualifiedName&, Document*, bool createdByParser);
+    HTMLStyleElement(const QualifiedName&, Document&, bool createdByParser);
 
     // overload from HTMLElement
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    virtual void didNotifySubtreeInsertions(ContainerNode*) OVERRIDE;
+    virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
diff --git a/Source/core/html/HTMLStyleElement.idl b/Source/core/html/HTMLStyleElement.idl
index 70efc26..a5fd4f3 100644
--- a/Source/core/html/HTMLStyleElement.idl
+++ b/Source/core/html/HTMLStyleElement.idl
@@ -20,7 +20,7 @@
 
 interface HTMLStyleElement : HTMLElement {
     attribute boolean disabled;
-    [EnabledAtRuntime=styleScoped] attribute boolean scoped;
+    [EnabledAtRuntime=StyleScoped] attribute boolean scoped;
     [Reflect] attribute DOMString media;
     [Reflect] attribute DOMString type;
 
diff --git a/Source/core/html/HTMLSummaryElement.cpp b/Source/core/html/HTMLSummaryElement.cpp
index 635dd55..ed09699 100644
--- a/Source/core/html/HTMLSummaryElement.cpp
+++ b/Source/core/html/HTMLSummaryElement.cpp
@@ -24,25 +24,25 @@
 #include "HTMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/KeyboardEvent.h"
-#include "core/dom/NodeRenderingContext.h"
+#include "core/dom/NodeRenderingTraversal.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLDetailsElement.h"
 #include "core/html/shadow/DetailsMarkerControl.h"
 #include "core/html/shadow/HTMLContentElement.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
-PassRefPtr<HTMLSummaryElement> HTMLSummaryElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLSummaryElement> HTMLSummaryElement::create(const QualifiedName& tagName, Document& document)
 {
     RefPtr<HTMLSummaryElement> summary = adoptRef(new HTMLSummaryElement(tagName, document));
     summary->ensureUserAgentShadowRoot();
     return summary.release();
 }
 
-HTMLSummaryElement::HTMLSummaryElement(const QualifiedName& tagName, Document* document)
+HTMLSummaryElement::HTMLSummaryElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(summaryTag));
@@ -50,7 +50,7 @@
 
 RenderObject* HTMLSummaryElement::createRenderer(RenderStyle*)
 {
-    return new RenderBlock(this);
+    return new RenderBlockFlow(this);
 }
 
 void HTMLSummaryElement::didAddUserAgentShadowRoot(ShadowRoot* root)
diff --git a/Source/core/html/HTMLSummaryElement.h b/Source/core/html/HTMLSummaryElement.h
index ac4dc7e..0131611 100644
--- a/Source/core/html/HTMLSummaryElement.h
+++ b/Source/core/html/HTMLSummaryElement.h
@@ -29,12 +29,12 @@
 
 class HTMLSummaryElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLSummaryElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLSummaryElement> create(const QualifiedName&, Document&);
     bool isMainSummary() const;
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
-    HTMLSummaryElement(const QualifiedName&, Document*);
+    HTMLSummaryElement(const QualifiedName&, Document&);
 
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual void defaultEventHandler(Event*);
@@ -44,6 +44,12 @@
     bool supportsFocus() const OVERRIDE;
 };
 
+inline HTMLSummaryElement* toHTMLSummaryElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::summaryTag));
+    return static_cast<HTMLSummaryElement*>(node);
+}
+
 }
 
 #endif // HTMLSummaryElement_h
diff --git a/Source/core/html/HTMLTableCaptionElement.cpp b/Source/core/html/HTMLTableCaptionElement.cpp
index 2d774630..870d7b4 100644
--- a/Source/core/html/HTMLTableCaptionElement.cpp
+++ b/Source/core/html/HTMLTableCaptionElement.cpp
@@ -32,14 +32,14 @@
 
 using namespace HTMLNames;
 
-inline HTMLTableCaptionElement::HTMLTableCaptionElement(const QualifiedName& tagName, Document* document)
+inline HTMLTableCaptionElement::HTMLTableCaptionElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(captionTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTableCaptionElement> HTMLTableCaptionElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLTableCaptionElement> HTMLTableCaptionElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLTableCaptionElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLTableCaptionElement.h b/Source/core/html/HTMLTableCaptionElement.h
index 4601a7f..ce30265 100644
--- a/Source/core/html/HTMLTableCaptionElement.h
+++ b/Source/core/html/HTMLTableCaptionElement.h
@@ -32,15 +32,21 @@
 
 class HTMLTableCaptionElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLTableCaptionElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLTableCaptionElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLTableCaptionElement(const QualifiedName&, Document*);
+    HTMLTableCaptionElement(const QualifiedName&, Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 };
 
+inline HTMLTableCaptionElement* toHTMLTableCaptionElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::captionTag));
+    return static_cast<HTMLTableCaptionElement*>(node);
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/html/HTMLTableCellElement.cpp b/Source/core/html/HTMLTableCellElement.cpp
index 05a0858..34f7bad 100644
--- a/Source/core/html/HTMLTableCellElement.cpp
+++ b/Source/core/html/HTMLTableCellElement.cpp
@@ -42,13 +42,13 @@
 
 using namespace HTMLNames;
 
-inline HTMLTableCellElement::HTMLTableCellElement(const QualifiedName& tagName, Document* document)
+inline HTMLTableCellElement::HTMLTableCellElement(const QualifiedName& tagName, Document& document)
     : HTMLTablePartElement(tagName, document)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTableCellElement> HTMLTableCellElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLTableCellElement> HTMLTableCellElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLTableCellElement(tagName, document));
 }
@@ -164,7 +164,7 @@
 {
     HTMLTablePartElement::addSubresourceAttributeURLs(urls);
 
-    addSubresourceURL(urls, document()->completeURL(getAttribute(backgroundAttr)));
+    addSubresourceURL(urls, document().completeURL(getAttribute(backgroundAttr)));
 }
 
 HTMLTableCellElement* HTMLTableCellElement::cellAbove() const
diff --git a/Source/core/html/HTMLTableCellElement.h b/Source/core/html/HTMLTableCellElement.h
index f1c7780..413ccd9 100644
--- a/Source/core/html/HTMLTableCellElement.h
+++ b/Source/core/html/HTMLTableCellElement.h
@@ -32,7 +32,7 @@
 
 class HTMLTableCellElement FINAL : public HTMLTablePartElement {
 public:
-    static PassRefPtr<HTMLTableCellElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLTableCellElement> create(const QualifiedName&, Document&);
 
     int cellIndex() const;
 
@@ -51,7 +51,7 @@
     HTMLTableCellElement* cellAbove() const;
 
 private:
-    HTMLTableCellElement(const QualifiedName&, Document*);
+    HTMLTableCellElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLTableColElement.cpp b/Source/core/html/HTMLTableColElement.cpp
index c4de421..bf46d4d 100644
--- a/Source/core/html/HTMLTableColElement.cpp
+++ b/Source/core/html/HTMLTableColElement.cpp
@@ -34,14 +34,14 @@
 
 using namespace HTMLNames;
 
-inline HTMLTableColElement::HTMLTableColElement(const QualifiedName& tagName, Document* document)
+inline HTMLTableColElement::HTMLTableColElement(const QualifiedName& tagName, Document& document)
     : HTMLTablePartElement(tagName, document)
     , m_span(1)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTableColElement> HTMLTableColElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLTableColElement> HTMLTableColElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLTableColElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLTableColElement.h b/Source/core/html/HTMLTableColElement.h
index e6fba43..635c661 100644
--- a/Source/core/html/HTMLTableColElement.h
+++ b/Source/core/html/HTMLTableColElement.h
@@ -32,7 +32,7 @@
 
 class HTMLTableColElement FINAL : public HTMLTablePartElement {
 public:
-    static PassRefPtr<HTMLTableColElement> create(const QualifiedName& tagName, Document*);
+    static PassRefPtr<HTMLTableColElement> create(const QualifiedName& tagName, Document&);
 
     int span() const { return m_span; }
     void setSpan(int);
@@ -40,7 +40,7 @@
     String width() const;
 
 private:
-    HTMLTableColElement(const QualifiedName& tagName, Document*);
+    HTMLTableColElement(const QualifiedName& tagName, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -50,6 +50,12 @@
     int m_span;
 };
 
-} //namespace
+inline HTMLTableColElement* toHTMLTableColElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::colTag) || node->hasTagName(HTMLNames::colgroupTag));
+    return static_cast<HTMLTableColElement*>(node);
+}
+
+} // namespace WebCore
 
 #endif
diff --git a/Source/core/html/HTMLTableElement.cpp b/Source/core/html/HTMLTableElement.cpp
index 6950114..54cca88 100644
--- a/Source/core/html/HTMLTableElement.cpp
+++ b/Source/core/html/HTMLTableElement.cpp
@@ -46,7 +46,7 @@
 
 using namespace HTMLNames;
 
-HTMLTableElement::HTMLTableElement(const QualifiedName& tagName, Document* document)
+HTMLTableElement::HTMLTableElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_borderAttr(false)
     , m_borderColorAttr(false)
@@ -58,12 +58,12 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTableElement> HTMLTableElement::create(Document* document)
+PassRefPtr<HTMLTableElement> HTMLTableElement::create(Document& document)
 {
     return adoptRef(new HTMLTableElement(tableTag, document));
 }
 
-PassRefPtr<HTMLTableElement> HTMLTableElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLTableElement> HTMLTableElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLTableElement(tagName, document));
 }
@@ -72,7 +72,7 @@
 {
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
         if (child->hasTagName(captionTag))
-            return static_cast<HTMLTableCaptionElement*>(child);
+            return toHTMLTableCaptionElement(child);
     }
     return 0;
 }
@@ -317,7 +317,7 @@
     else if (name == backgroundAttr) {
         String url = stripLeadingAndTrailingHTMLSpaces(value);
         if (!url.isEmpty())
-            style->setProperty(CSSProperty(CSSPropertyBackgroundImage, CSSImageValue::create(document()->completeURL(url).string())));
+            style->setProperty(CSSProperty(CSSPropertyBackgroundImage, CSSImageValue::create(document().completeURL(url).string())));
     } else if (name == valignAttr) {
         if (!value.isEmpty())
             addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, value);
@@ -576,7 +576,7 @@
 {
     HTMLElement::addSubresourceAttributeURLs(urls);
 
-    addSubresourceURL(urls, document()->completeURL(getAttribute(backgroundAttr)));
+    addSubresourceURL(urls, document().completeURL(getAttribute(backgroundAttr)));
 }
 
 }
diff --git a/Source/core/html/HTMLTableElement.h b/Source/core/html/HTMLTableElement.h
index b203747..4ec1674 100644
--- a/Source/core/html/HTMLTableElement.h
+++ b/Source/core/html/HTMLTableElement.h
@@ -38,8 +38,8 @@
 
 class HTMLTableElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLTableElement> create(Document*);
-    static PassRefPtr<HTMLTableElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLTableElement> create(Document&);
+    static PassRefPtr<HTMLTableElement> create(const QualifiedName&, Document&);
 
     HTMLTableCaptionElement* caption() const;
     void setCaption(PassRefPtr<HTMLTableCaptionElement>, ExceptionState&);
@@ -70,7 +70,7 @@
     const StylePropertySet* additionalGroupStyle(bool rows);
 
 private:
-    HTMLTableElement(const QualifiedName&, Document*);
+    HTMLTableElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HTMLTablePartElement.cpp b/Source/core/html/HTMLTablePartElement.cpp
index 2373e52..79b2b6c 100644
--- a/Source/core/html/HTMLTablePartElement.cpp
+++ b/Source/core/html/HTMLTablePartElement.cpp
@@ -53,7 +53,7 @@
     else if (name == backgroundAttr) {
         String url = stripLeadingAndTrailingHTMLSpaces(value);
         if (!url.isEmpty())
-            style->setProperty(CSSProperty(CSSPropertyBackgroundImage, CSSImageValue::create(document()->completeURL(url).string())));
+            style->setProperty(CSSProperty(CSSPropertyBackgroundImage, CSSImageValue::create(document().completeURL(url).string())));
     } else if (name == valignAttr) {
         if (equalIgnoringCase(value, "top"))
             addPropertyToPresentationAttributeStyle(style, CSSPropertyVerticalAlign, CSSValueTop);
diff --git a/Source/core/html/HTMLTablePartElement.h b/Source/core/html/HTMLTablePartElement.h
index 974228a..7e20098 100644
--- a/Source/core/html/HTMLTablePartElement.h
+++ b/Source/core/html/HTMLTablePartElement.h
@@ -34,7 +34,7 @@
 
 class HTMLTablePartElement : public HTMLElement {
 protected:
-    HTMLTablePartElement(const QualifiedName& tagName, Document* document)
+    HTMLTablePartElement(const QualifiedName& tagName, Document& document)
         : HTMLElement(tagName, document)
     {
     }
diff --git a/Source/core/html/HTMLTableRowElement.cpp b/Source/core/html/HTMLTableRowElement.cpp
index 8bc0c3c..e50eaf8 100644
--- a/Source/core/html/HTMLTableRowElement.cpp
+++ b/Source/core/html/HTMLTableRowElement.cpp
@@ -37,19 +37,19 @@
 
 using namespace HTMLNames;
 
-HTMLTableRowElement::HTMLTableRowElement(const QualifiedName& tagName, Document* document)
+HTMLTableRowElement::HTMLTableRowElement(const QualifiedName& tagName, Document& document)
     : HTMLTablePartElement(tagName, document)
 {
     ASSERT(hasTagName(trTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(Document* document)
+PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(Document& document)
 {
     return adoptRef(new HTMLTableRowElement(trTag, document));
 }
 
-PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLTableRowElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLTableRowElement.h b/Source/core/html/HTMLTableRowElement.h
index a45f31b..0c1bff8 100644
--- a/Source/core/html/HTMLTableRowElement.h
+++ b/Source/core/html/HTMLTableRowElement.h
@@ -34,8 +34,8 @@
 
 class HTMLTableRowElement FINAL : public HTMLTablePartElement {
 public:
-    static PassRefPtr<HTMLTableRowElement> create(Document*);
-    static PassRefPtr<HTMLTableRowElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLTableRowElement> create(Document&);
+    static PassRefPtr<HTMLTableRowElement> create(const QualifiedName&, Document&);
 
     int rowIndex() const;
     void setRowIndex(int);
@@ -50,7 +50,7 @@
     void setCells(HTMLCollection *, ExceptionState&);
 
 private:
-    HTMLTableRowElement(const QualifiedName&, Document*);
+    HTMLTableRowElement(const QualifiedName&, Document&);
 };
 
 inline bool isHTMLTableRowElement(const Node* node)
diff --git a/Source/core/html/HTMLTableSectionElement.cpp b/Source/core/html/HTMLTableSectionElement.cpp
index 4a1d90e..c84d6b9 100644
--- a/Source/core/html/HTMLTableSectionElement.cpp
+++ b/Source/core/html/HTMLTableSectionElement.cpp
@@ -36,13 +36,13 @@
 
 using namespace HTMLNames;
 
-inline HTMLTableSectionElement::HTMLTableSectionElement(const QualifiedName& tagName, Document* document)
+inline HTMLTableSectionElement::HTMLTableSectionElement(const QualifiedName& tagName, Document& document)
     : HTMLTablePartElement(tagName, document)
 {
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTableSectionElement> HTMLTableSectionElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLTableSectionElement> HTMLTableSectionElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLTableSectionElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLTableSectionElement.h b/Source/core/html/HTMLTableSectionElement.h
index 16bc09a..f2d271b 100644
--- a/Source/core/html/HTMLTableSectionElement.h
+++ b/Source/core/html/HTMLTableSectionElement.h
@@ -34,7 +34,7 @@
 
 class HTMLTableSectionElement FINAL : public HTMLTablePartElement {
 public:
-    static PassRefPtr<HTMLTableSectionElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLTableSectionElement> create(const QualifiedName&, Document&);
 
     PassRefPtr<HTMLElement> insertRow(int index, ExceptionState&);
     void deleteRow(int index, ExceptionState&);
@@ -56,7 +56,7 @@
     PassRefPtr<HTMLCollection> rows();
 
 private:
-    HTMLTableSectionElement(const QualifiedName& tagName, Document*);
+    HTMLTableSectionElement(const QualifiedName& tagName, Document&);
 
     virtual const StylePropertySet* additionalPresentationAttributeStyle() OVERRIDE;
 };
diff --git a/Source/core/html/HTMLTemplateElement.cpp b/Source/core/html/HTMLTemplateElement.cpp
index ec67266..52e614e 100644
--- a/Source/core/html/HTMLTemplateElement.cpp
+++ b/Source/core/html/HTMLTemplateElement.cpp
@@ -39,7 +39,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLTemplateElement::HTMLTemplateElement(const QualifiedName& tagName, Document* document)
+inline HTMLTemplateElement::HTMLTemplateElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ScriptWrappable::init(this);
@@ -47,9 +47,11 @@
 
 HTMLTemplateElement::~HTMLTemplateElement()
 {
+    if (m_content)
+        m_content->clearHost();
 }
 
-PassRefPtr<HTMLTemplateElement> HTMLTemplateElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLTemplateElement> HTMLTemplateElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLTemplateElement(tagName, document));
 }
@@ -57,7 +59,7 @@
 DocumentFragment* HTMLTemplateElement::content() const
 {
     if (!m_content)
-        m_content = TemplateContentDocumentFragment::create(document()->ensureTemplateDocument(), this);
+        m_content = TemplateContentDocumentFragment::create(document().ensureTemplateDocument(), this);
 
     return m_content.get();
 }
@@ -78,15 +80,7 @@
     HTMLElement::didMoveToNewDocument(oldDocument);
     if (!m_content)
         return;
-    document()->ensureTemplateDocument()->adoptIfNeeded(m_content.get());
+    document().ensureTemplateDocument().adoptIfNeeded(m_content.get());
 }
 
-#ifndef NDEBUG
-const HTMLTemplateElement* toHTMLTemplateElement(const Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && node->hasTagName(templateTag)));
-    return static_cast<const HTMLTemplateElement*>(node);
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/html/HTMLTemplateElement.h b/Source/core/html/HTMLTemplateElement.h
index a24d8aa..82a4846 100644
--- a/Source/core/html/HTMLTemplateElement.h
+++ b/Source/core/html/HTMLTemplateElement.h
@@ -31,14 +31,16 @@
 #ifndef HTMLTemplateElement_h
 #define HTMLTemplateElement_h
 
-#include "core/dom/DocumentFragment.h"
 #include "core/html/HTMLElement.h"
 
 namespace WebCore {
 
+class DocumentFragment;
+class TemplateContentDocumentFragment;
+
 class HTMLTemplateElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLTemplateElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLTemplateElement> create(const QualifiedName&, Document&);
     virtual ~HTMLTemplateElement();
 
     DocumentFragment* content() const;
@@ -47,26 +49,22 @@
     virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE;
     virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
 
-    HTMLTemplateElement(const QualifiedName&, Document*);
+    HTMLTemplateElement(const QualifiedName&, Document&);
 
-    mutable RefPtr<DocumentFragment> m_content;
+    mutable RefPtr<TemplateContentDocumentFragment> m_content;
 };
 
-const HTMLTemplateElement* toHTMLTemplateElement(const Node*);
-
 inline HTMLTemplateElement* toHTMLTemplateElement(Node* node)
 {
-    return const_cast<HTMLTemplateElement*>(toHTMLTemplateElement(static_cast<const Node*>(node)));
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && node->hasTagName(HTMLNames::templateTag)));
+    return static_cast<HTMLTemplateElement*>(node);
 }
 
-#ifdef NDEBUG
-
-// The debug version of this, with assertions, is not inlined.
 inline const HTMLTemplateElement* toHTMLTemplateElement(const Node* node)
 {
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && node->hasTagName(HTMLNames::templateTag)));
     return static_cast<const HTMLTemplateElement*>(node);
 }
-#endif // NDEBUG
 
 } // namespace WebCore
 
diff --git a/Source/core/html/HTMLTextAreaElement.cpp b/Source/core/html/HTMLTextAreaElement.cpp
index 7445d1e..3ef62fe 100644
--- a/Source/core/html/HTMLTextAreaElement.cpp
+++ b/Source/core/html/HTMLTextAreaElement.cpp
@@ -79,7 +79,7 @@
     return text.length() + numberOfLineBreaks(text);
 }
 
-HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
     : HTMLTextFormControlElement(tagName, document, form)
     , m_rows(defaultRows)
     , m_cols(defaultCols)
@@ -93,7 +93,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(const QualifiedName& tagName, Document* document, HTMLFormElement* form)
+PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
 {
     RefPtr<HTMLTextAreaElement> textArea = adoptRef(new HTMLTextAreaElement(tagName, document, form));
     textArea->ensureUserAgentShadowRoot();
@@ -211,7 +211,7 @@
     if (name().isEmpty())
         return false;
 
-    document()->updateLayout();
+    document().updateLayout();
 
     const String& text = (m_wrap == HardWrap) ? valueWithHardLineBreaks() : value();
     encoding.appendData(name(), text);
@@ -253,8 +253,8 @@
     } else
         restoreCachedSelection();
 
-    if (document()->frame())
-        document()->frame()->selection()->revealSelection();
+    if (document().frame())
+        document().frame()->selection().revealSelection();
 }
 
 void HTMLTextAreaElement::defaultEventHandler(Event* event)
@@ -269,7 +269,7 @@
 
 void HTMLTextAreaElement::handleFocusEvent(Element*, FocusDirection)
 {
-    if (Frame* frame = document()->frame())
+    if (Frame* frame = document().frame())
         frame->editor().textAreaOrTextFieldDidBeginEditing(this);
 }
 
@@ -305,7 +305,7 @@
     // If the text field has no focus, we don't need to take account of the
     // selection length. The selection is the source of text drag-and-drop in
     // that case, and nothing in the text field will be removed.
-    unsigned selectionLength = focused() ? computeLengthForSubmission(plainText(document()->frame()->selection()->selection().toNormalizedRange().get())) : 0;
+    unsigned selectionLength = focused() ? computeLengthForSubmission(plainText(document().frame()->selection().selection().toNormalizedRange().get())) : 0;
     ASSERT(currentLength >= selectionLength);
     unsigned baseLength = currentLength - selectionLength;
     unsigned appendableLength = unsignedMaxLength > baseLength ? unsignedMaxLength - baseLength : 0;
@@ -387,7 +387,7 @@
     setFormControlValueMatchesRenderer(true);
 
     // Set the caret to the end of the text value.
-    if (document()->focusedElement() == this) {
+    if (document().focusedElement() == this) {
         unsigned endOfString = m_value.length();
         setSelectionRange(endOfString, endOfString);
     }
@@ -428,7 +428,7 @@
     value.replace("\r\n", "\n");
     value.replace('\r', '\n');
 
-    insertBefore(document()->createTextNode(value), firstChild(), IGNORE_EXCEPTION);
+    insertBefore(document().createTextNode(value), firstChild(), IGNORE_EXCEPTION);
 
     if (!m_isDirty)
         setNonDirtyValue(value);
diff --git a/Source/core/html/HTMLTextAreaElement.h b/Source/core/html/HTMLTextAreaElement.h
index 57d33d7..80d2f29 100644
--- a/Source/core/html/HTMLTextAreaElement.h
+++ b/Source/core/html/HTMLTextAreaElement.h
@@ -34,7 +34,7 @@
 
 class HTMLTextAreaElement FINAL : public HTMLTextFormControlElement {
 public:
-    static PassRefPtr<HTMLTextAreaElement> create(const QualifiedName&, Document*, HTMLFormElement*);
+    static PassRefPtr<HTMLTextAreaElement> create(const QualifiedName&, Document&, HTMLFormElement*);
 
     int cols() const { return m_cols; }
     int rows() const { return m_rows; }
@@ -62,11 +62,14 @@
     void setRows(int);
 
 private:
-    HTMLTextAreaElement(const QualifiedName&, Document*, HTMLFormElement*);
+    HTMLTextAreaElement(const QualifiedName&, Document&, HTMLFormElement*);
 
     enum WrapMethod { NoWrap, SoftWrap, HardWrap };
 
     virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+    // FIXME: Author shadows should be allowed
+    // https://bugs.webkit.org/show_bug.cgi?id=92608
+    virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
 
     void handleBeforeTextInsertedEvent(BeforeTextInsertedEvent*) const;
     static String sanitizeUserInputValue(const String&, unsigned maxLength);
diff --git a/Source/core/html/HTMLTextAreaElement.idl b/Source/core/html/HTMLTextAreaElement.idl
index cefbca9..51c8419 100644
--- a/Source/core/html/HTMLTextAreaElement.idl
+++ b/Source/core/html/HTMLTextAreaElement.idl
@@ -32,7 +32,7 @@
     [Reflect] attribute boolean required;
     attribute long rows;
     [Reflect] attribute DOMString wrap;
-    [EnabledAtRuntime=inputModeAttribute, Reflect] attribute DOMString inputMode;
+    [EnabledAtRuntime=InputModeAttribute, Reflect] attribute DOMString inputMode;
 
     readonly attribute DOMString type;
     [TreatNullAs=NullString] attribute DOMString defaultValue;
diff --git a/Source/core/html/HTMLTextFormControlElement.cpp b/Source/core/html/HTMLTextFormControlElement.cpp
index 4ccdd5c..acbd7cd 100644
--- a/Source/core/html/HTMLTextFormControlElement.cpp
+++ b/Source/core/html/HTMLTextFormControlElement.cpp
@@ -32,7 +32,6 @@
 #include "core/dom/Document.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Text.h"
 #include "core/editing/FrameSelection.h"
@@ -49,7 +48,7 @@
 using namespace HTMLNames;
 using namespace std;
 
-HTMLTextFormControlElement::HTMLTextFormControlElement(const QualifiedName& tagName, Document* doc, HTMLFormElement* form)
+HTMLTextFormControlElement::HTMLTextFormControlElement(const QualifiedName& tagName, Document& doc, HTMLFormElement* form)
     : HTMLFormControlElementWithState(tagName, doc, form)
     , m_lastChangeWasUserEdit(false)
     , m_cachedSelectionStart(-1)
@@ -140,7 +139,7 @@
         && isEmptyValue()
         && isEmptySuggestedValue()
         && !isPlaceholderEmpty()
-        && (document()->focusedElement() != this || (RenderTheme::theme().shouldShowPlaceholderWhenFocused()))
+        && (document().focusedElement() != this || (RenderTheme::theme().shouldShowPlaceholderWhenFocused()))
         && (!renderer() || renderer()->style()->visibility() == VISIBLE);
 }
 
@@ -271,7 +270,7 @@
 
 void HTMLTextFormControlElement::setSelectionRange(int start, int end, TextFieldSelectionDirection direction)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (!renderer() || !renderer()->isTextControl())
         return;
@@ -303,8 +302,8 @@
         newSelection = VisibleSelection(startPosition, endPosition);
     newSelection.setIsDirectional(direction != SelectionHasNoDirection);
 
-    if (Frame* frame = document()->frame())
-        frame->selection()->setSelection(newSelection);
+    if (Frame* frame = document().frame())
+        frame->selection().setSelection(newSelection);
 }
 
 VisiblePosition HTMLTextFormControlElement::visiblePositionForIndex(int index) const
@@ -323,7 +322,8 @@
     Position indexPosition = pos.deepEquivalent().parentAnchoredEquivalent();
     if (enclosingTextFormControl(indexPosition) != this)
         return 0;
-    RefPtr<Range> range = Range::create(indexPosition.document());
+    ASSERT(indexPosition.document());
+    RefPtr<Range> range = Range::create(*indexPosition.document());
     range->setStart(innerTextElement(), 0, ASSERT_NO_EXCEPTION);
     range->setEnd(indexPosition.containerNode(), indexPosition.offsetInContainerNode(), ASSERT_NO_EXCEPTION);
     return TextIterator::rangeLength(range.get());
@@ -333,7 +333,7 @@
 {
     if (!isTextFormControl())
         return 0;
-    if (document()->focusedElement() != this && hasCachedSelection())
+    if (document().focusedElement() != this && hasCachedSelection())
         return m_cachedSelectionStart;
 
     return computeSelectionStart();
@@ -342,18 +342,18 @@
 int HTMLTextFormControlElement::computeSelectionStart() const
 {
     ASSERT(isTextFormControl());
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return 0;
 
-    return indexForVisiblePosition(frame->selection()->start());
+    return indexForVisiblePosition(frame->selection().start());
 }
 
 int HTMLTextFormControlElement::selectionEnd() const
 {
     if (!isTextFormControl())
         return 0;
-    if (document()->focusedElement() != this && hasCachedSelection())
+    if (document().focusedElement() != this && hasCachedSelection())
         return m_cachedSelectionEnd;
     return computeSelectionEnd();
 }
@@ -361,11 +361,11 @@
 int HTMLTextFormControlElement::computeSelectionEnd() const
 {
     ASSERT(isTextFormControl());
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return 0;
 
-    return indexForVisiblePosition(frame->selection()->end());
+    return indexForVisiblePosition(frame->selection().end());
 }
 
 static const AtomicString& directionString(TextFieldSelectionDirection direction)
@@ -391,7 +391,7 @@
 {
     if (!isTextFormControl())
         return directionString(SelectionHasNoDirection);
-    if (document()->focusedElement() != this && hasCachedSelection())
+    if (document().focusedElement() != this && hasCachedSelection())
         return directionString(m_cachedSelectionDirection);
 
     return directionString(computeSelectionDirection());
@@ -400,11 +400,11 @@
 TextFieldSelectionDirection HTMLTextFormControlElement::computeSelectionDirection() const
 {
     ASSERT(isTextFormControl());
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return SelectionHasNoDirection;
 
-    const VisibleSelection& selection = frame->selection()->selection();
+    const VisibleSelection& selection = frame->selection().selection();
     return selection.isDirectional() ? (selection.isBaseFirst() ? SelectionHasForwardDirection : SelectionHasBackwardDirection) : SelectionHasNoDirection;
 }
 
@@ -473,8 +473,8 @@
     // selectionStart() or selectionEnd() will return cached selection when this node doesn't have focus
     cacheSelection(computeSelectionStart(), computeSelectionEnd(), computeSelectionDirection());
 
-    if (Frame* frame = document()->frame()) {
-        if (frame->selection()->isRange() && userTriggered)
+    if (Frame* frame = document().frame()) {
+        if (frame->selection().isRange() && userTriggered)
             dispatchEvent(Event::createBubble(eventNames().selectEvent));
     }
 }
@@ -483,7 +483,7 @@
 {
     if (name == placeholderAttr) {
         updatePlaceholderVisibility(true);
-        UseCounter::count(document(), UseCounter::PlaceholderAttribute);
+        UseCounter::count(&document(), UseCounter::PlaceholderAttribute);
     } else
         HTMLFormControlElementWithState::parseAttribute(name, value);
 }
@@ -502,8 +502,8 @@
 
     bool textIsChanged = value != innerTextValue();
     if (textIsChanged || !innerTextElement()->hasChildNodes()) {
-        if (textIsChanged && document() && renderer()) {
-            if (AXObjectCache* cache = document()->existingAXObjectCache())
+        if (textIsChanged && renderer()) {
+            if (AXObjectCache* cache = document().existingAXObjectCache())
                 cache->postNotification(this, AXObjectCache::AXValueChanged, false);
         }
         innerTextElement()->setInnerText(value, ASSERT_NO_EXCEPTION);
diff --git a/Source/core/html/HTMLTextFormControlElement.h b/Source/core/html/HTMLTextFormControlElement.h
index 72afa6e..4c9e1ec 100644
--- a/Source/core/html/HTMLTextFormControlElement.h
+++ b/Source/core/html/HTMLTextFormControlElement.h
@@ -89,7 +89,7 @@
     void setTextAsOfLastFormControlChangeEvent(const String& text) { m_textAsOfLastFormControlChangeEvent = text; }
 
 protected:
-    HTMLTextFormControlElement(const QualifiedName&, Document*, HTMLFormElement*);
+    HTMLTextFormControlElement(const QualifiedName&, Document&, HTMLFormElement*);
     bool isPlaceholderEmpty() const;
     virtual void updatePlaceholderText() = 0;
 
@@ -117,10 +117,6 @@
     int computeSelectionEnd() const;
     TextFieldSelectionDirection computeSelectionDirection() const;
 
-    // FIXME: Author shadows should be allowed
-    // https://bugs.webkit.org/show_bug.cgi?id=92608
-    virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
-
     virtual void dispatchFocusEvent(Element* oldFocusedElement, FocusDirection) OVERRIDE;
     virtual void dispatchBlurEvent(Element* newFocusedElement) OVERRIDE;
 
diff --git a/Source/core/html/HTMLTitleElement.cpp b/Source/core/html/HTMLTitleElement.cpp
index 7b14261..48ed56e 100644
--- a/Source/core/html/HTMLTitleElement.cpp
+++ b/Source/core/html/HTMLTitleElement.cpp
@@ -35,7 +35,7 @@
 
 using namespace HTMLNames;
 
-inline HTMLTitleElement::HTMLTitleElement(const QualifiedName& tagName, Document* document)
+inline HTMLTitleElement::HTMLTitleElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(titleTag));
@@ -43,7 +43,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLTitleElement> HTMLTitleElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLTitleElement> HTMLTitleElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLTitleElement(tagName, document));
 }
@@ -52,7 +52,7 @@
 {
     HTMLElement::insertedInto(insertionPoint);
     if (inDocument() && !isInShadowTree())
-        document()->setTitleElement(text(), this);
+        document().setTitleElement(text(), this);
     return InsertionDone;
 }
 
@@ -60,14 +60,14 @@
 {
     HTMLElement::removedFrom(insertionPoint);
     if (insertionPoint->inDocument() && !insertionPoint->isInShadowTree())
-        document()->removeTitle(this);
+        document().removeTitle(this);
 }
 
 void HTMLTitleElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
     HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
     if (inDocument() && !isInShadowTree())
-        document()->setTitleElement(text(), this);
+        document().setTitleElement(text(), this);
 }
 
 String HTMLTitleElement::text() const
@@ -99,7 +99,7 @@
         if (numChildren > 0)
             removeChildren();
 
-        appendChild(document()->createTextNode(valueCopy.impl()), IGNORE_EXCEPTION);
+        appendChild(document().createTextNode(valueCopy.impl()), IGNORE_EXCEPTION);
     }
 }
 
diff --git a/Source/core/html/HTMLTitleElement.h b/Source/core/html/HTMLTitleElement.h
index 5561afa..580a291 100644
--- a/Source/core/html/HTMLTitleElement.h
+++ b/Source/core/html/HTMLTitleElement.h
@@ -28,13 +28,13 @@
 
 class HTMLTitleElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLTitleElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLTitleElement> create(const QualifiedName&, Document&);
 
     String text() const;
     void setText(const String&);
 
 private:
-    HTMLTitleElement(const QualifiedName&, Document*);
+    HTMLTitleElement(const QualifiedName&, Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
diff --git a/Source/core/html/HTMLTrackElement.cpp b/Source/core/html/HTMLTrackElement.cpp
index 1006484..dfbbc45 100644
--- a/Source/core/html/HTMLTrackElement.cpp
+++ b/Source/core/html/HTMLTrackElement.cpp
@@ -51,7 +51,7 @@
 }
 #endif
 
-inline HTMLTrackElement::HTMLTrackElement(const QualifiedName& tagName, Document* document)
+inline HTMLTrackElement::HTMLTrackElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
     , m_loadTimer(this, &HTMLTrackElement::loadTimerFired)
 {
@@ -66,7 +66,7 @@
         m_track->clearClient();
 }
 
-PassRefPtr<HTMLTrackElement> HTMLTrackElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLTrackElement> HTMLTrackElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLTrackElement(tagName, document));
 }
@@ -118,7 +118,7 @@
 
 KURL HTMLTrackElement::src() const
 {
-    return document()->completeURL(getAttribute(srcAttr));
+    return document().completeURL(getAttribute(srcAttr));
 }
 
 void HTMLTrackElement::setSrc(const String& url)
@@ -252,7 +252,7 @@
     if (url.isEmpty())
         return false;
 
-    if (!document()->contentSecurityPolicy()->allowMediaFromSource(url)) {
+    if (!document().contentSecurityPolicy()->allowMediaFromSource(url)) {
         LOG(Media, "HTMLTrackElement::canLoadUrl(%s) -> rejected by Content Security Policy", urlForLoggingTrack(url).utf8().data());
         return false;
     }
diff --git a/Source/core/html/HTMLTrackElement.h b/Source/core/html/HTMLTrackElement.h
index c75cb69..adfc36e 100644
--- a/Source/core/html/HTMLTrackElement.h
+++ b/Source/core/html/HTMLTrackElement.h
@@ -36,7 +36,7 @@
 
 class HTMLTrackElement FINAL : public HTMLElement, public TextTrackClient {
 public:
-    static PassRefPtr<HTMLTrackElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLTrackElement> create(const QualifiedName&, Document&);
 
     KURL src() const;
     void setSrc(const String&);
@@ -67,7 +67,7 @@
     const AtomicString& mediaElementCrossOriginAttribute() const;
 
 private:
-    HTMLTrackElement(const QualifiedName&, Document*);
+    HTMLTrackElement(const QualifiedName&, Document&);
     virtual ~HTMLTrackElement();
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -96,6 +96,12 @@
     Timer<HTMLTrackElement> m_loadTimer;
 };
 
+inline HTMLTrackElement* toHTMLTrackElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::trackTag));
+    return static_cast<HTMLTrackElement*>(node);
+}
+
 }
 
 #endif
diff --git a/Source/core/html/HTMLTrackElement.idl b/Source/core/html/HTMLTrackElement.idl
index d27ae46..9c4e1bf 100644
--- a/Source/core/html/HTMLTrackElement.idl
+++ b/Source/core/html/HTMLTrackElement.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=videoTrack
+    EnabledAtRuntime=VideoTrack
 ] interface HTMLTrackElement : HTMLElement {
     attribute DOMString kind;
     [Reflect, URL] attribute DOMString src;
diff --git a/Source/core/html/HTMLUListElement.cpp b/Source/core/html/HTMLUListElement.cpp
index d263f3a..e5b804c 100644
--- a/Source/core/html/HTMLUListElement.cpp
+++ b/Source/core/html/HTMLUListElement.cpp
@@ -30,19 +30,19 @@
 
 using namespace HTMLNames;
 
-HTMLUListElement::HTMLUListElement(const QualifiedName& tagName, Document* document)
+HTMLUListElement::HTMLUListElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
     ASSERT(hasTagName(ulTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLUListElement> HTMLUListElement::create(Document* document)
+PassRefPtr<HTMLUListElement> HTMLUListElement::create(Document& document)
 {
     return adoptRef(new HTMLUListElement(ulTag, document));
 }
 
-PassRefPtr<HTMLUListElement> HTMLUListElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLUListElement> HTMLUListElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLUListElement(tagName, document));
 }
diff --git a/Source/core/html/HTMLUListElement.h b/Source/core/html/HTMLUListElement.h
index e2447d3..5954ed4 100644
--- a/Source/core/html/HTMLUListElement.h
+++ b/Source/core/html/HTMLUListElement.h
@@ -29,11 +29,11 @@
 
 class HTMLUListElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLUListElement> create(Document*);
-    static PassRefPtr<HTMLUListElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLUListElement> create(Document&);
+    static PassRefPtr<HTMLUListElement> create(const QualifiedName&, Document&);
 
 private:
-    HTMLUListElement(const QualifiedName&, Document*);
+    HTMLUListElement(const QualifiedName&, Document&);
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/Source/core/html/HTMLUnknownElement.h b/Source/core/html/HTMLUnknownElement.h
index 4839654..be493b1 100644
--- a/Source/core/html/HTMLUnknownElement.h
+++ b/Source/core/html/HTMLUnknownElement.h
@@ -36,7 +36,7 @@
 
 class HTMLUnknownElement FINAL : public HTMLElement {
 public:
-    static PassRefPtr<HTMLUnknownElement> create(const QualifiedName& tagName, Document* document)
+    static PassRefPtr<HTMLUnknownElement> create(const QualifiedName& tagName, Document& document)
     {
         return adoptRef(new HTMLUnknownElement(tagName, document));
     }
@@ -44,7 +44,7 @@
     virtual bool isHTMLUnknownElement() const OVERRIDE { return true; }
 
 private:
-    HTMLUnknownElement(const QualifiedName& tagName, Document* document)
+    HTMLUnknownElement(const QualifiedName& tagName, Document& document)
         : HTMLElement(tagName, document)
     {
         ScriptWrappable::init(this);
diff --git a/Source/core/html/HTMLVideoElement.cpp b/Source/core/html/HTMLVideoElement.cpp
index a5590d2..ded6f09 100644
--- a/Source/core/html/HTMLVideoElement.cpp
+++ b/Source/core/html/HTMLVideoElement.cpp
@@ -43,25 +43,25 @@
 
 using namespace HTMLNames;
 
-inline HTMLVideoElement::HTMLVideoElement(const QualifiedName& tagName, Document* document, bool createdByParser)
+inline HTMLVideoElement::HTMLVideoElement(const QualifiedName& tagName, Document& document, bool createdByParser)
     : HTMLMediaElement(tagName, document, createdByParser)
 {
     ASSERT(hasTagName(videoTag));
     ScriptWrappable::init(this);
-    if (document->settings())
-        m_defaultPosterURL = document->settings()->defaultVideoPosterURL();
+    if (document.settings())
+        m_defaultPosterURL = document.settings()->defaultVideoPosterURL();
 }
 
-PassRefPtr<HTMLVideoElement> HTMLVideoElement::create(const QualifiedName& tagName, Document* document, bool createdByParser)
+PassRefPtr<HTMLVideoElement> HTMLVideoElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
 {
     RefPtr<HTMLVideoElement> videoElement(adoptRef(new HTMLVideoElement(tagName, document, createdByParser)));
     videoElement->suspendIfNeeded();
     return videoElement.release();
 }
 
-bool HTMLVideoElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool HTMLVideoElement::rendererIsNeeded(const RenderStyle& style)
 {
-    return HTMLElement::rendererIsNeeded(context);
+    return HTMLElement::rendererIsNeeded(style);
 }
 
 RenderObject* HTMLVideoElement::createRenderer(RenderStyle*)
@@ -120,8 +120,7 @@
 
 bool HTMLVideoElement::supportsFullscreen() const
 {
-    Page* page = document() ? document()->page() : 0;
-    if (!page)
+    if (!document().page())
         return false;
 
     if (!player() || !player()->supportsFullscreen())
@@ -163,7 +162,7 @@
     return attribute.name() == posterAttr || HTMLMediaElement::isURLAttribute(attribute);
 }
 
-const AtomicString& HTMLVideoElement::imageSourceURL() const
+const AtomicString HTMLVideoElement::imageSourceURL() const
 {
     const AtomicString& url = getAttribute(posterAttr);
     if (!stripLeadingAndTrailingHTMLSpaces(url).isEmpty())
@@ -279,7 +278,7 @@
     String url = stripLeadingAndTrailingHTMLSpaces(imageSourceURL());
     if (url.isEmpty())
         return KURL();
-    return document()->completeURL(url);
+    return document().completeURL(url);
 }
 
 }
diff --git a/Source/core/html/HTMLVideoElement.h b/Source/core/html/HTMLVideoElement.h
index 04b2395..c939330 100644
--- a/Source/core/html/HTMLVideoElement.h
+++ b/Source/core/html/HTMLVideoElement.h
@@ -35,8 +35,8 @@
 
 class HTMLVideoElement FINAL : public HTMLMediaElement {
 public:
-    static PassRefPtr<HTMLVideoElement> create(Document* document) { return create(HTMLNames::videoTag, document, false); }
-    static PassRefPtr<HTMLVideoElement> create(const QualifiedName&, Document*, bool);
+    static PassRefPtr<HTMLVideoElement> create(Document& document) { return create(HTMLNames::videoTag, document, false); }
+    static PassRefPtr<HTMLVideoElement> create(const QualifiedName&, Document&, bool);
 
     unsigned width() const;
     unsigned height() const;
@@ -71,9 +71,9 @@
     KURL posterImageURL() const;
 
 private:
-    HTMLVideoElement(const QualifiedName&, Document*, bool);
+    HTMLVideoElement(const QualifiedName&, Document&, bool);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -83,7 +83,7 @@
     virtual bool hasVideo() const { return player() && player()->hasVideo(); }
     virtual bool supportsFullscreen() const;
     virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
-    virtual const AtomicString& imageSourceURL() const OVERRIDE;
+    virtual const AtomicString imageSourceURL() const OVERRIDE;
 
     virtual bool hasAvailableVideoFrame() const;
     virtual void updateDisplayState();
diff --git a/Source/core/html/HTMLVideoElement.idl b/Source/core/html/HTMLVideoElement.idl
index 5d9d744..31dd2bc 100644
--- a/Source/core/html/HTMLVideoElement.idl
+++ b/Source/core/html/HTMLVideoElement.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=media
+    EnabledAtRuntime=Media
 ] interface HTMLVideoElement : HTMLMediaElement {
     [Reflect] attribute unsigned long width;
     [Reflect] attribute unsigned long height;
diff --git a/Source/core/html/HTMLViewSourceDocument.cpp b/Source/core/html/HTMLViewSourceDocument.cpp
index 550a568..b5b8cef 100644
--- a/Source/core/html/HTMLViewSourceDocument.cpp
+++ b/Source/core/html/HTMLViewSourceDocument.cpp
@@ -63,21 +63,21 @@
 
 void HTMLViewSourceDocument::createContainingTable()
 {
-    RefPtr<HTMLHtmlElement> html = HTMLHtmlElement::create(this);
+    RefPtr<HTMLHtmlElement> html = HTMLHtmlElement::create(*this);
     parserAppendChild(html);
     html->lazyAttach();
-    RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(this);
+    RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(*this);
     html->parserAppendChild(body);
 
     // Create a line gutter div that can be used to make sure the gutter extends down the height of the whole
     // document.
-    RefPtr<HTMLDivElement> div = HTMLDivElement::create(this);
+    RefPtr<HTMLDivElement> div = HTMLDivElement::create(*this);
     div->setAttribute(classAttr, "webkit-line-gutter-backdrop");
     body->parserAppendChild(div);
 
-    RefPtr<HTMLTableElement> table = HTMLTableElement::create(this);
+    RefPtr<HTMLTableElement> table = HTMLTableElement::create(*this);
     body->parserAppendChild(table);
-    m_tbody = HTMLTableSectionElement::create(tbodyTag, this);
+    m_tbody = HTMLTableSectionElement::create(tbodyTag, *this);
     table->parserAppendChild(m_tbody);
     m_current = m_tbody;
     m_lineNumber = 0;
@@ -173,7 +173,7 @@
         return m_current;
     }
 
-    RefPtr<HTMLElement> span = HTMLElement::create(spanTag, this);
+    RefPtr<HTMLElement> span = HTMLElement::create(spanTag, *this);
     span->setAttribute(classAttr, className);
     m_current->parserAppendChild(span);
     return span.release();
@@ -182,23 +182,23 @@
 void HTMLViewSourceDocument::addLine(const AtomicString& className)
 {
     // Create a table row.
-    RefPtr<HTMLTableRowElement> trow = HTMLTableRowElement::create(this);
+    RefPtr<HTMLTableRowElement> trow = HTMLTableRowElement::create(*this);
     m_tbody->parserAppendChild(trow);
 
     // Create a cell that will hold the line number (it is generated in the stylesheet using counters).
-    RefPtr<HTMLTableCellElement> td = HTMLTableCellElement::create(tdTag, this);
+    RefPtr<HTMLTableCellElement> td = HTMLTableCellElement::create(tdTag, *this);
     td->setAttribute(classAttr, "webkit-line-number");
     td->setAttribute(valueAttr, String::number(++m_lineNumber));
     trow->parserAppendChild(td);
 
     // Create a second cell for the line contents
-    td = HTMLTableCellElement::create(tdTag, this);
+    td = HTMLTableCellElement::create(tdTag, *this);
     td->setAttribute(classAttr, "webkit-line-content");
     trow->parserAppendChild(td);
     m_current = m_td = td;
 
 #ifdef DEBUG_LINE_NUMBERS
-    RefPtr<Text> lineNumberText = Text::create(this, String::number(parser()->lineNumber() + 1) + " ");
+    RefPtr<Text> lineNumberText = Text::create(*this, String::number(parser()->lineNumber() + 1) + " ");
     td->addChild(lineNumberText);
     lineNumberText->lazyAttach();
 #endif
@@ -214,7 +214,7 @@
 void HTMLViewSourceDocument::finishLine()
 {
     if (!m_current->hasChildNodes()) {
-        RefPtr<HTMLBRElement> br = HTMLBRElement::create(this);
+        RefPtr<HTMLBRElement> br = HTMLBRElement::create(*this);
         m_current->parserAppendChild(br);
     }
     m_current = m_tbody;
@@ -239,7 +239,7 @@
             finishLine();
             continue;
         }
-        RefPtr<Text> t = Text::create(this, substring);
+        RefPtr<Text> t = Text::create(*this, substring);
         m_current->parserAppendChild(t);
         if (i < size - 1)
             finishLine();
@@ -267,7 +267,7 @@
 
 PassRefPtr<Element> HTMLViewSourceDocument::addBase(const AtomicString& href)
 {
-    RefPtr<HTMLBaseElement> base = HTMLBaseElement::create(baseTag, this);
+    RefPtr<HTMLBaseElement> base = HTMLBaseElement::create(baseTag, *this);
     base->setAttribute(hrefAttr, href);
     m_current->parserAppendChild(base);
     return base.release();
@@ -279,7 +279,7 @@
         addLine("webkit-html-tag");
 
     // Now create a link for the attribute value instead of a span.
-    RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(this);
+    RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(*this);
     const char* classValue;
     if (isAnchor)
         classValue = "webkit-html-attribute-value webkit-html-external-link";
diff --git a/Source/core/html/ImageDocument.cpp b/Source/core/html/ImageDocument.cpp
index 57a97d0..23b02c3 100644
--- a/Source/core/html/ImageDocument.cpp
+++ b/Source/core/html/ImageDocument.cpp
@@ -166,23 +166,23 @@
 
 void ImageDocument::createDocumentStructure()
 {
-    RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(this);
+    RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(*this);
     appendChild(rootElement);
     rootElement->insertedByParser();
 
     if (frame() && frame()->loader())
         frame()->loader()->dispatchDocumentElementAvailable();
 
-    RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(this);
-    RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(this);
+    RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(*this);
+    RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(*this);
     meta->setAttribute(nameAttr, "viewport");
     meta->setAttribute(contentAttr, "width=device-width");
     head->appendChild(meta);
 
-    RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(this);
+    RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(*this);
     body->setAttribute(styleAttr, "margin: 0px;");
 
-    m_imageElement = HTMLImageElement::create(this);
+    m_imageElement = HTMLImageElement::create(*this);
     m_imageElement->setAttribute(styleAttr, "-webkit-user-select: none");
     m_imageElement->setLoadManually(true);
     m_imageElement->setSrc(url().string());
@@ -202,7 +202,7 @@
 
 float ImageDocument::scale() const
 {
-    if (!m_imageElement || m_imageElement->document() != this)
+    if (!m_imageElement || &m_imageElement->document() != this)
         return 1.0f;
 
     FrameView* view = frame()->view();
@@ -220,7 +220,7 @@
 
 void ImageDocument::resizeImageToFit()
 {
-    if (!m_imageElement || m_imageElement->document() != this || pageZoomFactor(this) > 1)
+    if (!m_imageElement || &m_imageElement->document() != this || pageZoomFactor(this) > 1)
         return;
 
     LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), pageZoomFactor(this));
@@ -275,7 +275,7 @@
 
 void ImageDocument::restoreImageSize()
 {
-    if (!m_imageElement || !m_imageSizeIsKnown || m_imageElement->document() != this || pageZoomFactor(this) < 1)
+    if (!m_imageElement || !m_imageSizeIsKnown || &m_imageElement->document() != this || pageZoomFactor(this) < 1)
         return;
 
     LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), 1.0f);
@@ -292,7 +292,7 @@
 
 bool ImageDocument::imageFitsInWindow() const
 {
-    if (!m_imageElement || m_imageElement->document() != this)
+    if (!m_imageElement || &m_imageElement->document() != this)
         return true;
 
     FrameView* view = frame()->view();
@@ -307,7 +307,7 @@
 
 void ImageDocument::windowSizeChanged()
 {
-    if (!m_imageElement || !m_imageSizeIsKnown || m_imageElement->document() != this)
+    if (!m_imageElement || !m_imageSizeIsKnown || &m_imageElement->document() != this)
         return;
 
     bool fitsInWindow = imageFitsInWindow();
diff --git a/Source/core/html/ImageInputType.cpp b/Source/core/html/ImageInputType.cpp
index 6711fee..06ada94 100644
--- a/Source/core/html/ImageInputType.cpp
+++ b/Source/core/html/ImageInputType.cpp
@@ -189,7 +189,7 @@
         }
     }
 
-    element->document()->updateLayout();
+    element->document().updateLayout();
 
     RenderBox* box = element->renderBox();
     return box ? adjustForAbsoluteZoom(box->contentHeight(), box) : 0;
@@ -213,7 +213,7 @@
         }
     }
 
-    element->document()->updateLayout();
+    element->document().updateLayout();
 
     RenderBox* box = element->renderBox();
     return box ? adjustForAbsoluteZoom(box->contentWidth(), box) : 0;
diff --git a/Source/core/html/InputType.cpp b/Source/core/html/InputType.cpp
index 80949f5..8f41d58 100644
--- a/Source/core/html/InputType.cpp
+++ b/Source/core/html/InputType.cpp
@@ -106,10 +106,15 @@
     return map.release();
 }
 
-PassRefPtr<InputType> InputType::create(HTMLInputElement* element, const AtomicString& typeName)
+static const InputTypeFactoryMap* factoryMap()
 {
     static const InputTypeFactoryMap* factoryMap = createInputTypeFactoryMap().leakPtr();
-    InputTypeFactoryFunction factory = typeName.isEmpty() ? 0 : factoryMap->get(typeName);
+    return factoryMap;
+}
+
+PassRefPtr<InputType> InputType::create(HTMLInputElement* element, const AtomicString& typeName)
+{
+    InputTypeFactoryFunction factory = typeName.isEmpty() ? 0 : factoryMap()->get(typeName);
     if (!factory)
         factory = TextInputType::create;
     return factory(element);
@@ -120,6 +125,24 @@
     return TextInputType::create(element);
 }
 
+const AtomicString& InputType::normalizeTypeName(const AtomicString& typeName)
+{
+    if (typeName.isEmpty())
+        return InputTypeNames::text();
+    InputTypeFactoryMap::const_iterator it = factoryMap()->find(typeName);
+    return it == factoryMap()->end() ? InputTypeNames::text() : it->key;
+}
+
+bool InputType::canChangeFromAnotherType(const AtomicString& normalizedTypeName)
+{
+    // Don't allow the type to be changed to file after the first type change.
+    // In other engines this might mean a JavaScript programmer could set a text
+    // field's value to something like /etc/passwd and then change it to a file
+    // input. I don't think this would actually occur in Blink, but this rule
+    // still may be important for compatibility.
+    return normalizedTypeName != InputTypeNames::file();
+}
+
 InputType::~InputType()
 {
 }
@@ -390,11 +413,11 @@
 
     root->removeChildren();
 
-    // It's ok to clear contents of all other ShadowRoots because they must have
-    // been created by InputFieldPasswordGeneratorButtonElement, and we don't allow adding
-    // AuthorShadowRoot to HTMLInputElement.
-    // FIXME: Remove the PasswordGeneratorButtonElement's shadow root and then remove this loop.
-    while ((root = root->youngerShadowRoot())) {
+    // It's ok to clear contents of all other UA ShadowRoots because they must
+    // have been created by InputFieldPasswordGeneratorButtonElement.
+    // FIXME: Remove the PasswordGeneratorButtonElement's shadow root and then
+    // remove this loop.
+    while ((root = root->youngerShadowRoot()) && root->type() == ShadowRoot::UserAgentShadowRoot) {
         root->removeChildren();
         root->appendChild(HTMLShadowElement::create(shadowTag, element()->document()));
     }
@@ -432,7 +455,7 @@
 
 Chrome* InputType::chrome() const
 {
-    if (Page* page = element()->document()->page())
+    if (Page* page = element()->document().page())
         return &page->chrome();
     return 0;
 }
@@ -488,11 +511,6 @@
     return false;
 }
 
-bool InputType::canChangeFromAnotherType() const
-{
-    return true;
-}
-
 void InputType::sanitizeValueInResponseToMinOrMaxAttributeChange()
 {
 }
@@ -827,7 +845,7 @@
 
     setValueAsDecimal(newValue, eventBehavior, es);
 
-    if (AXObjectCache* cache = element()->document()->existingAXObjectCache())
+    if (AXObjectCache* cache = element()->document().existingAXObjectCache())
         cache->postNotification(element(), AXObjectCache::AXValueChanged, true);
 }
 
@@ -960,7 +978,7 @@
 {
     if (RenderStyle* style = element()->renderStyle()) {
         if (style->visibility() != HIDDEN)
-            UseCounter::count(element()->document(), feature);
+            UseCounter::count(&element()->document(), feature);
     }
 }
 
diff --git a/Source/core/html/InputType.h b/Source/core/html/InputType.h
index e29feb3..b19742e 100644
--- a/Source/core/html/InputType.h
+++ b/Source/core/html/InputType.h
@@ -60,12 +60,13 @@
 public:
     static PassRefPtr<InputType> create(HTMLInputElement*, const AtomicString&);
     static PassRefPtr<InputType> createText(HTMLInputElement*);
+    static const AtomicString& normalizeTypeName(const AtomicString&);
     virtual ~InputType();
 
+    static bool canChangeFromAnotherType(const AtomicString& normalizedTypeName);
     static bool themeSupportsDataListUI(InputType*);
 
     virtual const AtomicString& formControlType() const = 0;
-    virtual bool canChangeFromAnotherType() const;
 
     // Type query functions
 
diff --git a/Source/core/html/LabelableElement.cpp b/Source/core/html/LabelableElement.cpp
index 8f31d0c..5eeab71 100644
--- a/Source/core/html/LabelableElement.cpp
+++ b/Source/core/html/LabelableElement.cpp
@@ -30,7 +30,7 @@
 
 namespace WebCore {
 
-LabelableElement::LabelableElement(const QualifiedName& tagName, Document* document)
+LabelableElement::LabelableElement(const QualifiedName& tagName, Document& document)
     : HTMLElement(tagName, document)
 {
 }
@@ -43,8 +43,6 @@
 {
     if (!supportLabels())
         return 0;
-    if (!document())
-        return 0;
 
     return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<LabelsNodeList>(this, LabelsNodeListType, starAtom);
 }
diff --git a/Source/core/html/LabelableElement.h b/Source/core/html/LabelableElement.h
index 86a23ed..259285c 100644
--- a/Source/core/html/LabelableElement.h
+++ b/Source/core/html/LabelableElement.h
@@ -44,7 +44,7 @@
     virtual bool supportLabels() const { return false; }
 
 protected:
-    LabelableElement(const QualifiedName& tagName, Document*);
+    LabelableElement(const QualifiedName& tagName, Document&);
 
 private:
     virtual bool isLabelable() const OVERRIDE FINAL { return true; }
diff --git a/Source/core/html/LinkImport.cpp b/Source/core/html/LinkImport.cpp
index 31703ac..37945f8 100644
--- a/Source/core/html/LinkImport.cpp
+++ b/Source/core/html/LinkImport.cpp
@@ -32,10 +32,11 @@
 #include "core/html/LinkImport.h"
 
 #include "core/dom/Document.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/html/HTMLImportLoader.h"
 #include "core/html/HTMLImportsController.h"
 #include "core/html/HTMLLinkElement.h"
-#include "core/loader/CrossOriginAccessControl.h"
+
 
 namespace WebCore {
 
@@ -67,12 +68,12 @@
         return;
     if (!m_owner)
         return;
-    if (!m_owner->document()->frame() && !m_owner->document()->import())
+    if (!m_owner->document().frame() && !m_owner->document().import())
         return;
 
-    if (!m_owner->document()->import()) {
-        ASSERT(m_owner->document()->frame()); // The document should be the master.
-        HTMLImportsController::provideTo(m_owner->document());
+    if (!m_owner->document().import()) {
+        ASSERT(m_owner->document().frame()); // The document should be the master.
+        HTMLImportsController::provideTo(&m_owner->document());
     }
 
     LinkRequestBuilder builder(m_owner);
@@ -81,7 +82,7 @@
         return;
     }
 
-    HTMLImport* parent = m_owner->document()->import();
+    HTMLImport* parent = m_owner->document().import();
     HTMLImportsController* controller = parent->controller();
     m_loader = controller->createLoader(parent, builder.build(true));
     if (!m_loader) {
diff --git a/Source/core/html/LinkResource.cpp b/Source/core/html/LinkResource.cpp
index 5c7cd47..5e74a89 100644
--- a/Source/core/html/LinkResource.cpp
+++ b/Source/core/html/LinkResource.cpp
@@ -52,14 +52,14 @@
     , m_url(m_owner->getNonEmptyURLAttribute(hrefAttr))
 {
     m_charset = m_owner->getAttribute(charsetAttr);
-    if (m_charset.isEmpty() && m_owner->document()->frame())
-        m_charset = m_owner->document()->charset();
+    if (m_charset.isEmpty() && m_owner->document().frame())
+        m_charset = m_owner->document().charset();
 }
 
 FetchRequest LinkRequestBuilder::build(bool blocking) const
 {
     ResourceLoadPriority priority = blocking ? ResourceLoadPriorityUnresolved : ResourceLoadPriorityVeryLow;
-    return FetchRequest(ResourceRequest(m_owner->document()->completeURL(m_url)), m_owner->localName(), m_charset, priority);
+    return FetchRequest(ResourceRequest(m_owner->document().completeURL(m_url)), m_owner->localName(), m_charset, priority);
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/MediaController.idl b/Source/core/html/MediaController.idl
index b988d1a..81171ec 100644
--- a/Source/core/html/MediaController.idl
+++ b/Source/core/html/MediaController.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=media,
+    EnabledAtRuntime=Media,
     Constructor,
     ConstructorCallWith=ScriptExecutionContext
 ] interface MediaController : EventTarget {
diff --git a/Source/core/html/MediaDocument.cpp b/Source/core/html/MediaDocument.cpp
index f913bf7..874a45e 100644
--- a/Source/core/html/MediaDocument.cpp
+++ b/Source/core/html/MediaDocument.cpp
@@ -72,25 +72,26 @@
 
 void MediaDocumentParser::createDocumentStructure()
 {
-    RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(document());
+    ASSERT(document());
+    RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(*document());
     rootElement->insertedByParser();
     document()->appendChild(rootElement);
 
     if (document()->frame())
         document()->frame()->loader()->dispatchDocumentElementAvailable();
 
-    RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(document());
-    RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(document());
+    RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(*document());
+    RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(*document());
     meta->setAttribute(nameAttr, "viewport");
     meta->setAttribute(contentAttr, "width=device-width");
     head->appendChild(meta.release());
 
-    RefPtr<HTMLVideoElement> media = HTMLVideoElement::create(document());
+    RefPtr<HTMLVideoElement> media = HTMLVideoElement::create(*document());
     media->setAttribute(controlsAttr, "");
     media->setAttribute(autoplayAttr, "");
     media->setAttribute(nameAttr, "media");
 
-    RefPtr<HTMLSourceElement> source = HTMLSourceElement::create(document());
+    RefPtr<HTMLSourceElement> source = HTMLSourceElement::create(*document());
     source->setSrc(document()->url());
 
     if (DocumentLoader* loader = document()->loader())
@@ -98,7 +99,7 @@
 
     media->appendChild(source.release());
 
-    RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(document());
+    RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(*document());
     body->appendChild(media.release());
 
     rootElement->appendChild(head.release());
diff --git a/Source/core/html/MediaError.idl b/Source/core/html/MediaError.idl
index 3d35b71..376159d 100644
--- a/Source/core/html/MediaError.idl
+++ b/Source/core/html/MediaError.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=media
+    EnabledAtRuntime=Media
 ] interface MediaError {
       const unsigned short MEDIA_ERR_ABORTED = 1;
       const unsigned short MEDIA_ERR_NETWORK = 2;
diff --git a/Source/core/html/MediaKeyError.idl b/Source/core/html/MediaKeyError.idl
index a2660d7..ea442f8 100644
--- a/Source/core/html/MediaKeyError.idl
+++ b/Source/core/html/MediaKeyError.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=encryptedMediaAnyVersion
+    EnabledAtRuntime=EncryptedMediaAnyVersion
 ] interface MediaKeyError {
     const unsigned short MEDIA_KEYERR_UNKNOWN = 1;
     const unsigned short MEDIA_KEYERR_CLIENT = 2;
@@ -33,5 +33,5 @@
     const unsigned short MEDIA_KEYERR_HARDWARECHANGE = 5;
     const unsigned short MEDIA_KEYERR_DOMAIN = 6;
     readonly attribute unsigned short code;
-    [Conditional=ENCRYPTED_MEDIA_V2, EnabledAtRuntime=encryptedMedia] readonly attribute unsigned long systemCode;
+    [Conditional=ENCRYPTED_MEDIA_V2, EnabledAtRuntime=EncryptedMedia] readonly attribute unsigned long systemCode;
 };
diff --git a/Source/core/html/MediaKeyEvent.idl b/Source/core/html/MediaKeyEvent.idl
index 78c0ecb..297eabe 100644
--- a/Source/core/html/MediaKeyEvent.idl
+++ b/Source/core/html/MediaKeyEvent.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=legacyEncryptedMedia,
+    EnabledAtRuntime=LegacyEncryptedMedia,
     ConstructorTemplate=Event
 ] interface MediaKeyEvent : Event {
     [InitializedByEventConstructor] readonly attribute DOMString keySystem;
diff --git a/Source/core/html/PasswordInputType.cpp b/Source/core/html/PasswordInputType.cpp
index 834eb3a..ddad942 100644
--- a/Source/core/html/PasswordInputType.cpp
+++ b/Source/core/html/PasswordInputType.cpp
@@ -55,7 +55,7 @@
 
 bool PasswordInputType::isPasswordGenerationEnabled() const
 {
-    if (Page* page = element()->document()->page())
+    if (Page* page = element()->document().page())
         return page->chrome().client().isPasswordGenerationEnabled();
     return false;
 }
@@ -132,14 +132,14 @@
 
 void PasswordInputType::enableSecureTextInput()
 {
-    if (element()->document()->frame())
-        element()->document()->setUseSecureKeyboardEntryWhenActive(true);
+    if (element()->document().frame())
+        element()->document().setUseSecureKeyboardEntryWhenActive(true);
 }
 
 void PasswordInputType::disableSecureTextInput()
 {
-    if (element()->document()->frame())
-        element()->document()->setUseSecureKeyboardEntryWhenActive(false);
+    if (element()->document().frame())
+        element()->document().setUseSecureKeyboardEntryWhenActive(false);
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/PluginDocument.cpp b/Source/core/html/PluginDocument.cpp
index 0a53906..2f8ae7e 100644
--- a/Source/core/html/PluginDocument.cpp
+++ b/Source/core/html/PluginDocument.cpp
@@ -73,6 +73,7 @@
 {
     // FIXME: Assert we have a loader to figure out why the original null checks
     // and assert were added for the security bug in http://trac.webkit.org/changeset/87566
+    ASSERT(document());
     RELEASE_ASSERT(document()->loader());
 
     Frame* frame = document()->frame();
@@ -83,18 +84,18 @@
     if (!frame->settings() || !frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
         return;
 
-    RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(document());
+    RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(*document());
     rootElement->insertedByParser();
     document()->appendChild(rootElement);
     frame->loader()->dispatchDocumentElementAvailable();
 
-    RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(document());
+    RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(*document());
     body->setAttribute(marginwidthAttr, "0");
     body->setAttribute(marginheightAttr, "0");
     body->setAttribute(styleAttr, "background-color: rgb(38,38,38)");
     rootElement->appendChild(body);
 
-    m_embedElement = HTMLEmbedElement::create(document());
+    m_embedElement = HTMLEmbedElement::create(*document());
     m_embedElement->setAttribute(widthAttr, "100%");
     m_embedElement->setAttribute(heightAttr, "100%");
     m_embedElement->setAttribute(nameAttr, "plugin");
@@ -142,9 +143,9 @@
 
 PluginView* PluginDocumentParser::pluginView() const
 {
-    if (Widget* widget = static_cast<PluginDocument*>(document())->pluginWidget()) {
+    if (Widget* widget = toPluginDocument(document())->pluginWidget()) {
         ASSERT_WITH_SECURITY_IMPLICATION(widget->isPluginContainer());
-        return static_cast<PluginView*>(widget);
+        return toPluginView(widget);
     }
     return 0;
 }
diff --git a/Source/core/html/PluginDocument.h b/Source/core/html/PluginDocument.h
index 458dfc1..9764a9d 100644
--- a/Source/core/html/PluginDocument.h
+++ b/Source/core/html/PluginDocument.h
@@ -73,6 +73,12 @@
     return static_cast<const PluginDocument*>(document);
 }
 
+inline PluginDocument& toPluginDocument(Document& document)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(document.isPluginDocument());
+    return static_cast<PluginDocument&>(document);
+}
+
 // This will catch anyone doing an unnecessary cast.
 void toPluginDocument(const PluginDocument*);
 
diff --git a/Source/core/html/RadioInputType.cpp b/Source/core/html/RadioInputType.cpp
index 3039705..8b3dac2 100644
--- a/Source/core/html/RadioInputType.cpp
+++ b/Source/core/html/RadioInputType.cpp
@@ -75,8 +75,8 @@
     // Tested in WinIE, and even for RTL, left still means previous radio button (and so moves
     // to the right).  Seems strange, but we'll match it.
     // However, when using Spatial Navigation, we need to be able to navigate without changing the selection.
-    Document* document = element()->document();
-    if (isSpatialNavigationEnabled(document->frame()))
+    Document& document = element()->document();
+    if (isSpatialNavigationEnabled(document.frame()))
         return;
     bool forward = (key == "Down" || key == "Right");
 
@@ -95,7 +95,7 @@
             break;
         if (inputElement->isRadioButton() && inputElement->name() == element()->name() && inputElement->isFocusable()) {
             RefPtr<HTMLInputElement> protector(inputElement);
-            document->setFocusedElement(inputElement);
+            document.setFocusedElement(inputElement);
             inputElement->dispatchSimulatedClick(event, SendNoEvents, DoNotShowPressedLook);
             event->setDefaultHandled();
             return;
@@ -121,12 +121,12 @@
         return false;
 
     // When using Spatial Navigation, every radio button should be focusable.
-    if (isSpatialNavigationEnabled(element()->document()->frame()))
+    if (isSpatialNavigationEnabled(element()->document().frame()))
         return true;
 
     // Never allow keyboard tabbing to leave you in the same radio group.  Always
     // skip any other elements in the group.
-    Element* currentFocusedElement = element()->document()->focusedElement();
+    Element* currentFocusedElement = element()->document().focusedElement();
     if (currentFocusedElement && currentFocusedElement->hasTagName(inputTag)) {
         HTMLInputElement* focusedInput = toHTMLInputElement(currentFocusedElement);
         if (focusedInput->isRadioButton() && focusedInput->form() == element()->form() && focusedInput->name() == element()->name())
diff --git a/Source/core/html/RangeInputType.cpp b/Source/core/html/RangeInputType.cpp
index bc4c4ee..08f3608 100644
--- a/Source/core/html/RangeInputType.cpp
+++ b/Source/core/html/RangeInputType.cpp
@@ -232,7 +232,7 @@
         TextFieldEventBehavior eventBehavior = DispatchChangeEvent;
         setValueAsDecimal(newValue, eventBehavior, IGNORE_EXCEPTION);
 
-        if (AXObjectCache* cache = element()->document()->existingAXObjectCache())
+        if (AXObjectCache* cache = element()->document().existingAXObjectCache())
             cache->postNotification(element(), AXObjectCache::AXValueChanged, true);
         element()->dispatchFormControlChangeEvent();
     }
@@ -244,7 +244,7 @@
 {
     ASSERT(element()->shadow());
 
-    Document* document = element()->document();
+    Document& document = element()->document();
     RefPtr<HTMLDivElement> track = HTMLDivElement::create(document);
     track->setPart(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
     track->setAttribute(idAttr, ShadowElementNames::sliderTrack());
diff --git a/Source/core/html/StepRange.cpp b/Source/core/html/StepRange.cpp
index 60a1e87..cc3768b 100644
--- a/Source/core/html/StepRange.cpp
+++ b/Source/core/html/StepRange.cpp
@@ -25,6 +25,7 @@
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "wtf/MathExtras.h"
 #include "wtf/text/WTFString.h"
+#include <float.h>
 
 using namespace std;
 
diff --git a/Source/core/html/TextFieldInputType.cpp b/Source/core/html/TextFieldInputType.cpp
index 8a49a91..a599562 100644
--- a/Source/core/html/TextFieldInputType.cpp
+++ b/Source/core/html/TextFieldInputType.cpp
@@ -86,9 +86,9 @@
 
 static inline bool shouldIgnoreRequiredAttribute(const HTMLInputElement& input)
 {
-    if (!input.document()->settings() || !input.document()->settings()->needsSiteSpecificQuirks())
+    if (!input.document().settings() || !input.document().settings()->needsSiteSpecificQuirks())
         return false;
-    if (!equalIgnoringCase(input.document()->url().host(), "egov.uscis.gov"))
+    if (!equalIgnoringCase(input.document().url().host(), "egov.uscis.gov"))
         return false;
     return input.fastGetAttribute(requiredAttr) == "no";
 }
@@ -145,8 +145,7 @@
         break;
     }
 
-    // FIXME: Why do we do this when eventBehavior == DispatchNoEvent
-    if (!input->focused() || eventBehavior == DispatchNoEvent)
+    if (!input->focused())
         input->setTextAsOfLastFormControlChangeEvent(sanitizedValue);
 }
 
@@ -154,7 +153,7 @@
 {
     if (!element()->focused())
         return;
-    Frame* frame = element()->document()->frame();
+    Frame* frame = element()->document().frame();
     if (!frame || !frame->editor().doTextFieldCommandFromEvent(element(), event))
         return;
     event->setDefaultHandled();
@@ -188,7 +187,7 @@
             if (RenderBox* innerTextRenderer = innerTextElement()->renderBox()) {
                 if (RenderLayer* innerLayer = innerTextRenderer->layer()) {
                     IntSize scrollOffset(!renderTextControl->style()->isLeftToRightDirection() ? innerLayer->scrollWidth() : 0, 0);
-                    innerLayer->scrollToOffset(scrollOffset, RenderLayer::ScrollOffsetClamped);
+                    innerLayer->scrollToOffset(scrollOffset, ScrollOffsetClamped);
                 }
             }
 
@@ -243,7 +242,7 @@
     ASSERT(!m_innerText);
     ASSERT(!m_innerBlock);
 
-    Document* document = element()->document();
+    Document& document = element()->document();
     bool shouldHaveSpinButton = this->shouldHaveSpinButton();
     bool createsContainer = shouldHaveSpinButton || needsContainer();
 
@@ -337,9 +336,9 @@
     return c == '\r' || c == '\n';
 }
 
-static String limitLength(const String& string, int maxLength)
+static String limitLength(const String& string, unsigned maxLength)
 {
-    unsigned newLength = maxLength;
+    unsigned newLength = std::min(maxLength, string.length());
     // FIXME: We should not truncate the string at a control character. It's not
     // compatible with IE and Firefox.
     for (unsigned i = 0; i < newLength; ++i) {
@@ -349,6 +348,8 @@
             break;
         }
     }
+    if (newLength == string.length())
+        return string;
     if (newLength > 0 && U16_IS_LEAD(string[newLength - 1]))
         --newLength;
     return string.left(newLength);
@@ -373,7 +374,7 @@
     // If the text field has no focus, we don't need to take account of the
     // selection length. The selection is the source of text drag-and-drop in
     // that case, and nothing in the text field will be removed.
-    unsigned selectionLength = element()->focused() ? plainText(element()->document()->frame()->selection()->selection().toNormalizedRange().get()).length() : 0;
+    unsigned selectionLength = element()->focused() ? plainText(element()->document().frame()->selection().selection().toNormalizedRange().get()).length() : 0;
     ASSERT(oldLength >= selectionLength);
 
     // Selected characters will be removed by the next text event.
@@ -456,7 +457,7 @@
 {
     if (!element()->focused())
         return;
-    if (Frame* frame = element()->document()->frame())
+    if (Frame* frame = element()->document().frame())
         frame->editor().textDidChangeInTextField(element());
 }
 
diff --git a/Source/core/html/TimeRanges.idl b/Source/core/html/TimeRanges.idl
index ec11b43..3aa6b88 100644
--- a/Source/core/html/TimeRanges.idl
+++ b/Source/core/html/TimeRanges.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=media
+    EnabledAtRuntime=Media
 ] interface TimeRanges {
     readonly attribute unsigned long length;
     [RaisesException] double start(unsigned long index);
diff --git a/Source/core/html/ValidationMessage.cpp b/Source/core/html/ValidationMessage.cpp
index 7b4e298..faa67e2 100644
--- a/Source/core/html/ValidationMessage.cpp
+++ b/Source/core/html/ValidationMessage.cpp
@@ -57,7 +57,7 @@
 
 ValidationMessageClient* ValidationMessage::validationMessageClient() const
 {
-    Page* page = m_element->document()->page();
+    Page* page = m_element->document().page();
     if (!page)
         return 0;
     // The form valdiation feature requires ValidationMessageClient.
diff --git a/Source/core/html/canvas/Canvas2DContextAttributes.idl b/Source/core/html/canvas/Canvas2DContextAttributes.idl
index d6178d4..f756bda 100644
--- a/Source/core/html/canvas/Canvas2DContextAttributes.idl
+++ b/Source/core/html/canvas/Canvas2DContextAttributes.idl
@@ -26,7 +26,7 @@
 
 [
     NoInterfaceObject,
-    EnabledAtRuntime=experimentalCanvasFeatures
+    EnabledAtRuntime=ExperimentalCanvasFeatures
 ] interface Canvas2DContextAttributes {
     attribute boolean alpha;
 };
diff --git a/Source/core/html/canvas/CanvasPathMethods.cpp b/Source/core/html/canvas/CanvasPathMethods.cpp
index 90dc9e7..9104eac 100644
--- a/Source/core/html/canvas/CanvasPathMethods.cpp
+++ b/Source/core/html/canvas/CanvasPathMethods.cpp
@@ -5,7 +5,7 @@
  * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
  * Copyright (C) 2008 Dirk Schulze <krit@webkit.org>
  * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
- * Copyright (C) 2012 Intel Corporation. All rights reserved.
+ * Copyright (C) 2012, 2013 Intel Corporation. All rights reserved.
  * Copyright (C) 2012, 2013 Adobe Systems Incorporated. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -131,7 +131,9 @@
         m_path.addArcTo(p1, p2, r);
 }
 
-static float adjustEndAngle(float startAngle, float endAngle, bool anticlockwise)
+namespace {
+
+float adjustEndAngle(float startAngle, float endAngle, bool anticlockwise)
 {
     float twoPi = 2 * piFloat;
     float newEndAngle = endAngle;
@@ -164,40 +166,17 @@
     return newEndAngle;
 }
 
-void CanvasPathMethods::arc(float x, float y, float radius, float startAngle, float endAngle, bool anticlockwise, ExceptionState& es)
-{
-    if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radius) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
-        return;
-
-    if (radius < 0) {
-        es.throwDOMException(IndexSizeError);
-        return;
-    }
-
-    if (!isTransformInvertible())
-        return;
-
-    if (!radius || startAngle == endAngle) {
-        // The arc is empty but we still need to draw the connecting line.
-        lineTo(x + radius * cosf(startAngle), y + radius * sinf(startAngle));
-        return;
-    }
-
-    float adjustedEndAngle = adjustEndAngle(startAngle, endAngle, anticlockwise);
-    m_path.addArc(FloatPoint(x, y), radius, startAngle, adjustedEndAngle, anticlockwise);
-}
-
-inline static void lineToFloatPoint(CanvasPathMethods* path, const FloatPoint& p)
+inline void lineToFloatPoint(CanvasPathMethods* path, const FloatPoint& p)
 {
     path->lineTo(p.x(), p.y());
 }
 
-inline static FloatPoint getPointOnEllipse(float radiusX, float radiusY, float theta)
+inline FloatPoint getPointOnEllipse(float radiusX, float radiusY, float theta)
 {
     return FloatPoint(radiusX * cosf(theta), radiusY * sinf(theta));
 }
 
-inline static void canonicalizeAngle(float* startAngle, float* endAngle)
+void canonicalizeAngle(float* startAngle, float* endAngle)
 {
     // Make 0 <= startAngle < 2*PI
     float twoPi = 2 * piFloat;
@@ -210,6 +189,7 @@
     float delta = newStartAngle - *startAngle;
     *startAngle = newStartAngle;
     *endAngle = *endAngle + delta;
+    ASSERT(newStartAngle >= 0 && newStartAngle < twoPi);
 }
 
 /*
@@ -243,9 +223,11 @@
  * To handle both cases, degenerateEllipse() lines to start angle, local maximum points(every 0.5Pi), and end angle.
  * NOTE: Before ellipse() calls this function, adjustEndAngle() is called, so endAngle - startAngle must be less than 4Pi.
  */
-static void degenerateEllipse(CanvasPathMethods* path, float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise)
+void degenerateEllipse(CanvasPathMethods* path, float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise)
 {
     ASSERT(std::abs(endAngle - startAngle) < 4 * piFloat);
+    ASSERT(startAngle >= 0 && startAngle < 2 * piFloat);
+    ASSERT((anticlockwise && (startAngle - endAngle) >= 0) || (!anticlockwise && (endAngle - startAngle) >= 0));
 
     FloatPoint center(x, y);
     AffineTransform rotationMatrix;
@@ -255,9 +237,6 @@
     if ((!radiusX && !radiusY) || startAngle == endAngle)
         return;
 
-    canonicalizeAngle(&startAngle, &endAngle);
-    ASSERT(std::abs(endAngle - startAngle) < 4 * piFloat);
-
     float halfPiFloat = piFloat * 0.5;
     if (!anticlockwise) {
         // startAngle - fmodf(startAngle, halfPiFloat) + halfPiFloat is the one of (0, 0.5Pi, Pi, 1.5Pi, 2Pi)
@@ -272,6 +251,32 @@
     lineToFloatPoint(path, center + rotationMatrix.mapPoint(getPointOnEllipse(radiusX, radiusY, endAngle)));
 }
 
+} // namespace
+
+void CanvasPathMethods::arc(float x, float y, float radius, float startAngle, float endAngle, bool anticlockwise, ExceptionState& es)
+{
+    if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radius) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
+        return;
+
+    if (radius < 0) {
+        es.throwDOMException(IndexSizeError);
+        return;
+    }
+
+    if (!isTransformInvertible())
+        return;
+
+    if (!radius || startAngle == endAngle) {
+        // The arc is empty but we still need to draw the connecting line.
+        lineTo(x + radius * cosf(startAngle), y + radius * sinf(startAngle));
+        return;
+    }
+
+    canonicalizeAngle(&startAngle, &endAngle);
+    float adjustedEndAngle = adjustEndAngle(startAngle, endAngle, anticlockwise);
+    m_path.addArc(FloatPoint(x, y), radius, startAngle, adjustedEndAngle, anticlockwise);
+}
+
 void CanvasPathMethods::ellipse(float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise, ExceptionState& es)
 {
     if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radiusX) || !std::isfinite(radiusY) || !std::isfinite(rotation) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
@@ -285,6 +290,7 @@
     if (!isTransformInvertible())
         return;
 
+    canonicalizeAngle(&startAngle, &endAngle);
     float adjustedEndAngle = adjustEndAngle(startAngle, endAngle, anticlockwise);
     if (!radiusX || !radiusY || startAngle == adjustedEndAngle) {
         // The ellipse is empty but we still need to draw the connecting line to start point.
diff --git a/Source/core/html/canvas/CanvasRenderingContext.cpp b/Source/core/html/canvas/CanvasRenderingContext.cpp
index 4f362bc..7d259a4 100644
--- a/Source/core/html/canvas/CanvasRenderingContext.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext.cpp
@@ -61,7 +61,7 @@
         return false;
 
     ImageResource* cachedImage = image->cachedImage();
-    if (!cachedImage->image()->hasSingleSecurityOrigin())
+    if (!cachedImage->image()->currentFrameHasSingleSecurityOrigin())
         return true;
 
     return wouldTaintOrigin(cachedImage->response().url()) && !cachedImage->passesAccessControlCheck(canvas()->securityOrigin());
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index f774c4a..968cac2 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -5,7 +5,7 @@
  * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
  * Copyright (C) 2008 Dirk Schulze <krit@webkit.org>
  * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
- * Copyright (C) 2012 Intel Corporation. All rights reserved.
+ * Copyright (C) 2012, 2013 Intel Corporation. All rights reserved.
  * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -81,7 +81,7 @@
 
 static bool isOriginClean(ImageResource* cachedImage, SecurityOrigin* securityOrigin)
 {
-    if (!cachedImage->image()->hasSingleSecurityOrigin())
+    if (!cachedImage->image()->currentFrameHasSingleSecurityOrigin())
         return false;
     if (cachedImage->passesAccessControlCheck(securityOrigin))
         return true;
@@ -708,6 +708,31 @@
     m_path.transform(transform.inverse());
 }
 
+void CanvasRenderingContext2D::resetTransform()
+{
+    GraphicsContext* c = drawingContext();
+    if (!c)
+        return;
+
+    AffineTransform ctm = state().m_transform;
+    bool invertibleCTM = state().m_invertibleCTM;
+    // It is possible that CTM is identity while CTM is not invertible.
+    // When CTM becomes non-invertible, realizeSaves() can make CTM identity.
+    if (ctm.isIdentity() && invertibleCTM)
+        return;
+
+    realizeSaves();
+    // resetTransform() resolves the non-invertible CTM state.
+    modifiableState().m_transform.makeIdentity();
+    modifiableState().m_invertibleCTM = true;
+    c->setCTM(canvas()->baseTransform());
+
+    if (invertibleCTM)
+        m_path.transform(ctm.inverse());
+    // When else, do nothing because all transform methods didn't update m_path when CTM became non-invertible.
+    // It means that resetTransform() restores m_path just before CTM became non-invertible.
+}
+
 void CanvasRenderingContext2D::setTransform(float m11, float m12, float m21, float m22, float dx, float dy)
 {
     GraphicsContext* c = drawingContext();
@@ -736,7 +761,7 @@
     if (color == state().m_unparsedStrokeColor)
         return;
     realizeSaves();
-    setStrokeStyle(CanvasStyle::createFromString(color, canvas()->document()));
+    setStrokeStyle(CanvasStyle::createFromString(color, &canvas()->document()));
     modifiableState().m_unparsedStrokeColor = color;
 }
 
@@ -778,7 +803,7 @@
     if (color == state().m_unparsedFillColor)
         return;
     realizeSaves();
-    setFillStyle(CanvasStyle::createFromString(color, canvas()->document()));
+    setFillStyle(CanvasStyle::createFromString(color, &canvas()->document()));
     modifiableState().m_unparsedFillColor = color;
 }
 
@@ -1586,21 +1611,6 @@
     c->restore();
 }
 
-Path CanvasRenderingContext2D::transformAreaToDevice(const Path& path) const
-{
-    Path transformed(path);
-    transformed.transform(state().m_transform);
-    transformed.transform(canvas()->baseTransform());
-    return transformed;
-}
-
-Path CanvasRenderingContext2D::transformAreaToDevice(const FloatRect& rect) const
-{
-    Path path;
-    path.addRect(rect);
-    return transformAreaToDevice(path);
-}
-
 bool CanvasRenderingContext2D::rectContainsCanvas(const FloatRect& rect) const
 {
     FloatQuad quad(rect);
@@ -1608,48 +1618,7 @@
     return state().m_transform.mapQuad(quad).containsQuad(canvasQuad);
 }
 
-template<class T> IntRect CanvasRenderingContext2D::calculateCompositingBufferRect(const T& area, IntSize* croppedOffset)
-{
-    IntRect canvasRect(0, 0, canvas()->width(), canvas()->height());
-    canvasRect = canvas()->baseTransform().mapRect(canvasRect);
-    Path path = transformAreaToDevice(area);
-    IntRect bufferRect = enclosingIntRect(path.boundingRect());
-    IntPoint originalLocation = bufferRect.location();
-    bufferRect.intersect(canvasRect);
-    if (croppedOffset)
-        *croppedOffset = originalLocation - bufferRect.location();
-    return bufferRect;
-}
-
-PassOwnPtr<ImageBuffer> CanvasRenderingContext2D::createCompositingBuffer(const IntRect& bufferRect)
-{
-    RenderingMode renderMode = isAccelerated() ? Accelerated : Unaccelerated;
-    return ImageBuffer::create(bufferRect.size(), 1, renderMode);
-}
-
-void CanvasRenderingContext2D::compositeBuffer(ImageBuffer* buffer, const IntRect& bufferRect, CompositeOperator op)
-{
-    IntRect canvasRect(0, 0, canvas()->width(), canvas()->height());
-    canvasRect = canvas()->baseTransform().mapRect(canvasRect);
-
-    GraphicsContext* c = drawingContext();
-    if (!c)
-        return;
-
-    c->save();
-    c->setCTM(AffineTransform());
-    c->setCompositeOperation(op);
-
-    c->save();
-    c->clipOut(bufferRect);
-    c->clearRect(canvasRect);
-    c->restore();
-
-    c->drawImageBuffer(buffer, bufferRect.location(), state().m_globalComposite);
-    c->restore();
-}
-
-static void drawImageToContext(Image* image, GraphicsContext* context, FloatRect& dest, const FloatRect& src, CompositeOperator op)
+static void drawImageToContext(Image* image, GraphicsContext* context, const FloatRect& dest, const FloatRect& src, CompositeOperator op)
 {
     context->drawImage(image, dest, src, op);
 }
@@ -1663,55 +1632,33 @@
 {
     ASSERT(isFullCanvasCompositeMode(op));
 
-    IntSize croppedOffset;
-    IntRect bufferRect = calculateCompositingBufferRect(dest, &croppedOffset);
-    if (bufferRect.isEmpty()) {
-        clearCanvas();
-        return;
-    }
+    drawingContext()->beginTransparencyLayer(1, op);
+    drawImageToContext(image, drawingContext(), dest, src, CompositeSourceOver);
+    drawingContext()->endLayer();
+}
 
-    OwnPtr<ImageBuffer> buffer = createCompositingBuffer(bufferRect);
-    if (!buffer)
-        return;
+static void fillPrimitive(const FloatRect& rect, GraphicsContext* context)
+{
+    context->fillRect(rect);
+}
 
-    GraphicsContext* c = drawingContext();
-    if (!c)
-        return;
-
-    FloatRect adjustedDest = dest;
-    adjustedDest.setLocation(FloatPoint(0, 0));
-    AffineTransform effectiveTransform = c->getCTM();
-    IntRect transformedAdjustedRect = enclosingIntRect(effectiveTransform.mapRect(adjustedDest));
-    buffer->context()->translate(-transformedAdjustedRect.location().x(), -transformedAdjustedRect.location().y());
-    buffer->context()->translate(croppedOffset.width(), croppedOffset.height());
-    buffer->context()->concatCTM(effectiveTransform);
-    drawImageToContext(image, buffer->context(), adjustedDest, src, CompositeSourceOver);
-
-    compositeBuffer(buffer.get(), bufferRect, op);
+static void fillPrimitive(const Path& path, GraphicsContext* context)
+{
+    context->fillPath(path);
 }
 
 template<class T> void CanvasRenderingContext2D::fullCanvasCompositedFill(const T& area)
 {
     ASSERT(isFullCanvasCompositeMode(state().m_globalComposite));
 
-    IntRect bufferRect = calculateCompositingBufferRect(area, 0);
-    if (bufferRect.isEmpty()) {
-        clearCanvas();
-        return;
-    }
-
-    OwnPtr<ImageBuffer> buffer = createCompositingBuffer(bufferRect);
-    if (!buffer)
-        return;
-
-    Path path = transformAreaToDevice(area);
-    path.translate(FloatSize(-bufferRect.x(), -bufferRect.y()));
-
-    buffer->context()->setCompositeOperation(CompositeSourceOver);
-    state().m_fillStyle->applyFillColor(buffer->context());
-    buffer->context()->fillPath(path);
-
-    compositeBuffer(buffer.get(), bufferRect, state().m_globalComposite);
+    GraphicsContext* c = drawingContext();
+    ASSERT(c);
+    c->beginTransparencyLayer(1, state().m_globalComposite);
+    CompositeOperator previousOperator = c->compositeOperation();
+    c->setCompositeOperation(CompositeSourceOver);
+    fillPrimitive(area, c);
+    c->setCompositeOperation(previousOperator);
+    c->endLayer();
 }
 
 PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1, ExceptionState& es)
@@ -2306,7 +2253,7 @@
 
 const Font& CanvasRenderingContext2D::accessFont()
 {
-    canvas()->document()->updateStyleIfNeeded();
+    canvas()->document().updateStyleIfNeeded();
 
     if (!state().m_realizedFont)
         setFont(state().m_unparsedFont);
@@ -2351,7 +2298,7 @@
     // Note: we need to check document->focusedElement() rather than just calling
     // element->focused(), because element->focused() isn't updated until after
     // focus events fire.
-    if (element->document() && element->document()->focusedElement() == element)
+    if (element->document().focusedElement() == element)
         drawFocusRing(m_path);
 }
 
@@ -2388,7 +2335,7 @@
     // bounding box with the accessible object. Do this even if the element
     // isn't focused because assistive technology might try to explore the object's
     // location before it gets focus.
-    if (AXObjectCache* axObjectCache = element->document()->existingAXObjectCache()) {
+    if (AXObjectCache* axObjectCache = element->document().existingAXObjectCache()) {
         if (AccessibilityObject* obj = axObjectCache->getOrCreate(element)) {
             // Get the bounding rect and apply transformations.
             FloatRect bounds = m_path.boundingRect();
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.h b/Source/core/html/canvas/CanvasRenderingContext2D.h
index a76a954..46107a2 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.h
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.h
@@ -122,6 +122,7 @@
     void translate(float tx, float ty);
     void transform(float m11, float m12, float m21, float m22, float dx, float dy);
     void setTransform(float m11, float m12, float m21, float m22, float dx, float dy);
+    void resetTransform();
 
     void setStrokeColor(const String& color);
     void setStrokeColor(float grayLevel);
@@ -309,14 +310,8 @@
     const Font& accessFont();
 
     void clearCanvas();
-    Path transformAreaToDevice(const Path&) const;
-    Path transformAreaToDevice(const FloatRect&) const;
     bool rectContainsCanvas(const FloatRect&) const;
 
-    template<class T> IntRect calculateCompositingBufferRect(const T&, IntSize*);
-    PassOwnPtr<ImageBuffer> createCompositingBuffer(const IntRect&);
-    void compositeBuffer(ImageBuffer*, const IntRect&, CompositeOperator);
-
     void inflateStrokeRect(FloatRect&) const;
 
     template<class T> void fullCanvasCompositedFill(const T&);
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.idl b/Source/core/html/canvas/CanvasRenderingContext2D.idl
index 625e44e..69a3ffa 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.idl
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.idl
@@ -35,6 +35,7 @@
     void translate(float tx, float ty);
     void transform(float m11, float m12, float m21, float m22, float dx, float dy);
     void setTransform(float m11, float m12, float m21, float m22, float dx, float dy);
+    void resetTransform();
 
     attribute float globalAlpha;
     [TreatNullAs=NullString] attribute DOMString globalCompositeOperation;
@@ -127,9 +128,9 @@
     [RaisesException] void drawImage(HTMLVideoElement? video, float x, float y);
     [RaisesException] void drawImage(HTMLVideoElement? video, float x, float y, float width, float height);
     [RaisesException] void drawImage(HTMLVideoElement? video, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh);
-    [EnabledAtRuntime=experimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float x, float y);
-    [EnabledAtRuntime=experimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float x, float y, float width, float height);
-    [EnabledAtRuntime=experimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh);
+    [EnabledAtRuntime=ExperimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float x, float y);
+    [EnabledAtRuntime=ExperimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float x, float y, float width, float height);
+    [EnabledAtRuntime=ExperimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh);
 
     void drawImageFromRect(HTMLImageElement image,
                            optional float sx, optional float sy, optional float sw, optional float sh,
@@ -161,14 +162,14 @@
     [RaisesException] ImageData webkitGetImageDataHD(float sx, float sy, float sw, float sh);
 
     // Focus rings
-    [EnabledAtRuntime=experimentalCanvasFeatures] void drawSystemFocusRing(Element element);
-    [EnabledAtRuntime=experimentalCanvasFeatures] boolean drawCustomFocusRing(Element element);
+    [EnabledAtRuntime=ExperimentalCanvasFeatures] void drawSystemFocusRing(Element element);
+    [EnabledAtRuntime=ExperimentalCanvasFeatures] boolean drawCustomFocusRing(Element element);
 
     readonly attribute float webkitBackingStorePixelRatio;
 
     [ImplementedAs=imageSmoothingEnabled] attribute boolean webkitImageSmoothingEnabled;
     attribute boolean imageSmoothingEnabled;
 
-    [EnabledAtRuntime=experimentalCanvasFeatures] Canvas2DContextAttributes getContextAttributes();
+    [EnabledAtRuntime=ExperimentalCanvasFeatures] Canvas2DContextAttributes getContextAttributes();
 };
 
diff --git a/Source/core/html/canvas/CanvasStyle.cpp b/Source/core/html/canvas/CanvasStyle.cpp
index 866610d..3e9e869 100644
--- a/Source/core/html/canvas/CanvasStyle.cpp
+++ b/Source/core/html/canvas/CanvasStyle.cpp
@@ -65,7 +65,7 @@
 
 bool parseColorOrCurrentColor(RGBA32& parsedColor, const String& colorString, HTMLCanvasElement* canvas)
 {
-    ColorParseResult parseResult = parseColor(parsedColor, colorString, canvas ? canvas->document() : 0);
+    ColorParseResult parseResult = parseColor(parsedColor, colorString, canvas ? &canvas->document() : 0);
     switch (parseResult) {
     case ParsedRGBA:
     case ParsedSystemColor:
diff --git a/Source/core/html/canvas/Path.idl b/Source/core/html/canvas/Path.idl
index 5b767e3..ce19874 100644
--- a/Source/core/html/canvas/Path.idl
+++ b/Source/core/html/canvas/Path.idl
@@ -27,7 +27,7 @@
  */
 
 [
-    EnabledAtRuntime=experimentalCanvasFeatures,
+    EnabledAtRuntime=ExperimentalCanvasFeatures,
     Constructor,
     Constructor(Path path),
     Constructor(DOMString text),
diff --git a/Source/core/html/canvas/WebGLRenderingContext.cpp b/Source/core/html/canvas/WebGLRenderingContext.cpp
index 97b2d6d..a706605 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -494,8 +494,8 @@
 
 PassOwnPtr<WebGLRenderingContext> WebGLRenderingContext::create(HTMLCanvasElement* canvas, WebGLContextAttributes* attrs)
 {
-    Document* document = canvas->document();
-    Frame* frame = document->frame();
+    Document& document = canvas->document();
+    Frame* frame = document.frame();
     if (!frame)
         return nullptr;
     Settings* settings = frame->settings();
@@ -511,7 +511,7 @@
     requestedAttributes.noExtensions = true;
     requestedAttributes.shareResources = true;
     requestedAttributes.preferDiscreteGPU = true;
-    requestedAttributes.topDocumentURL = document->topDocument()->url();
+    requestedAttributes.topDocumentURL = document.topDocument()->url();
 
     GraphicsContext3D::Attributes attributes = adjustAttributes(requestedAttributes, settings);
 
@@ -539,7 +539,7 @@
 
 WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, PassRefPtr<GraphicsContext3D> context, GraphicsContext3D::Attributes attributes, GraphicsContext3D::Attributes requestedAttributes)
     : CanvasRenderingContext(passedCanvas)
-    , ActiveDOMObject(passedCanvas->document())
+    , ActiveDOMObject(&passedCanvas->document())
     , m_context(context)
     , m_drawingBuffer(0)
     , m_dispatchContextLostEventTimer(this, &WebGLRenderingContext::dispatchContextLostEvent)
@@ -685,7 +685,7 @@
 void WebGLRenderingContext::setupFlags()
 {
     ASSERT(m_context);
-    if (Page* p = canvas()->document()->page()) {
+    if (Page* p = canvas()->document().page()) {
         m_synthesizedErrorsToConsole = p->settings().webGLErrorsToConsoleEnabled();
 
         if (!m_multisamplingObserverRegistered && m_requestedAttributes.antialias) {
@@ -701,7 +701,7 @@
 
 bool WebGLRenderingContext::allowPrivilegedExtensions() const
 {
-    if (Page* p = canvas()->document()->page())
+    if (Page* p = canvas()->document().page())
         return p->settings().privilegedWebGLExtensionsEnabled();
     return false;
 }
@@ -750,7 +750,7 @@
     destroyGraphicsContext3D();
 
     if (m_multisamplingObserverRegistered) {
-        Page* page = canvas()->document()->page();
+        Page* page = canvas()->document().page();
         if (page)
             page->removeMultisamplingChangedObserver(this);
     }
@@ -875,7 +875,7 @@
         return;
     }
 
-    if (canvas()->document()->printing())
+    if (canvas()->document().printing())
         canvas()->clearPresentationCopy();
 
     // Until the canvas is written to by the application, the clear that
@@ -2007,7 +2007,7 @@
 
     // generateMipmap won't work properly if minFilter is not NEAREST_MIPMAP_LINEAR
     // on Mac.  Remove the hack once this driver bug is fixed.
-#if OS(DARWIN)
+#if OS(MACOSX)
     bool needToResetMinFilter = false;
     if (tex->getMinFilter() != GraphicsContext3D::NEAREST_MIPMAP_LINEAR) {
         m_context->texParameteri(target, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::NEAREST_MIPMAP_LINEAR);
@@ -2015,7 +2015,7 @@
     }
 #endif
     m_context->generateMipmap(target);
-#if OS(DARWIN)
+#if OS(MACOSX)
     if (needToResetMinFilter)
         m_context->texParameteri(target, GraphicsContext3D::TEXTURE_MIN_FILTER, tex->getMinFilter());
 #endif
@@ -3079,7 +3079,7 @@
         m_context->readPixels(x, y, width, height, format, type, data);
     }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     // FIXME: remove this section when GL driver bug on Mac is fixed, i.e.,
     // when alpha is off, readPixels should set alpha to 255 instead of 0.
     if (!m_framebufferBinding && !m_context->getContextAttributes().alpha) {
@@ -4110,10 +4110,8 @@
     if (mode == RealLostContext) {
         // Inform the embedder that a lost context was received. In response, the embedder might
         // decide to take action such as asking the user for permission to use WebGL again.
-        if (Document* document = canvas()->document()) {
-            if (Frame* frame = document->frame())
-                frame->loader()->client()->didLoseWebGLContext(m_context->getExtensions()->getGraphicsResetStatusARB());
-        }
+        if (Frame* frame = canvas()->document().frame())
+            frame->loader()->client()->didLoseWebGLContext(m_context->getExtensions()->getGraphicsResetStatusARB());
     }
 
     // Make absolutely sure we do not refer to an already-deleted texture or framebuffer.
@@ -4939,10 +4937,7 @@
 {
     if (!canvas())
         return;
-    Document* document = canvas()->document();
-    if (!document)
-        return;
-    document->addConsoleMessage(RenderingMessageSource, WarningMessageLevel, message);
+    canvas()->document().addConsoleMessage(RenderingMessageSource, WarningMessageLevel, message);
 }
 
 bool WebGLRenderingContext::validateFramebufferFuncParameters(const char* functionName, GC3Denum target, GC3Denum attachment)
@@ -5342,10 +5337,7 @@
     if (!m_restoreAllowed)
         return;
 
-    Document* document = canvas()->document();
-    if (!document)
-        return;
-    Frame* frame = document->frame();
+    Frame* frame = canvas()->document().frame();
     if (!frame)
         return;
 
diff --git a/Source/core/html/forms/InputTypeView.cpp b/Source/core/html/forms/InputTypeView.cpp
index bdfa27f..bbc1ba0 100644
--- a/Source/core/html/forms/InputTypeView.cpp
+++ b/Source/core/html/forms/InputTypeView.cpp
@@ -34,6 +34,11 @@
 
 namespace WebCore {
 
+PassRefPtr<InputTypeView> InputTypeView::create(HTMLInputElement* input)
+{
+    return adoptRef(new InputTypeView(input));
+}
+
 InputTypeView::~InputTypeView()
 {
 }
diff --git a/Source/core/html/forms/InputTypeView.h b/Source/core/html/forms/InputTypeView.h
index 366aed8..9614ade 100644
--- a/Source/core/html/forms/InputTypeView.h
+++ b/Source/core/html/forms/InputTypeView.h
@@ -70,6 +70,7 @@
     WTF_MAKE_FAST_ALLOCATED;
 
 public:
+    static PassRefPtr<InputTypeView> create(HTMLInputElement*);
     virtual ~InputTypeView();
 
     virtual bool sizeShouldIncludeDecoration(int defaultSize, int& preferredSize) const;
diff --git a/Source/core/html/ime/Composition.cpp b/Source/core/html/ime/Composition.cpp
index 9b40000..cf313ad 100644
--- a/Source/core/html/ime/Composition.cpp
+++ b/Source/core/html/ime/Composition.cpp
@@ -31,27 +31,43 @@
 #include "config.h"
 #include "core/html/ime/Composition.h"
 
+#include "core/html/ime/InputMethodContext.h"
+
 namespace WebCore {
 
 Composition::~Composition()
 {
 }
 
-PassRefPtr<Composition> Composition::create()
+PassRefPtr<Composition> Composition::create(InputMethodContext* context)
 {
-    return adoptRef(new Composition());
+    return adoptRef(new Composition(context));
 }
 
-Composition::Composition()
-    : m_selectionStart(0)
-    , m_selectionEnd(0)
+Composition::Composition(InputMethodContext* context)
+    : m_inputMethodContext(context)
 {
     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_segments;
+    return m_inputMethodContext->segments();
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/ime/Composition.h b/Source/core/html/ime/Composition.h
index a180c86..0069969 100644
--- a/Source/core/html/ime/Composition.h
+++ b/Source/core/html/ime/Composition.h
@@ -39,29 +39,22 @@
 
 namespace WebCore {
 
+class InputMethodContext;
+
 class Composition : public RefCounted<Composition>, public ScriptWrappable {
 public:
-    static PassRefPtr<Composition> create();
+    static PassRefPtr<Composition> create(InputMethodContext*);
     ~Composition();
 
-    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; }
-
+    String text() const;
+    int selectionStart() const;
+    int selectionEnd() const;
     const Vector<unsigned>& getSegments() const;
 
 private:
-    Composition();
+    explicit Composition(InputMethodContext*);
 
-    String m_text;
-    int m_selectionStart;
-    int m_selectionEnd;
-    Vector<unsigned> m_segments;
+    InputMethodContext* m_inputMethodContext;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/ime/InputMethodContext.cpp b/Source/core/html/ime/InputMethodContext.cpp
index 3518a7b..2ffdda0 100644
--- a/Source/core/html/ime/InputMethodContext.cpp
+++ b/Source/core/html/ime/InputMethodContext.cpp
@@ -31,6 +31,7 @@
 #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"
@@ -43,7 +44,7 @@
 }
 
 InputMethodContext::InputMethodContext(HTMLElement* element)
-    : m_composition(0)
+    : m_composition(Composition::create(this))
     , m_element(element)
 {
     ScriptWrappable::init(this);
@@ -55,8 +56,6 @@
 
 Composition* InputMethodContext::composition() const
 {
-    // FIXME: Implement this. This should lazily update the composition object
-    // here.
     return m_composition.get();
 }
 
@@ -73,15 +72,8 @@
 
 void InputMethodContext::confirmComposition()
 {
-    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();
+    if (hasFocus())
+        inputMethodController().confirmCompositionAndResetState();
 }
 
 void InputMethodContext::setCaretRectangle(Node* anchor, int x, int y, int w, int h)
@@ -94,4 +86,81 @@
     // 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 e75be39..21999ad 100644
--- a/Source/core/html/ime/InputMethodContext.h
+++ b/Source/core/html/ime/InputMethodContext.h
@@ -32,6 +32,7 @@
 #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"
@@ -40,6 +41,7 @@
 namespace WebCore {
 
 class Composition;
+class InputMethodController;
 class Node;
 
 class InputMethodContext : public ScriptWrappable {
@@ -57,9 +59,19 @@
     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/HTMLConstructionSite.cpp b/Source/core/html/parser/HTMLConstructionSite.cpp
index 9f0c91f..ddf3ed4 100644
--- a/Source/core/html/parser/HTMLConstructionSite.cpp
+++ b/Source/core/html/parser/HTMLConstructionSite.cpp
@@ -87,7 +87,7 @@
     return string.isAllSpecialCharacters<isHTMLSpace>();
 }
 
-static inline void insert(HTMLConstructionSiteTask& task, AttachBehavior attachBehavior = AttachLazily)
+static inline void insert(HTMLConstructionSiteTask& task)
 {
     if (task.parent->hasTagName(templateTag))
         task.parent = toHTMLTemplateElement(task.parent.get())->content();
@@ -96,16 +96,16 @@
         parent->parserRemoveChild(task.child.get());
 
     if (task.nextChild)
-        task.parent->parserInsertBefore(task.child.get(), task.nextChild.get(), attachBehavior);
+        task.parent->parserInsertBefore(task.child.get(), task.nextChild.get());
     else
-        task.parent->parserAppendChild(task.child.get(), attachBehavior);
+        task.parent->parserAppendChild(task.child.get());
 }
 
 static inline void executeInsertTask(HTMLConstructionSiteTask& task)
 {
     ASSERT(task.operation == HTMLConstructionSiteTask::Insert);
 
-    insert(task, DeprecatedAttachNow);
+    insert(task);
 
     task.child->beginParsingChildren();
 
@@ -206,18 +206,18 @@
     , m_redirectAttachToFosterParent(false)
     , m_inQuirksMode(document->inQuirksMode())
 {
-    ASSERT(m_document->isHTMLDocument() || m_document->isSVGDocument() || m_document->isXHTMLDocument());
+    ASSERT(m_document->isHTMLDocument() || m_document->isXHTMLDocument());
 }
 
 HTMLConstructionSite::HTMLConstructionSite(DocumentFragment* fragment, ParserContentPolicy parserContentPolicy)
-    : m_document(fragment->document())
+    : m_document(&fragment->document())
     , m_attachmentRoot(fragment)
     , m_parserContentPolicy(parserContentPolicy)
     , m_isParsingFragment(true)
     , m_redirectAttachToFosterParent(false)
-    , m_inQuirksMode(fragment->document()->inQuirksMode())
+    , m_inQuirksMode(fragment->document().inQuirksMode())
 {
-    ASSERT(m_document->isHTMLDocument() || m_document->isSVGDocument() || m_document->isXHTMLDocument());
+    ASSERT(m_document->isHTMLDocument() || m_document->isXHTMLDocument());
 }
 
 HTMLConstructionSite::~HTMLConstructionSite()
@@ -251,7 +251,8 @@
 
 void HTMLConstructionSite::insertHTMLHtmlStartTagBeforeHTML(AtomicHTMLToken* token)
 {
-    RefPtr<HTMLHtmlElement> element = HTMLHtmlElement::create(m_document);
+    ASSERT(m_document);
+    RefPtr<HTMLHtmlElement> element = HTMLHtmlElement::create(*m_document);
     setAttributes(element.get(), token, m_parserContentPolicy);
     attachLater(m_attachmentRoot, element);
     m_openElements.pushHTMLHtmlElement(HTMLStackItem::create(element, token));
@@ -430,7 +431,8 @@
 void HTMLConstructionSite::insertCommentOnDocument(AtomicHTMLToken* token)
 {
     ASSERT(token->type() == HTMLToken::Comment);
-    attachLater(m_attachmentRoot, Comment::create(m_document, token->comment()));
+    ASSERT(m_document);
+    attachLater(m_attachmentRoot, Comment::create(*m_document, token->comment()));
 }
 
 void HTMLConstructionSite::insertCommentOnHTMLHtmlElement(AtomicHTMLToken* token)
@@ -549,8 +551,7 @@
     if (previousChild && previousChild->isTextNode()) {
         // FIXME: We're only supposed to append to this text node if it
         // was the last text node inserted by the parser.
-        CharacterData* textNode = static_cast<CharacterData*>(previousChild);
-        currentPosition = textNode->parserAppendData(characters, 0, lengthLimit);
+        currentPosition = toCharacterData(previousChild)->parserAppendData(characters, 0, lengthLimit);
     }
 
     while (currentPosition < characters.length()) {
@@ -609,12 +610,12 @@
 PassRefPtr<Element> HTMLConstructionSite::createElement(AtomicHTMLToken* token, const AtomicString& namespaceURI)
 {
     QualifiedName tagName(nullAtom, token->name(), namespaceURI);
-    RefPtr<Element> element = ownerDocumentForCurrentNode()->createElement(tagName, true);
+    RefPtr<Element> element = ownerDocumentForCurrentNode().createElement(tagName, true);
     setAttributes(element.get(), token, m_parserContentPolicy);
     return element.release();
 }
 
-inline Document* HTMLConstructionSite::ownerDocumentForCurrentNode()
+inline Document& HTMLConstructionSite::ownerDocumentForCurrentNode()
 {
     if (currentNode()->hasTagName(templateTag))
         return toHTMLTemplateElement(currentElement())->content()->document();
@@ -624,14 +625,14 @@
 PassRefPtr<Element> HTMLConstructionSite::createHTMLElement(AtomicHTMLToken* token)
 {
     QualifiedName tagName(nullAtom, token->name(), xhtmlNamespaceURI);
-    Document* document = ownerDocumentForCurrentNode();
+    Document& document = ownerDocumentForCurrentNode();
     // Only associate the element with the current form if we're creating the new element
     // in a document with a browsing context (rather than in <template> contents).
-    HTMLFormElement* form = document->frame() ? m_form.get() : 0;
+    HTMLFormElement* form = document.frame() ? m_form.get() : 0;
     // FIXME: This can't use HTMLConstructionSite::createElement because we
     // have to pass the current form element.  We should rework form association
     // to occur after construction to allow better code sharing here.
-    RefPtr<Element> element = HTMLElementFactory::createHTMLElement(tagName, document, form, true);
+    RefPtr<Element> element = HTMLElementFactory::createHTMLElement(tagName, &document, form, true);
     setAttributes(element.get(), token, m_parserContentPolicy);
     ASSERT(element->isHTMLElement());
     return element.release();
diff --git a/Source/core/html/parser/HTMLConstructionSite.h b/Source/core/html/parser/HTMLConstructionSite.h
index cae255c..ba03ce7 100644
--- a/Source/core/html/parser/HTMLConstructionSite.h
+++ b/Source/core/html/parser/HTMLConstructionSite.h
@@ -143,7 +143,7 @@
     ContainerNode* currentNode() const { return m_openElements.topNode(); }
     HTMLStackItem* currentStackItem() const { return m_openElements.topStackItem(); }
     HTMLStackItem* oneBelowTop() const { return m_openElements.oneBelowTop(); }
-    Document* ownerDocumentForCurrentNode();
+    Document& ownerDocumentForCurrentNode();
     HTMLElementStack* openElements() const { return &m_openElements; }
     HTMLFormattingElementList* activeFormattingElements() const { return &m_activeFormattingElements; }
     bool currentIsRootNode() { return m_openElements.topNode() == m_openElements.rootNode(); }
diff --git a/Source/core/html/parser/HTMLDocumentParser.cpp b/Source/core/html/parser/HTMLDocumentParser.cpp
index cdc7e0a..7fdef89 100644
--- a/Source/core/html/parser/HTMLDocumentParser.cpp
+++ b/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -29,6 +29,7 @@
 #include "HTMLNames.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/Element.h"
+#include "core/html/HTMLDocument.h"
 #include "core/html/parser/AtomicHTMLToken.h"
 #include "core/html/parser/BackgroundHTMLParser.h"
 #include "core/html/parser/CompactHTMLToken.h"
@@ -73,7 +74,7 @@
     return HTMLTokenizer::DataState;
 }
 
-HTMLDocumentParser::HTMLDocumentParser(Document* document, bool reportErrors)
+HTMLDocumentParser::HTMLDocumentParser(HTMLDocument* document, bool reportErrors)
     : ScriptableDocumentParser(document)
     , m_options(document)
     , m_token(m_options.useThreading ? nullptr : adoptPtr(new HTMLToken))
@@ -95,12 +96,12 @@
 // FIXME: Member variables should be grouped into self-initializing structs to
 // minimize code duplication between these constructors.
 HTMLDocumentParser::HTMLDocumentParser(DocumentFragment* fragment, Element* contextElement, ParserContentPolicy parserContentPolicy)
-    : ScriptableDocumentParser(fragment->document(), parserContentPolicy)
-    , m_options(fragment->document())
+    : ScriptableDocumentParser(&fragment->document(), parserContentPolicy)
+    , m_options(&fragment->document())
     , m_token(adoptPtr(new HTMLToken))
     , m_tokenizer(HTMLTokenizer::create(m_options))
     , m_treeBuilder(HTMLTreeBuilder::create(this, fragment, contextElement, this->parserContentPolicy(), m_options))
-    , m_xssAuditorDelegate(fragment->document())
+    , m_xssAuditorDelegate(&fragment->document())
     , m_weakFactory(this)
     , m_isPinnedToMainThread(true)
     , m_endWasDelayed(false)
diff --git a/Source/core/html/parser/HTMLDocumentParser.h b/Source/core/html/parser/HTMLDocumentParser.h
index a305714..4b3be11 100644
--- a/Source/core/html/parser/HTMLDocumentParser.h
+++ b/Source/core/html/parser/HTMLDocumentParser.h
@@ -66,7 +66,7 @@
 class HTMLDocumentParser :  public ScriptableDocumentParser, HTMLScriptRunnerHost, ResourceClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassRefPtr<HTMLDocumentParser> create(Document* document, bool reportErrors)
+    static PassRefPtr<HTMLDocumentParser> create(HTMLDocument* document, bool reportErrors)
     {
         return adoptRef(new HTMLDocumentParser(document, reportErrors));
     }
@@ -101,7 +101,7 @@
     virtual void append(PassRefPtr<StringImpl>) OVERRIDE;
     virtual void finish() OVERRIDE;
 
-    HTMLDocumentParser(Document*, bool reportErrors);
+    HTMLDocumentParser(HTMLDocument*, bool reportErrors);
     HTMLDocumentParser(DocumentFragment*, Element* contextElement, ParserContentPolicy);
 
     HTMLTreeBuilder* treeBuilder() const { return m_treeBuilder.get(); }
diff --git a/Source/core/html/parser/HTMLScriptRunner.cpp b/Source/core/html/parser/HTMLScriptRunner.cpp
index 9fd7510..f03d204 100644
--- a/Source/core/html/parser/HTMLScriptRunner.cpp
+++ b/Source/core/html/parser/HTMLScriptRunner.cpp
@@ -81,7 +81,7 @@
 
 inline PassRefPtr<Event> createScriptLoadEvent()
 {
-    return Event::create(eventNames().loadEvent, false, false);
+    return Event::create(eventNames().loadEvent);
 }
 
 ScriptSourceCode HTMLScriptRunner::sourceFromPendingScript(const PendingScript& script, bool& errorOccurred) const
diff --git a/Source/core/html/parser/HTMLTreeBuilder.cpp b/Source/core/html/parser/HTMLTreeBuilder.cpp
index b9e73f6..1d887d7 100644
--- a/Source/core/html/parser/HTMLTreeBuilder.cpp
+++ b/Source/core/html/parser/HTMLTreeBuilder.cpp
@@ -35,6 +35,7 @@
 #include "XMLNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/DocumentFragment.h"
+#include "core/html/HTMLDocument.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLOptGroupElement.h"
@@ -272,7 +273,7 @@
     unsigned m_end;
 };
 
-HTMLTreeBuilder::HTMLTreeBuilder(HTMLDocumentParser* parser, Document* document, ParserContentPolicy parserContentPolicy, bool, const HTMLParserOptions& options)
+HTMLTreeBuilder::HTMLTreeBuilder(HTMLDocumentParser* parser, HTMLDocument* document, ParserContentPolicy parserContentPolicy, bool, const HTMLParserOptions& options)
     : m_framesetOk(true)
 #ifndef NDEBUG
     , m_isAttached(true)
diff --git a/Source/core/html/parser/HTMLTreeBuilder.h b/Source/core/html/parser/HTMLTreeBuilder.h
index d648673..c434d56 100644
--- a/Source/core/html/parser/HTMLTreeBuilder.h
+++ b/Source/core/html/parser/HTMLTreeBuilder.h
@@ -53,7 +53,7 @@
 class HTMLTreeBuilder {
     WTF_MAKE_NONCOPYABLE(HTMLTreeBuilder); WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<HTMLTreeBuilder> create(HTMLDocumentParser* parser, Document* document, ParserContentPolicy parserContentPolicy, bool reportErrors, const HTMLParserOptions& options)
+    static PassOwnPtr<HTMLTreeBuilder> create(HTMLDocumentParser* parser, HTMLDocument* document, ParserContentPolicy parserContentPolicy, bool reportErrors, const HTMLParserOptions& options)
     {
         return adoptPtr(new HTMLTreeBuilder(parser, document, parserContentPolicy, reportErrors, options));
     }
@@ -112,7 +112,7 @@
         AfterAfterFramesetMode,
     };
 
-    HTMLTreeBuilder(HTMLDocumentParser*, Document*, ParserContentPolicy, bool reportErrors, const HTMLParserOptions&);
+    HTMLTreeBuilder(HTMLDocumentParser*, HTMLDocument*, ParserContentPolicy, bool reportErrors, const HTMLParserOptions&);
     HTMLTreeBuilder(HTMLDocumentParser*, DocumentFragment*, Element* contextElement, ParserContentPolicy, const HTMLParserOptions&);
 
     void processToken(AtomicHTMLToken*);
diff --git a/Source/core/html/parser/TextDocumentParser.cpp b/Source/core/html/parser/TextDocumentParser.cpp
index d125ce3..38175a0 100644
--- a/Source/core/html/parser/TextDocumentParser.cpp
+++ b/Source/core/html/parser/TextDocumentParser.cpp
@@ -32,7 +32,7 @@
 
 using namespace HTMLNames;
 
-TextDocumentParser::TextDocumentParser(Document* document)
+TextDocumentParser::TextDocumentParser(HTMLDocument* document)
     : HTMLDocumentParser(document, false)
     , m_haveInsertedFakePreElement(false)
 {
diff --git a/Source/core/html/parser/TextDocumentParser.h b/Source/core/html/parser/TextDocumentParser.h
index bf14fde..6b5bb9e 100644
--- a/Source/core/html/parser/TextDocumentParser.h
+++ b/Source/core/html/parser/TextDocumentParser.h
@@ -32,14 +32,14 @@
 
 class TextDocumentParser : public HTMLDocumentParser {
 public:
-    static PassRefPtr<TextDocumentParser> create(Document* document)
+    static PassRefPtr<TextDocumentParser> create(HTMLDocument* document)
     {
         return adoptRef(new TextDocumentParser(document));
     }
     virtual ~TextDocumentParser();
 
 private:
-    explicit TextDocumentParser(Document*);
+    explicit TextDocumentParser(HTMLDocument*);
 
     virtual void append(PassRefPtr<StringImpl>);
     void insertFakePreElement();
diff --git a/Source/core/html/parser/XSSAuditor.cpp b/Source/core/html/parser/XSSAuditor.cpp
index 8e5246b..ccae51c 100644
--- a/Source/core/html/parser/XSSAuditor.cpp
+++ b/Source/core/html/parser/XSSAuditor.cpp
@@ -31,12 +31,12 @@
 #include "SVGNames.h"
 #include "XLinkNames.h"
 #include "core/dom/Document.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/html/HTMLParamElement.h"
 #include "core/html/parser/HTMLDocumentParser.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/XSSAuditorDelegate.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/Frame.h"
 #include "core/page/Settings.h"
diff --git a/Source/core/html/shadow/ClearButtonElement.cpp b/Source/core/html/shadow/ClearButtonElement.cpp
index c3eb8e9..fc91016 100644
--- a/Source/core/html/shadow/ClearButtonElement.cpp
+++ b/Source/core/html/shadow/ClearButtonElement.cpp
@@ -36,14 +36,14 @@
 
 using namespace HTMLNames;
 
-inline ClearButtonElement::ClearButtonElement(Document* document, ClearButtonOwner& clearButtonOwner)
+inline ClearButtonElement::ClearButtonElement(Document& document, ClearButtonOwner& clearButtonOwner)
     : HTMLDivElement(divTag, document)
     , m_clearButtonOwner(&clearButtonOwner)
     , m_capturing(false)
 {
 }
 
-PassRefPtr<ClearButtonElement> ClearButtonElement::create(Document* document, ClearButtonOwner& clearButtonOwner)
+PassRefPtr<ClearButtonElement> ClearButtonElement::create(Document& document, ClearButtonOwner& clearButtonOwner)
 {
     RefPtr<ClearButtonElement> element = adoptRef(new ClearButtonElement(document, clearButtonOwner));
     element->setPart(AtomicString("-webkit-clear-button", AtomicString::ConstructFromLiteral));
@@ -54,7 +54,7 @@
 void ClearButtonElement::detach(const AttachContext& context)
 {
     if (m_capturing) {
-        if (Frame* frame = document()->frame())
+        if (Frame* frame = document().frame())
             frame->eventHandler()->setCapturingMouseEventsNode(0);
     }
     HTMLDivElement::detach(context);
@@ -65,7 +65,7 @@
     if (!m_capturing)
         return;
 
-    if (Frame* frame = document()->frame()) {
+    if (Frame* frame = document().frame()) {
         frame->eventHandler()->setCapturingMouseEventsNode(0);
         m_capturing = false;
     }
@@ -87,7 +87,7 @@
 
     if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (renderer() && renderer()->visibleToHitTesting()) {
-            if (Frame* frame = document()->frame()) {
+            if (Frame* frame = document().frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(this);
                 m_capturing = true;
             }
@@ -97,7 +97,7 @@
     }
     if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (m_capturing) {
-            if (Frame* frame = document()->frame()) {
+            if (Frame* frame = document().frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(0);
                 m_capturing = false;
             }
diff --git a/Source/core/html/shadow/ClearButtonElement.h b/Source/core/html/shadow/ClearButtonElement.h
index 2371888..00bf5aa 100644
--- a/Source/core/html/shadow/ClearButtonElement.h
+++ b/Source/core/html/shadow/ClearButtonElement.h
@@ -41,12 +41,12 @@
         virtual void clearValue() = 0;
     };
 
-    static PassRefPtr<ClearButtonElement> create(Document*, ClearButtonOwner&);
+    static PassRefPtr<ClearButtonElement> create(Document&, ClearButtonOwner&);
     void releaseCapture();
     void removeClearButtonOwner() { m_clearButtonOwner = 0; }
 
 private:
-    ClearButtonElement(Document*, ClearButtonOwner&);
+    ClearButtonElement(Document&, ClearButtonOwner&);
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool isMouseFocusable() const { return false; }
     virtual void defaultEventHandler(Event*);
diff --git a/Source/core/html/shadow/DateTimeEditElement.cpp b/Source/core/html/shadow/DateTimeEditElement.cpp
index c50cab9..c56edae 100644
--- a/Source/core/html/shadow/DateTimeEditElement.cpp
+++ b/Source/core/html/shadow/DateTimeEditElement.cpp
@@ -144,7 +144,7 @@
     const int countForAbbreviatedMonth = 3;
     const int countForFullMonth = 4;
     const int countForNarrowMonth = 5;
-    Document* const document = m_editElement.document();
+    Document& document = m_editElement.document();
 
     switch (fieldType) {
     case DateTimeFormat::FieldTypeDayOfMonth: {
@@ -440,7 +440,7 @@
 {
 }
 
-DateTimeEditElement::DateTimeEditElement(Document* document, EditControlOwner& editControlOwner)
+DateTimeEditElement::DateTimeEditElement(Document& document, EditControlOwner& editControlOwner)
     : HTMLDivElement(divTag, document)
     , m_editControlOwner(&editControlOwner)
 {
@@ -482,7 +482,7 @@
         field->blur();
 }
 
-PassRefPtr<DateTimeEditElement> DateTimeEditElement::create(Document* document, EditControlOwner& editControlOwner)
+PassRefPtr<DateTimeEditElement> DateTimeEditElement::create(Document& document, EditControlOwner& editControlOwner)
 {
     RefPtr<DateTimeEditElement> container = adoptRef(new DateTimeEditElement(document, editControlOwner));
     container->setPart(AtomicString("-webkit-datetime-edit", AtomicString::ConstructFromLiteral));
@@ -573,7 +573,7 @@
 
 size_t DateTimeEditElement::focusedFieldIndex() const
 {
-    Element* const focusedFieldElement = document()->focusedElement();
+    Element* const focusedFieldElement = document().focusedElement();
     for (size_t fieldIndex = 0; fieldIndex < m_fields.size(); ++fieldIndex) {
         if (m_fields[fieldIndex] == focusedFieldElement)
             return fieldIndex;
diff --git a/Source/core/html/shadow/DateTimeEditElement.h b/Source/core/html/shadow/DateTimeEditElement.h
index c0ddde1..ecb06ac 100644
--- a/Source/core/html/shadow/DateTimeEditElement.h
+++ b/Source/core/html/shadow/DateTimeEditElement.h
@@ -79,7 +79,7 @@
         }
     };
 
-    static PassRefPtr<DateTimeEditElement> create(Document*, EditControlOwner&);
+    static PassRefPtr<DateTimeEditElement> create(Document&, EditControlOwner&);
 
     virtual ~DateTimeEditElement();
     void addField(PassRefPtr<DateTimeFieldElement>);
@@ -119,7 +119,7 @@
     //  8. AM/PM
     static const int maximumNumberOfFields = 8;
 
-    DateTimeEditElement(Document*, EditControlOwner&);
+    DateTimeEditElement(Document&, EditControlOwner&);
 
     DateTimeFieldElement* fieldAt(size_t) const;
     size_t fieldIndexOf(const DateTimeFieldElement&) const;
diff --git a/Source/core/html/shadow/DateTimeFieldElement.cpp b/Source/core/html/shadow/DateTimeFieldElement.cpp
index d7ee1e3..76c20d4 100644
--- a/Source/core/html/shadow/DateTimeFieldElement.cpp
+++ b/Source/core/html/shadow/DateTimeFieldElement.cpp
@@ -42,7 +42,7 @@
 {
 }
 
-DateTimeFieldElement::DateTimeFieldElement(Document* document, FieldOwner& fieldOwner)
+DateTimeFieldElement::DateTimeFieldElement(Document& document, FieldOwner& fieldOwner)
     : HTMLSpanElement(spanTag, document)
     , m_fieldOwner(&fieldOwner)
 {
@@ -179,7 +179,7 @@
 
 Locale& DateTimeFieldElement::localeForOwner() const
 {
-    return document()->getCachedLocale(localeIdentifier());
+    return document().getCachedLocale(localeIdentifier());
 }
 
 AtomicString DateTimeFieldElement::localeIdentifier() const
diff --git a/Source/core/html/shadow/DateTimeFieldElement.h b/Source/core/html/shadow/DateTimeFieldElement.h
index 896d6bc..a2e42a9 100644
--- a/Source/core/html/shadow/DateTimeFieldElement.h
+++ b/Source/core/html/shadow/DateTimeFieldElement.h
@@ -78,7 +78,7 @@
     virtual String visibleValue() const = 0;
 
 protected:
-    DateTimeFieldElement(Document*, FieldOwner&);
+    DateTimeFieldElement(Document&, FieldOwner&);
     virtual void didBlur();
     virtual void didFocus();
     void focusOnNextField();
diff --git a/Source/core/html/shadow/DateTimeFieldElements.cpp b/Source/core/html/shadow/DateTimeFieldElements.cpp
index d9b59c6..9ffa69f 100644
--- a/Source/core/html/shadow/DateTimeFieldElements.cpp
+++ b/Source/core/html/shadow/DateTimeFieldElements.cpp
@@ -35,12 +35,12 @@
 
 namespace WebCore {
 
-DateTimeAMPMFieldElement::DateTimeAMPMFieldElement(Document* document, FieldOwner& fieldOwner, const Vector<String>& ampmLabels)
+DateTimeAMPMFieldElement::DateTimeAMPMFieldElement(Document& document, FieldOwner& fieldOwner, const Vector<String>& ampmLabels)
     : DateTimeSymbolicFieldElement(document, fieldOwner, ampmLabels, 0, 1)
 {
 }
 
-PassRefPtr<DateTimeAMPMFieldElement> DateTimeAMPMFieldElement::create(Document* document, FieldOwner& fieldOwner, const Vector<String>& ampmLabels)
+PassRefPtr<DateTimeAMPMFieldElement> DateTimeAMPMFieldElement::create(Document& document, FieldOwner& fieldOwner, const Vector<String>& ampmLabels)
 {
     DEFINE_STATIC_LOCAL(AtomicString, ampmPsuedoId, ("-webkit-datetime-edit-ampm-field", AtomicString::ConstructFromLiteral));
     RefPtr<DateTimeAMPMFieldElement> field = adoptRef(new DateTimeAMPMFieldElement(document, fieldOwner, ampmLabels));
@@ -71,12 +71,12 @@
 
 // ----------------------------
 
-DateTimeDayFieldElement::DateTimeDayFieldElement(Document* document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
+DateTimeDayFieldElement::DateTimeDayFieldElement(Document& document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
     : DateTimeNumericFieldElement(document, fieldOwner, range, Range(1, 31), placeholder)
 {
 }
 
-PassRefPtr<DateTimeDayFieldElement> DateTimeDayFieldElement::create(Document* document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
+PassRefPtr<DateTimeDayFieldElement> DateTimeDayFieldElement::create(Document& document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
 {
     DEFINE_STATIC_LOCAL(AtomicString, dayPsuedoId, ("-webkit-datetime-edit-day-field", AtomicString::ConstructFromLiteral));
     RefPtr<DateTimeDayFieldElement> field = adoptRef(new DateTimeDayFieldElement(document, fieldOwner, placeholder.isEmpty() ? "--" : placeholder, range));
@@ -112,7 +112,7 @@
 
 // ----------------------------
 
-DateTimeHourFieldElementBase::DateTimeHourFieldElementBase(Document* document, FieldOwner& fieldOwner, const Range& range, const Range& hardLimits, const Step& step)
+DateTimeHourFieldElementBase::DateTimeHourFieldElementBase(Document& document, FieldOwner& fieldOwner, const Range& range, const Range& hardLimits, const Step& step)
     : DateTimeNumericFieldElement(document, fieldOwner, range, hardLimits, "--", step)
 {
 }
@@ -147,12 +147,12 @@
 }
 // ----------------------------
 
-DateTimeHour11FieldElement::DateTimeHour11FieldElement(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+DateTimeHour11FieldElement::DateTimeHour11FieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
     : DateTimeHourFieldElementBase(document, fieldOwner, range, Range(0, 11), step)
 {
 }
 
-PassRefPtr<DateTimeHour11FieldElement> DateTimeHour11FieldElement::create(Document* document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step)
+PassRefPtr<DateTimeHour11FieldElement> DateTimeHour11FieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step)
 {
     ASSERT(hour23Range.minimum >= 0);
     ASSERT(hour23Range.maximum <= 23);
@@ -188,12 +188,12 @@
 
 // ----------------------------
 
-DateTimeHour12FieldElement::DateTimeHour12FieldElement(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+DateTimeHour12FieldElement::DateTimeHour12FieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
     : DateTimeHourFieldElementBase(document, fieldOwner, range, Range(1, 12), step)
 {
 }
 
-PassRefPtr<DateTimeHour12FieldElement> DateTimeHour12FieldElement::create(Document* document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step)
+PassRefPtr<DateTimeHour12FieldElement> DateTimeHour12FieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step)
 {
     ASSERT(hour23Range.minimum >= 0);
     ASSERT(hour23Range.maximum <= 23);
@@ -231,12 +231,12 @@
 
 // ----------------------------
 
-DateTimeHour23FieldElement::DateTimeHour23FieldElement(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+DateTimeHour23FieldElement::DateTimeHour23FieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
     : DateTimeHourFieldElementBase(document, fieldOwner, range, Range(0, 23), step)
 {
 }
 
-PassRefPtr<DateTimeHour23FieldElement> DateTimeHour23FieldElement::create(Document* document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step)
+PassRefPtr<DateTimeHour23FieldElement> DateTimeHour23FieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step)
 {
     ASSERT(hour23Range.minimum >= 0);
     ASSERT(hour23Range.maximum <= 23);
@@ -267,12 +267,12 @@
 
 // ----------------------------
 
-DateTimeHour24FieldElement::DateTimeHour24FieldElement(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+DateTimeHour24FieldElement::DateTimeHour24FieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
     : DateTimeHourFieldElementBase(document, fieldOwner, range, Range(1, 24), step)
 {
 }
 
-PassRefPtr<DateTimeHour24FieldElement> DateTimeHour24FieldElement::create(Document* document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step)
+PassRefPtr<DateTimeHour24FieldElement> DateTimeHour24FieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& hour23Range, const Step& step)
 {
     ASSERT(hour23Range.minimum >= 0);
     ASSERT(hour23Range.maximum <= 23);
@@ -314,12 +314,12 @@
 
 // ----------------------------
 
-DateTimeMillisecondFieldElement::DateTimeMillisecondFieldElement(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+DateTimeMillisecondFieldElement::DateTimeMillisecondFieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
     : DateTimeNumericFieldElement(document, fieldOwner, range, Range(0, 999), "---", step)
 {
 }
 
-PassRefPtr<DateTimeMillisecondFieldElement> DateTimeMillisecondFieldElement::create(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+PassRefPtr<DateTimeMillisecondFieldElement> DateTimeMillisecondFieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
 {
     DEFINE_STATIC_LOCAL(AtomicString, millisecondPsuedoId, ("-webkit-datetime-edit-millisecond-field", AtomicString::ConstructFromLiteral));
     RefPtr<DateTimeMillisecondFieldElement> field = adoptRef(new DateTimeMillisecondFieldElement(document, fieldOwner, range, step));
@@ -355,12 +355,12 @@
 
 // ----------------------------
 
-DateTimeMinuteFieldElement::DateTimeMinuteFieldElement(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+DateTimeMinuteFieldElement::DateTimeMinuteFieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
     : DateTimeNumericFieldElement(document, fieldOwner, range, Range(0, 59), "--", step)
 {
 }
 
-PassRefPtr<DateTimeMinuteFieldElement> DateTimeMinuteFieldElement::create(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+PassRefPtr<DateTimeMinuteFieldElement> DateTimeMinuteFieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
 {
     DEFINE_STATIC_LOCAL(AtomicString, minutePsuedoId, ("-webkit-datetime-edit-minute-field", AtomicString::ConstructFromLiteral));
     RefPtr<DateTimeMinuteFieldElement> field = adoptRef(new DateTimeMinuteFieldElement(document, fieldOwner, range, step));
@@ -396,12 +396,12 @@
 
 // ----------------------------
 
-DateTimeMonthFieldElement::DateTimeMonthFieldElement(Document* document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
+DateTimeMonthFieldElement::DateTimeMonthFieldElement(Document& document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
     : DateTimeNumericFieldElement(document, fieldOwner, range, Range(1, 12), placeholder)
 {
 }
 
-PassRefPtr<DateTimeMonthFieldElement> DateTimeMonthFieldElement::create(Document* document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
+PassRefPtr<DateTimeMonthFieldElement> DateTimeMonthFieldElement::create(Document& document, FieldOwner& fieldOwner, const String& placeholder, const Range& range)
 {
     DEFINE_STATIC_LOCAL(AtomicString, monthPsuedoId, ("-webkit-datetime-edit-month-field", AtomicString::ConstructFromLiteral));
     RefPtr<DateTimeMonthFieldElement> field = adoptRef(new DateTimeMonthFieldElement(document, fieldOwner, placeholder.isEmpty() ? "--" : placeholder, range));
@@ -437,12 +437,12 @@
 
 // ----------------------------
 
-DateTimeSecondFieldElement::DateTimeSecondFieldElement(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+DateTimeSecondFieldElement::DateTimeSecondFieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
     : DateTimeNumericFieldElement(document, fieldOwner, range, Range(0, 59), "--", step)
 {
 }
 
-PassRefPtr<DateTimeSecondFieldElement> DateTimeSecondFieldElement::create(Document* document, FieldOwner& fieldOwner, const Range& range, const Step& step)
+PassRefPtr<DateTimeSecondFieldElement> DateTimeSecondFieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& range, const Step& step)
 {
     DEFINE_STATIC_LOCAL(AtomicString, secondPsuedoId, ("-webkit-datetime-edit-second-field", AtomicString::ConstructFromLiteral));
     RefPtr<DateTimeSecondFieldElement> field = adoptRef(new DateTimeSecondFieldElement(document, fieldOwner, range, step));
@@ -478,12 +478,12 @@
 
 // ----------------------------
 
-DateTimeSymbolicMonthFieldElement::DateTimeSymbolicMonthFieldElement(Document* document, FieldOwner& fieldOwner, const Vector<String>& labels, int minimum, int maximum)
+DateTimeSymbolicMonthFieldElement::DateTimeSymbolicMonthFieldElement(Document& document, FieldOwner& fieldOwner, const Vector<String>& labels, int minimum, int maximum)
     : DateTimeSymbolicFieldElement(document, fieldOwner, labels, minimum, maximum)
 {
 }
 
-PassRefPtr<DateTimeSymbolicMonthFieldElement> DateTimeSymbolicMonthFieldElement::create(Document* document, FieldOwner& fieldOwner, const Vector<String>& labels, int minimum, int maximum)
+PassRefPtr<DateTimeSymbolicMonthFieldElement> DateTimeSymbolicMonthFieldElement::create(Document& document, FieldOwner& fieldOwner, const Vector<String>& labels, int minimum, int maximum)
 {
     DEFINE_STATIC_LOCAL(AtomicString, monthPsuedoId, ("-webkit-datetime-edit-month-field", AtomicString::ConstructFromLiteral));
     RefPtr<DateTimeSymbolicMonthFieldElement> field = adoptRef(new DateTimeSymbolicMonthFieldElement(document, fieldOwner, labels, minimum, maximum));
@@ -522,12 +522,12 @@
 
 // ----------------------------
 
-DateTimeWeekFieldElement::DateTimeWeekFieldElement(Document* document, FieldOwner& fieldOwner, const Range& range)
+DateTimeWeekFieldElement::DateTimeWeekFieldElement(Document& document, FieldOwner& fieldOwner, const Range& range)
     : DateTimeNumericFieldElement(document, fieldOwner, range, Range(DateComponents::minimumWeekNumber, DateComponents::maximumWeekNumber), "--")
 {
 }
 
-PassRefPtr<DateTimeWeekFieldElement> DateTimeWeekFieldElement::create(Document* document, FieldOwner& fieldOwner, const Range& range)
+PassRefPtr<DateTimeWeekFieldElement> DateTimeWeekFieldElement::create(Document& document, FieldOwner& fieldOwner, const Range& range)
 {
     DEFINE_STATIC_LOCAL(AtomicString, weekPsuedoId, ("-webkit-datetime-edit-week-field", AtomicString::ConstructFromLiteral));
     RefPtr<DateTimeWeekFieldElement> field = adoptRef(new DateTimeWeekFieldElement(document, fieldOwner, range));
@@ -563,7 +563,7 @@
 
 // ----------------------------
 
-DateTimeYearFieldElement::DateTimeYearFieldElement(Document* document, FieldOwner& fieldOwner, const DateTimeYearFieldElement::Parameters& parameters)
+DateTimeYearFieldElement::DateTimeYearFieldElement(Document& document, FieldOwner& fieldOwner, const DateTimeYearFieldElement::Parameters& parameters)
     : DateTimeNumericFieldElement(document, fieldOwner, Range(parameters.minimumYear, parameters.maximumYear), Range(DateComponents::minimumYear(), DateComponents::maximumYear()), parameters.placeholder.isEmpty() ? "----" : parameters.placeholder)
     , m_minIsSpecified(parameters.minIsSpecified)
     , m_maxIsSpecified(parameters.maxIsSpecified)
@@ -572,7 +572,7 @@
     ASSERT(parameters.maximumYear <= DateComponents::maximumYear());
 }
 
-PassRefPtr<DateTimeYearFieldElement> DateTimeYearFieldElement::create(Document* document, FieldOwner& fieldOwner, const DateTimeYearFieldElement::Parameters& parameters)
+PassRefPtr<DateTimeYearFieldElement> DateTimeYearFieldElement::create(Document& document, FieldOwner& fieldOwner, const DateTimeYearFieldElement::Parameters& parameters)
 {
     DEFINE_STATIC_LOCAL(AtomicString, yearPsuedoId, ("-webkit-datetime-edit-year-field", AtomicString::ConstructFromLiteral));
     RefPtr<DateTimeYearFieldElement> field = adoptRef(new DateTimeYearFieldElement(document, fieldOwner, parameters));
diff --git a/Source/core/html/shadow/DateTimeFieldElements.h b/Source/core/html/shadow/DateTimeFieldElements.h
index 60f53a8..fb8ef52 100644
--- a/Source/core/html/shadow/DateTimeFieldElements.h
+++ b/Source/core/html/shadow/DateTimeFieldElements.h
@@ -36,10 +36,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeAMPMFieldElement);
 
 public:
-    static PassRefPtr<DateTimeAMPMFieldElement> create(Document*, FieldOwner&, const Vector<String>&);
+    static PassRefPtr<DateTimeAMPMFieldElement> create(Document&, FieldOwner&, const Vector<String>&);
 
 private:
-    DateTimeAMPMFieldElement(Document*, FieldOwner&, const Vector<String>&);
+    DateTimeAMPMFieldElement(Document&, FieldOwner&, const Vector<String>&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -51,10 +51,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeDayFieldElement);
 
 public:
-    static PassRefPtr<DateTimeDayFieldElement> create(Document*, FieldOwner&, const String& placeholder, const Range&);
+    static PassRefPtr<DateTimeDayFieldElement> create(Document&, FieldOwner&, const String& placeholder, const Range&);
 
 private:
-    DateTimeDayFieldElement(Document*, FieldOwner&, const String& placeholder, const Range&);
+    DateTimeDayFieldElement(Document&, FieldOwner&, const String& placeholder, const Range&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -66,7 +66,7 @@
     WTF_MAKE_NONCOPYABLE(DateTimeHourFieldElementBase);
 
 protected:
-    DateTimeHourFieldElementBase(Document*, FieldOwner&, const Range&, const Range& hardLimits, const Step&);
+    DateTimeHourFieldElementBase(Document&, FieldOwner&, const Range&, const Range& hardLimits, const Step&);
     void initialize();
 
 private:
@@ -79,10 +79,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeHour11FieldElement);
 
 public:
-    static PassRefPtr<DateTimeHour11FieldElement> create(Document*, FieldOwner&, const Range&, const Step&);
+    static PassRefPtr<DateTimeHour11FieldElement> create(Document&, FieldOwner&, const Range&, const Step&);
 
 private:
-    DateTimeHour11FieldElement(Document*, FieldOwner&, const Range& hour23Range, const Step&);
+    DateTimeHour11FieldElement(Document&, FieldOwner&, const Range& hour23Range, const Step&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -93,10 +93,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeHour12FieldElement);
 
 public:
-    static PassRefPtr<DateTimeHour12FieldElement> create(Document*, FieldOwner&, const Range&, const Step&);
+    static PassRefPtr<DateTimeHour12FieldElement> create(Document&, FieldOwner&, const Range&, const Step&);
 
 private:
-    DateTimeHour12FieldElement(Document*, FieldOwner&, const Range& hour23Range, const Step&);
+    DateTimeHour12FieldElement(Document&, FieldOwner&, const Range& hour23Range, const Step&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -107,10 +107,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeHour23FieldElement);
 
 public:
-    static PassRefPtr<DateTimeHour23FieldElement> create(Document*, FieldOwner&, const Range&, const Step&);
+    static PassRefPtr<DateTimeHour23FieldElement> create(Document&, FieldOwner&, const Range&, const Step&);
 
 private:
-    DateTimeHour23FieldElement(Document*, FieldOwner&, const Range& hour23Range, const Step&);
+    DateTimeHour23FieldElement(Document&, FieldOwner&, const Range& hour23Range, const Step&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -121,10 +121,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeHour24FieldElement);
 
 public:
-    static PassRefPtr<DateTimeHour24FieldElement> create(Document*, FieldOwner&, const Range&, const Step&);
+    static PassRefPtr<DateTimeHour24FieldElement> create(Document&, FieldOwner&, const Range&, const Step&);
 
 private:
-    DateTimeHour24FieldElement(Document*, FieldOwner&, const Range& hour23Range, const Step&);
+    DateTimeHour24FieldElement(Document&, FieldOwner&, const Range& hour23Range, const Step&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -135,10 +135,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeMillisecondFieldElement);
 
 public:
-    static PassRefPtr<DateTimeMillisecondFieldElement> create(Document*, FieldOwner&, const Range&, const Step&);
+    static PassRefPtr<DateTimeMillisecondFieldElement> create(Document&, FieldOwner&, const Range&, const Step&);
 
 private:
-    DateTimeMillisecondFieldElement(Document*, FieldOwner&, const Range&, const Step&);
+    DateTimeMillisecondFieldElement(Document&, FieldOwner&, const Range&, const Step&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -150,10 +150,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeMinuteFieldElement);
 
 public:
-    static PassRefPtr<DateTimeMinuteFieldElement> create(Document*, FieldOwner&, const Range&, const Step&);
+    static PassRefPtr<DateTimeMinuteFieldElement> create(Document&, FieldOwner&, const Range&, const Step&);
 
 private:
-    DateTimeMinuteFieldElement(Document*, FieldOwner&, const Range&, const Step&);
+    DateTimeMinuteFieldElement(Document&, FieldOwner&, const Range&, const Step&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -165,10 +165,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeMonthFieldElement);
 
 public:
-    static PassRefPtr<DateTimeMonthFieldElement> create(Document*, FieldOwner&, const String& placeholder, const Range&);
+    static PassRefPtr<DateTimeMonthFieldElement> create(Document&, FieldOwner&, const String& placeholder, const Range&);
 
 private:
-    DateTimeMonthFieldElement(Document*, FieldOwner&, const String& placeholder, const Range&);
+    DateTimeMonthFieldElement(Document&, FieldOwner&, const String& placeholder, const Range&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -180,10 +180,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeSecondFieldElement);
 
 public:
-    static PassRefPtr<DateTimeSecondFieldElement> create(Document*, FieldOwner&, const Range&, const Step&);
+    static PassRefPtr<DateTimeSecondFieldElement> create(Document&, FieldOwner&, const Range&, const Step&);
 
 private:
-    DateTimeSecondFieldElement(Document*, FieldOwner&, const Range&, const Step&);
+    DateTimeSecondFieldElement(Document&, FieldOwner&, const Range&, const Step&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -195,10 +195,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeSymbolicMonthFieldElement);
 
 public:
-    static PassRefPtr<DateTimeSymbolicMonthFieldElement> create(Document*, FieldOwner&, const Vector<String>&, int minimum, int maximum);
+    static PassRefPtr<DateTimeSymbolicMonthFieldElement> create(Document&, FieldOwner&, const Vector<String>&, int minimum, int maximum);
 
 private:
-    DateTimeSymbolicMonthFieldElement(Document*, FieldOwner&, const Vector<String>&, int minimum, int maximum);
+    DateTimeSymbolicMonthFieldElement(Document&, FieldOwner&, const Vector<String>&, int minimum, int maximum);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -210,10 +210,10 @@
     WTF_MAKE_NONCOPYABLE(DateTimeWeekFieldElement);
 
 public:
-    static PassRefPtr<DateTimeWeekFieldElement> create(Document*, FieldOwner&, const Range&);
+    static PassRefPtr<DateTimeWeekFieldElement> create(Document&, FieldOwner&, const Range&);
 
 private:
-    DateTimeWeekFieldElement(Document*, FieldOwner&, const Range&);
+    DateTimeWeekFieldElement(Document&, FieldOwner&, const Range&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
@@ -241,10 +241,10 @@
         }
     };
 
-    static PassRefPtr<DateTimeYearFieldElement> create(Document*, FieldOwner&, const Parameters&);
+    static PassRefPtr<DateTimeYearFieldElement> create(Document&, FieldOwner&, const Parameters&);
 
 private:
-    DateTimeYearFieldElement(Document*, FieldOwner&, const Parameters&);
+    DateTimeYearFieldElement(Document&, FieldOwner&, const Parameters&);
 
     // DateTimeFieldElement functions.
     virtual void populateDateTimeFieldsState(DateTimeFieldsState&) OVERRIDE FINAL;
diff --git a/Source/core/html/shadow/DateTimeNumericFieldElement.cpp b/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
index 281d5ba..15703d5 100644
--- a/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
+++ b/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
@@ -52,7 +52,7 @@
 
 // ----------------------------
 
-DateTimeNumericFieldElement::DateTimeNumericFieldElement(Document* document, FieldOwner& fieldOwner, const Range& range, const Range& hardLimits, const String& placeholder, const DateTimeNumericFieldElement::Step& step)
+DateTimeNumericFieldElement::DateTimeNumericFieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Range& hardLimits, const String& placeholder, const DateTimeNumericFieldElement::Step& step)
     : DateTimeFieldElement(document, fieldOwner)
     , m_lastDigitCharTime(0)
     , m_placeholder(placeholder)
diff --git a/Source/core/html/shadow/DateTimeNumericFieldElement.h b/Source/core/html/shadow/DateTimeNumericFieldElement.h
index 220efed..e38e210 100644
--- a/Source/core/html/shadow/DateTimeNumericFieldElement.h
+++ b/Source/core/html/shadow/DateTimeNumericFieldElement.h
@@ -62,7 +62,7 @@
     };
 
 protected:
-    DateTimeNumericFieldElement(Document*, FieldOwner&, const Range&, const Range& hardLimits, const String& placeholder, const Step& = Step());
+    DateTimeNumericFieldElement(Document&, FieldOwner&, const Range&, const Range& hardLimits, const String& placeholder, const Step& = Step());
 
     int clampValue(int value) const { return m_range.clampValue(value); }
     virtual int defaultValueForStepDown() const;
diff --git a/Source/core/html/shadow/DateTimeSymbolicFieldElement.cpp b/Source/core/html/shadow/DateTimeSymbolicFieldElement.cpp
index f20ed22..16d6244 100644
--- a/Source/core/html/shadow/DateTimeSymbolicFieldElement.cpp
+++ b/Source/core/html/shadow/DateTimeSymbolicFieldElement.cpp
@@ -47,7 +47,7 @@
     return builder.toAtomicString();
 }
 
-DateTimeSymbolicFieldElement::DateTimeSymbolicFieldElement(Document* document, FieldOwner& fieldOwner, const Vector<String>& symbols, int minimum, int maximum)
+DateTimeSymbolicFieldElement::DateTimeSymbolicFieldElement(Document& document, FieldOwner& fieldOwner, const Vector<String>& symbols, int minimum, int maximum)
     : DateTimeFieldElement(document, fieldOwner)
     , m_symbols(symbols)
     , m_visibleEmptyValue(makeVisibleEmptyValue(symbols))
diff --git a/Source/core/html/shadow/DateTimeSymbolicFieldElement.h b/Source/core/html/shadow/DateTimeSymbolicFieldElement.h
index 321fa34..65b8c44 100644
--- a/Source/core/html/shadow/DateTimeSymbolicFieldElement.h
+++ b/Source/core/html/shadow/DateTimeSymbolicFieldElement.h
@@ -38,7 +38,7 @@
     WTF_MAKE_NONCOPYABLE(DateTimeSymbolicFieldElement);
 
 protected:
-    DateTimeSymbolicFieldElement(Document*, FieldOwner&, const Vector<String>&, int minimum, int maximum);
+    DateTimeSymbolicFieldElement(Document&, FieldOwner&, const Vector<String>&, int minimum, int maximum);
     size_t symbolsSize() const { return m_symbols.size(); }
     virtual bool hasValue() const OVERRIDE FINAL;
     void initialize(const AtomicString& pseudo, const String& axHelpText);
diff --git a/Source/core/html/shadow/DetailsMarkerControl.cpp b/Source/core/html/shadow/DetailsMarkerControl.cpp
index 6a5e4aa..2056e1a 100644
--- a/Source/core/html/shadow/DetailsMarkerControl.cpp
+++ b/Source/core/html/shadow/DetailsMarkerControl.cpp
@@ -39,7 +39,7 @@
 
 using namespace HTMLNames;
 
-DetailsMarkerControl::DetailsMarkerControl(Document* document)
+DetailsMarkerControl::DetailsMarkerControl(Document& document)
     : HTMLDivElement(divTag, document)
 {
 }
@@ -49,16 +49,14 @@
     return new RenderDetailsMarker(this);
 }
 
-bool DetailsMarkerControl::rendererIsNeeded(const NodeRenderingContext& context)
+bool DetailsMarkerControl::rendererIsNeeded(const RenderStyle& style)
 {
-    return summaryElement()->isMainSummary() && HTMLDivElement::rendererIsNeeded(context);
+    return summaryElement()->isMainSummary() && HTMLDivElement::rendererIsNeeded(style);
 }
 
 HTMLSummaryElement* DetailsMarkerControl::summaryElement()
 {
-    Element* element = shadowHost();
-    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->hasTagName(summaryTag));
-    return static_cast<HTMLSummaryElement*>(element);
+    return toHTMLSummaryElement(shadowHost());
 }
 
 }
diff --git a/Source/core/html/shadow/DetailsMarkerControl.h b/Source/core/html/shadow/DetailsMarkerControl.h
index 1b1bf04..a86195f 100644
--- a/Source/core/html/shadow/DetailsMarkerControl.h
+++ b/Source/core/html/shadow/DetailsMarkerControl.h
@@ -40,17 +40,17 @@
 
 class DetailsMarkerControl FINAL : public HTMLDivElement {
 public:
-    DetailsMarkerControl(Document*);
-    static PassRefPtr<DetailsMarkerControl> create(Document*);
+    DetailsMarkerControl(Document&);
+    static PassRefPtr<DetailsMarkerControl> create(Document&);
 
 private:
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
 
     HTMLSummaryElement* summaryElement();
 };
 
-inline PassRefPtr<DetailsMarkerControl> DetailsMarkerControl::create(Document* document)
+inline PassRefPtr<DetailsMarkerControl> DetailsMarkerControl::create(Document& document)
 {
     RefPtr<DetailsMarkerControl> element = adoptRef(new DetailsMarkerControl(document));
     element->setPart(AtomicString("-webkit-details-marker", AtomicString::ConstructFromLiteral));
diff --git a/Source/core/html/shadow/HTMLContentElement.cpp b/Source/core/html/shadow/HTMLContentElement.cpp
index 5f5554b..004beb8 100644
--- a/Source/core/html/shadow/HTMLContentElement.cpp
+++ b/Source/core/html/shadow/HTMLContentElement.cpp
@@ -40,17 +40,17 @@
 
 using namespace HTMLNames;
 
-PassRefPtr<HTMLContentElement> HTMLContentElement::create(Document* document)
+PassRefPtr<HTMLContentElement> HTMLContentElement::create(Document& document)
 {
     return adoptRef(new HTMLContentElement(contentTag, document));
 }
 
-PassRefPtr<HTMLContentElement> HTMLContentElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLContentElement> HTMLContentElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLContentElement(tagName, document));
 }
 
-HTMLContentElement::HTMLContentElement(const QualifiedName& name, Document* document)
+HTMLContentElement::HTMLContentElement(const QualifiedName& name, Document& document)
     : InsertionPoint(name, document)
     , m_shouldParseSelect(false)
     , m_isValidSelector(true)
diff --git a/Source/core/html/shadow/HTMLContentElement.h b/Source/core/html/shadow/HTMLContentElement.h
index b3cb36a..df52237 100644
--- a/Source/core/html/shadow/HTMLContentElement.h
+++ b/Source/core/html/shadow/HTMLContentElement.h
@@ -38,8 +38,8 @@
 
 class HTMLContentElement FINAL : public InsertionPoint {
 public:
-    static PassRefPtr<HTMLContentElement> create(const QualifiedName&, Document*);
-    static PassRefPtr<HTMLContentElement> create(Document*);
+    static PassRefPtr<HTMLContentElement> create(const QualifiedName&, Document&);
+    static PassRefPtr<HTMLContentElement> create(Document&);
 
     virtual ~HTMLContentElement();
 
@@ -51,7 +51,7 @@
     bool isSelectValid() const;
 
 private:
-    HTMLContentElement(const QualifiedName&, Document*);
+    HTMLContentElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
diff --git a/Source/core/html/shadow/HTMLShadowElement.cpp b/Source/core/html/shadow/HTMLShadowElement.cpp
index d8b857d..a6cf529 100644
--- a/Source/core/html/shadow/HTMLShadowElement.cpp
+++ b/Source/core/html/shadow/HTMLShadowElement.cpp
@@ -38,14 +38,14 @@
 
 class Document;
 
-inline HTMLShadowElement::HTMLShadowElement(const QualifiedName& tagName, Document* document)
+inline HTMLShadowElement::HTMLShadowElement(const QualifiedName& tagName, Document& document)
     : InsertionPoint(tagName, document)
 {
     ASSERT(hasTagName(HTMLNames::shadowTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<HTMLShadowElement> HTMLShadowElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<HTMLShadowElement> HTMLShadowElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new HTMLShadowElement(tagName, document));
 }
@@ -60,7 +60,7 @@
     if (!containingRoot)
         return 0;
 
-    document()->updateDistributionForNodeIfNeeded(this);
+    document().updateDistributionForNodeIfNeeded(this);
 
     ShadowRoot* older = containingRoot->olderShadowRoot();
     if (!older || !older->shouldExposeToBindings() || older->insertionPoint() != this)
@@ -77,7 +77,7 @@
         ShadowRoot* root = containingShadowRoot();
         if (root && root->olderShadowRoot() && root->type() != root->olderShadowRoot()->type()) {
             String message = String::format("<shadow> doesn't work for %s element host.", root->host()->tagName().utf8().data());
-            document()->addConsoleMessage(RenderingMessageSource, WarningMessageLevel, message);
+            document().addConsoleMessage(RenderingMessageSource, WarningMessageLevel, message);
         }
     }
     return InsertionPoint::insertedInto(insertionPoint);
diff --git a/Source/core/html/shadow/HTMLShadowElement.h b/Source/core/html/shadow/HTMLShadowElement.h
index d108dff..b9943bd 100644
--- a/Source/core/html/shadow/HTMLShadowElement.h
+++ b/Source/core/html/shadow/HTMLShadowElement.h
@@ -38,14 +38,14 @@
 
 class HTMLShadowElement FINAL : public InsertionPoint {
 public:
-    static PassRefPtr<HTMLShadowElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<HTMLShadowElement> create(const QualifiedName&, Document&);
 
     virtual ~HTMLShadowElement();
 
     ShadowRoot* olderShadowRoot();
 
 private:
-    HTMLShadowElement(const QualifiedName&, Document*);
+    HTMLShadowElement(const QualifiedName&, Document&);
     virtual InsertionNotificationRequest insertedInto(ContainerNode* insertionPoint) OVERRIDE;
 };
 
diff --git a/Source/core/html/shadow/MediaControlElementTypes.cpp b/Source/core/html/shadow/MediaControlElementTypes.cpp
index 78b1687..6065a8f 100644
--- a/Source/core/html/shadow/MediaControlElementTypes.cpp
+++ b/Source/core/html/shadow/MediaControlElementTypes.cpp
@@ -102,7 +102,7 @@
 
 // ----------------------------
 
-MediaControlDivElement::MediaControlDivElement(Document* document, MediaControlElementType displayType)
+MediaControlDivElement::MediaControlDivElement(Document& document, MediaControlElementType displayType)
     : HTMLDivElement(divTag, document)
     , MediaControlElement(displayType, this)
 {
@@ -110,7 +110,7 @@
 
 // ----------------------------
 
-MediaControlInputElement::MediaControlInputElement(Document* document, MediaControlElementType displayType)
+MediaControlInputElement::MediaControlInputElement(Document& document, MediaControlElementType displayType)
     : HTMLInputElement(inputTag, document, 0, false)
     , MediaControlElement(displayType, this)
 {
@@ -123,7 +123,7 @@
 
 // ----------------------------
 
-MediaControlTimeDisplayElement::MediaControlTimeDisplayElement(Document* document, MediaControlElementType displayType)
+MediaControlTimeDisplayElement::MediaControlTimeDisplayElement(Document& document, MediaControlElementType displayType)
     : MediaControlDivElement(document, displayType)
     , m_currentValue(0)
 {
@@ -136,7 +136,7 @@
 
 // ----------------------------
 
-MediaControlMuteButtonElement::MediaControlMuteButtonElement(Document* document, MediaControlElementType displayType)
+MediaControlMuteButtonElement::MediaControlMuteButtonElement(Document& document, MediaControlElementType displayType)
     : MediaControlInputElement(document, displayType)
 {
 }
@@ -163,7 +163,7 @@
 
 // ----------------------------
 
-MediaControlVolumeSliderElement::MediaControlVolumeSliderElement(Document* document)
+MediaControlVolumeSliderElement::MediaControlVolumeSliderElement(Document& document)
     : MediaControlInputElement(document, MediaVolumeSlider)
     , m_clearMutedOnUserInteraction(false)
 {
diff --git a/Source/core/html/shadow/MediaControlElementTypes.h b/Source/core/html/shadow/MediaControlElementTypes.h
index fb53447..a2304fd 100644
--- a/Source/core/html/shadow/MediaControlElementTypes.h
+++ b/Source/core/html/shadow/MediaControlElementTypes.h
@@ -107,7 +107,7 @@
 class MediaControlDivElement : public HTMLDivElement, public MediaControlElement {
 protected:
     virtual bool isMediaControlElement() const OVERRIDE { return MediaControlElement::isMediaControlElement(); }
-    explicit MediaControlDivElement(Document*, MediaControlElementType);
+    explicit MediaControlDivElement(Document&, MediaControlElementType);
 };
 
 // ----------------------------
@@ -115,7 +115,7 @@
 class MediaControlInputElement : public HTMLInputElement, public MediaControlElement {
 protected:
     virtual bool isMediaControlElement() const OVERRIDE { return MediaControlElement::isMediaControlElement(); }
-    explicit MediaControlInputElement(Document*, MediaControlElementType);
+    explicit MediaControlInputElement(Document&, MediaControlElementType);
 
 private:
     virtual void updateDisplayType() { }
@@ -130,7 +130,7 @@
     double currentValue() const { return m_currentValue; }
 
 protected:
-    explicit MediaControlTimeDisplayElement(Document*, MediaControlElementType);
+    explicit MediaControlTimeDisplayElement(Document&, MediaControlElementType);
 
 private:
     double m_currentValue;
@@ -145,7 +145,7 @@
     virtual bool willRespondToMouseClickEvents() OVERRIDE { return true; }
 
 protected:
-    explicit MediaControlMuteButtonElement(Document*, MediaControlElementType);
+    explicit MediaControlMuteButtonElement(Document&, MediaControlElementType);
 
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
@@ -163,7 +163,7 @@
     void setClearMutedOnUserInteraction(bool);
 
 protected:
-    explicit MediaControlVolumeSliderElement(Document*);
+    explicit MediaControlVolumeSliderElement(Document&);
 
     virtual void defaultEventHandler(Event*) OVERRIDE;
 
diff --git a/Source/core/html/shadow/MediaControlElements.cpp b/Source/core/html/shadow/MediaControlElements.cpp
index 02e252a..cf339da 100644
--- a/Source/core/html/shadow/MediaControlElements.cpp
+++ b/Source/core/html/shadow/MediaControlElements.cpp
@@ -31,10 +31,10 @@
 #include "core/html/shadow/MediaControlElements.h"
 
 #include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/DOMTokenList.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/FullscreenElementStack.h"
 #include "core/dom/MouseEvent.h"
-#include "core/html/DOMTokenList.h"
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/shadow/MediaControls.h"
 #include "core/html/track/TextTrack.h"
@@ -57,7 +57,7 @@
 
 static const char* textTracksOffAttrValue = "-1"; // This must match HTMLMediaElement::textTracksOffIndex()
 
-MediaControlPanelElement::MediaControlPanelElement(Document* document)
+MediaControlPanelElement::MediaControlPanelElement(Document& document)
     : MediaControlDivElement(document, MediaControlsPanel)
     , m_canBeDragged(false)
     , m_isBeingDragged(false)
@@ -67,7 +67,7 @@
 {
 }
 
-PassRefPtr<MediaControlPanelElement> MediaControlPanelElement::create(Document* document)
+PassRefPtr<MediaControlPanelElement> MediaControlPanelElement::create(Document& document)
 {
     return adoptRef(new MediaControlPanelElement(document));
 }
@@ -90,7 +90,7 @@
     if (!renderer || !renderer->isBox())
         return;
 
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
@@ -119,7 +119,7 @@
 
     m_isBeingDragged = false;
 
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
@@ -248,13 +248,13 @@
 
 // ----------------------------
 
-MediaControlPanelEnclosureElement::MediaControlPanelEnclosureElement(Document* document)
+MediaControlPanelEnclosureElement::MediaControlPanelEnclosureElement(Document& document)
     // Mapping onto same MediaControlElementType as panel element, since it has similar properties.
     : MediaControlDivElement(document, MediaControlsPanel)
 {
 }
 
-PassRefPtr<MediaControlPanelEnclosureElement> MediaControlPanelEnclosureElement::create(Document* document)
+PassRefPtr<MediaControlPanelEnclosureElement> MediaControlPanelEnclosureElement::create(Document& document)
 {
     return adoptRef(new MediaControlPanelEnclosureElement(document));
 }
@@ -267,13 +267,13 @@
 
 // ----------------------------
 
-MediaControlOverlayEnclosureElement::MediaControlOverlayEnclosureElement(Document* document)
+MediaControlOverlayEnclosureElement::MediaControlOverlayEnclosureElement(Document& document)
     // Mapping onto same MediaControlElementType as panel element, since it has similar properties.
     : MediaControlDivElement(document, MediaControlsPanel)
 {
 }
 
-PassRefPtr<MediaControlOverlayEnclosureElement> MediaControlOverlayEnclosureElement::create(Document* document)
+PassRefPtr<MediaControlOverlayEnclosureElement> MediaControlOverlayEnclosureElement::create(Document& document)
 {
     return adoptRef(new MediaControlOverlayEnclosureElement(document));
 }
@@ -286,13 +286,13 @@
 
 // ----------------------------
 
-MediaControlPanelMuteButtonElement::MediaControlPanelMuteButtonElement(Document* document, MediaControls* controls)
+MediaControlPanelMuteButtonElement::MediaControlPanelMuteButtonElement(Document& document, MediaControls* controls)
     : MediaControlMuteButtonElement(document, MediaMuteButton)
     , m_controls(controls)
 {
 }
 
-PassRefPtr<MediaControlPanelMuteButtonElement> MediaControlPanelMuteButtonElement::create(Document* document, MediaControls* controls)
+PassRefPtr<MediaControlPanelMuteButtonElement> MediaControlPanelMuteButtonElement::create(Document& document, MediaControls* controls)
 {
     ASSERT(controls);
 
@@ -318,12 +318,12 @@
 
 // ----------------------------
 
-MediaControlVolumeSliderMuteButtonElement::MediaControlVolumeSliderMuteButtonElement(Document* document)
+MediaControlVolumeSliderMuteButtonElement::MediaControlVolumeSliderMuteButtonElement(Document& document)
     : MediaControlMuteButtonElement(document, MediaMuteButton)
 {
 }
 
-PassRefPtr<MediaControlVolumeSliderMuteButtonElement> MediaControlVolumeSliderMuteButtonElement::create(Document* document)
+PassRefPtr<MediaControlVolumeSliderMuteButtonElement> MediaControlVolumeSliderMuteButtonElement::create(Document& document)
 {
     RefPtr<MediaControlVolumeSliderMuteButtonElement> button = adoptRef(new MediaControlVolumeSliderMuteButtonElement(document));
     button->ensureUserAgentShadowRoot();
@@ -339,12 +339,12 @@
 
 // ----------------------------
 
-MediaControlPlayButtonElement::MediaControlPlayButtonElement(Document* document)
+MediaControlPlayButtonElement::MediaControlPlayButtonElement(Document& document)
     : MediaControlInputElement(document, MediaPlayButton)
 {
 }
 
-PassRefPtr<MediaControlPlayButtonElement> MediaControlPlayButtonElement::create(Document* document)
+PassRefPtr<MediaControlPlayButtonElement> MediaControlPlayButtonElement::create(Document& document)
 {
     RefPtr<MediaControlPlayButtonElement> button = adoptRef(new MediaControlPlayButtonElement(document));
     button->ensureUserAgentShadowRoot();
@@ -378,12 +378,12 @@
 
 // ----------------------------
 
-MediaControlOverlayPlayButtonElement::MediaControlOverlayPlayButtonElement(Document* document)
+MediaControlOverlayPlayButtonElement::MediaControlOverlayPlayButtonElement(Document& document)
     : MediaControlInputElement(document, MediaOverlayPlayButton)
 {
 }
 
-PassRefPtr<MediaControlOverlayPlayButtonElement> MediaControlOverlayPlayButtonElement::create(Document* document)
+PassRefPtr<MediaControlOverlayPlayButtonElement> MediaControlOverlayPlayButtonElement::create(Document& document)
 {
     RefPtr<MediaControlOverlayPlayButtonElement> button = adoptRef(new MediaControlOverlayPlayButtonElement(document));
     button->ensureUserAgentShadowRoot();
@@ -418,13 +418,13 @@
 
 // ----------------------------
 
-MediaControlToggleClosedCaptionsButtonElement::MediaControlToggleClosedCaptionsButtonElement(Document* document, MediaControls* controls)
+MediaControlToggleClosedCaptionsButtonElement::MediaControlToggleClosedCaptionsButtonElement(Document& document, MediaControls* controls)
     : MediaControlInputElement(document, MediaShowClosedCaptionsButton)
 {
     UNUSED_PARAM(controls);
 }
 
-PassRefPtr<MediaControlToggleClosedCaptionsButtonElement> MediaControlToggleClosedCaptionsButtonElement::create(Document* document, MediaControls* controls)
+PassRefPtr<MediaControlToggleClosedCaptionsButtonElement> MediaControlToggleClosedCaptionsButtonElement::create(Document& document, MediaControls* controls)
 {
     ASSERT(controls);
 
@@ -462,13 +462,13 @@
 
 // ----------------------------
 
-MediaControlTimelineElement::MediaControlTimelineElement(Document* document, MediaControls* controls)
+MediaControlTimelineElement::MediaControlTimelineElement(Document& document, MediaControls* controls)
     : MediaControlInputElement(document, MediaSlider)
     , m_controls(controls)
 {
 }
 
-PassRefPtr<MediaControlTimelineElement> MediaControlTimelineElement::create(Document* document, MediaControls* controls)
+PassRefPtr<MediaControlTimelineElement> MediaControlTimelineElement::create(Document& document, MediaControls* controls)
 {
     ASSERT(controls);
 
@@ -535,12 +535,12 @@
 
 // ----------------------------
 
-MediaControlPanelVolumeSliderElement::MediaControlPanelVolumeSliderElement(Document* document)
+MediaControlPanelVolumeSliderElement::MediaControlPanelVolumeSliderElement(Document& document)
     : MediaControlVolumeSliderElement(document)
 {
 }
 
-PassRefPtr<MediaControlPanelVolumeSliderElement> MediaControlPanelVolumeSliderElement::create(Document* document)
+PassRefPtr<MediaControlPanelVolumeSliderElement> MediaControlPanelVolumeSliderElement::create(Document& document)
 {
     RefPtr<MediaControlPanelVolumeSliderElement> slider = adoptRef(new MediaControlPanelVolumeSliderElement(document));
     slider->ensureUserAgentShadowRoot();
@@ -558,12 +558,12 @@
 
 // ----------------------------
 
-MediaControlFullscreenButtonElement::MediaControlFullscreenButtonElement(Document* document)
+MediaControlFullscreenButtonElement::MediaControlFullscreenButtonElement(Document& document)
     : MediaControlInputElement(document, MediaEnterFullscreenButton)
 {
 }
 
-PassRefPtr<MediaControlFullscreenButtonElement> MediaControlFullscreenButtonElement::create(Document* document)
+PassRefPtr<MediaControlFullscreenButtonElement> MediaControlFullscreenButtonElement::create(Document& document)
 {
     RefPtr<MediaControlFullscreenButtonElement> button = adoptRef(new MediaControlFullscreenButtonElement(document));
     button->ensureUserAgentShadowRoot();
@@ -580,11 +580,11 @@
         // allows apps which embed a WebView to retain the existing full screen
         // video implementation without requiring them to implement their own full
         // screen behavior.
-        if (document()->settings() && document()->settings()->fullScreenEnabled()) {
+        if (document().settings() && document().settings()->fullScreenEnabled()) {
             if (FullscreenElementStack::isActiveFullScreenElement(toParentMediaElement(this)))
-                FullscreenElementStack::from(document())->webkitCancelFullScreen();
+                FullscreenElementStack::from(&document())->webkitCancelFullScreen();
             else
-                FullscreenElementStack::from(document())->requestFullScreenForElement(toParentMediaElement(this), 0, FullscreenElementStack::ExemptIFrameAllowFullScreenRequirement);
+                FullscreenElementStack::from(&document())->requestFullScreenForElement(toParentMediaElement(this), 0, FullscreenElementStack::ExemptIFrameAllowFullScreenRequirement);
         } else
             mediaController()->enterFullscreen();
         event->setDefaultHandled();
@@ -605,12 +605,12 @@
 
 // ----------------------------
 
-MediaControlTimeRemainingDisplayElement::MediaControlTimeRemainingDisplayElement(Document* document)
+MediaControlTimeRemainingDisplayElement::MediaControlTimeRemainingDisplayElement(Document& document)
     : MediaControlTimeDisplayElement(document, MediaTimeRemainingDisplay)
 {
 }
 
-PassRefPtr<MediaControlTimeRemainingDisplayElement> MediaControlTimeRemainingDisplayElement::create(Document* document)
+PassRefPtr<MediaControlTimeRemainingDisplayElement> MediaControlTimeRemainingDisplayElement::create(Document& document)
 {
     return adoptRef(new MediaControlTimeRemainingDisplayElement(document));
 }
@@ -628,12 +628,12 @@
 
 // ----------------------------
 
-MediaControlCurrentTimeDisplayElement::MediaControlCurrentTimeDisplayElement(Document* document)
+MediaControlCurrentTimeDisplayElement::MediaControlCurrentTimeDisplayElement(Document& document)
     : MediaControlTimeDisplayElement(document, MediaCurrentTimeDisplay)
 {
 }
 
-PassRefPtr<MediaControlCurrentTimeDisplayElement> MediaControlCurrentTimeDisplayElement::create(Document* document)
+PassRefPtr<MediaControlCurrentTimeDisplayElement> MediaControlCurrentTimeDisplayElement::create(Document& document)
 {
     return adoptRef(new MediaControlCurrentTimeDisplayElement(document));
 }
@@ -651,13 +651,13 @@
 
 // ----------------------------
 
-MediaControlTextTrackContainerElement::MediaControlTextTrackContainerElement(Document* document)
+MediaControlTextTrackContainerElement::MediaControlTextTrackContainerElement(Document& document)
     : MediaControlDivElement(document, MediaTextTrackDisplayContainer)
     , m_fontSize(0)
 {
 }
 
-PassRefPtr<MediaControlTextTrackContainerElement> MediaControlTextTrackContainerElement::create(Document* document)
+PassRefPtr<MediaControlTextTrackContainerElement> MediaControlTextTrackContainerElement::create(Document& document)
 {
     RefPtr<MediaControlTextTrackContainerElement> element = adoptRef(new MediaControlTextTrackContainerElement(document));
     element->hide();
@@ -781,7 +781,7 @@
     if (!mediaElement)
         return;
 
-    if (!document()->page())
+    if (!document().page())
         return;
 
     IntRect videoBox;
diff --git a/Source/core/html/shadow/MediaControlElements.h b/Source/core/html/shadow/MediaControlElements.h
index 168ab29..e53002d 100644
--- a/Source/core/html/shadow/MediaControlElements.h
+++ b/Source/core/html/shadow/MediaControlElements.h
@@ -38,7 +38,7 @@
 
 class MediaControlPanelElement FINAL : public MediaControlDivElement {
 public:
-    static PassRefPtr<MediaControlPanelElement> create(Document*);
+    static PassRefPtr<MediaControlPanelElement> create(Document&);
 
     void setCanBeDragged(bool);
     void setIsDisplayed(bool);
@@ -51,7 +51,7 @@
     virtual bool willRespondToMouseClickEvents() OVERRIDE { return true; }
 
 private:
-    explicit MediaControlPanelElement(Document*);
+    explicit MediaControlPanelElement(Document&);
 
     virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
@@ -80,10 +80,10 @@
 
 class MediaControlPanelEnclosureElement FINAL : public MediaControlDivElement {
 public:
-    static PassRefPtr<MediaControlPanelEnclosureElement> create(Document*);
+    static PassRefPtr<MediaControlPanelEnclosureElement> create(Document&);
 
 private:
-    explicit MediaControlPanelEnclosureElement(Document*);
+    explicit MediaControlPanelEnclosureElement(Document&);
     virtual const AtomicString& part() const OVERRIDE;
 };
 
@@ -91,10 +91,10 @@
 
 class MediaControlOverlayEnclosureElement FINAL : public MediaControlDivElement {
 public:
-    static PassRefPtr<MediaControlOverlayEnclosureElement> create(Document*);
+    static PassRefPtr<MediaControlOverlayEnclosureElement> create(Document&);
 
 private:
-    explicit MediaControlOverlayEnclosureElement(Document*);
+    explicit MediaControlOverlayEnclosureElement(Document&);
     virtual const AtomicString& part() const OVERRIDE;
 };
 
@@ -102,12 +102,12 @@
 
 class MediaControlPanelMuteButtonElement FINAL : public MediaControlMuteButtonElement {
 public:
-    static PassRefPtr<MediaControlPanelMuteButtonElement> create(Document*, MediaControls*);
+    static PassRefPtr<MediaControlPanelMuteButtonElement> create(Document&, MediaControls*);
 
     virtual bool willRespondToMouseMoveEvents() OVERRIDE { return true; }
 
 private:
-    explicit MediaControlPanelMuteButtonElement(Document*, MediaControls*);
+    explicit MediaControlPanelMuteButtonElement(Document&, MediaControls*);
 
     virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
@@ -119,10 +119,10 @@
 
 class MediaControlVolumeSliderMuteButtonElement FINAL : public MediaControlMuteButtonElement {
 public:
-    static PassRefPtr<MediaControlVolumeSliderMuteButtonElement> create(Document*);
+    static PassRefPtr<MediaControlVolumeSliderMuteButtonElement> create(Document&);
 
 private:
-    explicit MediaControlVolumeSliderMuteButtonElement(Document*);
+    explicit MediaControlVolumeSliderMuteButtonElement(Document&);
     virtual const AtomicString& part() const OVERRIDE;
 };
 
@@ -131,13 +131,13 @@
 
 class MediaControlPlayButtonElement FINAL : public MediaControlInputElement {
 public:
-    static PassRefPtr<MediaControlPlayButtonElement> create(Document*);
+    static PassRefPtr<MediaControlPlayButtonElement> create(Document&);
 
     virtual bool willRespondToMouseClickEvents() OVERRIDE { return true; }
     virtual void updateDisplayType() OVERRIDE;
 
 private:
-    explicit MediaControlPlayButtonElement(Document*);
+    explicit MediaControlPlayButtonElement(Document&);
 
     virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
@@ -147,12 +147,12 @@
 
 class MediaControlOverlayPlayButtonElement FINAL : public MediaControlInputElement {
 public:
-    static PassRefPtr<MediaControlOverlayPlayButtonElement> create(Document*);
+    static PassRefPtr<MediaControlOverlayPlayButtonElement> create(Document&);
 
     virtual void updateDisplayType() OVERRIDE;
 
 private:
-    explicit MediaControlOverlayPlayButtonElement(Document*);
+    explicit MediaControlOverlayPlayButtonElement(Document&);
 
     virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
@@ -162,14 +162,14 @@
 
 class MediaControlToggleClosedCaptionsButtonElement FINAL : public MediaControlInputElement {
 public:
-    static PassRefPtr<MediaControlToggleClosedCaptionsButtonElement> create(Document*, MediaControls*);
+    static PassRefPtr<MediaControlToggleClosedCaptionsButtonElement> create(Document&, MediaControls*);
 
     virtual bool willRespondToMouseClickEvents() OVERRIDE { return true; }
 
     virtual void updateDisplayType() OVERRIDE;
 
 private:
-    explicit MediaControlToggleClosedCaptionsButtonElement(Document*, MediaControls*);
+    explicit MediaControlToggleClosedCaptionsButtonElement(Document&, MediaControls*);
 
     virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
@@ -179,7 +179,7 @@
 
 class MediaControlTimelineElement FINAL : public MediaControlInputElement {
 public:
-    static PassRefPtr<MediaControlTimelineElement> create(Document*, MediaControls*);
+    static PassRefPtr<MediaControlTimelineElement> create(Document&, MediaControls*);
 
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
@@ -187,7 +187,7 @@
     void setDuration(double);
 
 private:
-    explicit MediaControlTimelineElement(Document*, MediaControls*);
+    explicit MediaControlTimelineElement(Document&, MediaControls*);
 
     virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
@@ -199,14 +199,14 @@
 
 class MediaControlFullscreenButtonElement FINAL : public MediaControlInputElement {
 public:
-    static PassRefPtr<MediaControlFullscreenButtonElement> create(Document*);
+    static PassRefPtr<MediaControlFullscreenButtonElement> create(Document&);
 
     virtual bool willRespondToMouseClickEvents() OVERRIDE { return true; }
 
     virtual void setIsFullscreen(bool);
 
 private:
-    explicit MediaControlFullscreenButtonElement(Document*);
+    explicit MediaControlFullscreenButtonElement(Document&);
 
     virtual const AtomicString& part() const OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
@@ -216,10 +216,10 @@
 
 class MediaControlPanelVolumeSliderElement FINAL : public MediaControlVolumeSliderElement {
 public:
-    static PassRefPtr<MediaControlPanelVolumeSliderElement> create(Document*);
+    static PassRefPtr<MediaControlPanelVolumeSliderElement> create(Document&);
 
 private:
-    explicit MediaControlPanelVolumeSliderElement(Document*);
+    explicit MediaControlPanelVolumeSliderElement(Document&);
     virtual const AtomicString& part() const OVERRIDE;
 };
 
@@ -227,10 +227,10 @@
 
 class MediaControlTimeRemainingDisplayElement FINAL : public MediaControlTimeDisplayElement {
 public:
-    static PassRefPtr<MediaControlTimeRemainingDisplayElement> create(Document*);
+    static PassRefPtr<MediaControlTimeRemainingDisplayElement> create(Document&);
 
 private:
-    explicit MediaControlTimeRemainingDisplayElement(Document*);
+    explicit MediaControlTimeRemainingDisplayElement(Document&);
     virtual const AtomicString& part() const OVERRIDE;
 };
 
@@ -238,10 +238,10 @@
 
 class MediaControlCurrentTimeDisplayElement FINAL : public MediaControlTimeDisplayElement {
 public:
-    static PassRefPtr<MediaControlCurrentTimeDisplayElement> create(Document*);
+    static PassRefPtr<MediaControlCurrentTimeDisplayElement> create(Document&);
 
 private:
-    explicit MediaControlCurrentTimeDisplayElement(Document*);
+    explicit MediaControlCurrentTimeDisplayElement(Document&);
     virtual const AtomicString& part() const OVERRIDE;
 };
 
@@ -249,14 +249,14 @@
 
 class MediaControlTextTrackContainerElement FINAL : public MediaControlDivElement {
 public:
-    static PassRefPtr<MediaControlTextTrackContainerElement> create(Document*);
+    static PassRefPtr<MediaControlTextTrackContainerElement> create(Document&);
 
     void updateDisplay();
     void updateSizes(bool forceUpdate = false);
     static const AtomicString& textTrackContainerElementShadowPseudoId();
 
 private:
-    explicit MediaControlTextTrackContainerElement(Document*);
+    explicit MediaControlTextTrackContainerElement(Document&);
     virtual const AtomicString& part() const OVERRIDE;
 
     virtual RenderObject* createRenderer(RenderStyle*);
diff --git a/Source/core/html/shadow/MediaControls.cpp b/Source/core/html/shadow/MediaControls.cpp
index 8fc410a..e86861e 100644
--- a/Source/core/html/shadow/MediaControls.cpp
+++ b/Source/core/html/shadow/MediaControls.cpp
@@ -33,7 +33,7 @@
 
 static const double timeWithoutMouseMovementBeforeHidingFullscreenControls = 3;
 
-MediaControls::MediaControls(Document* document)
+MediaControls::MediaControls(Document& document)
     : HTMLDivElement(HTMLNames::divTag, document)
     , m_mediaController(0)
     , m_panel(0)
@@ -79,7 +79,7 @@
 
 void MediaControls::reset()
 {
-    Page* page = document()->page();
+    Page* page = document().page();
     if (!page)
         return;
 
@@ -121,7 +121,7 @@
 
 void MediaControls::reportedError()
 {
-    Page* page = document()->page();
+    Page* page = document().page();
     if (!page)
         return;
 
@@ -319,7 +319,7 @@
     if (!m_isFullscreen)
         return;
 
-    Page* page = document()->page();
+    Page* page = document().page();
     if (!page)
         return;
 
diff --git a/Source/core/html/shadow/MediaControls.h b/Source/core/html/shadow/MediaControls.h
index 130d03c..4342ac1 100644
--- a/Source/core/html/shadow/MediaControls.h
+++ b/Source/core/html/shadow/MediaControls.h
@@ -50,7 +50,7 @@
 
     // This function is to be implemented in your port-specific media
     // controls implementation since it will return a child instance.
-    static PassRefPtr<MediaControls> create(Document*);
+    static PassRefPtr<MediaControls> create(Document&);
 
     virtual void setMediaController(MediaControllerInterface*);
 
@@ -95,7 +95,7 @@
     virtual void updateTextTrackDisplay();
 
 protected:
-    explicit MediaControls(Document*);
+    explicit MediaControls(Document&);
 
     virtual void defaultEventHandler(Event*);
 
diff --git a/Source/core/html/shadow/MediaControlsChromium.cpp b/Source/core/html/shadow/MediaControlsChromium.cpp
index a14e7f3..d4fadf7 100644
--- a/Source/core/html/shadow/MediaControlsChromium.cpp
+++ b/Source/core/html/shadow/MediaControlsChromium.cpp
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-MediaControlsChromium::MediaControlsChromium(Document* document)
+MediaControlsChromium::MediaControlsChromium(Document& document)
     : MediaControls(document)
     , m_durationDisplay(0)
     , m_enclosure(0)
@@ -43,15 +43,15 @@
 
 // MediaControls::create() for Android is defined in MediaControlsChromiumAndroid.cpp.
 #if !OS(ANDROID)
-PassRefPtr<MediaControls> MediaControls::create(Document* document)
+PassRefPtr<MediaControls> MediaControls::create(Document& document)
 {
     return MediaControlsChromium::createControls(document);
 }
 #endif
 
-PassRefPtr<MediaControlsChromium> MediaControlsChromium::createControls(Document* document)
+PassRefPtr<MediaControlsChromium> MediaControlsChromium::createControls(Document& document)
 {
-    if (!document->page())
+    if (!document.page())
         return 0;
 
     RefPtr<MediaControlsChromium> controls = adoptRef(new MediaControlsChromium(document));
@@ -62,7 +62,7 @@
     return 0;
 }
 
-bool MediaControlsChromium::initializeControls(Document* document)
+bool MediaControlsChromium::initializeControls(Document& document)
 {
     // Create an enclosing element for the panel so we can visually offset the controls correctly.
     RefPtr<MediaControlPanelEnclosureElement> enclosure = MediaControlPanelEnclosureElement::create(document);
@@ -151,7 +151,7 @@
 
 void MediaControlsChromium::reset()
 {
-    Page* page = document()->page();
+    Page* page = document().page();
     if (!page)
         return;
 
@@ -175,7 +175,7 @@
     double now = m_mediaController->currentTime();
     double duration = m_mediaController->duration();
 
-    Page* page = document()->page();
+    Page* page = document().page();
     if (!page)
         return;
 
diff --git a/Source/core/html/shadow/MediaControlsChromium.h b/Source/core/html/shadow/MediaControlsChromium.h
index 3e8b7c7..5e3c55e 100644
--- a/Source/core/html/shadow/MediaControlsChromium.h
+++ b/Source/core/html/shadow/MediaControlsChromium.h
@@ -34,7 +34,7 @@
 class MediaControlsChromium : public MediaControls {
 public:
     // Called from port-specific parent create function to create custom controls.
-    static PassRefPtr<MediaControlsChromium> createControls(Document*);
+    static PassRefPtr<MediaControlsChromium> createControls(Document&);
 
     virtual void setMediaController(MediaControllerInterface*) OVERRIDE;
 
@@ -51,9 +51,9 @@
     virtual void insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement>);
 
 protected:
-    explicit MediaControlsChromium(Document*);
+    explicit MediaControlsChromium(Document&);
 
-    bool initializeControls(Document*);
+    bool initializeControls(Document&);
 
 private:
     MediaControlTimeRemainingDisplayElement* m_durationDisplay;
diff --git a/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp b/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
index 77adeaf..1585d86 100644
--- a/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
+++ b/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
@@ -31,21 +31,21 @@
 
 namespace WebCore {
 
-MediaControlsChromiumAndroid::MediaControlsChromiumAndroid(Document* document)
+MediaControlsChromiumAndroid::MediaControlsChromiumAndroid(Document& document)
     : MediaControlsChromium(document)
     , m_overlayPlayButton(0)
     , m_overlayEnclosure(0)
 {
 }
 
-PassRefPtr<MediaControls> MediaControls::create(Document* document)
+PassRefPtr<MediaControls> MediaControls::create(Document& document)
 {
     return MediaControlsChromiumAndroid::createControls(document);
 }
 
-PassRefPtr<MediaControlsChromiumAndroid> MediaControlsChromiumAndroid::createControls(Document* document)
+PassRefPtr<MediaControlsChromiumAndroid> MediaControlsChromiumAndroid::createControls(Document& document)
 {
-    if (!document->page())
+    if (!document.page())
         return 0;
 
     RefPtr<MediaControlsChromiumAndroid> controls = adoptRef(new MediaControlsChromiumAndroid(document));
diff --git a/Source/core/html/shadow/MediaControlsChromiumAndroid.h b/Source/core/html/shadow/MediaControlsChromiumAndroid.h
index 2980160..5935f38 100644
--- a/Source/core/html/shadow/MediaControlsChromiumAndroid.h
+++ b/Source/core/html/shadow/MediaControlsChromiumAndroid.h
@@ -33,7 +33,7 @@
 
 class MediaControlsChromiumAndroid : public MediaControlsChromium {
 public:
-    static PassRefPtr<MediaControlsChromiumAndroid> createControls(Document*);
+    static PassRefPtr<MediaControlsChromiumAndroid> createControls(Document&);
 
     virtual void setMediaController(MediaControllerInterface*) OVERRIDE;
     virtual void playbackStarted() OVERRIDE;
@@ -42,7 +42,7 @@
     void insertTextTrackContainer(PassRefPtr<MediaControlTextTrackContainerElement>) OVERRIDE;
 
 private:
-    explicit MediaControlsChromiumAndroid(Document*);
+    explicit MediaControlsChromiumAndroid(Document&);
 
     MediaControlOverlayPlayButtonElement* m_overlayPlayButton;
     MediaControlOverlayEnclosureElement* m_overlayEnclosure;
diff --git a/Source/core/html/shadow/MeterShadowElement.cpp b/Source/core/html/shadow/MeterShadowElement.cpp
index 834b6fb..0462983 100644
--- a/Source/core/html/shadow/MeterShadowElement.cpp
+++ b/Source/core/html/shadow/MeterShadowElement.cpp
@@ -42,7 +42,7 @@
 
 using namespace HTMLNames;
 
-inline MeterShadowElement::MeterShadowElement(Document* document)
+inline MeterShadowElement::MeterShadowElement(Document& document)
     : HTMLDivElement(HTMLNames::divTag, document)
 {
 }
@@ -52,31 +52,31 @@
     return toHTMLMeterElement(shadowHost());
 }
 
-bool MeterShadowElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool MeterShadowElement::rendererIsNeeded(const RenderStyle& style)
 {
-    RenderObject* render = meterElement()->renderer();
-    return render && !RenderTheme::theme().supportsMeter(render->style()->appearance()) && HTMLDivElement::rendererIsNeeded(context);
+    RenderObject* renderer = meterElement()->renderer();
+    return renderer && !RenderTheme::theme().supportsMeter(renderer->style()->appearance()) && HTMLDivElement::rendererIsNeeded(style);
 }
 
-inline MeterInnerElement::MeterInnerElement(Document* document)
+inline MeterInnerElement::MeterInnerElement(Document& document)
     : MeterShadowElement(document)
 {
 }
 
-PassRefPtr<MeterInnerElement> MeterInnerElement::create(Document* document)
+PassRefPtr<MeterInnerElement> MeterInnerElement::create(Document& document)
 {
     RefPtr<MeterInnerElement> element = adoptRef(new MeterInnerElement(document));
     element->setPart(AtomicString("-webkit-meter-inner-element", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
-bool MeterInnerElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool MeterInnerElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (meterElement()->hasAuthorShadowRoot())
-        return HTMLDivElement::rendererIsNeeded(context);
+        return HTMLDivElement::rendererIsNeeded(style);
 
-    RenderObject* render = meterElement()->renderer();
-    return render && !RenderTheme::theme().supportsMeter(render->style()->appearance()) && HTMLDivElement::rendererIsNeeded(context);
+    RenderObject* renderer = meterElement()->renderer();
+    return renderer && !RenderTheme::theme().supportsMeter(renderer->style()->appearance()) && HTMLDivElement::rendererIsNeeded(style);
 }
 
 RenderObject* MeterInnerElement::createRenderer(RenderStyle*)
@@ -84,24 +84,24 @@
     return new RenderMeter(this);
 }
 
-inline MeterBarElement::MeterBarElement(Document* document)
+inline MeterBarElement::MeterBarElement(Document& document)
     : MeterShadowElement(document)
 {
 }
 
-PassRefPtr<MeterBarElement> MeterBarElement::create(Document* document)
+PassRefPtr<MeterBarElement> MeterBarElement::create(Document& document)
 {
     RefPtr<MeterBarElement> element = adoptRef(new MeterBarElement(document));
     element->setPart(AtomicString("-webkit-meter-bar", AtomicString::ConstructFromLiteral));
     return element.release();
 }
 
-inline MeterValueElement::MeterValueElement(Document* document)
+inline MeterValueElement::MeterValueElement(Document& document)
     : MeterShadowElement(document)
 {
 }
 
-PassRefPtr<MeterValueElement> MeterValueElement::create(Document* document)
+PassRefPtr<MeterValueElement> MeterValueElement::create(Document& document)
 {
     RefPtr<MeterValueElement> element = adoptRef(new MeterValueElement(document));
     element->updatePseudo();
diff --git a/Source/core/html/shadow/MeterShadowElement.h b/Source/core/html/shadow/MeterShadowElement.h
index a314267..30bbd9c 100644
--- a/Source/core/html/shadow/MeterShadowElement.h
+++ b/Source/core/html/shadow/MeterShadowElement.h
@@ -41,39 +41,39 @@
 
 class MeterShadowElement : public HTMLDivElement {
 protected:
-    MeterShadowElement(Document*);
+    MeterShadowElement(Document&);
     HTMLMeterElement* meterElement() const;
 
 private:
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
 };
 
 class MeterInnerElement FINAL : public MeterShadowElement {
 public:
-    static PassRefPtr<MeterInnerElement> create(Document*);
+    static PassRefPtr<MeterInnerElement> create(Document&);
 
 private:
-    MeterInnerElement(Document*);
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
+    MeterInnerElement(Document&);
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 };
 
 class MeterBarElement FINAL : public MeterShadowElement {
 private:
-    MeterBarElement(Document*);
+    MeterBarElement(Document&);
 
 public:
-    static PassRefPtr<MeterBarElement> create(Document*);
+    static PassRefPtr<MeterBarElement> create(Document&);
 };
 
 class MeterValueElement FINAL : public MeterShadowElement {
 public:
-    static PassRefPtr<MeterValueElement> create(Document*);
+    static PassRefPtr<MeterValueElement> create(Document&);
     void setWidthPercentage(double);
     void updatePseudo() { setPart(valuePseudoId()); }
 
 private:
-    MeterValueElement(Document*);
+    MeterValueElement(Document&);
     const AtomicString& valuePseudoId() const;
 };
 
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
index bcc124f..33d4428 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
@@ -52,7 +52,7 @@
 
 // FIXME: This class is only used in Chromium and has no layout tests.
 
-PasswordGeneratorButtonElement::PasswordGeneratorButtonElement(Document* document)
+PasswordGeneratorButtonElement::PasswordGeneratorButtonElement(Document& document)
     : HTMLDivElement(HTMLNames::divTag, document)
     , m_isInHoverState(false)
 {
@@ -171,7 +171,7 @@
 
     RefPtr<PasswordGeneratorButtonElement> protector(this);
     if (event->type() == eventNames().clickEvent) {
-        if (Page* page = document()->page())
+        if (Page* page = document().page())
             page->chrome().client().openPasswordGenerator(input.get());
         event->setDefaultHandled();
     }
diff --git a/Source/core/html/shadow/PasswordGeneratorButtonElement.h b/Source/core/html/shadow/PasswordGeneratorButtonElement.h
index 3a3d7c1..e0853ea 100644
--- a/Source/core/html/shadow/PasswordGeneratorButtonElement.h
+++ b/Source/core/html/shadow/PasswordGeneratorButtonElement.h
@@ -42,7 +42,7 @@
 
 class PasswordGeneratorButtonElement FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<PasswordGeneratorButtonElement> create(Document* document)
+    static PassRefPtr<PasswordGeneratorButtonElement> create(Document& document)
     {
         return adoptRef(new PasswordGeneratorButtonElement(document));
     }
@@ -53,7 +53,7 @@
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
-    PasswordGeneratorButtonElement(Document*);
+    PasswordGeneratorButtonElement(Document&);
     virtual bool isPasswordGeneratorButtonElement() const OVERRIDE { return true; }
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
diff --git a/Source/core/html/shadow/PickerIndicatorElement.cpp b/Source/core/html/shadow/PickerIndicatorElement.cpp
index 6fbb1cf..208475d 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.cpp
+++ b/Source/core/html/shadow/PickerIndicatorElement.cpp
@@ -44,13 +44,13 @@
 
 using namespace HTMLNames;
 
-inline PickerIndicatorElement::PickerIndicatorElement(Document* document, PickerIndicatorOwner& pickerIndicatorOwner)
+inline PickerIndicatorElement::PickerIndicatorElement(Document& document, PickerIndicatorOwner& pickerIndicatorOwner)
     : HTMLDivElement(divTag, document)
     , m_pickerIndicatorOwner(&pickerIndicatorOwner)
 {
 }
 
-PassRefPtr<PickerIndicatorElement> PickerIndicatorElement::create(Document* document, PickerIndicatorOwner& pickerIndicatorOwner)
+PassRefPtr<PickerIndicatorElement> PickerIndicatorElement::create(Document& document, PickerIndicatorOwner& pickerIndicatorOwner)
 {
     RefPtr<PickerIndicatorElement> element = adoptRef(new PickerIndicatorElement(document, pickerIndicatorOwner));
     element->setPart(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
@@ -109,14 +109,14 @@
 {
     if (m_chooser)
         return;
-    if (!document()->page())
+    if (!document().page())
         return;
     if (!m_pickerIndicatorOwner)
         return;
     DateTimeChooserParameters parameters;
     if (!m_pickerIndicatorOwner->setupDateTimeChooserParameters(parameters))
         return;
-    m_chooser = document()->page()->chrome().openDateTimeChooser(this, parameters);
+    m_chooser = document().page()->chrome().openDateTimeChooser(this, parameters);
 }
 
 void PickerIndicatorElement::closePopup()
diff --git a/Source/core/html/shadow/PickerIndicatorElement.h b/Source/core/html/shadow/PickerIndicatorElement.h
index 29aff6e..3e899fe 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.h
+++ b/Source/core/html/shadow/PickerIndicatorElement.h
@@ -53,7 +53,7 @@
         virtual bool setupDateTimeChooserParameters(DateTimeChooserParameters&) = 0;
     };
 
-    static PassRefPtr<PickerIndicatorElement> create(Document*, PickerIndicatorOwner&);
+    static PassRefPtr<PickerIndicatorElement> create(Document&, PickerIndicatorOwner&);
     virtual ~PickerIndicatorElement();
     void openPopup();
     void closePopup();
@@ -65,7 +65,7 @@
     virtual void didEndChooser() OVERRIDE;
 
 private:
-    PickerIndicatorElement(Document*, PickerIndicatorOwner&);
+    PickerIndicatorElement(Document&, PickerIndicatorOwner&);
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
diff --git a/Source/core/html/shadow/ProgressShadowElement.cpp b/Source/core/html/shadow/ProgressShadowElement.cpp
index c1bc2b7..2de1161 100644
--- a/Source/core/html/shadow/ProgressShadowElement.cpp
+++ b/Source/core/html/shadow/ProgressShadowElement.cpp
@@ -40,7 +40,7 @@
 
 using namespace HTMLNames;
 
-ProgressShadowElement::ProgressShadowElement(Document* document)
+ProgressShadowElement::ProgressShadowElement(Document& document)
     : HTMLDivElement(HTMLNames::divTag, document)
 {
 }
@@ -50,24 +50,15 @@
     return toHTMLProgressElement(shadowHost());
 }
 
-bool ProgressShadowElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool ProgressShadowElement::rendererIsNeeded(const RenderStyle& style)
 {
     RenderObject* progressRenderer = progressElement()->renderer();
-    return progressRenderer && !progressRenderer->style()->hasAppearance() && HTMLDivElement::rendererIsNeeded(context);
+    return progressRenderer && !progressRenderer->style()->hasAppearance() && HTMLDivElement::rendererIsNeeded(style);
 }
 
-ProgressInnerElement::ProgressInnerElement(Document* document)
+ProgressInnerElement::ProgressInnerElement(Document& document)
     : ProgressShadowElement(document)
 {
-    DEFINE_STATIC_LOCAL(AtomicString, pseudoId, ("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
-    setPart(pseudoId);
-}
-
-PassRefPtr<ProgressInnerElement> ProgressInnerElement::create(Document* document)
-{
-    RefPtr<ProgressInnerElement> element = adoptRef(new ProgressInnerElement(document));
-    element->setPart(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
-    return element.release();
 }
 
 RenderObject* ProgressInnerElement::createRenderer(RenderStyle*)
@@ -75,13 +66,23 @@
     return new RenderProgress(this);
 }
 
-bool ProgressInnerElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool ProgressInnerElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (progressElement()->hasAuthorShadowRoot())
-        return HTMLDivElement::rendererIsNeeded(context);
+        return HTMLDivElement::rendererIsNeeded(style);
 
     RenderObject* progressRenderer = progressElement()->renderer();
-    return progressRenderer && !progressRenderer->style()->hasAppearance() && HTMLDivElement::rendererIsNeeded(context);
+    return progressRenderer && !progressRenderer->style()->hasAppearance() && HTMLDivElement::rendererIsNeeded(style);
+}
+
+ProgressBarElement::ProgressBarElement(Document& document)
+    : ProgressShadowElement(document)
+{
+}
+
+ProgressValueElement::ProgressValueElement(Document& document)
+    : ProgressShadowElement(document)
+{
 }
 
 void ProgressValueElement::setWidthPercentage(double width)
diff --git a/Source/core/html/shadow/ProgressShadowElement.h b/Source/core/html/shadow/ProgressShadowElement.h
index 8e02bdc..b375fcc 100644
--- a/Source/core/html/shadow/ProgressShadowElement.h
+++ b/Source/core/html/shadow/ProgressShadowElement.h
@@ -41,54 +41,52 @@
 
 class ProgressShadowElement : public HTMLDivElement {
 public:
-    ProgressShadowElement(Document*);
+    ProgressShadowElement(Document&);
     HTMLProgressElement* progressElement() const;
 
 protected:
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
 };
 
 class ProgressInnerElement FINAL : public ProgressShadowElement {
 public:
-    ProgressInnerElement(Document*);
+    static PassRefPtr<ProgressInnerElement> create(Document&);
 
-    static PassRefPtr<ProgressInnerElement> create(Document*);
 private:
+    ProgressInnerElement(Document&);
+
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
 };
 
+inline PassRefPtr<ProgressInnerElement> ProgressInnerElement::create(Document& document)
+{
+    return adoptRef(new ProgressInnerElement(document));
+}
+
 class ProgressBarElement FINAL : public ProgressShadowElement {
 public:
-    ProgressBarElement(Document* document)
-        : ProgressShadowElement(document)
-    {
-        DEFINE_STATIC_LOCAL(AtomicString, pseudoId, ("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
-        setPart(pseudoId);
-    }
+    static PassRefPtr<ProgressBarElement> create(Document&);
 
-    static PassRefPtr<ProgressBarElement> create(Document*);
+private:
+    ProgressBarElement(Document&);
 };
 
-inline PassRefPtr<ProgressBarElement> ProgressBarElement::create(Document* document)
+inline PassRefPtr<ProgressBarElement> ProgressBarElement::create(Document& document)
 {
     return adoptRef(new ProgressBarElement(document));
 }
 
 class ProgressValueElement FINAL : public ProgressShadowElement {
 public:
-    ProgressValueElement(Document* document)
-        : ProgressShadowElement(document)
-    {
-        DEFINE_STATIC_LOCAL(AtomicString, pseudoId, ("-webkit-progress-value", AtomicString::ConstructFromLiteral));
-        setPart(pseudoId);
-    }
-
-    static PassRefPtr<ProgressValueElement> create(Document*);
+    static PassRefPtr<ProgressValueElement> create(Document&);
     void setWidthPercentage(double);
+
+private:
+    ProgressValueElement(Document&);
 };
 
-inline PassRefPtr<ProgressValueElement> ProgressValueElement::create(Document* document)
+inline PassRefPtr<ProgressValueElement> ProgressValueElement::create(Document& document)
 {
     return adoptRef(new ProgressValueElement(document));
 }
diff --git a/Source/core/html/shadow/SliderThumbElement.cpp b/Source/core/html/shadow/SliderThumbElement.cpp
index eea1a7a..14165d4 100644
--- a/Source/core/html/shadow/SliderThumbElement.cpp
+++ b/Source/core/html/shadow/SliderThumbElement.cpp
@@ -73,7 +73,7 @@
 // --------------------------------
 
 RenderSliderThumb::RenderSliderThumb(SliderThumbElement* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
 }
 
@@ -195,13 +195,13 @@
 
 // --------------------------------
 
-inline SliderThumbElement::SliderThumbElement(Document* document)
+inline SliderThumbElement::SliderThumbElement(Document& document)
     : HTMLDivElement(HTMLNames::divTag, document)
     , m_inDragMode(false)
 {
 }
 
-PassRefPtr<SliderThumbElement> SliderThumbElement::create(Document* document)
+PassRefPtr<SliderThumbElement> SliderThumbElement::create(Document& document)
 {
     RefPtr<SliderThumbElement> element = adoptRef(new SliderThumbElement(document));
     element->setAttribute(idAttr, ShadowElementNames::sliderThumb());
@@ -256,7 +256,6 @@
     if (!input->renderer() || !renderBox() || !trackElement->renderBox())
         return;
 
-    input->setTextAsOfLastFormControlChangeEvent(input->value());
     LayoutPoint offset = roundedLayoutPoint(input->renderer()->absoluteToLocal(point, UseTransforms));
     bool isVertical = hasVerticalAppearance(input.get());
     bool isLeftToRightDirection = renderBox()->style()->isLeftToRightDirection();
@@ -312,7 +311,7 @@
 
 void SliderThumbElement::startDragging()
 {
-    if (Frame* frame = document()->frame()) {
+    if (Frame* frame = document().frame()) {
         frame->eventHandler()->setCapturingMouseEventsNode(this);
         m_inDragMode = true;
     }
@@ -323,7 +322,7 @@
     if (!m_inDragMode)
         return;
 
-    if (Frame* frame = document()->frame())
+    if (Frame* frame = document().frame())
         frame->eventHandler()->setCapturingMouseEventsNode(0);
     m_inDragMode = false;
     if (renderer())
@@ -389,7 +388,7 @@
 void SliderThumbElement::detach(const AttachContext& context)
 {
     if (m_inDragMode) {
-        if (Frame* frame = document()->frame())
+        if (Frame* frame = document().frame())
             frame->eventHandler()->setCapturingMouseEventsNode(0);
     }
     HTMLDivElement::detach(context);
@@ -436,12 +435,12 @@
 
 // --------------------------------
 
-inline SliderContainerElement::SliderContainerElement(Document* document)
+inline SliderContainerElement::SliderContainerElement(Document& document)
     : HTMLDivElement(HTMLNames::divTag, document)
 {
 }
 
-PassRefPtr<SliderContainerElement> SliderContainerElement::create(Document* document)
+PassRefPtr<SliderContainerElement> SliderContainerElement::create(Document& document)
 {
     return adoptRef(new SliderContainerElement(document));
 }
diff --git a/Source/core/html/shadow/SliderThumbElement.h b/Source/core/html/shadow/SliderThumbElement.h
index 9e8bc8b..1c625dd 100644
--- a/Source/core/html/shadow/SliderThumbElement.h
+++ b/Source/core/html/shadow/SliderThumbElement.h
@@ -34,7 +34,7 @@
 
 #include "HTMLNames.h"
 #include "core/html/HTMLDivElement.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "wtf/Forward.h"
 
 namespace WebCore {
@@ -46,7 +46,7 @@
 
 class SliderThumbElement FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<SliderThumbElement> create(Document*);
+    static PassRefPtr<SliderThumbElement> create(Document&);
 
     void setPositionFromValue();
 
@@ -60,7 +60,7 @@
     void setPositionFromPoint(const LayoutPoint&);
 
 private:
-    SliderThumbElement(Document*);
+    SliderThumbElement(Document&);
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren();
     virtual bool isDisabledFormControl() const OVERRIDE;
@@ -86,23 +86,24 @@
 
 // --------------------------------
 
-class RenderSliderThumb FINAL : public RenderBlock {
+class RenderSliderThumb FINAL : public RenderBlockFlow {
 public:
     RenderSliderThumb(SliderThumbElement*);
     void updateAppearance(RenderStyle* parentStyle);
 
 private:
     virtual bool isSliderThumb() const;
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 };
 
 // --------------------------------
 
 class SliderContainerElement FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<SliderContainerElement> create(Document*);
+    static PassRefPtr<SliderContainerElement> create(Document&);
 
 private:
-    SliderContainerElement(Document*);
+    SliderContainerElement(Document&);
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual const AtomicString& part() const;
 };
diff --git a/Source/core/html/shadow/SpinButtonElement.cpp b/Source/core/html/shadow/SpinButtonElement.cpp
index 998f1d4..4521b32 100644
--- a/Source/core/html/shadow/SpinButtonElement.cpp
+++ b/Source/core/html/shadow/SpinButtonElement.cpp
@@ -43,7 +43,7 @@
 
 using namespace HTMLNames;
 
-inline SpinButtonElement::SpinButtonElement(Document* document, SpinButtonOwner& spinButtonOwner)
+inline SpinButtonElement::SpinButtonElement(Document& document, SpinButtonOwner& spinButtonOwner)
     : HTMLDivElement(divTag, document)
     , m_spinButtonOwner(&spinButtonOwner)
     , m_capturing(false)
@@ -53,7 +53,7 @@
 {
 }
 
-PassRefPtr<SpinButtonElement> SpinButtonElement::create(Document* document, SpinButtonOwner& spinButtonOwner)
+PassRefPtr<SpinButtonElement> SpinButtonElement::create(Document& document, SpinButtonOwner& spinButtonOwner)
 {
     RefPtr<SpinButtonElement> element = adoptRef(new SpinButtonElement(document, spinButtonOwner));
     element->setPart(AtomicString("-webkit-inner-spin-button", AtomicString::ConstructFromLiteral));
@@ -116,10 +116,10 @@
     else if (event->type() == eventNames().mousemoveEvent) {
         if (box->pixelSnappedBorderBoxRect().contains(local)) {
             if (!m_capturing) {
-                if (Frame* frame = document()->frame()) {
+                if (Frame* frame = document().frame()) {
                     frame->eventHandler()->setCapturingMouseEventsNode(this);
                     m_capturing = true;
-                    if (Page* page = document()->page())
+                    if (Page* page = document().page())
                         page->chrome().registerPopupOpeningObserver(this);
                 }
             }
@@ -192,10 +192,10 @@
 {
     stopRepeatingTimer();
     if (m_capturing) {
-        if (Frame* frame = document()->frame()) {
+        if (Frame* frame = document().frame()) {
             frame->eventHandler()->setCapturingMouseEventsNode(0);
             m_capturing = false;
-            if (Page* page = document()->page())
+            if (Page* page = document().page())
                 page->chrome().unregisterPopupOpeningObserver(this);
         }
     }
@@ -230,7 +230,7 @@
     // On Mac OS, NSStepper updates the value for the button under the mouse
     // cursor regardless of the button pressed at the beginning. So the
     // following check is not needed for Mac OS.
-#if !OS(DARWIN)
+#if !OS(MACOSX)
     if (m_upDownState != m_pressStartingState)
         return;
 #endif
diff --git a/Source/core/html/shadow/SpinButtonElement.h b/Source/core/html/shadow/SpinButtonElement.h
index 77d031e..715f434 100644
--- a/Source/core/html/shadow/SpinButtonElement.h
+++ b/Source/core/html/shadow/SpinButtonElement.h
@@ -54,7 +54,7 @@
     // The owner of SpinButtonElement must call removeSpinButtonOwner
     // because SpinButtonElement can be outlive SpinButtonOwner
     // implementation, e.g. during event handling.
-    static PassRefPtr<SpinButtonElement> create(Document*, SpinButtonOwner&);
+    static PassRefPtr<SpinButtonElement> create(Document&, SpinButtonOwner&);
     UpDownState upDownState() const { return m_upDownState; }
     virtual void releaseCapture();
     void removeSpinButtonOwner() { m_spinButtonOwner = 0; }
@@ -67,7 +67,7 @@
     void forwardEvent(Event*);
 
 private:
-    SpinButtonElement(Document*, SpinButtonOwner&);
+    SpinButtonElement(Document&, SpinButtonOwner&);
 
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool isSpinButtonElement() const { return true; }
diff --git a/Source/core/html/shadow/TextControlInnerElements.cpp b/Source/core/html/shadow/TextControlInnerElements.cpp
index 7dc3244..fa833fe 100644
--- a/Source/core/html/shadow/TextControlInnerElements.cpp
+++ b/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -48,12 +48,12 @@
 
 using namespace HTMLNames;
 
-TextControlInnerContainer::TextControlInnerContainer(Document* document)
+TextControlInnerContainer::TextControlInnerContainer(Document& document)
     : HTMLDivElement(divTag, document)
 {
 }
 
-PassRefPtr<TextControlInnerContainer> TextControlInnerContainer::create(Document* document)
+PassRefPtr<TextControlInnerContainer> TextControlInnerContainer::create(Document& document)
 {
     return adoptRef(new TextControlInnerContainer(document));
 }
@@ -63,13 +63,13 @@
     return new RenderTextControlInnerContainer(this);
 }
 
-TextControlInnerElement::TextControlInnerElement(Document* document)
+TextControlInnerElement::TextControlInnerElement(Document& document)
     : HTMLDivElement(divTag, document)
 {
     setHasCustomStyleCallbacks();
 }
 
-PassRefPtr<TextControlInnerElement> TextControlInnerElement::create(Document* document)
+PassRefPtr<TextControlInnerElement> TextControlInnerElement::create(Document& document)
 {
     return adoptRef(new TextControlInnerElement(document));
 }
@@ -97,13 +97,13 @@
 
 // ---------------------------
 
-inline TextControlInnerTextElement::TextControlInnerTextElement(Document* document)
+inline TextControlInnerTextElement::TextControlInnerTextElement(Document& document)
     : HTMLDivElement(divTag, document)
 {
     setHasCustomStyleCallbacks();
 }
 
-PassRefPtr<TextControlInnerTextElement> TextControlInnerTextElement::create(Document* document)
+PassRefPtr<TextControlInnerTextElement> TextControlInnerTextElement::create(Document& document)
 {
     return adoptRef(new TextControlInnerTextElement(document));
 }
@@ -143,12 +143,12 @@
 
 // ----------------------------
 
-inline SearchFieldDecorationElement::SearchFieldDecorationElement(Document* document)
+inline SearchFieldDecorationElement::SearchFieldDecorationElement(Document& document)
     : HTMLDivElement(divTag, document)
 {
 }
 
-PassRefPtr<SearchFieldDecorationElement> SearchFieldDecorationElement::create(Document* document)
+PassRefPtr<SearchFieldDecorationElement> SearchFieldDecorationElement::create(Document& document)
 {
     RefPtr<SearchFieldDecorationElement> element = adoptRef(new SearchFieldDecorationElement(document));
     element->setAttribute(idAttr, ShadowElementNames::searchDecoration());
@@ -191,13 +191,13 @@
 
 // ----------------------------
 
-inline SearchFieldCancelButtonElement::SearchFieldCancelButtonElement(Document* document)
+inline SearchFieldCancelButtonElement::SearchFieldCancelButtonElement(Document& document)
     : HTMLDivElement(divTag, document)
     , m_capturing(false)
 {
 }
 
-PassRefPtr<SearchFieldCancelButtonElement> SearchFieldCancelButtonElement::create(Document* document)
+PassRefPtr<SearchFieldCancelButtonElement> SearchFieldCancelButtonElement::create(Document& document)
 {
     RefPtr<SearchFieldCancelButtonElement> element = adoptRef(new SearchFieldCancelButtonElement(document));
     element->setPart(AtomicString("-webkit-search-cancel-button", AtomicString::ConstructFromLiteral));
@@ -208,7 +208,7 @@
 void SearchFieldCancelButtonElement::detach(const AttachContext& context)
 {
     if (m_capturing) {
-        if (Frame* frame = document()->frame())
+        if (Frame* frame = document().frame())
             frame->eventHandler()->setCapturingMouseEventsNode(0);
     }
     HTMLDivElement::detach(context);
@@ -227,7 +227,7 @@
 
     if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (renderer() && renderer()->visibleToHitTesting()) {
-            if (Frame* frame = document()->frame()) {
+            if (Frame* frame = document().frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(this);
                 m_capturing = true;
             }
@@ -238,7 +238,7 @@
     }
     if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (m_capturing) {
-            if (Frame* frame = document()->frame()) {
+            if (Frame* frame = document().frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(0);
                 m_capturing = false;
             }
@@ -268,7 +268,7 @@
 
 #if ENABLE(INPUT_SPEECH)
 
-inline InputFieldSpeechButtonElement::InputFieldSpeechButtonElement(Document* document)
+inline InputFieldSpeechButtonElement::InputFieldSpeechButtonElement(Document& document)
     : HTMLDivElement(divTag, document)
     , m_capturing(false)
     , m_state(Idle)
@@ -286,7 +286,7 @@
     }
 }
 
-PassRefPtr<InputFieldSpeechButtonElement> InputFieldSpeechButtonElement::create(Document* document)
+PassRefPtr<InputFieldSpeechButtonElement> InputFieldSpeechButtonElement::create(Document& document)
 {
     RefPtr<InputFieldSpeechButtonElement> element = adoptRef(new InputFieldSpeechButtonElement(document));
     element->setPart(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
@@ -316,7 +316,7 @@
     // On mouse down, select the text and set focus.
     if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (renderer() && renderer()->visibleToHitTesting()) {
-            if (Frame* frame = document()->frame()) {
+            if (Frame* frame = document().frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(this);
                 m_capturing = true;
             }
@@ -329,7 +329,7 @@
     // On mouse up, release capture cleanly.
     if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (m_capturing && renderer() && renderer()->visibleToHitTesting()) {
-            if (Frame* frame = document()->frame()) {
+            if (Frame* frame = document().frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(0);
                 m_capturing = false;
             }
@@ -374,7 +374,7 @@
 
 SpeechInput* InputFieldSpeechButtonElement::speechInput()
 {
-    return SpeechInput::from(document()->page());
+    return SpeechInput::from(document().page());
 }
 
 void InputFieldSpeechButtonElement::didCompleteRecording(int)
@@ -399,12 +399,12 @@
         return;
 
     RefPtr<InputFieldSpeechButtonElement> holdRefButton(this);
-    if (document() && document()->domWindow()) {
+    if (document().domWindow()) {
         // Call selectionChanged, causing the element to cache the selection,
         // so that the text event inserts the text in this element even if
         // focus has moved away from it.
         input->selectionChanged(false);
-        input->dispatchEvent(TextEvent::create(document()->domWindow(), results.isEmpty() ? "" : results[0]->utterance(), TextEventInputOther));
+        input->dispatchEvent(TextEvent::create(document().domWindow(), results.isEmpty() ? "" : results[0]->utterance(), TextEventInputOther));
     }
 
     // This event is sent after the text event so the website can perform actions using the input field content immediately.
@@ -420,7 +420,7 @@
 void InputFieldSpeechButtonElement::attach(const AttachContext& context)
 {
     ASSERT(!m_listenerId);
-    if (SpeechInput* input = SpeechInput::from(document()->page()))
+    if (SpeechInput* input = SpeechInput::from(document().page()))
         m_listenerId = input->registerListener(this);
     HTMLDivElement::attach(context);
 }
@@ -428,7 +428,7 @@
 void InputFieldSpeechButtonElement::detach(const AttachContext& context)
 {
     if (m_capturing) {
-        if (Frame* frame = document()->frame())
+        if (Frame* frame = document().frame())
             frame->eventHandler()->setCapturingMouseEventsNode(0);
     }
 
@@ -450,8 +450,8 @@
     RefPtr<HTMLInputElement> input = toHTMLInputElement(shadowHost());
     AtomicString language = input->computeInheritedLanguage();
     String grammar = input->getAttribute(webkitgrammarAttr);
-    IntRect rect = document()->view()->contentsToRootView(pixelSnappedBoundingBox());
-    if (speechInput()->startRecognition(m_listenerId, rect, language, grammar, document()->securityOrigin()))
+    IntRect rect = document().view()->contentsToRootView(pixelSnappedBoundingBox());
+    if (speechInput()->startRecognition(m_listenerId, rect, language, grammar, document().securityOrigin()))
         setState(Recording);
 }
 
diff --git a/Source/core/html/shadow/TextControlInnerElements.h b/Source/core/html/shadow/TextControlInnerElements.h
index 955b8f2..1966330 100644
--- a/Source/core/html/shadow/TextControlInnerElements.h
+++ b/Source/core/html/shadow/TextControlInnerElements.h
@@ -37,18 +37,18 @@
 
 class TextControlInnerContainer FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<TextControlInnerContainer> create(Document*);
+    static PassRefPtr<TextControlInnerContainer> create(Document&);
 protected:
-    TextControlInnerContainer(Document*);
+    TextControlInnerContainer(Document&);
     virtual RenderObject* createRenderer(RenderStyle*);
 };
 
 class TextControlInnerElement FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<TextControlInnerElement> create(Document*);
+    static PassRefPtr<TextControlInnerElement> create(Document&);
 
 protected:
-    TextControlInnerElement(Document*);
+    TextControlInnerElement(Document&);
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
 
 private:
@@ -57,12 +57,12 @@
 
 class TextControlInnerTextElement FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<TextControlInnerTextElement> create(Document*);
+    static PassRefPtr<TextControlInnerTextElement> create(Document&);
 
     virtual void defaultEventHandler(Event*);
 
 private:
-    TextControlInnerTextElement(Document*);
+    TextControlInnerTextElement(Document&);
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
     virtual bool supportsFocus() const OVERRIDE { return false; }
@@ -70,26 +70,26 @@
 
 class SearchFieldDecorationElement FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<SearchFieldDecorationElement> create(Document*);
+    static PassRefPtr<SearchFieldDecorationElement> create(Document&);
 
     virtual void defaultEventHandler(Event*);
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
-    SearchFieldDecorationElement(Document*);
+    SearchFieldDecorationElement(Document&);
     virtual const AtomicString& part() const OVERRIDE;
     virtual bool supportsFocus() const OVERRIDE { return false; }
 };
 
 class SearchFieldCancelButtonElement FINAL : public HTMLDivElement {
 public:
-    static PassRefPtr<SearchFieldCancelButtonElement> create(Document*);
+    static PassRefPtr<SearchFieldCancelButtonElement> create(Document&);
 
     virtual void defaultEventHandler(Event*);
     virtual bool willRespondToMouseClickEvents() OVERRIDE;
 
 private:
-    SearchFieldCancelButtonElement(Document*);
+    SearchFieldCancelButtonElement(Document&);
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool supportsFocus() const OVERRIDE { return false; }
 
@@ -108,7 +108,7 @@
         Recognizing,
     };
 
-    static PassRefPtr<InputFieldSpeechButtonElement> create(Document*);
+    static PassRefPtr<InputFieldSpeechButtonElement> create(Document&);
     virtual ~InputFieldSpeechButtonElement();
 
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
@@ -125,7 +125,7 @@
     void setRecognitionResult(int, const SpeechInputResultArray&);
 
 private:
-    InputFieldSpeechButtonElement(Document*);
+    InputFieldSpeechButtonElement(Document&);
     SpeechInput* speechInput();
     void setState(SpeechInputState state);
     virtual bool isMouseFocusable() const { return false; }
diff --git a/Source/core/html/track/InbandTextTrack.cpp b/Source/core/html/track/InbandTextTrack.cpp
index b1076d4..95f629d 100644
--- a/Source/core/html/track/InbandTextTrack.cpp
+++ b/Source/core/html/track/InbandTextTrack.cpp
@@ -156,9 +156,9 @@
         cue->setLine(lround(cueData->line()), IGNORE_EXCEPTION);
     if (cueData->size() > 0)
         cue->setSize(lround(cueData->size()), IGNORE_EXCEPTION);
-    if (cueData->backgroundColor().alpha())
+    if (cueData->backgroundColor().isValid())
         cue->setBackgroundColor(cueData->backgroundColor().rgb());
-    if (cueData->foregroundColor().alpha())
+    if (cueData->foregroundColor().isValid())
         cue->setForegroundColor(cueData->foregroundColor().rgb());
 
     if (cueData->align() == GenericCueData::Start)
diff --git a/Source/core/html/track/LoadableTextTrack.cpp b/Source/core/html/track/LoadableTextTrack.cpp
index 51c9722..9ccb64b 100644
--- a/Source/core/html/track/LoadableTextTrack.cpp
+++ b/Source/core/html/track/LoadableTextTrack.cpp
@@ -34,7 +34,7 @@
 namespace WebCore {
 
 LoadableTextTrack::LoadableTextTrack(HTMLTrackElement* track, const String& kind, const String& label, const String& language)
-    : TextTrack(track->document(), track, kind, label, language, TrackElement)
+    : TextTrack(&track->document(), track, kind, label, language, TrackElement)
     , m_trackElement(track)
     , m_loadTimer(this, &LoadableTextTrack::loadTimerFired)
     , m_isDefault(false)
@@ -89,7 +89,7 @@
     // 4. Download: If URL is not the empty string, perform a potentially CORS-enabled fetch of URL, with the
     // mode being the state of the media element's crossorigin content attribute, the origin being the
     // origin of the media element's Document, and the default origin behaviour set to fail.
-    m_loader = TextTrackLoader::create(this, static_cast<ScriptExecutionContext*>(m_trackElement->document()));
+    m_loader = TextTrackLoader::create(this, static_cast<ScriptExecutionContext*>(&m_trackElement->document()));
     if (!m_loader->load(m_url, m_trackElement->mediaElementCrossOriginAttribute()))
         m_trackElement->didCompleteLoad(this, HTMLTrackElement::Failure);
 }
diff --git a/Source/core/html/track/TextTrack.idl b/Source/core/html/track/TextTrack.idl
index 36e19d9..1067901 100644
--- a/Source/core/html/track/TextTrack.idl
+++ b/Source/core/html/track/TextTrack.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=videoTrack
+    EnabledAtRuntime=VideoTrack
 ] interface TextTrack : EventTarget {
     readonly attribute DOMString kind;
     readonly attribute DOMString label;
diff --git a/Source/core/html/track/TextTrackCue.cpp b/Source/core/html/track/TextTrackCue.cpp
index 1625698..167f032 100644
--- a/Source/core/html/track/TextTrackCue.cpp
+++ b/Source/core/html/track/TextTrackCue.cpp
@@ -92,7 +92,7 @@
 
 // ----------------------------
 
-TextTrackCueBox::TextTrackCueBox(Document* document, TextTrackCue* cue)
+TextTrackCueBox::TextTrackCueBox(Document& document, TextTrackCue* cue)
     : HTMLDivElement(divTag, document)
     , m_cue(cue)
 {
@@ -204,7 +204,7 @@
     , m_isActive(false)
     , m_pauseOnExit(false)
     , m_snapToLines(true)
-    , m_cueBackgroundBox(HTMLDivElement::create(toDocument(context)))
+    , m_cueBackgroundBox(HTMLDivElement::create(*toDocument(context)))
     , m_displayTreeShouldChange(true)
     , m_displayDirection(CSSValueLtr)
 {
@@ -228,7 +228,8 @@
 
 PassRefPtr<TextTrackCueBox> TextTrackCue::createDisplayTree()
 {
-    return TextTrackCueBox::create(ownerDocument(), this);
+    ASSERT(ownerDocument());
+    return TextTrackCueBox::create(*ownerDocument(), this);
 }
 
 PassRefPtr<TextTrackCueBox> TextTrackCue::displayTreeInternal()
@@ -515,7 +516,7 @@
 PassRefPtr<DocumentFragment> TextTrackCue::getCueAsHTML()
 {
     createWebVTTNodeTree();
-    RefPtr<DocumentFragment> clonedFragment = DocumentFragment::create(ownerDocument());
+    RefPtr<DocumentFragment> clonedFragment = DocumentFragment::create(*ownerDocument());
     copyWebVTTNodeToDOMTree(m_webVTTNodeTree.get(), clonedFragment.get());
     return clonedFragment.release();
 }
@@ -524,7 +525,7 @@
 {
     RefPtr<DocumentFragment> clonedFragment;
     createWebVTTNodeTree();
-    clonedFragment = DocumentFragment::create(ownerDocument());
+    clonedFragment = DocumentFragment::create(*ownerDocument());
     m_webVTTNodeTree->cloneChildNodes(clonedFragment.get());
     return clonedFragment.release();
 }
diff --git a/Source/core/html/track/TextTrackCue.h b/Source/core/html/track/TextTrackCue.h
index 82efa89..61fd450 100644
--- a/Source/core/html/track/TextTrackCue.h
+++ b/Source/core/html/track/TextTrackCue.h
@@ -49,7 +49,7 @@
 
 class TextTrackCueBox : public HTMLDivElement {
 public:
-    static PassRefPtr<TextTrackCueBox> create(Document* document, TextTrackCue* cue)
+    static PassRefPtr<TextTrackCueBox> create(Document& document, TextTrackCue* cue)
     {
         return adoptRef(new TextTrackCueBox(document, cue));
     }
@@ -60,7 +60,7 @@
     static const AtomicString& textTrackCueBoxShadowPseudoId();
 
 protected:
-    TextTrackCueBox(Document*, TextTrackCue*);
+    TextTrackCueBox(Document&, TextTrackCue*);
 
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
diff --git a/Source/core/html/track/TextTrackCue.idl b/Source/core/html/track/TextTrackCue.idl
index d379587..e64d8a3 100644
--- a/Source/core/html/track/TextTrackCue.idl
+++ b/Source/core/html/track/TextTrackCue.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=videoTrack,
+    EnabledAtRuntime=VideoTrack,
     Constructor(double startTime, double endTime, DOMString text),
     ConstructorCallWith=ScriptExecutionContext
 ] interface TextTrackCue : EventTarget {
diff --git a/Source/core/html/track/TextTrackCueGeneric.cpp b/Source/core/html/track/TextTrackCueGeneric.cpp
index a7d4cbe..b80e67b 100644
--- a/Source/core/html/track/TextTrackCueGeneric.cpp
+++ b/Source/core/html/track/TextTrackCueGeneric.cpp
@@ -36,7 +36,7 @@
 
 class TextTrackCueGenericBoxElement FINAL : public TextTrackCueBox {
 public:
-    static PassRefPtr<TextTrackCueGenericBoxElement> create(Document* document, TextTrackCueGeneric* cue)
+    static PassRefPtr<TextTrackCueGenericBoxElement> create(Document& document, TextTrackCueGeneric* cue)
     {
         return adoptRef(new TextTrackCueGenericBoxElement(document, cue));
     }
@@ -44,10 +44,10 @@
     virtual void applyCSSProperties(const IntSize&) OVERRIDE;
 
 private:
-    TextTrackCueGenericBoxElement(Document*, TextTrackCue*);
+    TextTrackCueGenericBoxElement(Document&, TextTrackCue*);
 };
 
-TextTrackCueGenericBoxElement::TextTrackCueGenericBoxElement(Document* document, TextTrackCue* cue)
+TextTrackCueGenericBoxElement::TextTrackCueGenericBoxElement(Document& document, TextTrackCue* cue)
     : TextTrackCueBox(document, cue)
 {
 }
@@ -73,10 +73,10 @@
             setInlineStyleProperty(CSSPropertyHeight, size,  CSSPrimitiveValue::CSS_PERCENTAGE);
     }
 
-    if (cue->foregroundColor().alpha())
+    if (cue->foregroundColor().isValid())
         setInlineStyleProperty(CSSPropertyColor, cue->foregroundColor().serialized());
 
-    if (cue->backgroundColor().alpha())
+    if (cue->backgroundColor().isValid())
         cue->element()->setInlineStyleProperty(CSSPropertyBackgroundColor, cue->backgroundColor().serialized());
 
     if (cue->getWritingDirection() == TextTrackCue::Horizontal)
@@ -113,7 +113,8 @@
 
 PassRefPtr<TextTrackCueBox> TextTrackCueGeneric::createDisplayTree()
 {
-    return TextTrackCueGenericBoxElement::create(ownerDocument(), this);
+    ASSERT(ownerDocument());
+    return TextTrackCueGenericBoxElement::create(*ownerDocument(), this);
 }
 
 void TextTrackCueGeneric::setLine(int line, ExceptionState& es)
diff --git a/Source/core/html/track/TextTrackCueGeneric.h b/Source/core/html/track/TextTrackCueGeneric.h
index 9034222..a62611a 100644
--- a/Source/core/html/track/TextTrackCueGeneric.h
+++ b/Source/core/html/track/TextTrackCueGeneric.h
@@ -61,10 +61,11 @@
     void setFontName(String name) { m_fontName = name; }
 
     Color foregroundColor() const { return m_foregroundColor; }
-    void setForegroundColor(Color color) { m_foregroundColor = color; }
+
+    void setForegroundColor(RGBA32 color) { m_foregroundColor.setRGB(color); }
 
     Color backgroundColor() const { return m_backgroundColor; }
-    void setBackgroundColor(Color color) { m_backgroundColor = color; }
+    void setBackgroundColor(RGBA32 color) { m_backgroundColor.setRGB(color); }
 
     virtual void videoSizeDidChange(const IntSize&);
 
diff --git a/Source/core/html/track/TextTrackCueList.idl b/Source/core/html/track/TextTrackCueList.idl
index 155d419..4f28935 100644
--- a/Source/core/html/track/TextTrackCueList.idl
+++ b/Source/core/html/track/TextTrackCueList.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=videoTrack
+    EnabledAtRuntime=VideoTrack
 ] interface TextTrackCueList {
     readonly attribute unsigned long length;
     getter TextTrackCue item(unsigned long index);
diff --git a/Source/core/html/track/TextTrackList.idl b/Source/core/html/track/TextTrackList.idl
index d52c548..bdfcc74 100644
--- a/Source/core/html/track/TextTrackList.idl
+++ b/Source/core/html/track/TextTrackList.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=videoTrack,
+    EnabledAtRuntime=VideoTrack,
     GenerateIsReachable=owner
 ] interface TextTrackList : EventTarget {
     readonly attribute unsigned long length;
diff --git a/Source/core/html/track/TextTrackRegion.cpp b/Source/core/html/track/TextTrackRegion.cpp
index cc59fc8..d5c30b3 100644
--- a/Source/core/html/track/TextTrackRegion.cpp
+++ b/Source/core/html/track/TextTrackRegion.cpp
@@ -37,7 +37,7 @@
 #include "bindings/v8/ExceptionState.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/ClientRect.h"
-#include "core/html/DOMTokenList.h"
+#include "core/dom/DOMTokenList.h"
 #include "core/html/HTMLDivElement.h"
 #include "core/html/track/WebVTTParser.h"
 #include "core/platform/Logging.h"
diff --git a/Source/core/html/track/TextTrackRegion.idl b/Source/core/html/track/TextTrackRegion.idl
index 104abba..62ca08e 100644
--- a/Source/core/html/track/TextTrackRegion.idl
+++ b/Source/core/html/track/TextTrackRegion.idl
@@ -26,7 +26,7 @@
 [
     Conditional=WEBVTT_REGIONS,
     Constructor(),
-    EnabledAtRuntime=videoTrack,
+    EnabledAtRuntime=VideoTrack,
     ConstructorCallWith=ScriptExecutionContext
 ] interface TextTrackRegion {
     readonly attribute TextTrack track;
diff --git a/Source/core/html/track/TextTrackRegionList.idl b/Source/core/html/track/TextTrackRegionList.idl
index ad5611f..844cd9d 100644
--- a/Source/core/html/track/TextTrackRegionList.idl
+++ b/Source/core/html/track/TextTrackRegionList.idl
@@ -26,7 +26,7 @@
 [
     NoInterfaceObject,
     Conditional=WEBVTT_REGIONS,
-    EnabledAtRuntime=videoTrack
+    EnabledAtRuntime=VideoTrack
 ] interface TextTrackRegionList {
     readonly attribute unsigned long length;
     getter TextTrackRegion item(unsigned long index);
diff --git a/Source/core/html/track/TrackEvent.idl b/Source/core/html/track/TrackEvent.idl
index 0b1a0e9..c1dc03e 100644
--- a/Source/core/html/track/TrackEvent.idl
+++ b/Source/core/html/track/TrackEvent.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    EnabledAtRuntime=videoTrack,
+    EnabledAtRuntime=VideoTrack,
     ConstructorTemplate=Event
 ] interface TrackEvent : Event {
     [InitializedByEventConstructor, CustomGetter] readonly attribute object track;
diff --git a/Source/core/html/track/WebVTTElement.cpp b/Source/core/html/track/WebVTTElement.cpp
index 009aaa7..c988de0 100644
--- a/Source/core/html/track/WebVTTElement.cpp
+++ b/Source/core/html/track/WebVTTElement.cpp
@@ -78,7 +78,7 @@
 
 PassRefPtr<Element> WebVTTElement::cloneElementWithoutAttributesAndChildren()
 {
-    RefPtr<WebVTTElement> clone = create(static_cast<WebVTTNodeType>(m_webVTTNodeType), document());
+    RefPtr<WebVTTElement> clone = create(static_cast<WebVTTNodeType>(m_webVTTNodeType), &document());
     clone->setLanguage(m_language);
     return clone;
 }
diff --git a/Source/core/html/track/WebVTTParser.cpp b/Source/core/html/track/WebVTTParser.cpp
index 4b2dfc2..27507c4 100644
--- a/Source/core/html/track/WebVTTParser.cpp
+++ b/Source/core/html/track/WebVTTParser.cpp
@@ -330,11 +330,12 @@
 
     ASSERT(m_scriptExecutionContext->isDocument());
     Document* document = toDocument(m_scriptExecutionContext);
+    ASSERT(document);
 
-    RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
+    RefPtr<DocumentFragment> fragment = DocumentFragment::create(*document);
 
     if (!text.length()) {
-        fragment->parserAppendChild(Text::create(document, ""));
+        fragment->parserAppendChild(Text::create(*document, ""));
         return fragment;
     }
 
@@ -345,7 +346,7 @@
     m_languageStack.clear();
     SegmentedString content(text);
     while (m_tokenizer->nextToken(content, m_token))
-        constructTreeFromToken(document);
+        constructTreeFromToken(*document);
 
     return fragment.release();
 }
@@ -483,7 +484,7 @@
     return WebVTTNodeTypeNone;
 }
 
-void WebVTTParser::constructTreeFromToken(Document* document)
+void WebVTTParser::constructTreeFromToken(Document& document)
 {
     QualifiedName tagName(nullAtom, AtomicString(m_token.name()), xhtmlNamespaceURI);
 
@@ -500,7 +501,7 @@
         RefPtr<WebVTTElement> child;
         WebVTTNodeType nodeType = tokenToNodeType(m_token);
         if (nodeType != WebVTTNodeTypeNone)
-            child = WebVTTElement::create(nodeType, document);
+            child = WebVTTElement::create(nodeType, &document);
         if (child) {
             if (m_token.classes().size() > 0)
                 child->setAttribute(classAttr, AtomicString(m_token.classes()));
diff --git a/Source/core/html/track/WebVTTParser.h b/Source/core/html/track/WebVTTParser.h
index 7d4f08f..c717e57 100644
--- a/Source/core/html/track/WebVTTParser.h
+++ b/Source/core/html/track/WebVTTParser.h
@@ -143,7 +143,7 @@
     static void skipLineTerminator(const char* data, unsigned length, unsigned*);
     static String collectNextLine(const char* data, unsigned length, unsigned*);
 
-    void constructTreeFromToken(Document*);
+    void constructTreeFromToken(Document&);
 
     String m_currentHeaderName;
     String m_currentHeaderValue;
diff --git a/Source/core/injected_canvas_script_source.target.darwin-arm.mk b/Source/core/injected_canvas_script_source.target.darwin-arm.mk
index 1e31c52..12a7eb8 100644
--- a/Source/core/injected_canvas_script_source.target.darwin-arm.mk
+++ b/Source/core/injected_canvas_script_source.target.darwin-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.darwin-mips.mk b/Source/core/injected_canvas_script_source.target.darwin-mips.mk
index 1e31c52..12a7eb8 100644
--- a/Source/core/injected_canvas_script_source.target.darwin-mips.mk
+++ b/Source/core/injected_canvas_script_source.target.darwin-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.darwin-x86.mk b/Source/core/injected_canvas_script_source.target.darwin-x86.mk
index 1e31c52..12a7eb8 100644
--- a/Source/core/injected_canvas_script_source.target.darwin-x86.mk
+++ b/Source/core/injected_canvas_script_source.target.darwin-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.linux-arm.mk b/Source/core/injected_canvas_script_source.target.linux-arm.mk
index 1e31c52..12a7eb8 100644
--- a/Source/core/injected_canvas_script_source.target.linux-arm.mk
+++ b/Source/core/injected_canvas_script_source.target.linux-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.linux-mips.mk b/Source/core/injected_canvas_script_source.target.linux-mips.mk
index 1e31c52..12a7eb8 100644
--- a/Source/core/injected_canvas_script_source.target.linux-mips.mk
+++ b/Source/core/injected_canvas_script_source.target.linux-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_canvas_script_source.target.linux-x86.mk b/Source/core/injected_canvas_script_source.target.linux-x86.mk
index 1e31c52..12a7eb8 100644
--- a/Source/core/injected_canvas_script_source.target.linux-x86.mk
+++ b/Source/core/injected_canvas_script_source.target.linux-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h from inspector/InjectedScriptCanvasModuleSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptCanvasModuleSource_js inspector/InjectedScriptCanvasModuleSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptCanvasModuleSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.darwin-arm.mk b/Source/core/injected_script_source.target.darwin-arm.mk
index e10dc02..4313399 100644
--- a/Source/core/injected_script_source.target.darwin-arm.mk
+++ b/Source/core/injected_script_source.target.darwin-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.darwin-mips.mk b/Source/core/injected_script_source.target.darwin-mips.mk
index e10dc02..4313399 100644
--- a/Source/core/injected_script_source.target.darwin-mips.mk
+++ b/Source/core/injected_script_source.target.darwin-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.darwin-x86.mk b/Source/core/injected_script_source.target.darwin-x86.mk
index e10dc02..4313399 100644
--- a/Source/core/injected_script_source.target.darwin-x86.mk
+++ b/Source/core/injected_script_source.target.darwin-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.linux-arm.mk b/Source/core/injected_script_source.target.linux-arm.mk
index e10dc02..4313399 100644
--- a/Source/core/injected_script_source.target.linux-arm.mk
+++ b/Source/core/injected_script_source.target.linux-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.linux-mips.mk b/Source/core/injected_script_source.target.linux-mips.mk
index e10dc02..4313399 100644
--- a/Source/core/injected_script_source.target.linux-mips.mk
+++ b/Source/core/injected_script_source.target.linux-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/injected_script_source.target.linux-x86.mk b/Source/core/injected_script_source.target.linux-x86.mk
index e10dc02..4313399 100644
--- a/Source/core/injected_script_source.target.linux-x86.mk
+++ b/Source/core/injected_script_source.target.linux-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h from inspector/InjectedScriptSource.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InjectedScriptSource_js inspector/InjectedScriptSource.js "$(gyp_shared_intermediate_dir)/blink/InjectedScriptSource.h"
 
 
 
diff --git a/Source/core/inspector/CodeGeneratorInstrumentation.py b/Source/core/inspector/CodeGeneratorInstrumentation.py
index 5cfe1f9..ce639eb 100644
--- a/Source/core/inspector/CodeGeneratorInstrumentation.py
+++ b/Source/core/inspector/CodeGeneratorInstrumentation.py
@@ -261,7 +261,6 @@
             if not "Keep" in self.params_impl[0].options:
                 self.params_impl = self.params_impl[1:]
             self.params_impl = [Parameter("InstrumentingAgents* agents")] + self.params_impl
-            self.agents_selector_class = re.match("(\w*)", self.params[0].type).group(1)
 
         self.agents = filter(lambda option: not "=" in option, self.options)
 
@@ -288,8 +287,7 @@
             condition = ""
             template = template_inline_forward
         else:
-            condition = "InstrumentingAgents* agents = instrumentingAgentsFor%s(%s)" % (
-                self.agents_selector_class, self.params[0].name)
+            condition = "InstrumentingAgents* agents = instrumentingAgentsFor(%s)" % self.params[0].name
 
             if self.returns_value:
                 template = template_inline_returns_value
diff --git a/Source/core/inspector/DOMEditor.cpp b/Source/core/inspector/DOMEditor.cpp
index dd6412e..152d47f 100644
--- a/Source/core/inspector/DOMEditor.cpp
+++ b/Source/core/inspector/DOMEditor.cpp
@@ -221,7 +221,8 @@
     virtual bool perform(ExceptionState& es)
     {
         m_oldHTML = createMarkup(m_node.get());
-        DOMPatchSupport domPatchSupport(m_domEditor.get(), m_node->ownerDocument());
+        ASSERT(m_node->ownerDocument());
+        DOMPatchSupport domPatchSupport(m_domEditor.get(), *m_node->ownerDocument());
         m_newNode = domPatchSupport.patchNode(m_node.get(), m_html, es);
         return !es.hadException();
     }
diff --git a/Source/core/inspector/DOMPatchSupport.cpp b/Source/core/inspector/DOMPatchSupport.cpp
index 2f090c5..7f98678 100644
--- a/Source/core/inspector/DOMPatchSupport.cpp
+++ b/Source/core/inspector/DOMPatchSupport.cpp
@@ -68,7 +68,7 @@
     Vector<OwnPtr<Digest> > m_children;
 };
 
-void DOMPatchSupport::patchDocument(Document* document, const String& markup)
+void DOMPatchSupport::patchDocument(Document& document, const String& markup)
 {
     InspectorHistory history;
     DOMEditor domEditor(&history);
@@ -76,7 +76,7 @@
     patchSupport.patchDocument(markup);
 }
 
-DOMPatchSupport::DOMPatchSupport(DOMEditor* domEditor, Document* document)
+DOMPatchSupport::DOMPatchSupport(DOMEditor* domEditor, Document& document)
     : m_domEditor(domEditor)
     , m_document(document)
 {
@@ -87,31 +87,31 @@
 void DOMPatchSupport::patchDocument(const String& markup)
 {
     RefPtr<Document> newDocument;
-    if (m_document->isHTMLDocument())
+    if (m_document.isHTMLDocument())
         newDocument = HTMLDocument::create();
-    else if (m_document->isXHTMLDocument())
+    else if (m_document.isXHTMLDocument())
         newDocument = HTMLDocument::createXHTML();
-    else if (m_document->isSVGDocument())
+    else if (m_document.isSVGDocument())
         newDocument = Document::create();
 
     ASSERT(newDocument);
-    newDocument->setContextFeatures(m_document->contextFeatures());
+    newDocument->setContextFeatures(m_document.contextFeatures());
     RefPtr<DocumentParser> parser;
-    if (m_document->isHTMLDocument())
-        parser = HTMLDocumentParser::create(static_cast<HTMLDocument*>(newDocument.get()), false);
+    if (m_document.isHTMLDocument())
+        parser = HTMLDocumentParser::create(toHTMLDocument(newDocument.get()), false);
     else
         parser = XMLDocumentParser::create(newDocument.get(), 0);
     parser->insert(markup); // Use insert() so that the parser will not yield.
     parser->finish();
     parser->detach();
 
-    OwnPtr<Digest> oldInfo = createDigest(m_document->documentElement(), 0);
+    OwnPtr<Digest> oldInfo = createDigest(m_document.documentElement(), 0);
     OwnPtr<Digest> newInfo = createDigest(newDocument->documentElement(), &m_unusedNodesMap);
 
     if (!innerPatchNode(oldInfo.get(), newInfo.get(), IGNORE_EXCEPTION)) {
         // Fall back to rewrite.
-        m_document->write(markup);
-        m_document->close();
+        m_document.write(markup);
+        m_document.close();
     }
 }
 
@@ -126,10 +126,10 @@
     Node* previousSibling = node->previousSibling();
     // FIXME: This code should use one of createFragment* in markup.h
     RefPtr<DocumentFragment> fragment = DocumentFragment::create(m_document);
-    if (m_document->isHTMLDocument())
-        fragment->parseHTML(markup, node->parentElement() ? node->parentElement() : m_document->documentElement());
+    if (m_document.isHTMLDocument())
+        fragment->parseHTML(markup, node->parentElement() ? node->parentElement() : m_document.documentElement());
     else
-        fragment->parseXML(markup, node->parentElement() ? node->parentElement() : m_document->documentElement());
+        fragment->parseXML(markup, node->parentElement() ? node->parentElement() : m_document.documentElement());
 
     // Compose the old list.
     ContainerNode* parentNode = node->parentNode();
@@ -502,7 +502,7 @@
 #ifdef DEBUG_DOM_PATCH_SUPPORT
 static String nodeName(Node* node)
 {
-    if (node->document()->isXHTMLDocument())
+    if (node->document().isXHTMLDocument())
          return node->nodeName();
     return node->nodeName().lower();
 }
diff --git a/Source/core/inspector/DOMPatchSupport.h b/Source/core/inspector/DOMPatchSupport.h
index f843c83..4462fb5 100644
--- a/Source/core/inspector/DOMPatchSupport.h
+++ b/Source/core/inspector/DOMPatchSupport.h
@@ -48,9 +48,9 @@
 class DOMPatchSupport {
     WTF_MAKE_NONCOPYABLE(DOMPatchSupport);
 public:
-    static void patchDocument(Document*, const String& markup);
+    static void patchDocument(Document&, const String& markup);
 
-    DOMPatchSupport(DOMEditor*, Document*);
+    DOMPatchSupport(DOMEditor*, Document&);
     virtual ~DOMPatchSupport();
 
     void patchDocument(const String& markup);
@@ -73,7 +73,7 @@
 #endif
 
     DOMEditor* m_domEditor;
-    Document* m_document;
+    Document& m_document;
 
     UnusedNodesMap m_unusedNodesMap;
 };
diff --git a/Source/core/inspector/InjectedScriptSource.js b/Source/core/inspector/InjectedScriptSource.js
index 2a94e5f..59eac83 100644
--- a/Source/core/inspector/InjectedScriptSource.js
+++ b/Source/core/inspector/InjectedScriptSource.js
@@ -162,7 +162,7 @@
             for (var i = 0; i < columns.length; ++i)
                 columnNames.push(String(columns[i]));
         }
-        return this._wrapObject(table, "console", false, true, columnNames);
+        return this._wrapObject(table, "console", false, true, columnNames, true);
     },
 
     /**
@@ -208,13 +208,14 @@
      * @param {boolean=} forceValueType
      * @param {boolean=} generatePreview
      * @param {?Array.<string>=} columnNames
+     * @param {boolean=} isTable
      * @return {!RuntimeAgent.RemoteObject}
      * @suppress {checkTypes}
      */
-    _wrapObject: function(object, objectGroupName, forceValueType, generatePreview, columnNames)
+    _wrapObject: function(object, objectGroupName, forceValueType, generatePreview, columnNames, isTable)
     {
         try {
-            return new InjectedScript.RemoteObject(object, objectGroupName, forceValueType, generatePreview, columnNames);
+            return new InjectedScript.RemoteObject(object, objectGroupName, forceValueType, generatePreview, columnNames, isTable);
         } catch (e) {
             try {
                 var description = injectedScript._describe(e);
@@ -902,8 +903,9 @@
  * @param {boolean=} forceValueType
  * @param {boolean=} generatePreview
  * @param {?Array.<string>=} columnNames
+ * @param {boolean=} isTable
  */
-InjectedScript.RemoteObject = function(object, objectGroupName, forceValueType, generatePreview, columnNames)
+InjectedScript.RemoteObject = function(object, objectGroupName, forceValueType, generatePreview, columnNames, isTable)
 {
     this.type = typeof object;
     if (injectedScript.isPrimitiveValue(object) || object === null || forceValueType) {
@@ -931,7 +933,7 @@
     this.description = injectedScript._describe(object);
 
     if (generatePreview && (this.type === "object" || injectedScript._isHTMLAllCollection(object)))
-        this.preview = this._generatePreview(object, undefined, columnNames);
+        this.preview = this._generatePreview(object, undefined, columnNames, isTable, false);
 }
 
 InjectedScript.RemoteObject.prototype = {
@@ -939,24 +941,25 @@
      * @param {Object} object
      * @param {Array.<string>=} firstLevelKeys
      * @param {?Array.<string>=} secondLevelKeys
+     * @param {boolean=} isTable
+     * @param {boolean=} isTableRow
      * @return {!RuntimeAgent.ObjectPreview} preview
      */
-    _generatePreview: function(object, firstLevelKeys, secondLevelKeys)
+    _generatePreview: function(object, firstLevelKeys, secondLevelKeys, isTable, isTableRow)
     {
         var preview = {};
         preview.lossless = true;
         preview.overflow = false;
         preview.properties = [];
 
-        var isTableRowsRequest = secondLevelKeys === null || secondLevelKeys;
         var firstLevelKeysCount = firstLevelKeys ? firstLevelKeys.length : 0;
 
         var propertiesThreshold = {
-            properties: isTableRowsRequest ? 1000 : Math.max(5, firstLevelKeysCount),
-            indexes: isTableRowsRequest ? 1000 : Math.max(100, firstLevelKeysCount)
+            properties: (isTable || isTableRow) ? 1000 : Math.max(5, firstLevelKeysCount),
+            indexes: (isTable || isTableRow) ? 1000 : Math.max(100, firstLevelKeysCount)
         };
         for (var o = object; injectedScript._isDefined(o); o = o.__proto__)
-            this._generateProtoPreview(/** @type {!Object} */ (o), preview, propertiesThreshold, firstLevelKeys, secondLevelKeys);
+            this._generateProtoPreview(/** @type {!Object} */ (o), preview, propertiesThreshold, firstLevelKeys, secondLevelKeys, isTable);
         return preview;
     },
 
@@ -966,8 +969,9 @@
      * @param {!Object} propertiesThreshold
      * @param {Array.<string>=} firstLevelKeys
      * @param {Array.<string>=} secondLevelKeys
+     * @param {boolean=} isTable
      */
-    _generateProtoPreview: function(object, preview, propertiesThreshold, firstLevelKeys, secondLevelKeys)
+    _generateProtoPreview: function(object, preview, propertiesThreshold, firstLevelKeys, secondLevelKeys, isTable)
     {
         var propertyNames = firstLevelKeys ? firstLevelKeys : Object.keys(object);
         try {
@@ -1009,7 +1013,7 @@
                 }
 
                 if (secondLevelKeys === null || secondLevelKeys) {
-                    var subPreview = this._generatePreview(value, secondLevelKeys || undefined);
+                    var subPreview = this._generatePreview(value, secondLevelKeys || undefined, undefined, false, isTable);
                     var property = { name: name, type: type, valuePreview: subPreview };
                     this._appendPropertyPreview(preview, property, propertiesThreshold);
                     if (!subPreview.lossless)
diff --git a/Source/core/inspector/InspectorCSSAgent.cpp b/Source/core/inspector/InspectorCSSAgent.cpp
index 83f05af..e680633 100644
--- a/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/Source/core/inspector/InspectorCSSAgent.cpp
@@ -1231,7 +1231,7 @@
     if (!node)
         return;
 
-    InspectorStyleSheet* inspectorStyleSheet = viaInspectorStyleSheet(node->document(), true);
+    InspectorStyleSheet* inspectorStyleSheet = viaInspectorStyleSheet(&node->document(), true);
     if (!inspectorStyleSheet) {
         *errorString = "No target stylesheet found";
         return;
@@ -1587,7 +1587,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().styleSheetCollections());
         if (!rule)
             return 0;
     }
diff --git a/Source/core/inspector/InspectorCanvasAgent.cpp b/Source/core/inspector/InspectorCanvasAgent.cpp
index c979295..294770e 100644
--- a/Source/core/inspector/InspectorCanvasAgent.cpp
+++ b/Source/core/inspector/InspectorCanvasAgent.cpp
@@ -53,7 +53,7 @@
 using WebCore::TypeBuilder::Canvas::ResourceState;
 using WebCore::TypeBuilder::Canvas::TraceLog;
 using WebCore::TypeBuilder::Canvas::TraceLogId;
-using WebCore::TypeBuilder::Network::FrameId;
+using WebCore::TypeBuilder::Page::FrameId;
 using WebCore::TypeBuilder::Runtime::RemoteObject;
 
 namespace WebCore {
@@ -272,10 +272,10 @@
 
         virtual void visitNode(Node* node) OVERRIDE
         {
-            if (!node->hasTagName(HTMLNames::canvasTag) || !node->document() || !node->document()->frame())
+            if (!node->hasTagName(HTMLNames::canvasTag) || !node->document().frame())
                 return;
 
-            Frame* frame = node->document()->frame();
+            Frame* frame = node->document().frame();
             if (frame->page() != m_page)
                 return;
 
diff --git a/Source/core/inspector/InspectorCanvasAgent.h b/Source/core/inspector/InspectorCanvasAgent.h
index 9ae3d73..5d30d75 100644
--- a/Source/core/inspector/InspectorCanvasAgent.h
+++ b/Source/core/inspector/InspectorCanvasAgent.h
@@ -77,8 +77,8 @@
     virtual void disable(ErrorString*);
     virtual void dropTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&);
     virtual void hasUninstrumentedCanvases(ErrorString*, bool*);
-    virtual void captureFrame(ErrorString*, const TypeBuilder::Network::FrameId*, TypeBuilder::Canvas::TraceLogId*);
-    virtual void startCapturing(ErrorString*, const TypeBuilder::Network::FrameId*, TypeBuilder::Canvas::TraceLogId*);
+    virtual void captureFrame(ErrorString*, const TypeBuilder::Page::FrameId*, TypeBuilder::Canvas::TraceLogId*);
+    virtual void startCapturing(ErrorString*, const TypeBuilder::Page::FrameId*, TypeBuilder::Canvas::TraceLogId*);
     virtual void stopCapturing(ErrorString*, const TypeBuilder::Canvas::TraceLogId&);
     virtual void getTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, const int*, const int*, RefPtr<TypeBuilder::Canvas::TraceLog>&);
     virtual void replayTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, int, RefPtr<TypeBuilder::Canvas::ResourceState>&, double*);
diff --git a/Source/core/inspector/InspectorConsoleAgent.cpp b/Source/core/inspector/InspectorConsoleAgent.cpp
index 11be2ae..67b9261 100644
--- a/Source/core/inspector/InspectorConsoleAgent.cpp
+++ b/Source/core/inspector/InspectorConsoleAgent.cpp
@@ -270,7 +270,7 @@
     }
 }
 
-void InspectorConsoleAgent::didReceiveResourceResponse(unsigned long requestIdentifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader*)
+void InspectorConsoleAgent::didReceiveResourceResponse(unsigned long requestIdentifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
 {
     if (!loader)
         return;
diff --git a/Source/core/inspector/InspectorDOMAgent.cpp b/Source/core/inspector/InspectorDOMAgent.cpp
index c875c23..80b35fe 100644
--- a/Source/core/inspector/InspectorDOMAgent.cpp
+++ b/Source/core/inspector/InspectorDOMAgent.cpp
@@ -503,7 +503,7 @@
     Document* document = assertDocument(errorString, documentNodeId);
     if (!document)
         return 0;
-    if (nodeToPush->document() != document) {
+    if (&nodeToPush->document() != document) {
         *errorString = "Node is not part of the document with given id";
         return 0;
     }
@@ -676,12 +676,12 @@
         return;
 
     String markup = "<span " + text + "></span>";
-    RefPtr<DocumentFragment> fragment = element->document()->createDocumentFragment();
+    RefPtr<DocumentFragment> fragment = element->document().createDocumentFragment();
 
-    bool shouldIgnoreCase = element->document()->isHTMLDocument() && element->isHTMLElement();
+    bool shouldIgnoreCase = element->document().isHTMLDocument() && element->isHTMLElement();
     // Not all elements can represent the context (i.e. IFRAME), hence using document.body.
-    if (shouldIgnoreCase && element->document()->body())
-        fragment->parseHTML(markup, element->document()->body(), DisallowScriptingContent);
+    if (shouldIgnoreCase && element->document().body())
+        fragment->parseHTML(markup, element->document().body(), DisallowScriptingContent);
     else
         fragment->parseXML(markup, 0, DisallowScriptingContent);
 
@@ -748,7 +748,7 @@
         return;
 
     TrackExceptionState es;
-    RefPtr<Element> newElem = oldNode->document()->createElement(tagName, es);
+    RefPtr<Element> newElem = oldNode->document().createElement(tagName, es);
     if (es.hadException())
         return;
 
@@ -786,7 +786,8 @@
 void InspectorDOMAgent::setOuterHTML(ErrorString* errorString, int nodeId, const String& outerHTML)
 {
     if (!nodeId) {
-        DOMPatchSupport domPatchSupport(m_domEditor.get(), m_document.get());
+        ASSERT(m_document);
+        DOMPatchSupport domPatchSupport(m_domEditor.get(), *m_document.get());
         domPatchSupport.patchDocument(outerHTML);
         return;
     }
@@ -1337,16 +1338,9 @@
     }
 
     RenderObject* renderer = node->renderer();
-    Frame* frame = node->document()->frame();
+    Frame* frame = node->document().frame();
     FrameView* view = frame->view();
 
-    IntRect viewRect = frame->view()->visibleContentRect();
-    RefPtr<TypeBuilder::DOM::Rect> rect = TypeBuilder::DOM::Rect::create().
-        setX(viewRect.x()).
-        setY(viewRect.y()).
-        setWidth(viewRect.width()).
-        setHeight(viewRect.height());
-
     IntRect boundingBox = pixelSnappedIntRect(view->contentsToRootView(renderer->absoluteBoundingBoxRect()));
     RenderBoxModelObject* modelObject = renderer->isBoxModelObject() ? toRenderBoxModelObject(renderer) : 0;
 
@@ -1356,8 +1350,25 @@
         .setBorder(buildArrayForQuad(quads.at(1)))
         .setMargin(buildArrayForQuad(quads.at(0)))
         .setWidth(modelObject ? adjustForAbsoluteZoom(modelObject->pixelSnappedOffsetWidth(), modelObject) : boundingBox.width())
-        .setHeight(modelObject ? adjustForAbsoluteZoom(modelObject->pixelSnappedOffsetHeight(), modelObject) : boundingBox.height())
-        .setVisibleContentRect(rect);
+        .setHeight(modelObject ? adjustForAbsoluteZoom(modelObject->pixelSnappedOffsetHeight(), modelObject) : boundingBox.height());
+}
+
+void InspectorDOMAgent::getNodeForLocation(ErrorString* errorString, int x, int y, int* nodeId)
+{
+    // This call operates no handles, it could emerge before getDocument.
+    if (!m_documentNodeToIdMap.contains(m_document)) {
+        RefPtr<TypeBuilder::DOM::Node> root;
+        getDocument(errorString, root);
+        if (!errorString->isEmpty())
+            return;
+    }
+
+    Node* node = hoveredNodeForPoint(m_document->frame(), IntPoint(x, y), false);
+    if (!node) {
+        *errorString = "No node found at given location";
+        return;
+    }
+    *nodeId = pushNodePathToFrontend(node);
 }
 
 void InspectorDOMAgent::resolveNode(ErrorString* errorString, int nodeId, const String* const objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& result)
@@ -1466,7 +1477,7 @@
         }
 
         if (element->hasTagName(templateTag)) {
-            value->setTemplateContent(buildObjectForNode(static_cast<HTMLTemplateElement*>(element)->content(), 0, nodesMap));
+            value->setTemplateContent(buildObjectForNode(toHTMLTemplateElement(element)->content(), 0, nodesMap));
             forcePushChildren = true;
         }
     } else if (node->isDocumentNode()) {
@@ -1475,7 +1486,7 @@
         value->setBaseURL(documentBaseURLString(document));
         value->setXmlVersion(document->xmlVersion());
     } else if (node->nodeType() == Node::DOCUMENT_TYPE_NODE) {
-        DocumentType* docType = static_cast<DocumentType*>(node);
+        DocumentType* docType = toDocumentType(node);
         value->setPublicId(docType->publicId());
         value->setSystemId(docType->systemId());
         value->setInternalSubset(docType->internalSubset());
@@ -1541,17 +1552,17 @@
 PassRefPtr<TypeBuilder::DOM::EventListener> InspectorDOMAgent::buildObjectForEventListener(const RegisteredEventListener& registeredEventListener, const AtomicString& eventType, Node* node, const String* objectGroupId)
 {
     RefPtr<EventListener> eventListener = registeredEventListener.listener;
-    Document* document = node->document();
+    Document& document = node->document();
     RefPtr<TypeBuilder::DOM::EventListener> value = TypeBuilder::DOM::EventListener::create()
         .setType(eventType)
         .setUseCapture(registeredEventListener.useCapture)
         .setIsAttribute(eventListener->isAttribute())
         .setNodeId(pushNodePathToFrontend(node))
-        .setHandlerBody(eventListenerHandlerBody(document, eventListener.get()));
+        .setHandlerBody(eventListenerHandlerBody(&document, eventListener.get()));
     if (objectGroupId) {
-        ScriptValue functionValue = eventListenerHandler(document, eventListener.get());
+        ScriptValue functionValue = eventListenerHandler(&document, eventListener.get());
         if (!functionValue.hasNoValue()) {
-            Frame* frame = document->frame();
+            Frame* frame = document.frame();
             if (frame) {
                 ScriptState* scriptState = eventListenerHandlerScriptState(frame, eventListener.get());
                 if (scriptState) {
@@ -1567,7 +1578,7 @@
     String sourceName;
     String scriptId;
     int lineNumber;
-    if (eventListenerHandlerLocation(node->document(), eventListener.get(), sourceName, scriptId, lineNumber)) {
+    if (eventListenerHandlerLocation(&node->document(), eventListener.get(), sourceName, scriptId, lineNumber)) {
         RefPtr<TypeBuilder::Debugger::Location> location = TypeBuilder::Debugger::Location::create()
             .setScriptId(scriptId)
             .setLineNumber(lineNumber);
@@ -1891,7 +1902,7 @@
 
 PassRefPtr<TypeBuilder::Runtime::RemoteObject> InspectorDOMAgent::resolveNode(Node* node, const String& objectGroup)
 {
-    Document* document = node->isDocumentNode() ? node->document() : node->ownerDocument();
+    Document* document = node->isDocumentNode() ? &node->document() : node->ownerDocument();
     Frame* frame = document ? document->frame() : 0;
     if (!frame)
         return 0;
diff --git a/Source/core/inspector/InspectorDOMAgent.h b/Source/core/inspector/InspectorDOMAgent.h
index 76023f8..ed92ab3 100644
--- a/Source/core/inspector/InspectorDOMAgent.h
+++ b/Source/core/inspector/InspectorDOMAgent.h
@@ -149,6 +149,7 @@
     virtual void focus(ErrorString*, int nodeId);
     virtual void setFileInputFiles(ErrorString*, int nodeId, const RefPtr<JSONArray>& files);
     virtual void getBoxModel(ErrorString*, int nodeId, RefPtr<TypeBuilder::DOM::BoxModel>&);
+    virtual void getNodeForLocation(ErrorString*, int x, int y, int* nodeId);
 
     static void getEventListeners(Node*, Vector<EventListenerInfo>& listenersArray, bool includeAncestors);
 
diff --git a/Source/core/inspector/InspectorDOMStorageAgent.cpp b/Source/core/inspector/InspectorDOMStorageAgent.cpp
index 4b2a118..4420d1b 100644
--- a/Source/core/inspector/InspectorDOMStorageAgent.cpp
+++ b/Source/core/inspector/InspectorDOMStorageAgent.cpp
@@ -108,22 +108,6 @@
     m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, false);
 }
 
-void InspectorDOMStorageAgent::getValue(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key, TypeBuilder::OptOutput<WTF::String>* value)
-{
-    Frame* frame;
-    OwnPtr<StorageArea> storageArea = findStorageArea(errorString, storageId, frame);
-    if (!storageArea)
-        return;
-
-    TrackExceptionState es;
-    bool keyPresent = storageArea->contains(key, es, frame);
-    if (hadException(es, errorString) || !keyPresent)
-        return;
-
-    *value = storageArea->getItem(key, es, frame);
-    hadException(es, errorString);
-}
-
 void InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, const RefPtr<JSONObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > >& items)
 {
     Frame* frame;
diff --git a/Source/core/inspector/InspectorDOMStorageAgent.h b/Source/core/inspector/InspectorDOMStorageAgent.h
index e3b35b0..4c79cef 100644
--- a/Source/core/inspector/InspectorDOMStorageAgent.h
+++ b/Source/core/inspector/InspectorDOMStorageAgent.h
@@ -60,7 +60,6 @@
     // Called from the front-end.
     virtual void enable(ErrorString*);
     virtual void disable(ErrorString*);
-    virtual void getValue(ErrorString*, const RefPtr<JSONObject>& storageId, const String& key, TypeBuilder::OptOutput<WTF::String>* value);
     virtual void getDOMStorageItems(ErrorString*, const RefPtr<JSONObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > >& items);
     virtual void setDOMStorageItem(ErrorString*, const RefPtr<JSONObject>& storageId, const String& key, const String& value);
     virtual void removeDOMStorageItem(ErrorString*, const RefPtr<JSONObject>& storageId, const String& key);
diff --git a/Source/core/inspector/InspectorDebuggerAgent.cpp b/Source/core/inspector/InspectorDebuggerAgent.cpp
index 2900027..db63572 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -68,6 +68,9 @@
 static const char condition[] = "condition";
 static const char isAnti[] = "isAnti";
 static const char skipStackPattern[] = "skipStackPattern";
+static const char skipAllPauses[] = "skipAllPauses";
+static const char skipAllPausesExpiresOnReload[] = "skipAllPausesExpiresOnReload";
+
 };
 
 static const int numberOfStepsBeforeStepOut = 10;
@@ -100,6 +103,7 @@
     , m_javaScriptPauseScheduled(false)
     , m_listener(0)
     , m_skipStepInCount(numberOfStepsBeforeStepOut)
+    , m_skipAllPauses(false)
 {
     // FIXME: make breakReason optional so that there was no need to init it with "other".
     clearBreakDetails();
@@ -137,6 +141,8 @@
 
     if (m_listener)
         m_listener->debuggerWasDisabled();
+
+    m_skipAllPauses = false;
 }
 
 bool InspectorDebuggerAgent::enabled()
@@ -183,6 +189,11 @@
         String error;
         setPauseOnExceptionsImpl(&error, pauseState);
         m_cachedSkipStackRegExp = compileSkipCallFramePattern(m_state->getString(DebuggerAgentState::skipStackPattern));
+        m_skipAllPauses = m_state->getBoolean(DebuggerAgentState::skipAllPauses);
+        if (m_skipAllPauses && m_state->getBoolean(DebuggerAgentState::skipAllPausesExpiresOnReload)) {
+            m_skipAllPauses = false;
+            m_state->setBoolean(DebuggerAgentState::skipAllPauses, false);
+        }
     }
 }
 
@@ -211,6 +222,22 @@
     scriptDebugServer().setBreakpointsActivated(active);
 }
 
+void InspectorDebuggerAgent::setSkipAllPauses(ErrorString*, bool skipped, const bool* untilReload)
+{
+    m_skipAllPauses = skipped;
+    bool untilReloadValue = untilReload && *untilReload;
+    m_state->setBoolean(DebuggerAgentState::skipAllPauses, m_skipAllPauses);
+    m_state->setBoolean(DebuggerAgentState::skipAllPausesExpiresOnReload, untilReloadValue);
+}
+
+void InspectorDebuggerAgent::pageDidCommitLoad()
+{
+    if (m_state->getBoolean(DebuggerAgentState::skipAllPausesExpiresOnReload)) {
+        m_skipAllPauses = false;
+        m_state->setBoolean(DebuggerAgentState::skipAllPauses, m_skipAllPauses);
+    }
+}
+
 bool InspectorDebuggerAgent::isPaused()
 {
     return scriptDebugServer().isPaused();
@@ -434,6 +461,9 @@
 
 ScriptDebugListener::SkipPauseRequest InspectorDebuggerAgent::shouldSkipExceptionPause(RefPtr<JavaScriptCallFrame>& topFrame)
 {
+    if (m_skipAllPauses)
+        return ScriptDebugListener::Continue;
+
     String topFrameScriptUrl = scriptURL(topFrame.get());
     if (m_cachedSkipStackRegExp && !topFrameScriptUrl.isEmpty() && m_cachedSkipStackRegExp->match(topFrameScriptUrl) != -1)
         return ScriptDebugListener::Continue;
@@ -480,11 +510,16 @@
 
 ScriptDebugListener::SkipPauseRequest InspectorDebuggerAgent::shouldSkipBreakpointPause(RefPtr<JavaScriptCallFrame>& topFrame)
 {
+    if (m_skipAllPauses)
+        return ScriptDebugListener::Continue;
     return ScriptDebugListener::NoSkip;
 }
 
 ScriptDebugListener::SkipPauseRequest InspectorDebuggerAgent::shouldSkipStepPause(RefPtr<JavaScriptCallFrame>& topFrame)
 {
+    if (m_skipAllPauses)
+        return ScriptDebugListener::Continue;
+
     if (m_cachedSkipStackRegExp) {
         String scriptUrl = scriptURL(topFrame.get());
         if (!scriptUrl.isEmpty() && m_cachedSkipStackRegExp->match(scriptUrl) != -1) {
diff --git a/Source/core/inspector/InspectorDebuggerAgent.h b/Source/core/inspector/InspectorDebuggerAgent.h
index e0f583d..b4b281e 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.h
+++ b/Source/core/inspector/InspectorDebuggerAgent.h
@@ -90,6 +90,7 @@
     virtual void enable(ErrorString*);
     virtual void disable(ErrorString*);
     virtual void setBreakpointsActive(ErrorString*, bool active);
+    virtual void setSkipAllPauses(ErrorString*, bool skipped, const bool* untilReload);
 
     virtual void setBreakpointByUrl(ErrorString*, int lineNumber, const String* optionalURL, const String* optionalURLRegex, const int* optionalColumnNumber, const String* optionalCondition, const bool* isAntiBreakpoint, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& locations);
     virtual void setBreakpoint(ErrorString*, const RefPtr<JSONObject>& location, const String* optionalCondition, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Debugger::Location>& actualLocation);
@@ -166,6 +167,7 @@
     virtual void didPause(ScriptState*, const ScriptValue& callFrames, const ScriptValue& exception, const Vector<String>& hitBreakpoints);
     virtual void didContinue();
     void reset();
+    void pageDidCommitLoad();
 
 private:
     void cancelPauseOnNextStatement();
@@ -208,6 +210,7 @@
     Listener* m_listener;
 
     int m_skipStepInCount;
+    bool m_skipAllPauses;
     OwnPtr<RegularExpression> m_cachedSkipStackRegExp;
 };
 
diff --git a/Source/core/inspector/InspectorFileSystemAgent.cpp b/Source/core/inspector/InspectorFileSystemAgent.cpp
index 6a75eee..b16d966 100644
--- a/Source/core/inspector/InspectorFileSystemAgent.cpp
+++ b/Source/core/inspector/InspectorFileSystemAgent.cpp
@@ -35,13 +35,13 @@
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/Event.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/fileapi/File.h"
 #include "core/fileapi/FileError.h"
 #include "core/fileapi/FileReader.h"
 #include "core/html/VoidCallback.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/page/Frame.h"
 #include "core/platform/MIMETypeRegistry.h"
 #include "modules/filesystem/DOMFileSystem.h"
@@ -161,7 +161,7 @@
     }
 
     RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &FileSystemRootRequest::didGetEntry);
-    OwnPtr<ResolveURICallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, "/");
+    OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, "/");
 
     LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
 }
@@ -231,7 +231,7 @@
     }
 
     RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &DirectoryContentRequest::didGetEntry);
-    OwnPtr<ResolveURICallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, path);
+    OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, path);
 
     LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
 }
@@ -356,7 +356,7 @@
     }
 
     RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &MetadataRequest::didGetEntry);
-    OwnPtr<ResolveURICallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, m_path);
+    OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, m_path);
     LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
 }
 
@@ -462,7 +462,7 @@
     }
 
     RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &FileContentRequest::didGetEntry);
-    OwnPtr<ResolveURICallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, path);
+    OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, path);
 
     LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
 }
@@ -572,11 +572,11 @@
     }
 
     if (path == "/") {
-        OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = VoidCallbacks::create(this, errorCallback);
+        OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = VoidCallbacks::create(this, errorCallback, 0);
         LocalFileSystem::from(scriptExecutionContext)->deleteFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
     } else {
         RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &DeleteEntryRequest::didGetEntry);
-        OwnPtr<ResolveURICallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, path);
+        OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, path);
         LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
     }
 }
diff --git a/Source/core/inspector/InspectorFrontendClient.h b/Source/core/inspector/InspectorFrontendClient.h
index 37599d0..00848e1 100644
--- a/Source/core/inspector/InspectorFrontendClient.h
+++ b/Source/core/inspector/InspectorFrontendClient.h
@@ -38,38 +38,15 @@
 
 class InspectorFrontendClient {
 public:
-    enum DockSide {
-        Undocked = 0,
-        DockedToRight,
-        DockedToBottom
-    };
-
     virtual ~InspectorFrontendClient() { }
 
     virtual void windowObjectCleared() = 0;
-    virtual void moveWindowBy(float x, float y) = 0;
-
-    virtual void bringToFront() = 0;
-    virtual void closeWindow() = 0;
-
-    virtual void requestSetDockSide(DockSide) = 0;
-    virtual void changeAttachedWindowHeight(unsigned) = 0;
-
-    virtual void openInNewTab(const String& url) = 0;
-
-    virtual void save(const WTF::String& url, const WTF::String& content, bool forceSaveAs) = 0;
-    virtual void append(const WTF::String& url, const WTF::String& content) = 0;
 
     virtual void inspectedURLChanged(const String&) = 0;
 
     virtual void sendMessageToBackend(const String&) = 0;
 
-    virtual void requestFileSystems() = 0;
-    virtual void addFileSystem() = 0;
-    virtual void removeFileSystem(const String& fileSystemPath) = 0;
-    virtual void indexPath(int requestId, const String& fileSystemPath) = 0;
-    virtual void stopIndexing(int requestId) = 0;
-    virtual void searchInPath(int requestId, const String& fileSystemPath, const String& query) = 0;
+    virtual void sendMessageToEmbedder(const String&) = 0;
 
     virtual bool isUnderTest() = 0;
 };
diff --git a/Source/core/inspector/InspectorFrontendHost.cpp b/Source/core/inspector/InspectorFrontendHost.cpp
index 551331d..c4b6fbc 100644
--- a/Source/core/inspector/InspectorFrontendHost.cpp
+++ b/Source/core/inspector/InspectorFrontendHost.cpp
@@ -32,16 +32,18 @@
 
 #include "bindings/v8/ScriptFunctionCall.h"
 #include "core/dom/UserGestureIndicator.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorFrontendClient.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/page/ContextMenuController.h"
 #include "core/page/ContextMenuProvider.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/ContextMenu.h"
 #include "core/platform/ContextMenuItem.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/Pasteboard.h"
 #include "core/platform/network/ResourceError.h"
 #include "core/platform/network/ResourceRequest.h"
@@ -136,32 +138,16 @@
 {
 }
 
-void InspectorFrontendHost::requestSetDockSide(const String& side)
-{
-    if (!m_client)
-        return;
-    if (side == "undocked")
-        m_client->requestSetDockSide(InspectorFrontendClient::Undocked);
-    else if (side == "right")
-        m_client->requestSetDockSide(InspectorFrontendClient::DockedToRight);
-    else if (side == "bottom")
-        m_client->requestSetDockSide(InspectorFrontendClient::DockedToBottom);
-}
-
 void InspectorFrontendHost::closeWindow()
 {
     if (m_client) {
-        m_client->closeWindow();
+        RefPtr<JSONObject> message = JSONObject::create();
+        message->setString("method", "closeWindow");
+        sendMessageToEmbedder(message->toJSONString());
         disconnectClient(); // Disconnect from client.
     }
 }
 
-void InspectorFrontendHost::bringToFront()
-{
-    if (m_client)
-        m_client->bringToFront();
-}
-
 void InspectorFrontendHost::setZoomFactor(float zoom)
 {
     m_frontendPage->mainFrame()->setPageAndTextZoomFactors(zoom, 1);
@@ -175,14 +161,6 @@
 
 void InspectorFrontendHost::setAttachedWindowHeight(unsigned height)
 {
-    if (m_client)
-        m_client->changeAttachedWindowHeight(height);
-}
-
-void InspectorFrontendHost::moveWindowBy(float x, float y) const
-{
-    if (m_client)
-        m_client->moveWindowBy(x, y);
 }
 
 void InspectorFrontendHost::setInjectedScriptForOrigin(const String& origin, const String& script)
@@ -200,29 +178,11 @@
     Pasteboard::generalPasteboard()->writePlainText(text, Pasteboard::CannotSmartReplace);
 }
 
-void InspectorFrontendHost::openInNewTab(const String& url)
-{
-    if (m_client)
-        m_client->openInNewTab(url);
-}
-
 bool InspectorFrontendHost::canSave()
 {
     return true;
 }
 
-void InspectorFrontendHost::save(const String& url, const String& content, bool forceSaveAs)
-{
-    if (m_client)
-        m_client->save(url, content, forceSaveAs);
-}
-
-void InspectorFrontendHost::append(const String& url, const String& content)
-{
-    if (m_client)
-        m_client->append(url, content);
-}
-
 void InspectorFrontendHost::close(const String&)
 {
 }
@@ -233,6 +193,12 @@
         m_client->sendMessageToBackend(message);
 }
 
+void InspectorFrontendHost::sendMessageToEmbedder(const String& message)
+{
+    if (m_client)
+        m_client->sendMessageToEmbedder(message);
+}
+
 void InspectorFrontendHost::showContextMenu(Event* event, const Vector<ContextMenuItem>& items)
 {
     if (!event)
@@ -258,7 +224,7 @@
     Vector<char> data;
     ResourceError error;
     ResourceResponse response;
-    m_frontendPage->mainFrame()->loader()->loadResourceSynchronously(request, DoNotAllowStoredCredentials, error, response, data);
+    m_frontendPage->mainFrame()->document()->fetcher()->fetchSynchronously(request, DoNotAllowStoredCredentials, error, response, data);
     WTF::TextEncoding textEncoding(response.textEncodingName());
     bool useDetector = false;
     if (!textEncoding.isValid()) {
@@ -272,13 +238,13 @@
 String InspectorFrontendHost::getSelectionBackgroundColor()
 {
     Color color = RenderTheme::theme().activeSelectionBackgroundColor();
-    return color != Color::transparent ? color.serialized() : "";
+    return color.isValid() ? color.serialized() : "";
 }
 
 String InspectorFrontendHost::getSelectionForegroundColor()
 {
     Color color = RenderTheme::theme().activeSelectionForegroundColor();
-    return color != Color::transparent ? color.serialized() : "";
+    return color.isValid() ? color.serialized() : "";
 }
 
 bool InspectorFrontendHost::supportsFileSystems()
@@ -286,46 +252,10 @@
     return true;
 }
 
-void InspectorFrontendHost::requestFileSystems()
-{
-    if (m_client)
-        m_client->requestFileSystems();
-}
-
-void InspectorFrontendHost::addFileSystem()
-{
-    if (m_client)
-        m_client->addFileSystem();
-}
-
-void InspectorFrontendHost::removeFileSystem(const String& fileSystemPath)
-{
-    if (m_client)
-        m_client->removeFileSystem(fileSystemPath);
-}
-
 PassRefPtr<DOMFileSystem> InspectorFrontendHost::isolatedFileSystem(const String& fileSystemName, const String& rootURL)
 {
     ScriptExecutionContext* context = m_frontendPage->mainFrame()->document();
-    return DOMFileSystem::create(context, fileSystemName, FileSystemTypeIsolated, KURL(ParsedURLString, rootURL), AsyncFileSystem::create());
-}
-
-void InspectorFrontendHost::indexPath(int requestId, const String& fileSystemPath)
-{
-    if (m_client)
-        m_client->indexPath(requestId, fileSystemPath);
-}
-
-void InspectorFrontendHost::stopIndexing(int requestId)
-{
-    if (m_client)
-        m_client->stopIndexing(requestId);
-}
-
-void InspectorFrontendHost::searchInPath(int requestId, const String& fileSystemPath, const String& query)
-{
-    if (m_client)
-        m_client->searchInPath(requestId, fileSystemPath, query);
+    return DOMFileSystem::create(context, fileSystemName, FileSystemTypeIsolated, KURL(ParsedURLString, rootURL));
 }
 
 bool InspectorFrontendHost::isUnderTest()
diff --git a/Source/core/inspector/InspectorFrontendHost.h b/Source/core/inspector/InspectorFrontendHost.h
index deeb369..4c955c3 100644
--- a/Source/core/inspector/InspectorFrontendHost.h
+++ b/Source/core/inspector/InspectorFrontendHost.h
@@ -54,37 +54,26 @@
     ~InspectorFrontendHost();
     void disconnectClient();
 
-    void requestSetDockSide(const String&);
     void closeWindow();
-    void bringToFront();
     void setZoomFactor(float);
     void inspectedURLChanged(const String&);
 
     void setAttachedWindowHeight(unsigned);
-    void moveWindowBy(float x, float y) const;
     void setInjectedScriptForOrigin(const String& origin, const String& script);
 
     void copyText(const String& text);
-    void openInNewTab(const String& url);
-    void save(const String& url, const String& content, bool forceSaveAs);
-    void append(const String& url, const String& content);
     void close(const String& url);
 
     // Called from [Custom] implementations.
     void showContextMenu(Event*, const Vector<ContextMenuItem>& items);
     void sendMessageToBackend(const String& message);
+    void sendMessageToEmbedder(const String& message);
 
     String loadResourceSynchronously(const String& url);
     String getSelectionBackgroundColor();
     String getSelectionForegroundColor();
 
-    void requestFileSystems();
-    void addFileSystem();
-    void removeFileSystem(const String& fileSystemPath);
     PassRefPtr<DOMFileSystem> isolatedFileSystem(const String& fileSystemName, const String& rootURL);
-    void indexPath(int requestId, const String& fileSystemPath);
-    void stopIndexing(int requestId);
-    void searchInPath(int requestId, const String& fileSystemPath, const String& query);
 
     bool isUnderTest();
 
diff --git a/Source/core/inspector/InspectorFrontendHost.idl b/Source/core/inspector/InspectorFrontendHost.idl
index f764bf2..678a36c 100644
--- a/Source/core/inspector/InspectorFrontendHost.idl
+++ b/Source/core/inspector/InspectorFrontendHost.idl
@@ -34,25 +34,20 @@
     NoInterfaceObject
 ] interface InspectorFrontendHost {
     void closeWindow();
-    void bringToFront();
     void setZoomFactor(float zoom);
     void inspectedURLChanged(DOMString newURL);
 
-    void requestSetDockSide(DOMString side);
     void setAttachedWindowHeight(unsigned long height);
-    void moveWindowBy(float x, float y);
     void setInjectedScriptForOrigin(DOMString origin, DOMString script);
 
     void copyText(DOMString text);
-    void openInNewTab(DOMString url);
-    void save(DOMString url, DOMString content, boolean forceSaveAs);
-    void append(DOMString url, DOMString content);
     void close(DOMString url);
 
     [Custom] DOMString platform();
     [Custom] DOMString port();
     [Custom] void showContextMenu(MouseEvent event, any items);
     void sendMessageToBackend(DOMString message);
+    void sendMessageToEmbedder(DOMString message);
 
     [Custom] void recordActionTaken(unsigned long actionCode);
     [Custom] void recordPanelShown(unsigned long panelCode);
@@ -62,13 +57,7 @@
     DOMString getSelectionBackgroundColor();
     DOMString getSelectionForegroundColor();
 
-    void requestFileSystems();
-    void addFileSystem();
-    void removeFileSystem(DOMString fileSystemPath);
     DOMFileSystem isolatedFileSystem(DOMString fileSystemId, DOMString registeredName);
-    void indexPath(long requestId, DOMString fileSystemPath);
-    void stopIndexing(long requestId);
-    void searchInPath(long requestId, DOMString fileSystemPath, DOMString query);
 
     boolean isUnderTest();
 
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.cpp b/Source/core/inspector/InspectorIndexedDBAgent.cpp
index fecf5d1..bd5a454 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;
+    v8::HandleScope handleScope(frame->script()->isolate());
     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;
+    v8::HandleScope handleScope(frame->script()->isolate());
     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;
+    v8::HandleScope handleScope(frame->script()->isolate());
     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;
+    v8::HandleScope handleScope(frame->script()->isolate());
     v8::Handle<v8::Context> context = document->frame()->script()->mainWorldContext();
     ASSERT(!context.IsEmpty());
     v8::Context::Scope contextScope(context);
diff --git a/Source/core/inspector/InspectorInstrumentation.cpp b/Source/core/inspector/InspectorInstrumentation.cpp
index 246b9c3..4788d69 100644
--- a/Source/core/inspector/InspectorInstrumentation.cpp
+++ b/Source/core/inspector/InspectorInstrumentation.cpp
@@ -162,20 +162,20 @@
 
 bool canvasAgentEnabled(ScriptExecutionContext* scriptExecutionContext)
 {
-    InstrumentingAgents* instrumentingAgents = instrumentingAgentsForScriptExecutionContext(scriptExecutionContext);
+    InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(scriptExecutionContext);
     return instrumentingAgents && instrumentingAgents->inspectorCanvasAgent();
 }
 
 bool consoleAgentEnabled(ScriptExecutionContext* scriptExecutionContext)
 {
-    InstrumentingAgents* instrumentingAgents = instrumentingAgentsForScriptExecutionContext(scriptExecutionContext);
+    InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(scriptExecutionContext);
     InspectorConsoleAgent* consoleAgent = instrumentingAgents ? instrumentingAgents->inspectorConsoleAgent() : 0;
     return consoleAgent && consoleAgent->enabled();
 }
 
 bool timelineAgentEnabled(ScriptExecutionContext* scriptExecutionContext)
 {
-    InstrumentingAgents* instrumentingAgents = instrumentingAgentsForScriptExecutionContext(scriptExecutionContext);
+    InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(scriptExecutionContext);
     return instrumentingAgents && instrumentingAgents->inspectorTimelineAgent();
 }
 
@@ -207,19 +207,19 @@
     return 0;
 }
 
-InstrumentingAgents* instrumentingAgentsForPage(Page* page)
+InstrumentingAgents* instrumentingAgentsFor(Page* page)
 {
     if (!page)
         return 0;
     return instrumentationForPage(page);
 }
 
-InstrumentingAgents* instrumentingAgentsForRenderObject(RenderObject* renderer)
+InstrumentingAgents* instrumentingAgentsFor(RenderObject* renderer)
 {
-    return instrumentingAgentsForFrame(renderer->frame());
+    return instrumentingAgentsFor(renderer->frame());
 }
 
-InstrumentingAgents* instrumentingAgentsForWorkerGlobalScope(WorkerGlobalScope* workerGlobalScope)
+InstrumentingAgents* instrumentingAgentsFor(WorkerGlobalScope* workerGlobalScope)
 {
     if (!workerGlobalScope)
         return 0;
diff --git a/Source/core/inspector/InspectorInstrumentation.h b/Source/core/inspector/InspectorInstrumentation.h
index fcecc81..3e4f9e2 100644
--- a/Source/core/inspector/InspectorInstrumentation.h
+++ b/Source/core/inspector/InspectorInstrumentation.h
@@ -42,6 +42,7 @@
 #include "core/page/Page.h"
 #include "core/platform/network/FormData.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/RenderImage.h"
 #include "core/storage/StorageArea.h"
 #include "modules/websockets/WebSocketFrame.h"
 #include "modules/websockets/WebSocketHandshakeRequest.h"
@@ -102,14 +103,16 @@
 
 InspectorTimelineAgent* retrieveTimelineAgent(const InspectorInstrumentationCookie&);
 
-InstrumentingAgents* instrumentingAgentsForPage(Page*);
-InstrumentingAgents* instrumentingAgentsForFrame(Frame*);
-InstrumentingAgents* instrumentingAgentsForScriptExecutionContext(ScriptExecutionContext*);
-InstrumentingAgents* instrumentingAgentsForDocument(Document*);
-InstrumentingAgents* instrumentingAgentsForRenderObject(RenderObject*);
-InstrumentingAgents* instrumentingAgentsForElement(Element*);
+// Called from generated instrumentation code.
+InstrumentingAgents* instrumentingAgentsFor(Page*);
+InstrumentingAgents* instrumentingAgentsFor(Frame*);
+InstrumentingAgents* instrumentingAgentsFor(ScriptExecutionContext*);
+InstrumentingAgents* instrumentingAgentsFor(Document*);
+InstrumentingAgents* instrumentingAgentsFor(RenderObject*);
+InstrumentingAgents* instrumentingAgentsFor(Element*);
+InstrumentingAgents* instrumentingAgentsFor(WorkerGlobalScope*);
 
-InstrumentingAgents* instrumentingAgentsForWorkerGlobalScope(WorkerGlobalScope*);
+// Helper for the one above.
 InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ScriptExecutionContext*);
 
 }  // namespace InspectorInstrumentation
@@ -134,34 +137,32 @@
 
 namespace InspectorInstrumentation {
 
-inline InstrumentingAgents* instrumentingAgentsForScriptExecutionContext(ScriptExecutionContext* context)
+inline InstrumentingAgents* instrumentingAgentsFor(ScriptExecutionContext* context)
 {
     if (!context)
         return 0;
-    if (context->isDocument())
-        return instrumentingAgentsForPage(toDocument(context)->page());
-    return instrumentingAgentsForNonDocumentContext(context);
+    return context->isDocument() ? instrumentingAgentsFor(toDocument(context)) : instrumentingAgentsForNonDocumentContext(context);
 }
 
-inline InstrumentingAgents* instrumentingAgentsForFrame(Frame* frame)
+inline InstrumentingAgents* instrumentingAgentsFor(Frame* frame)
 {
-    return frame ? instrumentingAgentsForPage(frame->page()) : 0;
+    return frame ? instrumentingAgentsFor(frame->page()) : 0;
 }
 
-inline InstrumentingAgents* instrumentingAgentsForDocument(Document* document)
+inline InstrumentingAgents* instrumentingAgentsFor(Document* document)
 {
     if (document) {
         Page* page = document->page();
         if (!page && document->templateDocumentHost())
             page = document->templateDocumentHost()->page();
-        return instrumentingAgentsForPage(page);
+        return instrumentingAgentsFor(page);
     }
     return 0;
 }
 
-inline InstrumentingAgents* instrumentingAgentsForElement(Element* element)
+inline InstrumentingAgents* instrumentingAgentsFor(Element* element)
 {
-    return element ? instrumentingAgentsForDocument(element->document()) : 0;
+    return element ? instrumentingAgentsFor(&element->document()) : 0;
 }
 
 bool cssErrorFilter(const CSSParserString& content, int propertyId, int errorType);
diff --git a/Source/core/inspector/InspectorInstrumentation.idl b/Source/core/inspector/InspectorInstrumentation.idl
index 5803742..b706ee5 100644
--- a/Source/core/inspector/InspectorInstrumentation.idl
+++ b/Source/core/inspector/InspectorInstrumentation.idl
@@ -217,6 +217,12 @@
     [Timeline, Page, Inline=FastReturn]
     void didPaint([Keep] RenderObject*, GraphicsContext*, const LayoutRect&);
 
+    [Timeline, Inline=FastReturn]
+    void willPaintImage([Keep] RenderImage*);
+
+    [Timeline, Inline=FastReturn]
+    void didPaintImage(RenderImage*);
+
     [Resource, Timeline, Inline=FastReturn]
     InspectorInstrumentationCookie willRecalculateStyle([Keep] Document*);
 
@@ -318,13 +324,16 @@
     [DOM, Timeline, Page]
     void loadEventFired([Keep] Frame*);
 
+    [Page]
+    void frameAttachedToParent([Keep] Frame*);
+
     [Canvas, Page, CSS]
     void frameDetachedFromParent([Keep] Frame*);
 
     [Page, Inline=FastReturn]
     void childDocumentOpened([Keep] Document*);
 
-    [Console, Resource, CSS, Database, DOM, LayerTree, Inspector, Canvas, Page]
+    [Console, Resource, CSS, Database, DOM, Inspector, Canvas, Page, PageDebugger]
     void didCommitLoad([Keep] Frame*, DocumentLoader*);
 
     [DOM, Inline=FastReturn]
diff --git a/Source/core/inspector/InspectorInstrumentationCustomInl.h b/Source/core/inspector/InspectorInstrumentationCustomInl.h
index 68a54b8..49dcdb7 100644
--- a/Source/core/inspector/InspectorInstrumentationCustomInl.h
+++ b/Source/core/inspector/InspectorInstrumentationCustomInl.h
@@ -47,14 +47,14 @@
 
 inline bool profilerEnabled(WorkerGlobalScope* scope)
 {
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForWorkerGlobalScope(scope))
+    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(scope))
         return profilerEnabledImpl(instrumentingAgents);
     return false;
 }
 
 inline bool profilerEnabled(Page* page)
 {
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForPage(page))
+    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(page))
         return profilerEnabledImpl(instrumentingAgents);
     return false;
 }
@@ -62,7 +62,7 @@
 inline bool isDebuggerPaused(Frame* frame)
 {
     FAST_RETURN_IF_NO_FRONTENDS(false);
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForFrame(frame))
+    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(frame))
         return isDebuggerPausedImpl(instrumentingAgents);
     return false;
 }
@@ -70,7 +70,7 @@
 inline bool collectingHTMLParseErrors(Page* page)
 {
     FAST_RETURN_IF_NO_FRONTENDS(false);
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForPage(page))
+    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(page))
         return collectingHTMLParseErrorsImpl(instrumentingAgents);
     return false;
 }
@@ -78,7 +78,7 @@
 inline String preprocessEventListener(Frame* frame, const String& source, const String& url, const String& functionName)
 {
     FAST_RETURN_IF_NO_FRONTENDS(source);
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForFrame(frame))
+    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(frame))
         return preprocessEventListenerImpl(instrumentingAgents, frame, source, url, functionName);
     return source;
 }
@@ -86,7 +86,7 @@
 inline PassOwnPtr<ScriptSourceCode> preprocess(Frame* frame, const ScriptSourceCode& sourceCode)
 {
     FAST_RETURN_IF_NO_FRONTENDS(PassOwnPtr<ScriptSourceCode>());
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForFrame(frame))
+    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(frame))
         return preprocessImpl(instrumentingAgents, frame, sourceCode);
     return PassOwnPtr<ScriptSourceCode>();
 }
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.cpp b/Source/core/inspector/InspectorLayerTreeAgent.cpp
index 9983c15..5f92bb0 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.cpp
+++ b/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -39,6 +39,7 @@
 #include "core/inspector/InspectorState.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/DocumentLoader.h"
+#include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/graphics/IntRect.h"
 #include "core/platform/graphics/transforms/TransformationMatrix.h"
@@ -55,26 +56,24 @@
 static const char layerTreeAgentEnabled[] = "layerTreeAgentEnabled";
 };
 
-static PassRefPtr<TypeBuilder::LayerTree::Layer> buildObjectForLayer(GraphicsLayer* graphicsLayer, int nodeId, bool forceRoot)
+static PassRefPtr<TypeBuilder::LayerTree::Layer> buildObjectForLayer(GraphicsLayer* graphicsLayer, int nodeId)
 {
     RefPtr<TypeBuilder::LayerTree::Layer> layerObject = TypeBuilder::LayerTree::Layer::create()
         .setLayerId(String::number(graphicsLayer->platformLayer()->id()))
-        .setNodeId(nodeId)
         .setOffsetX(graphicsLayer->position().x())
         .setOffsetY(graphicsLayer->position().y())
         .setWidth(graphicsLayer->size().width())
         .setHeight(graphicsLayer->size().height())
         .setPaintCount(graphicsLayer->paintCount());
 
-    // Artificially clip tree at root render layer's graphic layer -- it might be not the real
-    // root of graphics layer hierarchy, as platform adds containing layers (e.g. for frame scrolling).
-    if (!forceRoot) {
-        GraphicsLayer* parent = graphicsLayer->parent();
-        if (!parent)
-            parent = graphicsLayer->replicatedLayer();
-        if (parent)
-            layerObject->setParentLayerId(String::number(parent->platformLayer()->id()));
-    }
+    if (nodeId)
+        layerObject->setNodeId(nodeId);
+
+    GraphicsLayer* parent = graphicsLayer->parent();
+    if (!parent)
+        parent = graphicsLayer->replicatedLayer();
+    if (parent)
+        layerObject->setParentLayerId(String::number(parent->platformLayer()->id()));
     if (!graphicsLayer->contentsAreVisible())
         layerObject->setInvisible(true);
     const TransformationMatrix& transform = graphicsLayer->transform();
@@ -93,11 +92,14 @@
     return layerObject;
 }
 
-static void maybeAddGraphicsLayer(GraphicsLayer* graphicsLayer, int nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers, bool forceRoot = false)
+void gatherGraphicsLayers(GraphicsLayer* root, HashMap<int, int>& layerIdToNodeIdMap, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
 {
-    if (!graphicsLayer)
-        return;
-    layers->addItem(buildObjectForLayer(graphicsLayer, nodeId, forceRoot));
+    int layerId = root->platformLayer()->id();
+    layers->addItem(buildObjectForLayer(root, layerIdToNodeIdMap.get(layerId)));
+    if (GraphicsLayer* replica = root->replicaLayer())
+        gatherGraphicsLayers(replica, layerIdToNodeIdMap, layers);
+    for (size_t i = 0, size = root->children().size(); i < size; ++i)
+        gatherGraphicsLayers(root->children()[i], layerIdToNodeIdMap, layers);
 }
 
 InspectorLayerTreeAgent::InspectorLayerTreeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorDOMAgent* domAgent, Page* page)
@@ -143,12 +145,6 @@
     m_instrumentingAgents->setInspectorLayerTreeAgent(0);
 }
 
-void InspectorLayerTreeAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
-{
-    if (loader->frame() != frame->page()->mainFrame())
-        return;
-}
-
 void InspectorLayerTreeAgent::layerTreeDidChange()
 {
     m_frontend->layerTreeDidChange();
@@ -156,13 +152,17 @@
 
 void InspectorLayerTreeAgent::getLayers(ErrorString* errorString, const int* nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
 {
+    LayerIdToNodeIdMap layerIdToNodeIdMap;
     layers = TypeBuilder::Array<TypeBuilder::LayerTree::Layer>::create();
 
-    RenderLayerCompositor* compositor = renderLayerCompositor(errorString);
-    if (!compositor)
+    RenderLayerCompositor* compositor = renderLayerCompositor();
+    if (!compositor || !compositor->inCompositingMode()) {
+        *errorString = "Not in the compositing mode";
         return;
+    }
     if (!nodeId) {
-        gatherLayersUsingRenderLayerHierarchy(errorString, compositor->rootRenderLayer(), layers);
+        buildLayerIdToNodeIdMap(errorString, compositor->rootRenderLayer(), layerIdToNodeIdMap);
+        gatherGraphicsLayers(compositor->rootGraphicsLayer(), layerIdToNodeIdMap, layers);
         return;
     }
     Node* node = m_instrumentingAgents->inspectorDOMAgent()->nodeForId(*nodeId);
@@ -175,46 +175,29 @@
         *errorString = "Node for provided node id doesn't have a renderer";
         return;
     }
-    gatherLayersUsingRenderObjectHierarchy(errorString, renderer, layers);
+    RenderLayer* enclosingLayer = renderer->enclosingLayer();
+    GraphicsLayer* enclosingGraphicsLayer = enclosingLayer->enclosingCompositingLayer()->backing()->childForSuperlayers();
+    buildLayerIdToNodeIdMap(errorString, enclosingLayer, layerIdToNodeIdMap);
+    gatherGraphicsLayers(enclosingGraphicsLayer, layerIdToNodeIdMap, layers);
 }
 
-void InspectorLayerTreeAgent::addRenderLayerBacking(ErrorString* errorString, RenderLayerBacking* layerBacking, Node* node, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
+void InspectorLayerTreeAgent::buildLayerIdToNodeIdMap(ErrorString* errorString, RenderLayer* root, LayerIdToNodeIdMap& layerIdToNodeIdMap)
 {
-    int nodeId = idForNode(errorString, node);
-    bool forceRoot = layerBacking->owningLayer()->isRootLayer();
-    if (layerBacking->ancestorClippingLayer()) {
-        maybeAddGraphicsLayer(layerBacking->ancestorClippingLayer(), nodeId, layers, forceRoot);
-        forceRoot = false;
+    if (root->isComposited()) {
+        if (Node* node = root->renderer()->generatingNode()) {
+            GraphicsLayer* graphicsLayer = root->backing()->childForSuperlayers();
+            layerIdToNodeIdMap.set(graphicsLayer->platformLayer()->id(), idForNode(errorString, node));
+        }
     }
-    maybeAddGraphicsLayer(layerBacking->graphicsLayer(), nodeId, layers, forceRoot);
-    maybeAddGraphicsLayer(layerBacking->clippingLayer(), nodeId, layers);
-    maybeAddGraphicsLayer(layerBacking->foregroundLayer(), nodeId, layers);
-    maybeAddGraphicsLayer(layerBacking->backgroundLayer(), nodeId, layers);
-    maybeAddGraphicsLayer(layerBacking->scrollingLayer(), nodeId, layers);
-    maybeAddGraphicsLayer(layerBacking->scrollingContentsLayer(), nodeId, layers);
-    maybeAddGraphicsLayer(layerBacking->layerForHorizontalScrollbar(), nodeId, layers);
-    maybeAddGraphicsLayer(layerBacking->layerForVerticalScrollbar(), nodeId, layers);
-}
-
-void InspectorLayerTreeAgent::gatherLayersUsingRenderObjectHierarchy(ErrorString* errorString, RenderObject* renderer, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
-{
-    if (renderer->hasLayer()) {
-        gatherLayersUsingRenderLayerHierarchy(errorString, toRenderLayerModelObject(renderer)->layer(), layers);
+    for (RenderLayer* child = root->firstChild(); child; child = child->nextSibling())
+        buildLayerIdToNodeIdMap(errorString, child, layerIdToNodeIdMap);
+    if (!root->renderer()->isRenderIFrame())
         return;
+    FrameView* childFrameView = toFrameView(toRenderWidget(root->renderer())->widget());
+    if (RenderView* childRenderView = childFrameView->renderView()) {
+        if (RenderLayerCompositor* childCompositor = childRenderView->compositor())
+            buildLayerIdToNodeIdMap(errorString, childCompositor->rootRenderLayer(), layerIdToNodeIdMap);
     }
-
-    for (renderer = renderer->firstChild(); renderer; renderer = renderer->nextSibling())
-        gatherLayersUsingRenderObjectHierarchy(errorString, renderer, layers);
-}
-
-void InspectorLayerTreeAgent::gatherLayersUsingRenderLayerHierarchy(ErrorString* errorString, RenderLayer* renderLayer, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
-{
-    if (renderLayer->isComposited()) {
-        Node* node = (renderLayer->isReflection() ? renderLayer->parent() : renderLayer)->renderer()->generatingNode();
-        addRenderLayerBacking(errorString, renderLayer->backing(), node, layers);
-    }
-    for (renderLayer = renderLayer->firstChild(); renderLayer; renderLayer = renderLayer->nextSibling())
-        gatherLayersUsingRenderLayerHierarchy(errorString, renderLayer, layers);
 }
 
 int InspectorLayerTreeAgent::idForNode(ErrorString* errorString, Node* node)
@@ -223,17 +206,15 @@
 
     int nodeId = domAgent->boundNodeId(node);
     if (!nodeId)
-        nodeId = domAgent->pushNodeToFrontend(errorString, domAgent->boundNodeId(node->document()), node);
+        nodeId = domAgent->pushNodeToFrontend(errorString, domAgent->boundNodeId(&node->document()), node);
 
     return nodeId;
 }
 
-RenderLayerCompositor* InspectorLayerTreeAgent::renderLayerCompositor(ErrorString* errorString)
+RenderLayerCompositor* InspectorLayerTreeAgent::renderLayerCompositor()
 {
     RenderView* renderView = m_page->mainFrame()->contentRenderer();
     RenderLayerCompositor* compositor = renderView ? renderView->compositor() : 0;
-    if (!compositor)
-        *errorString = "Not in the compositing mode";
     return compositor;
 }
 
@@ -241,6 +222,10 @@
 {
     if (root->platformLayer()->id() == layerId)
         return root;
+    if (root->replicaLayer()) {
+        if (GraphicsLayer* layer = findLayerById(root->replicaLayer(), layerId))
+            return layer;
+    }
     for (size_t i = 0, size = root->children().size(); i < size; ++i) {
         if (GraphicsLayer* layer = findLayerById(root->children()[i], layerId))
             return layer;
@@ -256,7 +241,7 @@
         *errorString = "Invalid layer id";
         return 0;
     }
-    RenderLayerCompositor* compositor = renderLayerCompositor(errorString);
+    RenderLayerCompositor* compositor = renderLayerCompositor();
     if (!compositor)
         return 0;
 
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.h b/Source/core/inspector/InspectorLayerTreeAgent.h
index 526dc71..9db42fd 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.h
+++ b/Source/core/inspector/InspectorLayerTreeAgent.h
@@ -60,7 +60,6 @@
     virtual void clearFrontend();
     virtual void restore();
 
-    void didCommitLoad(Frame*, DocumentLoader*);
     void layerTreeDidChange();
 
     // Called from the front-end.
@@ -70,16 +69,15 @@
     virtual void compositingReasons(ErrorString*, const String& layerId, RefPtr<TypeBuilder::Array<String> >&);
 
 private:
+    typedef HashMap<int, int> LayerIdToNodeIdMap;
+
     InspectorLayerTreeAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorDOMAgent*, Page*);
 
-    RenderLayerCompositor* renderLayerCompositor(ErrorString*);
+    RenderLayerCompositor* renderLayerCompositor();
     GraphicsLayer* layerById(ErrorString*, const String& layerId);
     int idForNode(ErrorString*, Node*);
 
-    void gatherLayersUsingRenderObjectHierarchy(ErrorString*, RenderObject*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
-    void gatherLayersUsingRenderLayerHierarchy(ErrorString*, RenderLayer*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
-    void gatherLayersUsingGraphicsLayerHierarchy(ErrorString*, GraphicsLayer*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
-    void addRenderLayerBacking(ErrorString*, RenderLayerBacking*, Node*, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
+    void buildLayerIdToNodeIdMap(ErrorString*, RenderLayer*, LayerIdToNodeIdMap&);
 
     InspectorFrontend::LayerTree* m_frontend;
     Page* m_page;
diff --git a/Source/core/inspector/InspectorOverlay.cpp b/Source/core/inspector/InspectorOverlay.cpp
index c81ac7f..e970566 100644
--- a/Source/core/inspector/InspectorOverlay.cpp
+++ b/Source/core/inspector/InspectorOverlay.cpp
@@ -141,7 +141,7 @@
 static bool buildNodeQuads(Node* node, Vector<FloatQuad>& quads)
 {
     RenderObject* renderer = node->renderer();
-    Frame* containingFrame = node->document()->frame();
+    Frame* containingFrame = node->document().frame();
 
     if (!renderer || !containingFrame)
         return false;
@@ -159,62 +159,64 @@
         return false;
     }
 
-    if (renderer->isBox() || renderer->isRenderInline()) {
-        LayoutRect contentBox;
-        LayoutRect paddingBox;
-        LayoutRect borderBox;
-        LayoutRect marginBox;
+    if (!renderer->isBox() && !renderer->isRenderInline())
+        return false;
 
-        if (renderer->isBox()) {
-            RenderBox* renderBox = toRenderBox(renderer);
+    LayoutRect contentBox;
+    LayoutRect paddingBox;
+    LayoutRect borderBox;
+    LayoutRect marginBox;
 
-            // RenderBox returns the "pure" content area box, exclusive of the scrollbars (if present), which also count towards the content area in CSS.
-            contentBox = renderBox->contentBoxRect();
-            contentBox.setWidth(contentBox.width() + renderBox->verticalScrollbarWidth());
-            contentBox.setHeight(contentBox.height() + renderBox->horizontalScrollbarHeight());
+    if (renderer->isBox()) {
+        RenderBox* renderBox = toRenderBox(renderer);
 
-            paddingBox = LayoutRect(contentBox.x() - renderBox->paddingLeft(), contentBox.y() - renderBox->paddingTop(),
-                    contentBox.width() + renderBox->paddingLeft() + renderBox->paddingRight(), contentBox.height() + renderBox->paddingTop() + renderBox->paddingBottom());
-            borderBox = LayoutRect(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(),
-                    paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom());
-            marginBox = LayoutRect(borderBox.x() - renderBox->marginLeft(), borderBox.y() - renderBox->marginTop(),
-                    borderBox.width() + renderBox->marginWidth(), borderBox.height() + renderBox->marginHeight());
-        } else {
-            RenderInline* renderInline = toRenderInline(renderer);
+        // RenderBox returns the "pure" content area box, exclusive of the scrollbars (if present), which also count towards the content area in CSS.
+        contentBox = renderBox->contentBoxRect();
+        contentBox.setWidth(contentBox.width() + renderBox->verticalScrollbarWidth());
+        contentBox.setHeight(contentBox.height() + renderBox->horizontalScrollbarHeight());
 
-            // RenderInline's bounding box includes paddings and borders, excludes margins.
-            borderBox = renderInline->linesBoundingBox();
-            paddingBox = LayoutRect(borderBox.x() + renderInline->borderLeft(), borderBox.y() + renderInline->borderTop(),
-                    borderBox.width() - renderInline->borderLeft() - renderInline->borderRight(), borderBox.height() - renderInline->borderTop() - renderInline->borderBottom());
-            contentBox = LayoutRect(paddingBox.x() + renderInline->paddingLeft(), paddingBox.y() + renderInline->paddingTop(),
-                    paddingBox.width() - renderInline->paddingLeft() - renderInline->paddingRight(), paddingBox.height() - renderInline->paddingTop() - renderInline->paddingBottom());
-            // Ignore marginTop and marginBottom for inlines.
-            marginBox = LayoutRect(borderBox.x() - renderInline->marginLeft(), borderBox.y(),
-                    borderBox.width() + renderInline->marginWidth(), borderBox.height());
-        }
+        paddingBox = LayoutRect(contentBox.x() - renderBox->paddingLeft(), contentBox.y() - renderBox->paddingTop(),
+            contentBox.width() + renderBox->paddingLeft() + renderBox->paddingRight(), contentBox.height() + renderBox->paddingTop() + renderBox->paddingBottom());
+        borderBox = LayoutRect(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(),
+            paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom());
+        marginBox = LayoutRect(borderBox.x() - renderBox->marginLeft(), borderBox.y() - renderBox->marginTop(),
+            borderBox.width() + renderBox->marginWidth(), borderBox.height() + renderBox->marginHeight());
+    } else {
+        RenderInline* renderInline = toRenderInline(renderer);
 
-        FloatQuad absContentQuad = renderer->localToAbsoluteQuad(FloatRect(contentBox));
-        FloatQuad absPaddingQuad = renderer->localToAbsoluteQuad(FloatRect(paddingBox));
-        FloatQuad absBorderQuad = renderer->localToAbsoluteQuad(FloatRect(borderBox));
-        FloatQuad absMarginQuad = renderer->localToAbsoluteQuad(FloatRect(marginBox));
-
-        contentsQuadToPage(mainView, containingView, absContentQuad);
-        contentsQuadToPage(mainView, containingView, absPaddingQuad);
-        contentsQuadToPage(mainView, containingView, absBorderQuad);
-        contentsQuadToPage(mainView, containingView, absMarginQuad);
-
-        quads.append(absMarginQuad);
-        quads.append(absBorderQuad);
-        quads.append(absPaddingQuad);
-        quads.append(absContentQuad);
+        // RenderInline's bounding box includes paddings and borders, excludes margins.
+        borderBox = renderInline->linesBoundingBox();
+        paddingBox = LayoutRect(borderBox.x() + renderInline->borderLeft(), borderBox.y() + renderInline->borderTop(),
+            borderBox.width() - renderInline->borderLeft() - renderInline->borderRight(), borderBox.height() - renderInline->borderTop() - renderInline->borderBottom());
+        contentBox = LayoutRect(paddingBox.x() + renderInline->paddingLeft(), paddingBox.y() + renderInline->paddingTop(),
+            paddingBox.width() - renderInline->paddingLeft() - renderInline->paddingRight(), paddingBox.height() - renderInline->paddingTop() - renderInline->paddingBottom());
+        // Ignore marginTop and marginBottom for inlines.
+        marginBox = LayoutRect(borderBox.x() - renderInline->marginLeft(), borderBox.y(),
+            borderBox.width() + renderInline->marginWidth(), borderBox.height());
     }
+
+    FloatQuad absContentQuad = renderer->localToAbsoluteQuad(FloatRect(contentBox));
+    FloatQuad absPaddingQuad = renderer->localToAbsoluteQuad(FloatRect(paddingBox));
+    FloatQuad absBorderQuad = renderer->localToAbsoluteQuad(FloatRect(borderBox));
+    FloatQuad absMarginQuad = renderer->localToAbsoluteQuad(FloatRect(marginBox));
+
+    contentsQuadToPage(mainView, containingView, absContentQuad);
+    contentsQuadToPage(mainView, containingView, absPaddingQuad);
+    contentsQuadToPage(mainView, containingView, absBorderQuad);
+    contentsQuadToPage(mainView, containingView, absMarginQuad);
+
+    quads.append(absMarginQuad);
+    quads.append(absBorderQuad);
+    quads.append(absPaddingQuad);
+    quads.append(absContentQuad);
+
     return true;
 }
 
 static void buildNodeHighlight(Node* node, const HighlightConfig& highlightConfig, Highlight* highlight)
 {
     RenderObject* renderer = node->renderer();
-    Frame* containingFrame = node->document()->frame();
+    Frame* containingFrame = node->document().frame();
 
     if (!renderer || !containingFrame)
         return;
@@ -441,7 +443,7 @@
     drawOverridesMessage();
 
     // Position DOM elements.
-    overlayPage()->mainFrame()->document()->recalcStyle(Node::Force);
+    overlayPage()->mainFrame()->document()->recalcStyle(Force);
     if (overlayView->needsLayout())
         overlayView->layout();
 
@@ -527,10 +529,10 @@
     RefPtr<JSONObject> highlightObject = buildObjectForHighlight(highlight);
 
     Node* node = m_highlightNode.get();
-    if (node->isElementNode() && m_nodeHighlightConfig.showInfo && node->renderer() && node->document()->frame()) {
+    if (node->isElementNode() && m_nodeHighlightConfig.showInfo && node->renderer() && node->document().frame()) {
         RefPtr<JSONObject> elementInfo = JSONObject::create();
         Element* element = toElement(node);
-        bool isXHTML = element->document()->isXHTMLDocument();
+        bool isXHTML = element->document().isXHTMLDocument();
         elementInfo->setString("tagName", isXHTML ? element->nodeName() : element->nodeName().lower());
         elementInfo->setString("idValue", element->getIdAttribute());
         HashSet<AtomicString> usedClassNames;
@@ -549,7 +551,7 @@
         }
 
         RenderObject* renderer = node->renderer();
-        Frame* containingFrame = node->document()->frame();
+        Frame* containingFrame = node->document().frame();
         FrameView* containingView = containingFrame->view();
         IntRect boundingBox = pixelSnappedIntRect(containingView->contentsToRootView(renderer->absoluteBoundingBoxRect()));
         RenderBoxModelObject* modelObject = renderer->isBoxModelObject() ? toRenderBoxModelObject(renderer) : 0;
@@ -631,18 +633,19 @@
     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::HandleScope handleScope;
+    v8::Isolate* isolate = frame->script()->isolate();
+    v8::HandleScope handleScope(isolate);
     v8::Handle<v8::Context> frameContext = frame->script()->currentWorldContext();
     v8::Context::Scope contextScope(frameContext);
-    v8::Handle<v8::Value> overlayHostObj = toV8(m_overlayHost.get(), v8::Handle<v8::Object>(), frameContext->GetIsolate());
+    v8::Handle<v8::Value> overlayHostObj = toV8(m_overlayHost.get(), v8::Handle<v8::Object>(), isolate);
     v8::Handle<v8::Object> global = frameContext->Global();
     global->Set(v8::String::New("InspectorOverlayHost"), overlayHostObj);
 
-#if OS(WINDOWS)
+#if OS(WIN)
     evaluateInOverlay("setPlatform", "windows");
-#elif OS(DARWIN)
+#elif OS(MACOSX)
     evaluateInOverlay("setPlatform", "mac");
-#elif OS(UNIX)
+#elif OS(POSIX)
     evaluateInOverlay("setPlatform", "linux");
 #endif
 
@@ -697,4 +700,3 @@
 }
 
 } // namespace WebCore
-
diff --git a/Source/core/inspector/InspectorOverlayPage.html b/Source/core/inspector/InspectorOverlayPage.html
index a41e3f7..fc150af 100644
--- a/Source/core/inspector/InspectorOverlayPage.html
+++ b/Source/core/inspector/InspectorOverlayPage.html
@@ -70,15 +70,15 @@
 }
 
 .controls-line {
-    display: -webkit-flex;
-    -webkit-justify-content: center;
+    display: flex;
+    justify-content: center;
     margin: 10px 0;
 }
 
 .message-box {
     padding: 2px 4px;
-    display: -webkit-flex;
-    -webkit-align-items: center;
+    display: flex;
+    align-items: center;
     cursor: default;
 }
 
diff --git a/Source/core/inspector/InspectorPageAgent.cpp b/Source/core/inspector/InspectorPageAgent.cpp
index 8103dc6..51f34a4 100644
--- a/Source/core/inspector/InspectorPageAgent.cpp
+++ b/Source/core/inspector/InspectorPageAgent.cpp
@@ -46,6 +46,7 @@
 #include "core/fetch/Resource.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/ScriptResource.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/ContentSearchUtils.h"
 #include "core/inspector/DOMPatchSupport.h"
@@ -60,7 +61,6 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
@@ -457,6 +457,12 @@
     frame->loader()->load(request);
 }
 
+void InspectorPageAgent::getNavigationHistory(ErrorString*, int*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::NavigationEntry> >&)
+{ }
+
+void InspectorPageAgent::navigateToHistoryEntry(ErrorString*, int)
+{ }
+
 static PassRefPtr<TypeBuilder::Page::Cookie> buildObjectForCookie(const Cookie& cookie)
 {
     return TypeBuilder::Page::Cookie::create()
@@ -655,7 +661,7 @@
         *errorString = "No Document instance to set HTML for";
         return;
     }
-    DOMPatchSupport::patchDocument(document, html);
+    DOMPatchSupport::patchDocument(*document, html);
 }
 
 void InspectorPageAgent::setDeviceMetricsOverride(ErrorString* errorString, int width, int height, double fontScaleFactor, bool fitWindow)
@@ -830,6 +836,11 @@
     m_frontend->frameNavigated(buildObjectForFrame(loader->frame()));
 }
 
+void InspectorPageAgent::frameAttachedToParent(Frame* frame)
+{
+    m_frontend->frameAttached(frameId(frame));
+}
+
 void InspectorPageAgent::frameDetachedFromParent(Frame* frame)
 {
     HashMap<Frame*, String>::iterator iterator = m_frameToIdentifier.find(frame);
@@ -1264,12 +1275,12 @@
     mainFrame->view()->updateCompositingLayersAfterStyleChange();
 }
 
-void InspectorPageAgent::captureScreenshot(ErrorString*, const String*, const int*, const double*, String*)
+void InspectorPageAgent::captureScreenshot(ErrorString*, const String*, const int*, const int*, const int*, String*, double*, double*, RefPtr<TypeBuilder::DOM::Rect>&)
 {
     // Handled on the browser level.
 }
 
-void InspectorPageAgent::startScreencast(ErrorString*, const String*, const int*, const double*)
+void InspectorPageAgent::startScreencast(ErrorString*, const String*, const int*, const int*, const int*)
 {
     // Handled on the browser level.
 }
diff --git a/Source/core/inspector/InspectorPageAgent.h b/Source/core/inspector/InspectorPageAgent.h
index c07e03a..8ae2721 100644
--- a/Source/core/inspector/InspectorPageAgent.h
+++ b/Source/core/inspector/InspectorPageAgent.h
@@ -93,6 +93,8 @@
     virtual void removeScriptToEvaluateOnLoad(ErrorString*, const String& identifier);
     virtual void reload(ErrorString*, const bool* optionalIgnoreCache, const String* optionalScriptToEvaluateOnLoad, const String* optionalScriptPreprocessor);
     virtual void navigate(ErrorString*, const String& url);
+    virtual void getNavigationHistory(ErrorString*, int*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::NavigationEntry> >&);
+    virtual void navigateToHistoryEntry(ErrorString*, int);
     virtual void getCookies(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::Cookie> >& cookies, WTF::String* cookiesString);
     virtual void deleteCookie(ErrorString*, const String& cookieName, const String& url);
     virtual void getResourceTree(ErrorString*, RefPtr<TypeBuilder::Page::FrameResourceTree>&);
@@ -115,8 +117,8 @@
     virtual void setTouchEmulationEnabled(ErrorString*, bool);
     virtual void setEmulatedMedia(ErrorString*, const String&);
     virtual void setForceCompositingMode(ErrorString*, bool force);
-    virtual void captureScreenshot(ErrorString*, const String* format, const int* quality, const double* scale, String* data);
-    virtual void startScreencast(ErrorString*, const String* format, const int* quality, const double* scale);
+    virtual void captureScreenshot(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight, String* data, double* deviceScaleFactor, double* pageScaleFactor, RefPtr<TypeBuilder::DOM::Rect>&);
+    virtual void startScreencast(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight);
     virtual void stopScreencast(ErrorString*);
     virtual void handleJavaScriptDialog(ErrorString*, bool accept, const String* promptText);
     virtual void setShowViewportSizeOnResize(ErrorString*, bool show, const bool* showGrid);
@@ -133,6 +135,7 @@
     void loadEventFired(Frame*);
     void childDocumentOpened(Document*);
     void didCommitLoad(Frame*, DocumentLoader*);
+    void frameAttachedToParent(Frame*);
     void frameDetachedFromParent(Frame*);
     void loaderDetachedFromFrame(DocumentLoader*);
     void frameStartedLoading(Frame*);
diff --git a/Source/core/inspector/InspectorResourceAgent.cpp b/Source/core/inspector/InspectorResourceAgent.cpp
index 9036b6a..fad8d67 100644
--- a/Source/core/inspector/InspectorResourceAgent.cpp
+++ b/Source/core/inspector/InspectorResourceAgent.cpp
@@ -339,7 +339,7 @@
     Resource* cachedResource = 0;
     if (resourceLoader && !isNotModified)
         cachedResource = resourceLoader->cachedResource();
-    if (!cachedResource)
+    if (!cachedResource || cachedResource->type() == Resource::MainResource)
         cachedResource = InspectorPageAgent::cachedResource(loader->frame(), response.url());
 
     if (cachedResource) {
diff --git a/Source/core/inspector/InspectorStyleSheet.cpp b/Source/core/inspector/InspectorStyleSheet.cpp
index ff1fe39..56d40a9 100644
--- a/Source/core/inspector/InspectorStyleSheet.cpp
+++ b/Source/core/inspector/InspectorStyleSheet.cpp
@@ -143,7 +143,7 @@
 static PassOwnPtr<CSSParser> createCSSParser(Document* document)
 {
     UseCounter* counter = 0;
-    return adoptPtr(new CSSParser(document ? CSSParserContext(document) : strictCSSParserContext(), counter));
+    return adoptPtr(new CSSParser(document ? CSSParserContext(*document) : strictCSSParserContext(), counter));
 }
 
 namespace {
@@ -1758,7 +1758,7 @@
 
 Document* InspectorStyleSheetForInlineStyle::ownerDocument() const
 {
-    return m_element->document();
+    return &m_element->document();
 }
 
 bool InspectorStyleSheetForInlineStyle::ensureParsedDataReady()
@@ -1815,8 +1815,8 @@
 
     RefPtr<MutableStylePropertySet> tempDeclaration = MutableStylePropertySet::create();
     RuleSourceDataList ruleSourceDataResult;
-    StyleSheetHandler handler(m_styleText, m_element->document(), m_element->document()->elementSheet()->contents(), &ruleSourceDataResult);
-    createCSSParser(m_element->document())->parseDeclaration(tempDeclaration.get(), m_styleText, &handler, m_element->document()->elementSheet()->contents());
+    StyleSheetHandler handler(m_styleText, &m_element->document(), m_element->document().elementSheet()->contents(), &ruleSourceDataResult);
+    createCSSParser(&m_element->document())->parseDeclaration(tempDeclaration.get(), m_styleText, &handler, m_element->document().elementSheet()->contents());
     return ruleSourceDataResult.first().release();
 }
 
diff --git a/Source/core/inspector/InspectorTimelineAgent.cpp b/Source/core/inspector/InspectorTimelineAgent.cpp
index 51d2c71..96b6414 100644
--- a/Source/core/inspector/InspectorTimelineAgent.cpp
+++ b/Source/core/inspector/InspectorTimelineAgent.cpp
@@ -153,8 +153,7 @@
 
 void TimelineTimeConverter::reset()
 {
-    m_startTimeMs = currentTime() * 1000;
-    m_timestampsBaseMs = monotonicallyIncreasingTime() * 1000;
+    m_startOffset = monotonicallyIncreasingTime() - currentTime();
 }
 
 void InspectorTimelineAgent::pushGCEventRecords()
@@ -165,9 +164,9 @@
     GCEvents events = m_gcEvents;
     m_gcEvents.clear();
     for (GCEvents::iterator i = events.begin(); i != events.end(); ++i) {
-        RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(m_timeConverter.toProtocolTimestamp(i->startTime), m_maxCallStackDepth, TimelineRecordType::GCEvent);
+        RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(m_timeConverter.fromMonotonicallyIncreasingTime(i->startTime), m_maxCallStackDepth, TimelineRecordType::GCEvent);
         record->setObject("data", TimelineRecordFactory::createGCEventData(i->collectedBytes));
-        record->setNumber("endTime", m_timeConverter.toProtocolTimestamp(i->endTime));
+        record->setNumber("endTime", m_timeConverter.fromMonotonicallyIncreasingTime(i->endTime));
         addRecordToTimeline(record.release());
     }
 }
@@ -219,7 +218,6 @@
     m_state->setBoolean(TimelineAgentState::includeDomCounters, includeDomCounters && *includeDomCounters);
     m_state->setBoolean(TimelineAgentState::includeNativeMemoryStatistics, includeNativeMemoryStatistics && *includeNativeMemoryStatistics);
     m_timeConverter.reset();
-    m_frontend->timelineStarted(m_timeConverter.timestampsBaseMs(), m_timeConverter.startTimeMs());
 
     m_instrumentingAgents->setInspectorTimelineAgent(this);
     ScriptGCEvent::addEventListener(this);
@@ -383,6 +381,17 @@
     didCompleteCurrentRecord(TimelineRecordType::Paint);
 }
 
+void InspectorTimelineAgent::willPaintImage(RenderImage* renderImage)
+{
+    ASSERT(!m_imageBeingPainted);
+    m_imageBeingPainted = renderImage;
+}
+
+void InspectorTimelineAgent::didPaintImage()
+{
+    m_imageBeingPainted = 0;
+}
+
 void InspectorTimelineAgent::willScrollLayer(RenderObject* renderer)
 {
     pushCurrentRecord(TimelineRecordFactory::createLayerData(idForNode(renderer->generatingNode())), TimelineRecordType::ScrollLayer, false, renderer->frame());
@@ -395,7 +404,10 @@
 
 void InspectorTimelineAgent::willDecodeImage(const String& imageType)
 {
-    pushCurrentRecord(TimelineRecordFactory::createDecodeImageData(imageType), TimelineRecordType::DecodeImage, true, 0);
+    RefPtr<JSONObject> data = TimelineRecordFactory::createDecodeImageData(imageType);
+    if (m_imageBeingPainted)
+        populateImageDetails(data.get(), *m_imageBeingPainted);
+    pushCurrentRecord(data, TimelineRecordType::DecodeImage, true, 0);
 }
 
 void InspectorTimelineAgent::didDecodeImage()
@@ -405,7 +417,10 @@
 
 void InspectorTimelineAgent::willResizeImage(bool shouldCache)
 {
-    pushCurrentRecord(TimelineRecordFactory::createResizeImageData(shouldCache), TimelineRecordType::ResizeImage, true, 0);
+    RefPtr<JSONObject> data = TimelineRecordFactory::createResizeImageData(shouldCache);
+    if (m_imageBeingPainted)
+        populateImageDetails(data.get(), *m_imageBeingPainted);
+    pushCurrentRecord(data, TimelineRecordType::ResizeImage, true, 0);
 }
 
 void InspectorTimelineAgent::didResizeImage()
@@ -693,6 +708,12 @@
     record->setString("frameId", frameId);
 }
 
+void InspectorTimelineAgent::populateImageDetails(JSONObject* data, const RenderImage& renderImage)
+{
+    const ImageResource* resource = renderImage.cachedImage();
+    TimelineRecordFactory::appendImageDetails(data, idForNode(renderImage.generatingNode()), resource ? resource->url().string() : "");
+}
+
 void InspectorTimelineAgent::didCompleteCurrentRecord(const String& type)
 {
     // An empty stack could merely mean that the timeline agent was turned on in the middle of
@@ -731,6 +752,7 @@
     , m_weakFactory(this)
     , m_styleRecalcElementCounter(0)
     , m_layerTreeId(0)
+    , m_imageBeingPainted(0)
 {
 }
 
@@ -806,9 +828,9 @@
         m_domAgent->releaseBackendNodeIds(&unused, BackendNodeIdGroup);
 }
 
-double InspectorTimelineAgent::timestamp() const
+double InspectorTimelineAgent::timestamp()
 {
-    return m_timeConverter.toProtocolTimestamp(WTF::monotonicallyIncreasingTime());
+    return m_timeConverter.fromMonotonicallyIncreasingTime(WTF::monotonicallyIncreasingTime());
 }
 
 Page* InspectorTimelineAgent::page()
diff --git a/Source/core/inspector/InspectorTimelineAgent.h b/Source/core/inspector/InspectorTimelineAgent.h
index e54ebc6..769f34f 100644
--- a/Source/core/inspector/InspectorTimelineAgent.h
+++ b/Source/core/inspector/InspectorTimelineAgent.h
@@ -62,6 +62,7 @@
 class KURL;
 class Node;
 class Page;
+class RenderImage;
 class RenderObject;
 class ResourceError;
 class ResourceLoader;
@@ -86,18 +87,14 @@
 class TimelineTimeConverter {
 public:
     TimelineTimeConverter()
-        : m_timestampsBaseMs(0)
-        , m_startTimeMs(0)
+        : m_startOffset(0)
     {
     }
-    double toProtocolTimestamp(double seconds) const  { return seconds * 1000.0 - m_timestampsBaseMs; }
-    double startTimeMs() const { return m_startTimeMs; }
-    double timestampsBaseMs() const { return m_timestampsBaseMs; }
+    double fromMonotonicallyIncreasingTime(double time) const  { return (time - m_startOffset) * 1000.0; }
     void reset();
 
 private:
-    double m_timestampsBaseMs;
-    double m_startTimeMs;
+    double m_startOffset;
 };
 
 class InspectorTimelineAgent
@@ -153,6 +150,9 @@
     void willPaint(RenderObject*);
     void didPaint(RenderObject*, GraphicsContext*, const LayoutRect&);
 
+    void willPaintImage(RenderImage*);
+    void didPaintImage();
+
     void willScrollLayer(RenderObject*);
     void didScrollLayer();
 
@@ -237,14 +237,14 @@
     void appendRecord(PassRefPtr<JSONObject> data, const String& type, bool captureCallStack, Frame*);
     void pushCurrentRecord(PassRefPtr<JSONObject>, const String& type, bool captureCallStack, Frame*, bool hasLowLevelDetails = false);
 
-    void setDOMCounters(TypeBuilder::Timeline::TimelineEvent* record);
-    void setNativeHeapStatistics(TypeBuilder::Timeline::TimelineEvent* record);
+    void setDOMCounters(TypeBuilder::Timeline::TimelineEvent*);
     void setFrameIdentifier(JSONObject* record, Frame*);
+    void populateImageDetails(JSONObject* data, const RenderImage&);
+
     void pushGCEventRecords();
 
     void didCompleteCurrentRecord(const String& type);
 
-    void setHeapSizeStatistics(JSONObject* record);
     void commitFrameRecord();
 
     void addRecordToTimeline(PassRefPtr<JSONObject>);
@@ -256,7 +256,7 @@
     long long idForNode(Node*);
     void releaseNodeIds();
 
-    double timestamp() const;
+    double timestamp();
     Page* page();
 
     InspectorPageAgent* m_pageAgent;
@@ -290,6 +290,7 @@
     RefPtr<TimelineTraceEventProcessor> m_traceEventProcessor;
     unsigned m_styleRecalcElementCounter;
     int m_layerTreeId;
+    RenderImage* m_imageBeingPainted;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/NetworkResourcesData.cpp b/Source/core/inspector/NetworkResourcesData.cpp
index f5c8abe..dab7c31 100644
--- a/Source/core/inspector/NetworkResourcesData.cpp
+++ b/Source/core/inspector/NetworkResourcesData.cpp
@@ -31,7 +31,7 @@
 
 #include "core/dom/DOMImplementation.h"
 #include "core/fetch/Resource.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/network/ResourceResponse.h"
 
diff --git a/Source/core/inspector/NetworkResourcesData.h b/Source/core/inspector/NetworkResourcesData.h
index d51b220..3ed6f70 100644
--- a/Source/core/inspector/NetworkResourcesData.h
+++ b/Source/core/inspector/NetworkResourcesData.h
@@ -29,8 +29,8 @@
 #ifndef NetworkResourcesData_h
 #define NetworkResourcesData_h
 
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/inspector/InspectorPageAgent.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/platform/network/HTTPHeaderMap.h"
 #include "weborigin/KURL.h"
 #include "wtf/Deque.h"
diff --git a/Source/core/inspector/PageDebuggerAgent.cpp b/Source/core/inspector/PageDebuggerAgent.cpp
index dc1b432..b306986 100644
--- a/Source/core/inspector/PageDebuggerAgent.cpp
+++ b/Source/core/inspector/PageDebuggerAgent.cpp
@@ -38,6 +38,7 @@
 #include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InstrumentingAgents.h"
+#include "core/loader/DocumentLoader.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/PageConsole.h"
@@ -155,5 +156,12 @@
     return m_pageScriptDebugServer->preprocess(frame, sourceCode);
 }
 
+void PageDebuggerAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
+{
+    Frame* mainFrame = frame->page()->mainFrame();
+    if (loader->frame() == mainFrame)
+        pageDidCommitLoad();
+}
+
 } // namespace WebCore
 
diff --git a/Source/core/inspector/PageDebuggerAgent.h b/Source/core/inspector/PageDebuggerAgent.h
index 161b55f..fa66819 100644
--- a/Source/core/inspector/PageDebuggerAgent.h
+++ b/Source/core/inspector/PageDebuggerAgent.h
@@ -37,6 +37,7 @@
 
 namespace WebCore {
 
+class DocumentLoader;
 class InspectorOverlay;
 class InspectorPageAgent;
 class Page;
@@ -55,6 +56,7 @@
     void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
     String preprocessEventListener(Frame*, const String& source, const String& url, const String& functionName);
     PassOwnPtr<ScriptSourceCode> preprocess(Frame*, const ScriptSourceCode&);
+    void didCommitLoad(Frame*, DocumentLoader*);
 
 protected:
     virtual void enable();
diff --git a/Source/core/inspector/ScriptCallFrame.cpp b/Source/core/inspector/ScriptCallFrame.cpp
index e6d2f62..4e5989e 100644
--- a/Source/core/inspector/ScriptCallFrame.cpp
+++ b/Source/core/inspector/ScriptCallFrame.cpp
@@ -33,8 +33,9 @@
 
 namespace WebCore {
 
-ScriptCallFrame::ScriptCallFrame(const String& functionName, const String& scriptName, unsigned lineNumber, unsigned column)
+ScriptCallFrame::ScriptCallFrame(const String& functionName, const String& scriptId, const String& scriptName, unsigned lineNumber, unsigned column)
     : m_functionName(functionName)
+    , m_scriptId(scriptId)
     , m_scriptName(scriptName)
     , m_lineNumber(lineNumber)
     , m_column(column)
@@ -48,6 +49,7 @@
 bool ScriptCallFrame::isEqual(const ScriptCallFrame& o) const
 {
     return m_functionName == o.m_functionName
+        && m_scriptId == o.m_scriptId
         && m_scriptName == o.m_scriptName
         && m_lineNumber == o.m_lineNumber;
 }
@@ -56,6 +58,7 @@
 {
     return TypeBuilder::Console::CallFrame::create()
         .setFunctionName(m_functionName)
+        .setScriptId(m_scriptId)
         .setUrl(m_scriptName)
         .setLineNumber(m_lineNumber)
         .setColumnNumber(m_column)
diff --git a/Source/core/inspector/ScriptCallFrame.h b/Source/core/inspector/ScriptCallFrame.h
index 48745f9..021e66d 100644
--- a/Source/core/inspector/ScriptCallFrame.h
+++ b/Source/core/inspector/ScriptCallFrame.h
@@ -39,10 +39,11 @@
 
 class ScriptCallFrame  {
 public:
-    ScriptCallFrame(const String& functionName, const String& scriptName, unsigned lineNumber, unsigned column = 0);
+    ScriptCallFrame(const String& functionName, const String& scriptId, const String& scriptName, unsigned lineNumber, unsigned column = 0);
     ~ScriptCallFrame();
 
     const String& functionName() const { return m_functionName; }
+    const String& scriptId() const { return m_scriptId; }
     const String& sourceURL() const { return m_scriptName; }
     unsigned lineNumber() const { return m_lineNumber; }
     unsigned columnNumber() const { return m_column; }
@@ -53,6 +54,7 @@
 
 private:
     String m_functionName;
+    String m_scriptId;
     String m_scriptName;
     unsigned m_lineNumber;
     unsigned m_column;
diff --git a/Source/core/inspector/ScriptProfile.cpp b/Source/core/inspector/ScriptProfile.cpp
index 5db3af7..7894f80 100644
--- a/Source/core/inspector/ScriptProfile.cpp
+++ b/Source/core/inspector/ScriptProfile.cpp
@@ -45,7 +45,7 @@
 
 String ScriptProfile::title() const
 {
-    v8::HandleScope scope;
+    v8::HandleScope scope(v8::Isolate::GetCurrent());
     return toWebCoreString(m_profile->GetTitle());
 }
 
@@ -71,7 +71,7 @@
 
 static PassRefPtr<TypeBuilder::Profiler::CPUProfileNode> buildInspectorObjectFor(const v8::CpuProfileNode* node)
 {
-    v8::HandleScope handleScope;
+    v8::HandleScope handleScope(v8::Isolate::GetCurrent());
 
     RefPtr<TypeBuilder::Array<TypeBuilder::Profiler::CPUProfileNode> > children = TypeBuilder::Array<TypeBuilder::Profiler::CPUProfileNode>::create();
     const int childrenCount = node->GetChildrenCount();
@@ -87,7 +87,8 @@
         .setLineNumber(node->GetLineNumber())
         .setHitCount(node->GetHitCount())
         .setCallUID(node->GetCallUid())
-        .setChildren(children.release());
+        .setChildren(children.release())
+        .setDeoptReason(node->GetBailoutReason());
     result->setId(node->GetNodeId());
     return result.release();
 }
diff --git a/Source/core/inspector/TimelineRecordFactory.cpp b/Source/core/inspector/TimelineRecordFactory.cpp
index 35f2ee3..75badf8 100644
--- a/Source/core/inspector/TimelineRecordFactory.cpp
+++ b/Source/core/inspector/TimelineRecordFactory.cpp
@@ -261,5 +261,13 @@
     data->setNumber("elementCount", elementCount);
 }
 
+void TimelineRecordFactory::appendImageDetails(JSONObject* data, long long imageElementId, const String& url)
+{
+    if (imageElementId)
+        data->setNumber("elementId", imageElementId);
+    if (!url.isEmpty())
+        data->setString("url", url);
+}
+
 } // namespace WebCore
 
diff --git a/Source/core/inspector/TimelineRecordFactory.h b/Source/core/inspector/TimelineRecordFactory.h
index f128fa9..bb2df6a 100644
--- a/Source/core/inspector/TimelineRecordFactory.h
+++ b/Source/core/inspector/TimelineRecordFactory.h
@@ -98,6 +98,8 @@
 
         static void appendStyleRecalcDetails(JSONObject* data, unsigned elementCount);
 
+        static void appendImageDetails(JSONObject* data, long long imageElementId, const String& url);
+
         static inline PassRefPtr<JSONObject> createWebSocketCreateData(unsigned long identifier, const KURL& url, const String& protocol)
         {
             RefPtr<JSONObject> data = JSONObject::create();
diff --git a/Source/core/inspector/TimelineTraceEventProcessor.cpp b/Source/core/inspector/TimelineTraceEventProcessor.cpp
index c6537c1..ba28720 100644
--- a/Source/core/inspector/TimelineTraceEventProcessor.cpp
+++ b/Source/core/inspector/TimelineTraceEventProcessor.cpp
@@ -266,13 +266,13 @@
 void TimelineTraceEventProcessor::onPaintSetupBegin(const TraceEvent& event)
 {
     ASSERT(!m_paintSetupStart);
-    m_paintSetupStart = m_timeConverter.toProtocolTimestamp(event.timestamp());
+    m_paintSetupStart = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
 }
 
 void TimelineTraceEventProcessor::onPaintSetupEnd(const TraceEvent& event)
 {
     ASSERT(m_paintSetupStart);
-    m_paintSetupEnd = m_timeConverter.toProtocolTimestamp(event.timestamp());
+    m_paintSetupEnd = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
 }
 
 void TimelineTraceEventProcessor::onRasterTaskBegin(const TraceEvent& event)
@@ -293,7 +293,7 @@
     if (!state.inKnownLayerTask)
         return;
     ASSERT(state.recordStack.isOpenRecordOfType(TimelineRecordType::Rasterize));
-    state.recordStack.closeScopedRecord(m_timeConverter.toProtocolTimestamp(event.timestamp()));
+    state.recordStack.closeScopedRecord(m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp()));
     leaveLayerTask(state);
 }
 
@@ -336,7 +336,7 @@
     if (!state.inKnownLayerTask)
         return;
     ASSERT(state.recordStack.isOpenRecordOfType(TimelineRecordType::DecodeImage));
-    state.recordStack.closeScopedRecord(m_timeConverter.toProtocolTimestamp(event.timestamp()));
+    state.recordStack.closeScopedRecord(m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp()));
 }
 
 void TimelineTraceEventProcessor::onLayerDeleted(const TraceEvent& event)
@@ -370,7 +370,7 @@
 
 PassRefPtr<JSONObject> TimelineTraceEventProcessor::createRecord(const TraceEvent& event, const String& recordType, PassRefPtr<JSONObject> data)
 {
-    double startTime = m_timeConverter.toProtocolTimestamp(event.timestamp());
+    double startTime = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
     RefPtr<JSONObject> record = TimelineRecordFactory::createBackgroundRecord(startTime, String::number(event.threadIdentifier()));
     record->setString("type", recordType);
     record->setObject("data", data ? data : JSONObject::create());
diff --git a/Source/core/inspector_overlay_page.target.darwin-arm.mk b/Source/core/inspector_overlay_page.target.darwin-arm.mk
index ca2f374..fcef9cd 100644
--- a/Source/core/inspector_overlay_page.target.darwin-arm.mk
+++ b/Source/core/inspector_overlay_page.target.darwin-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.darwin-mips.mk b/Source/core/inspector_overlay_page.target.darwin-mips.mk
index ca2f374..fcef9cd 100644
--- a/Source/core/inspector_overlay_page.target.darwin-mips.mk
+++ b/Source/core/inspector_overlay_page.target.darwin-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.darwin-x86.mk b/Source/core/inspector_overlay_page.target.darwin-x86.mk
index ca2f374..fcef9cd 100644
--- a/Source/core/inspector_overlay_page.target.darwin-x86.mk
+++ b/Source/core/inspector_overlay_page.target.darwin-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.linux-arm.mk b/Source/core/inspector_overlay_page.target.linux-arm.mk
index ca2f374..fcef9cd 100644
--- a/Source/core/inspector_overlay_page.target.linux-arm.mk
+++ b/Source/core/inspector_overlay_page.target.linux-arm.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.linux-mips.mk b/Source/core/inspector_overlay_page.target.linux-mips.mk
index ca2f374..fcef9cd 100644
--- a/Source/core/inspector_overlay_page.target.linux-mips.mk
+++ b/Source/core/inspector_overlay_page.target.linux-mips.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/inspector_overlay_page.target.linux-x86.mk b/Source/core/inspector_overlay_page.target.linux-x86.mk
index ca2f374..fcef9cd 100644
--- a/Source/core/inspector_overlay_page.target.linux-x86.mk
+++ b/Source/core/inspector_overlay_page.target.linux-x86.mk
@@ -18,9 +18,9 @@
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/xxd.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating $(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h from inspector/InspectorOverlayPage.html ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl InspectorOverlayPage_html inspector/InspectorOverlayPage.html "$(gyp_shared_intermediate_dir)/blink/InspectorOverlayPage.h"
 
 
 
diff --git a/Source/core/loader/CrossOriginPreflightResultCache.cpp b/Source/core/loader/CrossOriginPreflightResultCache.cpp
index d137440..869076e 100644
--- a/Source/core/loader/CrossOriginPreflightResultCache.cpp
+++ b/Source/core/loader/CrossOriginPreflightResultCache.cpp
@@ -27,7 +27,7 @@
 #include "config.h"
 #include "core/loader/CrossOriginPreflightResultCache.h"
 
-#include "core/loader/CrossOriginAccessControl.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/platform/network/ResourceResponse.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/MainThread.h"
diff --git a/Source/core/loader/DocumentLoader.cpp b/Source/core/loader/DocumentLoader.cpp
index 77a3197..29bea9b 100644
--- a/Source/core/loader/DocumentLoader.cpp
+++ b/Source/core/loader/DocumentLoader.cpp
@@ -36,16 +36,17 @@
 #include "core/dom/Document.h"
 #include "core/dom/DocumentParser.h"
 #include "core/dom/Event.h"
+#include "core/fetch/FetchContext.h"
 #include "core/fetch/MemoryCache.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/ResourceLoader.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/DocumentWriter.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/SinkDocument.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
 #include "core/loader/archive/ArchiveResourceCollection.h"
@@ -66,24 +67,6 @@
 
 namespace WebCore {
 
-static void cancelAll(const ResourceLoaderSet& loaders)
-{
-    Vector<RefPtr<ResourceLoader> > loadersCopy;
-    copyToVector(loaders, loadersCopy);
-    size_t size = loadersCopy.size();
-    for (size_t i = 0; i < size; ++i)
-        loadersCopy[i]->cancel();
-}
-
-static void setAllDefersLoading(const ResourceLoaderSet& loaders, bool defers)
-{
-    Vector<RefPtr<ResourceLoader> > loadersCopy;
-    copyToVector(loaders, loadersCopy);
-    size_t size = loadersCopy.size();
-    for (size_t i = 0; i < size; ++i)
-        loadersCopy[i]->setDefersLoading(defers);
-}
-
 static bool isArchiveMIMEType(const String& mimeType)
 {
     return mimeType == "multipart/related";
@@ -208,9 +191,7 @@
 {
     ASSERT(!error.isNull());
     ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading());
-
     m_applicationCacheHost->failedLoadingMainResource();
-
     if (!frameLoader())
         return;
     setMainDocumentError(error);
@@ -242,9 +223,6 @@
             m_frame->loader()->stopLoading();
     }
 
-    // Always cancel multipart loaders
-    cancelAll(m_multipartResourceLoaders);
-
     clearArchiveResources();
 
     if (!loading)
@@ -253,7 +231,7 @@
     if (isLoadingMainResource()) {
         // Stop the main resource loader and let it send the cancelled message.
         cancelMainResourceLoad(ResourceError::cancelledError(m_request.url()));
-    } else if (!m_resourceLoaders.isEmpty()) {
+    } else if (m_fetcher->isFetching()) {
         // The main resource loader already finished loading. Set the cancelled error on the
         // document and let the resourceLoaders send individual cancelled messages below.
         setMainDocumentError(ResourceError::cancelledError(m_request.url()));
@@ -263,7 +241,7 @@
         mainReceivedError(ResourceError::cancelledError(m_request.url()));
     }
 
-    stopLoadingSubresources();
+    m_fetcher->stopFetching();
 }
 
 void DocumentLoader::commitIfReady()
@@ -279,7 +257,7 @@
     if (document() && document()->hasActiveParser())
         return true;
 
-    return isLoadingMainResource() || !m_resourceLoaders.isEmpty();
+    return isLoadingMainResource() || m_fetcher->isFetching();
 }
 
 void DocumentLoader::notifyFinished(Resource* resource)
@@ -304,7 +282,7 @@
     RefPtr<DocumentLoader> protect(this);
 
     if (m_identifierForLoadWithoutResourceLoader) {
-        frameLoader()->notifier()->dispatchDidFinishLoading(this, m_identifierForLoadWithoutResourceLoader, finishTime);
+        m_frame->fetchContext().dispatchDidFinishLoading(this, m_identifierForLoadWithoutResourceLoader, finishTime);
         m_identifierForLoadWithoutResourceLoader = 0;
     }
 
@@ -346,11 +324,8 @@
     clearMainResourceHandle();
 }
 
-bool DocumentLoader::isPostOrRedirectAfterPost(const ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
+bool DocumentLoader::isRedirectAfterPost(const ResourceRequest& newRequest, const ResourceResponse& redirectResponse)
 {
-    if (newRequest.httpMethod() == "POST")
-        return true;
-
     int status = redirectResponse.httpStatusCode();
     if (((status >= 301 && status <= 303) || status == 307)
         && m_originalRequest.httpMethod() == "POST")
@@ -395,7 +370,7 @@
 
     // If we're loading content into a subframe, check against the parent's Content Security Policy
     // and kill the load if that check fails.
-    if (m_frame->ownerElement() && !m_frame->ownerElement()->document()->contentSecurityPolicy()->allowChildFrameFromSource(request.url()))
+    if (m_frame->ownerElement() && !m_frame->ownerElement()->document().contentSecurityPolicy()->allowChildFrameFromSource(request.url()))
         return false;
 
     NavigationPolicy policy = NavigationPolicyCurrentTab;
@@ -456,8 +431,7 @@
     // If we're fielding a redirect in response to a POST, force a load from origin, since
     // this is a common site technique to return to a page viewing some data that the POST
     // just modified.
-    // Also, POST requests always load from origin, but this does not affect subresources.
-    if (newRequest.cachePolicy() == UseProtocolCachePolicy && isPostOrRedirectAfterPost(newRequest, redirectResponse))
+    if (newRequest.cachePolicy() == UseProtocolCachePolicy && isRedirectAfterPost(newRequest, redirectResponse))
         newRequest.setCachePolicy(ReloadIgnoringCacheData);
 
     Frame* parent = m_frame->tree()->parent();
@@ -558,7 +532,7 @@
         m_mainResource->setDataBufferingPolicy(BufferData);
 
     if (m_identifierForLoadWithoutResourceLoader)
-        frameLoader()->notifier()->dispatchDidReceiveResponse(this, m_identifierForLoadWithoutResourceLoader, m_response, 0);
+        m_frame->fetchContext().dispatchDidReceiveResponse(this, m_identifierForLoadWithoutResourceLoader, m_response, 0);
 
     if (!shouldContinueForResponse()) {
         InspectorInstrumentation::continueWithPolicyIgnore(m_frame, this, m_mainResource->identifier(), m_response);
@@ -568,15 +542,11 @@
 
     if (m_response.isHTTP()) {
         int status = m_response.httpStatusCode();
-        if (status < 200 || status >= 300) {
-            bool hostedByObject = frameLoader()->isHostedByObjectElement();
-
-            frameLoader()->handleFallbackContent();
+        if ((status < 200 || status >= 300) && m_frame->ownerElement() && m_frame->ownerElement()->isObjectElement()) {
+            m_frame->ownerElement()->renderFallbackContent();
             // object elements are no longer rendered after we fallback, so don't
             // keep trying to process data from their load
-
-            if (hostedByObject)
-                cancelMainResourceLoad(ResourceError::cancelledError(m_request.url()));
+            cancelMainResourceLoad(ResourceError::cancelledError(m_request.url()));
         }
     }
 }
@@ -625,7 +595,7 @@
     RefPtr<DocumentLoader> protectLoader(this);
 
     if (m_identifierForLoadWithoutResourceLoader)
-        frameLoader()->notifier()->dispatchDidReceiveData(this, m_identifierForLoadWithoutResourceLoader, data, length, -1);
+        frame()->fetchContext().dispatchDidReceiveData(this, m_identifierForLoadWithoutResourceLoader, data, length, -1);
 
     m_applicationCacheHost->mainResourceDataReceived(data, length);
     m_timeOfLastDataReceived = monotonicallyIncreasingTime();
@@ -827,36 +797,7 @@
     if (mainResourceLoader() && mainResourceLoader()->isLoadedBy(m_fetcher.get()))
         mainResourceLoader()->setDefersLoading(defers);
 
-    setAllDefersLoading(m_resourceLoaders, defers);
-}
-
-void DocumentLoader::stopLoadingSubresources()
-{
-    cancelAll(m_resourceLoaders);
-}
-
-void DocumentLoader::addResourceLoader(ResourceLoader* loader)
-{
-    // The main resource's underlying ResourceLoader will ask to be added here.
-    // It is much simpler to handle special casing of main resource loads if we don't
-    // let it be added. In the main resource load case, mainResourceLoader()
-    // will still be null at this point, but document() should be zero here if and only
-    // if we are just starting the main resource load.
-    if (!document())
-        return;
-    ASSERT(!m_resourceLoaders.contains(loader));
-    ASSERT(!mainResourceLoader() || mainResourceLoader() != loader);
-    m_resourceLoaders.add(loader);
-}
-
-void DocumentLoader::removeResourceLoader(ResourceLoader* loader)
-{
-    if (!m_resourceLoaders.contains(loader))
-        return;
-    m_resourceLoaders.remove(loader);
-    checkLoadComplete();
-    if (Frame* frame = m_frame)
-        frame->loader()->checkLoadComplete();
+    m_fetcher->setDefersLoading(defers);
 }
 
 bool DocumentLoader::maybeLoadEmpty()
@@ -898,7 +839,7 @@
 
     if (m_substituteData.isValid()) {
         m_identifierForLoadWithoutResourceLoader = createUniqueIdentifier();
-        frameLoader()->notifier()->dispatchWillSendRequest(this, m_identifierForLoadWithoutResourceLoader, m_request, ResourceResponse());
+        frame()->fetchContext().dispatchWillSendRequest(this, m_identifierForLoadWithoutResourceLoader, m_request, ResourceResponse());
         handleSubstituteDataLoadSoon();
         return;
     }
@@ -941,15 +882,6 @@
     mainReceivedError(error);
 }
 
-void DocumentLoader::subresourceLoaderFinishedLoadingOnePart(ResourceLoader* loader)
-{
-    m_multipartResourceLoaders.add(loader);
-    m_resourceLoaders.remove(loader);
-    checkLoadComplete();
-    if (Frame* frame = m_frame)
-        frame->loader()->checkLoadComplete();
-}
-
 DocumentWriter* DocumentLoader::beginWriting(const String& mimeType, const String& encoding, const KURL& url)
 {
     m_writer = createWriterFor(m_frame, 0, url, mimeType, encoding, false, true);
diff --git a/Source/core/loader/DocumentLoader.h b/Source/core/loader/DocumentLoader.h
index b84b114..7fe971f 100644
--- a/Source/core/loader/DocumentLoader.h
+++ b/Source/core/loader/DocumentLoader.h
@@ -62,8 +62,6 @@
     class ResourceLoader;
     class SharedBuffer;
 
-    typedef HashSet<RefPtr<ResourceLoader> > ResourceLoaderSet;
-
     class DocumentLoader : public RefCounted<DocumentLoader>, private RawResourceClient {
         WTF_MAKE_FAST_ALLOCATED;
     public:
@@ -143,8 +141,6 @@
         bool isLoadingMainResource() const { return m_loadingMainResource; }
 
         void stopLoadingSubresources();
-        void addResourceLoader(ResourceLoader*);
-        void removeResourceLoader(ResourceLoader*);
 
         void subresourceLoaderFinishedLoadingOnePart(ResourceLoader*);
 
@@ -201,7 +197,7 @@
 
         bool maybeLoadEmpty();
 
-        bool isPostOrRedirectAfterPost(const ResourceRequest&, const ResourceResponse&);
+        bool isRedirectAfterPost(const ResourceRequest&, const ResourceResponse&);
 
         bool shouldContinueForResponse() const;
 
@@ -215,8 +211,6 @@
         RefPtr<ResourceFetcher> m_fetcher;
 
         ResourcePtr<RawResource> m_mainResource;
-        ResourceLoaderSet m_resourceLoaders;
-        ResourceLoaderSet m_multipartResourceLoaders;
 
         RefPtr<DocumentWriter> m_writer;
 
diff --git a/Source/core/loader/DocumentThreadableLoader.cpp b/Source/core/loader/DocumentThreadableLoader.cpp
index 33e2681..77af89e 100644
--- a/Source/core/loader/DocumentThreadableLoader.cpp
+++ b/Source/core/loader/DocumentThreadableLoader.cpp
@@ -33,11 +33,12 @@
 #include "core/loader/DocumentThreadableLoader.h"
 
 #include "core/dom/Document.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/RawResource.h"
+#include "core/fetch/Resource.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/CrossOriginAccessControl.h"
 #include "core/loader/CrossOriginPreflightResultCache.h"
 #include "core/loader/DocumentThreadableLoaderClient.h"
 #include "core/loader/FrameLoader.h"
@@ -286,7 +287,7 @@
     if (m_actualRequest) {
         DocumentLoader* loader = m_document->frame()->loader()->documentLoader();
         InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_document->frame(), identifier, response);
-        InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, loader, response, 0);
+        InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, loader, response, m_resource ? m_resource->loader() : 0);
 
         if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
             preflightFailure(identifier, response.url().string(), accessControlErrorDescription);
@@ -412,8 +413,8 @@
     ASSERT(m_sameOriginRequest || requestURL.user().isEmpty());
     ASSERT(m_sameOriginRequest || requestURL.pass().isEmpty());
 
+    ThreadableLoaderOptions options = m_options;
     if (m_async) {
-        ThreadableLoaderOptions options = m_options;
         options.crossOriginCredentialPolicy = DoNotAskClientForCrossOriginCredentials;
         if (m_actualRequest) {
             // Don't sniff content or send load callbacks for the preflight request.
@@ -445,12 +446,11 @@
     ResourceResponse response;
     unsigned long identifier = std::numeric_limits<unsigned long>::max();
     if (Frame* frame = m_document->frame()) {
-        Frame* top = frame->tree()->top();
-        if (!top->loader()->mixedContentChecker()->canDisplayInsecureContent(top->document()->securityOrigin(), requestURL)) {
+        if (!m_document->fetcher()->checkInsecureContent(Resource::Raw, requestURL, options.mixedContentBlockingTreatment)) {
             m_client->didFail(error);
             return;
         }
-        identifier = frame->loader()->loadResourceSynchronously(request, m_options.allowCredentials, error, response, data);
+        identifier = m_document->fetcher()->fetchSynchronously(request, m_options.allowCredentials, error, response, data);
     }
 
     InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
diff --git a/Source/core/loader/DocumentWriter.cpp b/Source/core/loader/DocumentWriter.cpp
index 566351d..61e19f1 100644
--- a/Source/core/loader/DocumentWriter.cpp
+++ b/Source/core/loader/DocumentWriter.cpp
@@ -31,9 +31,9 @@
 
 #include "core/dom/Document.h"
 #include "core/dom/ScriptableDocumentParser.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderStateMachine.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
diff --git a/Source/core/loader/EmptyClients.h b/Source/core/loader/EmptyClients.h
index b677f15..ab07244 100644
--- a/Source/core/loader/EmptyClients.h
+++ b/Source/core/loader/EmptyClients.h
@@ -193,7 +193,7 @@
     virtual void dispatchWillSendRequest(DocumentLoader*, unsigned long, ResourceRequest&, const ResourceResponse&) OVERRIDE { }
     virtual void dispatchDidReceiveResponse(DocumentLoader*, unsigned long, const ResourceResponse&) OVERRIDE { }
     virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long) OVERRIDE { }
-    virtual void dispatchDidLoadResourceFromMemoryCache(DocumentLoader*, const ResourceRequest&, const ResourceResponse&, int) OVERRIDE { }
+    virtual void dispatchDidLoadResourceFromMemoryCache(const ResourceRequest&, const ResourceResponse&) OVERRIDE { }
 
     virtual void dispatchDidHandleOnloadEvents() OVERRIDE { }
     virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() OVERRIDE { }
diff --git a/Source/core/loader/FormSubmission.cpp b/Source/core/loader/FormSubmission.cpp
index 13fb0e9..9b2b866 100644
--- a/Source/core/loader/FormSubmission.cpp
+++ b/Source/core/loader/FormSubmission.cpp
@@ -162,8 +162,8 @@
             copiedAttributes.setTarget(attributeValue);
     }
 
-    Document* document = form->document();
-    KURL actionURL = document->completeURL(copiedAttributes.action().isEmpty() ? document->url().string() : copiedAttributes.action());
+    Document& document = form->document();
+    KURL actionURL = document.completeURL(copiedAttributes.action().isEmpty() ? document.url().string() : copiedAttributes.action());
     bool isMailtoForm = actionURL.protocolIs("mailto");
     bool isMultiPartForm = false;
     String encodingType = copiedAttributes.encodingType();
@@ -176,7 +176,7 @@
         }
     }
 
-    WTF::TextEncoding dataEncoding = isMailtoForm ? UTF8Encoding() : FormDataBuilder::encodingFromAcceptCharset(copiedAttributes.acceptCharset(), document);
+    WTF::TextEncoding dataEncoding = isMailtoForm ? UTF8Encoding() : FormDataBuilder::encodingFromAcceptCharset(copiedAttributes.acceptCharset(), &document);
     RefPtr<DOMFormData> domFormData = DOMFormData::create(dataEncoding.encodingForFormSubmission());
     Vector<pair<String, String> > formValues;
 
@@ -199,7 +199,7 @@
     String boundary;
 
     if (isMultiPartForm) {
-        formData = FormData::createMultiPart(*(static_cast<FormDataList*>(domFormData.get())), domFormData->encoding(), document);
+        formData = FormData::createMultiPart(*(static_cast<FormDataList*>(domFormData.get())), domFormData->encoding(), &document);
         boundary = formData->boundary().data();
     } else {
         formData = FormData::create(*(static_cast<FormDataList*>(domFormData.get())), domFormData->encoding(), attributes.method() == GetMethod ? FormData::FormURLEncoded : FormData::parseEncodingType(encodingType));
@@ -212,8 +212,8 @@
 
     formData->setIdentifier(generateFormDataIdentifier());
     formData->setContainsPasswordData(containsPasswordData);
-    String targetOrBaseTarget = copiedAttributes.target().isEmpty() ? document->baseTarget() : copiedAttributes.target();
-    RefPtr<FormState> formState = FormState::create(form, formValues, document, trigger);
+    String targetOrBaseTarget = copiedAttributes.target().isEmpty() ? document.baseTarget() : copiedAttributes.target();
+    RefPtr<FormState> formState = FormState::create(form, formValues, &document, trigger);
     return adoptRef(new FormSubmission(copiedAttributes.method(), actionURL, targetOrBaseTarget, encodingType, formState.release(), formData.release(), boundary, event));
 }
 
diff --git a/Source/core/loader/FrameFetchContext.cpp b/Source/core/loader/FrameFetchContext.cpp
new file mode 100644
index 0000000..387f13a
--- /dev/null
+++ b/Source/core/loader/FrameFetchContext.cpp
@@ -0,0 +1,168 @@
+/*
+ * 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/loader/FrameFetchContext.h"
+
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/loader/DocumentLoader.h"
+#include "core/loader/FrameLoader.h"
+#include "core/loader/FrameLoaderClient.h"
+#include "core/loader/ProgressTracker.h"
+#include "core/page/Frame.h"
+#include "core/page/Page.h"
+#include "core/page/Settings.h"
+#include "weborigin/SecurityPolicy.h"
+
+namespace WebCore {
+
+FrameFetchContext::FrameFetchContext(Frame* frame)
+    : m_frame(frame)
+{
+}
+
+void FrameFetchContext::reportLocalLoadFailed(const KURL& url)
+{
+    FrameLoader::reportLocalLoadFailed(m_frame, url.elidedString());
+}
+
+void FrameFetchContext::addAdditionalRequestHeaders(Document& document, ResourceRequest& request, Resource::Type type)
+{
+    bool isMainResource = type == Resource::MainResource;
+
+    FrameLoader* frameLoader = m_frame->loader();
+
+    if (!isMainResource) {
+        String outgoingReferrer;
+        String outgoingOrigin;
+        if (request.httpReferrer().isNull()) {
+            outgoingReferrer = frameLoader->outgoingReferrer();
+            outgoingOrigin = frameLoader->outgoingOrigin();
+        } else {
+            outgoingReferrer = request.httpReferrer();
+            outgoingOrigin = SecurityOrigin::createFromString(outgoingReferrer)->toString();
+        }
+
+        outgoingReferrer = SecurityPolicy::generateReferrerHeader(document.referrerPolicy(), request.url(), outgoingReferrer);
+        if (outgoingReferrer.isEmpty())
+            request.clearHTTPReferrer();
+        else if (!request.httpReferrer())
+            request.setHTTPReferrer(outgoingReferrer);
+
+        FrameLoader::addHTTPOriginIfNeeded(request, outgoingOrigin);
+    }
+
+    frameLoader->addExtraFieldsToRequest(request);
+}
+
+CachePolicy FrameFetchContext::cachePolicy(Resource::Type type) const
+{
+    if (type != Resource::MainResource)
+        return m_frame->loader()->subresourceCachePolicy();
+
+    if (m_frame->loader()->loadType() == FrameLoadTypeReloadFromOrigin || m_frame->loader()->loadType() == FrameLoadTypeReload)
+        return CachePolicyReload;
+    return CachePolicyVerify;
+
+}
+
+// FIXME(http://crbug.com/274173):
+// |loader| can be null if the resource is loaded from imported document.
+// This means inspector, which uses DocumentLoader as an grouping entity,
+// cannot see imported documents.
+inline DocumentLoader* FrameFetchContext::ensureLoader(DocumentLoader* loader)
+{
+    return loader ? loader : m_frame->loader()->activeDocumentLoader();
+}
+
+void FrameFetchContext::dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority loadPriority)
+{
+    m_frame->loader()->client()->dispatchDidChangeResourcePriority(identifier, loadPriority);
+}
+
+void FrameFetchContext::dispatchWillSendRequest(DocumentLoader* loader, unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& initiatorInfo)
+{
+    m_frame->loader()->applyUserAgent(request);
+    m_frame->loader()->client()->dispatchWillSendRequest(loader, identifier, request, redirectResponse);
+    InspectorInstrumentation::willSendRequest(m_frame, identifier, ensureLoader(loader), request, redirectResponse, initiatorInfo);
+}
+
+void FrameFetchContext::dispatchDidLoadResourceFromMemoryCache(const ResourceRequest& request, const ResourceResponse& response)
+{
+    m_frame->loader()->client()->dispatchDidLoadResourceFromMemoryCache(request, response);
+}
+
+void FrameFetchContext::dispatchDidReceiveResponse(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, ResourceLoader* resourceLoader)
+{
+    if (Page* page = m_frame->page())
+        page->progress().incrementProgress(identifier, r);
+    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_frame, identifier, r);
+    m_frame->loader()->client()->dispatchDidReceiveResponse(loader, identifier, r);
+    InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, ensureLoader(loader), r, resourceLoader);
+}
+
+void FrameFetchContext::dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength)
+{
+    if (Page* page = m_frame->page())
+        page->progress().incrementProgress(identifier, data, dataLength);
+    InspectorInstrumentation::didReceiveData(m_frame, identifier, data, dataLength, encodedDataLength);
+}
+
+void FrameFetchContext::dispatchDidFinishLoading(DocumentLoader* loader, unsigned long identifier, double finishTime)
+{
+    if (Page* page = m_frame->page())
+        page->progress().completeProgress(identifier);
+    m_frame->loader()->client()->dispatchDidFinishLoading(loader, identifier);
+
+    InspectorInstrumentation::didFinishLoading(m_frame, identifier, ensureLoader(loader), finishTime);
+}
+
+void FrameFetchContext::dispatchDidFail(DocumentLoader* loader, unsigned long identifier, const ResourceError& error)
+{
+    if (Page* page = m_frame->page())
+        page->progress().completeProgress(identifier);
+    InspectorInstrumentation::didFailLoading(m_frame, identifier, ensureLoader(loader), error);
+}
+
+void FrameFetchContext::sendRemainingDelegateMessages(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& response, const char* data, int dataLength, int encodedDataLength, const ResourceError& error)
+{
+    if (!response.isNull())
+        dispatchDidReceiveResponse(ensureLoader(loader), identifier, response);
+
+    if (dataLength > 0)
+        dispatchDidReceiveData(ensureLoader(loader), identifier, data, dataLength, encodedDataLength);
+
+    if (error.isNull())
+        dispatchDidFinishLoading(ensureLoader(loader), identifier, 0);
+    else
+        dispatchDidFail(ensureLoader(loader), identifier, error);
+}
+
+} // namespace WebCore
diff --git a/Source/core/loader/FrameFetchContext.h b/Source/core/loader/FrameFetchContext.h
new file mode 100644
index 0000000..77a92af
--- /dev/null
+++ b/Source/core/loader/FrameFetchContext.h
@@ -0,0 +1,73 @@
+/*
+ * 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 FrameFetchContext_h
+#define FrameFetchContext_h
+
+#include "core/fetch/FetchContext.h"
+#include "core/platform/network/ResourceRequest.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class DocumentLoader;
+class Frame;
+class Page;
+class ResourceError;
+class ResourceLoader;
+class ResourceResponse;
+class ResourceRequest;
+
+class FrameFetchContext  : public FetchContext {
+public:
+    static PassOwnPtr<FrameFetchContext> create(Frame* frame) { return adoptPtr(new FrameFetchContext(frame)); }
+
+    virtual void reportLocalLoadFailed(const KURL&) OVERRIDE;
+    virtual void addAdditionalRequestHeaders(Document&, ResourceRequest&, Resource::Type) OVERRIDE;
+    virtual CachePolicy cachePolicy(Resource::Type) const OVERRIDE;
+    virtual void dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority);
+    virtual void dispatchWillSendRequest(DocumentLoader*, unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& = FetchInitiatorInfo()) OVERRIDE;
+    virtual void dispatchDidLoadResourceFromMemoryCache(const ResourceRequest&, const ResourceResponse&) OVERRIDE;
+    virtual void dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse&, ResourceLoader* = 0) OVERRIDE;
+    virtual void dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength)  OVERRIDE;
+    virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier, double finishTime) OVERRIDE;
+    virtual void dispatchDidFail(DocumentLoader*, unsigned long identifier, const ResourceError&) OVERRIDE;
+    virtual void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, const char* data, int dataLength, int encodedDataLength, const ResourceError&) OVERRIDE;
+
+private:
+    explicit FrameFetchContext(Frame*);
+    inline DocumentLoader* ensureLoader(DocumentLoader*);
+
+    Frame* m_frame;
+};
+
+}
+
+#endif
diff --git a/Source/core/loader/FrameLoader.cpp b/Source/core/loader/FrameLoader.cpp
index 082ecb6..c4c0412 100644
--- a/Source/core/loader/FrameLoader.cpp
+++ b/Source/core/loader/FrameLoader.cpp
@@ -45,12 +45,13 @@
 #include "core/dom/EventNames.h"
 #include "core/dom/PageTransitionEvent.h"
 #include "core/editing/Editor.h"
+#include "core/fetch/FetchContext.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/ResourceLoader.h"
 #include "core/history/BackForwardController.h"
 #include "core/history/HistoryItem.h"
 #include "core/html/HTMLFormElement.h"
-#include "core/html/HTMLObjectElement.h"
+#include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorInstrumentation.h"
@@ -58,6 +59,7 @@
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FormState.h"
 #include "core/loader/FormSubmission.h"
+#include "core/loader/FrameFetchContext.h"
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/IconController.h"
@@ -152,8 +154,8 @@
     : m_frame(frame)
     , m_client(client)
     , m_history(frame)
-    , m_notifer(frame)
     , m_icon(adoptPtr(new IconController(frame)))
+    , m_fetchContext(FrameFetchContext::create(frame))
     , m_mixedContentChecker(frame)
     , m_state(FrameStateProvisional)
     , m_loadType(FrameLoadTypeStandard)
@@ -279,7 +281,7 @@
         m_frame->script()->clearWindowShell();
     }
 
-    m_frame->selection()->prepareForDestruction();
+    m_frame->selection().prepareForDestruction();
     m_frame->eventHandler()->clear();
     if (m_frame->view())
         m_frame->view()->clear();
@@ -515,15 +517,6 @@
         m_frame->document()->initSecurityContext();
 }
 
-// FIXME: This does not belong in FrameLoader!
-void FrameLoader::handleFallbackContent()
-{
-    HTMLFrameOwnerElement* owner = m_frame->ownerElement();
-    if (!owner || !owner->hasTagName(objectTag))
-        return;
-    toHTMLObjectElement(owner)->renderFallbackContent();
-}
-
 bool FrameLoader::allowPlugins(ReasonForCallingAllowPlugins reason)
 {
     Settings* settings = m_frame->settings();
@@ -533,7 +526,7 @@
     return allowed;
 }
 
-void FrameLoader::updateForSameDocumentNavigation(const KURL& newURL, SameDocumentNavigationSource sameDocumentNavigationSource, PassRefPtr<SerializedScriptValue> data, const String& title)
+void FrameLoader::updateForSameDocumentNavigation(const KURL& newURL, SameDocumentNavigationSource sameDocumentNavigationSource, PassRefPtr<SerializedScriptValue> data, const String& title, UpdateBackForwardListPolicy updateBackForwardList)
 {
     // Update the data source's request with the new URL to fake the URL change
     KURL oldURL = m_frame->document()->url();
@@ -541,6 +534,12 @@
     setOutgoingReferrer(newURL);
     documentLoader()->replaceRequestURLForSameDocumentNavigation(newURL);
 
+    // updateBackForwardListForFragmentScroll() must happen after
+    // replaceRequestURLForSameDocumentNavigation(), since we add based on
+    // the current request.
+    if (updateBackForwardList == UpdateBackForwardList)
+        history()->updateBackForwardListForFragmentScroll();
+
     if (sameDocumentNavigationSource == SameDocumentNavigationDefault)
         history()->updateForSameDocumentNavigation();
     else if (sameDocumentNavigationSource == SameDocumentNavigationPushState)
@@ -580,10 +579,10 @@
         m_frame->eventHandler()->stopAutoscrollTimer();
         m_frame->document()->enqueueHashchangeEvent(oldURL, url);
     }
-
     m_documentLoader->setIsClientRedirect((m_startingClientRedirect && !isNewNavigation) || !UserGestureIndicator::processingUserGesture());
     m_documentLoader->setReplacesCurrentHistoryItem(!isNewNavigation);
-    updateForSameDocumentNavigation(url, SameDocumentNavigationDefault, 0, String());
+    UpdateBackForwardListPolicy updateBackForwardList = isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject ? UpdateBackForwardList : DoNotUpdateBackForwardList;
+    updateForSameDocumentNavigation(url, SameDocumentNavigationDefault, 0, String(), updateBackForwardList);
 
     // It's important to model this as a load that starts and immediately finishes.
     // Otherwise, the parent frame may think we never finished loading.
@@ -731,6 +730,8 @@
     if (targetFrame && targetFrame != m_frame) {
         request.setFrameName("_self");
         targetFrame->loader()->load(request);
+        if (Page* page = targetFrame->page())
+            page->chrome().focus();
         return;
     }
 
@@ -775,20 +776,6 @@
     frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Not allowed to load local resource: " + url);
 }
 
-bool FrameLoader::willLoadMediaElementURL(KURL& url)
-{
-    ResourceRequest request(url);
-
-    unsigned long identifier;
-    ResourceError error;
-    requestFromDelegate(request, identifier, error);
-    notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, ResourceResponse(url, String(), -1, String(), String()), 0, -1, -1, error);
-
-    url = request.url();
-
-    return error.isNull();
-}
-
 void FrameLoader::reload(ReloadPolicy reloadPolicy, const KURL& overrideURL, const String& overrideEncoding)
 {
     DocumentLoader* documentLoader = activeDocumentLoader();
@@ -871,6 +858,15 @@
     m_client->didAccessInitialDocument();
 }
 
+void FrameLoader::notifyIfInitialDocumentAccessed()
+{
+    if (m_didAccessInitialDocumentTimer.isActive()
+        && m_stateMachine.isDisplayingInitialEmptyDocument()) {
+        m_didAccessInitialDocumentTimer.stop();
+        didAccessInitialDocumentTimerFired(0);
+    }
+}
+
 bool FrameLoader::isLoading() const
 {
     DocumentLoader* docLoader = activeDocumentLoader();
@@ -897,21 +893,15 @@
     // The call to closeURL() invokes the unload event handler, which can execute arbitrary
     // JavaScript. If the script initiates a new load, we need to abandon the current load,
     // or the two will stomp each other.
+    // detachChildren will similarly trigger child frame unload event handlers.
     if (m_documentLoader)
         closeURL();
+    detachChildren();
     if (pdl != m_provisionalDocumentLoader)
         return;
-
-    // detachChildren() can trigger this frame's unload event, and therefore
-    // script can run and do just about anything. For example, an unload event that calls
-    // document.write("") on its parent frame can lead to a recursive detachChildren()
-    // invocation for this frame. Leave the loader that is being committed in a temporarily
-    // detached state, such that it can't be found and cancelled.
-    RefPtr<DocumentLoader> loaderBeingCommitted = m_provisionalDocumentLoader.release();
-    detachChildren();
     if (m_documentLoader)
         m_documentLoader->detachFromFrame();
-    m_documentLoader = loaderBeingCommitted;
+    m_documentLoader = m_provisionalDocumentLoader.release();
     m_state = FrameStateCommittedPage;
 
     if (isLoadingMainFrame())
@@ -946,12 +936,6 @@
         m_client->dispatchWillClose();
 }
 
-bool FrameLoader::isHostedByObjectElement() const
-{
-    HTMLFrameOwnerElement* owner = m_frame->ownerElement();
-    return owner && owner->hasTagName(objectTag);
-}
-
 bool FrameLoader::isLoadingMainFrame() const
 {
     Page* page = m_frame->page();
@@ -1009,6 +993,26 @@
 void FrameLoader::checkLoadCompleteForThisFrame()
 {
     ASSERT(m_client->hasWebView());
+
+    if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
+        const ResourceError& error = m_provisionalDocumentLoader->mainDocumentError();
+        if (error.isNull())
+            return;
+        RefPtr<DocumentLoader> loader = m_provisionalDocumentLoader;
+        m_client->dispatchDidFailProvisionalLoad(error);
+        if (loader != m_provisionalDocumentLoader)
+            return;
+        m_provisionalDocumentLoader->detachFromFrame();
+        m_provisionalDocumentLoader = 0;
+        m_progressTracker->progressCompleted();
+        m_state = FrameStateComplete;
+
+        // Reset the back forward list to the last committed history item at the top level.
+        RefPtr<HistoryItem> item = m_frame->page()->mainFrame()->loader()->history()->currentItem();
+        if (isBackForwardLoadType(loadType()) && !history()->provisionalItem() && item)
+            m_frame->page()->backForward().setCurrentItem(item.get());
+    }
+
     if (m_state != FrameStateCommittedPage)
         return;
 
@@ -1097,6 +1101,13 @@
     }
 }
 
+void FrameLoader::checkLoadComplete(DocumentLoader* documentLoader)
+{
+    if (documentLoader)
+        documentLoader->checkLoadComplete();
+    checkLoadComplete();
+}
+
 int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
 {
     if (!recurse)
@@ -1214,34 +1225,6 @@
     request.setHTTPOrigin(origin);
 }
 
-unsigned long FrameLoader::loadResourceSynchronously(const ResourceRequest& request, StoredCredentials storedCredentials, ResourceError& error, ResourceResponse& response, Vector<char>& data)
-{
-    ASSERT(m_frame->document());
-    String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), request.url(), outgoingReferrer());
-
-    ResourceRequest initialRequest = request;
-    initialRequest.setTimeoutInterval(10);
-
-    if (!referrer.isEmpty())
-        initialRequest.setHTTPReferrer(referrer);
-    addHTTPOriginIfNeeded(initialRequest, outgoingOrigin());
-
-    addExtraFieldsToRequest(initialRequest);
-
-    unsigned long identifier = 0;
-    ResourceRequest newRequest(initialRequest);
-    requestFromDelegate(newRequest, identifier, error);
-
-    if (error.isNull()) {
-        ASSERT(!newRequest.isNull());
-        documentLoader()->applicationCacheHost()->willStartLoadingSynchronously(newRequest);
-        ResourceLoader::loadResourceSynchronously(newRequest, storedCredentials, error, response, data);
-    }
-    int encodedDataLength = response.resourceLoadInfo() ? static_cast<int>(response.resourceLoadInfo()->encodedDataLength) : -1;
-    notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, response, data.data(), data.size(), encodedDataLength, error);
-    return identifier;
-}
-
 const ResourceRequest& FrameLoader::originalRequest() const
 {
     return activeDocumentLoader()->originalRequestCopy();
@@ -1259,23 +1242,8 @@
     // FIXME: We really ought to be able to just check for isCancellation() here, but there are some
     // ResourceErrors that setIsCancellation() but aren't created by ResourceError::cancelledError().
     ResourceError c(ResourceError::cancelledError(KURL()));
-    if (error.errorCode() != c.errorCode() || error.domain() != c.domain())
-        handleFallbackContent();
-
-    if (m_state == FrameStateProvisional && m_provisionalDocumentLoader) {
-        m_client->dispatchDidFailProvisionalLoad(error);
-        if (loader != m_provisionalDocumentLoader)
-            return;
-        m_provisionalDocumentLoader->detachFromFrame();
-        m_provisionalDocumentLoader = 0;
-        m_progressTracker->progressCompleted();
-        m_state = FrameStateComplete;
-
-        // Reset the back forward list to the last committed history item at the top level.
-        RefPtr<HistoryItem> item = m_frame->page()->mainFrame()->loader()->history()->currentItem();
-        if (isBackForwardLoadType(loadType()) && !history()->provisionalItem() && item)
-            m_frame->page()->backForward().setCurrentItem(item.get());
-    }
+    if ((error.errorCode() != c.errorCode() || error.domain() != c.domain()) && m_frame->ownerElement())
+        m_frame->ownerElement()->renderFallbackContent();
 
     checkCompleted();
     if (m_frame->page())
@@ -1297,8 +1265,6 @@
             m_provisionalDocumentLoader->detachFromFrame();
         m_provisionalDocumentLoader = 0;
     }
-    if (isNewNavigation && !shouldTreatURLAsSameAsCurrent(request.url()))
-        history()->updateBackForwardListForFragmentScroll();
     loadInSameDocument(request.url(), 0, isNewNavigation);
 }
 
@@ -1479,48 +1445,6 @@
     mainFrame->loader()->loadWithNavigationAction(action.resourceRequest(), NavigationAction(action.resourceRequest()), FrameLoadTypeStandard, formState, SubstituteData());
 }
 
-void FrameLoader::requestFromDelegate(ResourceRequest& request, unsigned long& identifier, ResourceError& error)
-{
-    ASSERT(!request.isNull());
-
-    identifier = 0;
-    if (Page* page = m_frame->page())
-        identifier = createUniqueIdentifier();
-
-    ResourceRequest newRequest(request);
-    notifier()->dispatchWillSendRequest(m_documentLoader.get(), identifier, newRequest, ResourceResponse());
-
-    if (newRequest.isNull())
-        error = ResourceError::cancelledError(request.url());
-    else
-        error = ResourceError();
-
-    request = newRequest;
-}
-
-void FrameLoader::loadedResourceFromMemoryCache(Resource* resource)
-{
-    Page* page = m_frame->page();
-    if (!page)
-        return;
-
-    if (!resource->shouldSendResourceLoadCallbacks())
-        return;
-
-    // Main resource delegate messages are synthesized in MainResourceLoader, so we must not send them here.
-    if (resource->type() == Resource::MainResource)
-        return;
-
-    ResourceRequest request(resource->url());
-    m_client->dispatchDidLoadResourceFromMemoryCache(m_documentLoader.get(), request, resource->response(), resource->encodedSize());
-
-    unsigned long identifier;
-    ResourceError error;
-    requestFromDelegate(request, identifier, error);
-    InspectorInstrumentation::markResourceAsCached(page, identifier);
-    notifier()->sendRemainingDelegateMessages(m_documentLoader.get(), identifier, resource->response(), 0, resource->encodedSize(), 0, error);
-}
-
 void FrameLoader::applyUserAgent(ResourceRequest& request)
 {
     String userAgent = this->userAgent(request.url());
@@ -1641,7 +1565,7 @@
         addHTTPOriginIfNeeded(request, securityOrigin->toString());
     }
 
-    loadWithNavigationAction(request, NavigationAction(request, FrameLoadTypeBackForward, false), FrameLoadTypeBackForward, 0, SubstituteData());
+    loadWithNavigationAction(request, NavigationAction(request, FrameLoadTypeBackForward, formData), FrameLoadTypeBackForward, 0, SubstituteData());
 }
 
 void FrameLoader::insertDummyHistoryItem()
diff --git a/Source/core/loader/FrameLoader.h b/Source/core/loader/FrameLoader.h
index 518aea6..9887942 100644
--- a/Source/core/loader/FrameLoader.h
+++ b/Source/core/loader/FrameLoader.h
@@ -35,7 +35,6 @@
 #include "core/dom/IconURL.h"
 #include "core/dom/SecurityContext.h"
 #include "core/fetch/CachePolicy.h"
-#include "core/fetch/ResourceLoadNotifier.h"
 #include "core/fetch/ResourceLoaderOptions.h"
 #include "core/loader/FrameLoaderStateMachine.h"
 #include "core/loader/FrameLoaderTypes.h"
@@ -54,6 +53,7 @@
 class DOMWrapperWorld;
 class DocumentLoader;
 class Event;
+class FetchContext;
 class FormState;
 class FormSubmission;
 class FrameLoaderClient;
@@ -83,7 +83,7 @@
     Frame* frame() const { return m_frame; }
 
     HistoryController* history() const { return &m_history; }
-    ResourceLoadNotifier* notifier() const { return &m_notifer; }
+
     IconController* icon() const { return m_icon.get(); }
     MixedContentChecker* mixedContentChecker() const { return &m_mixedContentChecker; }
 
@@ -94,9 +94,6 @@
     void reload(ReloadPolicy = NormalReload, const KURL& overrideURL = KURL(), const String& overrideEncoding = String());
     void loadHistoryItem(HistoryItem*); // The entry point for all back/forward loads
 
-    // FIXME: This doesn't really belong here, since we don't load Frames synchronously.
-    unsigned long loadResourceSynchronously(const ResourceRequest&, StoredCredentials, ResourceError&, ResourceResponse&, Vector<char>& data);
-
     HistoryItem* requestedHistoryItem() const { return m_requestedHistoryItem.get(); }
 
     static void reportLocalLoadFailed(Frame*, const String& url);
@@ -110,8 +107,15 @@
     // FIXME: clear() is trying to do too many things. We should break it down into smaller functions.
     void clear(ClearOptions);
 
+    // Sets a timer to notify the client that the initial empty document has
+    // been accessed, and thus it is no longer safe to show a provisional URL
+    // above the document without risking a URL spoof.
     void didAccessInitialDocument();
-    void didAccessInitialDocumentTimerFired(Timer<FrameLoader>*);
+
+    // If the initial empty document is showing and has been accessed, this
+    // cancels the timer and immediately notifies the client in cases that
+    // waiting to notify would allow a URL spoof.
+    void notifyIfInitialDocumentAccessed();
 
     bool isLoading() const;
 
@@ -124,15 +128,11 @@
     DocumentLoader* policyDocumentLoader() const { return m_policyDocumentLoader.get(); }
     DocumentLoader* provisionalDocumentLoader() const { return m_provisionalDocumentLoader.get(); }
     FrameState state() const { return m_state; }
+    FetchContext& fetchContext() const { return *m_fetchContext; }
 
     const ResourceRequest& originalRequest() const;
     void receivedMainResourceError(const ResourceError&);
 
-    bool willLoadMediaElementURL(KURL&);
-
-    void handleFallbackContent();
-
-    bool isHostedByObjectElement() const;
     bool isLoadingMainFrame() const;
 
     bool subframeIsLoading() const;
@@ -147,8 +147,7 @@
     void didLayout(LayoutMilestones);
     void didFirstLayout();
 
-    void loadedResourceFromMemoryCache(Resource*);
-
+    void checkLoadComplete(DocumentLoader*);
     void checkLoadComplete();
     void detachFromParent();
 
@@ -211,7 +210,11 @@
     bool containsPlugins() const { return m_containsPlugins; }
     bool allowPlugins(ReasonForCallingAllowPlugins);
 
-    void updateForSameDocumentNavigation(const KURL&, SameDocumentNavigationSource, PassRefPtr<SerializedScriptValue>, const String& title);
+    enum UpdateBackForwardListPolicy {
+        UpdateBackForwardList,
+        DoNotUpdateBackForwardList
+    };
+    void updateForSameDocumentNavigation(const KURL&, SameDocumentNavigationSource, PassRefPtr<SerializedScriptValue>, const String& title, UpdateBackForwardListPolicy);
 
 private:
     bool allChildrenAreComplete() const; // immediate children, not all descendants
@@ -219,6 +222,7 @@
     void completed();
 
     void checkTimerFired(Timer<FrameLoader>*);
+    void didAccessInitialDocumentTimerFired(Timer<FrameLoader>*);
 
     void insertDummyHistoryItem();
 
@@ -243,8 +247,6 @@
     void loadWithNavigationAction(const ResourceRequest&, const NavigationAction&,
         FrameLoadType, PassRefPtr<FormState>, const SubstituteData&, const String& overrideEncoding = String());
 
-    void requestFromDelegate(ResourceRequest&, unsigned long& identifier, ResourceError&);
-
     void detachChildren();
     void closeAndRemoveChild(Frame*);
 
@@ -262,7 +264,6 @@
     // header dependencies unless performance testing proves otherwise.
     // Some of these could be lazily created for memory savings on devices.
     mutable HistoryController m_history;
-    mutable ResourceLoadNotifier m_notifer;
     mutable FrameLoaderStateMachine m_stateMachine;
     OwnPtr<IconController> m_icon;
     mutable MixedContentChecker m_mixedContentChecker;
@@ -280,6 +281,7 @@
     RefPtr<DocumentLoader> m_documentLoader;
     RefPtr<DocumentLoader> m_provisionalDocumentLoader;
     RefPtr<DocumentLoader> m_policyDocumentLoader;
+    OwnPtr<FetchContext> m_fetchContext;
 
     bool m_inStopAllLoaders;
 
diff --git a/Source/core/loader/FrameLoaderClient.h b/Source/core/loader/FrameLoaderClient.h
index 1d2a75e..668a6cb 100644
--- a/Source/core/loader/FrameLoaderClient.h
+++ b/Source/core/loader/FrameLoaderClient.h
@@ -96,7 +96,7 @@
         virtual void dispatchWillSendRequest(DocumentLoader*, unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse) = 0;
         virtual void dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse&) = 0;
         virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier) = 0;
-        virtual void dispatchDidLoadResourceFromMemoryCache(DocumentLoader*, const ResourceRequest&, const ResourceResponse&, int length) = 0;
+        virtual void dispatchDidLoadResourceFromMemoryCache(const ResourceRequest&, const ResourceResponse&) = 0;
 
         virtual void dispatchDidHandleOnloadEvents() = 0;
         virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() = 0;
diff --git a/Source/core/loader/HistoryController.cpp b/Source/core/loader/HistoryController.cpp
index d07a446..be314f5 100644
--- a/Source/core/loader/HistoryController.cpp
+++ b/Source/core/loader/HistoryController.cpp
@@ -34,6 +34,7 @@
 #include "core/dom/Document.h"
 #include "core/history/BackForwardController.h"
 #include "core/history/HistoryItem.h"
+#include "core/html/HTMLFrameOwnerElement.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
@@ -534,7 +535,7 @@
             // we don't want to create a history item, because that causes fallback content
             // to be ignored on reload.
             FrameLoader* childLoader = child->loader();
-            if (childLoader->stateMachine()->startedFirstRealLoad() || !childLoader->isHostedByObjectElement())
+            if (childLoader->stateMachine()->startedFirstRealLoad() || !child->ownerElement()->isObjectElement())
                 bfItem->addChildItem(childLoader->history()->createItemTree(targetFrame, clipAtTarget));
         }
     }
diff --git a/Source/core/loader/ImageLoader.cpp b/Source/core/loader/ImageLoader.cpp
index 2269bfe..0648212 100644
--- a/Source/core/loader/ImageLoader.cpp
+++ b/Source/core/loader/ImageLoader.cpp
@@ -27,13 +27,12 @@
 #include "core/dom/Element.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventSender.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ImageResource.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/CrossOriginAccessControl.h"
-#include "core/page/Frame.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderVideo.h"
 #include "core/rendering/svg/RenderSVGImage.h"
@@ -144,8 +143,8 @@
 {
     // If we're not making renderers for the page, then don't load images.  We don't want to slow
     // down the raw HTML parsing case by loading images we don't intend to display.
-    Document* document = m_element->document();
-    if (!document->renderer())
+    Document& document = m_element->document();
+    if (!document.renderer())
         return;
 
     AtomicString attr = m_element->imageSourceURL();
@@ -157,30 +156,30 @@
     // an empty string.
     ResourcePtr<ImageResource> newImage = 0;
     if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) {
-        FetchRequest request(ResourceRequest(document->completeURL(sourceURI(attr))), element()->localName());
+        FetchRequest request(ResourceRequest(document.completeURL(sourceURI(attr))), element()->localName());
 
         String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
         if (!crossOriginMode.isNull()) {
             StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
-            updateRequestForAccessControl(request.mutableResourceRequest(), document->securityOrigin(), allowCredentials);
+            updateRequestForAccessControl(request.mutableResourceRequest(), document.securityOrigin(), allowCredentials);
         }
 
         if (m_loadManually) {
-            bool autoLoadOtherImages = document->fetcher()->autoLoadImages();
-            document->fetcher()->setAutoLoadImages(false);
+            bool autoLoadOtherImages = document.fetcher()->autoLoadImages();
+            document.fetcher()->setAutoLoadImages(false);
             newImage = new ImageResource(request.resourceRequest());
             newImage->setLoading(true);
-            document->fetcher()->m_documentResources.set(newImage->url(), newImage.get());
-            document->fetcher()->setAutoLoadImages(autoLoadOtherImages);
+            document.fetcher()->m_documentResources.set(newImage->url(), newImage.get());
+            document.fetcher()->setAutoLoadImages(autoLoadOtherImages);
         } else {
-            newImage = document->fetcher()->fetchImage(request);
+            newImage = document.fetcher()->fetchImage(request);
         }
 
         // If we do not have an image here, it means that a cross-site
         // violation occurred, or that the image was blocked via Content
         // Security Policy, or the page is being dismissed. Trigger an
         // error event if the page is not being dismissed.
-        if (!newImage && !pageIsBeingDismissed(document)) {
+        if (!newImage && !pageIsBeingDismissed(&document)) {
             m_failedLoadURL = attr;
             m_hasPendingErrorEvent = true;
             errorEventSender().dispatchEventSoon(this);
@@ -215,13 +214,13 @@
         }
 
         m_image = newImage;
-        m_hasPendingBeforeLoadEvent = !m_element->document()->isImageDocument() && newImage;
+        m_hasPendingBeforeLoadEvent = !m_element->document().isImageDocument() && newImage;
         m_hasPendingLoadEvent = newImage;
         m_imageComplete = !newImage;
 
         if (newImage) {
-            if (!m_element->document()->isImageDocument()) {
-                if (!m_element->document()->hasListenerType(Document::BEFORELOAD_LISTENER))
+            if (!m_element->document().isImageDocument()) {
+                if (!m_element->document().hasListenerType(Document::BEFORELOAD_LISTENER))
                     dispatchPendingBeforeLoadEvent();
                 else
                     beforeLoadEventSender().dispatchEventSoon(this);
@@ -267,8 +266,8 @@
         return;
 
     if (m_element->fastHasAttribute(HTMLNames::crossoriginAttr)
-        && !m_element->document()->securityOrigin()->canRequest(image()->response().url())
-        && !resource->passesAccessControlCheck(m_element->document()->securityOrigin())) {
+        && !m_element->document().securityOrigin()->canRequest(image()->response().url())
+        && !resource->passesAccessControlCheck(m_element->document().securityOrigin())) {
 
         setImageWithoutConsideringPendingLoadEvent(0);
 
@@ -276,7 +275,7 @@
         errorEventSender().dispatchEventSoon(this);
 
         DEFINE_STATIC_LOCAL(String, consoleMessage, ("Cross-origin image load denied by Cross-Origin Resource Sharing policy."));
-        m_element->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
+        m_element->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
 
         ASSERT(!m_hasPendingLoadEvent);
 
@@ -378,7 +377,7 @@
         return;
     if (!m_image)
         return;
-    if (!m_element->document()->attached())
+    if (!m_element->document().attached())
         return;
     m_hasPendingBeforeLoadEvent = false;
     if (m_element->dispatchBeforeLoadEvent(m_image->url().string())) {
@@ -408,7 +407,7 @@
     if (!m_image)
         return;
     m_hasPendingLoadEvent = false;
-    if (element()->document()->attached())
+    if (element()->document().attached())
         dispatchLoadEvent();
 
     // Only consider updating the protection ref-count of the Element immediately before returning
@@ -421,7 +420,7 @@
     if (!m_hasPendingErrorEvent)
         return;
     m_hasPendingErrorEvent = false;
-    if (element()->document()->attached())
+    if (element()->document().attached())
         element()->dispatchEvent(Event::create(eventNames().errorEvent));
 
     // Only consider updating the protection ref-count of the Element immediately before returning
diff --git a/Source/core/loader/LinkLoader.cpp b/Source/core/loader/LinkLoader.cpp
index 73103fa..2e49672 100644
--- a/Source/core/loader/LinkLoader.cpp
+++ b/Source/core/loader/LinkLoader.cpp
@@ -104,36 +104,36 @@
     m_client->didSendDOMContentLoadedForLinkPrerender();
 }
 
-bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const String& type, const KURL& href, Document* document)
+bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const String& type, const KURL& href, Document& document)
 {
     if (relAttribute.isDNSPrefetch()) {
-        Settings* settings = document->settings();
+        Settings* settings = document.settings();
         // FIXME: The href attribute of the link element can be in "//hostname" form, and we shouldn't attempt
         // to complete that as URL <https://bugs.webkit.org/show_bug.cgi?id=48857>.
         if (settings && settings->dnsPrefetchingEnabled() && href.isValid() && !href.isEmpty())
             prefetchDNS(href.host());
     }
 
-    if ((relAttribute.isLinkPrefetch() || relAttribute.isLinkSubresource()) && href.isValid() && document->frame()) {
+    if ((relAttribute.isLinkPrefetch() || relAttribute.isLinkSubresource()) && href.isValid() && document.frame()) {
         if (!m_client->shouldLoadLink())
             return false;
         Resource::Type type = relAttribute.isLinkSubresource() ?  Resource::LinkSubresource : Resource::LinkPrefetch;
-        FetchRequest linkRequest(ResourceRequest(document->completeURL(href)), FetchInitiatorTypeNames::link);
+        FetchRequest linkRequest(ResourceRequest(document.completeURL(href)), FetchInitiatorTypeNames::link);
         if (m_cachedLinkResource) {
             m_cachedLinkResource->removeClient(this);
             m_cachedLinkResource = 0;
         }
-        m_cachedLinkResource = document->fetcher()->fetchLinkResource(type, linkRequest);
+        m_cachedLinkResource = document.fetcher()->fetchLinkResource(type, linkRequest);
         if (m_cachedLinkResource)
             m_cachedLinkResource->addClient(this);
     }
 
     if (relAttribute.isLinkPrerender()) {
         if (!m_prerenderHandle) {
-            m_prerenderHandle = document->prerenderer()->render(this, href);
+            m_prerenderHandle = document.prerenderer()->render(this, href);
         } else if (m_prerenderHandle->url() != href) {
             m_prerenderHandle->cancel();
-            m_prerenderHandle = document->prerenderer()->render(this, href);
+            m_prerenderHandle = document.prerenderer()->render(this, href);
         }
     } else if (m_prerenderHandle) {
         m_prerenderHandle->cancel();
diff --git a/Source/core/loader/LinkLoader.h b/Source/core/loader/LinkLoader.h
index 086be49..b020860 100644
--- a/Source/core/loader/LinkLoader.h
+++ b/Source/core/loader/LinkLoader.h
@@ -61,7 +61,7 @@
     virtual void didSendDOMContentLoadedForPrerender() OVERRIDE;
 
     void released();
-    bool loadLink(const LinkRelAttribute&, const String& type, const KURL&, Document*);
+    bool loadLink(const LinkRelAttribute&, const String& type, const KURL&, Document&);
 
 private:
     void linkLoadTimerFired(Timer<LinkLoader>*);
diff --git a/Source/core/loader/NavigationAction.cpp b/Source/core/loader/NavigationAction.cpp
index 603f40a..ffabc57 100644
--- a/Source/core/loader/NavigationAction.cpp
+++ b/Source/core/loader/NavigationAction.cpp
@@ -37,13 +37,14 @@
 static NavigationType navigationType(FrameLoadType frameLoadType, bool isFormSubmission, bool haveEvent)
 {
     bool isReload = frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin;
+    bool isBackForward = isBackForwardLoadType(frameLoadType);
     if (isFormSubmission)
-        return isReload ? NavigationTypeFormResubmitted : NavigationTypeFormSubmitted;
+        return (isReload || isBackForward) ? NavigationTypeFormResubmitted : NavigationTypeFormSubmitted;
     if (haveEvent)
         return NavigationTypeLinkClicked;
     if (isReload)
         return NavigationTypeReload;
-    if (isBackForwardLoadType(frameLoadType))
+    if (isBackForward)
         return NavigationTypeBackForward;
     return NavigationTypeOther;
 }
diff --git a/Source/core/loader/NavigationPolicy.cpp b/Source/core/loader/NavigationPolicy.cpp
index ca1d702..e8494ff 100644
--- a/Source/core/loader/NavigationPolicy.cpp
+++ b/Source/core/loader/NavigationPolicy.cpp
@@ -37,7 +37,7 @@
 
 bool navigationPolicyFromMouseEvent(unsigned short button, bool ctrl, bool shift, bool alt, bool meta, NavigationPolicy* policy)
 {
-#if OS(DARWIN)
+#if OS(MACOSX)
     const bool newTabModifier = (button == 1) || meta;
 #else
     const bool newTabModifier = (button == 1) || ctrl;
diff --git a/Source/core/loader/TextResourceDecoderBuilder.h b/Source/core/loader/TextResourceDecoderBuilder.h
index ba71e5a..c2a57b9 100644
--- a/Source/core/loader/TextResourceDecoderBuilder.h
+++ b/Source/core/loader/TextResourceDecoderBuilder.h
@@ -31,7 +31,7 @@
 #ifndef TextResourceDecoderBuilder_h
 #define TextResourceDecoderBuilder_h
 
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/loader/TextTrackLoader.cpp b/Source/core/loader/TextTrackLoader.cpp
index afce1b0..7e6fd86 100644
--- a/Source/core/loader/TextTrackLoader.cpp
+++ b/Source/core/loader/TextTrackLoader.cpp
@@ -29,11 +29,11 @@
 
 #include "FetchInitiatorTypeNames.h"
 #include "core/dom/Document.h"
+#include "core/fetch/CrossOriginAccessControl.h"
 #include "core/fetch/FetchRequest.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/TextTrackResource.h"
 #include "core/html/track/WebVTTParser.h"
-#include "core/loader/CrossOriginAccessControl.h"
 #include "core/platform/Logging.h"
 #include "core/platform/SharedBuffer.h"
 #include "weborigin/SecurityOrigin.h"
diff --git a/Source/core/make_derived_sources.target.darwin-arm.mk b/Source/core/make_derived_sources.target.darwin-arm.mk
index 7886a99..e58ed01 100644
--- a/Source/core/make_derived_sources.target.darwin-arm.mk
+++ b/Source/core/make_derived_sources.target.darwin-arm.mk
@@ -21,7 +21,7 @@
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
 
 
 ### Rules for action "generateXMLViewerCSS":
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerCSS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
 ### Rules for action "generateXMLViewerJS":
@@ -41,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerJS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
 ### Rules for action "HTMLEntityTable":
@@ -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/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/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"
 
@@ -72,7 +72,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -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 $(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/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/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(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)
 	@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"
 
@@ -180,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -189,9 +189,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
@@ -442,6 +442,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -454,6 +455,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -522,6 +524,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -534,6 +537,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
diff --git a/Source/core/make_derived_sources.target.darwin-mips.mk b/Source/core/make_derived_sources.target.darwin-mips.mk
index fdf170b..09ee9a1 100644
--- a/Source/core/make_derived_sources.target.darwin-mips.mk
+++ b/Source/core/make_derived_sources.target.darwin-mips.mk
@@ -21,7 +21,7 @@
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
 
 
 ### Rules for action "generateXMLViewerCSS":
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerCSS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
 ### Rules for action "generateXMLViewerJS":
@@ -41,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerJS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
 ### Rules for action "HTMLEntityTable":
@@ -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/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/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"
 
@@ -72,7 +72,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -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 $(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/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/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(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)
 	@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"
 
@@ -180,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -189,9 +189,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
@@ -442,6 +442,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -454,6 +455,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -522,6 +524,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -534,6 +537,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
diff --git a/Source/core/make_derived_sources.target.darwin-x86.mk b/Source/core/make_derived_sources.target.darwin-x86.mk
index d377080..78c16a0 100644
--- a/Source/core/make_derived_sources.target.darwin-x86.mk
+++ b/Source/core/make_derived_sources.target.darwin-x86.mk
@@ -21,7 +21,7 @@
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
 
 
 ### Rules for action "generateXMLViewerCSS":
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerCSS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
 ### Rules for action "generateXMLViewerJS":
@@ -41,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerJS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
 ### Rules for action "HTMLEntityTable":
@@ -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/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/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"
 
@@ -72,7 +72,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -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 $(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/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/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(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)
 	@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"
 
@@ -180,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -189,9 +189,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
@@ -444,6 +444,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -456,6 +457,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -527,6 +529,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -539,6 +542,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
diff --git a/Source/core/make_derived_sources.target.linux-arm.mk b/Source/core/make_derived_sources.target.linux-arm.mk
index 7886a99..e58ed01 100644
--- a/Source/core/make_derived_sources.target.linux-arm.mk
+++ b/Source/core/make_derived_sources.target.linux-arm.mk
@@ -21,7 +21,7 @@
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
 
 
 ### Rules for action "generateXMLViewerCSS":
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerCSS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
 ### Rules for action "generateXMLViewerJS":
@@ -41,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerJS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
 ### Rules for action "HTMLEntityTable":
@@ -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/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/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"
 
@@ -72,7 +72,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -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 $(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/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/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(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)
 	@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"
 
@@ -180,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -189,9 +189,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
@@ -442,6 +442,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -454,6 +455,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -522,6 +524,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -534,6 +537,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
diff --git a/Source/core/make_derived_sources.target.linux-mips.mk b/Source/core/make_derived_sources.target.linux-mips.mk
index fdf170b..09ee9a1 100644
--- a/Source/core/make_derived_sources.target.linux-mips.mk
+++ b/Source/core/make_derived_sources.target.linux-mips.mk
@@ -21,7 +21,7 @@
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
 
 
 ### Rules for action "generateXMLViewerCSS":
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerCSS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
 ### Rules for action "generateXMLViewerJS":
@@ -41,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerJS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
 ### Rules for action "HTMLEntityTable":
@@ -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/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/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"
 
@@ -72,7 +72,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -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 $(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/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/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(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)
 	@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"
 
@@ -180,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -189,9 +189,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
@@ -442,6 +442,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -454,6 +455,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -522,6 +524,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -534,6 +537,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
diff --git a/Source/core/make_derived_sources.target.linux-x86.mk b/Source/core/make_derived_sources.target.linux-x86.mk
index d377080..78c16a0 100644
--- a/Source/core/make_derived_sources.target.linux-x86.mk
+++ b/Source/core/make_derived_sources.target.linux-x86.mk
@@ -21,7 +21,7 @@
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h: $(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustomScript.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl V8ArrayBufferViewCustomScript_js ../bindings/v8/custom/V8ArrayBufferViewCustomScript.js "$(gyp_shared_intermediate_dir)/blink/V8ArrayBufferViewCustomScript.h"
 
 
 ### Rules for action "generateXMLViewerCSS":
@@ -31,7 +31,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerCSS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_css xml/XMLViewer.css "$(gyp_shared_intermediate_dir)/blink/XMLViewerCSS.h"
 
 
 ### Rules for action "generateXMLViewerJS":
@@ -41,7 +41,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/XMLViewer.js $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_generateXMLViewerJS ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl inspector/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; perl scripts/xxd.pl XMLViewer_js xml/XMLViewer.js "$(gyp_shared_intermediate_dir)/blink/XMLViewerJS.h"
 
 
 ### Rules for action "HTMLEntityTable":
@@ -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/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/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"
 
@@ -72,7 +72,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/blink/CSSPropertyNames.cpp ;
 
@@ -106,7 +106,7 @@
 $(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)
 	@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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(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\""
 
 $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/blink/CSSValueKeywords.cpp ;
 
@@ -117,7 +117,7 @@
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/HTMLNames.h" "$(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/HTMLNames.h: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/HTMLNames.cpp ;
@@ -142,7 +142,7 @@
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGNames.h" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/blink/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/SVGNames.h: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/blink/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/blink/SVGNames.cpp ;
@@ -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 $(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/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/dom/EventTargetFactory.in $(GYP_TARGET_DEPENDENCIES)
+$(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)
 	@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"
 
@@ -180,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/MathMLNames.h: $(gyp_shared_intermediate_dir)/blink/MathMLNames.cpp ;
 
@@ -189,9 +189,9 @@
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/xhtmlmp.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mediaControls.css css/mediaControlsAndroid.css css/fullscreen.css css/xhtmlmp.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --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\""
 
 $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/blink/UserAgentStyleSheets.h ;
 
@@ -246,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XLinkNames.h: $(gyp_shared_intermediate_dir)/blink/XLinkNames.cpp ;
 
@@ -257,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNSNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNSNames.cpp ;
 
@@ -268,7 +268,7 @@
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/blink; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/blink/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/blink/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"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\""
 
 $(gyp_shared_intermediate_dir)/blink/XMLNames.h: $(gyp_shared_intermediate_dir)/blink/XMLNames.cpp ;
 
@@ -444,6 +444,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -456,6 +457,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
@@ -527,6 +529,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -539,6 +542,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DANDROID' \
 	'-D__GNU_SOURCE=1' \
 	'-DUSE_STLPORT=1' \
diff --git a/Source/core/page/AutoscrollController.cpp b/Source/core/page/AutoscrollController.cpp
index c7174c1..257bb7d 100644
--- a/Source/core/page/AutoscrollController.cpp
+++ b/Source/core/page/AutoscrollController.cpp
@@ -90,7 +90,7 @@
         return;
 
     scrollable->stopAutoscroll();
-#if OS(WINDOWS)
+#if OS(WIN)
     if (panScrollInProgress()) {
         if (FrameView* view = scrollable->frame()->view()) {
             view->removePanScrollIcon();
@@ -118,7 +118,7 @@
 
     RenderObject* renderer = m_autoscrollRenderer;
 
-#if OS(WINDOWS)
+#if OS(WIN)
     HitTestResult hitTest = renderer->frame()->eventHandler()->hitTestResultAtPoint(m_panScrollStartPos, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
 
     if (Node* nodeAtPoint = hitTest.innerNode())
@@ -171,7 +171,7 @@
     }
 }
 
-#if OS(WINDOWS)
+#if OS(WIN)
 void AutoscrollController::handleMouseReleaseForPanScrolling(Frame* frame, const PlatformMouseEvent& mouseEvent)
 {
     Page* page = frame->page();
@@ -237,7 +237,7 @@
         break;
     case NoAutoscroll:
         break;
-#if OS(WINDOWS)
+#if OS(WIN)
     case AutoscrollForPanCanStop:
     case AutoscrollForPan:
         if (!panScrollInProgress()) {
@@ -257,7 +257,7 @@
     m_autoscrollTimer.startRepeating(autoscrollInterval);
 }
 
-#if OS(WINDOWS)
+#if OS(WIN)
 void AutoscrollController::updatePanScrollState(FrameView* view, const IntPoint& lastKnownMousePosition)
 {
     // At the original click location we draw a 4 arrowed icon. Over this icon there won't be any scroll
diff --git a/Source/core/page/AutoscrollController.h b/Source/core/page/AutoscrollController.h
index 4cb90cb..88ed10f 100644
--- a/Source/core/page/AutoscrollController.h
+++ b/Source/core/page/AutoscrollController.h
@@ -44,7 +44,7 @@
     NoAutoscroll,
     AutoscrollForDragAndDrop,
     AutoscrollForSelection,
-#if OS(WINDOWS)
+#if OS(WIN)
     AutoscrollForPanCanStop,
     AutoscrollForPan,
 #endif
@@ -62,7 +62,7 @@
     void stopAutoscrollIfNeeded(RenderObject*);
     void updateAutoscrollRenderer();
     void updateDragAndDrop(Node* targetNode, const IntPoint& eventPosition, double eventTime);
-#if OS(WINDOWS)
+#if OS(WIN)
     void handleMouseReleaseForPanScrolling(Frame*, const PlatformMouseEvent&);
     void startPanScrolling(RenderBox*, const IntPoint&);
 #endif
@@ -71,7 +71,7 @@
     AutoscrollController();
     void autoscrollTimerFired(Timer<AutoscrollController>*);
     void startAutoscrollTimer();
-#if OS(WINDOWS)
+#if OS(WIN)
     void updatePanScrollState(FrameView*, const IntPoint&);
 #endif
 
@@ -80,7 +80,7 @@
     AutoscrollType m_autoscrollType;
     IntPoint m_dragAndDropAutoscrollReferencePosition;
     double m_dragAndDropAutoscrollStartTime;
-#if OS(WINDOWS)
+#if OS(WIN)
     IntPoint m_panScrollStartPos;
 #endif
 };
diff --git a/Source/core/page/Chrome.cpp b/Source/core/page/Chrome.cpp
index 1972ef5..71a576f 100644
--- a/Source/core/page/Chrome.cpp
+++ b/Source/core/page/Chrome.cpp
@@ -306,8 +306,7 @@
 void Chrome::mouseDidMoveOverElement(const HitTestResult& result, unsigned modifierFlags)
 {
     if (result.innerNode()) {
-        Document* document = result.innerNode()->document();
-        if (document && document->isDNSPrefetchEnabled())
+        if (result.innerNode()->document().isDNSPrefetchEnabled())
             prefetchDNS(result.absoluteLinkURL().host());
     }
     m_client->mouseDidMoveOverElement(result, modifierFlags);
diff --git a/Source/core/page/ConsoleBase.cpp b/Source/core/page/ConsoleBase.cpp
index 97ef72b..e1eaa9e 100644
--- a/Source/core/page/ConsoleBase.cpp
+++ b/Source/core/page/ConsoleBase.cpp
@@ -158,12 +158,12 @@
 void ConsoleBase::time(const String& title)
 {
     InspectorInstrumentation::startConsoleTiming(context(), title);
-    TRACE_EVENT_COPY_ASYNC_BEGIN0("webkit", title.utf8().data(), this);
+    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", title.utf8().data(), this);
+    TRACE_EVENT_COPY_ASYNC_END0("webkit.console", title.utf8().data(), this);
     RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(state));
     InspectorInstrumentation::stopConsoleTiming(context(), title, callStack.release());
 }
diff --git a/Source/core/page/ContextMenuController.cpp b/Source/core/page/ContextMenuController.cpp
index 77797e3..226e210 100644
--- a/Source/core/page/ContextMenuController.cpp
+++ b/Source/core/page/ContextMenuController.cpp
@@ -72,7 +72,7 @@
 {
     if (Node* innerNode = m_hitTestResult.innerNode()) {
         // Invalidate the context menu info if its target document is detached.
-        if (innerNode->document() == document)
+        if (&innerNode->document() == document)
             clearContextMenu();
     }
 }
@@ -110,7 +110,7 @@
     MouseEvent* mouseEvent = toMouseEvent(event);
     HitTestResult result(mouseEvent->absoluteLocation());
 
-    if (Frame* frame = event->target()->toNode()->document()->frame())
+    if (Frame* frame = event->target()->toNode()->document().frame())
         result = frame->eventHandler()->hitTestResultAtPoint(mouseEvent->absoluteLocation(), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
 
     if (!result.innerNonSharedNode())
diff --git a/Source/core/page/DOMSelection.cpp b/Source/core/page/DOMSelection.cpp
index 2bc803c..a9fd1ad 100644
--- a/Source/core/page/DOMSelection.cpp
+++ b/Source/core/page/DOMSelection.cpp
@@ -49,7 +49,7 @@
 
 static Node* selectionShadowAncestor(Frame* frame)
 {
-    Node* node = frame->selection()->selection().base().anchorNode();
+    Node* node = frame->selection().selection().base().anchorNode();
     if (!node)
         return 0;
 
@@ -60,7 +60,7 @@
 }
 
 DOMSelection::DOMSelection(const TreeScope* treeScope)
-    : DOMWindowProperty(treeScope->rootNode()->document()->frame())
+    : DOMWindowProperty(treeScope->rootNode()->document().frame())
     , m_treeScope(treeScope)
 {
     ScriptWrappable::init(this);
@@ -74,7 +74,7 @@
 const VisibleSelection& DOMSelection::visibleSelection() const
 {
     ASSERT(m_frame);
-    return m_frame->selection()->selection();
+    return m_frame->selection().selection();
 }
 
 static Position anchorPosition(const VisibleSelection& selection)
@@ -167,7 +167,7 @@
 {
     if (!m_frame || selectionShadowAncestor(m_frame))
         return true;
-    return !m_frame->selection()->isRange();
+    return !m_frame->selection().isRange();
 }
 
 String DOMSelection::type() const
@@ -175,14 +175,14 @@
     if (!m_frame)
         return String();
 
-    FrameSelection* selection = m_frame->selection();
+    FrameSelection& selection = m_frame->selection();
 
     // This is a WebKit DOM extension, incompatible with an IE extension
     // IE has this same attribute, but returns "none", "text" and "control"
     // http://msdn.microsoft.com/en-us/library/ms534692(VS.85).aspx
-    if (selection->isNone())
+    if (selection.isNone())
         return "None";
-    if (selection->isCaret())
+    if (selection.isCaret())
         return "Caret";
     return "Range";
 }
@@ -191,7 +191,7 @@
 {
     if (!m_frame)
         return 0;
-    return m_frame->selection()->isNone() ? 0 : 1;
+    return m_frame->selection().isNone() ? 0 : 1;
 }
 
 void DOMSelection::collapse(Node* node, int offset, ExceptionState& es)
@@ -208,7 +208,7 @@
         return;
 
     // FIXME: Eliminate legacy editing positions
-    m_frame->selection()->moveTo(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
+    m_frame->selection().moveTo(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
 }
 
 void DOMSelection::collapseToEnd(ExceptionState& es)
@@ -216,14 +216,14 @@
     if (!m_frame)
         return;
 
-    const VisibleSelection& selection = m_frame->selection()->selection();
+    const VisibleSelection& selection = m_frame->selection().selection();
 
     if (selection.isNone()) {
         es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToEnd", "Selection", "there is no selection."));
         return;
     }
 
-    m_frame->selection()->moveTo(VisiblePosition(selection.end(), DOWNSTREAM));
+    m_frame->selection().moveTo(VisiblePosition(selection.end(), DOWNSTREAM));
 }
 
 void DOMSelection::collapseToStart(ExceptionState& es)
@@ -231,21 +231,21 @@
     if (!m_frame)
         return;
 
-    const VisibleSelection& selection = m_frame->selection()->selection();
+    const VisibleSelection& selection = m_frame->selection().selection();
 
     if (selection.isNone()) {
         es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToStart", "Selection", "there is no selection."));
         return;
     }
 
-    m_frame->selection()->moveTo(VisiblePosition(selection.start(), DOWNSTREAM));
+    m_frame->selection().moveTo(VisiblePosition(selection.start(), DOWNSTREAM));
 }
 
 void DOMSelection::empty()
 {
     if (!m_frame)
         return;
-    m_frame->selection()->clear();
+    m_frame->selection().clear();
 }
 
 void DOMSelection::setBaseAndExtent(Node* baseNode, int baseOffset, Node* extentNode, int extentOffset, ExceptionState& es)
@@ -270,7 +270,7 @@
     VisiblePosition visibleBase = VisiblePosition(createLegacyEditingPosition(baseNode, baseOffset), DOWNSTREAM);
     VisiblePosition visibleExtent = VisiblePosition(createLegacyEditingPosition(extentNode, extentOffset), DOWNSTREAM);
 
-    m_frame->selection()->moveTo(visibleBase, visibleExtent);
+    m_frame->selection().moveTo(visibleBase, visibleExtent);
 }
 
 void DOMSelection::setPosition(Node* node, int offset, ExceptionState& es)
@@ -286,7 +286,7 @@
         return;
 
     // FIXME: Eliminate legacy editing positions
-    m_frame->selection()->moveTo(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
+    m_frame->selection().moveTo(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
 }
 
 void DOMSelection::modify(const String& alterString, const String& directionString, const String& granularityString)
@@ -336,7 +336,7 @@
     else
         return;
 
-    m_frame->selection()->modify(alter, direction, granularity);
+    m_frame->selection().modify(alter, direction, granularity);
 }
 
 void DOMSelection::extend(Node* node, int offset, ExceptionState& es)
@@ -362,7 +362,7 @@
         return;
 
     // FIXME: Eliminate legacy editing positions
-    m_frame->selection()->setExtent(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
+    m_frame->selection().setExtent(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
 }
 
 PassRefPtr<Range> DOMSelection::getRangeAt(int index, ExceptionState& es)
@@ -384,7 +384,7 @@
         return Range::create(shadowAncestor->document(), container, offset, container, offset);
     }
 
-    const VisibleSelection& selection = m_frame->selection()->selection();
+    const VisibleSelection& selection = m_frame->selection().selection();
     return selection.firstRange();
 }
 
@@ -392,7 +392,7 @@
 {
     if (!m_frame)
         return;
-    m_frame->selection()->clear();
+    m_frame->selection().clear();
 }
 
 void DOMSelection::addRange(Range* r)
@@ -402,34 +402,36 @@
     if (!r)
         return;
 
-    FrameSelection* selection = m_frame->selection();
+    FrameSelection& selection = m_frame->selection();
 
-    if (selection->isNone()) {
-        selection->setSelection(VisibleSelection(r));
+    if (selection.isNone()) {
+        selection.setSelection(VisibleSelection(r));
         return;
     }
 
-    RefPtr<Range> range = selection->selection().toNormalizedRange();
+    RefPtr<Range> range = selection.selection().toNormalizedRange();
     if (r->compareBoundaryPoints(Range::START_TO_START, range.get(), IGNORE_EXCEPTION) == -1) {
         // We don't support discontiguous selection. We don't do anything if r and range don't intersect.
         if (r->compareBoundaryPoints(Range::START_TO_END, range.get(), IGNORE_EXCEPTION) > -1) {
-            if (r->compareBoundaryPoints(Range::END_TO_END, range.get(), IGNORE_EXCEPTION) == -1)
+            if (r->compareBoundaryPoints(Range::END_TO_END, range.get(), IGNORE_EXCEPTION) == -1) {
                 // The original range and r intersect.
-                selection->setSelection(VisibleSelection(r->startPosition(), range->endPosition(), DOWNSTREAM));
-            else
+                selection.setSelection(VisibleSelection(r->startPosition(), range->endPosition(), DOWNSTREAM));
+            } else {
                 // r contains the original range.
-                selection->setSelection(VisibleSelection(r));
+                selection.setSelection(VisibleSelection(r));
+            }
         }
     } else {
         // We don't support discontiguous selection. We don't do anything if r and range don't intersect.
         TrackExceptionState es;
         if (r->compareBoundaryPoints(Range::END_TO_START, range.get(), es) < 1 && !es.hadException()) {
-            if (r->compareBoundaryPoints(Range::END_TO_END, range.get(), IGNORE_EXCEPTION) == -1)
+            if (r->compareBoundaryPoints(Range::END_TO_END, range.get(), IGNORE_EXCEPTION) == -1) {
                 // The original range contains r.
-                selection->setSelection(VisibleSelection(range.get()));
-            else
+                selection.setSelection(VisibleSelection(range.get()));
+            } else {
                 // The original range and r intersect.
-                selection->setSelection(VisibleSelection(range->startPosition(), r->endPosition(), DOWNSTREAM));
+                selection.setSelection(VisibleSelection(range->startPosition(), r->endPosition(), DOWNSTREAM));
+            }
         }
     }
 }
@@ -439,15 +441,15 @@
     if (!m_frame)
         return;
 
-    FrameSelection* selection = m_frame->selection();
+    FrameSelection& selection = m_frame->selection();
 
-    if (selection->isNone())
+    if (selection.isNone())
         return;
 
     if (isCollapsed())
-        selection->modify(FrameSelection::AlterationExtend, DirectionBackward, CharacterGranularity);
+        selection.modify(FrameSelection::AlterationExtend, DirectionBackward, CharacterGranularity);
 
-    RefPtr<Range> selectedRange = selection->selection().toNormalizedRange();
+    RefPtr<Range> selectedRange = selection.selection().toNormalizedRange();
     if (!selectedRange)
         return;
 
@@ -461,13 +463,13 @@
     if (!m_frame)
         return false;
 
-    FrameSelection* selection = m_frame->selection();
+    FrameSelection& selection = m_frame->selection();
 
-    if (!n || m_frame->document() != n->document() || selection->isNone())
+    if (!n || m_frame->document() != &n->document() || selection.isNone())
         return false;
 
     unsigned nodeIndex = n->nodeIndex();
-    RefPtr<Range> selectedRange = selection->selection().toNormalizedRange();
+    RefPtr<Range> selectedRange = selection.selection().toNormalizedRange();
 
     ContainerNode* parentNode = n->parentNode();
     if (!parentNode)
@@ -503,7 +505,7 @@
     if (!m_frame)
         return String();
 
-    return plainText(m_frame->selection()->selection().toNormalizedRange().get());
+    return plainText(m_frame->selection().selection().toNormalizedRange().get());
 }
 
 Node* DOMSelection::shadowAdjustedNode(const Position& position) const
@@ -545,7 +547,7 @@
     ASSERT(m_frame);
     if (!node)
         return true;
-    return node->document() == m_frame->document();
+    return &node->document() == m_frame->document();
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/DOMWindow.cpp b/Source/core/page/DOMWindow.cpp
index e4fec98..abe3bee 100644
--- a/Source/core/page/DOMWindow.cpp
+++ b/Source/core/page/DOMWindow.cpp
@@ -361,7 +361,7 @@
         }
     }
 
-    m_frame->selection()->updateSecureKeyboardEntryIfActive();
+    m_frame->selection().updateSecureKeyboardEntryIfActive();
 
     if (m_frame->page() && m_frame->page()->mainFrame() == m_frame) {
         m_frame->page()->mainFrame()->notifyChromeClientWheelEventHandlerCountChanged();
@@ -1410,9 +1410,7 @@
 
     if (Document* document = this->document()) {
         document->addListenerTypeIfNeeded(eventType);
-        if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
-            document->didAddWheelEventHandler();
-        else if (eventNames().isTouchEventType(eventType))
+        if (eventNames().isTouchEventType(eventType))
             document->didAddTouchEventHandler(document);
         else if (eventType == eventNames().storageEvent)
             didAddStorageEventListener(this);
@@ -1446,9 +1444,7 @@
         return false;
 
     if (Document* document = this->document()) {
-        if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
-            document->didRemoveWheelEventHandler();
-        else if (eventNames().isTouchEventType(eventType))
+        if (eventNames().isTouchEventType(eventType))
             document->didRemoveTouchEventHandler(document);
     }
 
diff --git a/Source/core/page/DOMWindow.h b/Source/core/page/DOMWindow.h
index 6644dc3..cdda703 100644
--- a/Source/core/page/DOMWindow.h
+++ b/Source/core/page/DOMWindow.h
@@ -257,6 +257,9 @@
         void dispatchLoadEvent();
 
         DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
+        DEFINE_ATTRIBUTE_EVENT_LISTENER(animationend);
+        DEFINE_ATTRIBUTE_EVENT_LISTENER(animationiteration);
+        DEFINE_ATTRIBUTE_EVENT_LISTENER(animationstart);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(beforeunload);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(blur);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(canplay);
@@ -318,6 +321,7 @@
         DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(suspend);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(timeupdate);
+        DEFINE_ATTRIBUTE_EVENT_LISTENER(transitionend);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(unload);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(volumechange);
         DEFINE_ATTRIBUTE_EVENT_LISTENER(waiting);
@@ -327,7 +331,6 @@
         DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationiteration, webkitAnimationIteration);
         DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationend, webkitAnimationEnd);
         DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkittransitionend, webkitTransitionEnd);
-        DEFINE_ATTRIBUTE_EVENT_LISTENER(transitionend);
 
         void captureEvents() { }
         void releaseEvents() { }
diff --git a/Source/core/page/DragController.cpp b/Source/core/page/DragController.cpp
index 875d2da..166fc1c 100644
--- a/Source/core/page/DragController.cpp
+++ b/Source/core/page/DragController.cpp
@@ -78,7 +78,7 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefPtr.h"
 
-#if OS(WINDOWS)
+#if OS(WIN)
 #include <windows.h>
 #endif
 
@@ -149,9 +149,8 @@
     ASSERT(dragData);
     chosePlainText = false;
 
-    Document* document = context->ownerDocument();
-    ASSERT(document);
-    if (document && dragData->containsCompatibleContent()) {
+    Document& document = context->ownerDocument();
+    if (dragData->containsCompatibleContent()) {
         if (PassRefPtr<DocumentFragment> fragment = dragData->asFragment(frame, context, allowPlainText, chosePlainText))
             return fragment;
 
@@ -168,9 +167,9 @@
                     if (title.isEmpty())
                         title = url;
                 }
-                RefPtr<Node> anchorText = document->createTextNode(title);
+                RefPtr<Node> anchorText = document.createTextNode(title);
                 anchor->appendChild(anchorText);
-                RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
+                RefPtr<DocumentFragment> fragment = document.createDocumentFragment();
                 fragment->appendChild(anchor);
                 return fragment.release();
             }
@@ -184,9 +183,9 @@
     return 0;
 }
 
-bool DragController::dragIsMove(FrameSelection* selection, DragData* dragData)
+bool DragController::dragIsMove(FrameSelection& selection, DragData* dragData)
 {
-    return m_documentUnderMouse == m_dragInitiator && selection->isContentEditable() && selection->isRange() && !isCopyKeyDown(dragData);
+    return m_documentUnderMouse == m_dragInitiator && selection.isContentEditable() && selection.isRange() && !isCopyKeyDown(dragData);
 }
 
 // FIXME: This method is poorly named.  We're just clearing the selection from the document this drag is exiting.
@@ -297,19 +296,11 @@
 static HTMLInputElement* asFileInput(Node* node)
 {
     ASSERT(node);
-
-    if (!node->hasTagName(HTMLNames::inputTag))
-        return 0;
-    HTMLInputElement* inputElement = toHTMLInputElement(node);
-    // If this is a button inside of the a file input, move up to the file input.
-    if (inputElement->isTextButton() && inputElement->treeScope()->rootNode()->isShadowRoot()) {
-        Element* host = toShadowRoot(inputElement->treeScope()->rootNode())->host();
-        if (!host->hasTagName(HTMLNames::inputTag))
-            return 0;
-        inputElement = toHTMLInputElement(host);
+    for (; node; node = node->shadowHost()) {
+        if (node->hasTagName(HTMLNames::inputTag) && toHTMLInputElement(node)->isFileUpload())
+            return toHTMLInputElement(node);
     }
-
-    return inputElement->isFileUpload() ? inputElement : 0;
+    return 0;
 }
 
 // This can return null if an empty document is loaded.
@@ -325,7 +316,7 @@
 
     Node* n = result.innerNode();
     while (n && !n->isElementNode())
-        n = n->parentNode();
+        n = n->parentOrShadowHostNode();
     if (n)
         n = n->deprecatedShadowAncestorNode();
 
@@ -381,7 +372,7 @@
         if (!m_fileInputElementUnderMouse)
             m_page->dragCaretController().setCaretPosition(m_documentUnderMouse->frame()->visiblePositionForPoint(point));
 
-        Frame* innerFrame = element->document()->frame();
+        Frame* innerFrame = element->document().frame();
         dragSession.operation = dragIsMove(innerFrame->selection(), dragData) ? DragOperationMove : DragOperationCopy;
         dragSession.mouseIsOverFileInput = m_fileInputElementUnderMouse;
         dragSession.numberOfItemsToBeAccepted = 0;
@@ -429,13 +420,13 @@
 
 static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, RefPtr<Range>& range, const IntPoint& point)
 {
-    frame->selection()->setSelection(dragCaret);
-    if (frame->selection()->isNone()) {
+    frame->selection().setSelection(dragCaret);
+    if (frame->selection().isNone()) {
         dragCaret = frame->visiblePositionForPoint(point);
-        frame->selection()->setSelection(dragCaret);
+        frame->selection().setSelection(dragCaret);
         range = dragCaret.toNormalizedRange();
     }
-    return !frame->selection()->isNone() && frame->selection()->isContentEditable();
+    return !frame->selection().isNone() && frame->selection().isContentEditable();
 }
 
 bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
@@ -487,13 +478,13 @@
     VisibleSelection dragCaret = m_page->dragCaretController().caretPosition();
     m_page->dragCaretController().clear();
     RefPtr<Range> range = dragCaret.toNormalizedRange();
-    RefPtr<Element> rootEditableElement = innerFrame->selection()->rootEditableElement();
+    RefPtr<Element> rootEditableElement = innerFrame->selection().rootEditableElement();
 
     // For range to be null a WebKit client must have done something bad while
     // manually controlling drag behaviour
     if (!range)
         return false;
-    ResourceFetcher* fetcher = range->ownerDocument()->fetcher();
+    ResourceFetcher* fetcher = range->ownerDocument().fetcher();
     ResourceCacheValidationSuppressor validationSuppressor(fetcher);
     if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
         bool chosePlainText = false;
@@ -506,8 +497,8 @@
             // NSTextView behavior is to always smart delete on moving a selection,
             // but only to smart insert if the selection granularity is word granularity.
             bool smartDelete = innerFrame->editor().smartInsertDeleteEnabled();
-            bool smartInsert = smartDelete && innerFrame->selection()->granularity() == WordGranularity && dragData->canSmartReplace();
-            applyCommand(MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete));
+            bool smartInsert = smartDelete && innerFrame->selection().granularity() == WordGranularity && dragData->canSmartReplace();
+            MoveSelectionCommand::create(fragment, dragCaret.base(), smartInsert, smartDelete)->apply();
         } else {
             if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
                 ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::PreventNesting;
@@ -515,7 +506,8 @@
                     options |= ReplaceSelectionCommand::SmartReplace;
                 if (chosePlainText)
                     options |= ReplaceSelectionCommand::MatchStyle;
-                applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), fragment, options));
+                ASSERT(m_documentUnderMouse);
+                ReplaceSelectionCommand::create(*m_documentUnderMouse.get(), fragment, options)->apply();
             }
         }
     } else {
@@ -524,12 +516,14 @@
             return false;
         }
 
-        if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point))
-            applyCommand(ReplaceSelectionCommand::create(m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting));
+        if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
+            ASSERT(m_documentUnderMouse);
+            ReplaceSelectionCommand::create(*m_documentUnderMouse.get(), createFragmentFromText(range.get(), text),  ReplaceSelectionCommand::SelectReplacement | ReplaceSelectionCommand::MatchStyle | ReplaceSelectionCommand::PreventNesting)->apply();
+        }
     }
 
     if (rootEditableElement) {
-        if (Frame* frame = rootEditableElement->document()->frame())
+        if (Frame* frame = rootEditableElement->document().frame())
             frame->eventHandler()->updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
     }
 
@@ -557,7 +551,7 @@
         return true;
 
     if (result.innerNonSharedNode()->isPluginElement()) {
-        HTMLPlugInElement* plugin = static_cast<HTMLPlugInElement*>(result.innerNonSharedNode());
+        HTMLPlugInElement* plugin = toHTMLPlugInElement(result.innerNonSharedNode());
         if (!plugin->canProcessDrag() && !result.innerNonSharedNode()->rendererIsEditable())
             return false;
     } else if (!result.innerNonSharedNode()->rendererIsEditable())
@@ -622,7 +616,7 @@
 
 Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
 {
-    state.m_dragType = (src->selection()->contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
+    state.m_dragType = (src->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
 
     for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
         Node* node = renderer->nonPseudoNode();
@@ -687,7 +681,7 @@
     if (node->isContentRichlyEditable()) {
         RefPtr<Range> range = source->document()->createRange();
         range->selectNode(node, ASSERT_NO_EXCEPTION);
-        source->selection()->setSelection(VisibleSelection(range.get(), DOWNSTREAM));
+        source->selection().setSelection(VisibleSelection(range.get(), DOWNSTREAM));
     }
     clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, source);
 }
@@ -715,10 +709,10 @@
     Node* node = state.m_dragSrc.get();
 
     if (state.m_dragType == DragSourceActionSelection) {
-        if (enclosingTextFormControl(src->selection()->start())) {
+        if (enclosingTextFormControl(src->selection().start())) {
             clipboard->writePlainText(src->selectedTextForClipboard());
         } else {
-            RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
+            RefPtr<Range> selectionRange = src->selection().toNormalizedRange();
             ASSERT(selectionRange);
 
             clipboard->writeRange(selectionRange.get(), src);
@@ -752,7 +746,7 @@
 
 static IntPoint dragLocationForSelectionDrag(Frame* sourceFrame)
 {
-    IntRect draggingRect = enclosingIntRect(sourceFrame->selection()->bounds());
+    IntRect draggingRect = enclosingIntRect(sourceFrame->selection().bounds());
     int xpos = draggingRect.maxX();
     xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
     int ypos = draggingRect.maxY();
@@ -762,7 +756,7 @@
 
 static const IntSize& maxDragImageSize()
 {
-#if OS(DARWIN)
+#if OS(MACOSX)
     // Match Safari's drag image size.
     static const IntSize maxDragImageSize(400, 400);
 #else
@@ -867,14 +861,12 @@
     } else if (state.m_dragType == DragSourceActionLink) {
         if (linkURL.isEmpty())
             return false;
-        if (src->selection()->isCaret() && src->selection()->isContentEditable()) {
+        if (src->selection().isCaret() && src->selection().isContentEditable()) {
             // a user can initiate a drag on a link without having any text
             // selected.  In this case, we should expand the selection to
             // the enclosing anchor element
-            Position pos = src->selection()->base();
-            Node* node = enclosingAnchorElement(pos);
-            if (node)
-                src->selection()->setSelection(VisibleSelection::selectionFromContentsOfNode(node));
+            if (Node* node = enclosingAnchorElement(src->selection().base()))
+                src->selection().setSelection(VisibleSelection::selectionFromContentsOfNode(node));
         }
 
         if (!dragImage) {
@@ -924,7 +916,7 @@
 bool DragController::isCopyKeyDown(DragData*)
 {
     // FIXME: This should not be OS specific.  Delegate to the embedder instead.
-#if OS(WINDOWS)
+#if OS(WIN)
     return ::GetAsyncKeyState(VK_CONTROL);
 #else
     return false;
diff --git a/Source/core/page/DragController.h b/Source/core/page/DragController.h
index 65a705f..23293e5 100644
--- a/Source/core/page/DragController.h
+++ b/Source/core/page/DragController.h
@@ -84,7 +84,7 @@
         bool tryDHTMLDrag(DragData*, DragOperation&);
         DragOperation dragOperation(DragData*);
         void cancelDrag();
-        bool dragIsMove(FrameSelection*, DragData*);
+        bool dragIsMove(FrameSelection&, DragData*);
         bool isCopyKeyDown(DragData*);
 
         void mouseMovedIntoDocument(Document*);
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index 453825b..2afd72a 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -129,7 +129,7 @@
 // dividing cursor sizes (limited above) by the scale.
 const double minimumCursorScale = 0.001;
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 const double EventHandler::TextDragDelay = 0.15;
 #else
 const double EventHandler::TextDragDelay = 0.0;
@@ -367,11 +367,10 @@
         m_clickNode = 0;
 }
 
-static void setSelectionIfNeeded(FrameSelection* selection, const VisibleSelection& newSelection)
+static void setSelectionIfNeeded(FrameSelection& selection, const VisibleSelection& newSelection)
 {
-    ASSERT(selection);
-    if (selection->selection() != newSelection && selection->shouldChangeSelection(newSelection))
-        selection->setSelection(newSelection);
+    if (selection.selection() != newSelection && selection.shouldChangeSelection(newSelection))
+        selection.setSelection(newSelection);
 }
 
 static inline bool dispatchSelectStart(Node* node)
@@ -379,7 +378,7 @@
     if (!node || !node->renderer())
         return true;
 
-    return node->dispatchEvent(Event::create(eventNames().selectstartEvent, true, true));
+    return node->dispatchEvent(Event::createCancelableBubble(eventNames().selectstartEvent));
 }
 
 static VisibleSelection expandSelectionToRespectUserSelectAll(Node* targetNode, const VisibleSelection& selection)
@@ -410,7 +409,7 @@
         m_selectionInitiationState = PlacedCaret;
     }
 
-    m_frame->selection()->setNonDirectionalSelectionIfNeeded(selection, granularity);
+    m_frame->selection().setNonDirectionalSelectionIfNeeded(selection, granularity);
 
     return true;
 }
@@ -444,7 +443,7 @@
         Position start = pos.deepEquivalent();
         Position end = pos.deepEquivalent();
         if (pos.isNotNull()) {
-            Vector<DocumentMarker*> markers = innerNode->document()->markers()->markersInRange(
+            Vector<DocumentMarker*> markers = innerNode->document().markers()->markersInRange(
                 makeRange(pos, pos).get(), DocumentMarker::Spelling | DocumentMarker::Grammar);
             if (markers.size() == 1) {
                 start.moveToOffset(markers[0]->startOffset());
@@ -499,16 +498,16 @@
     if (event.event().button() != LeftButton)
         return false;
 
-    if (m_frame->selection()->isRange())
+    if (m_frame->selection().isRange()) {
         // A double-click when range is already selected
         // should not change the selection.  So, do not call
         // selectClosestWordFromMouseEvent, but do set
         // m_beganSelectingText to prevent handleMouseReleaseEvent
         // from setting caret selection.
         m_selectionInitiationState = ExtendedSelection;
-    else
+    } else {
         selectClosestWordFromMouseEvent(event);
-
+    }
     return true;
 }
 
@@ -533,8 +532,8 @@
 
 static int textDistance(const Position& start, const Position& end)
 {
-     RefPtr<Range> range = Range::create(start.anchorNode()->document(), start, end);
-     return TextIterator::rangeLength(range.get(), true);
+    RefPtr<Range> range = Range::create(*start.document(), start, end);
+    return TextIterator::rangeLength(range.get(), true);
 }
 
 bool EventHandler::handleMousePressEventSingleClick(const MouseEventWithHitTestResults& event)
@@ -551,7 +550,7 @@
     // existing selection so we can allow for text dragging.
     if (FrameView* view = m_frame->view()) {
         LayoutPoint vPoint = view->windowToContents(event.event().position());
-        if (!extendSelection && m_frame->selection()->contains(vPoint)) {
+        if (!extendSelection && m_frame->selection().contains(vPoint)) {
             m_mouseDownWasSingleClickInSelection = true;
             return false;
         }
@@ -562,7 +561,7 @@
         visiblePos = VisiblePosition(firstPositionInOrBeforeNode(innerNode), DOWNSTREAM);
     Position pos = visiblePos.deepEquivalent();
 
-    VisibleSelection newSelection = m_frame->selection()->selection();
+    VisibleSelection newSelection = m_frame->selection().selection();
     TextGranularity granularity = CharacterGranularity;
 
     if (extendSelection && newSelection.isCaretOrRange()) {
@@ -588,9 +587,9 @@
         } else
             newSelection.setExtent(pos);
 
-        if (m_frame->selection()->granularity() != CharacterGranularity) {
-            granularity = m_frame->selection()->granularity();
-            newSelection.expandUsingGranularity(m_frame->selection()->granularity());
+        if (m_frame->selection().granularity() != CharacterGranularity) {
+            granularity = m_frame->selection().granularity();
+            newSelection.expandUsingGranularity(m_frame->selection().granularity());
         }
     } else
         newSelection = expandSelectionToRespectUserSelectAll(innerNode, visiblePos);
@@ -742,14 +741,14 @@
     if (!target)
         return;
 
-    VisiblePosition targetPosition = m_frame->selection()->selection().visiblePositionRespectingEditingBoundary(hitTestResult.localPoint(), target);
+    VisiblePosition targetPosition = m_frame->selection().selection().visiblePositionRespectingEditingBoundary(hitTestResult.localPoint(), target);
     // Don't modify the selection if we're not on a node.
     if (targetPosition.isNull())
         return;
 
     // Restart the selection if this is the first mouse move. This work is usually
     // done in handleMousePressEvent, but not if the mouse press was on an existing selection.
-    VisibleSelection newSelection = m_frame->selection()->selection();
+    VisibleSelection newSelection = m_frame->selection().selection();
 
     // Special case to limit selection to the containing block for SVG text.
     // FIXME: Isn't there a better non-SVG-specific way to do this?
@@ -790,26 +789,16 @@
         newSelection.setExtent(targetPosition);
     }
 
-    if (m_frame->selection()->granularity() != CharacterGranularity)
-        newSelection.expandUsingGranularity(m_frame->selection()->granularity());
+    if (m_frame->selection().granularity() != CharacterGranularity)
+        newSelection.expandUsingGranularity(m_frame->selection().granularity());
 
-    m_frame->selection()->setNonDirectionalSelectionIfNeeded(newSelection, m_frame->selection()->granularity(),
+    m_frame->selection().setNonDirectionalSelectionIfNeeded(newSelection, m_frame->selection().granularity(),
         FrameSelection::AdjustEndpointsAtBidiBoundary);
 }
 
 void EventHandler::lostMouseCapture()
 {
-    m_frame->selection()->setCaretBlinkingSuspended(false);
-}
-
-bool EventHandler::handleMouseUp(const MouseEventWithHitTestResults& event)
-{
-    // If this was the first click in the window, we don't even want to clear the selection.
-    // This case occurs when the user clicks on a draggable element, since we have to process
-    // the mouse down and drag events to see if we might start a drag.  For other first clicks
-    // in a window, we just don't acceptFirstMouse, and the whole down-drag-up sequence gets
-    // ignored upstream of this layer.
-    return false;
+    m_frame->selection().setCaretBlinkingSuspended(false);
 }
 
 bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& event)
@@ -818,9 +807,6 @@
     if (page && page->autoscrollInProgress())
         stopAutoscrollTimer();
 
-    if (handleMouseUp(event))
-        return true;
-
     // Used to prevent mouseMoveEvent from initiating a drag before
     // the mouse is pressed again.
     m_mousePressed = false;
@@ -838,7 +824,7 @@
     // editing, place the caret.
     if (m_mouseDownWasSingleClickInSelection && m_selectionInitiationState != ExtendedSelection
             && m_dragStartPos == event.event().position()
-            && m_frame->selection()->isRange()
+            && m_frame->selection().isRange()
             && event.event().button() != RightButton) {
         VisibleSelection newSelection;
         Node* node = event.targetNode();
@@ -853,9 +839,9 @@
         handled = true;
     }
 
-    m_frame->selection()->notifyRendererOfSelectionChange(UserTriggered);
+    m_frame->selection().notifyRendererOfSelectionChange(UserTriggered);
 
-    m_frame->selection()->selectFrameElementInParentIfFullySelected();
+    m_frame->selection().selectFrameElementInParentIfFullySelected();
 
     if (event.event().button() == MiddleButton && !event.isOverLink()) {
         // Ignore handled, since we want to paste to where the caret was placed anyway.
@@ -865,7 +851,7 @@
     return handled;
 }
 
-#if OS(WINDOWS)
+#if OS(WIN)
 
 void EventHandler::startPanScrolling(RenderObject* renderer)
 {
@@ -878,7 +864,7 @@
     invalidateClick();
 }
 
-#endif // OS(WINDOWS)
+#endif // OS(WIN)
 
 bool EventHandler::panScrollInProgress() const
 {
@@ -1051,7 +1037,7 @@
     if (!widget || !widget->isFrameView())
         return 0;
 
-    return toFrameView(widget)->frame();
+    return &toFrameView(widget)->frame();
 }
 
 static bool isSubmitImage(Node* node)
@@ -1062,7 +1048,7 @@
 // Returns true if the node's editable block is not current focused for editing
 static bool nodeIsNotBeingEdited(Node* node, Frame* frame)
 {
-    return frame->selection()->rootEditableElement() != node->rootEditableElement();
+    return frame->selection().rootEditableElement() != node->rootEditableElement();
 }
 
 bool EventHandler::useHandCursor(Node* node, bool isOverLink, bool shiftKey)
@@ -1108,7 +1094,7 @@
     Page* page = m_frame->page();
     if (!page)
         return NoCursorChange;
-#if OS(WINDOWS)
+#if OS(WIN)
     if (panScrollInProgress())
         return NoCursorChange;
 #endif
@@ -1123,7 +1109,7 @@
     // 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)
+        && m_frame->selection().isCaretOrRange() && !m_capturingMouseEventsNode)
         return iBeam;
 
     if (renderer) {
@@ -1323,7 +1309,7 @@
         return true;
     }
 
-#if OS(WINDOWS)
+#if OS(WIN)
     // We store whether pan scrolling is in progress before calling stopAutoscrollTimer()
     // because it will set m_autoscrollType to NoAutoscroll on return.
     bool isPanScrollInProgress = panScrollInProgress();
@@ -1351,7 +1337,7 @@
         }
     }
 
-    m_frame->selection()->setCaretBlinkingSuspended(true);
+    m_frame->selection().setCaretBlinkingSuspended(true);
 
     bool swallowEvent = !dispatchMouseEvent(eventNames().mousedownEvent, mev.targetNode(), true, m_clickCount, mouseEvent, true);
     m_capturesDragging = !swallowEvent || mev.scrollbar();
@@ -1605,7 +1591,7 @@
 {
     RefPtr<FrameView> protector(m_frame->view());
 
-    m_frame->selection()->setCaretBlinkingSuspended(false);
+    m_frame->selection().setCaretBlinkingSuspended(false);
 
     bool defaultPrevented = dispatchSyntheticTouchEventIfEnabled(mouseEvent);
     if (defaultPrevented)
@@ -1618,7 +1604,7 @@
     else
         gestureIndicator = adoptPtr(new UserGestureIndicator(DefinitelyProcessingUserGesture));
 
-#if OS(WINDOWS)
+#if OS(WIN)
     if (Page* page = m_frame->page())
         page->handleMouseReleaseForPanScrolling(m_frame, mouseEvent);
 #endif
@@ -1654,7 +1640,7 @@
     bool swallowMouseUpEvent = !dispatchMouseEvent(eventNames().mouseupEvent, mev.targetNode(), true, m_clickCount, mouseEvent, false);
 
     bool contextMenuEvent = mouseEvent.button() == RightButton;
-#if OS(DARWIN)
+#if OS(MACOSX)
     // FIXME: The Mac port achieves the same behavior by checking whether the context menu is currently open in WebPage::mouseEvent(). Consider merging the implementations.
     if (mouseEvent.button() == LeftButton && mouseEvent.modifiers() & PlatformEvent::CtrlKey)
         contextMenuEvent = true;
@@ -1965,9 +1951,9 @@
         RenderLayer* layerForNodeUnderMouse = layerForNode(m_nodeUnderMouse.get());
         Page* page = m_frame->page();
 
-        if (m_lastNodeUnderMouse && (!m_nodeUnderMouse || m_nodeUnderMouse->document() != m_frame->document())) {
+        if (m_lastNodeUnderMouse && (!m_nodeUnderMouse || &m_nodeUnderMouse->document() != m_frame->document())) {
             // The mouse has moved between frames.
-            if (Frame* frame = m_lastNodeUnderMouse->document()->frame()) {
+            if (Frame* frame = m_lastNodeUnderMouse->document().frame()) {
                 if (FrameView* frameView = frame->view())
                     frameView->mouseExitedContentArea();
             }
@@ -1977,9 +1963,9 @@
                 scrollableAreaForLastNode->mouseExitedContentArea();
         }
 
-        if (m_nodeUnderMouse && (!m_lastNodeUnderMouse || m_lastNodeUnderMouse->document() != m_frame->document())) {
+        if (m_nodeUnderMouse && (!m_lastNodeUnderMouse || &m_lastNodeUnderMouse->document() != m_frame->document())) {
             // The mouse has moved between frames.
-            if (Frame* frame = m_nodeUnderMouse->document()->frame()) {
+            if (Frame* frame = m_nodeUnderMouse->document().frame()) {
                 if (FrameView* frameView = frame->view())
                     frameView->mouseEnteredContentArea();
             }
@@ -1989,7 +1975,7 @@
                 scrollableAreaForNodeUnderMouse->mouseEnteredContentArea();
         }
 
-        if (m_lastNodeUnderMouse && m_lastNodeUnderMouse->document() != m_frame->document()) {
+        if (m_lastNodeUnderMouse && &m_lastNodeUnderMouse->document() != m_frame->document()) {
             m_lastNodeUnderMouse = 0;
             m_lastScrollbarUnderMouse = 0;
             m_lastInstanceUnderMouse = 0;
@@ -2047,8 +2033,8 @@
     // mouseup will set a selection inside it, which will call
     // FrameSelection::setFocusedNodeIfNeeded.
     if (element
-        && m_frame->selection()->isRange()
-        && m_frame->selection()->toNormalizedRange()->compareNode(element, IGNORE_EXCEPTION) == Range::NODE_INSIDE
+        && m_frame->selection().isRange()
+        && m_frame->selection().toNormalizedRange()->compareNode(element, IGNORE_EXCEPTION) == Range::NODE_INSIDE
         && element->isDescendantOf(m_frame->document()->focusedElement()))
         return true;
 
@@ -2093,15 +2079,15 @@
 
 bool EventHandler::shouldTurnVerticalTicksIntoHorizontal(const HitTestResult& result, const PlatformWheelEvent& event) const
 {
-#if OS(UNIX) && !OS(DARWIN)
+#if OS(ANDROID) || OS(MACOSX) || OS(WIN)
+    UNUSED_PARAM(result);
+    UNUSED_PARAM(event);
+    return false;
+#else
     // GTK+ must scroll horizontally if the mouse pointer is on top of the
     // horizontal scrollbar while scrolling with the wheel.
     // This code comes from gtk/EventHandlerGtk.cpp.
     return !event.hasPreciseScrollingDeltas() && result.scrollbar() && result.scrollbar()->orientation() == HorizontalScrollbar;
-#else
-    UNUSED_PARAM(result);
-    UNUSED_PARAM(event);
-    return false;
 #endif
 }
 
@@ -2398,7 +2384,7 @@
         Node* innerNode = result.targetNode();
         if (!result.isLiveLink() && innerNode && (innerNode->isContentEditable() || innerNode->isTextNode())) {
             selectClosestWordFromHitTestResult(result, DontAppendTrailingWhitespace);
-            if (m_frame->selection()->isRange()) {
+            if (m_frame->selection().isRange()) {
                 focusDocumentView();
                 return true;
             }
@@ -2463,7 +2449,7 @@
     if (!widget->isFrameView())
         return false;
 
-    return toFrameView(widget)->frame()->eventHandler()->handleGestureEvent(gestureEvent);
+    return toFrameView(widget)->frame().eventHandler()->handleGestureEvent(gestureEvent);
 }
 
 bool EventHandler::passGestureEventToWidgetIfPossible(const PlatformGestureEvent& gestureEvent, RenderObject* renderer)
@@ -2699,12 +2685,12 @@
     HitTestRequest request(HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
     MouseEventWithHitTestResults mev = doc->prepareMouseEvent(request, viewportPos, event);
 
-    if (!m_frame->selection()->contains(viewportPos)
+    if (!m_frame->selection().contains(viewportPos)
         && !mev.scrollbar()
         // FIXME: In the editable case, word selection sometimes selects content that isn't underneath the mouse.
         // If the selection is non-editable, we do word selection to make it easier to use the contextual menu items
         // available for text selections.  But only if we're above text.
-        && (m_frame->selection()->isContentEditable() || (mev.targetNode() && mev.targetNode()->isTextNode()))) {
+        && (m_frame->selection().isContentEditable() || (mev.targetNode() && mev.targetNode()->isTextNode()))) {
         m_mouseDownMayStartSelect = true; // context menu events are always allowed to perform a selection
 
         if (mev.hitTestResult().isMisspelled())
@@ -2733,7 +2719,7 @@
 
     static const int kContextMenuMargin = 1;
 
-#if OS(WINDOWS)
+#if OS(WIN)
     int rightAligned = ::GetSystemMetrics(SM_MENUDROPALIGNMENT);
 #else
     int rightAligned = 0;
@@ -2741,11 +2727,11 @@
     IntPoint location;
 
     Element* focusedElement = doc->focusedElement();
-    FrameSelection* selection = m_frame->selection();
-    Position start = selection->selection().start();
+    FrameSelection& selection = m_frame->selection();
+    Position start = selection.selection().start();
 
-    if (start.deprecatedNode() && (selection->rootEditableElement() || selection->isRange())) {
-        RefPtr<Range> selectionRange = selection->toNormalizedRange();
+    if (start.deprecatedNode() && (selection.rootEditableElement() || selection.isRange())) {
+        RefPtr<Range> selectionRange = selection.toNormalizedRange();
         IntRect firstRect = m_frame->editor().firstRectForRange(selectionRange.get());
 
         int x = rightAligned ? firstRect.maxX() : firstRect.x();
@@ -2781,7 +2767,7 @@
     // The contextmenu event is a mouse event even when invoked using the keyboard.
     // This is required for web compatibility.
 
-#if OS(WINDOWS)
+#if OS(WIN)
     PlatformEvent::Type eventType = PlatformEvent::MouseReleased;
 #else
     PlatformEvent::Type eventType = PlatformEvent::MousePressed;
@@ -2794,7 +2780,7 @@
 
 bool EventHandler::sendContextMenuEventForGesture(const PlatformGestureEvent& event)
 {
-#if OS(WINDOWS)
+#if OS(WIN)
     PlatformEvent::Type eventType = PlatformEvent::MouseReleased;
 #else
     PlatformEvent::Type eventType = PlatformEvent::MousePressed;
@@ -2970,7 +2956,7 @@
     if (initialKeyEvent.windowsVirtualKeyCode() == VK_CAPITAL)
         capsLockStateMayHaveChanged();
 
-#if OS(WINDOWS)
+#if OS(WIN)
     if (panScrollInProgress()) {
         // If a key is pressed while the panScroll is in progress then we want to stop
         if (initialKeyEvent.type() == PlatformEvent::KeyDown || initialKeyEvent.type() == PlatformEvent::RawKeyDown)
@@ -3287,7 +3273,7 @@
     if (!dragController.populateDragClipboard(m_frame, dragState(), m_mouseDownPos))
         return false;
     m_mouseDownMayStartDrag = dispatchDragSrcEvent(eventNames().dragstartEvent, m_mouseDown)
-        && !m_frame->selection()->isInPasswordField();
+        && !m_frame->selection().isInPasswordField();
 
     // Invalidate clipboard here against anymore pasteboard writing for security. The drag
     // image can still be changed as we drag, but not the pasteboard data.
@@ -3466,7 +3452,7 @@
 
 void EventHandler::sendResizeEvent()
 {
-    m_frame->document()->enqueueWindowEvent(Event::create(eventNames().resizeEvent, false, false));
+    m_frame->document()->enqueueWindowEvent(Event::create(eventNames().resizeEvent));
 }
 
 void EventHandler::sendScrollEvent()
@@ -3636,15 +3622,13 @@
             if (node->isTextNode())
                 node = EventPathWalker::parent(node);
 
-            Document* doc = node->document();
+            Document& doc = node->document();
             // Record the originating touch document even if it does not have a touch listener.
             if (freshTouchEvents) {
-                m_originatingTouchPointDocument = doc;
+                m_originatingTouchPointDocument = &doc;
                 freshTouchEvents = false;
             }
-            if (!doc)
-                continue;
-            if (!doc->hasTouchEventHandlers())
+            if (!doc.hasTouchEventHandlers())
                 continue;
             m_originatingTouchPointTargets.set(touchPointTargetKey, node);
             touchTarget = node;
@@ -3666,12 +3650,10 @@
 
         if (!touchTarget.get())
             continue;
-        Document* doc = touchTarget->toNode()->document();
-        if (!doc)
+        Document& doc = touchTarget->toNode()->document();
+        if (!doc.hasTouchEventHandlers())
             continue;
-        if (!doc->hasTouchEventHandlers())
-            continue;
-        Frame* targetFrame = doc->frame();
+        Frame* targetFrame = doc.frame();
         if (!targetFrame)
             continue;
 
@@ -3740,7 +3722,7 @@
 
             RefPtr<TouchEvent> touchEvent =
                 TouchEvent::create(effectiveTouches.get(), targetTouches.get(), changedTouches[state].m_touches.get(),
-                                   stateName, touchEventTarget->toNode()->document()->defaultView(),
+                                   stateName, touchEventTarget->toNode()->document().defaultView(),
                                    0, 0, 0, 0, event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey());
             touchEventTarget->toNode()->dispatchTouchEvent(touchEvent.get());
             swallowedEvent = swallowedEvent || touchEvent->defaultPrevented() || touchEvent->defaultHandled();
@@ -3786,12 +3768,12 @@
     // really strange (having the whole frame be greyed out), so we deselect the
     // selection.
     IntPoint p = m_frame->view()->windowToContents(mev.event().position());
-    if (m_frame->selection()->contains(p)) {
+    if (m_frame->selection().contains(p)) {
         VisiblePosition visiblePos(
             mev.targetNode()->renderer()->positionForPoint(mev.localPoint()));
         VisibleSelection newSelection(visiblePos);
-        if (m_frame->selection()->shouldChangeSelection(newSelection))
-            m_frame->selection()->setSelection(newSelection);
+        if (m_frame->selection().shouldChangeSelection(newSelection))
+            m_frame->selection().setSelection(newSelection);
     }
 
     subframe->eventHandler()->handleMousePressEvent(mev.event());
@@ -3824,7 +3806,7 @@
     if (!widget->isFrameView())
         return false;
 
-    return toFrameView(widget)->frame()->eventHandler()->handleWheelEvent(wheelEvent);
+    return toFrameView(widget)->frame().eventHandler()->handleWheelEvent(wheelEvent);
 }
 
 bool EventHandler::passWidgetMouseDownEventToWidget(const MouseEventWithHitTestResults& event)
@@ -3851,7 +3833,7 @@
 
 unsigned EventHandler::accessKeyModifiers()
 {
-#if OS(DARWIN)
+#if OS(MACOSX)
     return PlatformEvent::CtrlKey | PlatformEvent::AltKey;
 #else
     return PlatformEvent::AltKey;
diff --git a/Source/core/page/EventHandler.h b/Source/core/page/EventHandler.h
index 3e95ae6..5c5c4b9 100644
--- a/Source/core/page/EventHandler.h
+++ b/Source/core/page/EventHandler.h
@@ -99,7 +99,7 @@
     Node* mousePressNode() const;
     void setMousePressNode(PassRefPtr<Node>);
 
-#if OS(WINDOWS)
+#if OS(WIN)
     void startPanScrolling(RenderObject*);
 #endif
 
@@ -254,7 +254,6 @@
 
     bool handleDrag(const MouseEventWithHitTestResults&, CheckDragHysteresis);
     bool tryStartDrag(const MouseEventWithHitTestResults&);
-    bool handleMouseUp(const MouseEventWithHitTestResults&);
     void clearDragState();
 
     bool dispatchDragSrcEvent(const AtomicString& eventType, const PlatformMouseEvent&);
diff --git a/Source/core/page/EventSource.cpp b/Source/core/page/EventSource.cpp
index e0973ad..d9cedc5 100644
--- a/Source/core/page/EventSource.cpp
+++ b/Source/core/page/EventSource.cpp
@@ -42,7 +42,7 @@
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/MessageEvent.h"
 #include "core/dom/ScriptExecutionContext.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/loader/ThreadableLoader.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/DOMWindow.h"
diff --git a/Source/core/page/FocusController.cpp b/Source/core/page/FocusController.cpp
index 0e7540a..81c4129 100644
--- a/Source/core/page/FocusController.cpp
+++ b/Source/core/page/FocusController.cpp
@@ -81,7 +81,7 @@
         ShadowRoot* shadowRoot = toShadowRoot(root);
         return shadowRoot->isYoungest() ? shadowRoot->host() : shadowRoot->insertionPoint();
     }
-    if (Frame* frame = root->document()->frame())
+    if (Frame* frame = root->document().frame())
         return frame->ownerElement();
     return 0;
 }
@@ -94,7 +94,7 @@
         root = n;
     // The result is not always a ShadowRoot nor a DocumentNode since
     // a starting node is in an orphaned tree in composed shadow tree.
-    return FocusNavigationScope(root->treeScope());
+    return FocusNavigationScope(&root->treeScope());
 }
 
 FocusNavigationScope FocusNavigationScope::ownedByNonFocusableFocusScopeOwner(Node* node)
@@ -137,7 +137,7 @@
 
     if (!focused && document->focusedElement())
         document->focusedElement()->dispatchBlurEvent(0);
-    document->dispatchWindowEvent(Event::create(focused ? eventNames().focusEvent : eventNames().blurEvent, false, false));
+    document->dispatchWindowEvent(Event::create(focused ? eventNames().focusEvent : eventNames().blurEvent));
     if (focused && document->focusedElement())
         document->focusedElement()->dispatchFocusEvent(0, FocusDirectionPage);
 }
@@ -221,13 +221,13 @@
 
     // Now that the frame is updated, fire events and update the selection focused states of both frames.
     if (oldFrame && oldFrame->view()) {
-        oldFrame->selection()->setFocused(false);
-        oldFrame->document()->dispatchWindowEvent(Event::create(eventNames().blurEvent, false, false));
+        oldFrame->selection().setFocused(false);
+        oldFrame->document()->dispatchWindowEvent(Event::create(eventNames().blurEvent));
     }
 
     if (newFrame && newFrame->view() && isFocused()) {
-        newFrame->selection()->setFocused(true);
-        newFrame->document()->dispatchWindowEvent(Event::create(eventNames().focusEvent, false, false));
+        newFrame->selection().setFocused(true);
+        newFrame->document()->dispatchWindowEvent(Event::create(eventNames().focusEvent));
     }
 
     m_isChangingFocusedFrame = false;
@@ -254,7 +254,7 @@
         setFocusedFrame(m_page->mainFrame());
 
     if (m_focusedFrame->view()) {
-        m_focusedFrame->selection()->setFocused(focused);
+        m_focusedFrame->selection().setFocused(focused);
         dispatchEventsOnWindowAndFocusedNode(m_focusedFrame->document(), focused);
     }
 }
@@ -319,7 +319,7 @@
     bool caretBrowsing = frame->settings() && frame->settings()->caretBrowsingEnabled();
 
     if (caretBrowsing && !currentNode)
-        currentNode = frame->selection()->start().deprecatedNode();
+        currentNode = frame->selection().start().deprecatedNode();
 
     document->updateLayoutIgnorePendingStylesheets();
 
@@ -368,21 +368,20 @@
     // FIXME: It would be nice to just be able to call setFocusedElement(node)
     // here, but we can't do that because some elements (e.g. HTMLInputElement
     // and HTMLTextAreaElement) do extra work in their focus() methods.
-    Document* newDocument = element->document();
+    Document& newDocument = element->document();
 
-    if (newDocument != document) {
+    if (&newDocument != document) {
         // Focus is going away from this document, so clear the focused node.
         document->setFocusedElement(0);
     }
 
-    if (newDocument)
-        setFocusedFrame(newDocument->frame());
+    setFocusedFrame(newDocument.frame());
 
     if (caretBrowsing) {
         Position position = firstPositionInOrBeforeNode(element);
         VisibleSelection newSelection(position, position, DOWNSTREAM);
-        if (frame->selection()->shouldChangeSelection(newSelection))
-            frame->selection()->setSelection(newSelection);
+        if (frame->selection().shouldChangeSelection(newSelection))
+            frame->selection().setSelection(newSelection);
     }
 
     element->focus(false, direction);
@@ -562,7 +561,7 @@
     ASSERT(node->rendererIsEditable());
 
     Node* root = node->rootEditableElement();
-    Frame* frame = node->document()->frame();
+    Frame* frame = node->document().frame();
     if (!frame || !root)
         return false;
 
@@ -577,22 +576,22 @@
     if (oldFocusedFrame->document() != newFocusedFrame->document())
         return;
 
-    FrameSelection* s = oldFocusedFrame->selection();
-    if (s->isNone())
+    FrameSelection& selection = oldFocusedFrame->selection();
+    if (selection.isNone())
         return;
 
     bool caretBrowsing = oldFocusedFrame->settings()->caretBrowsingEnabled();
     if (caretBrowsing)
         return;
 
-    Node* selectionStartNode = s->selection().start().deprecatedNode();
+    Node* selectionStartNode = selection.selection().start().deprecatedNode();
     if (selectionStartNode == newFocusedNode || selectionStartNode->isDescendantOf(newFocusedNode) || selectionStartNode->deprecatedShadowAncestorNode() == newFocusedNode)
         return;
 
     if (Node* mousePressNode = newFocusedFrame->eventHandler()->mousePressNode()) {
         if (mousePressNode->renderer() && !mousePressNode->canStartSelection()) {
             // Don't clear the selection for contentEditable elements, but do clear it for input and textarea. See bug 38696.
-            Node * root = s->rootEditableElement();
+            Node* root = selection.rootEditableElement();
             if (!root)
                 return;
 
@@ -603,7 +602,7 @@
         }
     }
 
-    s->clear();
+    selection.clear();
 }
 
 bool FocusController::setFocusedElement(Element* element, PassRefPtr<Frame> newFocusedFrame, FocusDirection direction)
@@ -629,7 +628,7 @@
         return true;
     }
 
-    RefPtr<Document> newDocument = element->document();
+    RefPtr<Document> newDocument = &element->document();
 
     if (newDocument && newDocument->focusedElement() == element)
         return true;
@@ -666,7 +665,7 @@
         view->updateControlTints();
     }
 
-    focusedOrMainFrame()->selection()->pageActivationChanged();
+    focusedOrMainFrame()->selection().pageActivationChanged();
 }
 
 static void contentAreaDidShowOrHide(ScrollableArea* scrollableArea, bool didShow)
@@ -738,7 +737,7 @@
         // If 2 nodes are intersecting, do hit test to find which node in on top.
         LayoutUnit x = intersectionRect.x() + intersectionRect.width() / 2;
         LayoutUnit y = intersectionRect.y() + intersectionRect.height() / 2;
-        HitTestResult result = candidate.visibleNode->document()->page()->mainFrame()->eventHandler()->hitTestResultAtPoint(IntPoint(x, y), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent);
+        HitTestResult result = candidate.visibleNode->document().page()->mainFrame()->eventHandler()->hitTestResultAtPoint(IntPoint(x, y), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent);
         if (candidate.visibleNode->contains(result.innerNode())) {
             closest = candidate;
             return;
@@ -788,7 +787,7 @@
 
 bool FocusController::advanceFocusDirectionallyInContainer(Node* container, const LayoutRect& startingRect, FocusDirection direction)
 {
-    if (!container || !container->document())
+    if (!container)
         return false;
 
     LayoutRect newStartingRect = startingRect;
@@ -814,7 +813,7 @@
         ASSERT(frameElement->contentFrame());
 
         if (focusCandidate.isOffscreenAfterScrolling) {
-            scrollInDirection(focusCandidate.visibleNode->document(), direction);
+            scrollInDirection(&focusCandidate.visibleNode->document(), direction);
             return true;
         }
         // Navigate into a new frame.
diff --git a/Source/core/page/Frame.cpp b/Source/core/page/Frame.cpp
index 2aa9a65..c9ed2a3 100644
--- a/Source/core/page/Frame.cpp
+++ b/Source/core/page/Frame.cpp
@@ -34,6 +34,7 @@
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/DocumentType.h"
 #include "core/dom/Event.h"
+#include "core/dom/WheelController.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
 #include "core/editing/InputMethodController.h"
@@ -41,6 +42,7 @@
 #include "core/editing/markup.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/html/HTMLFrameElementBase.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/page/Chrome.h"
@@ -78,7 +80,7 @@
 {
     if (!ownerElement)
         return 0;
-    return ownerElement->document()->frame();
+    return ownerElement->document().frame();
 }
 
 static inline float parentPageZoomFactor(Frame* frame)
@@ -133,6 +135,7 @@
     RefPtr<Frame> frame = adoptRef(new Frame(page, ownerElement, client));
     if (!ownerElement)
         page->setMainFrame(frame);
+    InspectorInstrumentation::frameAttachedToParent(frame.get());
     return frame.release();
 }
 
@@ -163,7 +166,7 @@
     HTMLFrameOwnerElement* owner = doc->ownerElement();
     if (!owner)
         return false;
-    return owner->treeScope() == scope;
+    return &owner->treeScope() == scope;
 }
 
 void Frame::addDestructionObserver(FrameDestructionObserver* observer)
@@ -208,7 +211,7 @@
 {
     m_orientation = orientation;
     if (Document* doc = document())
-        doc->dispatchWindowEvent(Event::create(eventNames().orientationchangeEvent, false, false));
+        doc->dispatchWindowEvent(Event::create(eventNames().orientationchangeEvent));
 }
 #endif // ENABLE(ORIENTATION_EVENTS)
 
@@ -303,25 +306,24 @@
 {
     ASSERT_ARG(widget, widget);
 
-    if (RenderWidget* renderer = RenderWidget::find(widget))
+    if (RenderWidget* renderer = RenderWidget::find(widget)) {
         if (Node* node = renderer->node())
-            return node->document()->frame();
+            return node->document().frame();
+    }
 
     // Assume all widgets are either a FrameView or owned by a RenderWidget.
     // FIXME: That assumption is not right for scroll bars!
     ASSERT_WITH_SECURITY_IMPLICATION(widget->isFrameView());
-    return toFrameView(widget)->frame();
+    return &toFrameView(widget)->frame();
 }
 
 void Frame::clearTimers(FrameView *view, Document *document)
 {
     if (view) {
         view->unscheduleRelayout();
-        if (view->frame()) {
-            if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
-                view->frame()->animation()->suspendAnimationsForDocument(document);
-            view->frame()->eventHandler()->stopAutoscrollTimer();
-        }
+        if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+            view->frame().animation()->suspendAnimationsForDocument(document);
+        view->frame().eventHandler()->stopAutoscrollTimer();
     }
 }
 
@@ -400,12 +402,12 @@
 
 String Frame::selectedText() const
 {
-    return selection()->selectedText();
+    return selection().selectedText();
 }
 
 String Frame::selectedTextForClipboard() const
 {
-    return selection()->selectedTextForClipboard();
+    return selection().selectedTextForClipboard();
 }
 
 VisiblePosition Frame::visiblePositionForPoint(const IntPoint& framePoint)
@@ -433,7 +435,7 @@
 
     if (contentRenderer())
         result = eventHandler()->hitTestResultAtPoint(pt, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
-    return result.innerNode() ? result.innerNode()->document() : 0;
+    return result.innerNode() ? &result.innerNode()->document() : 0;
 }
 
 PassRefPtr<Range> Frame::rangeForPoint(const IntPoint& framePoint)
@@ -460,7 +462,7 @@
     return 0;
 }
 
-void Frame::createView(const IntSize& viewportSize, const StyleColor& backgroundColor, bool transparent,
+void Frame::createView(const IntSize& viewportSize, const Color& backgroundColor, bool transparent,
     const IntSize& fixedLayoutSize, bool useFixedLayout, ScrollbarMode horizontalScrollbarMode, bool horizontalLock,
     ScrollbarMode verticalScrollbarMode, bool verticalLock)
 {
@@ -487,7 +489,7 @@
     setView(frameView);
 
     if (backgroundColor.isValid())
-        frameView->updateBackgroundRecursively(backgroundColor.color(), transparent);
+        frameView->updateBackgroundRecursively(backgroundColor, transparent);
 
     if (isMainFrame)
         frameView->setParentVisible(true);
@@ -558,7 +560,7 @@
     m_pageZoomFactor = pageZoomFactor;
     m_textZoomFactor = textZoomFactor;
 
-    document->recalcStyle(Node::Force);
+    document->recalcStyle(Force);
 
     for (RefPtr<Frame> child = tree()->firstChild(); child; child = child->tree()->nextSibling())
         child->setPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor);
@@ -585,7 +587,7 @@
     unsigned count = 0;
     for (const Frame* frame = this; frame; frame = frame->tree()->traverseNext()) {
         if (frame->document())
-            count += frame->document()->wheelEventHandlerCount();
+            count += WheelController::from(frame->document())->wheelEventHandlerCount();
     }
 
     m_page->chrome().client().numWheelEventHandlersChanged(count);
@@ -677,14 +679,14 @@
 
 PassOwnPtr<DragImage> Frame::dragImageForSelection()
 {
-    if (!selection()->isRange())
+    if (!selection().isRange())
         return nullptr;
 
     const ScopedFramePaintingState state(this, 0);
     m_view->setPaintBehavior(PaintBehaviorSelectionOnly | PaintBehaviorFlattenCompositingLayers);
     document()->updateLayout();
 
-    IntRect paintingRect = enclosingIntRect(selection()->bounds());
+    IntRect paintingRect = enclosingIntRect(selection().bounds());
 
     float deviceScaleFactor = 1;
     if (m_page)
diff --git a/Source/core/page/Frame.h b/Source/core/page/Frame.h
index 1f17809..1a912eb 100644
--- a/Source/core/page/Frame.h
+++ b/Source/core/page/Frame.h
@@ -28,7 +28,6 @@
 #ifndef Frame_h
 #define Frame_h
 
-#include "core/css/StyleColor.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/NavigationScheduler.h"
 #include "core/page/AdjustViewSizeOrNot.h"
@@ -48,6 +47,7 @@
     class Editor;
     class Element;
     class EventHandler;
+    class FetchContext;
     class FloatSize;
     class FrameDestructionObserver;
     class FrameSelection;
@@ -73,7 +73,7 @@
 
         void init();
         void setView(PassRefPtr<FrameView>);
-        void createView(const IntSize&, const StyleColor&, bool,
+        void createView(const IntSize&, const Color&, bool,
             const IntSize& fixedLayoutSize = IntSize(), bool useFixedLayout = false, ScrollbarMode = ScrollbarAuto, bool horizontalLock = false,
             ScrollbarMode = ScrollbarAuto, bool verticalLock = false);
 
@@ -98,10 +98,11 @@
         EventHandler* eventHandler() const;
         FrameLoader* loader() const;
         NavigationScheduler* navigationScheduler() const;
-        FrameSelection* selection() const;
+        FrameSelection& selection() const;
         FrameTree* tree() const;
         AnimationController* animation() const;
         InputMethodController& inputMethodController() const;
+        FetchContext& fetchContext() const { return loader()->fetchContext(); }
         ScriptController* script();
 
         RenderView* contentRenderer() const; // Root of the render tree for the document contained in this frame.
@@ -185,7 +186,7 @@
 
         OwnPtr<ScriptController> m_script;
         const OwnPtr<Editor> m_editor;
-        OwnPtr<FrameSelection> m_selection;
+        const OwnPtr<FrameSelection> m_selection;
         OwnPtr<EventHandler> m_eventHandler;
         OwnPtr<AnimationController> m_animationController;
         OwnPtr<InputMethodController> m_inputMethodController;
@@ -230,9 +231,9 @@
         return m_domWindow.get();
     }
 
-    inline FrameSelection* Frame::selection() const
+    inline FrameSelection& Frame::selection() const
     {
-        return m_selection.get();
+        return *m_selection;
     }
 
     inline Editor& Frame::editor() const
diff --git a/Source/core/page/FrameView.cpp b/Source/core/page/FrameView.cpp
index 65d7c96..ee27429 100644
--- a/Source/core/page/FrameView.cpp
+++ b/Source/core/page/FrameView.cpp
@@ -37,13 +37,13 @@
 #include "core/dom/OverflowEvent.h"
 #include "core/editing/FrameSelection.h"
 #include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/html/HTMLFrameElement.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLPlugInImageElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/EventHandler.h"
@@ -59,6 +59,8 @@
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/text/TextStream.h"
+#include "core/rendering/LayoutIndicator.h"
+#include "core/rendering/RenderCounter.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerBacking.h"
@@ -179,21 +181,16 @@
     , m_didRunAutosize(false)
     , m_hasSoftwareFilters(false)
     , m_visibleContentScaleFactor(1)
+    , m_partialLayout()
 {
+    ASSERT(m_frame);
     init();
 
-    // FIXME: Can m_frame ever be null here?
-    if (!m_frame)
+    if (!isMainFrame())
         return;
 
-    Page* page = m_frame->page();
-    if (!page)
-        return;
-
-    if (m_frame == page->mainFrame()) {
-        ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
-        ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed);
-    }
+    ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
+    ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed);
 }
 
 PassRefPtr<FrameView> FrameView::create(Frame* frame)
@@ -231,12 +228,11 @@
     ASSERT(!m_scrollCorner);
     ASSERT(m_actionScheduler->isEmpty());
 
-    if (m_frame) {
-        ASSERT(m_frame->view() != this || !m_frame->contentRenderer());
-        RenderPart* renderer = m_frame->ownerRenderer();
-        if (renderer && renderer->widget() == this)
-            renderer->setWidget(0);
-    }
+    ASSERT(m_frame);
+    ASSERT(m_frame->view() != this || !m_frame->contentRenderer());
+    RenderPart* renderer = m_frame->ownerRenderer();
+    if (renderer && renderer->widget() == this)
+        renderer->setWidget(0);
 }
 
 void FrameView::reset()
@@ -279,6 +275,7 @@
     m_firstVisuallyNonEmptyLayoutCallbackPending = true;
     m_maintainScrollPositionAnchor = 0;
     m_disableRepaints = 0;
+    m_partialLayout.reset();
 }
 
 void FrameView::removeFromAXObjectCache()
@@ -287,12 +284,6 @@
         cache->remove(this);
 }
 
-void FrameView::clearFrame()
-{
-    RELEASE_ASSERT(!isInLayout());
-    m_frame = 0;
-}
-
 void FrameView::resetScrollbars()
 {
     // Reset the document's scrollbars back to our defaults before we yield the floor.
@@ -313,7 +304,7 @@
     m_size = LayoutSize();
 
     // Propagate the marginwidth/height and scrolling modes to the view.
-    Element* ownerElement = m_frame ? m_frame->ownerElement() : 0;
+    Element* ownerElement = m_frame->ownerElement();
     if (ownerElement && (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))) {
         HTMLFrameElementBase* frameElt = toHTMLFrameElementBase(ownerElement);
         if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
@@ -339,7 +330,7 @@
     // right now, otherwise it won't be able to reach the topDocument()'s axObject cache later.
     removeFromAXObjectCache();
 
-    if (m_frame && m_frame->page()) {
+    if (m_frame->page()) {
         if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator())
             scrollingCoordinator->willDestroyScrollableArea(this);
     }
@@ -366,13 +357,13 @@
     ScrollbarOverlayStyle oldOverlayStyle = scrollbarOverlayStyle();
     ScrollbarOverlayStyle overlayStyle = ScrollbarOverlayStyleDefault;
 
-    StyleColor backgroundColor = documentBackgroundColor();
+    Color backgroundColor = documentBackgroundColor();
     if (backgroundColor.isValid()) {
         // Reduce the background color from RGB to a lightness value
         // and determine which scrollbar style to use based on a lightness
         // heuristic.
         double hue, saturation, lightness;
-        backgroundColor.color().getHSL(hue, saturation, lightness);
+        backgroundColor.getHSL(hue, saturation, lightness);
         if (lightness <= .5)
             overlayStyle = ScrollbarOverlayStyleLight;
     }
@@ -387,10 +378,8 @@
 
     reset();
 
-    if (m_frame) {
-        if (RenderPart* renderer = m_frame->ownerRenderer())
-            renderer->viewCleared();
-    }
+    if (RenderPart* renderer = m_frame->ownerRenderer())
+        renderer->viewCleared();
 
     setScrollbarsSuppressed(true);
 }
@@ -408,9 +397,6 @@
         return;
     }
 
-    if (!m_frame)
-        return;
-
     RenderPart* renderer = m_frame->ownerRenderer();
     if (!renderer)
         return;
@@ -429,8 +415,8 @@
 
     // Autosized font sizes depend on the width of the viewing area.
     if (newRect.width() != oldRect.width()) {
-        Page* page = m_frame ? m_frame->page() : 0;
-        if (page && page->mainFrame() == m_frame && page->settings().textAutosizingEnabled()) {
+        Page* page = m_frame->page();
+        if (isMainFrame() && page->settings().textAutosizingEnabled()) {
             for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
                 m_frame->document()->textAutosizer()->recalculateMultipliers();
         }
@@ -457,6 +443,21 @@
     return false;
 }
 
+RenderView* FrameView::renderView() const
+{
+    return frame().contentRenderer();
+}
+
+int FrameView::mapFromLayoutToCSSUnits(LayoutUnit value) const
+{
+    return value / frame().pageZoomFactor();
+}
+
+LayoutUnit FrameView::mapFromCSSToLayoutUnits(int value) const
+{
+    return value * frame().pageZoomFactor();
+}
+
 void FrameView::setMarginWidth(LayoutUnit w)
 {
     // make it update the rendering area when set
@@ -489,7 +490,7 @@
 PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
 {
     if (Settings* settings = m_frame->settings()) {
-        if (!settings->allowCustomScrollbarInMainFrame() && m_frame->page() && m_frame->page()->mainFrame() == m_frame)
+        if (!settings->allowCustomScrollbarInMainFrame() && isMainFrame())
             return ScrollView::createScrollbar(orientation);
     }
 
@@ -525,13 +526,13 @@
     ScrollView::setContentsSize(size);
     ScrollView::contentsResized();
 
-    Page* page = frame() ? frame()->page() : 0;
+    Page* page = frame().page();
     if (!page)
         return;
 
     updateScrollableAreaSet();
 
-    page->chrome().contentsSizeChanged(frame(), size); // Notify only.
+    page->chrome().contentsSizeChanged(m_frame.get(), size); // Notify only.
 
     m_deferSetNeedsLayouts--;
 
@@ -649,7 +650,7 @@
         // Seamless documents begin with heights of 0; we special case that here
         // to correctly render documents that don't need scrollbars.
         IntSize fullVisibleSize = visibleContentRect(IncludeScrollbars).size();
-        bool isSeamlessDocument = frame() && frame()->document() && frame()->document()->shouldDisplaySeamlesslyWithParent();
+        bool isSeamlessDocument = frame().document() && frame().document()->shouldDisplaySeamlesslyWithParent();
         vMode = (isSeamlessDocument && !fullVisibleSize.height()) ? ScrollbarAlwaysOff : ScrollbarAuto;
     } else {
         hMode = ScrollbarAlwaysOff;
@@ -669,7 +670,8 @@
                 // It's sufficient to just check the X overflow,
                 // since it's illegal to have visible in only one direction.
                 RenderObject* o = rootRenderer->style()->overflowX() == OVISIBLE && isHTMLHtmlElement(document->documentElement()) ? body->renderer() : rootRenderer;
-                applyOverflowToViewport(o, hMode, vMode);
+                if (o->style())
+                    applyOverflowToViewport(o, hMode, vMode);
             }
         } else if (rootRenderer)
             applyOverflowToViewport(rootRenderer, hMode, vMode);
@@ -843,7 +845,7 @@
     // Don't schedule more layouts, we're in one.
     TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
 
-    if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !frame()->document()->shouldDisplaySeamlesslyWithParent()) {
+    if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !frame().document()->shouldDisplaySeamlesslyWithParent()) {
         // This is a new top-level layout. If there are any remaining tasks from the previous layout, finish them now.
         m_inSynchronousPostLayout = true;
         performPostLayoutTasks();
@@ -876,24 +878,33 @@
     // performLayout is the actual guts of layout().
     // FIXME: The 300 other lines in layout() probably belong in other helper functions
     // so that a single human could understand what layout() is actually doing.
+    {
+        bool disableLayoutState = false;
+        if (inSubtreeLayout) {
+            RenderView* view = rootForThisLayout->view();
+            disableLayoutState = view->shouldDisableLayoutStateForSubtree(rootForThisLayout);
+            view->pushLayoutState(rootForThisLayout);
+        }
+        LayoutStateDisabler layoutStateDisabler(disableLayoutState ? rootForThisLayout->view() : 0);
 
-    bool disableLayoutState = false;
-    if (inSubtreeLayout) {
-        RenderView* view = rootForThisLayout->view();
-        disableLayoutState = view->shouldDisableLayoutStateForSubtree(rootForThisLayout);
-        view->pushLayoutState(rootForThisLayout);
+        m_inLayout = true;
+
+        beginDeferredRepaints();
+        forceLayoutParentViewIfNeeded();
+
+        // Text Autosizing requires two-pass layout which is incompatible with partial layout.
+        // If enabled, only do partial layout for the second layout.
+        // FIXME (crbug.com/256657): Do not do two layouts for text autosizing.
+        PartialLayoutDisabler partialLayoutDisabler(partialLayout(), m_frame->settings() && m_frame->settings()->textAutosizingEnabled());
+
+        LayoutIndicator layoutIndicator;
+        rootForThisLayout->layout();
     }
-    LayoutStateDisabler layoutStateDisabler(disableLayoutState ? rootForThisLayout->view() : 0);
 
-    m_inLayout = true;
-    beginDeferredRepaints();
-    forceLayoutParentViewIfNeeded();
-
-    rootForThisLayout->layout(); // THIS IS WHERE LAYOUT ACTUALLY HAPPENS.
-
-    bool autosized = frame()->document()->textAutosizer()->processSubtree(rootForThisLayout);
+    bool autosized = frame().document()->textAutosizer()->processSubtree(rootForThisLayout);
     if (autosized && rootForThisLayout->needsLayout()) {
         TRACE_EVENT0("webkit", "2nd layout due to Text Autosizing");
+        LayoutIndicator layoutIndicator;
         rootForThisLayout->layout();
     }
 
@@ -911,8 +922,11 @@
         return;
     }
 
+    // Partial layouts should not happen with synchronous post layouts.
+    ASSERT(!(m_inSynchronousPostLayout && partialLayout().isStopping()));
+
     if (!m_inSynchronousPostLayout) {
-        if (frame()->document()->shouldDisplaySeamlesslyWithParent()) {
+        if (frame().document()->shouldDisplaySeamlesslyWithParent()) {
             if (RenderView* renderView = this->renderView())
                 renderView->updateWidgetPositions();
         } else {
@@ -923,13 +937,13 @@
         }
     }
 
-    if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || frame()->document()->shouldDisplaySeamlesslyWithParent())) {
+    if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || frame().document()->shouldDisplaySeamlesslyWithParent())) {
         // If we need layout or are already in a synchronous call to postLayoutTasks(),
         // defer widget updates and event dispatch until after we return. postLayoutTasks()
         // can make us need to update again, and we can get stuck in a nasty cycle unless
         // we call it through the timer here.
         m_postLayoutTasksTimer.startOneShot(0);
-        if (needsLayout()) {
+        if (!partialLayout().isStopping() && needsLayout()) {
             m_actionScheduler->pause();
             layout();
         }
@@ -946,6 +960,8 @@
     if (m_inLayout)
         return;
 
+    ASSERT(!partialLayout().isStopping());
+
     TRACE_EVENT0("webkit", "FrameView::layout");
     TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "Layout");
 
@@ -987,6 +1003,8 @@
         return;
     }
 
+    bool isPartialLayout = partialLayout().isPartialLayout();
+
     FontCachePurgePreventer fontCachePurgePreventer;
     RenderLayer* layer;
     {
@@ -994,15 +1012,16 @@
 
         m_nestedLayoutCount++;
 
+        updateCounters();
         autoSizeIfEnabled();
 
         ScrollbarMode hMode;
         ScrollbarMode vMode;
         calculateScrollbarModesForLayout(hMode, vMode);
 
-        m_doFullRepaint = !inSubtreeLayout && (m_firstLayout || toRenderView(rootForThisLayout)->printing());
+        m_doFullRepaint = !inSubtreeLayout && !isPartialLayout && (m_firstLayout || toRenderView(rootForThisLayout)->printing());
 
-        if (!inSubtreeLayout) {
+        if (!inSubtreeLayout && !isPartialLayout) {
             // Now set our scrollbar state for the layout.
             ScrollbarMode currentHMode = horizontalScrollbarMode();
             ScrollbarMode currentVMode = verticalScrollbarMode();
@@ -1049,13 +1068,14 @@
         layer = rootForThisLayout->enclosingLayer();
 
         m_actionScheduler->pause();
+
         performLayout(rootForThisLayout, inSubtreeLayout);
         m_layoutRoot = 0;
     } // Reset m_layoutSchedulingEnabled to its previous value.
 
     bool neededFullRepaint = m_doFullRepaint;
 
-    if (!inSubtreeLayout && !toRenderView(rootForThisLayout)->printing())
+    if (!inSubtreeLayout && !isPartialLayout && !toRenderView(rootForThisLayout)->printing())
         adjustViewSize();
 
     m_doFullRepaint = neededFullRepaint;
@@ -1077,11 +1097,11 @@
 
     m_layoutCount++;
 
-    if (AXObjectCache* cache = rootForThisLayout->document()->existingAXObjectCache())
+    if (AXObjectCache* cache = rootForThisLayout->document().existingAXObjectCache())
         cache->postNotification(rootForThisLayout, AXObjectCache::AXLayoutComplete, true);
     updateAnnotatedRegions();
 
-    ASSERT(!rootForThisLayout->needsLayout());
+    ASSERT(partialLayout().isStopping() || !rootForThisLayout->needsLayout());
 
     updateCanBlitOnScrollRecursively();
 
@@ -1098,10 +1118,13 @@
     if (m_nestedLayoutCount)
         return;
 
+    if (partialLayout().isStopping())
+        return;
+
 #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(!renderer->needsLayout());
+        ASSERT_WITH_SECURITY_IMPLICATION(!renderer->needsLayout());
 #endif
 
     // FIXME: It should be not possible to remove the FrameView from the frame/page during layout
@@ -1109,10 +1132,9 @@
     // in Frame/Page will fire. One of the post-layout tasks is disconnecting the Frame from
     // the page in fast/frames/crash-remove-iframe-during-object-beforeload-2.html
     // necessitating this check here.
-    ASSERT(frame());
     // ASSERT(frame()->page());
-    if (frame() && frame()->page())
-        frame()->page()->chrome().client().layoutUpdated(frame());
+    if (frame().page())
+        frame().page()->chrome().client().layoutUpdated(m_frame.get());
 }
 
 RenderBox* FrameView::embeddedContentBox() const
@@ -1309,7 +1331,7 @@
 
 IntPoint FrameView::lastKnownMousePosition() const
 {
-    return m_frame ? m_frame->eventHandler()->lastKnownMousePosition() : IntPoint();
+    return m_frame->eventHandler()->lastKnownMousePosition();
 }
 
 bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
@@ -1567,8 +1589,8 @@
 
 void FrameView::scrollPositionChanged()
 {
-    frame()->eventHandler()->sendScrollEvent();
-    frame()->eventHandler()->dispatchFakeMouseMoveEventSoon();
+    m_frame->eventHandler()->sendScrollEvent();
+    m_frame->eventHandler()->dispatchFakeMouseMoveEventSoon();
 
     if (RenderView* renderView = this->renderView()) {
         if (renderView->usesCompositing())
@@ -1598,7 +1620,7 @@
 
 bool FrameView::shouldRubberBandInDirection(ScrollDirection direction) const
 {
-    Page* page = frame() ? frame()->page() : 0;
+    Page* page = frame().page();
     if (!page)
         return ScrollView::shouldRubberBandInDirection(direction);
     return page->chrome().client().shouldRubberBandInDirection(direction);
@@ -1624,7 +1646,7 @@
 
 HostWindow* FrameView::hostWindow() const
 {
-    Page* page = frame() ? frame()->page() : 0;
+    Page* page = frame().page();
     if (!page)
         return 0;
     return &page->chrome();
@@ -1686,7 +1708,7 @@
     // be triggered before the view is attached by Frame::createView(...) setting
     // various values such as setScrollBarModes(...) for example.  An ASSERT is
     // triggered when a view is layout before being attached to a frame().
-    if (!frame()->view())
+    if (!frame().view())
         return;
 
     if (!useFixedLayout() && needsLayout())
@@ -1701,7 +1723,9 @@
 void FrameView::beginDeferredRepaints()
 {
     Page* page = m_frame->page();
-    if (page->mainFrame() != m_frame) {
+    ASSERT(page);
+
+    if (!isMainFrame()) {
         page->mainFrame()->view()->beginDeferredRepaints();
         return;
     }
@@ -1712,7 +1736,9 @@
 void FrameView::endDeferredRepaints()
 {
     Page* page = m_frame->page();
-    if (page->mainFrame() != m_frame) {
+    ASSERT(page);
+
+    if (!isMainFrame()) {
         page->mainFrame()->view()->endDeferredRepaints();
         return;
     }
@@ -1867,7 +1893,7 @@
 
     // When frame seamless is enabled, the contents of the frame could affect the layout of the parent frames.
     // Also invalidate parent frame starting from the owner element of this frame.
-    if (m_frame->ownerRenderer() && frame()->document()->shouldDisplaySeamlesslyWithParent())
+    if (m_frame->ownerRenderer() && m_frame->document()->shouldDisplaySeamlesslyWithParent())
         m_frame->ownerRenderer()->setNeedsLayout();
 
     int delay = m_frame->document()->minimumLayoutDelay();
@@ -1941,8 +1967,6 @@
     // This can return true in cases where the document does not have a body yet.
     // Document::shouldScheduleLayout takes care of preventing us from scheduling
     // layout in that case.
-    if (!m_frame)
-        return false;
 
     RenderView* renderView = this->renderView();
     return layoutPending()
@@ -2011,12 +2035,12 @@
     return m_baseBackgroundColor;
 }
 
-void FrameView::setBaseBackgroundColor(const StyleColor& backgroundColor)
+void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
 {
     if (!backgroundColor.isValid())
         m_baseBackgroundColor = Color::white;
     else
-        m_baseBackgroundColor = backgroundColor.color();
+        m_baseBackgroundColor = backgroundColor;
 
     if (RenderLayerBacking* backing = renderView() ? renderView()->layer()->backing() : 0) {
         backing->updateContentsOpaque();
@@ -2026,7 +2050,7 @@
     recalculateScrollbarOverlayStyle();
 }
 
-void FrameView::updateBackgroundRecursively(const StyleColor& backgroundColor, bool transparent)
+void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
 {
     for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
         if (FrameView* view = frame->view()) {
@@ -2176,8 +2200,8 @@
 
     m_postLayoutTasksTimer.stop();
 
-    m_frame->selection()->setCaretRectNeedsUpdate();
-    m_frame->selection()->updateAppearance();
+    m_frame->selection().setCaretRectNeedsUpdate();
+    m_frame->selection().updateAppearance();
 
     LayoutMilestones milestonesOfInterest = 0;
     LayoutMilestones milestonesAchieved = 0;
@@ -2191,10 +2215,8 @@
             m_frame->loader()->didFirstLayout();
             if (milestonesOfInterest & DidFirstLayout)
                 milestonesAchieved |= DidFirstLayout;
-            if (page) {
-                if (page->mainFrame() == m_frame)
-                    page->startCountingRelevantRepaintedObjects();
-            }
+            if (isMainFrame())
+                page->startCountingRelevantRepaintedObjects();
         }
 
         // Ensure that we always send this eventually.
@@ -2255,7 +2277,7 @@
     m_frame->eventHandler()->sendResizeEvent();
 
     Page* page = m_frame->page();
-    if (page && page->mainFrame() == m_frame)
+    if (isMainFrame())
         InspectorInstrumentation::didResizeMainFrame(page);
 }
 
@@ -2264,6 +2286,20 @@
     performPostLayoutTasks();
 }
 
+void FrameView::updateCounters()
+{
+    RenderView* view = renderView();
+    if (!view->hasRenderCounters())
+        return;
+
+    for (RenderObject* renderer = view; renderer; renderer = renderer->nextInPreOrder()) {
+        if (!renderer->isCounter())
+            continue;
+
+        toRenderCounter(renderer)->updateCounter();
+    }
+}
+
 void FrameView::autoSizeIfEnabled()
 {
     if (!m_shouldAutoSize)
@@ -2274,7 +2310,7 @@
 
     TemporaryChange<bool> changeInAutoSize(m_inAutoSize, true);
 
-    Document* document = frame()->document();
+    Document* document = frame().document();
     if (!document)
         return;
 
@@ -2348,7 +2384,7 @@
         // While loading only allow the size to increase (to avoid twitching during intermediate smaller states)
         // unless autoresize has just been turned on or the maximum size is smaller than the current size.
         if (m_didRunAutosize && size.height() <= m_maxAutoSize.height() && size.width() <= m_maxAutoSize.width()
-            && !frame()->document()->loadEventFinished() && (newSize.height() < size.height() || newSize.width() < size.width()))
+            && !m_frame->document()->loadEventFinished() && (newSize.height() < size.height() || newSize.width() < size.width()))
             break;
 
         resize(newSize.width(), newSize.height());
@@ -2392,10 +2428,8 @@
     if (m_pagination != Pagination())
         return m_pagination;
 
-    if (Page* page = m_frame->page()) {
-        if (page->mainFrame() == m_frame)
-            return page->pagination();
-    }
+    if (isMainFrame())
+        return m_frame->page()->pagination();
 
     return m_pagination;
 }
@@ -2407,8 +2441,7 @@
 
     m_pagination = pagination;
 
-    if (m_frame)
-        m_frame->document()->styleResolverChanged(RecalcStyleDeferred);
+    m_frame->document()->styleResolverChanged(RecalcStyleDeferred);
 }
 
 IntRect FrameView::windowClipRect(bool clipToContents) const
@@ -2420,12 +2453,12 @@
 
     // Set our clip rect to be our contents.
     IntRect clipRect = contentsToWindow(visibleContentRect(clipToContents ? ExcludeScrollbars : IncludeScrollbars));
-    if (!m_frame || !m_frame->ownerElement())
+    if (!m_frame->ownerElement())
         return clipRect;
 
     // Take our owner element and get its clip rect.
     HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement();
-    FrameView* parentView = ownerElement->document()->view();
+    FrameView* parentView = ownerElement->document().view();
     if (parentView)
         clipRect.intersect(parentView->windowClipRectForFrameOwner(ownerElement, true));
     return clipRect;
@@ -2455,7 +2488,7 @@
 
 bool FrameView::isActive() const
 {
-    Page* page = frame()->page();
+    Page* page = frame().page();
     return page && page->focusController().isActive();
 }
 
@@ -2465,7 +2498,7 @@
     ScrollView::scrollTo(newOffset);
     if (offset != scrollOffset())
         scrollPositionChanged();
-    frame()->loader()->client()->didChangeScrollOffset();
+    frame().loader()->client()->didChangeScrollOffset();
 }
 
 void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
@@ -2478,12 +2511,12 @@
 
 void FrameView::getTickmarks(Vector<IntRect>& tickmarks) const
 {
-    tickmarks = frame()->document()->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
+    tickmarks = frame().document()->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
 }
 
 IntRect FrameView::windowResizerRect() const
 {
-    Page* page = frame() ? frame()->page() : 0;
+    Page* page = frame().page();
     if (!page)
         return IntRect();
     return page->chrome().windowResizerRect();
@@ -2500,9 +2533,6 @@
 
 bool FrameView::scrollbarsCanBeActive() const
 {
-    if (!m_frame)
-        return false;
-
     if (m_frame->view() != this)
         return false;
 
@@ -2517,7 +2547,7 @@
 
 IntRect FrameView::scrollableAreaBoundingBox() const
 {
-    RenderPart* ownerRenderer = frame()->ownerRenderer();
+    RenderPart* ownerRenderer = frame().ownerRenderer();
     if (!ownerRenderer)
         return frameRect();
 
@@ -2575,10 +2605,7 @@
 
 void FrameView::scrollbarStyleChanged(int newStyle, bool forceUpdate)
 {
-    Page* page = m_frame->page();
-    if (!page)
-        return;
-    if (page->mainFrame() != m_frame)
+    if (!isMainFrame())
         return;
 
     if (forceUpdate)
@@ -2696,7 +2723,7 @@
     }
 
     if (m_scrollCorner) {
-        bool needsBackgorund = m_frame->page() && m_frame->page()->mainFrame() == m_frame;
+        bool needsBackgorund = isMainFrame();
         if (needsBackgorund)
             context->fillRect(cornerRect, baseBackgroundColor());
         m_scrollCorner->paintIntoRect(context, cornerRect.location(), cornerRect);
@@ -2708,7 +2735,7 @@
 
 void FrameView::paintScrollbar(GraphicsContext* context, Scrollbar* bar, const IntRect& rect)
 {
-    bool needsBackgorund = bar->isCustomScrollbar() && (m_frame->page() && m_frame->page()->mainFrame() == m_frame);
+    bool needsBackgorund = bar->isCustomScrollbar() && isMainFrame();
     if (needsBackgorund) {
         IntRect toFill = bar->frameRect();
         toFill.intersect(rect);
@@ -2718,35 +2745,35 @@
     ScrollView::paintScrollbar(context, bar, rect);
 }
 
-StyleColor FrameView::documentBackgroundColor() const
+Color FrameView::documentBackgroundColor() const
 {
     // <https://bugs.webkit.org/show_bug.cgi?id=59540> We blend the background color of
     // the document and the body against the base background color of the frame view.
     // Background images are unfortunately impractical to include.
 
     // Return invalid Color objects whenever there is insufficient information.
-    if (!frame()->document())
+    if (!frame().document())
         return Color();
 
-    Element* htmlElement = frame()->document()->documentElement();
-    Element* bodyElement = frame()->document()->body();
+    Element* htmlElement = frame().document()->documentElement();
+    Element* bodyElement = frame().document()->body();
 
     // Start with invalid colors.
-    StyleColor htmlBackgroundColor;
-    StyleColor bodyBackgroundColor;
+    Color htmlBackgroundColor;
+    Color bodyBackgroundColor;
     if (htmlElement && htmlElement->renderer())
-        htmlBackgroundColor = htmlElement->renderer()->resolveStyleColor(CSSPropertyBackgroundColor);
+        htmlBackgroundColor = htmlElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
     if (bodyElement && bodyElement->renderer())
-        bodyBackgroundColor = bodyElement->renderer()->resolveStyleColor(CSSPropertyBackgroundColor);
+        bodyBackgroundColor = bodyElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
 
     if (!bodyBackgroundColor.isValid()) {
         if (!htmlBackgroundColor.isValid())
-            return StyleColor();
-        return baseBackgroundColor().blend(htmlBackgroundColor.color());
+            return Color();
+        return baseBackgroundColor().blend(htmlBackgroundColor);
     }
 
     if (!htmlBackgroundColor.isValid())
-        return baseBackgroundColor().blend(bodyBackgroundColor.color());
+        return baseBackgroundColor().blend(bodyBackgroundColor);
 
     // We take the aggregate of the base background color
     // the <html> background color, and the <body>
@@ -2755,7 +2782,7 @@
     // technically part of the document background, but it
     // otherwise poses problems when the aggregate is not
     // fully opaque.
-    return baseBackgroundColor().blend(htmlBackgroundColor.color()).blend(bodyBackgroundColor.color());
+    return baseBackgroundColor().blend(htmlBackgroundColor).blend(bodyBackgroundColor);
 }
 
 bool FrameView::hasCustomScrollbars() const
@@ -2796,7 +2823,7 @@
     // to define when controls get the tint and to call this function when that changes.
 
     // Optimize the common case where we bring a window to the front while it's still empty.
-    if (!m_frame || m_frame->document()->url().isEmpty())
+    if (m_frame->document()->url().isEmpty())
         return;
 
     if (RenderTheme::theme().supportsControlTints() || hasCustomScrollbars())
@@ -2828,9 +2855,6 @@
 
 void FrameView::paintContents(GraphicsContext* p, const IntRect& rect)
 {
-    if (!frame())
-        return;
-
     Document* document = m_frame->document();
 
 #ifndef NDEBUG
@@ -2945,9 +2969,8 @@
     if (m_frame->document()->printing())
         return;
 
-    Page* page = m_frame->page();
-    if (page->mainFrame() == m_frame) {
-        if (page->chrome().client().paintCustomOverhangArea(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect))
+    if (isMainFrame()) {
+        if (m_frame->page()->chrome().client().paintCustomOverhangArea(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect))
             return;
     }
 
@@ -3339,7 +3362,6 @@
     return ScrollableArea::handleWheelEvent(wheelEvent);
 }
 
-
 bool FrameView::isVerticalDocument() const
 {
     RenderView* renderView = this->renderView();
@@ -3360,9 +3382,14 @@
 
 AXObjectCache* FrameView::axObjectCache() const
 {
-    if (frame() && frame()->document())
-        return frame()->document()->existingAXObjectCache();
+    if (frame().document())
+        return frame().document()->existingAXObjectCache();
     return 0;
 }
 
+bool FrameView::isMainFrame() const
+{
+    return m_frame->page() && m_frame->page()->mainFrame() == m_frame;
+}
+
 } // namespace WebCore
diff --git a/Source/core/page/FrameView.h b/Source/core/page/FrameView.h
index a17b47b..853d4e7 100644
--- a/Source/core/page/FrameView.h
+++ b/Source/core/page/FrameView.h
@@ -26,12 +26,12 @@
 #define FrameView_h
 
 #include "core/page/AdjustViewSizeOrNot.h"
-#include "core/page/Frame.h"
 #include "core/platform/ScrollView.h"
 #include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/rendering/Pagination.h"
 #include "core/rendering/PaintPhase.h"
+#include "core/rendering/PartialLayoutState.h"
 #include "wtf/Forward.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/text/WTFString.h"
@@ -41,6 +41,7 @@
 class Element;
 class Event;
 class FloatSize;
+class Frame;
 class FrameActionScheduler;
 class KURL;
 class Node;
@@ -73,13 +74,12 @@
 
     virtual bool scheduleAnimation();
 
-    Frame* frame() const { return m_frame.get(); }
-    void clearFrame();
+    Frame& frame() const { return *m_frame; }
 
-    RenderView* renderView() const { return m_frame ? m_frame->contentRenderer() : 0; }
+    RenderView* renderView() const;
 
-    int mapFromLayoutToCSSUnits(LayoutUnit);
-    LayoutUnit mapFromCSSToLayoutUnits(int);
+    int mapFromLayoutToCSSUnits(LayoutUnit) const;
+    LayoutUnit mapFromCSSToLayoutUnits(int) const;
 
     LayoutUnit marginWidth() const { return m_margins.width(); } // -1 means default
     LayoutUnit marginHeight() const { return m_margins.height(); } // -1 means default
@@ -138,8 +138,8 @@
     bool hasOpaqueBackground() const;
 
     Color baseBackgroundColor() const;
-    void setBaseBackgroundColor(const StyleColor&);
-    void updateBackgroundRecursively(const StyleColor&, bool);
+    void setBaseBackgroundColor(const Color&);
+    void updateBackgroundRecursively(const Color&, bool);
 
     bool shouldUpdateWhileOffscreen() const;
     void setShouldUpdateWhileOffscreen(bool);
@@ -230,7 +230,7 @@
     virtual void paintScrollCorner(GraphicsContext*, const IntRect& cornerRect);
     virtual void paintScrollbar(GraphicsContext*, Scrollbar*, const IntRect&) OVERRIDE;
 
-    StyleColor documentBackgroundColor() const;
+    Color documentBackgroundColor() const;
 
     static double currentFrameTimeStamp() { return s_currentFrameTimeStamp; }
 
@@ -335,6 +335,8 @@
     // DEPRECATED: Use viewportConstrainedVisibleContentRect() instead.
     IntSize scrollOffsetForFixedPosition() const;
 
+    PartialLayoutState& partialLayout() { return m_partialLayout; }
+
 protected:
     virtual bool scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect);
     virtual void scrollContentsSlowPath(const IntRect& updateRect);
@@ -363,6 +365,7 @@
 
     void paintControlTints();
 
+    void updateCounters();
     void autoSizeIfEnabled();
     void forceLayoutParentViewIfNeeded();
     void performPreLayoutTasks();
@@ -423,6 +426,8 @@
     virtual AXObjectCache* axObjectCache() const;
     void removeFromAXObjectCache();
 
+    bool isMainFrame() const;
+
     static double s_currentFrameTimeStamp; // used for detecting decoded resource thrash in the cache
     static bool s_inPaintContents;
 
@@ -531,6 +536,8 @@
     bool m_hasSoftwareFilters;
 
     float m_visibleContentScaleFactor;
+
+    PartialLayoutState m_partialLayout;
 };
 
 inline void FrameView::incrementVisuallyNonEmptyCharacterCount(unsigned count)
@@ -556,16 +563,6 @@
         setIsVisuallyNonEmpty();
 }
 
-inline int FrameView::mapFromLayoutToCSSUnits(LayoutUnit value)
-{
-    return value / m_frame->pageZoomFactor();
-}
-
-inline LayoutUnit FrameView::mapFromCSSToLayoutUnits(int value)
-{
-    return value * m_frame->pageZoomFactor();
-}
-
 inline FrameView* toFrameView(Widget* widget)
 {
     ASSERT(!widget || widget->isFrameView());
diff --git a/Source/core/page/History.cpp b/Source/core/page/History.cpp
index ee9109a..3e4f242 100644
--- a/Source/core/page/History.cpp
+++ b/Source/core/page/History.cpp
@@ -150,7 +150,7 @@
         es.throwSecurityError("A history state object with URL '" + fullURL.elidedString() + "' cannot be created in a document with origin '" + m_frame->document()->securityOrigin()->toString() + "'.");
         return;
     }
-    m_frame->loader()->updateForSameDocumentNavigation(fullURL, sameDocumentNavigationSource, data, title);
+    m_frame->loader()->updateForSameDocumentNavigation(fullURL, sameDocumentNavigationSource, data, title, FrameLoader::DoNotUpdateBackForwardList);
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/ImageBitmapTest.cpp b/Source/core/page/ImageBitmapTest.cpp
index ef0dbfc..7d3d1b0 100644
--- a/Source/core/page/ImageBitmapTest.cpp
+++ b/Source/core/page/ImageBitmapTest.cpp
@@ -85,7 +85,7 @@
 // one held by the HTMLImageElement.
 TEST_F(ImageBitmapTest, ImageResourceConsistency)
 {
-    RefPtr<HTMLImageElement> imageElement = HTMLImageElement::create(Document::create().get());
+    RefPtr<HTMLImageElement> imageElement = HTMLImageElement::create(*Document::create().get());
     imageElement->setImageResource(new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get()));
 
     RefPtr<ImageBitmap> imageBitmapNoCrop = ImageBitmap::create(imageElement.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
@@ -105,19 +105,19 @@
 // ImageBitmaps that have crop rects outside of the bounds of the HTMLImageElement do not have elevated CacheLiveResourcePriority.
 TEST_F(ImageBitmapTest, ImageBitmapLiveResourcePriority)
 {
-    RefPtr<HTMLImageElement> imageNoCrop = HTMLImageElement::create(Document::create().get());
+    RefPtr<HTMLImageElement> imageNoCrop = HTMLImageElement::create(*Document::create().get());
     ResourcePtr<ImageResource> cachedImageNoCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
     imageNoCrop->setImageResource(cachedImageNoCrop.get());
 
-    RefPtr<HTMLImageElement> imageInteriorCrop = HTMLImageElement::create(Document::create().get());
+    RefPtr<HTMLImageElement> imageInteriorCrop = HTMLImageElement::create(*Document::create().get());
     ResourcePtr<ImageResource> cachedImageInteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
     imageInteriorCrop->setImageResource(cachedImageInteriorCrop.get());
 
-    RefPtr<HTMLImageElement> imageExteriorCrop = HTMLImageElement::create(Document::create().get());
+    RefPtr<HTMLImageElement> imageExteriorCrop = HTMLImageElement::create(*Document::create().get());
     ResourcePtr<ImageResource> cachedImageExteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
     imageExteriorCrop->setImageResource(cachedImageExteriorCrop.get());
 
-    RefPtr<HTMLImageElement> imageOutsideCrop = HTMLImageElement::create(Document::create().get());
+    RefPtr<HTMLImageElement> imageOutsideCrop = HTMLImageElement::create(*Document::create().get());
     ResourcePtr<ImageResource> cachedImageOutsideCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
     imageOutsideCrop->setImageResource(cachedImageOutsideCrop.get());
 
@@ -170,7 +170,7 @@
 // Verifies that ImageBitmaps constructed from HTMLImageElements hold a reference to the original Image if the HTMLImageElement src is changed.
 TEST_F(ImageBitmapTest, ImageBitmapSourceChanged)
 {
-    RefPtr<HTMLImageElement> image = HTMLImageElement::create(Document::create().get());
+    RefPtr<HTMLImageElement> image = HTMLImageElement::create(*Document::create().get());
     ResourcePtr<ImageResource> originalImageResource = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
     image->setImageResource(originalImageResource.get());
 
@@ -193,7 +193,7 @@
 // Verifies that ImageBitmaps constructed from ImageBitmaps hold onto their own Image.
 TEST_F(ImageBitmapTest, ImageResourceLifetime)
 {
-    RefPtr<HTMLCanvasElement> canvasElement = HTMLCanvasElement::create(Document::create().get());
+    RefPtr<HTMLCanvasElement> canvasElement = HTMLCanvasElement::create(*Document::create().get());
     canvasElement->setHeight(40);
     canvasElement->setWidth(40);
     RefPtr<ImageBitmap> imageBitmapDerived;
diff --git a/Source/core/page/NavigatorID.cpp b/Source/core/page/NavigatorID.cpp
index 593d59e..6f60f5d 100644
--- a/Source/core/page/NavigatorID.cpp
+++ b/Source/core/page/NavigatorID.cpp
@@ -36,22 +36,10 @@
 #include "wtf/CPU.h"
 
 #if OS(LINUX)
-#include "sys/utsname.h"
 #include "wtf/StdLibExtras.h"
+#include <sys/utsname.h>
 #endif
 
-#ifndef WEBCORE_NAVIGATOR_PLATFORM
-#if OS(DARWIN) && (CPU(PPC) || CPU(PPC64))
-#define WEBCORE_NAVIGATOR_PLATFORM "MacPPC"
-#elif OS(DARWIN) && (CPU(X86) || CPU(X86_64))
-#define WEBCORE_NAVIGATOR_PLATFORM "MacIntel"
-#elif OS(WINDOWS)
-#define WEBCORE_NAVIGATOR_PLATFORM "Win32"
-#else
-#define WEBCORE_NAVIGATOR_PLATFORM ""
-#endif
-#endif // ifndef WEBCORE_NAVIGATOR_PLATFORM
-
 namespace WebCore {
 
 String NavigatorID::appName(const NavigatorBase*)
@@ -73,14 +61,16 @@
 
 String NavigatorID::platform(const NavigatorBase*)
 {
+#if defined(WEBCORE_NAVIGATOR_PLATFORM)
+    return WEBCORE_NAVIGATOR_PLATFORM;
+#else
 #if OS(LINUX)
-    if (!String(WEBCORE_NAVIGATOR_PLATFORM).isEmpty())
-        return WEBCORE_NAVIGATOR_PLATFORM;
     struct utsname osname;
     DEFINE_STATIC_LOCAL(String, platformName, (uname(&osname) >= 0 ? String(osname.sysname) + String(" ") + String(osname.machine) : emptyString()));
     return platformName;
 #else
-    return WEBCORE_NAVIGATOR_PLATFORM;
+#error Non-Linux ports must define WEBCORE_NAVIGATOR_PLATFORM.
+#endif
 #endif
 }
 
diff --git a/Source/core/page/Page.cpp b/Source/core/page/Page.cpp
index 37b360d..09a0158 100644
--- a/Source/core/page/Page.cpp
+++ b/Source/core/page/Page.cpp
@@ -78,7 +78,7 @@
 
     AtomicString eventName = networkStateNotifier().onLine() ? eventNames().onlineEvent : eventNames().offlineEvent;
     for (unsigned i = 0; i < frames.size(); i++)
-        frames[i]->document()->dispatchWindowEvent(Event::create(eventName, false, false));
+        frames[i]->document()->dispatchWindowEvent(Event::create(eventName));
 }
 
 float deviceScaleFactor(Frame* frame)
@@ -206,7 +206,7 @@
     m_autoscrollController->updateDragAndDrop(dropTargetNode, eventPosition, eventTime);
 }
 
-#if OS(WINDOWS)
+#if OS(WIN)
 void Page::handleMouseReleaseForPanScrolling(Frame* frame, const PlatformMouseEvent& point)
 {
     m_autoscrollController->handleMouseReleaseForPanScrolling(frame, point);
@@ -404,9 +404,6 @@
 {
     FrameView* view = mainFrame()->view();
 
-    bool oldProgrammaticScroll = view->inProgrammaticScroll();
-    view->setInProgrammaticScroll(false);
-
     if (scale != m_pageScaleFactor) {
         m_pageScaleFactor = scale;
 
@@ -421,8 +418,6 @@
 
     if (view && view->scrollPosition() != origin)
         view->notifyScrollPositionChanged(origin);
-
-    view->setInProgrammaticScroll(oldProgrammaticScroll);
 }
 
 void Page::setDeviceScaleFactor(float scaleFactor)
@@ -630,7 +625,7 @@
         return;
 
     // Objects inside sub-frames are not considered to be relevant.
-    if (object->document()->frame() != mainFrame())
+    if (object->document().frame() != mainFrame())
         return;
 
     RenderView* view = object->view();
diff --git a/Source/core/page/Page.h b/Source/core/page/Page.h
index 9e11a08..1323bff 100644
--- a/Source/core/page/Page.h
+++ b/Source/core/page/Page.h
@@ -157,7 +157,7 @@
     void stopAutoscrollTimer();
     void updateAutoscrollRenderer();
     void updateDragAndDrop(Node* targetNode, const IntPoint& eventPosition, double eventTime);
-#if OS(WINDOWS)
+#if OS(WIN)
     void handleMouseReleaseForPanScrolling(Frame*, const PlatformMouseEvent&);
     void startPanScrolling(RenderBox*, const IntPoint&);
 #endif
diff --git a/Source/core/page/PageConsole.h b/Source/core/page/PageConsole.h
index f65cbb1..20cd086 100644
--- a/Source/core/page/PageConsole.h
+++ b/Source/core/page/PageConsole.h
@@ -37,10 +37,7 @@
 
 namespace WebCore {
 
-class DOMWindow;
-class Document;
 class Page;
-class ScriptExecutionContext;
 
 class PageConsole {
 public:
@@ -56,9 +53,7 @@
     static void unmute();
 
 private:
-    PageConsole(Page*);
-
-    Page* page() { return m_page; };
+    explicit PageConsole(Page*);
 
     Page* m_page;
 };
diff --git a/Source/core/page/PageGroupLoadDeferrer.cpp b/Source/core/page/PageGroupLoadDeferrer.cpp
index 43f66cb..fec74c1 100644
--- a/Source/core/page/PageGroupLoadDeferrer.cpp
+++ b/Source/core/page/PageGroupLoadDeferrer.cpp
@@ -22,6 +22,7 @@
 #include "core/page/PageGroupLoadDeferrer.h"
 
 #include "core/dom/Document.h"
+#include "core/loader/FrameLoader.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/PageGroup.h"
@@ -42,6 +43,10 @@
             if (!otherPage->defersLoading()) {
                 m_deferredFrames.append(otherPage->mainFrame());
 
+                // Ensure that we notify the client if the initial empty document is accessed before showing anything
+                // modal, to prevent spoofs while the modal window or sheet is visible.
+                otherPage->mainFrame()->loader()->notifyIfInitialDocumentAccessed();
+
                 // This code is not logically part of load deferring, but we do not want JS code executed beneath modal
                 // windows or sheets, which is exactly when PageGroupLoadDeferrer is used.
                 for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext())
diff --git a/Source/core/page/PagePopupController.idl b/Source/core/page/PagePopupController.idl
index c7f545f..453850d 100644
--- a/Source/core/page/PagePopupController.idl
+++ b/Source/core/page/PagePopupController.idl
@@ -30,7 +30,7 @@
 
 [
     NoInterfaceObject,
-    EnabledAtRuntime=pagePopup
+    EnabledAtRuntime=PagePopup
 ] interface PagePopupController {
     void setValueAndClosePopup(long numberValue, DOMString stringValue);
     void setValue(DOMString value);
diff --git a/Source/core/page/PageScaleConstraints.cpp b/Source/core/page/PageScaleConstraints.cpp
index 9c82650..9cb4bde 100644
--- a/Source/core/page/PageScaleConstraints.cpp
+++ b/Source/core/page/PageScaleConstraints.cpp
@@ -29,7 +29,9 @@
  */
 
 #include "config.h"
-#include "PageScaleConstraints.h"
+#include "core/page/PageScaleConstraints.h"
+
+#include <algorithm>
 
 namespace WebCore {
 
diff --git a/Source/core/page/PageScaleConstraintsSet.cpp b/Source/core/page/PageScaleConstraintsSet.cpp
index e0d185b..6eacede 100644
--- a/Source/core/page/PageScaleConstraintsSet.cpp
+++ b/Source/core/page/PageScaleConstraintsSet.cpp
@@ -29,7 +29,9 @@
  */
 
 #include "config.h"
-#include "PageScaleConstraintsSet.h"
+#include "core/page/PageScaleConstraintsSet.h"
+
+#include "wtf/Assertions.h"
 
 namespace WebCore {
 
@@ -49,9 +51,9 @@
     return PageScaleConstraints(-1, defaultMinimumScale, defaultMaximumScale);
 }
 
-void PageScaleConstraintsSet::updatePageDefinedConstraints(const ViewportArguments& arguments, IntSize viewSize, int layoutFallbackWidth)
+void PageScaleConstraintsSet::updatePageDefinedConstraints(const ViewportArguments& arguments, IntSize viewSize)
 {
-    m_pageDefinedConstraints = arguments.resolve(viewSize, layoutFallbackWidth);
+    m_pageDefinedConstraints = arguments.resolve(viewSize);
 
     m_constraintsDirty = true;
 }
@@ -119,34 +121,49 @@
     return initialScale == -1 ? deviceSize.width() : deviceSize.width() / initialScale;
 }
 
-void PageScaleConstraintsSet::adjustPageDefinedConstraintsForAndroidWebView(const ViewportArguments& arguments, IntSize viewSize, int layoutFallbackWidth, float deviceScaleFactor, bool useWideViewport, bool loadWithOverviewMode)
+void PageScaleConstraintsSet::adjustForAndroidWebViewQuirks(const ViewportArguments& arguments, IntSize viewSize, int layoutFallbackWidth, float deviceScaleFactor, bool supportTargetDensityDPI, bool wideViewportQuirkEnabled, bool useWideViewport, bool loadWithOverviewMode)
 {
+    if (!supportTargetDensityDPI && !wideViewportQuirkEnabled && loadWithOverviewMode)
+        return;
+
     float initialScale = m_pageDefinedConstraints.initialScale;
-    if (arguments.zoom == -1 && !loadWithOverviewMode) {
-        if (arguments.width == -1 || (useWideViewport && arguments.width != ViewportArguments::ValueDeviceWidth))
+    if (!loadWithOverviewMode) {
+        bool resetInitialScale = false;
+        if (arguments.zoom == -1) {
+            if (arguments.maxWidth.isAuto())
+                resetInitialScale = true;
+            if (useWideViewport && arguments.maxWidth.isFixed())
+                resetInitialScale = true;
+        }
+        if (resetInitialScale)
             m_pageDefinedConstraints.initialScale = 1.0f;
     }
 
-    float targetDensityDPIFactor = computeDeprecatedTargetDensityDPIFactor(arguments, deviceScaleFactor);
-    if (m_pageDefinedConstraints.initialScale != -1)
-        m_pageDefinedConstraints.initialScale *= targetDensityDPIFactor;
-    m_pageDefinedConstraints.minimumScale *= targetDensityDPIFactor;
-    m_pageDefinedConstraints.maximumScale *= targetDensityDPIFactor;
-
     float adjustedLayoutSizeWidth = m_pageDefinedConstraints.layoutSize.width();
-    if (useWideViewport && arguments.width == -1 && arguments.zoom != 1.0f)
-        adjustedLayoutSizeWidth = layoutFallbackWidth;
-    else {
-        if (!useWideViewport)
-            adjustedLayoutSizeWidth = getLayoutWidthForNonWideViewport(viewSize, initialScale);
-        if (!useWideViewport || arguments.width == -1 || arguments.width == ViewportArguments::ValueDeviceWidth)
-            adjustedLayoutSizeWidth /= targetDensityDPIFactor;
+    float targetDensityDPIFactor = 1.0f;
+
+    if (supportTargetDensityDPI) {
+        targetDensityDPIFactor = computeDeprecatedTargetDensityDPIFactor(arguments, deviceScaleFactor);
+        if (m_pageDefinedConstraints.initialScale != -1)
+            m_pageDefinedConstraints.initialScale *= targetDensityDPIFactor;
+        m_pageDefinedConstraints.minimumScale *= targetDensityDPIFactor;
+        m_pageDefinedConstraints.maximumScale *= targetDensityDPIFactor;
+        adjustedLayoutSizeWidth /= targetDensityDPIFactor;
     }
 
-    ASSERT(m_pageDefinedConstraints.layoutSize.width() > 0);
-    float adjustedLayoutSizeHeight = (adjustedLayoutSizeWidth * m_pageDefinedConstraints.layoutSize.height()) / m_pageDefinedConstraints.layoutSize.width();
-    m_pageDefinedConstraints.layoutSize.setWidth(adjustedLayoutSizeWidth);
-    m_pageDefinedConstraints.layoutSize.setHeight(adjustedLayoutSizeHeight);
+    if (wideViewportQuirkEnabled) {
+        if (useWideViewport && (arguments.maxWidth.isAuto() || arguments.maxWidth.type() == ExtendToZoom) && arguments.zoom != 1.0f)
+            adjustedLayoutSizeWidth = layoutFallbackWidth;
+        else if (!useWideViewport)
+            adjustedLayoutSizeWidth = getLayoutWidthForNonWideViewport(viewSize, initialScale) / targetDensityDPIFactor;
+    }
+
+    if (adjustedLayoutSizeWidth != m_pageDefinedConstraints.layoutSize.width()) {
+        ASSERT(m_pageDefinedConstraints.layoutSize.width() > 0);
+        float adjustedLayoutSizeHeight = (adjustedLayoutSizeWidth * m_pageDefinedConstraints.layoutSize.height()) / m_pageDefinedConstraints.layoutSize.width();
+        m_pageDefinedConstraints.layoutSize.setWidth(adjustedLayoutSizeWidth);
+        m_pageDefinedConstraints.layoutSize.setHeight(adjustedLayoutSizeHeight);
+    }
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/PageScaleConstraintsSet.h b/Source/core/page/PageScaleConstraintsSet.h
index 8cdc08b..2e281cb 100644
--- a/Source/core/page/PageScaleConstraintsSet.h
+++ b/Source/core/page/PageScaleConstraintsSet.h
@@ -48,8 +48,8 @@
     // Settings defined in the website's viewport tag, if viewport tag support
     // is enabled.
     const PageScaleConstraints& pageDefinedConstraints() const { return m_pageDefinedConstraints; }
-    void updatePageDefinedConstraints(const ViewportArguments&, IntSize viewSize, int layoutFallbackWidth);
-    void adjustPageDefinedConstraintsForAndroidWebView(const ViewportArguments&, IntSize viewSize, int layoutFallbackWidth, float deviceScaleFactor, bool useWideViewport, bool loadWithOverviewMode);
+    void updatePageDefinedConstraints(const ViewportArguments&, IntSize viewSize);
+    void adjustForAndroidWebViewQuirks(const ViewportArguments&, IntSize viewSize, int layoutFallbackWidth, float deviceScaleFactor, bool supportTargetDensityDPI, bool wideViewportQuirkEnabled, bool useWideViewport, bool loadWithOverviewMode);
 
     // Constraints may also be set from Chromium -- this overrides any
     // page-defined values.
diff --git a/Source/core/page/PointerLockController.cpp b/Source/core/page/PointerLockController.cpp
index 6347dda..015c7ff 100644
--- a/Source/core/page/PointerLockController.cpp
+++ b/Source/core/page/PointerLockController.cpp
@@ -51,15 +51,15 @@
         return;
     }
 
-    if (target->document()->isSandboxed(SandboxPointerLock)) {
+    if (target->document().isSandboxed(SandboxPointerLock)) {
         // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
-        target->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked pointer lock on an element because the element's frame is sandboxed and the 'allow-pointer-lock' permission is not set.");
+        target->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked pointer lock on an element because the element's frame is sandboxed and the 'allow-pointer-lock' permission is not set.");
         enqueueEvent(eventNames().webkitpointerlockerrorEvent, target);
         return;
     }
 
     if (m_element) {
-        if (m_element->document() != target->document()) {
+        if (&m_element->document() != &target->document()) {
             enqueueEvent(eventNames().webkitpointerlockerrorEvent, target);
             return;
         }
@@ -81,7 +81,7 @@
 void PointerLockController::elementRemoved(Element* element)
 {
     if (m_element == element) {
-        m_documentOfRemovedElementWhileWaitingForUnlock = m_element->document();
+        m_documentOfRemovedElementWhileWaitingForUnlock = &m_element->document();
         // Set element null immediately to block any future interaction with it
         // including mouse events received before the unlock completes.
         clearElement();
@@ -91,7 +91,7 @@
 
 void PointerLockController::documentDetached(Document* document)
 {
-    if (m_element && m_element->document() == document) {
+    if (m_element && &m_element->document() == document) {
         clearElement();
         requestPointerUnlock();
     }
@@ -121,14 +121,14 @@
 
 void PointerLockController::didLosePointerLock()
 {
-    enqueueEvent(eventNames().webkitpointerlockchangeEvent, m_element ? m_element->document() : m_documentOfRemovedElementWhileWaitingForUnlock.get());
+    enqueueEvent(eventNames().webkitpointerlockchangeEvent, m_element ? &m_element->document() : m_documentOfRemovedElementWhileWaitingForUnlock.get());
     clearElement();
     m_documentOfRemovedElementWhileWaitingForUnlock = 0;
 }
 
 void PointerLockController::dispatchLockedMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType)
 {
-    if (!m_element || !m_element->document()->frame())
+    if (!m_element || !m_element->document().frame())
         return;
 
     m_element->dispatchMouseEvent(event, eventType, event.clickCount());
@@ -147,7 +147,7 @@
 void PointerLockController::enqueueEvent(const AtomicString& type, Element* element)
 {
     if (element)
-        enqueueEvent(type, element->document());
+        enqueueEvent(type, &element->document());
 }
 
 void PointerLockController::enqueueEvent(const AtomicString& type, Document* document)
diff --git a/Source/core/page/PrintContext.cpp b/Source/core/page/PrintContext.cpp
index a8c2840..0803a41 100644
--- a/Source/core/page/PrintContext.cpp
+++ b/Source/core/page/PrintContext.cpp
@@ -239,13 +239,13 @@
 {
     // Make sure the element is not freed during the layout.
     RefPtr<Element> elementRef(element);
-    element->document()->updateLayout();
+    element->document().updateLayout();
 
     RenderBoxModelObject* box = enclosingBoxModelObject(element->renderer());
     if (!box)
         return -1;
 
-    Frame* frame = element->document()->frame();
+    Frame* frame = element->document().frame();
     FloatRect pageRect(FloatPoint(0, 0), pageSizeInPixels);
     PrintContext printContext(frame);
     printContext.begin(pageRect.width(), pageRect.height());
@@ -274,12 +274,12 @@
     const AtomicString& href = toElement(node)->getAttribute(HTMLNames::hrefAttr);
     if (href.isNull())
         return;
-    KURL url = node->document()->completeURL(href);
+    KURL url = node->document().completeURL(href);
     if (!url.isValid())
         return;
-    if (url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(url, node->document()->baseURL())) {
+    if (url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(url, node->document().baseURL())) {
         String name = url.fragmentIdentifier();
-        Element* element = node->document()->findAnchor(name);
+        Element* element = node->document().findAnchor(name);
         if (element)
             m_linkedDestinations.set(name, element);
     }
diff --git a/Source/core/page/RuntimeCSSEnabled.cpp b/Source/core/page/RuntimeCSSEnabled.cpp
index 083647d..3727cec 100644
--- a/Source/core/page/RuntimeCSSEnabled.cpp
+++ b/Source/core/page/RuntimeCSSEnabled.cpp
@@ -112,6 +112,7 @@
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyPaintOrder, RuntimeEnabledFeatures::svgPaintOrderEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyVariable, RuntimeEnabledFeatures::cssVariablesEnabled());
     RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyObjectFit, RuntimeEnabledFeatures::objectFitPositionEnabled());
+    RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyMaskSourceType, RuntimeEnabledFeatures::cssMaskSourceTypeEnabled());
 }
 
 static BoolVector& propertySwitches()
diff --git a/Source/core/page/RuntimeEnabledFeatures.in b/Source/core/page/RuntimeEnabledFeatures.in
index 9461a6f..6108b66 100644
--- a/Source/core/page/RuntimeEnabledFeatures.in
+++ b/Source/core/page/RuntimeEnabledFeatures.in
@@ -23,10 +23,12 @@
 CSSCompositing status=experimental
 CSSExclusions status=experimental
 CSSGridLayout status=experimental
+CSSMaskSourceType status=experimental
 CSSRegions status=experimental
-CSSShapes status=experimental, writeable=True
+CSSShapes status=experimental
 CSSTouchAction status=test
 CSSVariables status=experimental
+CSSViewport status=experimental
 CSS3Text status=experimental
 CSS3TextDecorations status=experimental
 CustomElements status=experimental
@@ -47,7 +49,6 @@
 FileSystem status=stable
 FontLoadEvents status=experimental
 Fullscreen status=stable
-CSSViewport status=experimental
 Gamepad status=stable
 Geolocation status=stable
 HTMLImports status=test
@@ -66,7 +67,7 @@
 Notifications status=stable
 ObjectFitPosition status=experimental
 PagePopup status=stable
-ParseSVGAsHTML
+PartialLayout status=experimental
 PathOpsSVGClipping
 PeerConnection depends_on=MediaStream, status=stable
 ProgrammaticScrollNotifications status=test
diff --git a/Source/core/page/Settings.cpp b/Source/core/page/Settings.cpp
index 148aacf..c30a752 100644
--- a/Source/core/page/Settings.cpp
+++ b/Source/core/page/Settings.cpp
@@ -77,7 +77,6 @@
 }
 
 bool Settings::gMockScrollbarsEnabled = false;
-bool Settings::gUsesOverlayScrollbars = false;
 
 // NOTEs
 //  1) EditingMacBehavior comprises builds on Mac;
@@ -88,13 +87,13 @@
 static EditingBehaviorType editingBehaviorTypeForPlatform()
 {
     return
-#if OS(DARWIN)
+#if OS(MACOSX)
     EditingMacBehavior
-#elif OS(WINDOWS)
+#elif OS(WIN)
     EditingWindowsBehavior
 #elif OS(ANDROID)
     EditingAndroidBehavior
-#elif OS(UNIX)
+#elif OS(POSIX)
     EditingUnixBehavior
 #else
     // Fallback
@@ -104,12 +103,12 @@
 }
 
 static const bool defaultUnifiedTextCheckerEnabled = false;
-#if OS(DARWIN)
+#if OS(MACOSX)
 static const bool defaultSmartInsertDeleteEnabled = true;
 #else
 static const bool defaultSmartInsertDeleteEnabled = false;
 #endif
-#if OS(WINDOWS)
+#if OS(WIN)
 static const bool defaultSelectTrailingWhitespaceEnabled = true;
 #else
 static const bool defaultSelectTrailingWhitespaceEnabled = false;
@@ -137,6 +136,7 @@
     , m_cssStickyPositionEnabled(true)
     , m_dnsPrefetchingEnabled(false)
     , m_touchEventEmulationEnabled(false)
+    , m_openGLMultisamplingEnabled(false)
     , m_viewportEnabled(false)
     , m_setImageLoadingSettingsTimer(this, &Settings::imageLoadingSettingsTimerFired)
     , m_compositorDrivenAcceleratedScrollingEnabled(false)
@@ -358,16 +358,6 @@
     return gMockScrollbarsEnabled;
 }
 
-void Settings::setUsesOverlayScrollbars(bool flag)
-{
-    gUsesOverlayScrollbars = flag;
-}
-
-bool Settings::usesOverlayScrollbars()
-{
-    return gUsesOverlayScrollbars;
-}
-
 void Settings::setOpenGLMultisamplingEnabled(bool flag)
 {
     if (m_openGLMultisamplingEnabled == flag)
diff --git a/Source/core/page/Settings.h b/Source/core/page/Settings.h
index 9fe3bfa..588380b 100644
--- a/Source/core/page/Settings.h
+++ b/Source/core/page/Settings.h
@@ -142,9 +142,6 @@
     static void setMockScrollbarsEnabled(bool flag);
     static bool mockScrollbarsEnabled();
 
-    static void setUsesOverlayScrollbars(bool flag);
-    static bool usesOverlayScrollbars();
-
     void setTouchEventEmulationEnabled(bool enabled) { m_touchEventEmulationEnabled = enabled; }
     bool isTouchEventEmulationEnabled() const { return m_touchEventEmulationEnabled; }
 
@@ -202,7 +199,6 @@
     void imageLoadingSettingsTimerFired(Timer<Settings>*);
 
     static bool gMockScrollbarsEnabled;
-    static bool gUsesOverlayScrollbars;
 };
 
 } // namespace WebCore
diff --git a/Source/core/page/Settings.in b/Source/core/page/Settings.in
index 71e627f..9478713 100644
--- a/Source/core/page/Settings.in
+++ b/Source/core/page/Settings.in
@@ -89,6 +89,7 @@
 allowDisplayOfInsecureContent initial=true
 allowRunningOfInsecureContent initial=true
 mediaPlaybackRequiresUserGesture initial=false
+mediaFullscreenRequiresUserGesture initial=true
 passwordEchoEnabled initial=false
 visualWordMovementEnabled initial=false
 shouldDisplaySubtitles initial=false
@@ -132,6 +133,14 @@
 
 selectionIncludesAltImageText initial=false
 useLegacyBackgroundSizeShorthandBehavior initial=false
+# This quirk is to maintain compatibility with Android apps built on
+# the Android SDK prior to and including version 18. Presumably, this
+# can be removed any time after 2015. See http://crbug.com/282130.
+viewportMetaZeroValuesQuirk initial=false
+# This quirk is to maintain compatibility with Android apps.
+# It will be possible to remove it once WebSettings.{get|set}UseWideViewPort
+# API function will be removed. See http://crbug.com/288037.
+wideViewportQuirkEnabled initial=false
 
 # This setting enables touch based text selection and editing.
 touchEditingEnabled initial=false
diff --git a/Source/core/page/SpatialNavigation.cpp b/Source/core/page/SpatialNavigation.cpp
index 7a4b3f9..37426cb 100644
--- a/Source/core/page/SpatialNavigation.cpp
+++ b/Source/core/page/SpatialNavigation.cpp
@@ -292,7 +292,7 @@
     // Get the FrameView in which |node| is (which means the current viewport if |node|
     // is not in an inner document), so we can check if its content rect is visible
     // before we actually move the focus to it.
-    FrameView* frameView = node->document()->view();
+    FrameView* frameView = node->document().view();
     if (!frameView)
         return true;
 
@@ -437,7 +437,7 @@
     Node* parent = node;
     do {
         if (parent->isDocumentNode())
-            parent = toDocument(parent)->document()->frame()->ownerElement();
+            parent = toDocument(parent)->document().frame()->ownerElement();
         else
             parent = parent->parentOrShadowHostNode();
     } while (parent && !canScrollInDirection(parent, direction) && !parent->isDocumentNode());
@@ -515,11 +515,11 @@
 
 LayoutRect nodeRectInAbsoluteCoordinates(Node* node, bool ignoreBorder)
 {
-    ASSERT(node && node->renderer() && !node->document()->view()->needsLayout());
+    ASSERT(node && node->renderer() && !node->document().view()->needsLayout());
 
     if (node->isDocumentNode())
         return frameRectInAbsoluteCoordinates(toDocument(node)->frame());
-    LayoutRect rect = rectToAbsoluteCoordinates(node->document()->frame(), node->boundingBox());
+    LayoutRect rect = rectToAbsoluteCoordinates(node->document().frame(), node->boundingBox());
 
     // For authors that use border instead of outline in their CSS, we compensate by ignoring the border when calculating
     // the rect of the focused element.
@@ -671,7 +671,7 @@
 
     float distance = euclidianDistance + sameAxisDistance + 2 * otherAxisDistance;
     candidate.distance = roundf(distance);
-    LayoutSize viewSize = candidate.visibleNode->document()->page()->mainFrame()->view()->visibleContentRect().size();
+    LayoutSize viewSize = candidate.visibleNode->document().page()->mainFrame()->view()->visibleContentRect().size();
     candidate.alignment = alignmentForRects(direction, currentRect, nodeRect, viewSize);
 }
 
@@ -727,7 +727,7 @@
     ASSERT(area->imageElement());
     // Area elements tend to overlap more than other focusable elements. We flatten the rect of the area elements
     // to minimize the effect of overlapping areas.
-    LayoutRect rect = virtualRectForDirection(direction, rectToAbsoluteCoordinates(area->document()->frame(), area->computeRect(area->imageElement()->renderer())), 1);
+    LayoutRect rect = virtualRectForDirection(direction, rectToAbsoluteCoordinates(area->document().frame(), area->computeRect(area->imageElement()->renderer())), 1);
     return rect;
 }
 
diff --git a/Source/core/page/SpatialNavigation.h b/Source/core/page/SpatialNavigation.h
index 77dd3b0..e56c734 100644
--- a/Source/core/page/SpatialNavigation.h
+++ b/Source/core/page/SpatialNavigation.h
@@ -116,7 +116,7 @@
     bool isNull() const { return !visibleNode; }
     bool inScrollableContainer() const { return visibleNode && enclosingScrollableBox; }
     bool isFrameOwnerElement() const { return visibleNode && visibleNode->isFrameOwnerElement(); }
-    Document* document() const { return visibleNode ? visibleNode->document() : 0; }
+    Document* document() const { return visibleNode ? &visibleNode->document() : 0; }
 
     // We handle differently visibleNode and FocusableNode to properly handle the areas of imagemaps,
     // where visibleNode would represent the image element and focusableNode would represent the area element.
diff --git a/Source/core/page/TouchAdjustment.cpp b/Source/core/page/TouchAdjustment.cpp
index de2674d..fcd5901 100644
--- a/Source/core/page/TouchAdjustment.cpp
+++ b/Source/core/page/TouchAdjustment.cpp
@@ -27,6 +27,7 @@
 #include "core/dom/Text.h"
 #include "core/editing/Editor.h"
 #include "core/html/HTMLFrameOwnerElement.h"
+#include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/platform/graphics/FloatPoint.h"
 #include "core/platform/graphics/FloatQuad.h"
@@ -320,7 +321,7 @@
     IntRect rect = subtarget.boundingBox();
 
     // Convert from frame coordinates to window coordinates.
-    rect = subtarget.node()->document()->view()->contentsToWindow(rect);
+    rect = subtarget.node()->document().view()->contentsToWindow(rect);
 
     // Check the rectangle is meaningful zoom target. It should at least contain the hotspot.
     if (!rect.contains(touchHotspot))
@@ -343,7 +344,7 @@
     IntRect rect = subtarget.boundingBox();
 
     // Convert from frame coordinates to window coordinates.
-    rect = subtarget.node()->document()->view()->contentsToWindow(rect);
+    rect = subtarget.node()->document().view()->contentsToWindow(rect);
 
     float radiusSquared = 0.25f * (touchRect.size().diagonalLengthSquared());
     float distanceToAdjustScore = rect.distanceSquaredToPoint(touchHotspot) / radiusSquared;
@@ -384,7 +385,7 @@
 
 bool snapTo(const SubtargetGeometry& geom, const IntPoint& touchPoint, const IntRect& touchArea, IntPoint& adjustedPoint)
 {
-    FrameView* view = geom.node()->document()->view();
+    FrameView* view = geom.node()->document().view();
     FloatQuad quad = geom.quad();
 
     if (quad.isRectilinear()) {
@@ -462,7 +463,7 @@
         }
     }
     if (targetNode) {
-        targetArea = targetNode->document()->view()->contentsToWindow(targetArea);
+        targetArea = targetNode->document().view()->contentsToWindow(targetArea);
     }
     return (targetNode);
 }
diff --git a/Source/core/page/TouchDisambiguation.cpp b/Source/core/page/TouchDisambiguation.cpp
index a0ba0d9..4cab1f5 100644
--- a/Source/core/page/TouchDisambiguation.cpp
+++ b/Source/core/page/TouchDisambiguation.cpp
@@ -51,7 +51,7 @@
 
 static IntRect boundingBoxForEventNodes(Node* eventNode)
 {
-    if (!eventNode->document()->view())
+    if (!eventNode->document().view())
         return IntRect();
 
     IntRect result;
@@ -65,7 +65,7 @@
         result.unite(node->pixelSnappedBoundingBox());
         node = NodeTraversal::next(node, eventNode);
     }
-    return eventNode->document()->view()->contentsToWindow(result);
+    return eventNode->document().view()->contentsToWindow(result);
 }
 
 static float scoreTouchTarget(IntPoint touchPoint, int padding, IntRect boundingBox)
diff --git a/Source/core/page/UseCounter.cpp b/Source/core/page/UseCounter.cpp
index 4e16de2..5db2ae9 100644
--- a/Source/core/page/UseCounter.cpp
+++ b/Source/core/page/UseCounter.cpp
@@ -494,6 +494,7 @@
     case CSSPropertyAnimationTimingFunction: return 432;
     case CSSPropertyObjectFit: return 433;
     case CSSPropertyPaintOrder: return 434;
+    case CSSPropertyMaskSourceType: return 435;
 
     // Add new features above this line (don't change the assigned numbers of the existing
     // items) and update maximumCSSSampleId() with the new maximum value.
diff --git a/Source/core/page/UseCounter.h b/Source/core/page/UseCounter.h
index f70e966..73c4958 100644
--- a/Source/core/page/UseCounter.h
+++ b/Source/core/page/UseCounter.h
@@ -123,7 +123,7 @@
         DeprecatedFlexboxWebContent,
         DeprecatedFlexboxChrome,
         DeprecatedFlexboxChromeExtension,
-        SVGTRefElement,
+        UnusedSlot04,
         UnprefixedPerformanceTimeline,
         PrefixedPerformanceTimeline,
         UnprefixedUserTiming,
@@ -197,6 +197,11 @@
         UnprefixedAnimationIterationEvent,
         PrefixedAndUnprefixedAnimationIterationEvent,
         EventReturnValue, // Legacy IE extension.
+        SVGSVGElement,
+        SVGAnimateColorElement,
+        InsertAdjacentText,
+        InsertAdjacentElement,
+        HasAttributes, // Removed from DOM4.
         // 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/Window.idl b/Source/core/page/Window.idl
index 99f98d1..c720658 100644
--- a/Source/core/page/Window.idl
+++ b/Source/core/page/Window.idl
@@ -245,26 +245,29 @@
     // Webkit extensions
     attribute EventHandler onreset;
     attribute EventHandler onsearch;
+    [EnabledAtRuntime=CSSAnimationUnprefixed] attribute EventHandler onanimationend;
+    [EnabledAtRuntime=CSSAnimationUnprefixed] attribute EventHandler onanimationiteration;
+    [EnabledAtRuntime=CSSAnimationUnprefixed] attribute EventHandler onanimationstart;
     attribute EventHandler onwebkitanimationend;
     attribute EventHandler onwebkitanimationiteration;
     attribute EventHandler onwebkitanimationstart;
     attribute EventHandler onwebkittransitionend;
     attribute EventHandler ontransitionend;
     [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
-    [EnabledAtRuntime=touch] attribute EventHandler ontouchstart;
-    [EnabledAtRuntime=touch] attribute EventHandler ontouchmove;
-    [EnabledAtRuntime=touch] attribute EventHandler ontouchend;
-    [EnabledAtRuntime=touch] attribute EventHandler ontouchcancel;
+    [EnabledAtRuntime=Touch] attribute EventHandler ontouchstart;
+    [EnabledAtRuntime=Touch] attribute EventHandler ontouchmove;
+    [EnabledAtRuntime=Touch] attribute EventHandler ontouchend;
+    [EnabledAtRuntime=Touch] attribute EventHandler ontouchcancel;
 
-    [EnabledAtRuntime=deviceMotion] attribute EventHandler ondevicemotion;
-    [EnabledAtRuntime=deviceOrientation] attribute EventHandler ondeviceorientation;
+    [EnabledAtRuntime=DeviceMotion] attribute EventHandler ondevicemotion;
+    [EnabledAtRuntime=DeviceOrientation] attribute EventHandler ondeviceorientation;
 
     [DeprecateAs=CaptureEvents] void captureEvents();
     [DeprecateAs=ReleaseEvents] void releaseEvents();
 
     // Additional constructors.
     attribute TransitionEventConstructor WebKitTransitionEvent;
-    [EnabledAtRuntime=cssAnimationUnprefixed] attribute WebKitAnimationEventConstructor AnimationEvent;
+    [EnabledAtRuntime=CSSAnimationUnprefixed] attribute WebKitAnimationEventConstructor AnimationEvent;
     [CustomConstructor] attribute HTMLImageElementConstructorConstructor Image; // Usable with new operator
     // Mozilla has a separate XMLDocument object for XML documents.
     // We just use Document for this.
@@ -282,15 +285,15 @@
 
     // Constructors whose name does not match the interface name.
     // FIXME: Remove these once [ImplementedAs] is used and once constructor names match interface names.
-    [EnabledAtRuntime=mediaStream] attribute MediaStreamConstructor webkitMediaStream;
+    [EnabledAtRuntime=MediaStream] attribute MediaStreamConstructor webkitMediaStream;
     [Conditional=WEB_AUDIO, EnabledAtRuntime=WebAudio] attribute AudioContextConstructor webkitAudioContext;
     [Conditional=WEB_AUDIO, EnabledAtRuntime=WebAudio] attribute OfflineAudioContextConstructor webkitOfflineAudioContext;
-    [EnabledAtRuntime=peerConnection] attribute RTCPeerConnectionConstructor webkitRTCPeerConnection;
-    [EnabledAtRuntime=scriptedSpeech] attribute SpeechGrammarConstructor webkitSpeechGrammar;
-    [EnabledAtRuntime=scriptedSpeech] attribute SpeechGrammarListConstructor webkitSpeechGrammarList;
-    [EnabledAtRuntime=scriptedSpeech] attribute SpeechRecognitionConstructor webkitSpeechRecognition;
-    [EnabledAtRuntime=scriptedSpeech] attribute SpeechRecognitionErrorConstructor webkitSpeechRecognitionError;
-    [EnabledAtRuntime=scriptedSpeech] attribute SpeechRecognitionEventConstructor webkitSpeechRecognitionEvent;
+    [EnabledAtRuntime=PeerConnection] attribute RTCPeerConnectionConstructor webkitRTCPeerConnection;
+    [EnabledAtRuntime=ScriptedSpeech] attribute SpeechGrammarConstructor webkitSpeechGrammar;
+    [EnabledAtRuntime=ScriptedSpeech] attribute SpeechGrammarListConstructor webkitSpeechGrammarList;
+    [EnabledAtRuntime=ScriptedSpeech] attribute SpeechRecognitionConstructor webkitSpeechRecognition;
+    [EnabledAtRuntime=ScriptedSpeech] attribute SpeechRecognitionErrorConstructor webkitSpeechRecognitionError;
+    [EnabledAtRuntime=ScriptedSpeech] attribute SpeechRecognitionEventConstructor webkitSpeechRecognitionEvent;
     [Conditional=WEB_AUDIO] attribute PannerNodeConstructor webkitAudioPannerNode;
 
     // Prefixed ShadowRoot constructor should be phased out eventually, but for the moment it must be always exposed.
diff --git a/Source/core/page/WindowPagePopup.idl b/Source/core/page/WindowPagePopup.idl
index 36fea46..0ae9bbe 100644
--- a/Source/core/page/WindowPagePopup.idl
+++ b/Source/core/page/WindowPagePopup.idl
@@ -29,7 +29,7 @@
  */
 
 [
-    EnabledAtRuntime=pagePopup,
+    EnabledAtRuntime=PagePopup,
     ImplementedAs=DOMWindowPagePopup
 ] partial interface Window {
     [EnabledPerContext=pagePopup] readonly attribute PagePopupController pagePopupController;
diff --git a/Source/core/page/animation/AnimationBase.cpp b/Source/core/page/animation/AnimationBase.cpp
index 574adc4..77b4992 100644
--- a/Source/core/page/animation/AnimationBase.cpp
+++ b/Source/core/page/animation/AnimationBase.cpp
@@ -75,11 +75,6 @@
     return m_animation->playState() == AnimPlayStatePlaying;
 }
 
-bool AnimationBase::animationsMatch(const CSSAnimationData* anim) const
-{
-    return m_animation->animationsMatch(anim);
-}
-
 void AnimationBase::updateStateMachine(AnimStateInput input, double param)
 {
     if (!m_compAnim)
@@ -496,7 +491,7 @@
     const double fractionalTime = this->fractionalTime(scale, elapsedTime, offset);
 
     if (!timingFunction)
-        timingFunction = m_animation->timingFunction().get();
+        timingFunction = m_animation->timingFunction();
 
     return timingFunction->evaluate(fractionalTime, accuracyForDuration(m_animation->duration()));
 }
diff --git a/Source/core/page/animation/AnimationBase.h b/Source/core/page/animation/AnimationBase.h
index 641ff69..29cdb42 100644
--- a/Source/core/page/animation/AnimationBase.h
+++ b/Source/core/page/animation/AnimationBase.h
@@ -137,8 +137,6 @@
 
     void fireAnimationEventsIfNeeded();
 
-    bool animationsMatch(const CSSAnimationData*) const;
-
     void setAnimation(const CSSAnimationData* anim) { m_animation = const_cast<CSSAnimationData*>(anim); }
 
     // Return true if this animation is overridden. This will only be the case for
diff --git a/Source/core/page/animation/AnimationController.cpp b/Source/core/page/animation/AnimationController.cpp
index b6a61dc..b0fad9b 100644
--- a/Source/core/page/animation/AnimationController.cpp
+++ b/Source/core/page/animation/AnimationController.cpp
@@ -313,7 +313,7 @@
     RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
     for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
         RenderObject* renderer = it->key;
-        if (renderer->document() == document) {
+        if (&renderer->document() == document) {
             CompositeAnimation* compAnim = it->value.get();
             compAnim->suspendAnimations();
         }
@@ -329,7 +329,7 @@
     RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
     for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
         RenderObject* renderer = it->key;
-        if (renderer->document() == document) {
+        if (&renderer->document() == document) {
             CompositeAnimation* compAnim = it->value.get();
             compAnim->resumeAnimations();
         }
@@ -391,7 +391,7 @@
     for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
         RenderObject* renderer = it->key;
         CompositeAnimation* compAnim = it->value.get();
-        if (renderer->document() == document)
+        if (&renderer->document() == document)
             count += compAnim->numberOfActiveAnimations();
     }
 
@@ -498,9 +498,6 @@
 
 PassRefPtr<RenderStyle> AnimationController::updateAnimations(RenderObject* renderer, RenderStyle* newStyle)
 {
-    if (!renderer->document())
-        return newStyle;
-
     RenderStyle* oldStyle = renderer->style();
 
     if ((!oldStyle || (!oldStyle->animations() && !oldStyle->transitions())) && (!newStyle->animations() && !newStyle->transitions()))
diff --git a/Source/core/page/animation/CSSPropertyAnimation.cpp b/Source/core/page/animation/CSSPropertyAnimation.cpp
index 4b8e0c6..5b31b8c 100644
--- a/Source/core/page/animation/CSSPropertyAnimation.cpp
+++ b/Source/core/page/animation/CSSPropertyAnimation.cpp
@@ -69,11 +69,9 @@
     return narrowPrecisionToFloat(from + (to - from) * progress);
 }
 
-static inline Color blendFunc(const AnimationBase* animation, const StyleColor& from, const StyleColor& to, double progress)
+static inline Color blendFunc(const AnimationBase*, const Color& from, const Color& to, double progress)
 {
-    Color fromColor = animation->renderer()->resolveColor(from);
-    Color toColor = animation->renderer()->resolveColor(to);
-    return blend(fromColor, toColor, progress);
+    return blend(from, to, progress);
 }
 
 static inline Length blendFunc(const AnimationBase*, const Length& from, const Length& to, double progress)
@@ -110,14 +108,11 @@
     if (from->style() != to->style())
         return to->clone();
 
-    Color fromColor = anim->renderer()->resolveColor(from->color());
-    Color toColor = anim->renderer()->resolveColor(to->color());
-
     return ShadowData::create(blend(from->location(), to->location(), progress),
         blend(from->blur(), to->blur(), progress),
         blend(from->spread(), to->spread(), progress),
         blendFunc(anim, from->style(), to->style(), progress),
-        blend(fromColor, toColor, progress));
+        blend(from->color(), to->color(), progress));
 }
 
 static inline TransformOperations blendFunc(const AnimationBase* anim, const TransformOperations& from, const TransformOperations& to, double progress)
@@ -452,21 +447,21 @@
     }
 };
 
-class PropertyWrapperColor : public PropertyWrapperGetter<StyleColor> {
+class PropertyWrapperColor : public PropertyWrapperGetter<Color> {
 public:
-    PropertyWrapperColor(CSSPropertyID prop, StyleColor (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const StyleColor&))
-        : PropertyWrapperGetter<StyleColor>(prop, getter)
+    PropertyWrapperColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
+        : PropertyWrapperGetter<Color>(prop, getter)
         , m_setter(setter)
     {
     }
 
     virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
     {
-        (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<StyleColor>::m_getter)(), (b->*PropertyWrapperGetter<StyleColor>::m_getter)(), progress));
+        (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<Color>::m_getter)(), (b->*PropertyWrapperGetter<Color>::m_getter)(), progress));
     }
 
 protected:
-    void (RenderStyle::*m_setter)(const StyleColor&);
+    void (RenderStyle::*m_setter)(const Color&);
 };
 
 class PropertyWrapperAcceleratedOpacity : public PropertyWrapper<float> {
@@ -589,7 +584,7 @@
     }
 
 private:
-    PassOwnPtr<ShadowData*> blendSimpleOrMatchedShadowLists(const AnimationBase* anim, double progress, const ShadowData* shadowA, const ShadowData* shadowB) const
+    PassOwnPtr<ShadowData> blendSimpleOrMatchedShadowLists(const AnimationBase* anim, double progress, const ShadowData* shadowA, const ShadowData* shadowB) const
     {
         OwnPtr<ShadowData> newShadowData;
         ShadowData* lastShadow = 0;
@@ -615,7 +610,7 @@
         return newShadowData.release();
     }
 
-    PassOwnPtr<ShadowData*> blendMismatchedShadowLists(const AnimationBase* anim, double progress, const ShadowData* shadowA, const ShadowData* shadowB, int fromLength, int toLength) const
+    PassOwnPtr<ShadowData> blendMismatchedShadowLists(const AnimationBase* anim, double progress, const ShadowData* shadowA, const ShadowData* shadowB, int fromLength, int toLength) const
     {
         // The shadows in ShadowData are stored in reverse order, so when animating mismatched lists,
         // reverse them and match from the end.
@@ -656,7 +651,7 @@
 
 class PropertyWrapperMaybeInvalidColor : public AnimationPropertyWrapperBase {
 public:
-    PropertyWrapperMaybeInvalidColor(CSSPropertyID prop, StyleColor (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const StyleColor&))
+    PropertyWrapperMaybeInvalidColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
         : AnimationPropertyWrapperBase(prop)
         , m_getter(getter)
         , m_setter(setter)
@@ -665,8 +660,8 @@
 
     virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
     {
-        StyleColor fromColor = (a->*m_getter)();
-        StyleColor toColor = (b->*m_getter)();
+        Color fromColor = (a->*m_getter)();
+        Color toColor = (b->*m_getter)();
 
         if (!fromColor.isValid() && !toColor.isValid())
             return true;
@@ -681,8 +676,8 @@
 
     virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
     {
-        StyleColor fromColor = (a->*m_getter)();
-        StyleColor toColor = (b->*m_getter)();
+        Color fromColor = (a->*m_getter)();
+        Color toColor = (b->*m_getter)();
 
         if (!fromColor.isValid() && !toColor.isValid())
             return;
@@ -695,23 +690,23 @@
     }
 
 private:
-    StyleColor (RenderStyle::*m_getter)() const;
-    void (RenderStyle::*m_setter)(const StyleColor&);
+    Color (RenderStyle::*m_getter)() const;
+    void (RenderStyle::*m_setter)(const Color&);
 };
 
 
 enum MaybeInvalidColorTag { MaybeInvalidColor };
 class PropertyWrapperVisitedAffectedColor : public AnimationPropertyWrapperBase {
 public:
-    PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, StyleColor (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const StyleColor&),
-        StyleColor (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const StyleColor&))
+    PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&),
+        Color (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const Color&))
         : AnimationPropertyWrapperBase(prop)
         , m_wrapper(adoptPtr(new PropertyWrapperColor(prop, getter, setter)))
         , m_visitedWrapper(adoptPtr(new PropertyWrapperColor(prop, visitedGetter, visitedSetter)))
     {
     }
-    PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, MaybeInvalidColorTag, StyleColor (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const StyleColor&),
-        StyleColor (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const StyleColor&))
+    PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, MaybeInvalidColorTag, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&),
+        Color (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const Color&))
         : AnimationPropertyWrapperBase(prop)
         , m_wrapper(adoptPtr(new PropertyWrapperMaybeInvalidColor(prop, getter, setter)))
         , m_visitedWrapper(adoptPtr(new PropertyWrapperMaybeInvalidColor(prop, visitedGetter, visitedSetter)))
@@ -963,7 +958,7 @@
 
 class PropertyWrapperSVGPaint : public AnimationPropertyWrapperBase {
 public:
-    PropertyWrapperSVGPaint(CSSPropertyID prop, const SVGPaint::SVGPaintType& (RenderStyle::*paintTypeGetter)() const, StyleColor (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const StyleColor&))
+    PropertyWrapperSVGPaint(CSSPropertyID prop, const SVGPaint::SVGPaintType& (RenderStyle::*paintTypeGetter)() const, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
         : AnimationPropertyWrapperBase(prop)
         , m_paintTypeGetter(paintTypeGetter)
         , m_getter(getter)
@@ -976,20 +971,20 @@
         if ((a->*m_paintTypeGetter)() != (b->*m_paintTypeGetter)())
             return false;
 
-        // We only support animations between SVGPaints that are pure StyleColor values.
+        // We only support animations between SVGPaints that are pure Color values.
         // For everything else we must return true for this method, otherwise
         // we will try to animate between values forever.
         if ((a->*m_paintTypeGetter)() == SVGPaint::SVG_PAINTTYPE_RGBCOLOR) {
-            StyleColor fromColor = (a->*m_getter)();
-            StyleColor toColor = (b->*m_getter)();
+            Color fromColor = (a->*m_getter)();
+            Color toColor = (b->*m_getter)();
 
             if (!fromColor.isValid() && !toColor.isValid())
                 return true;
 
             if (!fromColor.isValid())
-                fromColor = StyleColor();
+                fromColor = Color();
             if (!toColor.isValid())
-                toColor = StyleColor();
+                toColor = Color();
 
             return fromColor == toColor;
         }
@@ -1002,23 +997,23 @@
             || (b->*m_paintTypeGetter)() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR)
             return;
 
-        StyleColor fromColor = (a->*m_getter)();
-        StyleColor toColor = (b->*m_getter)();
+        Color fromColor = (a->*m_getter)();
+        Color toColor = (b->*m_getter)();
 
         if (!fromColor.isValid() && !toColor.isValid())
             return;
 
         if (!fromColor.isValid())
-            fromColor = StyleColor();
+            fromColor = Color();
         if (!toColor.isValid())
-            toColor = StyleColor();
+            toColor = Color();
         (dst->*m_setter)(blendFunc(anim, fromColor, toColor, progress));
     }
 
 private:
     const SVGPaint::SVGPaintType& (RenderStyle::*m_paintTypeGetter)() const;
-    StyleColor (RenderStyle::*m_getter)() const;
-    void (RenderStyle::*m_setter)(const StyleColor&);
+    Color (RenderStyle::*m_getter)() const;
+    void (RenderStyle::*m_setter)(const Color&);
 };
 
 static void addShorthandProperties()
diff --git a/Source/core/page/animation/ImplicitAnimation.cpp b/Source/core/page/animation/ImplicitAnimation.cpp
index 2072f13..4ceeff6 100644
--- a/Source/core/page/animation/ImplicitAnimation.cpp
+++ b/Source/core/page/animation/ImplicitAnimation.cpp
@@ -61,7 +61,7 @@
 
 bool ImplicitAnimation::shouldSendEventForListener(Document::ListenerType inListenerType) const
 {
-    return m_object->document()->hasListenerType(inListenerType);
+    return m_object->document().hasListenerType(inListenerType);
 }
 
 void ImplicitAnimation::animate(CompositeAnimation*, RenderObject*, const RenderStyle*, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle)
diff --git a/Source/core/page/animation/KeyframeAnimation.cpp b/Source/core/page/animation/KeyframeAnimation.cpp
index da07f66..da92432 100644
--- a/Source/core/page/animation/KeyframeAnimation.cpp
+++ b/Source/core/page/animation/KeyframeAnimation.cpp
@@ -53,7 +53,7 @@
 {
     // Get the keyframe RenderStyles
     if (m_object && m_object->node() && m_object->node()->isElementNode())
-        m_object->document()->styleResolver()->keyframeStylesForAnimation(toElement(m_object->node()), unanimatedStyle, m_keyframes);
+        m_object->document().styleResolver()->keyframeStylesForAnimation(toElement(m_object->node()), unanimatedStyle, m_keyframes);
 
     // Update the m_transformFunctionListValid flag based on whether the function lists in the keyframes match.
     validateTransformFunctionList();
@@ -70,20 +70,6 @@
         endAnimation();
 }
 
-static const CSSAnimationData* getAnimationFromStyleByName(const RenderStyle* style, const AtomicString& name)
-{
-    if (!style->animations())
-        return 0;
-
-    size_t animationCount = style->animations()->size();
-    for (size_t i = 0; i < animationCount; i++) {
-        if (name == style->animations()->animation(i)->name())
-            return style->animations()->animation(i);
-    }
-
-    return 0;
-}
-
 void KeyframeAnimation::fetchIntervalEndpointsForProperty(CSSPropertyID property, const RenderStyle*& fromStyle, const RenderStyle*& toStyle, double& prog) const
 {
     // Find the first key
@@ -133,7 +119,7 @@
     }
 
     // Iterate backward to find previous keyframe.
-    for (size_t i = currentIndex; i < numKeyframes; --i) {
+    for (int i = currentIndex; i >= 0; --i) {
         const KeyframeValue& keyFrame = m_keyframes[i];
         if (keyFrame.key() <= fractionalTime && keyFrame.containsProperty(property)) {
             prevIndex = i;
@@ -159,10 +145,7 @@
     offset = prevKeyframe.key();
     scale = 1.0 / (nextKeyframe.key() - prevKeyframe.key());
 
-    const TimingFunction* timingFunction = 0;
-    if (const CSSAnimationData* matchedAnimation = getAnimationFromStyleByName(fromStyle, name()))
-        timingFunction = matchedAnimation->timingFunction().get();
-
+    const TimingFunction* timingFunction = prevKeyframe.timingFunction(name());
     prog = progress(scale, offset, timingFunction);
 }
 
@@ -287,7 +270,7 @@
 
 bool KeyframeAnimation::shouldSendEventForListener(Document::ListenerType listenerType) const
 {
-    return m_object->document()->hasListenerType(listenerType);
+    return m_object->document().hasListenerType(listenerType);
 }
 
 void KeyframeAnimation::onAnimationStart(double elapsedTime)
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.cpp b/Source/core/page/scrolling/ScrollingCoordinator.cpp
index ca740b9..6d70329 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -30,10 +30,12 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/Document.h"
 #include "core/dom/Node.h"
+#include "core/dom/WheelController.h"
 #include "core/html/HTMLElement.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
+#include "core/page/Settings.h"
 #include "core/platform/PlatformWheelEvent.h"
 #include "core/platform/ScrollAnimator.h"
 #include "core/platform/ScrollbarTheme.h"
@@ -44,7 +46,7 @@
 #include "core/platform/graphics/IntRect.h"
 #include "core/platform/graphics/Region.h"
 #include "core/platform/graphics/transforms/TransformState.h"
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include "core/platform/mac/ScrollAnimatorMac.h"
 #endif
 #include "core/plugins/PluginView.h"
@@ -208,6 +210,14 @@
     return scrollbarLayer.release();
 }
 
+PassOwnPtr<WebScrollbarLayer> ScrollingCoordinator::createSolidColorScrollbarLayer(ScrollbarOrientation orientation, int thumbThickness, bool isLeftSideVerticalScrollbar)
+{
+    WebKit::WebScrollbar::Orientation webOrientation = (orientation == HorizontalScrollbar) ? WebKit::WebScrollbar::Horizontal : WebKit::WebScrollbar::Vertical;
+    OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createSolidColorScrollbarLayer(webOrientation, thumbThickness, isLeftSideVerticalScrollbar));
+    GraphicsLayer::registerContentsLayer(scrollbarLayer->layer());
+    return scrollbarLayer.release();
+}
+
 static void detachScrollbarLayer(GraphicsLayer* scrollbarGraphicsLayer)
 {
     ASSERT(scrollbarGraphicsLayer);
@@ -245,7 +255,7 @@
 void ScrollingCoordinator::scrollableAreaScrollbarLayerDidChange(ScrollableArea* scrollableArea, ScrollbarOrientation orientation)
 {
 // FIXME: Instead of hardcode here, we should make a setting flag.
-#if OS(DARWIN)
+#if OS(MACOSX)
     static const bool platformSupportsCoordinatedScrollbar = ScrollAnimatorMac::canUseCoordinatedScrollbar();
     static const bool platformSupportsMainFrameOnly = false; // Don't care.
 #elif OS(ANDROID)
@@ -271,8 +281,18 @@
         }
 
         WebScrollbarLayer* scrollbarLayer = getWebScrollbarLayer(scrollableArea, orientation);
-        if (!scrollbarLayer)
-            scrollbarLayer = addWebScrollbarLayer(scrollableArea, orientation, createScrollbarLayer(scrollbar));
+        if (!scrollbarLayer) {
+            Settings* settings = m_page->mainFrame()->document()->settings();
+
+            OwnPtr<WebScrollbarLayer> webScrollbarLayer;
+            if (settings->useSolidColorScrollbars()) {
+                ASSERT(RuntimeEnabledFeatures::overlayScrollbarsEnabled());
+                webScrollbarLayer = createSolidColorScrollbarLayer(orientation, -1, scrollableArea->shouldPlaceVerticalScrollbarOnLeft());
+            } else {
+                webScrollbarLayer = createScrollbarLayer(scrollbar);
+            }
+            scrollbarLayer = addWebScrollbarLayer(scrollableArea, orientation, webScrollbarLayer.release());
+        }
 
         // Root layer non-overlay scrollbars should be marked opaque to disable
         // blending.
@@ -526,7 +546,7 @@
     ASSERT(m_page);
 
     // We currently only handle the main frame.
-    if (frameView->frame() != m_page->mainFrame())
+    if (&frameView->frame() != m_page->mainFrame())
         return false;
 
     // We currently only support composited mode.
@@ -653,7 +673,7 @@
 
     for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
         if (frame->document())
-            wheelEventHandlerCount += frame->document()->wheelEventHandlerCount();
+            wheelEventHandlerCount += WheelController::from(frame->document())->wheelEventHandlerCount();
     }
 
     return wheelEventHandlerCount;
@@ -711,11 +731,7 @@
 
 GraphicsLayer* ScrollingCoordinator::scrollLayerForFrameView(FrameView* frameView)
 {
-    Frame* frame = frameView->frame();
-    if (!frame)
-        return 0;
-
-    RenderView* renderView = frame->contentRenderer();
+    RenderView* renderView = frameView->frame().contentRenderer();
     if (!renderView)
         return 0;
     return renderView->compositor()->scrollLayer();
@@ -739,7 +755,7 @@
     updateShouldUpdateScrollLayerPositionOnMainThread();
 }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 void ScrollingCoordinator::handleWheelEventPhase(PlatformWheelEventPhase phase)
 {
     ASSERT(isMainThread());
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.h b/Source/core/page/scrolling/ScrollingCoordinator.h
index 175c97d..d94ea48 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.h
+++ b/Source/core/page/scrolling/ScrollingCoordinator.h
@@ -76,7 +76,7 @@
     // Should be called whenever the root layer for the given frame view changes.
     void frameViewRootLayerDidChange(FrameView*);
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     // Dispatched by the scrolling tree during handleWheelEvent. This is required as long as scrollbars are painted on the main thread.
     void handleWheelEventPhase(PlatformWheelEventPhase);
 #endif
@@ -90,6 +90,8 @@
     MainThreadScrollingReasons mainThreadScrollingReasons() const;
     bool shouldUpdateScrollLayerPositionOnMainThread() const { return mainThreadScrollingReasons() != 0; }
 
+    PassOwnPtr<WebKit::WebScrollbarLayer> createSolidColorScrollbarLayer(ScrollbarOrientation, int thumbThickness, bool isLeftSideVerticalScrollbar);
+
     void willDestroyScrollableArea(ScrollableArea*);
     // Returns true if the coordinator handled this change.
     bool scrollableAreaScrollLayerDidChange(ScrollableArea*);
diff --git a/Source/core/platform/AsyncFileSystemCallbacks.h b/Source/core/platform/AsyncFileSystemCallbacks.h
index 7134297..788ff1d 100644
--- a/Source/core/platform/AsyncFileSystemCallbacks.h
+++ b/Source/core/platform/AsyncFileSystemCallbacks.h
@@ -42,13 +42,13 @@
 class AsyncFileSystemCallbacks {
     WTF_MAKE_NONCOPYABLE(AsyncFileSystemCallbacks);
 public:
-    AsyncFileSystemCallbacks() { }
+    AsyncFileSystemCallbacks() : m_blockUntilCompletion(false) { }
 
     // Called when a requested operation is completed successfully.
     virtual void didSucceed() { ASSERT_NOT_REACHED(); }
 
     // Called when a requested file system is opened.
-    virtual void didOpenFileSystem(const String& name, const KURL& rootURL, PassOwnPtr<AsyncFileSystem>) { ASSERT_NOT_REACHED(); }
+    virtual void didOpenFileSystem(const String& name, const KURL& rootURL) { ASSERT_NOT_REACHED(); }
 
     // Called when a file metadata is read successfully.
     virtual void didReadMetadata(const FileMetadata&) { ASSERT_NOT_REACHED(); }
@@ -70,9 +70,20 @@
 
     // Returns true if the caller expects that the calling thread blocks
     // until completion.
-    virtual bool shouldBlockUntilCompletion() const { return false; }
+    virtual bool shouldBlockUntilCompletion() const
+    {
+        return m_blockUntilCompletion;
+    }
+
+    void setShouldBlockUntilCompletion(bool flag)
+    {
+        m_blockUntilCompletion = flag;
+    }
 
     virtual ~AsyncFileSystemCallbacks() { }
+
+private:
+    bool m_blockUntilCompletion;
 };
 
 } // namespace
diff --git a/Source/core/platform/DecimalTest.cpp b/Source/core/platform/DecimalTest.cpp
index 3e2aa83..b56fe88 100644
--- a/Source/core/platform/DecimalTest.cpp
+++ b/Source/core/platform/DecimalTest.cpp
@@ -33,6 +33,7 @@
 
 #include "wtf/MathExtras.h"
 #include "wtf/text/CString.h"
+#include <float.h>
 #include <gtest/gtest.h>
 
 namespace WebCore {
diff --git a/Source/core/platform/DragData.cpp b/Source/core/platform/DragData.cpp
index 90e4605..ce0d142 100644
--- a/Source/core/platform/DragData.cpp
+++ b/Source/core/platform/DragData.cpp
@@ -156,7 +156,8 @@
         String html;
         KURL baseURL;
         m_platformDragData->htmlAndBaseURL(html, baseURL);
-        if (RefPtr<DocumentFragment> fragment = createFragmentFromMarkup(frame->document(), html, baseURL, DisallowScriptingAndPluginContent))
+        ASSERT(frame->document());
+        if (RefPtr<DocumentFragment> fragment = createFragmentFromMarkup(*frame->document(), html, baseURL, DisallowScriptingAndPluginContent))
             return fragment.release();
     }
 
diff --git a/Source/core/platform/Language.cpp b/Source/core/platform/Language.cpp
index 1106545..3376fab 100644
--- a/Source/core/platform/Language.cpp
+++ b/Source/core/platform/Language.cpp
@@ -26,37 +26,10 @@
 #include "config.h"
 #include "core/platform/Language.h"
 
-#include "wtf/HashMap.h"
-#include "wtf/RetainPtr.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-typedef HashMap<void*, LanguageChangeObserverFunction> ObserverMap;
-static ObserverMap& observerMap()
-{
-    DEFINE_STATIC_LOCAL(ObserverMap, map, ());
-    return map;
-}
-
-void addLanguageChangeObserver(void* context, LanguageChangeObserverFunction customObserver)
-{
-    observerMap().set(context, customObserver);
-}
-
-void removeLanguageChangeObserver(void* context)
-{
-    ASSERT(observerMap().contains(context));
-    observerMap().remove(context);
-}
-
-void languageDidChange()
-{
-    ObserverMap::iterator end = observerMap().end();
-    for (ObserverMap::iterator iter = observerMap().begin(); iter != end; ++iter)
-        iter->value(iter->key);
-}
-
 String defaultLanguage()
 {
     Vector<String> languages = userPreferredLanguages();
diff --git a/Source/core/platform/Language.h b/Source/core/platform/Language.h
index c727256..2626085 100644
--- a/Source/core/platform/Language.h
+++ b/Source/core/platform/Language.h
@@ -37,15 +37,8 @@
 void overrideUserPreferredLanguages(const Vector<String>&);
 size_t indexOfBestMatchingLanguageInList(const String& language, const Vector<String>& languageList);
 
-// The observer function will be called when system language changes.
-typedef void (*LanguageChangeObserverFunction)(void* context);
-void addLanguageChangeObserver(void* context, LanguageChangeObserverFunction);
-void removeLanguageChangeObserver(void* context);
-
 Vector<String> platformUserPreferredLanguages();
 
-// Called from platform specific code when the user's preferred language(s) change.
-void languageDidChange();
 }
 
 #endif
diff --git a/Source/core/platform/LayoutUnit.h b/Source/core/platform/LayoutUnit.h
index b1b293a..712fc88 100644
--- a/Source/core/platform/LayoutUnit.h
+++ b/Source/core/platform/LayoutUnit.h
@@ -31,11 +31,12 @@
 #ifndef LayoutUnit_h
 #define LayoutUnit_h
 
+#include "wtf/Assertions.h"
 #include "wtf/MathExtras.h"
 #include "wtf/SaturatedArithmetic.h"
 #include <limits.h>
 #include <limits>
-#include <math.h>
+#include <stdlib.h>
 
 namespace WebCore {
 
@@ -130,7 +131,7 @@
         returnValue.setRawValue(::abs(m_value));
         return returnValue;
     }
-#if OS(DARWIN)
+#if OS(MACOSX)
     int wtf_ceil() const
 #else
     int ceil() const
diff --git a/Source/core/platform/chromium/LocalizedStringsChromium.cpp b/Source/core/platform/LocalizedStrings.cpp
similarity index 99%
rename from Source/core/platform/chromium/LocalizedStringsChromium.cpp
rename to Source/core/platform/LocalizedStrings.cpp
index dbf0c21..d79d99c 100644
--- a/Source/core/platform/chromium/LocalizedStringsChromium.cpp
+++ b/Source/core/platform/LocalizedStrings.cpp
@@ -34,7 +34,6 @@
 #include "core/platform/NotImplemented.h"
 #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"
diff --git a/Source/core/platform/Partitions.cpp b/Source/core/platform/Partitions.cpp
index a5c54f4..05ee880 100644
--- a/Source/core/platform/Partitions.cpp
+++ b/Source/core/platform/Partitions.cpp
@@ -34,13 +34,13 @@
 
 namespace WebCore {
 
-PartitionRoot Partitions::m_objectModelRoot;
-PartitionRoot Partitions::m_renderingRoot;
+PartitionAllocator<3072> Partitions::m_objectModelAllocator;
+PartitionAllocator<1024> Partitions::m_renderingAllocator;
 
 void Partitions::init()
 {
-    partitionAllocInit(&m_objectModelRoot);
-    partitionAllocInit(&m_renderingRoot);
+    m_objectModelAllocator.init();
+    m_renderingAllocator.init();
 }
 
 void Partitions::shutdown()
@@ -48,8 +48,8 @@
     // We could ASSERT here for a memory leak within the partition, but it leads
     // to very hard to diagnose ASSERTs, so it's best to leave leak checking for
     // the valgrind and heapcheck bots, which run without partitions.
-    (void) partitionAllocShutdown(&m_objectModelRoot);
-    (void) partitionAllocShutdown(&m_renderingRoot);
+    (void) m_renderingAllocator.shutdown();
+    (void) m_objectModelAllocator.shutdown();
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/Partitions.h b/Source/core/platform/Partitions.h
index fe2d148..6f20e70 100644
--- a/Source/core/platform/Partitions.h
+++ b/Source/core/platform/Partitions.h
@@ -40,12 +40,12 @@
     static void init();
     static void shutdown();
 
-    ALWAYS_INLINE static PartitionRoot* getObjectModelPartition() { return &m_objectModelRoot; }
-    ALWAYS_INLINE static PartitionRoot* getRenderingPartition() { return &m_renderingRoot; }
+    ALWAYS_INLINE static PartitionRoot* getObjectModelPartition() { return m_objectModelAllocator.root(); }
+    ALWAYS_INLINE static PartitionRoot* getRenderingPartition() { return m_renderingAllocator.root(); }
 
 private:
-    static PartitionRoot m_objectModelRoot;
-    static PartitionRoot m_renderingRoot;
+    static PartitionAllocator<3072> m_objectModelAllocator;
+    static PartitionAllocator<1024> m_renderingAllocator;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/Pasteboard.cpp b/Source/core/platform/Pasteboard.cpp
index 1aa983a..594cc79 100644
--- a/Source/core/platform/Pasteboard.cpp
+++ b/Source/core/platform/Pasteboard.cpp
@@ -42,7 +42,7 @@
 #include "core/fetch/ImageResource.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/page/Frame.h"
-#include "core/platform/chromium/ClipboardChromium.h"
+#include "core/platform/chromium/ChromiumDataObject.h"
 #include "core/platform/chromium/ClipboardUtilitiesChromium.h"
 #include "core/platform/graphics/Image.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
@@ -51,6 +51,8 @@
 #include "public/platform/WebClipboard.h"
 #include "public/platform/WebDragData.h"
 #include "weborigin/KURL.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
@@ -78,9 +80,9 @@
 void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, const String& text)
 {
     String html = createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs);
-    KURL url = selectedRange->startContainer()->document()->url();
+    KURL url = selectedRange->startContainer()->document().url();
     String plainText = text;
-#if OS(WINDOWS)
+#if OS(WIN)
     replaceNewlinesWithWindowsStyleNewlines(plainText);
 #endif
     replaceNBSPWithSpace(plainText);
@@ -91,7 +93,7 @@
 void Pasteboard::writePlainText(const String& text, SmartReplaceOption)
 {
     // FIXME: add support for smart replace
-#if OS(WINDOWS)
+#if OS(WIN)
     String plainText(text);
     replaceNewlinesWithWindowsStyleNewlines(plainText);
     WebKit::Platform::current()->clipboard()->writePlainText(plainText);
@@ -141,15 +143,14 @@
         urlString = toElement(node)->getAttribute(XLinkNames::hrefAttr);
     else if (node->hasTagName(HTMLNames::embedTag) || node->hasTagName(HTMLNames::objectTag))
         urlString = toElement(node)->imageSourceURL();
-    KURL url = urlString.isEmpty() ? KURL() : node->document()->completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
+    KURL url = urlString.isEmpty() ? KURL() : node->document().completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
     WebKit::WebImage webImage = bitmap->bitmap();
     WebKit::Platform::current()->clipboard()->writeImage(webImage, WebKit::WebURL(url), WebKit::WebString(title));
 }
 
-void Pasteboard::writeClipboard(Clipboard* clipboard)
+void Pasteboard::writeDataObject(PassRefPtr<ChromiumDataObject> dataObject)
 {
-    WebKit::WebDragData dragData = static_cast<ClipboardChromium*>(clipboard)->dataObject();
-    WebKit::Platform::current()->clipboard()->writeDataObject(dragData);
+    WebKit::Platform::current()->clipboard()->writeDataObject(dataObject);
 }
 
 bool Pasteboard::canSmartReplace()
@@ -173,7 +174,8 @@
         WebKit::WebURL url;
         WebKit::WebString markup = WebKit::Platform::current()->clipboard()->readHTML(buffer, &url, &fragmentStart, &fragmentEnd);
         if (!markup.isEmpty()) {
-            if (RefPtr<DocumentFragment> fragment = createFragmentFromMarkupWithContext(frame->document(), markup, fragmentStart, fragmentEnd, KURL(url), DisallowScriptingAndPluginContent))
+            ASSERT(frame->document());
+            if (RefPtr<DocumentFragment> fragment = createFragmentFromMarkupWithContext(*frame->document(), markup, fragmentStart, fragmentEnd, KURL(url), DisallowScriptingAndPluginContent))
                 return fragment.release();
         }
     }
diff --git a/Source/core/platform/Pasteboard.h b/Source/core/platform/Pasteboard.h
index ecacf55..8e7c2d9 100644
--- a/Source/core/platform/Pasteboard.h
+++ b/Source/core/platform/Pasteboard.h
@@ -39,7 +39,7 @@
 namespace WebCore {
 
 class ArchiveResource;
-class Clipboard;
+class ChromiumDataObject;
 class DocumentFragment;
 class Frame;
 class HitTestResult;
@@ -61,7 +61,7 @@
     void writePlainText(const String&, SmartReplaceOption);
     void writeURL(const KURL&, const String&);
     void writeImage(Node*, const KURL&, const String& title);
-    void writeClipboard(Clipboard*);
+    void writeDataObject(PassRefPtr<ChromiumDataObject>);
     bool canSmartReplace();
     PassRefPtr<DocumentFragment> documentFragment(Frame*, PassRefPtr<Range>, bool allowPlainText, bool& chosePlainText);
     String plainText();
diff --git a/Source/core/platform/PlatformWheelEvent.h b/Source/core/platform/PlatformWheelEvent.h
index 1984e7a..894c776 100644
--- a/Source/core/platform/PlatformWheelEvent.h
+++ b/Source/core/platform/PlatformWheelEvent.h
@@ -44,7 +44,7 @@
         ScrollByPixelWheelEvent,
     };
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     enum PlatformWheelEventPhase {
         PlatformWheelEventPhaseNone        = 0,
         PlatformWheelEventPhaseBegan       = 1 << 0,
@@ -67,7 +67,7 @@
             , m_granularity(ScrollByPixelWheelEvent)
             , m_directionInvertedFromDevice(false)
             , m_hasPreciseScrollingDeltas(false)
-#if OS(DARWIN)
+#if OS(MACOSX)
             , m_phase(PlatformWheelEventPhaseNone)
             , m_momentumPhase(PlatformWheelEventPhaseNone)
             , m_scrollCount(0)
@@ -88,7 +88,7 @@
             , m_granularity(granularity)
             , m_directionInvertedFromDevice(false)
             , m_hasPreciseScrollingDeltas(false)
-#if OS(DARWIN)
+#if OS(MACOSX)
             , m_phase(PlatformWheelEventPhaseNone)
             , m_momentumPhase(PlatformWheelEventPhaseNone)
             , m_scrollCount(0)
@@ -125,7 +125,7 @@
 
         bool hasPreciseScrollingDeltas() const { return m_hasPreciseScrollingDeltas; }
         void setHasPreciseScrollingDeltas(bool b) { m_hasPreciseScrollingDeltas = b; }
-#if OS(DARWIN)
+#if OS(MACOSX)
         PlatformWheelEventPhase phase() const { return m_phase; }
         PlatformWheelEventPhase momentumPhase() const { return m_momentumPhase; }
         unsigned scrollCount() const { return m_scrollCount; }
@@ -146,7 +146,7 @@
         PlatformWheelEventGranularity m_granularity;
         bool m_directionInvertedFromDevice;
         bool m_hasPreciseScrollingDeltas;
-#if OS(DARWIN)
+#if OS(MACOSX)
         PlatformWheelEventPhase m_phase;
         PlatformWheelEventPhase m_momentumPhase;
         unsigned m_scrollCount;
diff --git a/Source/core/platform/ScrollAnimator.cpp b/Source/core/platform/ScrollAnimator.cpp
index a503f69..3be5c13 100644
--- a/Source/core/platform/ScrollAnimator.cpp
+++ b/Source/core/platform/ScrollAnimator.cpp
@@ -86,7 +86,7 @@
 
     bool handled = false;
 
-#if !OS(DARWIN)
+#if !OS(MACOSX)
     ScrollGranularity granularity = e.hasPreciseScrollingDeltas() ? ScrollByPrecisePixel : ScrollByPixel;
 #else
     ScrollGranularity granularity = ScrollByPixel;
diff --git a/Source/core/platform/ScrollAnimator.h b/Source/core/platform/ScrollAnimator.h
index c0a7f02..964a46b 100644
--- a/Source/core/platform/ScrollAnimator.h
+++ b/Source/core/platform/ScrollAnimator.h
@@ -65,7 +65,7 @@
 
     virtual bool handleWheelEvent(const PlatformWheelEvent&);
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     virtual void handleWheelEventPhase(PlatformWheelEventPhase) { }
 #endif
 
diff --git a/Source/core/platform/ScrollView.cpp b/Source/core/platform/ScrollView.cpp
index 79dd29b..17f4180 100644
--- a/Source/core/platform/ScrollView.cpp
+++ b/Source/core/platform/ScrollView.cpp
@@ -110,7 +110,7 @@
 
 PassRefPtr<Scrollbar> ScrollView::createScrollbar(ScrollbarOrientation orientation)
 {
-    return Scrollbar::createNativeScrollbar(this, orientation, RegularScrollbar);
+    return Scrollbar::create(this, orientation, RegularScrollbar);
 }
 
 void ScrollView::setScrollbarModes(ScrollbarMode horizontalMode, ScrollbarMode verticalMode,
@@ -809,6 +809,11 @@
     return mode == ScrollbarAuto || mode == ScrollbarAlwaysOn;
 }
 
+bool ScrollView::shouldPlaceVerticalScrollbarOnLeft() const
+{
+    return false;
+}
+
 void ScrollView::repaintContentRectangle(const IntRect& rect)
 {
     IntRect paintRect = rect;
diff --git a/Source/core/platform/ScrollView.h b/Source/core/platform/ScrollView.h
index 4b2de99..bea72cf 100644
--- a/Source/core/platform/ScrollView.h
+++ b/Source/core/platform/ScrollView.h
@@ -50,6 +50,7 @@
     virtual bool isScrollCornerVisible() const OVERRIDE;
     virtual void scrollbarStyleChanged(int newStyle, bool forceUpdate) OVERRIDE;
     virtual bool userInputScrollable(ScrollbarOrientation) const OVERRIDE;
+    virtual bool shouldPlaceVerticalScrollbarOnLeft() const OVERRIDE;
 
     virtual void notifyPageThatContentAreaWillPaint() const;
 
diff --git a/Source/core/platform/ScrollableArea.cpp b/Source/core/platform/ScrollableArea.cpp
index ff56d74..8bb6bed 100644
--- a/Source/core/platform/ScrollableArea.cpp
+++ b/Source/core/platform/ScrollableArea.cpp
@@ -402,11 +402,6 @@
     return scrollPosition.shrunkTo(maximumScrollPosition()).expandedTo(minimumScrollPosition());
 }
 
-TextDirection ScrollableArea::textDirection() const
-{
-    return !m_scrollOrigin.x() ? LTR : RTL;
-}
-
 int ScrollableArea::lineStep(ScrollbarOrientation) const
 {
     return pixelsPerLineStep();
diff --git a/Source/core/platform/ScrollableArea.h b/Source/core/platform/ScrollableArea.h
index ca66145..4494722 100644
--- a/Source/core/platform/ScrollableArea.h
+++ b/Source/core/platform/ScrollableArea.h
@@ -27,7 +27,6 @@
 #define ScrollableArea_h
 
 #include "core/platform/Scrollbar.h"
-#include "core/platform/text/TextDirection.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
@@ -180,6 +179,7 @@
     virtual void updateNeedsCompositedScrolling() { }
 
     virtual bool userInputScrollable(ScrollbarOrientation) const = 0;
+    virtual bool shouldPlaceVerticalScrollbarOnLeft() const = 0;
 
     // Convenience functions
     int scrollPosition(ScrollbarOrientation orientation) { return orientation == HorizontalScrollbar ? scrollPosition().x() : scrollPosition().y(); }
@@ -187,8 +187,6 @@
     int maximumScrollPosition(ScrollbarOrientation orientation) { return orientation == HorizontalScrollbar ? maximumScrollPosition().x() : maximumScrollPosition().y(); }
     int clampScrollPosition(ScrollbarOrientation orientation, int pos)  { return std::max(std::min(pos, maximumScrollPosition(orientation)), minimumScrollPosition(orientation)); }
 
-    TextDirection textDirection() const;
-
 protected:
     ScrollableArea();
     virtual ~ScrollableArea();
diff --git a/Source/core/platform/Scrollbar.cpp b/Source/core/platform/Scrollbar.cpp
index bcc2367..96c712b 100644
--- a/Source/core/platform/Scrollbar.cpp
+++ b/Source/core/platform/Scrollbar.cpp
@@ -42,7 +42,7 @@
 
 using namespace std;
 
-#if OS(UNIX) && !OS(DARWIN)
+#if OS(POSIX) && !OS(MACOSX)
 // The position of the scrollbar thumb affects the appearance of the steppers, so
 // when the thumb moves, we have to invalidate them for painting.
 #define THUMB_POSITION_AFFECTS_BUTTONS
@@ -50,7 +50,7 @@
 
 namespace WebCore {
 
-PassRefPtr<Scrollbar> Scrollbar::createNativeScrollbar(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, ScrollbarControlSize size)
+PassRefPtr<Scrollbar> Scrollbar::create(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, ScrollbarControlSize size)
 {
     return adoptRef(new Scrollbar(scrollableArea, orientation, size));
 }
@@ -121,11 +121,11 @@
     return parent() && parent()->isFrameView() && toFrameView(parent())->isScrollViewScrollbar(this);
 }
 
-TextDirection Scrollbar::textDirection() const
+bool Scrollbar::isLeftSideVerticalScrollbar() const
 {
     if (m_orientation == VerticalScrollbar && m_scrollableArea)
-        return m_scrollableArea->textDirection();
-    return LTR;
+        return m_scrollableArea->shouldPlaceVerticalScrollbarOnLeft();
+    return false;
 }
 
 void Scrollbar::offsetDidChange()
@@ -442,7 +442,7 @@
     }
 
     if (parent() && parent()->isFrameView())
-        toFrameView(parent())->frame()->eventHandler()->setMousePressed(false);
+        toFrameView(parent())->frame().eventHandler()->setMousePressed(false);
 }
 
 void Scrollbar::mouseDown(const PlatformMouseEvent& evt)
diff --git a/Source/core/platform/Scrollbar.h b/Source/core/platform/Scrollbar.h
index 15b9e03..f8de1fa 100644
--- a/Source/core/platform/Scrollbar.h
+++ b/Source/core/platform/Scrollbar.h
@@ -30,7 +30,6 @@
 #include "core/platform/ScrollbarThemeClient.h"
 #include "core/platform/Timer.h"
 #include "core/platform/Widget.h"
-#include "core/platform/text/TextDirection.h"
 #include "wtf/MathExtras.h"
 #include "wtf/PassRefPtr.h"
 
@@ -47,8 +46,7 @@
                   public ScrollbarThemeClient {
 
 public:
-    // Must be implemented by platforms that can't simply use the Scrollbar base class.  Right now the only platform that is not using the base class is GTK.
-    static PassRefPtr<Scrollbar> createNativeScrollbar(ScrollableArea*, ScrollbarOrientation, ScrollbarControlSize);
+    static PassRefPtr<Scrollbar> create(ScrollableArea*, ScrollbarOrientation, ScrollbarControlSize);
 
     virtual ~Scrollbar();
 
@@ -78,7 +76,7 @@
 
     virtual bool isCustomScrollbar() const { return false; }
     virtual ScrollbarOrientation orientation() const { return m_orientation; }
-    TextDirection textDirection() const;
+    virtual bool isLeftSideVerticalScrollbar() const;
 
     virtual int value() const { return lroundf(m_currentPos); }
     virtual float currentPos() const { return m_currentPos; }
diff --git a/Source/core/platform/ScrollbarTheme.cpp b/Source/core/platform/ScrollbarTheme.cpp
index 019ee97..158981e 100644
--- a/Source/core/platform/ScrollbarTheme.cpp
+++ b/Source/core/platform/ScrollbarTheme.cpp
@@ -26,16 +26,23 @@
 #include "config.h"
 #include "core/platform/ScrollbarTheme.h"
 
+#include "RuntimeEnabledFeatures.h"
 #include "core/page/Settings.h"
 #include "core/platform/ScrollbarThemeClient.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/mock/ScrollbarThemeMock.h"
+#include "core/platform/mock/ScrollbarThemeOverlayMock.h"
 
 namespace WebCore {
 
 ScrollbarTheme* ScrollbarTheme::theme()
 {
     if (Settings::mockScrollbarsEnabled()) {
+        if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) {
+            DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, overlayMockTheme, ());
+            return &overlayMockTheme;
+        }
+
         DEFINE_STATIC_LOCAL(ScrollbarThemeMock, mockTheme, ());
         return &mockTheme;
     }
@@ -202,14 +209,13 @@
     // This function won't even get called unless we're big enough to have some combination of these three rects where at least
     // one of them is non-empty.
     IntRect trackRect = constrainTrackRectToTrackPieces(scrollbar, unconstrainedTrackRect);
-    int thickness = scrollbar->orientation() == HorizontalScrollbar ? scrollbar->height() : scrollbar->width();
     int thumbPos = thumbPosition(scrollbar);
     if (scrollbar->orientation() == HorizontalScrollbar) {
-        thumbRect = IntRect(trackRect.x() + thumbPos, trackRect.y() + (trackRect.height() - thickness) / 2, thumbLength(scrollbar), thickness);
+        thumbRect = IntRect(trackRect.x() + thumbPos, trackRect.y(), thumbLength(scrollbar), scrollbar->height());
         beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), thumbPos + thumbRect.width() / 2, trackRect.height());
         afterThumbRect = IntRect(trackRect.x() + beforeThumbRect.width(), trackRect.y(), trackRect.maxX() - beforeThumbRect.maxX(), trackRect.height());
     } else {
-        thumbRect = IntRect(trackRect.x() + (trackRect.width() - thickness) / 2, trackRect.y() + thumbPos, thickness, thumbLength(scrollbar));
+        thumbRect = IntRect(trackRect.x(), trackRect.y() + thumbPos, scrollbar->width(), thumbLength(scrollbar));
         beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), trackRect.width(), thumbPos + thumbRect.height() / 2);
         afterThumbRect = IntRect(trackRect.x(), trackRect.y() + beforeThumbRect.height(), trackRect.width(), trackRect.maxY() - beforeThumbRect.maxY());
     }
diff --git a/Source/core/platform/ScrollbarThemeAndroid.cpp b/Source/core/platform/ScrollbarThemeAndroid.cpp
index bbceb46..48103ce 100644
--- a/Source/core/platform/ScrollbarThemeAndroid.cpp
+++ b/Source/core/platform/ScrollbarThemeAndroid.cpp
@@ -32,7 +32,7 @@
 
 ScrollbarTheme* ScrollbarTheme::nativeTheme()
 {
-    DEFINE_STATIC_LOCAL(ScrollbarThemeOverlay, theme, (3, 4));
+    DEFINE_STATIC_LOCAL(ScrollbarThemeOverlay, theme, (3, 4, ScrollbarThemeOverlay::DisallowHitTest));
     return &theme;
 }
 
diff --git a/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp b/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp
index f75829e..f76772f 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));
+        DEFINE_STATIC_LOCAL(ScrollbarThemeOverlay, theme, (7, 0, ScrollbarThemeOverlay::AllowHitTest));
         return &theme;
     }
 
diff --git a/Source/core/platform/ScrollbarThemeClient.h b/Source/core/platform/ScrollbarThemeClient.h
index 8372736..1fca367 100644
--- a/Source/core/platform/ScrollbarThemeClient.h
+++ b/Source/core/platform/ScrollbarThemeClient.h
@@ -64,6 +64,7 @@
 
     virtual bool isCustomScrollbar() const = 0;
     virtual ScrollbarOrientation orientation() const = 0;
+    virtual bool isLeftSideVerticalScrollbar() const = 0;
 
     virtual int value() const = 0;
     virtual float currentPos() const = 0;
diff --git a/Source/core/platform/ScrollbarThemeMacCommon.mm b/Source/core/platform/ScrollbarThemeMacCommon.mm
index 3e6d089..9aacbf4 100644
--- a/Source/core/platform/ScrollbarThemeMacCommon.mm
+++ b/Source/core/platform/ScrollbarThemeMacCommon.mm
@@ -45,7 +45,7 @@
 #include "public/platform/Platform.h"
 #include "public/platform/WebRect.h"
 #include "skia/ext/skia_utils_mac.h"
-#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/TemporaryChange.h"
 #include "wtf/UnusedParam.h"
@@ -61,12 +61,12 @@
 
 namespace WebCore {
 
-typedef HashMap<ScrollbarThemeClient*, ScrollbarThemeClient*> ScrollbarMap;
+typedef HashSet<ScrollbarThemeClient*> ScrollbarSet;
 
-static ScrollbarMap* scrollbarMap()
+static ScrollbarSet& scrollbarSet()
 {
-    static ScrollbarMap* map = new ScrollbarMap;
-    return map;
+    DEFINE_STATIC_LOCAL(ScrollbarSet, set, ());
+    return set;
 }
 
 }
@@ -92,12 +92,12 @@
         return;
 
     static_cast<ScrollbarThemeMacCommon*>(ScrollbarTheme::theme())->preferencesChanged();
-    if (scrollbarMap()->isEmpty())
+    if (scrollbarSet().isEmpty())
         return;
-    ScrollbarMap::iterator end = scrollbarMap()->end();
-    for (ScrollbarMap::iterator it = scrollbarMap()->begin(); it != end; ++it) {
-        it->key->styleChanged();
-        it->key->invalidate();
+    ScrollbarSet::iterator end = scrollbarSet().end();
+    for (ScrollbarSet::iterator it = scrollbarSet().begin(); it != end; ++it) {
+        (*it)->styleChanged();
+        (*it)->invalidate();
     }
 }
 
@@ -140,12 +140,12 @@
 
 void ScrollbarThemeMacCommon::registerScrollbar(ScrollbarThemeClient* scrollbar)
 {
-    scrollbarMap()->add(scrollbar, scrollbar);
+    scrollbarSet().add(scrollbar);
 }
 
 void ScrollbarThemeMacCommon::unregisterScrollbar(ScrollbarThemeClient* scrollbar)
 {
-    scrollbarMap()->remove(scrollbar);
+    scrollbarSet().remove(scrollbar);
 }
 
 void ScrollbarThemeMacCommon::paintGivenTickmarks(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect, const Vector<IntRect>& tickmarks)
diff --git a/Source/core/platform/ScrollbarThemeOverlay.cpp b/Source/core/platform/ScrollbarThemeOverlay.cpp
index d6c4631..97151de 100644
--- a/Source/core/platform/ScrollbarThemeOverlay.cpp
+++ b/Source/core/platform/ScrollbarThemeOverlay.cpp
@@ -37,10 +37,12 @@
 
 namespace WebCore {
 
-ScrollbarThemeOverlay::ScrollbarThemeOverlay(int thumbThickness, int scrollbarMargin)
+ScrollbarThemeOverlay::ScrollbarThemeOverlay(int thumbThickness, int scrollbarMargin, HitTestBehavior allowHitTest, Color color)
     : ScrollbarTheme()
     , m_thumbThickness(thumbThickness)
     , m_scrollbarMargin(scrollbarMargin)
+    , m_allowHitTest(allowHitTest)
+    , m_color(color)
 {
 }
 
@@ -71,7 +73,7 @@
     if (!scrollbar->totalSize())
         return trackLen;
 
-    float proportion = (float)scrollbar->visibleSize() / scrollbar->totalSize();
+    float proportion = static_cast<float>(scrollbar->visibleSize()) / scrollbar->totalSize();
     int length = round(proportion * trackLen);
     length = min(max(length, minimumThumbLength(scrollbar)), trackLen);
     return length;
@@ -105,11 +107,22 @@
 void ScrollbarThemeOverlay::paintThumb(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
 {
     IntRect thumbRect = rect;
-    if (scrollbar->orientation() == HorizontalScrollbar)
+    if (scrollbar->orientation() == HorizontalScrollbar) {
         thumbRect.setHeight(thumbRect.height() - m_scrollbarMargin);
-    else
+    } else {
         thumbRect.setWidth(thumbRect.width() - m_scrollbarMargin);
-    context->fillRect(thumbRect, Color(128, 128, 128, 128));
+        if (scrollbar->isLeftSideVerticalScrollbar())
+            thumbRect.setX(thumbRect.x() + m_scrollbarMargin);
+    }
+    context->fillRect(thumbRect, m_color);
+}
+
+ScrollbarPart ScrollbarThemeOverlay::hitTest(ScrollbarThemeClient* scrollbar, const IntPoint& position)
+{
+    if (m_allowHitTest == DisallowHitTest)
+        return NoPart;
+
+    return ScrollbarTheme::hitTest(scrollbar, position);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/ScrollbarThemeOverlay.h b/Source/core/platform/ScrollbarThemeOverlay.h
index 62e4f01..14d6d31 100644
--- a/Source/core/platform/ScrollbarThemeOverlay.h
+++ b/Source/core/platform/ScrollbarThemeOverlay.h
@@ -34,7 +34,9 @@
 // than Mac. Mac's overlay scrollbars are in ScrollbarThemeMac*.
 class ScrollbarThemeOverlay : public ScrollbarTheme {
 public:
-    ScrollbarThemeOverlay(int thumbThickness, int scrollbarMargin);
+    enum HitTestBehavior { AllowHitTest, DisallowHitTest };
+
+    ScrollbarThemeOverlay(int thumbThickness, int scrollbarMargin, HitTestBehavior, Color = Color(128, 128, 128, 128));
     virtual ~ScrollbarThemeOverlay() { }
 
     virtual int scrollbarThickness(ScrollbarControlSize) OVERRIDE;
@@ -51,10 +53,13 @@
     virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
 
     virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
+    virtual ScrollbarPart hitTest(ScrollbarThemeClient*, const IntPoint&) OVERRIDE;
 
 private:
     int m_thumbThickness;
     int m_scrollbarMargin;
+    HitTestBehavior m_allowHitTest;
+    Color m_color;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/SecureTextInput.cpp b/Source/core/platform/SecureTextInput.cpp
index 9fc732c..78d3b81 100644
--- a/Source/core/platform/SecureTextInput.cpp
+++ b/Source/core/platform/SecureTextInput.cpp
@@ -26,7 +26,7 @@
 #include "config.h"
 
 // FIXME: This should be moved to WebKit, because browser process needs to track secure input state anyway to manipulate input contexts.
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include "core/platform/SecureTextInput.h"
 
 #import <Carbon/Carbon.h>
@@ -49,4 +49,4 @@
 
 } // namespace WebCore
 
-#endif // OS(DARWIN)
+#endif // OS(MACOSX)
diff --git a/Source/core/platform/SecureTextInput.h b/Source/core/platform/SecureTextInput.h
index 1753efd..146e62c 100644
--- a/Source/core/platform/SecureTextInput.h
+++ b/Source/core/platform/SecureTextInput.h
@@ -38,7 +38,7 @@
 void enableSecureTextInput();
 void disableSecureTextInput();
 
-#if !OS(DARWIN)
+#if !OS(MACOSX)
 inline void enableSecureTextInput() { }
 inline void disableSecureTextInput() { }
 #endif
diff --git a/Source/core/platform/animation/AnimationValue.h b/Source/core/platform/animation/AnimationValue.h
new file mode 100644
index 0000000..c6298dc
--- /dev/null
+++ b/Source/core/platform/animation/AnimationValue.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. 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 AnimationValue_h
+#define AnimationValue_h
+
+#include "core/platform/animation/TimingFunction.h"
+#include "core/platform/graphics/filters/FilterOperations.h"
+#include "core/platform/graphics/transforms/TransformOperations.h"
+
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+// Base class for animation values (also used for transitions). Here to
+// represent values for properties being animated via the GraphicsLayer,
+// without pulling in style-related data from outside of the platform directory.
+class AnimationValue {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    explicit AnimationValue(double keyTime, PassRefPtr<TimingFunction> timingFunction = 0)
+        : m_keyTime(keyTime)
+        , m_timingFunction(timingFunction)
+    {
+    }
+
+    virtual ~AnimationValue() { }
+
+    double keyTime() const { return m_keyTime; }
+    const TimingFunction* timingFunction() const { return m_timingFunction.get(); }
+    virtual PassOwnPtr<AnimationValue> clone() const = 0;
+
+private:
+    double m_keyTime;
+    RefPtr<TimingFunction> m_timingFunction;
+};
+
+// Used to store one float value of an animation.
+class FloatAnimationValue : public AnimationValue {
+public:
+    FloatAnimationValue(double keyTime, float value, PassRefPtr<TimingFunction> timingFunction = 0)
+        : AnimationValue(keyTime, timingFunction)
+        , m_value(value)
+    {
+    }
+    virtual PassOwnPtr<AnimationValue> clone() const OVERRIDE { return adoptPtr(new FloatAnimationValue(*this)); }
+
+    float value() const { return m_value; }
+
+private:
+    float m_value;
+};
+
+// Used to store one transform value in a keyframe list.
+class TransformAnimationValue : public AnimationValue {
+public:
+    explicit TransformAnimationValue(double keyTime, const TransformOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
+        : AnimationValue(keyTime, timingFunction)
+    {
+        if (value)
+            m_value = *value;
+    }
+    virtual PassOwnPtr<AnimationValue> clone() const OVERRIDE { return adoptPtr(new TransformAnimationValue(*this)); }
+
+    const TransformOperations* value() const { return &m_value; }
+
+private:
+    TransformOperations m_value;
+};
+
+// Used to store one filter value in a keyframe list.
+class FilterAnimationValue : public AnimationValue {
+public:
+    explicit FilterAnimationValue(double keyTime, const FilterOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
+        : AnimationValue(keyTime, timingFunction)
+    {
+        if (value)
+            m_value = *value;
+    }
+    virtual PassOwnPtr<AnimationValue> clone() const OVERRIDE { return adoptPtr(new FilterAnimationValue(*this)); }
+
+    const FilterOperations* value() const { return &m_value; }
+
+private:
+    FilterOperations m_value;
+};
+
+} // namespace WebCore
+
+#endif // AnimationValue_h
diff --git a/Source/core/platform/animation/CSSAnimationData.h b/Source/core/platform/animation/CSSAnimationData.h
index a8ab459..49c4beb 100644
--- a/Source/core/platform/animation/CSSAnimationData.h
+++ b/Source/core/platform/animation/CSSAnimationData.h
@@ -118,7 +118,7 @@
     const String& name() const { return m_name; }
     EAnimPlayState playState() const { return static_cast<EAnimPlayState>(m_playState); }
     CSSPropertyID property() const { return m_property; }
-    const PassRefPtr<TimingFunction> timingFunction() const { return m_timingFunction; }
+    TimingFunction* timingFunction() const { return m_timingFunction.get(); }
     AnimationMode animationMode() const { return m_mode; }
 
     void setDelay(double c) { m_delay = c; m_delaySet = true; }
@@ -136,9 +136,6 @@
 
     CSSAnimationData& operator=(const CSSAnimationData& o);
 
-    // return true if all members of this class match (excluding m_next)
-    bool animationsMatch(const CSSAnimationData*, bool matchPlayStates = true) const;
-
     // return true every CSSAnimationData in the chain (defined by m_next) match
     bool operator==(const CSSAnimationData& o) const { return animationsMatch(&o); }
     bool operator!=(const CSSAnimationData& o) const { return !(*this == o); }
@@ -150,6 +147,9 @@
     CSSAnimationData();
     explicit CSSAnimationData(const CSSAnimationData&);
 
+    // return true if all members of this class match (excluding m_next)
+    bool animationsMatch(const CSSAnimationData*, bool matchPlayStates = true) const;
+
     AtomicString m_name;
     CSSPropertyID m_property;
     AnimationMode m_mode;
diff --git a/Source/core/platform/animation/KeyframeValueList.cpp b/Source/core/platform/animation/KeyframeValueList.cpp
new file mode 100644
index 0000000..174172c
--- /dev/null
+++ b/Source/core/platform/animation/KeyframeValueList.cpp
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. 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.
+ */
+
+#include "config.h"
+
+#include "core/platform/animation/KeyframeValueList.h"
+
+namespace WebCore {
+
+void KeyframeValueList::insert(PassOwnPtr<const AnimationValue> value)
+{
+    for (size_t i = 0; i < m_values.size(); ++i) {
+        const AnimationValue* curValue = m_values[i].get();
+        if (curValue->keyTime() == value->keyTime()) {
+            ASSERT_NOT_REACHED();
+            // insert after
+            m_values.insert(i + 1, value);
+            return;
+        }
+        if (curValue->keyTime() > value->keyTime()) {
+            // insert before
+            m_values.insert(i, value);
+            return;
+        }
+    }
+
+    m_values.append(value);
+}
+
+} // namespace WebCore
diff --git a/Source/core/platform/animation/KeyframeValueList.h b/Source/core/platform/animation/KeyframeValueList.h
new file mode 100644
index 0000000..86ffb00
--- /dev/null
+++ b/Source/core/platform/animation/KeyframeValueList.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. 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 KeyframeValueList_h
+#define KeyframeValueList_h
+
+#include "core/platform/animation/AnimationValue.h"
+
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+enum AnimatedPropertyID {
+    AnimatedPropertyInvalid,
+    AnimatedPropertyWebkitTransform,
+    AnimatedPropertyOpacity,
+    AnimatedPropertyBackgroundColor,
+    AnimatedPropertyWebkitFilter
+};
+
+// Used to store a series of values in a keyframe list.
+// Values will all be of the same type, which can be inferred from the property.
+class KeyframeValueList {
+public:
+    explicit KeyframeValueList(AnimatedPropertyID property)
+        : m_property(property)
+    {
+    }
+
+    KeyframeValueList(const KeyframeValueList& other)
+        : m_property(other.property())
+    {
+        for (size_t i = 0; i < other.m_values.size(); ++i)
+            m_values.append(other.m_values[i]->clone());
+    }
+
+    KeyframeValueList& operator=(const KeyframeValueList& other)
+    {
+        KeyframeValueList copy(other);
+        swap(copy);
+        return *this;
+    }
+
+    void swap(KeyframeValueList& other)
+    {
+        std::swap(m_property, other.m_property);
+        m_values.swap(other.m_values);
+    }
+
+    AnimatedPropertyID property() const { return m_property; }
+
+    size_t size() const { return m_values.size(); }
+    const AnimationValue* at(size_t i) const { return m_values.at(i).get(); }
+
+    // Insert, sorted by keyTime.
+    void insert(PassOwnPtr<const AnimationValue>);
+
+protected:
+    Vector<OwnPtr<const AnimationValue> > m_values;
+    AnimatedPropertyID m_property;
+};
+
+} // namespace WebCore
+
+#endif // KeyframeValueList_h
diff --git a/Source/core/platform/animation/TimingFunction.h b/Source/core/platform/animation/TimingFunction.h
index 6a61d8e..c4bb368 100644
--- a/Source/core/platform/animation/TimingFunction.h
+++ b/Source/core/platform/animation/TimingFunction.h
@@ -25,7 +25,10 @@
 #ifndef TimingFunction_h
 #define TimingFunction_h
 
+#include "RuntimeEnabledFeatures.h"
 #include "core/platform/graphics/UnitBezier.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include <algorithm>
@@ -35,17 +38,13 @@
 class TimingFunction : public RefCounted<TimingFunction> {
 public:
 
-    enum TimingFunctionType {
+    enum Type {
         LinearFunction, CubicBezierFunction, StepsFunction
     };
 
     virtual ~TimingFunction() { }
 
-    TimingFunctionType type() const { return m_type; }
-
-    bool isLinearTimingFunction() const { return m_type == LinearFunction; }
-    bool isCubicBezierTimingFunction() const { return m_type == CubicBezierFunction; }
-    bool isStepsTimingFunction() const { return m_type == StepsFunction; }
+    Type type() const { return m_type; }
 
     // Evaluates the timing function at the given fraction. The accuracy parameter provides a hint as to the required
     // accuracy and is not guaranteed.
@@ -53,12 +52,13 @@
     virtual bool operator==(const TimingFunction& other) const = 0;
 
 protected:
-    TimingFunction(TimingFunctionType type)
+    TimingFunction(Type type)
         : m_type(type)
     {
     }
 
-    TimingFunctionType m_type;
+private:
+    Type m_type;
 };
 
 class LinearTimingFunction : public TimingFunction {
@@ -72,12 +72,14 @@
 
     virtual double evaluate(double fraction, double) const
     {
+        ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1));
+        RELEASE_ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
         return fraction;
     }
 
     virtual bool operator==(const TimingFunction& other) const
     {
-        return other.isLinearTimingFunction();
+        return other.type() == LinearFunction;
     }
 
 private:
@@ -89,7 +91,7 @@
 
 class CubicBezierTimingFunction : public TimingFunction {
 public:
-    enum TimingFunctionPreset {
+    enum SubType {
         Ease,
         EaseIn,
         EaseOut,
@@ -102,9 +104,9 @@
         return adoptRef(new CubicBezierTimingFunction(Custom, x1, y1, x2, y2));
     }
 
-    static CubicBezierTimingFunction* preset(TimingFunctionPreset type)
+    static CubicBezierTimingFunction* preset(SubType subType)
     {
-        switch (type) {
+        switch (subType) {
         case Ease:
             {
                 static CubicBezierTimingFunction* ease = adoptRef(new CubicBezierTimingFunction(Ease, 0.25, 0.1, 0.25, 1.0)).leakRef();
@@ -135,15 +137,19 @@
 
     virtual double evaluate(double fraction, double accuracy) const
     {
-        return UnitBezier(m_x1, m_y1, m_x2, m_y2).solve(fraction, accuracy);
+        ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1));
+        RELEASE_ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+        if (!m_bezier)
+            m_bezier = adoptPtr(new UnitBezier(m_x1, m_y1, m_x2, m_y2));
+        return m_bezier->solve(fraction, accuracy);
     }
 
     virtual bool operator==(const TimingFunction& other) const
     {
-        if (other.isCubicBezierTimingFunction()) {
+        if (other.type() == CubicBezierFunction) {
             const CubicBezierTimingFunction* ctf = static_cast<const CubicBezierTimingFunction*>(&other);
-            if (m_timingFunctionPreset != Custom)
-                return m_timingFunctionPreset == ctf->m_timingFunctionPreset;
+            if (m_subType != Custom)
+                return m_subType == ctf->m_subType;
 
             return m_x1 == ctf->m_x1 && m_y1 == ctf->m_y1 && m_x2 == ctf->m_x2 && m_y2 == ctf->m_y2;
         }
@@ -155,16 +161,16 @@
     double x2() const { return m_x2; }
     double y2() const { return m_y2; }
 
-    TimingFunctionPreset timingFunctionPreset() const { return m_timingFunctionPreset; }
+    SubType subType() const { return m_subType; }
 
 private:
-    explicit CubicBezierTimingFunction(TimingFunctionPreset preset, double x1, double y1, double x2, double y2)
+    explicit CubicBezierTimingFunction(SubType subType, double x1, double y1, double x2, double y2)
         : TimingFunction(CubicBezierFunction)
         , m_x1(x1)
         , m_y1(y1)
         , m_x2(x2)
         , m_y2(y2)
-        , m_timingFunctionPreset(preset)
+        , m_subType(subType)
     {
     }
 
@@ -172,27 +178,58 @@
     double m_y1;
     double m_x2;
     double m_y2;
-    TimingFunctionPreset m_timingFunctionPreset;
+    SubType m_subType;
+    mutable OwnPtr<UnitBezier> m_bezier;
 };
 
 class StepsTimingFunction : public TimingFunction {
 public:
+    enum SubType {
+        Start,
+        End,
+        Custom
+    };
+
     static PassRefPtr<StepsTimingFunction> create(int steps, bool stepAtStart)
     {
-        return adoptRef(new StepsTimingFunction(steps, stepAtStart));
+        return adoptRef(new StepsTimingFunction(Custom, steps, stepAtStart));
     }
 
+    static StepsTimingFunction* preset(SubType subType)
+    {
+        switch (subType) {
+        case Start:
+            {
+                static StepsTimingFunction* start = adoptRef(new StepsTimingFunction(Start, 1, true)).leakRef();
+                return start;
+            }
+        case End:
+            {
+                static StepsTimingFunction* end = adoptRef(new StepsTimingFunction(End, 1, false)).leakRef();
+                return end;
+            }
+        default:
+            ASSERT_NOT_REACHED();
+            return 0;
+        }
+    }
+
+
     ~StepsTimingFunction() { }
 
     virtual double evaluate(double fraction, double) const
     {
+        ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1));
+        RELEASE_ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
         return std::min(1.0, (floor(m_steps * fraction) + m_stepAtStart) / m_steps);
     }
 
     virtual bool operator==(const TimingFunction& other) const
     {
-        if (other.isStepsTimingFunction()) {
+        if (other.type() == StepsFunction) {
             const StepsTimingFunction* stf = static_cast<const StepsTimingFunction*>(&other);
+            if (m_subType != Custom)
+                return m_subType == stf->m_subType;
             return m_steps == stf->m_steps && m_stepAtStart == stf->m_stepAtStart;
         }
         return false;
@@ -201,16 +238,20 @@
     int numberOfSteps() const { return m_steps; }
     bool stepAtStart() const { return m_stepAtStart; }
 
+    SubType subType() const { return m_subType; }
+
 private:
-    StepsTimingFunction(int steps, bool stepAtStart)
+    StepsTimingFunction(SubType subType, int steps, bool stepAtStart)
         : TimingFunction(StepsFunction)
         , m_steps(steps)
         , m_stepAtStart(stepAtStart)
+        , m_subType(subType)
     {
     }
 
     int m_steps;
     bool m_stepAtStart;
+    SubType m_subType;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/audio/AudioDSPKernelProcessor.cpp b/Source/core/platform/audio/AudioDSPKernelProcessor.cpp
index 0875464..d284b1c 100644
--- a/Source/core/platform/audio/AudioDSPKernelProcessor.cpp
+++ b/Source/core/platform/audio/AudioDSPKernelProcessor.cpp
@@ -35,6 +35,7 @@
 #include "core/platform/audio/AudioDSPKernelProcessor.h"
 
 #include "core/platform/audio/AudioDSPKernel.h"
+#include "wtf/MainThread.h"
 
 namespace WebCore {
 
@@ -50,6 +51,7 @@
     if (isInitialized())
         return;
 
+    MutexLocker locker(m_processLock);
     ASSERT(!m_kernels.size());
 
     // Create processing kernels, one per channel.
@@ -65,6 +67,7 @@
     if (!isInitialized())
         return;
 
+    MutexLocker locker(m_processLock);
     m_kernels.clear();
 
     m_initialized = false;
@@ -81,18 +84,26 @@
         return;
     }
 
-    bool channelCountMatches = source->numberOfChannels() == destination->numberOfChannels() && source->numberOfChannels() == m_kernels.size();
-    ASSERT(channelCountMatches);
-    if (!channelCountMatches)
-        return;
+    MutexTryLocker tryLocker(m_processLock);
+    if (tryLocker.locked()) {
+        bool channelCountMatches = source->numberOfChannels() == destination->numberOfChannels() && source->numberOfChannels() == m_kernels.size();
+        ASSERT(channelCountMatches);
+        if (!channelCountMatches)
+            return;
 
-    for (unsigned i = 0; i < m_kernels.size(); ++i)
-        m_kernels[i]->process(source->channel(i)->data(), destination->channel(i)->mutableData(), framesToProcess);
+        for (unsigned i = 0; i < m_kernels.size(); ++i)
+            m_kernels[i]->process(source->channel(i)->data(), destination->channel(i)->mutableData(), framesToProcess);
+    } else {
+        // Unfortunately, the kernel is being processed by another thread.
+        // See also ConvolverNode::process().
+        destination->zero();
+    }
 }
 
 // Resets filter state
 void AudioDSPKernelProcessor::reset()
 {
+    ASSERT(isMainThread());
     if (!isInitialized())
         return;
 
@@ -100,6 +111,7 @@
     // Any processing depending on this value must set it to false at the appropriate time.
     m_hasJustReset = true;
 
+    MutexLocker locker(m_processLock);
     for (unsigned i = 0; i < m_kernels.size(); ++i)
         m_kernels[i]->reset();
 }
@@ -116,14 +128,28 @@
 
 double AudioDSPKernelProcessor::tailTime() const
 {
-    // It is expected that all the kernels have the same tailTime.
-    return !m_kernels.isEmpty() ? m_kernels.first()->tailTime() : 0;
+    ASSERT(!isMainThread());
+    MutexTryLocker tryLocker(m_processLock);
+    if (tryLocker.locked()) {
+        // It is expected that all the kernels have the same tailTime.
+        return !m_kernels.isEmpty() ? m_kernels.first()->tailTime() : 0;
+    }
+    // Since we don't want to block the Audio Device thread, we return a large value
+    // instead of trying to acquire the lock.
+    return std::numeric_limits<double>::infinity();
 }
 
 double AudioDSPKernelProcessor::latencyTime() const
 {
-    // It is expected that all the kernels have the same latencyTime.
-    return !m_kernels.isEmpty() ? m_kernels.first()->latencyTime() : 0;
+    ASSERT(!isMainThread());
+    MutexTryLocker tryLocker(m_processLock);
+    if (tryLocker.locked()) {
+        // It is expected that all the kernels have the same latencyTime.
+        return !m_kernels.isEmpty() ? m_kernels.first()->latencyTime() : 0;
+    }
+    // Since we don't want to block the Audio Device thread, we return a large value
+    // instead of trying to acquire the lock.
+    return std::numeric_limits<double>::infinity();
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/audio/AudioDSPKernelProcessor.h b/Source/core/platform/audio/AudioDSPKernelProcessor.h
index 5c03835..41c168a 100644
--- a/Source/core/platform/audio/AudioDSPKernelProcessor.h
+++ b/Source/core/platform/audio/AudioDSPKernelProcessor.h
@@ -35,6 +35,7 @@
 #include "core/platform/audio/AudioProcessor.h"
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
+#include "wtf/ThreadingPrimitives.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
@@ -69,6 +70,7 @@
 
 protected:
     Vector<OwnPtr<AudioDSPKernel> > m_kernels;
+    mutable Mutex m_processLock;
     bool m_hasJustReset;
 };
 
diff --git a/Source/core/platform/audio/AudioUtilities.cpp b/Source/core/platform/audio/AudioUtilities.cpp
index 758bd8f..a76753e 100644
--- a/Source/core/platform/audio/AudioUtilities.cpp
+++ b/Source/core/platform/audio/AudioUtilities.cpp
@@ -27,6 +27,7 @@
 #if ENABLE(WEB_AUDIO)
 
 #include "core/platform/audio/AudioUtilities.h"
+#include "wtf/Assertions.h"
 #include "wtf/MathExtras.h"
 
 namespace WebCore {
diff --git a/Source/core/platform/audio/Biquad.cpp b/Source/core/platform/audio/Biquad.cpp
index a9f9760..20c6487 100644
--- a/Source/core/platform/audio/Biquad.cpp
+++ b/Source/core/platform/audio/Biquad.cpp
@@ -37,7 +37,7 @@
 #include "core/platform/audio/DenormalDisabler.h"
 #include "wtf/MathExtras.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include <Accelerate/Accelerate.h>
 #endif
 
@@ -47,7 +47,7 @@
 
 Biquad::Biquad()
 {
-#if OS(DARWIN)
+#if OS(MACOSX)
     // Allocate two samples more for filter history
     m_inputBuffer.allocate(kBufferSize + 2);
     m_outputBuffer.allocate(kBufferSize + 2);
@@ -74,7 +74,7 @@
 
 void Biquad::process(const float* sourceP, float* destP, size_t framesToProcess)
 {
-#if OS(DARWIN)
+#if OS(MACOSX)
     // Use vecLib if available
     processFast(sourceP, destP, framesToProcess);
 
@@ -125,7 +125,7 @@
 #endif
 }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 
 // Here we have optimized version using Accelerate.framework
 
@@ -179,12 +179,12 @@
     destP[1] = destP[framesToProcess - 1 + 2];
 }
 
-#endif // OS(DARWIN)
+#endif // OS(MACOSX)
 
 
 void Biquad::reset()
 {
-#if OS(DARWIN)
+#if OS(MACOSX)
     // Two extra samples for filter history
     double* inputP = m_inputBuffer.data();
     inputP[0] = 0;
diff --git a/Source/core/platform/audio/Biquad.h b/Source/core/platform/audio/Biquad.h
index ac3e0af..ae0baf9 100644
--- a/Source/core/platform/audio/Biquad.h
+++ b/Source/core/platform/audio/Biquad.h
@@ -92,7 +92,7 @@
     double m_a1;
     double m_a2;
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     void processFast(const float* sourceP, float* destP, size_t framesToProcess);
     void processSliceFast(double* sourceP, double* destP, double* coefficientsP, size_t framesToProcess);
 
diff --git a/Source/core/platform/audio/DenormalDisabler.h b/Source/core/platform/audio/DenormalDisabler.h
index 942e302..802cb73 100644
--- a/Source/core/platform/audio/DenormalDisabler.h
+++ b/Source/core/platform/audio/DenormalDisabler.h
@@ -25,28 +25,30 @@
 #ifndef DenormalDisabler_h
 #define DenormalDisabler_h
 
+#include "wtf/CPU.h"
 #include "wtf/MathExtras.h"
+#include <float.h>
 
 namespace WebCore {
 
 // Deal with denormals. They can very seriously impact performance on x86.
 
 // Define HAVE_DENORMAL if we support flushing denormals to zero.
-#if OS(WINDOWS) && COMPILER(MSVC)
-#define HAVE_DENORMAL
+#if OS(WIN) && COMPILER(MSVC)
+#define HAVE_DENORMAL 1
 #endif
 
-#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
-#define HAVE_DENORMAL
+#if COMPILER(GCC) && (CPU(X86) || CPU(X86_64))
+#define HAVE_DENORMAL 1
 #endif
 
-#ifdef HAVE_DENORMAL
+#if HAVE(DENORMAL)
 class DenormalDisabler {
 public:
     DenormalDisabler()
             : m_savedCSR(0)
     {
-#if OS(WINDOWS) && COMPILER(MSVC)
+#if OS(WIN) && COMPILER(MSVC)
         // Save the current state, and set mode to flush denormals.
         //
         // http://stackoverflow.com/questions/637175/possible-bug-in-controlfp-s-may-not-restore-control-word-correctly
@@ -61,7 +63,7 @@
 
     ~DenormalDisabler()
     {
-#if OS(WINDOWS) && COMPILER(MSVC)
+#if OS(WIN) && COMPILER(MSVC)
         unsigned int unused;
         _controlfp_s(&unused, m_savedCSR, _MCW_DN);
 #else
@@ -72,7 +74,7 @@
     // This is a nop if we can flush denormals to zero in hardware.
     static inline float flushDenormalFloatToZero(float f)
     {
-#if OS(WINDOWS) && COMPILER(MSVC) && (!_M_IX86_FP)
+#if OS(WIN) && COMPILER(MSVC) && (!_M_IX86_FP)
         // For systems using x87 instead of sse, there's no hardware support
         // to flush denormals automatically. Hence, we need to flush
         // denormals to zero manually.
@@ -82,7 +84,7 @@
 #endif
     }
 private:
-#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
+#if COMPILER(GCC) && (CPU(X86) || CPU(X86_64))
     inline int getCSR()
     {
         int result;
diff --git a/Source/core/platform/audio/DirectConvolver.cpp b/Source/core/platform/audio/DirectConvolver.cpp
index 5594dfb..d74fea4 100644
--- a/Source/core/platform/audio/DirectConvolver.cpp
+++ b/Source/core/platform/audio/DirectConvolver.cpp
@@ -32,11 +32,12 @@
 
 #include "core/platform/audio/DirectConvolver.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include <Accelerate/Accelerate.h>
 #endif
 
 #include "core/platform/audio/VectorMath.h"
+#include "wtf/CPU.h"
 
 namespace WebCore {
 
@@ -89,12 +90,12 @@
     // Copy samples to 2nd half of input buffer.
     memcpy(inputP, sourceP, sizeof(float) * framesToProcess);
 
-#if OS(DARWIN)
-#if defined(__ppc__) || defined(__i386__)
+#if OS(MACOSX)
+#if CPU(X86)
     conv(inputP - kernelSize + 1, 1, kernelP + kernelSize - 1, -1, destP, 1, framesToProcess, kernelSize);
 #else
     vDSP_conv(inputP - kernelSize + 1, 1, kernelP + kernelSize - 1, -1, destP, 1, framesToProcess, kernelSize);
-#endif // defined(__ppc__) || defined(__i386__)
+#endif // CPU(X86)
 #else
     // FIXME: The macro can be further optimized to avoid pipeline stalls. One possibility is to maintain 4 separate sums and change the macro to CONVOLVE_FOUR_SAMPLES.
 #define CONVOLVE_ONE_SAMPLE             \
@@ -365,7 +366,7 @@
         }
         destP[i++] = sum;
     }
-#endif // OS(DARWIN)
+#endif // OS(MACOSX)
 
     // Copy 2nd half of input buffer to 1st half.
     memcpy(m_buffer.data(), inputP, sizeof(float) * framesToProcess);
diff --git a/Source/core/platform/audio/FFTFrame.h b/Source/core/platform/audio/FFTFrame.h
index 8e473f8..38f9016 100644
--- a/Source/core/platform/audio/FFTFrame.h
+++ b/Source/core/platform/audio/FFTFrame.h
@@ -31,7 +31,7 @@
 
 #include "core/platform/audio/AudioArray.h"
 
-#if OS(DARWIN) && !USE(WEBAUDIO_FFMPEG)
+#if OS(MACOSX) && !USE(WEBAUDIO_FFMPEG)
 #define USE_ACCELERATE_FFT 1
 #else
 #define USE_ACCELERATE_FFT 0
diff --git a/Source/core/platform/audio/FFTFrameStub.cpp b/Source/core/platform/audio/FFTFrameStub.cpp
index ee98949..6a0f887 100644
--- a/Source/core/platform/audio/FFTFrameStub.cpp
+++ b/Source/core/platform/audio/FFTFrameStub.cpp
@@ -29,7 +29,7 @@
 
 #if ENABLE(WEB_AUDIO)
 
-#if !OS(DARWIN) && !USE(WEBAUDIO_FFMPEG) && !USE(WEBAUDIO_IPP) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
+#if !OS(MACOSX) && !USE(WEBAUDIO_FFMPEG) && !USE(WEBAUDIO_IPP) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
 
 #include "core/platform/audio/FFTFrame.h"
 
@@ -102,6 +102,6 @@
 
 } // namespace WebCore
 
-#endif // !OS(DARWIN) && !USE(WEBAUDIO_FFMPEG) && !USE(WEBAUDIO_IPP) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
+#endif // !OS(MACOSX) && !USE(WEBAUDIO_FFMPEG) && !USE(WEBAUDIO_IPP) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
 
 #endif // ENABLE(WEB_AUDIO)
diff --git a/Source/core/platform/audio/HRTFElevation.cpp b/Source/core/platform/audio/HRTFElevation.cpp
index a37e696..a5c606c 100644
--- a/Source/core/platform/audio/HRTFElevation.cpp
+++ b/Source/core/platform/audio/HRTFElevation.cpp
@@ -37,6 +37,7 @@
 #include "core/platform/audio/AudioBus.h"
 #include "core/platform/audio/HRTFPanner.h"
 #include "wtf/OwnPtr.h"
+#include "wtf/ThreadingPrimitives.h"
 
 using namespace std;
 
@@ -64,7 +65,9 @@
 {
     typedef HashMap<String, RefPtr<AudioBus> > AudioBusMap;
     DEFINE_STATIC_LOCAL(AudioBusMap, audioBusMap, ());
+    DEFINE_STATIC_LOCAL(Mutex, mutex, ());
 
+    MutexLocker locker(mutex);
     RefPtr<AudioBus> bus;
     AudioBusMap::iterator iterator = audioBusMap.find(subjectName);
     if (iterator == audioBusMap.end()) {
diff --git a/Source/core/platform/audio/Reverb.cpp b/Source/core/platform/audio/Reverb.cpp
index 4886184..9ca5c90 100644
--- a/Source/core/platform/audio/Reverb.cpp
+++ b/Source/core/platform/audio/Reverb.cpp
@@ -40,7 +40,7 @@
 #include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 using namespace std;
 #endif
 
diff --git a/Source/core/platform/audio/ReverbConvolverStage.cpp b/Source/core/platform/audio/ReverbConvolverStage.cpp
index e4c9954..51fe898 100644
--- a/Source/core/platform/audio/ReverbConvolverStage.cpp
+++ b/Source/core/platform/audio/ReverbConvolverStage.cpp
@@ -58,8 +58,11 @@
         m_fftKernel->doPaddedFFT(impulseResponse + stageOffset, stageLength);
         m_fftConvolver = adoptPtr(new FFTConvolver(fftSize));
     } else {
+        ASSERT(!stageOffset);
+        ASSERT(stageLength <= fftSize / 2);
+
         m_directKernel = adoptPtr(new AudioFloatArray(fftSize / 2));
-        m_directKernel->copyToRange(impulseResponse + stageOffset, 0, fftSize / 2);
+        m_directKernel->copyToRange(impulseResponse, 0, stageLength);
         m_directConvolver = adoptPtr(new DirectConvolver(renderSliceSize));
     }
     m_temporaryBuffer.allocate(renderSliceSize);
diff --git a/Source/core/platform/audio/VectorMath.cpp b/Source/core/platform/audio/VectorMath.cpp
index 56c33d5..d16f3c8 100644
--- a/Source/core/platform/audio/VectorMath.cpp
+++ b/Source/core/platform/audio/VectorMath.cpp
@@ -28,9 +28,10 @@
 
 #include "core/platform/audio/VectorMath.h"
 #include "wtf/Assertions.h"
+#include "wtf/CPU.h"
 #include <stdint.h>
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include <Accelerate/Accelerate.h>
 #endif
 
@@ -49,14 +50,14 @@
 
 namespace VectorMath {
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 // On the Mac we use the highly optimized versions in Accelerate.framework
 // In 32-bit mode (__ppc__ or __i386__) <Accelerate/Accelerate.h> includes <vecLib/vDSP_translate.h> which defines macros of the same name as
 // our namespaced function names, so we must handle this case differently. Other architectures (64bit, ARM, etc.) do not include this header file.
 
 void vsmul(const float* sourceP, int sourceStride, const float* scale, float* destP, int destStride, size_t framesToProcess)
 {
-#if defined(__ppc__) || defined(__i386__)
+#if CPU(X86)
     ::vsmul(sourceP, sourceStride, scale, destP, destStride, framesToProcess);
 #else
     vDSP_vsmul(sourceP, sourceStride, scale, destP, destStride, framesToProcess);
@@ -65,7 +66,7 @@
 
 void vadd(const float* source1P, int sourceStride1, const float* source2P, int sourceStride2, float* destP, int destStride, size_t framesToProcess)
 {
-#if defined(__ppc__) || defined(__i386__)
+#if CPU(X86)
     ::vadd(source1P, sourceStride1, source2P, sourceStride2, destP, destStride, framesToProcess);
 #else
     vDSP_vadd(source1P, sourceStride1, source2P, sourceStride2, destP, destStride, framesToProcess);
@@ -74,7 +75,7 @@
 
 void vmul(const float* source1P, int sourceStride1, const float* source2P, int sourceStride2, float* destP, int destStride, size_t framesToProcess)
 {
-#if defined(__ppc__) || defined(__i386__)
+#if CPU(X86)
     ::vmul(source1P, sourceStride1, source2P, sourceStride2, destP, destStride, framesToProcess);
 #else
     vDSP_vmul(source1P, sourceStride1, source2P, sourceStride2, destP, destStride, framesToProcess);
@@ -92,7 +93,7 @@
     sc2.imagp = const_cast<float*>(imag2P);
     dest.realp = realDestP;
     dest.imagp = imagDestP;
-#if defined(__ppc__) || defined(__i386__)
+#if CPU(X86)
     ::zvmul(&sc1, 1, &sc2, 1, &dest, 1, framesToProcess, 1);
 #else
     vDSP_zvmul(&sc1, 1, &sc2, 1, &dest, 1, framesToProcess, 1);
@@ -680,7 +681,7 @@
     }
 }
 
-#endif // OS(DARWIN)
+#endif // OS(MACOSX)
 
 } // namespace VectorMath
 
diff --git a/Source/core/platform/audio/ffmpeg/FFTFrameFFMPEG.cpp b/Source/core/platform/audio/ffmpeg/FFTFrameFFMPEG.cpp
index 05af6f4..59f182f 100644
--- a/Source/core/platform/audio/ffmpeg/FFTFrameFFMPEG.cpp
+++ b/Source/core/platform/audio/ffmpeg/FFTFrameFFMPEG.cpp
@@ -248,6 +248,6 @@
 
 } // namespace WebCore
 
-#endif // !OS(DARWIN) && USE(WEBAUDIO_FFMPEG)
+#endif // !OS(MACOSX) && USE(WEBAUDIO_FFMPEG)
 
 #endif // ENABLE(WEB_AUDIO)
diff --git a/Source/core/platform/audio/mac/FFTFrameMac.cpp b/Source/core/platform/audio/mac/FFTFrameMac.cpp
index 802117e..344f953 100644
--- a/Source/core/platform/audio/mac/FFTFrameMac.cpp
+++ b/Source/core/platform/audio/mac/FFTFrameMac.cpp
@@ -32,7 +32,7 @@
 
 #if ENABLE(WEB_AUDIO)
 
-#if OS(DARWIN) && !USE(WEBAUDIO_FFMPEG)
+#if OS(MACOSX) && !USE(WEBAUDIO_FFMPEG)
 
 #include "core/platform/audio/FFTFrame.h"
 
@@ -188,6 +188,6 @@
 
 } // namespace WebCore
 
-#endif // #if OS(DARWIN) && !USE(WEBAUDIO_FFMPEG)
+#endif // #if OS(MACOSX) && !USE(WEBAUDIO_FFMPEG)
 
 #endif // ENABLE(WEB_AUDIO)
diff --git a/Source/core/platform/chromium/ClipboardChromium.cpp b/Source/core/platform/chromium/ClipboardChromium.cpp
index 48b258c..54afa4d 100644
--- a/Source/core/platform/chromium/ClipboardChromium.cpp
+++ b/Source/core/platform/chromium/ClipboardChromium.cpp
@@ -246,8 +246,6 @@
         return;
 
     m_dataObject->clearData(normalizeType(type));
-
-    ASSERT_NOT_REACHED();
 }
 
 void ClipboardChromium::clearAllData()
@@ -442,7 +440,7 @@
     m_dataObject->setHTMLAndBaseURL(createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs), frame->document()->url());
 
     String str = frame->selectedTextForClipboard();
-#if OS(WINDOWS)
+#if OS(WIN)
     replaceNewlinesWithWindowsStyleNewlines(str);
 #endif
     replaceNBSPWithSpace(str);
@@ -455,7 +453,7 @@
         return;
 
     String str = text;
-#if OS(WINDOWS)
+#if OS(WIN)
     replaceNewlinesWithWindowsStyleNewlines(str);
 #endif
     replaceNBSPWithSpace(str);
diff --git a/Source/core/platform/chromium/ClipboardChromiumTest.cpp b/Source/core/platform/chromium/ClipboardChromiumTest.cpp
index 2bc99f4..8bbaf5a 100644
--- a/Source/core/platform/chromium/ClipboardChromiumTest.cpp
+++ b/Source/core/platform/chromium/ClipboardChromiumTest.cpp
@@ -38,7 +38,7 @@
 
 namespace {
 
-#if OS(WINDOWS)
+#if OS(WIN)
 const char invalidCharacters[] = "\x00/\\:*?\"<>|";
 #else
 const char invalidCharacters[] =
diff --git a/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp b/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp
index cec9ed9..6d86b7e 100644
--- a/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp
+++ b/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp
@@ -46,7 +46,7 @@
         WebKit::WebClipboard::BufferStandard;
 }
 
-#if OS(WINDOWS)
+#if OS(WIN)
 void replaceNewlinesWithWindowsStyleNewlines(String& str)
 {
     DEFINE_STATIC_LOCAL(String, windowsNewline, ("\r\n"));
diff --git a/Source/core/platform/chromium/ClipboardUtilitiesChromium.h b/Source/core/platform/chromium/ClipboardUtilitiesChromium.h
index 4bd35ae..1a9cb3d 100644
--- a/Source/core/platform/chromium/ClipboardUtilitiesChromium.h
+++ b/Source/core/platform/chromium/ClipboardUtilitiesChromium.h
@@ -39,7 +39,7 @@
 class KURL;
 
 WebKit::WebClipboard::Buffer currentPasteboardBuffer();
-#if OS(WINDOWS)
+#if OS(WIN)
 void replaceNewlinesWithWindowsStyleNewlines(String&);
 #endif
 void replaceNBSPWithSpace(String&);
diff --git a/Source/core/platform/chromium/KeyboardCodes.h b/Source/core/platform/chromium/KeyboardCodes.h
index 594e280..9228fdd 100644
--- a/Source/core/platform/chromium/KeyboardCodes.h
+++ b/Source/core/platform/chromium/KeyboardCodes.h
@@ -31,7 +31,7 @@
 #ifndef KeyboardCodes_h
 #define KeyboardCodes_h
 
-#if OS(WINDOWS)
+#if OS(WIN)
 #include <windows.h>
 #endif
 
diff --git a/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp b/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp
index e37f84e..228686b 100644
--- a/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp
+++ b/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp
@@ -27,9 +27,9 @@
 #include "config.h"
 #include "core/platform/PlatformKeyboardEvent.h"
 
-#if OS(WINDOWS)
+#if OS(WIN)
 #include <windows.h>
-#elif OS(DARWIN)
+#elif OS(MACOSX)
 #import <Carbon/Carbon.h>
 #else
 #include "core/platform/NotImplemented.h"
@@ -37,13 +37,13 @@
 
 namespace WebCore {
 
-#if OS(WINDOWS)
+#if OS(WIN)
 static const unsigned short HIGH_BIT_MASK_SHORT = 0x8000;
 #endif
 
 void PlatformKeyboardEvent::disambiguateKeyDownEvent(Type type)
 {
-#if OS(WINDOWS)
+#if OS(WIN)
     // No KeyDown events on Windows to disambiguate.
     ASSERT_NOT_REACHED();
 #else
@@ -58,7 +58,7 @@
     } else {
         m_keyIdentifier = String();
         m_windowsVirtualKeyCode = 0;
-#if OS(DARWIN)
+#if OS(MACOSX)
         if (m_text.length() == 1 && (m_text[0U] >= 0xF700 && m_text[0U] <= 0xF7FF)) {
             // According to NSEvents.h, OpenStep reserves the range 0xF700-0xF8FF for function keys. However, some actual private use characters
             // happen to be in this range, e.g. the Apple logo (Option+Shift+K).
@@ -73,10 +73,10 @@
 
 bool PlatformKeyboardEvent::currentCapsLockState()
 {
-#if OS(WINDOWS)
+#if OS(WIN)
     // FIXME: Does this even work inside the sandbox?
     return GetKeyState(VK_CAPITAL) & 1;
-#elif OS(DARWIN)
+#elif OS(MACOSX)
     return GetCurrentKeyModifiers() & alphaLock;
 #else
     notImplemented();
@@ -86,12 +86,12 @@
 
 void PlatformKeyboardEvent::getCurrentModifierState(bool& shiftKey, bool& ctrlKey, bool& altKey, bool& metaKey)
 {
-#if OS(WINDOWS)
+#if OS(WIN)
     shiftKey = GetKeyState(VK_SHIFT) & HIGH_BIT_MASK_SHORT;
     ctrlKey = GetKeyState(VK_CONTROL) & HIGH_BIT_MASK_SHORT;
     altKey = GetKeyState(VK_MENU) & HIGH_BIT_MASK_SHORT;
     metaKey = false;
-#elif OS(DARWIN)
+#elif OS(MACOSX)
     UInt32 currentModifiers = GetCurrentKeyModifiers();
     shiftKey = currentModifiers & ::shiftKey;
     ctrlKey = currentModifiers & ::controlKey;
diff --git a/Source/core/platform/chromium/support/WebCrypto.cpp b/Source/core/platform/chromium/support/WebCrypto.cpp
index 09b670f..db3a0ff 100644
--- a/Source/core/platform/chromium/support/WebCrypto.cpp
+++ b/Source/core/platform/chromium/support/WebCrypto.cpp
@@ -50,7 +50,7 @@
     reset();
 }
 
-void WebCryptoResult::completeWithBuffer(const void* bytes, size_t bytesSize)
+void WebCryptoResult::completeWithBuffer(const void* bytes, unsigned bytesSize)
 {
     WebArrayBuffer buffer = WebKit::WebArrayBuffer::create(bytesSize, 1);
     RELEASE_ASSERT(!buffer.isNull());
diff --git a/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp b/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
index fe8ff81..464dbae 100644
--- a/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
+++ b/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
@@ -39,26 +39,24 @@
 
 class WebCryptoAlgorithmPrivate : public ThreadSafeRefCounted<WebCryptoAlgorithmPrivate> {
 public:
-    WebCryptoAlgorithmPrivate(WebCryptoAlgorithmId id, const char* name, PassOwnPtr<WebCryptoAlgorithmParams> params)
+    WebCryptoAlgorithmPrivate(WebCryptoAlgorithmId id, PassOwnPtr<WebCryptoAlgorithmParams> params)
         : id(id)
-        , name(name)
         , params(params)
     {
     }
 
     WebCryptoAlgorithmId id;
-    const char* const name;
     OwnPtr<WebCryptoAlgorithmParams> params;
 };
 
-WebCryptoAlgorithm::WebCryptoAlgorithm(WebCryptoAlgorithmId id, const char* name, PassOwnPtr<WebCryptoAlgorithmParams> params)
-    : m_private(adoptRef(new WebCryptoAlgorithmPrivate(id, name, params)))
+WebCryptoAlgorithm::WebCryptoAlgorithm(WebCryptoAlgorithmId id, PassOwnPtr<WebCryptoAlgorithmParams> params)
+    : m_private(adoptRef(new WebCryptoAlgorithmPrivate(id, params)))
 {
 }
 
-WebCryptoAlgorithm WebCryptoAlgorithm::adoptParamsAndCreate(WebCryptoAlgorithmId id, const char* name, WebCryptoAlgorithmParams* params)
+WebCryptoAlgorithm WebCryptoAlgorithm::adoptParamsAndCreate(WebCryptoAlgorithmId id, WebCryptoAlgorithmParams* params)
 {
-    return WebCryptoAlgorithm(id, name, adoptPtr(params));
+    return WebCryptoAlgorithm(id, adoptPtr(params));
 }
 
 WebCryptoAlgorithmId WebCryptoAlgorithm::id() const
@@ -66,11 +64,6 @@
     return m_private->id;
 }
 
-const char* WebCryptoAlgorithm::name() const
-{
-    return m_private->name;
-}
-
 WebCryptoAlgorithmParamsType WebCryptoAlgorithm::paramsType() const
 {
     if (!m_private->params)
@@ -78,42 +71,42 @@
     return m_private->params->type();
 }
 
-WebCryptoAesCbcParams* WebCryptoAlgorithm::aesCbcParams() const
+const WebCryptoAesCbcParams* WebCryptoAlgorithm::aesCbcParams() const
 {
     if (paramsType() == WebCryptoAlgorithmParamsTypeAesCbcParams)
         return static_cast<WebCryptoAesCbcParams*>(m_private->params.get());
     return 0;
 }
 
-WebCryptoAesKeyGenParams* WebCryptoAlgorithm::aesKeyGenParams() const
+const WebCryptoAesKeyGenParams* WebCryptoAlgorithm::aesKeyGenParams() const
 {
     if (paramsType() == WebCryptoAlgorithmParamsTypeAesKeyGenParams)
         return static_cast<WebCryptoAesKeyGenParams*>(m_private->params.get());
     return 0;
 }
 
-WebCryptoHmacParams* WebCryptoAlgorithm::hmacParams() const
+const WebCryptoHmacParams* WebCryptoAlgorithm::hmacParams() const
 {
     if (paramsType() == WebCryptoAlgorithmParamsTypeHmacParams)
         return static_cast<WebCryptoHmacParams*>(m_private->params.get());
     return 0;
 }
 
-WebCryptoHmacKeyParams* WebCryptoAlgorithm::hmacKeyParams() const
+const WebCryptoHmacKeyParams* WebCryptoAlgorithm::hmacKeyParams() const
 {
     if (paramsType() == WebCryptoAlgorithmParamsTypeHmacKeyParams)
         return static_cast<WebCryptoHmacKeyParams*>(m_private->params.get());
     return 0;
 }
 
-WebCryptoRsaSsaParams* WebCryptoAlgorithm::rsaSsaParams() const
+const WebCryptoRsaSsaParams* WebCryptoAlgorithm::rsaSsaParams() const
 {
     if (paramsType() == WebCryptoAlgorithmParamsTypeRsaSsaParams)
         return static_cast<WebCryptoRsaSsaParams*>(m_private->params.get());
     return 0;
 }
 
-WebCryptoRsaKeyGenParams* WebCryptoAlgorithm::rsaKeyGenParams() const
+const WebCryptoRsaKeyGenParams* WebCryptoAlgorithm::rsaKeyGenParams() const
 {
     if (paramsType() == WebCryptoAlgorithmParamsTypeRsaKeyGenParams)
         return static_cast<WebCryptoRsaKeyGenParams*>(m_private->params.get());
diff --git a/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp b/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp
new file mode 100644
index 0000000..a0c7525
--- /dev/null
+++ b/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp
@@ -0,0 +1,151 @@
+/*
+ * 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 "public/platform/WebFileSystemCallbacks.h"
+
+#include "core/platform/AsyncFileSystemCallbacks.h"
+#include "core/platform/FileMetadata.h"
+#include "public/platform/WebFileInfo.h"
+#include "public/platform/WebFileSystem.h"
+#include "public/platform/WebFileSystemEntry.h"
+#include "public/platform/WebFileWriter.h"
+#include "public/platform/WebString.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+using namespace WebCore;
+
+namespace WebKit {
+
+class WebFileSystemCallbacksPrivate : public RefCounted<WebFileSystemCallbacksPrivate> {
+public:
+    static PassRefPtr<WebFileSystemCallbacksPrivate> create(const PassOwnPtr<AsyncFileSystemCallbacks>& callbacks)
+    {
+        return adoptRef(new WebFileSystemCallbacksPrivate(callbacks));
+    }
+
+    AsyncFileSystemCallbacks* callbacks() { return m_callbacks.get(); }
+
+private:
+    WebFileSystemCallbacksPrivate(const PassOwnPtr<AsyncFileSystemCallbacks>& callbacks) : m_callbacks(callbacks) { }
+    OwnPtr<AsyncFileSystemCallbacks> m_callbacks;
+};
+
+WebFileSystemCallbacks::WebFileSystemCallbacks(const PassOwnPtr<AsyncFileSystemCallbacks>& callbacks)
+{
+    m_private = WebFileSystemCallbacksPrivate::create(callbacks);
+}
+
+void WebFileSystemCallbacks::reset()
+{
+    m_private.reset();
+}
+
+void WebFileSystemCallbacks::assign(const WebFileSystemCallbacks& other)
+{
+    m_private = other.m_private;
+}
+
+void WebFileSystemCallbacks::didSucceed()
+{
+    ASSERT(!m_private.isNull());
+    m_private->callbacks()->didSucceed();
+    m_private.reset();
+}
+
+void WebFileSystemCallbacks::didReadMetadata(const WebFileInfo& webFileInfo)
+{
+    ASSERT(!m_private.isNull());
+    FileMetadata fileMetadata;
+    fileMetadata.modificationTime = webFileInfo.modificationTime;
+    fileMetadata.length = webFileInfo.length;
+    fileMetadata.type = static_cast<FileMetadata::Type>(webFileInfo.type);
+    fileMetadata.platformPath = webFileInfo.platformPath;
+    m_private->callbacks()->didReadMetadata(fileMetadata);
+    m_private.reset();
+}
+
+void WebFileSystemCallbacks::didCreateSnapshotFile(const WebFileInfo& webFileInfo)
+{
+    ASSERT(!m_private.isNull());
+    // It's important to create a BlobDataHandle that refers to the platform file path prior
+    // to return from this method so the underlying file will not be deleted.
+    OwnPtr<BlobData> blobData = BlobData::create();
+    blobData->appendFile(webFileInfo.platformPath);
+    RefPtr<BlobDataHandle> snapshotBlob = BlobDataHandle::create(blobData.release(), webFileInfo.length);
+
+    FileMetadata fileMetadata;
+    fileMetadata.modificationTime = webFileInfo.modificationTime;
+    fileMetadata.length = webFileInfo.length;
+    fileMetadata.type = static_cast<FileMetadata::Type>(webFileInfo.type);
+    fileMetadata.platformPath = webFileInfo.platformPath;
+    m_private->callbacks()->didCreateSnapshotFile(fileMetadata, snapshotBlob);
+    m_private.reset();
+}
+
+void WebFileSystemCallbacks::didReadDirectory(const WebVector<WebFileSystemEntry>& entries, bool hasMore)
+{
+    ASSERT(!m_private.isNull());
+    for (size_t i = 0; i < entries.size(); ++i)
+        m_private->callbacks()->didReadDirectoryEntry(entries[i].name, entries[i].isDirectory);
+    m_private->callbacks()->didReadDirectoryEntries(hasMore);
+    m_private.reset();
+}
+
+void WebFileSystemCallbacks::didOpenFileSystem(const WebString& name, const WebURL& rootURL)
+{
+    ASSERT(!m_private.isNull());
+    m_private->callbacks()->didOpenFileSystem(name, rootURL);
+    m_private.reset();
+}
+
+void WebFileSystemCallbacks::didCreateFileWriter(WebFileWriter* webFileWriter, long long length)
+{
+    ASSERT(!m_private.isNull());
+    m_private->callbacks()->didCreateFileWriter(adoptPtr(webFileWriter), length);
+    m_private.reset();
+}
+
+void WebFileSystemCallbacks::didFail(WebFileError error)
+{
+    ASSERT(!m_private.isNull());
+    m_private->callbacks()->didFail(error);
+    m_private.reset();
+}
+
+bool WebFileSystemCallbacks::shouldBlockUntilCompletion() const
+{
+    ASSERT(!m_private.isNull());
+    return m_private->callbacks()->shouldBlockUntilCompletion();
+}
+
+} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebHTTPBody.cpp b/Source/core/platform/chromium/support/WebHTTPBody.cpp
index 4322a8d..0b1116d 100644
--- a/Source/core/platform/chromium/support/WebHTTPBody.cpp
+++ b/Source/core/platform/chromium/support/WebHTTPBody.cpp
@@ -81,6 +81,7 @@
     result.modificationTime = invalidFileTime();
     result.url = KURL();
     result.blobURL = KURL();
+    result.blobUUID.reset();
 
     switch (element.m_type) {
     case FormDataElement::data:
@@ -96,12 +97,13 @@
         break;
     case FormDataElement::encodedBlob:
         result.type = Element::TypeBlob;
-        result.url = element.m_url;
+        result.url = element.m_url; // DEPRECATED, should be able to remove after https://codereview.chromium.org/23223003/ lands
         result.blobURL = element.m_url; // FIXME: deprecate this.
         break;
     case FormDataElement::encodedURL:
-        result.type = Element::TypeURL;
-        result.url = element.m_url;
+        result.type = Element::TypeFileSystemURL;
+        result.url = element.m_url; // DEPRECATED
+        result.fileSystemURL = element.m_url;
         result.fileStart = element.m_fileStart;
         result.fileLength = element.m_fileLength;
         result.modificationTime = element.m_expectedFileModificationTime;
@@ -134,7 +136,7 @@
     m_private->appendFileRange(filePath, fileStart, fileLength, modificationTime);
 }
 
-void WebHTTPBody::appendURLRange(const WebURL& url, long long start, long long length, double modificationTime)
+void WebHTTPBody::appendFileSystemURLRange(const WebURL& url, long long start, long long length, double modificationTime)
 {
     // Currently we only support filesystem URL.
     ASSERT(KURL(url).protocolIs("filesystem"));
@@ -142,6 +144,11 @@
     m_private->appendURLRange(url, start, length, modificationTime);
 }
 
+void WebHTTPBody::appendURLRange(const WebURL& url, long long start, long long length, double modificationTime)
+{
+    appendFileSystemURLRange(url, start, length, modificationTime);
+}
+
 void WebHTTPBody::appendBlob(const WebURL& blobURL)
 {
     ASSERT(KURL(blobURL).protocolIs("blob"));
diff --git a/Source/core/platform/chromium/support/WebScrollbarImpl.cpp b/Source/core/platform/chromium/support/WebScrollbarImpl.cpp
index f88bfbc..6e5258d 100644
--- a/Source/core/platform/chromium/support/WebScrollbarImpl.cpp
+++ b/Source/core/platform/chromium/support/WebScrollbarImpl.cpp
@@ -28,7 +28,6 @@
 
 #include "core/platform/Scrollbar.h"
 #include "core/platform/graphics/IntRect.h"
-#include "core/platform/text/TextDirection.h"
 
 namespace WebKit {
 
@@ -119,9 +118,9 @@
     return static_cast<WebScrollbar::Orientation>(m_scrollbar->orientation());
 }
 
-bool WebScrollbarImpl::isRightToLeft() const
+bool WebScrollbarImpl::isLeftSideVerticalScrollbar() const
 {
-    return m_scrollbar->textDirection() == WebCore::RTL;
+    return m_scrollbar->isLeftSideVerticalScrollbar();
 }
 
 bool WebScrollbarImpl::isCustomScrollbar() const
diff --git a/Source/core/platform/chromium/support/WebScrollbarImpl.h b/Source/core/platform/chromium/support/WebScrollbarImpl.h
index 124b1a6..e5459de 100644
--- a/Source/core/platform/chromium/support/WebScrollbarImpl.h
+++ b/Source/core/platform/chromium/support/WebScrollbarImpl.h
@@ -54,7 +54,7 @@
     virtual ScrollbarOverlayStyle scrollbarOverlayStyle() const OVERRIDE;
     virtual bool isCustomScrollbar() const OVERRIDE;
     virtual Orientation orientation() const OVERRIDE;
-    virtual bool isRightToLeft() const OVERRIDE;
+    virtual bool isLeftSideVerticalScrollbar() const OVERRIDE;
     virtual bool isAlphaLocked() const OVERRIDE;
     virtual void setIsAlphaLocked(bool) OVERRIDE;
 
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp b/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp
index 7a3f5e0..bd6780d 100644
--- a/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp
+++ b/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp
@@ -153,6 +153,11 @@
     return static_cast<WebCore::ScrollbarOrientation>(m_scrollbar->orientation());
 }
 
+bool WebScrollbarThemeClientImpl::isLeftSideVerticalScrollbar() const
+{
+    return m_scrollbar->isLeftSideVerticalScrollbar();
+}
+
 int WebScrollbarThemeClientImpl::value() const
 {
     return m_scrollbar->value();
diff --git a/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h b/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h
index 5f6728f..3c08004 100644
--- a/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h
+++ b/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h
@@ -62,6 +62,7 @@
     virtual IntPoint convertFromContainingWindow(const IntPoint&) OVERRIDE;
     virtual bool isCustomScrollbar() const OVERRIDE;
     virtual ScrollbarOrientation orientation() const OVERRIDE;
+    virtual bool isLeftSideVerticalScrollbar() const OVERRIDE;
     virtual int value() const OVERRIDE;
     virtual float currentPos() const OVERRIDE;
     virtual int visibleSize() const OVERRIDE;
diff --git a/Source/core/platform/chromium/support/WebString.cpp b/Source/core/platform/chromium/support/WebString.cpp
index 4b5dd6b..c3ed5db 100644
--- a/Source/core/platform/chromium/support/WebString.cpp
+++ b/Source/core/platform/chromium/support/WebString.cpp
@@ -88,12 +88,31 @@
 
 WebString WebString::fromUTF8(const char* data, size_t length)
 {
-    return WTF::String::fromUTF8(data, length);
+    return String::fromUTF8(data, length);
 }
 
 WebString WebString::fromUTF8(const char* data)
 {
-    return WTF::String::fromUTF8(data);
+    return String::fromUTF8(data);
+}
+
+std::string WebString::latin1() const
+{
+    String string(m_private.get());
+
+    if (string.isEmpty())
+        return std::string();
+
+    if (string.is8Bit())
+        return std::string(reinterpret_cast<const char*>(string.characters8()), string.length());
+
+    WebCString latin1 = string.latin1();
+    return std::string(latin1.data(), latin1.length());
+}
+
+WebString WebString::fromLatin1(const WebLChar* data, size_t length)
+{
+    return String(data, length);
 }
 
 bool WebString::equals(const WebString& s) const
diff --git a/Source/core/platform/chromium/support/WebURLResponse.cpp b/Source/core/platform/chromium/support/WebURLResponse.cpp
index 1ca9712..a69027b 100644
--- a/Source/core/platform/chromium/support/WebURLResponse.cpp
+++ b/Source/core/platform/chromium/support/WebURLResponse.cpp
@@ -392,15 +392,12 @@
 
 WebString WebURLResponse::downloadFilePath() const
 {
-    const File* downloadedFile = m_private->m_resourceResponse->downloadedFile();
-    if (downloadedFile)
-        return downloadedFile->path();
-    return WebString();
+    return m_private->m_resourceResponse->downloadedFilePath();
 }
 
 void WebURLResponse::setDownloadFilePath(const WebString& downloadFilePath)
 {
-    m_private->m_resourceResponse->setDownloadedFile(downloadFilePath.isEmpty() ? 0 : File::create(downloadFilePath));
+    m_private->m_resourceResponse->setDownloadedFilePath(downloadFilePath);
 }
 
 WebString WebURLResponse::remoteIPAddress() const
diff --git a/Source/core/platform/graphics/BitmapImage.cpp b/Source/core/platform/graphics/BitmapImage.cpp
index 2b2c36d..178f33d 100644
--- a/Source/core/platform/graphics/BitmapImage.cpp
+++ b/Source/core/platform/graphics/BitmapImage.cpp
@@ -105,12 +105,6 @@
     return true;
 }
 
-bool BitmapImage::hasSingleSecurityOrigin() const
-{
-    return true;
-}
-
-
 void BitmapImage::destroyDecodedData(bool destroyAll)
 {
     for (size_t i = 0; i < m_frames.size(); ++i) {
diff --git a/Source/core/platform/graphics/BitmapImage.h b/Source/core/platform/graphics/BitmapImage.h
index 5197fbb..6914f23 100644
--- a/Source/core/platform/graphics/BitmapImage.h
+++ b/Source/core/platform/graphics/BitmapImage.h
@@ -59,7 +59,7 @@
 
     virtual bool isBitmapImage() const OVERRIDE;
 
-    virtual bool hasSingleSecurityOrigin() const OVERRIDE;
+    virtual bool currentFrameHasSingleSecurityOrigin() const OVERRIDE { return true; };
 
     virtual IntSize size() const OVERRIDE;
     IntSize sizeRespectingOrientation() const;
diff --git a/Source/core/platform/graphics/Color.cpp b/Source/core/platform/graphics/Color.cpp
index 4e0cb62..c76efef 100644
--- a/Source/core/platform/graphics/Color.cpp
+++ b/Source/core/platform/graphics/Color.cpp
@@ -44,7 +44,6 @@
 const RGBA32 Color::gray;
 const RGBA32 Color::lightGray;
 const RGBA32 Color::transparent;
-const RGBA32 Color::stdShadowColor;
 #endif
 
 static const RGBA32 lightenedBlack = 0xFF545454;
@@ -179,6 +178,29 @@
     return dR * dR + dG * dG + dB * dB;
 }
 
+Color::Color(const String& name)
+{
+    if (name[0] == '#') {
+        if (name.is8Bit())
+            m_valid = parseHexColor(name.characters8() + 1, name.length() - 1, m_color);
+        else
+            m_valid = parseHexColor(name.characters16() + 1, name.length() - 1, m_color);
+    } else {
+        setNamedColor(name);
+    }
+}
+
+Color::Color(const char* name)
+{
+    if (name[0] == '#') {
+        m_valid = parseHexColor(&name[1], m_color);
+    } else {
+        const NamedColor* foundColor = findColor(name, strlen(name));
+        m_color = foundColor ? foundColor->ARGBValue : 0;
+        m_valid = foundColor;
+    }
+}
+
 String Color::serialized() const
 {
     if (!hasAlpha()) {
@@ -223,6 +245,29 @@
     return String::format("#%02X%02X%02X", red(), green(), blue());
 }
 
+static inline const NamedColor* findNamedColor(const String& name)
+{
+    char buffer[64]; // easily big enough for the longest color name
+    unsigned length = name.length();
+    if (length > sizeof(buffer) - 1)
+        return 0;
+    for (unsigned i = 0; i < length; ++i) {
+        UChar c = name[i];
+        if (!c || c > 0x7F)
+            return 0;
+        buffer[i] = toASCIILower(static_cast<char>(c));
+    }
+    buffer[length] = '\0';
+    return findColor(buffer, length);
+}
+
+void Color::setNamedColor(const String& name)
+{
+    const NamedColor* foundColor = findNamedColor(name);
+    m_color = foundColor ? foundColor->ARGBValue : 0;
+    m_valid = foundColor;
+}
+
 Color Color::light() const
 {
     // Hardcode this common case for speed.
diff --git a/Source/core/platform/graphics/Color.h b/Source/core/platform/graphics/Color.h
index 4416bde..012d641 100644
--- a/Source/core/platform/graphics/Color.h
+++ b/Source/core/platform/graphics/Color.h
@@ -55,14 +55,16 @@
 class Color {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    Color() : m_color(0) { }
-    Color(RGBA32 color) : m_color(color) { }
-    Color(int r, int g, int b) : m_color(makeRGB(r, g, b)) { }
-    Color(int r, int g, int b, int a) : m_color(makeRGBA(r, g, b, a)) { }
+    Color() : m_color(0), m_valid(false) { }
+    Color(RGBA32 color, bool valid = true) : m_color(color), m_valid(valid) { ASSERT(!m_color || m_valid); }
+    Color(int r, int g, int b) : m_color(makeRGB(r, g, b)), m_valid(true) { }
+    Color(int r, int g, int b, int a) : m_color(makeRGBA(r, g, b, a)), m_valid(true) { }
     // Color is currently limited to 32bit RGBA, perhaps some day we'll support better colors
-    Color(float r, float g, float b, float a) : m_color(makeRGBA32FromFloats(r, g, b, a)) { }
+    Color(float r, float g, float b, float a) : m_color(makeRGBA32FromFloats(r, g, b, a)), m_valid(true) { }
     // Creates a new color from the specific CMYK and alpha values.
-    Color(float c, float m, float y, float k, float a) : m_color(makeRGBAFromCMYKA(c, m, y, k, a)) { }
+    Color(float c, float m, float y, float k, float a) : m_color(makeRGBAFromCMYKA(c, m, y, k, a)), m_valid(true) { }
+    explicit Color(const String&);
+    explicit Color(const char*);
 
     static Color createUnchecked(int r, int g, int b)
     {
@@ -83,6 +85,10 @@
     // The latter format is not a valid CSS color, and should only be seen in DRT dumps.
     String nameForRenderTreeAsText() const;
 
+    void setNamedColor(const String&);
+
+    bool isValid() const { return m_valid; }
+
     bool hasAlpha() const { return alpha() < 255; }
 
     int red() const { return redChannel(m_color); }
@@ -91,8 +97,8 @@
     int alpha() const { return alphaChannel(m_color); }
 
     RGBA32 rgb() const { return m_color; } // Preserve the alpha.
-    void setRGB(int r, int g, int b) { m_color = makeRGB(r, g, b); }
-    void setRGB(RGBA32 rgb) { m_color = rgb; }
+    void setRGB(int r, int g, int b) { m_color = makeRGB(r, g, b); m_valid = true; }
+    void setRGB(RGBA32 rgb) { m_color = rgb; m_valid = true; }
     void getRGBA(float& r, float& g, float& b, float& a) const;
     void getRGBA(double& r, double& g, double& b, double& a) const;
     void getHSL(double& h, double& s, double& l) const;
@@ -114,15 +120,15 @@
     static const RGBA32 gray = 0xFFA0A0A0;
     static const RGBA32 lightGray = 0xFFC0C0C0;
     static const RGBA32 transparent = 0x00000000;
-    static const RGBA32 stdShadowColor = 0x00000055;
 
 private:
     RGBA32 m_color;
+    bool m_valid;
 };
 
 inline bool operator==(const Color& a, const Color& b)
 {
-    return a.rgb() == b.rgb();
+    return a.rgb() == b.rgb() && a.isValid() == b.isValid();
 }
 
 inline bool operator!=(const Color& a, const Color& b)
@@ -135,6 +141,10 @@
 
 inline Color blend(const Color& from, const Color& to, double progress, bool blendPremultiplied = true)
 {
+    // We need to preserve the state of the valid flag at the end of the animation
+    if (progress == 1 && !to.isValid())
+        return Color();
+
     if (blendPremultiplied) {
         // Contrary to the name, RGBA32 actually stores ARGB, so we can initialize Color directly from premultipliedARGBFromColor().
         // Also, premultipliedARGBFromColor() bails on zero alpha, so special-case that.
diff --git a/Source/core/platform/graphics/DrawLooper.cpp b/Source/core/platform/graphics/DrawLooper.cpp
index 609878b..461db1c 100644
--- a/Source/core/platform/graphics/DrawLooper.cpp
+++ b/Source/core/platform/graphics/DrawLooper.cpp
@@ -62,10 +62,14 @@
     ShadowTransformMode shadowTransformMode, ShadowAlphaMode shadowAlphaMode)
 {
     // Detect when there's no effective shadow.
-    if (!color.alpha())
+    if (!color.isValid() || !color.alpha())
         return;
 
-    SkColor skColor = color.rgb();
+    SkColor skColor;
+    if (color.isValid())
+        skColor = color.rgb();
+    else
+        skColor = SkColorSetARGB(0xFF / 3, 0, 0, 0); // "std" apple shadow color.
 
     SkLayerDrawLooper::LayerInfo info;
 
diff --git a/Source/core/platform/graphics/FloatPoint.h b/Source/core/platform/graphics/FloatPoint.h
index 1574deb..9ddbc2b 100644
--- a/Source/core/platform/graphics/FloatPoint.h
+++ b/Source/core/platform/graphics/FloatPoint.h
@@ -30,8 +30,9 @@
 #include "core/platform/graphics/FloatSize.h"
 #include "core/platform/graphics/IntPoint.h"
 #include "wtf/MathExtras.h"
+#include <algorithm>
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 typedef struct CGPoint CGPoint;
 
 #ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
@@ -131,7 +132,7 @@
         return FloatPoint(m_y, m_x);
     }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     FloatPoint(const CGPoint&);
     operator CGPoint() const;
 #if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
diff --git a/Source/core/platform/graphics/FloatRect.h b/Source/core/platform/graphics/FloatRect.h
index 40bea2b..e0b631f 100644
--- a/Source/core/platform/graphics/FloatRect.h
+++ b/Source/core/platform/graphics/FloatRect.h
@@ -30,7 +30,7 @@
 #include "core/platform/graphics/FloatPoint.h"
 #include "wtf/Vector.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 typedef struct CGRect CGRect;
 #ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
 typedef struct CGRect NSRect;
@@ -160,7 +160,7 @@
     void fitToPoints(const FloatPoint& p0, const FloatPoint& p1, const FloatPoint& p2);
     void fitToPoints(const FloatPoint& p0, const FloatPoint& p1, const FloatPoint& p2, const FloatPoint& p3);
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     FloatRect(const CGRect&);
     operator CGRect() const;
 #if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
diff --git a/Source/core/platform/graphics/FloatSize.h b/Source/core/platform/graphics/FloatSize.h
index e9606f0..320fa67 100644
--- a/Source/core/platform/graphics/FloatSize.h
+++ b/Source/core/platform/graphics/FloatSize.h
@@ -32,7 +32,7 @@
 #include "wtf/MathExtras.h"
 
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 typedef struct CGSize CGSize;
 
 #ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
@@ -105,7 +105,7 @@
         return FloatSize(m_height, m_width);
     }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     explicit FloatSize(const CGSize&); // don't do this implicitly since it's lossy
     operator CGSize() const;
 #if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
diff --git a/Source/core/platform/graphics/Font.cpp b/Source/core/platform/graphics/Font.cpp
index 740bd6b..bdf6843 100644
--- a/Source/core/platform/graphics/Font.cpp
+++ b/Source/core/platform/graphics/Font.cpp
@@ -251,7 +251,7 @@
     return width(run);
 }
 
-#if !OS(DARWIN)
+#if !OS(MACOSX)
 
 PassOwnPtr<TextLayout> Font::createLayout(RenderText*, float, bool) const
 {
diff --git a/Source/core/platform/graphics/Font.h b/Source/core/platform/graphics/Font.h
index 3c57abc..9e83145 100644
--- a/Source/core/platform/graphics/Font.h
+++ b/Source/core/platform/graphics/Font.h
@@ -147,7 +147,7 @@
     {
         return glyphDataAndPageForCharacter(c, mirror, variant).first;
     }
-#if OS(DARWIN)
+#if OS(MACOSX)
     const SimpleFontData* fontDataForCombiningCharacterSequence(const UChar*, size_t length, FontDataVariant) const;
 #endif
     std::pair<GlyphData, GlyphPage*> glyphDataAndPageForCharacter(UChar32, bool mirror, FontDataVariant = AutoVariant) const;
diff --git a/Source/core/platform/graphics/FontCache.cpp b/Source/core/platform/graphics/FontCache.cpp
index 49a1c41..143765a 100644
--- a/Source/core/platform/graphics/FontCache.cpp
+++ b/Source/core/platform/graphics/FontCache.cpp
@@ -53,10 +53,12 @@
     return &globalFontCache;
 }
 
+#if !OS(WIN) || ENABLE(GDI_FONTS_ON_WINDOWS)
 FontCache::FontCache()
     : m_purgePreventCount(0)
 {
 }
+#endif // !OS(WIN) || ENABLE(GDI_FONTS_ON_WINDOWS)
 
 struct FontPlatformDataCacheKey {
     WTF_MAKE_FAST_ALLOCATED;
@@ -134,7 +136,7 @@
     DEFINE_STATIC_LOCAL(AtomicString, courierNew, ("Courier New", AtomicString::ConstructFromLiteral));
     if (equalIgnoringCase(familyName, courier))
         return courierNew;
-#if !OS(WINDOWS)
+#if !OS(WIN)
     // On Windows, Courier New (truetype font) is always present and
     // Courier is a bitmap font. So, we don't want to map Courier New to
     // Courier.
@@ -158,7 +160,7 @@
     if (equalIgnoringCase(familyName, helvetica))
         return arial;
 
-#if OS(WINDOWS)
+#if OS(WIN)
     // On Windows, bitmap fonts are blocked altogether so that we have to
     // alias MS Sans Serif (bitmap font) -> Microsoft Sans Serif (truetype font)
     DEFINE_STATIC_LOCAL(AtomicString, msSans, ("MS Sans Serif", AtomicString::ConstructFromLiteral));
@@ -180,7 +182,7 @@
                                                        const AtomicString& passedFamilyName,
                                                        bool checkingAlternateName)
 {
-#if OS(WINDOWS) && ENABLE(OPENTYPE_VERTICAL)
+#if OS(WIN) && ENABLE(OPENTYPE_VERTICAL)
     // Leading "@" in the font name enables Windows vertical flow flag for the font.
     // Because we do vertical flow by ourselves, we don't want to use the Windows feature.
     // IE disregards "@" regardless of the orientatoin, so we follow the behavior.
diff --git a/Source/core/platform/graphics/FontCache.h b/Source/core/platform/graphics/FontCache.h
index 905f1cb..882b5ee 100644
--- a/Source/core/platform/graphics/FontCache.h
+++ b/Source/core/platform/graphics/FontCache.h
@@ -39,12 +39,16 @@
 #include "wtf/text/WTFString.h"
 #include "wtf/unicode/Unicode.h"
 
-#if OS(WINDOWS)
+#if OS(WIN)
 #include <windows.h>
 #include <objidl.h>
 #include <mlang.h>
 #endif
 
+#if OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS)
+#include "SkFontMgr.h"
+#endif
+
 class SkTypeface;
 
 namespace WebCore {
@@ -93,7 +97,7 @@
     size_t inactiveFontDataCount();
     void purgeInactiveFontData(int count = INT_MAX);
 
-#if OS(WINDOWS)
+#if OS(WIN)
     PassRefPtr<SimpleFontData> fontDataFromDescriptionAndLogFont(const FontDescription&, ShouldRetain, const LOGFONT&, wchar_t* outFontFamilyName);
 #endif
 
@@ -139,7 +143,11 @@
     // Don't purge if this count is > 0;
     int m_purgePreventCount;
 
-#if OS(DARWIN) || OS(ANDROID)
+#if OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS)
+    OwnPtr<SkFontMgr> m_fontManager;
+#endif
+
+#if OS(MACOSX) || OS(ANDROID)
     friend class ComplexTextController;
 #endif
     friend class SimpleFontData; // For getFontResourceData(const FontPlatformData*)
diff --git a/Source/core/platform/graphics/FontCustomPlatformData.h b/Source/core/platform/graphics/FontCustomPlatformData.h
index e7a2239..f07a117 100644
--- a/Source/core/platform/graphics/FontCustomPlatformData.h
+++ b/Source/core/platform/graphics/FontCustomPlatformData.h
@@ -38,17 +38,17 @@
 #include "wtf/Noncopyable.h"
 #include "wtf/text/WTFString.h"
 
-#if OS(WINDOWS) && ENABLE(GDI_FONTS_ON_WINDOWS)
+#if OS(WIN) && ENABLE(GDI_FONTS_ON_WINDOWS)
 #include <windows.h>
 #endif
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include "wtf/RetainPtr.h"
 #include <CoreFoundation/CFBase.h>
 typedef struct CGFont* CGFontRef;
 #endif
 
-#if OS(DARWIN) || OS(UNIX) || (OS(WINDOWS) && !ENABLE(GDI_FONTS_ON_WINDOWS))
+#if OS(MACOSX) || OS(POSIX) || (OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS))
 #include "wtf/RefPtr.h"
 class SkTypeface;
 #endif
@@ -69,15 +69,15 @@
     static bool supportsFormat(const String&);
 
 private:
-#if OS(WINDOWS) && ENABLE(GDI_FONTS_ON_WINDOWS)
+#if OS(WIN) && ENABLE(GDI_FONTS_ON_WINDOWS)
     FontCustomPlatformData(HANDLE fontReference, const String& name);
     HANDLE m_fontReference;
     String m_name;
-#elif OS(DARWIN)
+#elif OS(MACOSX)
     explicit FontCustomPlatformData(CGFontRef, PassRefPtr<SkTypeface>);
     RetainPtr<CGFontRef> m_cgFont;
     RefPtr<SkTypeface> m_typeface;
-#elif OS(UNIX) || (OS(WINDOWS) && !ENABLE(GDI_FONTS_ON_WINDOWS))
+#elif OS(POSIX) || (OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS))
     explicit FontCustomPlatformData(PassRefPtr<SkTypeface>);
     RefPtr<SkTypeface> m_typeface;
 #endif
diff --git a/Source/core/platform/graphics/FontDescription.h b/Source/core/platform/graphics/FontDescription.h
index 0411fc9..7aa1522 100644
--- a/Source/core/platform/graphics/FontDescription.h
+++ b/Source/core/platform/graphics/FontDescription.h
@@ -144,7 +144,7 @@
     void setIsAbsoluteSize(bool s) { m_isAbsoluteSize = s; }
     void setWeight(FontWeight w) { m_weight = w; }
     void setGenericFamily(GenericFamilyType genericFamily) { m_genericFamily = genericFamily; }
-#if OS(DARWIN)
+#if OS(MACOSX)
     void setUsePrinterFont(bool) { }
 #else
     void setUsePrinterFont(bool p) { m_usePrinterFont = p; }
diff --git a/Source/core/platform/graphics/FontPlatformData.cpp b/Source/core/platform/graphics/FontPlatformData.cpp
index 06b9cca..3e2f72c 100644
--- a/Source/core/platform/graphics/FontPlatformData.cpp
+++ b/Source/core/platform/graphics/FontPlatformData.cpp
@@ -27,7 +27,7 @@
 #include "wtf/text/WTFString.h"
 #include "wtf/Vector.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
 #endif
 
@@ -41,12 +41,12 @@
     , m_orientation(Horizontal)
     , m_size(0)
     , m_widthVariant(RegularWidth)
-#if OS(DARWIN)
+#if OS(MACOSX)
     , m_font(hashTableDeletedFontValue())
 #endif
     , m_isColorBitmapFont(false)
     , m_isCompositeFontReference(false)
-#if OS(DARWIN)
+#if OS(MACOSX)
     , m_isPrinterFont(false)
 #endif
 {
@@ -58,12 +58,12 @@
     , m_orientation(Horizontal)
     , m_size(0)
     , m_widthVariant(RegularWidth)
-#if OS(DARWIN)
+#if OS(MACOSX)
     , m_font(0)
 #endif
     , m_isColorBitmapFont(false)
     , m_isCompositeFontReference(false)
-#if OS(DARWIN)
+#if OS(MACOSX)
     , m_isPrinterFont(false)
 #endif
 {
@@ -75,18 +75,18 @@
     , m_orientation(orientation)
     , m_size(size)
     , m_widthVariant(widthVariant)
-#if OS(DARWIN)
+#if OS(MACOSX)
     , m_font(0)
 #endif
     , m_isColorBitmapFont(false)
     , m_isCompositeFontReference(false)
-#if OS(DARWIN)
+#if OS(MACOSX)
     , m_isPrinterFont(false)
 #endif
 {
 }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 FontPlatformData::FontPlatformData(CGFontRef cgFont, float size, bool syntheticBold, bool syntheticOblique, FontOrientation orientation, FontWidthVariant widthVariant)
     : m_syntheticBold(syntheticBold)
     , m_syntheticOblique(syntheticOblique)
@@ -110,7 +110,7 @@
     , m_widthVariant(source.m_widthVariant)
     , m_isColorBitmapFont(source.m_isColorBitmapFont)
     , m_isCompositeFontReference(source.m_isCompositeFontReference)
-#if OS(DARWIN)
+#if OS(MACOSX)
     , m_isPrinterFont(source.m_isPrinterFont)
 #endif
 {
@@ -130,7 +130,7 @@
     m_widthVariant = other.m_widthVariant;
     m_isColorBitmapFont = other.m_isColorBitmapFont;
     m_isCompositeFontReference = other.m_isCompositeFontReference;
-#if OS(DARWIN)
+#if OS(MACOSX)
     m_isPrinterFont = other.m_isPrinterFont;
 #endif
 
diff --git a/Source/core/platform/graphics/FontPlatformData.h b/Source/core/platform/graphics/FontPlatformData.h
index fee50e4..5571b23 100644
--- a/Source/core/platform/graphics/FontPlatformData.h
+++ b/Source/core/platform/graphics/FontPlatformData.h
@@ -23,9 +23,9 @@
  */
 
 // FIXME: This is temporary until all ports switch to using this file.
-#if OS(WINDOWS)
+#if OS(WIN)
 #include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#elif OS(UNIX) && !OS(DARWIN)
+#elif !OS(MACOSX)
 #include "core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h"
 
 #else
@@ -36,7 +36,7 @@
 #include "core/platform/graphics/FontOrientation.h"
 #include "core/platform/graphics/FontWidthVariant.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 OBJC_CLASS NSFont;
 
 typedef struct CGFont* CGFontRef;
@@ -53,11 +53,11 @@
 #include "wtf/RetainPtr.h"
 #include "wtf/text/StringImpl.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include "core/platform/graphics/chromium/CrossProcessFontLoading.h"
 #endif
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 typedef struct CGFont* CGFontRef;
 typedef const struct __CTFont* CTFontRef;
 typedef UInt32 FMFont;
@@ -70,11 +70,11 @@
 class FontDescription;
 class SharedBuffer;
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 class HarfBuzzFace;
 #endif
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 inline CTFontRef toCTFontRef(NSFont *nsFont) { return reinterpret_cast<CTFontRef>(nsFont); }
 #endif
 
@@ -86,7 +86,7 @@
     FontPlatformData(const FontDescription&, const AtomicString& family);
     FontPlatformData(float size, bool syntheticBold, bool syntheticOblique, FontOrientation = Horizontal, FontWidthVariant = RegularWidth);
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     FontPlatformData(NSFont*, float size, bool isPrinterFont = false, bool syntheticBold = false, bool syntheticOblique = false,
                      FontOrientation = Horizontal, FontWidthVariant = RegularWidth);
     FontPlatformData(CGFontRef, float size, bool syntheticBold, bool syntheticOblique, FontOrientation, FontWidthVariant);
@@ -94,12 +94,12 @@
 
     ~FontPlatformData();
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     NSFont* font() const { return m_font; }
     void setFont(NSFont*);
 #endif
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     CGFontRef cgFont() const { return m_cgFont.get(); }
     CTFontRef ctFont() const;
 
@@ -115,7 +115,7 @@
     bool syntheticOblique() const { return m_syntheticOblique; }
     bool isColorBitmapFont() const { return m_isColorBitmapFont; }
     bool isCompositeFontReference() const { return m_isCompositeFontReference; }
-#if OS(DARWIN)
+#if OS(MACOSX)
     bool isPrinterFont() const { return m_isPrinterFont; }
 #endif
     FontOrientation orientation() const { return m_orientation; }
@@ -123,13 +123,13 @@
 
     void setOrientation(FontOrientation orientation) { m_orientation = orientation; }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     HarfBuzzFace* harfBuzzFace();
 #endif
 
     unsigned hash() const
     {
-#if OS(DARWIN)
+#if OS(MACOSX)
         ASSERT(m_font || !m_cgFont);
         uintptr_t hashCodes[3] = { (uintptr_t)m_font, m_widthVariant, static_cast<uintptr_t>(m_isPrinterFont << 3 | m_orientation << 2 | m_syntheticBold << 1 | m_syntheticOblique) };
         return StringHasher::hashMemory<sizeof(hashCodes)>(hashCodes);
@@ -146,7 +146,7 @@
             && m_syntheticOblique == other.m_syntheticOblique
             && m_isColorBitmapFont == other.m_isColorBitmapFont
             && m_isCompositeFontReference == other.m_isCompositeFontReference
-#if OS(DARWIN)
+#if OS(MACOSX)
             && m_isPrinterFont == other.m_isPrinterFont
 #endif
             && m_orientation == other.m_orientation
@@ -155,7 +155,7 @@
 
     bool isHashTableDeletedValue() const
     {
-#if OS(DARWIN)
+#if OS(MACOSX)
         return m_font == hashTableDeletedFontValue();
 #endif
     }
@@ -168,7 +168,7 @@
     bool platformIsEqual(const FontPlatformData&) const;
     void platformDataInit(const FontPlatformData&);
     const FontPlatformData& platformDataAssign(const FontPlatformData&);
-#if OS(DARWIN)
+#if OS(MACOSX)
     // Load various data about the font specified by |nsFont| with the size fontSize into the following output paramters:
     // Note: Callers should always take into account that for the Chromium port, |outNSFont| isn't necessarily the same
     // font as |nsFont|. This because the sandbox may block loading of the original font.
@@ -187,11 +187,11 @@
     FontWidthVariant m_widthVariant;
 
 private:
-#if OS(DARWIN)
+#if OS(MACOSX)
     NSFont* m_font;
 #endif
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     RetainPtr<CGFontRef> m_cgFont;
     mutable RetainPtr<CTFontRef> m_CTFont;
 
@@ -201,7 +201,7 @@
 
     bool m_isColorBitmapFont;
     bool m_isCompositeFontReference;
-#if OS(DARWIN)
+#if OS(MACOSX)
     bool m_isPrinterFont;
 #endif
 };
diff --git a/Source/core/platform/graphics/GeneratedImage.h b/Source/core/platform/graphics/GeneratedImage.h
index de7d8f8..8c5bfb1 100644
--- a/Source/core/platform/graphics/GeneratedImage.h
+++ b/Source/core/platform/graphics/GeneratedImage.h
@@ -34,7 +34,7 @@
 
 class GeneratedImage : public Image {
 public:
-    virtual bool hasSingleSecurityOrigin() const OVERRIDE { return true; }
+    virtual bool currentFrameHasSingleSecurityOrigin() const OVERRIDE { return true; }
 
     virtual void setContainerSize(const IntSize& size) OVERRIDE { m_size = size; }
     virtual bool usesContainerSize() const OVERRIDE { return true; }
diff --git a/Source/core/platform/graphics/GlyphBuffer.h b/Source/core/platform/graphics/GlyphBuffer.h
index 97399cb..b580615 100644
--- a/Source/core/platform/graphics/GlyphBuffer.h
+++ b/Source/core/platform/graphics/GlyphBuffer.h
@@ -35,7 +35,7 @@
 #include "wtf/UnusedParam.h"
 #include "wtf/Vector.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include <ApplicationServices/ApplicationServices.h>
 #endif
 
@@ -47,7 +47,7 @@
 
 // CG uses CGSize instead of FloatSize so that the result of advances()
 // can be passed directly to CGContextShowGlyphsWithAdvances in FontMac.mm
-#if OS(DARWIN)
+#if OS(MACOSX)
 struct GlyphBufferAdvance : CGSize {
 public:
     GlyphBufferAdvance(CGSize size) : CGSize(size)
@@ -96,7 +96,7 @@
         m_fontData.append(font);
         m_glyphs.append(glyph);
 
-#if OS(DARWIN)
+#if OS(MACOSX)
         CGSize advance = { width, 0 };
         m_advances.append(advance);
 #else
diff --git a/Source/core/platform/graphics/GraphicsContext.cpp b/Source/core/platform/graphics/GraphicsContext.cpp
index 9af9b34..32b266f 100644
--- a/Source/core/platform/graphics/GraphicsContext.cpp
+++ b/Source/core/platform/graphics/GraphicsContext.cpp
@@ -48,7 +48,7 @@
 #include "wtf/Assertions.h"
 #include "wtf/MathExtras.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include <ApplicationServices/ApplicationServices.h>
 #endif
 
@@ -273,7 +273,7 @@
     if (paintingDisabled())
         return;
 
-    if (!color.alpha() || (!offset.width() && !offset.height() && !blur)) {
+    if (!color.isValid() || !color.alpha() || (!offset.width() && !offset.height() && !blur)) {
         clearShadow();
         return;
     }
@@ -401,6 +401,11 @@
 
 void GraphicsContext::beginTransparencyLayer(float opacity, const FloatRect* bounds)
 {
+    beginTransparencyLayer(opacity, m_state->m_compositeOperator, bounds);
+}
+
+void GraphicsContext::beginTransparencyLayer(float opacity, CompositeOperator op, const FloatRect* bounds)
+{
     if (paintingDisabled())
         return;
 
@@ -412,7 +417,8 @@
 
     SkPaint layerPaint;
     layerPaint.setAlpha(static_cast<unsigned char>(opacity * 255));
-    layerPaint.setXfermodeMode(m_state->m_xferMode);
+    RefPtr<SkXfermode> xferMode = WebCoreCompositeToSkiaComposite(op, m_state->m_blendMode);
+    layerPaint.setXfermode(xferMode.get());
 
     if (bounds) {
         SkRect skBounds = WebCoreFloatRectToSKRect(*bounds);
@@ -697,7 +703,7 @@
     static SkBitmap* misspellBitmap2x[2] = { 0, 0 };
     SkBitmap** misspellBitmap = deviceScaleFactor == 2 ? misspellBitmap2x : misspellBitmap1x;
     if (!misspellBitmap[index]) {
-#if OS(DARWIN)
+#if OS(MACOSX)
         // Match the artwork used by the Mac.
         const int rowPixels = 4 * deviceScaleFactor;
         const int colPixels = 3 * deviceScaleFactor;
@@ -772,7 +778,7 @@
 #endif
     }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     SkScalar originX = WebCoreFloatToSkScalar(pt.x()) * deviceScaleFactor;
     SkScalar originY = WebCoreFloatToSkScalar(pt.y()) * deviceScaleFactor;
 
@@ -1701,14 +1707,19 @@
 #endif
 
     paint->setAntiAlias(m_state->m_shouldAntialias);
-    paint->setXfermodeMode(m_state->m_xferMode);
-    paint->setLooper(m_state->m_looper.get());
+
+    if (!SkXfermode::IsMode(m_state->m_xferMode.get(), SkXfermode::kSrcOver_Mode))
+        paint->setXfermode(m_state->m_xferMode.get());
+
+    if (m_state->m_looper)
+        paint->setLooper(m_state->m_looper.get());
+
     paint->setColorFilter(m_state->m_colorFilter.get());
 }
 
 void GraphicsContext::drawOuterPath(const SkPath& path, SkPaint& paint, int width)
 {
-#if OS(DARWIN)
+#if OS(MACOSX)
     paint.setAlpha(64);
     paint.setStrokeWidth(width);
     paint.setPathEffect(new SkCornerPathEffect((width - 1) * 0.5f))->unref();
@@ -1721,7 +1732,7 @@
 
 void GraphicsContext::drawInnerPath(const SkPath& path, SkPaint& paint, int width)
 {
-#if OS(DARWIN)
+#if OS(MACOSX)
     paint.setAlpha(128);
     paint.setStrokeWidth(width * 0.5f);
     drawPath(path, paint);
@@ -1740,7 +1751,7 @@
         SkIntToScalar(bottomLeft.height()));
 }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 CGColorSpaceRef deviceRGBColorSpaceRef()
 {
     static CGColorSpaceRef deviceSpace = CGColorSpaceCreateDeviceRGB();
@@ -1852,6 +1863,10 @@
     }
 
     paint->setColor(m_state->applyAlpha(color));
+
+    if (!shader)
+        return;
+
     paint->setShader(shader.get());
 }
 
diff --git a/Source/core/platform/graphics/GraphicsContext.h b/Source/core/platform/graphics/GraphicsContext.h
index cc19784..ac6e851 100644
--- a/Source/core/platform/graphics/GraphicsContext.h
+++ b/Source/core/platform/graphics/GraphicsContext.h
@@ -295,6 +295,7 @@
     void drawLineForDocumentMarker(const FloatPoint&, float width, DocumentMarkerLineStyle);
 
     void beginTransparencyLayer(float opacity, const FloatRect* = 0);
+    void beginTransparencyLayer(float opacity, CompositeOperator, const FloatRect* = 0);
     void beginMaskedLayer(const FloatRect&, MaskType = AlphaMaskType);
     void endLayer();
 
@@ -366,7 +367,7 @@
     static void setPathFromConvexPoints(SkPath*, size_t, const FloatPoint*);
     static void setRadii(SkVector*, IntSize, IntSize, IntSize, IntSize);
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     static inline int getFocusRingOutset(int offset) { return offset + 2; }
 #else
     static inline int getFocusRingOutset(int offset) { return 0; }
diff --git a/Source/core/platform/graphics/GraphicsContext3D.h b/Source/core/platform/graphics/GraphicsContext3D.h
index be085a1..4c4aca7 100644
--- a/Source/core/platform/graphics/GraphicsContext3D.h
+++ b/Source/core/platform/graphics/GraphicsContext3D.h
@@ -43,7 +43,7 @@
 #include "wtf/text/WTFString.h"
 
 // FIXME: Find a better way to avoid the name confliction for NO_ERROR.
-#if OS(WINDOWS)
+#if OS(WIN)
 #undef NO_ERROR
 #endif
 
diff --git a/Source/core/platform/graphics/GraphicsContextState.h b/Source/core/platform/graphics/GraphicsContextState.h
index 496ce20..dd5c2b1 100644
--- a/Source/core/platform/graphics/GraphicsContextState.h
+++ b/Source/core/platform/graphics/GraphicsContextState.h
@@ -54,7 +54,7 @@
         , m_fillRule(RULE_NONZERO)
         , m_textDrawingMode(TextModeFill)
         , m_alpha(1)
-        , m_xferMode(SkXfermode::kSrcOver_Mode)
+        , m_xferMode(0)
         , m_compositeOperator(CompositeSourceOver)
         , m_blendMode(BlendModeNormal)
 #if USE(LOW_QUALITY_IMAGE_INTERPOLATION)
@@ -123,7 +123,7 @@
 
     // Common shader state.
     float m_alpha;
-    SkXfermode::Mode m_xferMode;
+    RefPtr<SkXfermode> m_xferMode;
     RefPtr<SkColorFilter> m_colorFilter;
 
     // Compositing control, for the CSS and Canvas compositing spec.
diff --git a/Source/core/platform/graphics/GraphicsLayer.cpp b/Source/core/platform/graphics/GraphicsLayer.cpp
index 6b65051..8955250 100644
--- a/Source/core/platform/graphics/GraphicsLayer.cpp
+++ b/Source/core/platform/graphics/GraphicsLayer.cpp
@@ -39,7 +39,6 @@
 #include "core/platform/graphics/chromium/TransformSkMatrix44Conversions.h"
 #include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/platform/graphics/transforms/RotateTransformOperation.h"
 #include "core/platform/text/TextStream.h"
 
 #include "wtf/CurrentTime.h"
@@ -79,26 +78,6 @@
     return map;
 }
 
-void KeyframeValueList::insert(PassOwnPtr<const AnimationValue> value)
-{
-    for (size_t i = 0; i < m_values.size(); ++i) {
-        const AnimationValue* curValue = m_values[i].get();
-        if (curValue->keyTime() == value->keyTime()) {
-            ASSERT_NOT_REACHED();
-            // insert after
-            m_values.insert(i + 1, value);
-            return;
-        }
-        if (curValue->keyTime() > value->keyTime()) {
-            // insert before
-            m_values.insert(i, value);
-            return;
-        }
-    }
-
-    m_values.append(value);
-}
-
 PassOwnPtr<GraphicsLayer> GraphicsLayer::create(GraphicsLayerFactory* factory, GraphicsLayerClient* client)
 {
     return factory->createGraphicsLayer(client);
@@ -127,6 +106,7 @@
     , m_linkHighlight(0)
     , m_contentsLayerPurpose(NoContentsLayer)
     , m_scrollableArea(0)
+    , m_compositingReasons(WebKit::CompositingReasonUnknown)
 {
 #ifndef NDEBUG
     if (m_client)
@@ -401,119 +381,6 @@
     }
 }
 
-static inline const FilterOperations* filterOperationsAt(const KeyframeValueList& valueList, size_t index)
-{
-    return static_cast<const FilterAnimationValue*>(valueList.at(index))->value();
-}
-
-int GraphicsLayer::validateFilterOperations(const KeyframeValueList& valueList)
-{
-    ASSERT(valueList.property() == AnimatedPropertyWebkitFilter);
-
-    if (valueList.size() < 2)
-        return -1;
-
-    // Empty filters match anything, so find the first non-empty entry as the reference
-    size_t firstIndex = 0;
-    for ( ; firstIndex < valueList.size(); ++firstIndex) {
-        if (filterOperationsAt(valueList, firstIndex)->operations().size() > 0)
-            break;
-    }
-
-    if (firstIndex >= valueList.size())
-        return -1;
-
-    const FilterOperations* firstVal = filterOperationsAt(valueList, firstIndex);
-
-    for (size_t i = firstIndex + 1; i < valueList.size(); ++i) {
-        const FilterOperations* val = filterOperationsAt(valueList, i);
-
-        // An emtpy filter list matches anything.
-        if (val->operations().isEmpty())
-            continue;
-
-        if (!firstVal->operationsMatch(*val))
-            return -1;
-    }
-
-    return firstIndex;
-}
-
-// An "invalid" list is one whose functions don't match, and therefore has to be animated as a Matrix
-// The hasBigRotation flag will always return false if isValid is false. Otherwise hasBigRotation is
-// true if the rotation between any two keyframes is >= 180 degrees.
-
-static inline const TransformOperations* operationsAt(const KeyframeValueList& valueList, size_t index)
-{
-    return static_cast<const TransformAnimationValue*>(valueList.at(index))->value();
-}
-
-int GraphicsLayer::validateTransformOperations(const KeyframeValueList& valueList, bool& hasBigRotation)
-{
-    ASSERT(valueList.property() == AnimatedPropertyWebkitTransform);
-
-    hasBigRotation = false;
-
-    if (valueList.size() < 2)
-        return -1;
-
-    // Empty transforms match anything, so find the first non-empty entry as the reference.
-    size_t firstIndex = 0;
-    for ( ; firstIndex < valueList.size(); ++firstIndex) {
-        if (operationsAt(valueList, firstIndex)->operations().size() > 0)
-            break;
-    }
-
-    if (firstIndex >= valueList.size())
-        return -1;
-
-    const TransformOperations* firstVal = operationsAt(valueList, firstIndex);
-
-    // See if the keyframes are valid.
-    for (size_t i = firstIndex + 1; i < valueList.size(); ++i) {
-        const TransformOperations* val = operationsAt(valueList, i);
-
-        // An emtpy transform list matches anything.
-        if (val->operations().isEmpty())
-            continue;
-
-        if (!firstVal->operationsMatch(*val))
-            return -1;
-    }
-
-    // Keyframes are valid, check for big rotations.
-    double lastRotAngle = 0.0;
-    double maxRotAngle = -1.0;
-
-    for (size_t j = 0; j < firstVal->operations().size(); ++j) {
-        TransformOperation::OperationType type = firstVal->operations().at(j)->getOperationType();
-
-        // if this is a rotation entry, we need to see if any angle differences are >= 180 deg
-        if (type == TransformOperation::RotateX
-            || type == TransformOperation::RotateY
-            || type == TransformOperation::RotateZ
-            || type == TransformOperation::Rotate3D) {
-            lastRotAngle = static_cast<RotateTransformOperation*>(firstVal->operations().at(j).get())->angle();
-
-            if (maxRotAngle < 0)
-                maxRotAngle = fabs(lastRotAngle);
-
-            for (size_t i = firstIndex + 1; i < valueList.size(); ++i) {
-                const TransformOperations* val = operationsAt(valueList, i);
-                double rotAngle = val->operations().isEmpty() ? 0 : (static_cast<RotateTransformOperation*>(val->operations().at(j).get())->angle());
-                double diffAngle = fabs(rotAngle - lastRotAngle);
-                if (diffAngle > maxRotAngle)
-                    maxRotAngle = diffAngle;
-                lastRotAngle = rotAngle;
-            }
-        }
-    }
-
-    hasBigRotation = maxRotAngle >= 180.0;
-
-    return firstIndex;
-}
-
 void GraphicsLayer::updateChildList()
 {
     WebLayer* childHost = m_layer->layer();
@@ -764,7 +631,7 @@
         ts << ")\n";
     }
 
-    if (m_backgroundColor != Color::transparent) {
+    if (m_backgroundColor.isValid() && m_backgroundColor != Color::transparent) {
         writeIndent(ts, indent + 1);
         ts << "(backgroundColor " << m_backgroundColor.nameForRenderTreeAsText() << ")\n";
     }
@@ -1252,6 +1119,8 @@
             return false;
         }
         SkiaImageFilterBuilder builder;
+        FilterOutsets outsets = filters.outsets();
+        builder.setCropOffset(FloatSize(outsets.left(), outsets.top()));
         RefPtr<SkImageFilter> imageFilter = builder.build(filters);
         m_layer->layer()->setFilter(imageFilter.get());
     } else {
diff --git a/Source/core/platform/graphics/GraphicsLayer.h b/Source/core/platform/graphics/GraphicsLayer.h
index ae7a045..7572b3c 100644
--- a/Source/core/platform/graphics/GraphicsLayer.h
+++ b/Source/core/platform/graphics/GraphicsLayer.h
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -27,6 +28,7 @@
 #define GraphicsLayer_h
 
 #include "core/platform/animation/CSSAnimationData.h"
+#include "core/platform/animation/KeyframeValueList.h"
 #include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/FloatPoint.h"
 #include "core/platform/graphics/FloatPoint3D.h"
@@ -35,7 +37,6 @@
 #include "core/platform/graphics/IntRect.h"
 #include "core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
 #include "core/platform/graphics/transforms/TransformationMatrix.h"
 
 #include "wtf/HashMap.h"
@@ -64,127 +65,6 @@
 class Image;
 class ScrollableArea;
 class TextStream;
-class TimingFunction;
-
-// Base class for animation values (also used for transitions). Here to
-// represent values for properties being animated via the GraphicsLayer,
-// without pulling in style-related data from outside of the platform directory.
-// FIXME: Should be moved to its own header file.
-class AnimationValue {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    explicit AnimationValue(double keyTime, PassRefPtr<TimingFunction> timingFunction = 0)
-        : m_keyTime(keyTime)
-        , m_timingFunction(timingFunction)
-    {
-    }
-
-    virtual ~AnimationValue() { }
-
-    double keyTime() const { return m_keyTime; }
-    const TimingFunction* timingFunction() const { return m_timingFunction.get(); }
-    virtual PassOwnPtr<AnimationValue> clone() const = 0;
-
-private:
-    double m_keyTime;
-    RefPtr<TimingFunction> m_timingFunction;
-};
-
-// Used to store one float value of an animation.
-// FIXME: Should be moved to its own header file.
-class FloatAnimationValue : public AnimationValue {
-public:
-    FloatAnimationValue(double keyTime, float value, PassRefPtr<TimingFunction> timingFunction = 0)
-        : AnimationValue(keyTime, timingFunction)
-        , m_value(value)
-    {
-    }
-    virtual PassOwnPtr<AnimationValue> clone() const OVERRIDE { return adoptPtr(new FloatAnimationValue(*this)); }
-
-    float value() const { return m_value; }
-
-private:
-    float m_value;
-};
-
-// Used to store one transform value in a keyframe list.
-// FIXME: Should be moved to its own header file.
-class TransformAnimationValue : public AnimationValue {
-public:
-    explicit TransformAnimationValue(double keyTime, const TransformOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
-        : AnimationValue(keyTime, timingFunction)
-    {
-        if (value)
-            m_value = *value;
-    }
-    virtual PassOwnPtr<AnimationValue> clone() const OVERRIDE { return adoptPtr(new TransformAnimationValue(*this)); }
-
-    const TransformOperations* value() const { return &m_value; }
-
-private:
-    TransformOperations m_value;
-};
-
-// Used to store one filter value in a keyframe list.
-// FIXME: Should be moved to its own header file.
-class FilterAnimationValue : public AnimationValue {
-public:
-    explicit FilterAnimationValue(double keyTime, const FilterOperations* value = 0, PassRefPtr<TimingFunction> timingFunction = 0)
-        : AnimationValue(keyTime, timingFunction)
-    {
-        if (value)
-            m_value = *value;
-    }
-    virtual PassOwnPtr<AnimationValue> clone() const OVERRIDE { return adoptPtr(new FilterAnimationValue(*this)); }
-
-    const FilterOperations* value() const { return &m_value; }
-
-private:
-    FilterOperations m_value;
-};
-
-// Used to store a series of values in a keyframe list.
-// Values will all be of the same type, which can be inferred from the property.
-// FIXME: Should be moved to its own header file.
-class KeyframeValueList {
-public:
-    explicit KeyframeValueList(AnimatedPropertyID property)
-        : m_property(property)
-    {
-    }
-
-    KeyframeValueList(const KeyframeValueList& other)
-        : m_property(other.property())
-    {
-        for (size_t i = 0; i < other.m_values.size(); ++i)
-            m_values.append(other.m_values[i]->clone());
-    }
-
-    KeyframeValueList& operator=(const KeyframeValueList& other)
-    {
-        KeyframeValueList copy(other);
-        swap(copy);
-        return *this;
-    }
-
-    void swap(KeyframeValueList& other)
-    {
-        std::swap(m_property, other.m_property);
-        m_values.swap(other.m_values);
-    }
-
-    AnimatedPropertyID property() const { return m_property; }
-
-    size_t size() const { return m_values.size(); }
-    const AnimationValue* at(size_t i) const { return m_values.at(i).get(); }
-
-    // Insert, sorted by keyTime.
-    void insert(PassOwnPtr<const AnimationValue>);
-
-protected:
-    Vector<OwnPtr<const AnimationValue> > m_values;
-    AnimatedPropertyID m_property;
-};
 
 // FIXME: find a better home for this declaration.
 class LinkHighlightClient {
@@ -434,6 +314,11 @@
     virtual void didScroll() OVERRIDE;
 
 protected:
+    explicit GraphicsLayer(GraphicsLayerClient*);
+    // GraphicsLayerFactoryChromium that wants to create a GraphicsLayer need to be friends.
+    friend class WebKit::GraphicsLayerFactoryChromium;
+
+private:
     // Adds a child without calling updateChildList(), so that adding children
     // can be batched before updating.
     void addChildInternal(GraphicsLayer*);
@@ -443,24 +328,10 @@
     // needs to notifiy the change to the platform layer as needed.
     void clearFilters() { m_filters.clear(); }
 
-    // Given a KeyframeValueList containing filterOperations, return true if the operations are valid.
-    static int validateFilterOperations(const KeyframeValueList&);
-
-    // Given a list of TransformAnimationValues, see if all the operations for each keyframe match. If so
-    // return the index of the KeyframeValueList entry that has that list of operations (it may not be
-    // the first entry because some keyframes might have an empty transform and those match any list).
-    // If the lists don't match return -1. On return, if hasBigRotation is true, functions contain
-    // rotations of >= 180 degrees
-    static int validateTransformOperations(const KeyframeValueList&, bool& hasBigRotation);
-
     void setReplicatedLayer(GraphicsLayer* layer) { m_replicatedLayer = layer; }
 
     int incrementPaintCount() { return ++m_paintCount; }
 
-    // Any factory classes that want to create a GraphicsLayer need to be friends.
-    friend class WebKit::GraphicsLayerFactoryChromium;
-    explicit GraphicsLayer(GraphicsLayerClient*);
-
     static void writeIndent(TextStream&, int indent);
 
     void dumpProperties(TextStream&, int indent, LayerTreeFlags) const;
@@ -520,12 +391,9 @@
 
     int m_paintCount;
 
-    Color m_contentsSolidColor;
-
     OwnPtr<WebKit::WebContentLayer> m_layer;
     OwnPtr<WebKit::WebImageLayer> m_imageLayer;
     OwnPtr<WebKit::WebNinePatchLayer> m_ninePatchLayer;
-    OwnPtr<WebKit::WebSolidColorLayer> m_contentsSolidColorLayer;
     WebKit::WebLayer* m_contentsLayer;
     // We don't have ownership of m_contentsLayer, but we do want to know if a given layer is the
     // same as our current layer in setContentsTo(). Since m_contentsLayer may be deleted at this point,
@@ -538,7 +406,6 @@
     OwnPtr<OpaqueRectTrackingContentLayerDelegate> m_opaqueRectTrackingContentLayerDelegate;
 
     ContentsLayerPurpose m_contentsLayerPurpose;
-    bool m_inSetChildren;
 
     typedef HashMap<String, int> AnimationIdMap;
     AnimationIdMap m_animationIdMap;
diff --git a/Source/core/platform/graphics/GraphicsLayerClient.h b/Source/core/platform/graphics/GraphicsLayerClient.h
index 1728b43..88915eb 100644
--- a/Source/core/platform/graphics/GraphicsLayerClient.h
+++ b/Source/core/platform/graphics/GraphicsLayerClient.h
@@ -47,14 +47,6 @@
 };
 typedef unsigned GraphicsLayerPaintingPhase;
 
-enum AnimatedPropertyID {
-    AnimatedPropertyInvalid,
-    AnimatedPropertyWebkitTransform,
-    AnimatedPropertyOpacity,
-    AnimatedPropertyBackgroundColor,
-    AnimatedPropertyWebkitFilter
-};
-
 enum {
     LayerTreeNormal = 0,
     LayerTreeIncludesDebugInfo = 1 << 0, // Dump extra debugging info like layer addresses.
diff --git a/Source/core/platform/graphics/GraphicsLayerTransform.cpp b/Source/core/platform/graphics/GraphicsLayerTransform.cpp
deleted file mode 100644
index 1382c93..0000000
--- a/Source/core/platform/graphics/GraphicsLayerTransform.cpp
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies)
-
- 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/platform/graphics/GraphicsLayerTransform.h"
-
-namespace WebCore {
-
-GraphicsLayerTransform::GraphicsLayerTransform()
-    : m_anchorPoint(0.5, 0.5, 0)
-    , m_flattening(true)
-    , m_dirty(false) // false by default since all default values would be combined as the identity matrix
-    , m_childrenDirty(false)
-{
-}
-
-void GraphicsLayerTransform::setPosition(const FloatPoint& position)
-{
-    if (m_position == position)
-        return;
-    m_position = position;
-    m_dirty = true;
-}
-
-void GraphicsLayerTransform::setSize(const FloatSize& size)
-{
-    if (m_size == size)
-        return;
-    m_size = size;
-    m_dirty = true;
-}
-
-void GraphicsLayerTransform::setAnchorPoint(const FloatPoint3D& anchorPoint)
-{
-    if (m_anchorPoint == anchorPoint)
-        return;
-    m_anchorPoint = anchorPoint;
-    m_dirty = true;
-}
-
-void GraphicsLayerTransform::setFlattening(bool flattening)
-{
-    if (m_flattening == flattening)
-        return;
-    m_flattening = flattening;
-    m_dirty = true;
-}
-
-void GraphicsLayerTransform::setLocalTransform(const TransformationMatrix& transform)
-{
-    if (m_local == transform)
-        return;
-    m_local = transform;
-    m_dirty = true;
-}
-
-void GraphicsLayerTransform::setChildrenTransform(const TransformationMatrix& transform)
-{
-    if (m_children == transform)
-        return;
-    m_children = transform;
-    m_dirty = true;
-}
-
-TransformationMatrix GraphicsLayerTransform::combined()
-{
-    ASSERT(!m_dirty);
-    return m_combined;
-}
-
-TransformationMatrix GraphicsLayerTransform::combinedForChildren()
-{
-    ASSERT(!m_dirty);
-    if (m_childrenDirty)
-        combineTransformsForChildren();
-    return m_combinedForChildren;
-}
-
-void GraphicsLayerTransform::combineTransforms(const TransformationMatrix& parentTransform)
-{
-    float originX = m_anchorPoint.x() * m_size.width();
-    float originY = m_anchorPoint.y() * m_size.height();
-    m_combined =
-        TransformationMatrix(parentTransform)
-            .translate3d(originX + m_position.x(), originY + m_position.y(), m_anchorPoint.z() )
-            .multiply(m_local);
-
-    // The children transform will take it from here, if it gets used.
-    m_combinedForChildren = m_combined;
-    m_combined.translate3d(-originX, -originY, -m_anchorPoint.z());
-
-    m_dirty = false;
-    m_childrenDirty = true;
-}
-
-void GraphicsLayerTransform::combineTransformsForChildren()
-{
-    ASSERT(!m_dirty);
-    ASSERT(m_childrenDirty);
-
-    float originX = m_anchorPoint.x() * m_size.width();
-    float originY = m_anchorPoint.y() * m_size.height();
-
-    // In case a parent had preserves3D and this layer has not, flatten our children.
-    if (m_flattening)
-        m_combinedForChildren = m_combinedForChildren.to2dTransform();
-    m_combinedForChildren.multiply(m_children);
-    m_combinedForChildren.translate3d(-originX, -originY, -m_anchorPoint.z());
-
-    m_childrenDirty = false;
-}
-
-}
diff --git a/Source/core/platform/graphics/GraphicsLayerTransform.h b/Source/core/platform/graphics/GraphicsLayerTransform.h
deleted file mode 100644
index b241fbb..0000000
--- a/Source/core/platform/graphics/GraphicsLayerTransform.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies)
-
- 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 GraphicsLayerTransform_h
-#define GraphicsLayerTransform_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatPoint3D.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-
-namespace WebCore {
-
-class GraphicsLayerTransform {
-public:
-    GraphicsLayerTransform();
-    void setPosition(const FloatPoint&);
-    void setSize(const FloatSize&);
-    void setAnchorPoint(const FloatPoint3D&);
-    void setFlattening(bool);
-    void setLocalTransform(const TransformationMatrix&);
-    void setChildrenTransform(const TransformationMatrix&);
-    TransformationMatrix combined();
-    TransformationMatrix combinedForChildren();
-
-    void combineTransforms(const TransformationMatrix& parentTransform);
-
-private:
-    void combineTransformsForChildren();
-
-    FloatPoint3D m_anchorPoint;
-    FloatPoint m_position;
-    FloatSize m_size;
-    bool m_flattening;
-    bool m_dirty;
-    bool m_childrenDirty;
-
-    TransformationMatrix m_local;
-    TransformationMatrix m_children;
-    TransformationMatrix m_combined;
-    TransformationMatrix m_combinedForChildren;
-};
-
-}
-
-#endif // GraphicsLayerTransform_h
diff --git a/Source/core/platform/graphics/Image.h b/Source/core/platform/graphics/Image.h
index 953090b..222866e 100644
--- a/Source/core/platform/graphics/Image.h
+++ b/Source/core/platform/graphics/Image.h
@@ -67,9 +67,9 @@
     virtual bool isBitmapImage() const { return false; }
     virtual bool currentFrameKnownToBeOpaque() = 0;
 
-    // Derived classes should override this if they can assure that
-    // the image contains only resources from its own security origin.
-    virtual bool hasSingleSecurityOrigin() const { return false; }
+    // Derived classes should override this if they can assure that the current
+    // image frame contains only resources from its own security origin.
+    virtual bool currentFrameHasSingleSecurityOrigin() const { return false; }
 
     static Image* nullImage();
     bool isNull() const { return size().isEmpty(); }
diff --git a/Source/core/platform/graphics/ImageBuffer.cpp b/Source/core/platform/graphics/ImageBuffer.cpp
index 96280d0..1ecdaaf 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, OwnPtr<Canvas2DLayerBridge>* outLayerBridge, OpacityMode opacityMode)
+static SkCanvas* createAcceleratedCanvas(const IntSize& size, Canvas2DLayerBridgePtr* outLayerBridge, OpacityMode opacityMode)
 {
     RefPtr<GraphicsContext3D> context3D = SharedGraphicsContext3D::get();
     if (!context3D)
@@ -177,7 +177,7 @@
 
 bool ImageBuffer::isValid() const
 {
-    if (m_layerBridge.get())
+    if (m_layerBridge)
         return const_cast<Canvas2DLayerBridge*>(m_layerBridge.get())->isValid();
     return true;
 }
diff --git a/Source/core/platform/graphics/ImageBuffer.h b/Source/core/platform/graphics/ImageBuffer.h
index 7db503b..b34b4ea 100644
--- a/Source/core/platform/graphics/ImageBuffer.h
+++ b/Source/core/platform/graphics/ImageBuffer.h
@@ -34,6 +34,7 @@
 #include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/graphics/GraphicsTypes3D.h"
 #include "core/platform/graphics/IntSize.h"
+#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
 #include "core/platform/graphics/transforms/AffineTransform.h"
 #include "wtf/Forward.h"
 #include "wtf/OwnPtr.h"
@@ -48,7 +49,6 @@
 
 namespace WebCore {
 
-class Canvas2DLayerBridge;
 class Image;
 class ImageData;
 class IntPoint;
@@ -144,7 +144,7 @@
     float m_resolutionScale;
     OwnPtr<SkCanvas> m_canvas;
     OwnPtr<GraphicsContext> m_context;
-    OwnPtr<Canvas2DLayerBridge> m_layerBridge;
+    Canvas2DLayerBridgePtr m_layerBridge;
 
     // This constructor will place its success into the given out-variable
     // so that create() knows when it should return failure.
diff --git a/Source/core/platform/graphics/IntPoint.h b/Source/core/platform/graphics/IntPoint.h
index 97489d8..80746c4 100644
--- a/Source/core/platform/graphics/IntPoint.h
+++ b/Source/core/platform/graphics/IntPoint.h
@@ -30,7 +30,7 @@
 #include "core/platform/graphics/IntSize.h"
 #include "wtf/MathExtras.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 typedef struct CGPoint CGPoint;
 #ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
 typedef struct CGPoint NSPoint;
@@ -88,7 +88,7 @@
         return IntPoint(m_y, m_x);
     }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     explicit IntPoint(const CGPoint&); // don't do this implicitly since it's lossy
     operator CGPoint() const;
 
diff --git a/Source/core/platform/graphics/IntRect.h b/Source/core/platform/graphics/IntRect.h
index 22ea0d7..a2e3492 100644
--- a/Source/core/platform/graphics/IntRect.h
+++ b/Source/core/platform/graphics/IntRect.h
@@ -30,7 +30,7 @@
 #include "wtf/FastAllocBase.h"
 #include "wtf/Vector.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 typedef struct CGRect CGRect;
 
 #ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
@@ -152,7 +152,7 @@
 
     IntRect transposedRect() const { return IntRect(m_location.transposedPoint(), m_size.transposedSize()); }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     operator CGRect() const;
 #if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
     operator NSRect() const;
@@ -193,7 +193,7 @@
     return a.location() != b.location() || a.size() != b.size();
 }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 IntRect enclosingIntRect(const CGRect&);
 #if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
 IntRect enclosingIntRect(const NSRect&);
diff --git a/Source/core/platform/graphics/IntSize.h b/Source/core/platform/graphics/IntSize.h
index 1844e04..44d6c72 100644
--- a/Source/core/platform/graphics/IntSize.h
+++ b/Source/core/platform/graphics/IntSize.h
@@ -27,7 +27,7 @@
 #ifndef IntSize_h
 #define IntSize_h
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 typedef struct CGSize CGSize;
 
 #ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
@@ -112,7 +112,7 @@
         return IntSize(m_height, m_width);
     }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     explicit IntSize(const CGSize&); // don't do this implicitly since it's lossy
     operator CGSize() const;
 
diff --git a/Source/core/platform/graphics/LayoutBoxExtent.cpp b/Source/core/platform/graphics/LayoutBoxExtent.cpp
index 88b262e..2c3422b 100644
--- a/Source/core/platform/graphics/LayoutBoxExtent.cpp
+++ b/Source/core/platform/graphics/LayoutBoxExtent.cpp
@@ -31,6 +31,8 @@
 #include "config.h"
 #include "core/platform/graphics/LayoutBoxExtent.h"
 
+#include "wtf/Assertions.h"
+
 namespace WebCore {
 
 LayoutUnit LayoutBoxExtent::logicalTop(WritingMode writingMode) const
diff --git a/Source/core/platform/graphics/Path.cpp b/Source/core/platform/graphics/Path.cpp
index 04e3045..baaa013 100644
--- a/Source/core/platform/graphics/Path.cpp
+++ b/Source/core/platform/graphics/Path.cpp
@@ -3,6 +3,7 @@
  *                     2006 Rob Buis <buis@kde.org>
  * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
  * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -278,6 +279,10 @@
 
 void Path::addArc(const FloatPoint& p, float radius, float startAngle, float endAngle, bool anticlockwise)
 {
+    ASSERT(std::abs(endAngle - startAngle) < 4 * piFloat);
+    ASSERT(startAngle >= 0 && startAngle < 2 * piFloat);
+    ASSERT((anticlockwise && (startAngle - endAngle) >= 0) || (!anticlockwise && (endAngle - startAngle) >= 0));
+
     SkScalar cx = WebCoreFloatToSkScalar(p.x());
     SkScalar cy = WebCoreFloatToSkScalar(p.y());
     SkScalar radiusScalar = WebCoreFloatToSkScalar(radius);
@@ -289,26 +294,24 @@
     float sweep = endAngle - startAngle;
     SkScalar startDegrees = WebCoreFloatToSkScalar(startAngle * 180 / piFloat);
     SkScalar sweepDegrees = WebCoreFloatToSkScalar(sweep * 180 / piFloat);
-    // Check for a circle.
-    if (sweepDegrees >= s360 || sweepDegrees <= -s360) {
-        // Move to the start position (0 sweep means we add a single point).
-        m_path.arcTo(oval, startDegrees, 0, false);
-        // Draw the circle.
-        m_path.addOval(oval, anticlockwise ?
-            SkPath::kCCW_Direction : SkPath::kCW_Direction);
-        // Force a moveTo the end position.
-        m_path.arcTo(oval, startDegrees + sweepDegrees, 0, true);
+
+    // We can't use SkPath::addOval(), because addOval() makes new sub-path. addOval() calls moveTo() and close() internally.
+
+    // Use s180, not s360, because SkPath::arcTo(oval, angle, s360, false) draws nothing.
+    SkScalar s180 = SkIntToScalar(180);
+    if (sweepDegrees >= s360) {
+        // SkPath::arcTo can't handle the sweepAngle that is equal to or greater than 2Pi.
+        m_path.arcTo(oval, startDegrees, s180, false);
+        m_path.arcTo(oval, startDegrees + s180, s180, false);
+        m_path.arcTo(oval, startDegrees + s360, sweepDegrees - s360, false);
         return;
     }
-
-    // Counterclockwise arcs should be drawn with negative sweeps, while
-    // clockwise arcs should be drawn with positive sweeps. Check to see
-    // if the situation is reversed and correct it by adding or subtracting
-    // a full circle
-    if (anticlockwise && sweepDegrees > 0)
-        sweepDegrees -= s360;
-    else if (!anticlockwise && sweepDegrees < 0)
-        sweepDegrees += s360;
+    if (sweepDegrees <= -s360) {
+        m_path.arcTo(oval, startDegrees, -s180, false);
+        m_path.arcTo(oval, startDegrees - s180, -s180, false);
+        m_path.arcTo(oval, startDegrees - s360, sweepDegrees + s360, false);
+        return;
+    }
 
     m_path.arcTo(oval, startDegrees, sweepDegrees, false);
 }
@@ -320,6 +323,10 @@
 
 void Path::addEllipse(const FloatPoint& p, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise)
 {
+    ASSERT(std::abs(endAngle - startAngle) < 4 * piFloat);
+    ASSERT(startAngle >= 0 && startAngle < 2 * piFloat);
+    ASSERT((anticlockwise && (startAngle - endAngle) >= 0) || (!anticlockwise && (endAngle - startAngle) >= 0));
+
     // Optimize the common case of an entire ellipse.
     SkScalar twoPiScalar = WebCoreFloatToSkScalar(2 * piFloat);
     SkScalar endAngleScalar = WebCoreFloatToSkScalar(endAngle);
diff --git a/Source/core/platform/graphics/Pattern.cpp b/Source/core/platform/graphics/Pattern.cpp
index 35b6267..58159fe 100644
--- a/Source/core/platform/graphics/Pattern.cpp
+++ b/Source/core/platform/graphics/Pattern.cpp
@@ -37,12 +37,12 @@
 namespace WebCore {
 
 Pattern::Pattern(PassRefPtr<Image> image, bool repeatX, bool repeatY)
-    : m_tileImage(image)
-    , m_repeatX(repeatX)
+    : m_repeatX(repeatX)
     , m_repeatY(repeatY)
     , m_externalMemoryAllocated(0)
 {
-    ASSERT(m_tileImage);
+    ASSERT(image);
+    m_tileImage = image->nativeImageForCurrentFrame();
 }
 
 Pattern::~Pattern()
@@ -56,12 +56,11 @@
     if (m_pattern)
         return m_pattern.get();
 
-    RefPtr<NativeImageSkia> image = m_tileImage->nativeImageForCurrentFrame();
     // If we don't have a bitmap, return a transparent shader.
-    if (!image)
+    if (!m_tileImage)
         m_pattern = adoptRef(new SkColorShader(SK_ColorTRANSPARENT));
     else if (m_repeatX && m_repeatY)
-        m_pattern = adoptRef(SkShader::CreateBitmapShader(image->bitmap(), SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
+        m_pattern = adoptRef(SkShader::CreateBitmapShader(m_tileImage->bitmap(), SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
     else {
         // Skia does not have a "draw the tile only once" option. Clamp_TileMode
         // repeats the last line of the image after drawing one tile. To avoid
@@ -77,11 +76,11 @@
         // original, then copy the orignal into it.
         // FIXME: Is there a better way to pad (not scale) an image in skia?
         SkBitmap bm2;
-        bm2.setConfig(image->bitmap().config(), image->bitmap().width() + expandW, image->bitmap().height() + expandH);
+        bm2.setConfig(m_tileImage->bitmap().config(), m_tileImage->bitmap().width() + expandW, m_tileImage->bitmap().height() + expandH);
         bm2.allocPixels();
         bm2.eraseARGB(0x00, 0x00, 0x00, 0x00);
         SkCanvas canvas(bm2);
-        canvas.drawBitmap(image->bitmap(), 0, 0);
+        canvas.drawBitmap(m_tileImage->bitmap(), 0, 0);
         bm2.setImmutable();
         m_pattern = adoptRef(SkShader::CreateBitmapShader(bm2, tileModeX, tileModeY));
 
diff --git a/Source/core/platform/graphics/Pattern.h b/Source/core/platform/graphics/Pattern.h
index 84b441c..925e91d 100644
--- a/Source/core/platform/graphics/Pattern.h
+++ b/Source/core/platform/graphics/Pattern.h
@@ -49,8 +49,6 @@
     }
     ~Pattern();
 
-    Image* tileImage() const { return m_tileImage.get(); }
-
     SkShader* shader();
 
     void setPatternSpaceTransform(const AffineTransform& patternSpaceTransformation);
@@ -62,7 +60,7 @@
 private:
     Pattern(PassRefPtr<Image>, bool repeatX, bool repeatY);
 
-    RefPtr<Image> m_tileImage;
+    RefPtr<NativeImageSkia> m_tileImage;
     bool m_repeatX;
     bool m_repeatY;
     AffineTransform m_patternSpaceTransformation;
diff --git a/Source/core/platform/graphics/ShadowBlur.cpp b/Source/core/platform/graphics/ShadowBlur.cpp
index 4028b6d..aa0bf4c 100644
--- a/Source/core/platform/graphics/ShadowBlur.cpp
+++ b/Source/core/platform/graphics/ShadowBlur.cpp
@@ -30,6 +30,7 @@
 #include "core/platform/graphics/ShadowBlur.h"
 
 #include "wtf/MathExtras.h"
+#include <algorithm>
 
 using namespace std;
 
@@ -55,7 +56,7 @@
     m_blurRadius = m_blurRadius.shrunkTo(FloatSize(128, 128));
 
     // The type of shadow is decided by the blur radius, shadow offset, and shadow color.
-    if (!m_color.alpha()) {
+    if (!m_color.isValid() || !m_color.alpha()) {
         // Can't paint the shadow with invalid or invisible color.
         m_type = NoShadow;
     } else if (m_blurRadius.width() > 0 || m_blurRadius.height() > 0) {
diff --git a/Source/core/platform/graphics/SimpleFontData.h b/Source/core/platform/graphics/SimpleFontData.h
index 8b15f55..1d0a1ed 100644
--- a/Source/core/platform/graphics/SimpleFontData.h
+++ b/Source/core/platform/graphics/SimpleFontData.h
@@ -41,7 +41,7 @@
 #include "wtf/text/StringHash.h"
 #include "wtf/UnusedParam.h"
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include "wtf/RetainPtr.h"
 #endif
 
@@ -134,7 +134,7 @@
     float adjustedSpaceWidth() const { return m_adjustedSpaceWidth; }
     void setSpaceWidth(float spaceWidth) { m_spaceWidth = spaceWidth; }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     float syntheticBoldOffset() const { return m_syntheticBoldOffset; }
 #endif
 
@@ -168,16 +168,16 @@
     virtual String description() const;
 #endif
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     const SimpleFontData* getCompositeFontReferenceFontData(NSFont *key) const;
     NSFont* getNSFont() const { return m_platformData.font(); }
 #endif
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     CFDictionaryRef getCFStringAttributes(TypesettingFeatures, FontOrientation) const;
 #endif
 
-#if OS(DARWIN) || USE(HARFBUZZ)
+#if OS(MACOSX) || USE(HARFBUZZ)
     bool canRenderCombiningCharacterSequence(const UChar*, size_t) const;
 #endif
 
@@ -245,7 +245,7 @@
         RefPtr<SimpleFontData> brokenIdeograph;
         RefPtr<SimpleFontData> verticalRightOrientation;
         RefPtr<SimpleFontData> uprightOrientation;
-#if OS(DARWIN)
+#if OS(MACOSX)
         mutable RetainPtr<CFMutableDictionaryRef> compositeFontReferences;
 #endif
 
@@ -258,13 +258,13 @@
 
     mutable OwnPtr<DerivedFontData> m_derivedFontData;
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     float m_syntheticBoldOffset;
 
     mutable HashMap<unsigned, RetainPtr<CFDictionaryRef> > m_CFStringAttributes;
 #endif
 
-#if OS(DARWIN) || USE(HARFBUZZ)
+#if OS(MACOSX) || USE(HARFBUZZ)
     mutable OwnPtr<HashMap<String, bool> > m_combiningCharacterSequenceSupport;
 #endif
 };
@@ -301,7 +301,7 @@
         width = m_fontData->widthForSVGGlyph(glyph, m_platformData.size());
 #if ENABLE(OPENTYPE_VERTICAL)
     else if (m_verticalData)
-#if OS(DARWIN)
+#if OS(MACOSX)
         width = m_verticalData->advanceHeight(this, glyph) + m_syntheticBoldOffset;
 #else
         width = m_verticalData->advanceHeight(this, glyph);
diff --git a/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp b/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
index 58768f9..5650649 100644
--- a/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
+++ b/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
@@ -27,8 +27,9 @@
 #include "core/platform/graphics/chromium/AnimationTranslationUtil.h"
 
 #include "core/css/LengthFunctions.h"
+#include "core/platform/animation/CSSAnimationData.h"
+#include "core/platform/animation/KeyframeValueList.h"
 #include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/GraphicsLayer.h"
 #include "core/platform/graphics/chromium/TransformSkMatrix44Conversions.h"
 #include "core/platform/graphics/transforms/InterpolatedTransformOperation.h"
 #include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
@@ -221,7 +222,7 @@
         // If there hasn't been a timing function associated with this keyframe, use the
         // animation's timing function, if we have one.
         if (!originalTimingFunction && animation->isTimingFunctionSet())
-            originalTimingFunction = animation->timingFunction().get();
+            originalTimingFunction = animation->timingFunction();
 
         // Ease is the default timing function.
         WebKit::WebAnimationCurve::TimingFunctionType timingFunctionType = WebKit::WebAnimationCurve::TimingFunctionTypeEase;
diff --git a/Source/core/platform/graphics/chromium/AnimationTranslationUtilTest.cpp b/Source/core/platform/graphics/chromium/AnimationTranslationUtilTest.cpp
index 9d25fd7..666204e 100644
--- a/Source/core/platform/graphics/chromium/AnimationTranslationUtilTest.cpp
+++ b/Source/core/platform/graphics/chromium/AnimationTranslationUtilTest.cpp
@@ -27,7 +27,7 @@
 #include "core/platform/graphics/chromium/AnimationTranslationUtil.h"
 
 #include "core/platform/animation/CSSAnimationData.h"
-#include "core/platform/graphics/GraphicsLayer.h" // For KeyframeValueList
+#include "core/platform/animation/KeyframeValueList.h"
 #include "core/platform/graphics/IntSize.h"
 #include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
 #include "core/platform/graphics/transforms/RotateTransformOperation.h"
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
index 415175a..26873f1 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
@@ -44,6 +44,21 @@
 
 namespace WebCore {
 
+void Canvas2DLayerBridgePtr::clear()
+{
+    if (m_ptr) {
+        m_ptr->destroy();
+        m_ptr.clear();
+    }
+}
+
+Canvas2DLayerBridgePtr& Canvas2DLayerBridgePtr::operator=(const PassRefPtr<Canvas2DLayerBridge>& other)
+{
+    clear();
+    m_ptr = other;
+    return *this;
+}
+
 static SkSurface* createSurface(GraphicsContext3D* context3D, const IntSize& size)
 {
     ASSERT(!context3D->webContext()->isContextLost());
@@ -59,14 +74,15 @@
     return SkSurface::NewRenderTarget(gr, info);
 }
 
-PassOwnPtr<Canvas2DLayerBridge> Canvas2DLayerBridge::create(PassRefPtr<GraphicsContext3D> context, const IntSize& size, OpacityMode opacityMode)
+PassRefPtr<Canvas2DLayerBridge> Canvas2DLayerBridge::create(PassRefPtr<GraphicsContext3D> context, const IntSize& size, OpacityMode opacityMode)
 {
     TRACE_EVENT_INSTANT0("test_gpu", "Canvas2DLayerBridgeCreation");
     SkAutoTUnref<SkSurface> surface(createSurface(context.get(), size));
-    if (!surface.get())
-        return PassOwnPtr<Canvas2DLayerBridge>();
+    if (!surface.get()) {
+        return PassRefPtr<Canvas2DLayerBridge>();
+    }
     SkDeferredCanvas* canvas = SkDeferredCanvas::Create(surface.get());
-    OwnPtr<Canvas2DLayerBridge> layerBridge = adoptPtr(new Canvas2DLayerBridge(context, canvas, opacityMode));
+    RefPtr<Canvas2DLayerBridge> layerBridge = adoptRef(new Canvas2DLayerBridge(context, canvas, opacityMode));
     return layerBridge.release();
 }
 
@@ -77,6 +93,7 @@
     , m_didRecordDrawCommand(false)
     , m_surfaceIsValid(true)
     , m_framesPending(0)
+    , m_destructionInProgress(false)
     , m_rateLimitingEnabled(false)
     , m_next(0)
     , m_prev(0)
@@ -95,16 +112,40 @@
 
 Canvas2DLayerBridge::~Canvas2DLayerBridge()
 {
-    GraphicsLayer::unregisterContentsLayer(m_layer->layer());
-    Canvas2DLayerManager::get().layerToBeDestroyed(this);
-    m_canvas->setNotificationClient(0);
-    m_mailboxes.clear();
-    m_layer->clearTexture();
+    ASSERT(m_destructionInProgress);
     m_layer.clear();
+    Vector<MailboxInfo>::iterator mailboxInfo;
+    for (mailboxInfo = m_mailboxes.begin(); mailboxInfo < m_mailboxes.end(); mailboxInfo++) {
+        ASSERT(mailboxInfo->m_status != MailboxInUse);
+        if (mailboxInfo->m_status == MailboxReleased) {
+            if (mailboxInfo->m_mailbox.syncPoint) {
+                context()->waitSyncPoint(mailboxInfo->m_mailbox.syncPoint);
+                mailboxInfo->m_mailbox.syncPoint = 0;
+            }
+            // Invalidate texture state in case the compositor altered it since the copy-on-write.
+            mailboxInfo->m_image->getTexture()->invalidateCachedState();
+        }
+    }
+    m_mailboxes.clear();
+}
+
+void Canvas2DLayerBridge::destroy()
+{
+    ASSERT(!m_destructionInProgress);
+    m_destructionInProgress = true;
+    GraphicsLayer::unregisterContentsLayer(m_layer->layer());
+    m_canvas->setNotificationClient(0);
+    m_layer->clearTexture();
+    Canvas2DLayerManager::get().layerToBeDestroyed(this);
+    // Orphaning the layer is required to trigger the recration of a new layer
+    // in the case where destruction is caused by a canvas resize. Test:
+    // virtual/gpu/fast/canvas/canvas-resize-after-paint-without-layout.html
+    m_layer->layer()->removeFromParent();
 }
 
 void Canvas2DLayerBridge::limitPendingFrames()
 {
+    ASSERT(!m_destructionInProgress);
     if (m_didRecordDrawCommand) {
         m_framesPending++;
         m_didRecordDrawCommand = false;
@@ -121,6 +162,7 @@
 
 void Canvas2DLayerBridge::prepareForDraw()
 {
+    ASSERT(!m_destructionInProgress);
     ASSERT(m_layer);
     if (!isValid()) {
         if (m_canvas) {
@@ -134,6 +176,7 @@
 
 void Canvas2DLayerBridge::storageAllocatedForRecordingChanged(size_t bytesAllocated)
 {
+    ASSERT(!m_destructionInProgress);
     intptr_t delta = (intptr_t)bytesAllocated - (intptr_t)m_bytesAllocated;
     m_bytesAllocated = bytesAllocated;
     Canvas2DLayerManager::get().layerAllocatedStorageChanged(this, delta);
@@ -141,17 +184,20 @@
 
 size_t Canvas2DLayerBridge::storageAllocatedForRecording()
 {
+    ASSERT(!m_destructionInProgress);
     return m_canvas->storageAllocatedForRecording();
 }
 
 void Canvas2DLayerBridge::flushedDrawCommands()
 {
+    ASSERT(!m_destructionInProgress);
     storageAllocatedForRecordingChanged(storageAllocatedForRecording());
     m_framesPending = 0;
 }
 
 void Canvas2DLayerBridge::skippedPendingDrawCommands()
 {
+    ASSERT(!m_destructionInProgress);
     // Stop triggering the rate limiter if SkDeferredCanvas is detecting
     // and optimizing overdraw.
     setRateLimitingEnabled(false);
@@ -160,6 +206,7 @@
 
 void Canvas2DLayerBridge::setRateLimitingEnabled(bool enabled)
 {
+    ASSERT(!m_destructionInProgress || !enabled);
     if (m_rateLimitingEnabled != enabled) {
         m_rateLimitingEnabled = enabled;
         m_layer->setRateLimitContext(m_rateLimitingEnabled);
@@ -168,6 +215,7 @@
 
 size_t Canvas2DLayerBridge::freeMemoryIfPossible(size_t bytesToFree)
 {
+    ASSERT(!m_destructionInProgress);
     size_t bytesFreed = m_canvas->freeMemoryIfPossible(bytesToFree);
     if (bytesFreed)
         Canvas2DLayerManager::get().layerAllocatedStorageChanged(this, -((intptr_t)bytesFreed));
@@ -177,6 +225,7 @@
 
 void Canvas2DLayerBridge::flush()
 {
+    ASSERT(!m_destructionInProgress);
     if (m_canvas->hasPendingCommands()) {
         TRACE_EVENT0("cc", "Canvas2DLayerBridge::flush");
         m_canvas->flush();
@@ -196,6 +245,8 @@
 bool Canvas2DLayerBridge::isValid()
 {
     ASSERT(m_layer);
+    if (m_destructionInProgress)
+        return false;
     if (m_context->webContext()->isContextLost() || !m_surfaceIsValid) {
         // Attempt to recover.
         m_layer->clearTexture();
@@ -221,12 +272,18 @@
     if (!m_surfaceIsValid)
         setRateLimitingEnabled(false);
     return m_surfaceIsValid;
-
 }
 
 bool Canvas2DLayerBridge::prepareMailbox(WebKit::WebExternalTextureMailbox* outMailbox, WebKit::WebExternalBitmap* bitmap)
 {
-    ASSERT(!bitmap);
+    if (bitmap) {
+        // Using accelerated 2d canvas with software renderer, which
+        // should only happen in tests that use fake graphics contexts.
+        // In this case, we do not care about producing any results for
+        // compositing.
+        m_canvas->silentFlush();
+        return false;
+    }
     if (!isValid())
         return false;
     // Release to skia textures that were previouosly released by the
@@ -278,11 +335,16 @@
     // we must dirty the context.
     m_context->grContext()->resetContext(kTextureBinding_GrGLBackendState);
 
+    // set m_parentLayerBridge to make sure 'this' stays alive as long as it has
+    // live mailboxes
+    ASSERT(!mailboxInfo->m_parentLayerBridge);
+    mailboxInfo->m_parentLayerBridge = this;
     *outMailbox = mailboxInfo->m_mailbox;
     return true;
 }
 
 Canvas2DLayerBridge::MailboxInfo* Canvas2DLayerBridge::createMailboxInfo() {
+    ASSERT(!m_destructionInProgress);
     MailboxInfo* mailboxInfo;
     for (mailboxInfo = m_mailboxes.begin(); mailboxInfo < m_mailboxes.end(); mailboxInfo++) {
         if (mailboxInfo->m_status == MailboxAvailable) {
@@ -313,6 +375,11 @@
             mailboxInfo->m_mailbox.syncPoint = mailbox.syncPoint;
             ASSERT(mailboxInfo->m_status == MailboxInUse);
             mailboxInfo->m_status = MailboxReleased;
+            // Trigger Canvas2DLayerBridge self-destruction if this is the
+            // last live mailbox and the layer bridge is not externally
+            // referenced.
+            ASSERT(mailboxInfo->m_parentLayerBridge.get() == this);
+            mailboxInfo->m_parentLayerBridge.clear();
             return;
         }
     }
@@ -326,12 +393,14 @@
 
 void Canvas2DLayerBridge::contextAcquired()
 {
+    ASSERT(!m_destructionInProgress);
     Canvas2DLayerManager::get().layerDidDraw(this);
     m_didRecordDrawCommand = true;
 }
 
 unsigned Canvas2DLayerBridge::backBufferTexture()
 {
+    ASSERT(!m_destructionInProgress);
     if (!isValid())
         return 0;
     contextAcquired();
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
index 12f87fa..4771925 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
@@ -43,7 +43,25 @@
 
 namespace WebCore {
 
-class Canvas2DLayerBridge : public WebKit::WebExternalTextureLayerClient, public SkDeferredCanvas::NotificationClient, public DoublyLinkedListNode<Canvas2DLayerBridge> {
+class Canvas2DLayerBridge;
+class PassCanvas2DLayerBridgePtr;
+
+class Canvas2DLayerBridgePtr {
+public:
+    Canvas2DLayerBridgePtr() { }
+    Canvas2DLayerBridgePtr(const PassRefPtr<Canvas2DLayerBridge>& ptr) { m_ptr = ptr; }
+    ~Canvas2DLayerBridgePtr() { clear(); }
+    Canvas2DLayerBridge* operator->() const { return m_ptr.get(); }
+    Canvas2DLayerBridgePtr& operator=(const PassRefPtr<Canvas2DLayerBridge>&);
+    Canvas2DLayerBridge* get() const { return m_ptr.get(); }
+    operator bool () const { return m_ptr; }
+    void clear();
+    PassRefPtr<Canvas2DLayerBridge> release() WARN_UNUSED_RETURN { return m_ptr.release(); }
+private:
+    RefPtr<Canvas2DLayerBridge> m_ptr;
+};
+
+class Canvas2DLayerBridge : public WebKit::WebExternalTextureLayerClient, public SkDeferredCanvas::NotificationClient, public DoublyLinkedListNode<Canvas2DLayerBridge>, public RefCounted<Canvas2DLayerBridge> {
     WTF_MAKE_NONCOPYABLE(Canvas2DLayerBridge);
 public:
     enum OpacityMode {
@@ -51,7 +69,7 @@
         NonOpaque
     };
 
-    static PassOwnPtr<Canvas2DLayerBridge> create(PassRefPtr<GraphicsContext3D>, const IntSize&, OpacityMode);
+    static PassRefPtr<Canvas2DLayerBridge> create(PassRefPtr<GraphicsContext3D>, const IntSize&, OpacityMode);
 
     virtual ~Canvas2DLayerBridge();
 
@@ -82,6 +100,8 @@
     bool isValid();
 
 protected:
+    void destroy();
+    friend class Canvas2DLayerBridgePtr;
     Canvas2DLayerBridge(PassRefPtr<GraphicsContext3D>, SkDeferredCanvas*, OpacityMode);
     void setRateLimitingEnabled(bool);
 
@@ -92,6 +112,7 @@
     bool m_didRecordDrawCommand;
     bool m_surfaceIsValid;
     int m_framesPending;
+    bool m_destructionInProgress;
     bool m_rateLimitingEnabled;
 
     friend class WTF::DoublyLinkedListNode<Canvas2DLayerBridge>;
@@ -108,6 +129,7 @@
         WebKit::WebExternalTextureMailbox m_mailbox;
         SkAutoTUnref<SkImage> m_image;
         MailboxStatus m_status;
+        RefPtr<Canvas2DLayerBridge> m_parentLayerBridge;
 
         MailboxInfo(const MailboxInfo&);
         MailboxInfo() {}
@@ -117,7 +139,5 @@
     uint32_t m_lastImageId;
     Vector<MailboxInfo> m_mailboxes;
 };
-
 }
-
 #endif
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp b/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
index 7af3be0..48cbd7d 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
@@ -57,9 +57,9 @@
 
 class FakeCanvas2DLayerBridge : public Canvas2DLayerBridge {
 public:
-    static PassOwnPtr<FakeCanvas2DLayerBridge> create(PassRefPtr<GraphicsContext3D> context, SkDeferredCanvas* canvas, OpacityMode opacityMode)
+    static PassRefPtr<Canvas2DLayerBridge> create(PassRefPtr<GraphicsContext3D> context, SkDeferredCanvas* canvas, OpacityMode opacityMode)
     {
-        return adoptPtr(new FakeCanvas2DLayerBridge(context, canvas, opacityMode));
+        return adoptRef(static_cast<Canvas2DLayerBridge*>(new FakeCanvas2DLayerBridge(context, canvas, opacityMode)));
     }
 protected:
     FakeCanvas2DLayerBridge(PassRefPtr<GraphicsContext3D> context, SkDeferredCanvas* canvas, OpacityMode opacityMode) :
@@ -87,7 +87,7 @@
 
         ::testing::Mock::VerifyAndClearExpectations(&mainMock);
 
-        OwnPtr<Canvas2DLayerBridge> bridge = FakeCanvas2DLayerBridge::create(mainContext.release(), canvas.get(), Canvas2DLayerBridge::NonOpaque);
+        Canvas2DLayerBridgePtr bridge = FakeCanvas2DLayerBridge::create(mainContext.release(), canvas.get(), Canvas2DLayerBridge::NonOpaque);
 
         ::testing::Mock::VerifyAndClearExpectations(&mainMock);
 
diff --git a/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp b/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
index 33e9ca6..7f45ae9 100644
--- a/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
+++ b/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
@@ -100,6 +100,11 @@
     return adoptPtr(SkDeferredCanvas::Create(SkSurface::NewRaster(info)));
 }
 
+FakeCanvas2DLayerBridge* fake(const Canvas2DLayerBridgePtr& layer)
+{
+    return static_cast<FakeCanvas2DLayerBridge*>(layer.get());
+}
+
 class Canvas2DLayerManagerTest : public Test {
 protected:
     void storageAllocationTrackingTest()
@@ -109,22 +114,22 @@
         {
             RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
             OwnPtr<SkDeferredCanvas> canvas1 = createCanvas(context.get());
-            FakeCanvas2DLayerBridge layer1(context, canvas1.get());
+            Canvas2DLayerBridgePtr layer1(adoptRef(new FakeCanvas2DLayerBridge(context, canvas1.get())));
             EXPECT_EQ((size_t)0, manager.m_bytesAllocated);
-            layer1.storageAllocatedForRecordingChanged(1);
+            layer1->storageAllocatedForRecordingChanged(1);
             EXPECT_EQ((size_t)1, manager.m_bytesAllocated);
             // Test allocation increase
-            layer1.storageAllocatedForRecordingChanged(2);
+            layer1->storageAllocatedForRecordingChanged(2);
             EXPECT_EQ((size_t)2, manager.m_bytesAllocated);
             // Test allocation decrease
-            layer1.storageAllocatedForRecordingChanged(1);
+            layer1->storageAllocatedForRecordingChanged(1);
             EXPECT_EQ((size_t)1, manager.m_bytesAllocated);
             {
                 OwnPtr<SkDeferredCanvas> canvas2 = createCanvas(context.get());
-                FakeCanvas2DLayerBridge layer2(context, canvas2.get());
+                Canvas2DLayerBridgePtr layer2(adoptRef(new FakeCanvas2DLayerBridge(context, canvas2.get())));
                 EXPECT_EQ((size_t)1, manager.m_bytesAllocated);
                 // verify multi-layer allocation tracking
-                layer2.storageAllocatedForRecordingChanged(2);
+                layer2->storageAllocatedForRecordingChanged(2);
                 EXPECT_EQ((size_t)3, manager.m_bytesAllocated);
             }
             // Verify tracking after destruction
@@ -138,15 +143,15 @@
         Canvas2DLayerManager& manager = Canvas2DLayerManager::get();
         manager.init(10, 5);
         OwnPtr<SkDeferredCanvas> canvas = createCanvas(context.get());
-        FakeCanvas2DLayerBridge layer(context, canvas.get());
-        layer.fakeFreeableBytes(10);
-        layer.storageAllocatedForRecordingChanged(8); // under the max
-        EXPECT_EQ(0, layer.m_freeMemoryIfPossibleCount);
-        layer.storageAllocatedForRecordingChanged(12); // over the max
-        EXPECT_EQ(1, layer.m_freeMemoryIfPossibleCount);
-        EXPECT_EQ((size_t)3, layer.m_freeableBytes);
-        EXPECT_EQ(0, layer.m_flushCount); // eviction succeeded without triggering a flush
-        EXPECT_EQ((size_t)5, layer.bytesAllocated());
+        Canvas2DLayerBridgePtr layer(adoptRef(new FakeCanvas2DLayerBridge(context, canvas.get())));
+        fake(layer)->fakeFreeableBytes(10);
+        layer->storageAllocatedForRecordingChanged(8); // under the max
+        EXPECT_EQ(0, fake(layer)->m_freeMemoryIfPossibleCount);
+        layer->storageAllocatedForRecordingChanged(12); // over the max
+        EXPECT_EQ(1, fake(layer)->m_freeMemoryIfPossibleCount);
+        EXPECT_EQ((size_t)3, fake(layer)->m_freeableBytes);
+        EXPECT_EQ(0, fake(layer)->m_flushCount); // eviction succeeded without triggering a flush
+        EXPECT_EQ((size_t)5, layer->bytesAllocated());
     }
 
     void flushEvictionTest()
@@ -155,16 +160,16 @@
         Canvas2DLayerManager& manager = Canvas2DLayerManager::get();
         manager.init(10, 5);
         OwnPtr<SkDeferredCanvas> canvas = createCanvas(context.get());
-        FakeCanvas2DLayerBridge layer(context, canvas.get());
-        layer.fakeFreeableBytes(1); // Not enough freeable bytes, will cause aggressive eviction by flushing
-        layer.storageAllocatedForRecordingChanged(8); // under the max
-        EXPECT_EQ(0, layer.m_freeMemoryIfPossibleCount);
-        layer.storageAllocatedForRecordingChanged(12); // over the max
-        EXPECT_EQ(2, layer.m_freeMemoryIfPossibleCount); // Two tries, one before flush, one after flush
-        EXPECT_EQ((size_t)0, layer.m_freeableBytes);
-        EXPECT_EQ(1, layer.m_flushCount); // flush was attempted
-        EXPECT_EQ((size_t)11, layer.bytesAllocated()); // flush drops the layer from manager's tracking list
-        EXPECT_FALSE(manager.isInList(&layer));
+        Canvas2DLayerBridgePtr layer(adoptRef(new FakeCanvas2DLayerBridge(context, canvas.get())));
+        fake(layer)->fakeFreeableBytes(1); // Not enough freeable bytes, will cause aggressive eviction by flushing
+        layer->storageAllocatedForRecordingChanged(8); // under the max
+        EXPECT_EQ(0, fake(layer)->m_freeMemoryIfPossibleCount);
+        layer->storageAllocatedForRecordingChanged(12); // over the max
+        EXPECT_EQ(2, fake(layer)->m_freeMemoryIfPossibleCount); // Two tries, one before flush, one after flush
+        EXPECT_EQ((size_t)0, fake(layer)->m_freeableBytes);
+        EXPECT_EQ(1, fake(layer)->m_flushCount); // flush was attempted
+        EXPECT_EQ((size_t)11, layer->bytesAllocated()); // flush drops the layer from manager's tracking list
+        EXPECT_FALSE(manager.isInList(layer.get()));
     }
 
     void doDeferredFrameTestTask(FakeCanvas2DLayerBridge* layer, bool skipCommands)
@@ -205,35 +210,35 @@
         RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
         Canvas2DLayerManager::get().init(10, 10);
         OwnPtr<SkDeferredCanvas> canvas = createCanvas(context.get());
-        FakeCanvas2DLayerBridge fakeLayer(context, canvas.get());
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, &fakeLayer, true));
+        Canvas2DLayerBridgePtr layer(adoptRef(new FakeCanvas2DLayerBridge(context, canvas.get())));
+        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
         WebKit::Platform::current()->currentThread()->enterRunLoop();
         // Verify that didProcessTask was called upon completion
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
         // Verify that no flush was performed because frame is fresh
-        EXPECT_EQ(0, fakeLayer.m_flushCount);
+        EXPECT_EQ(0, fake(layer)->m_flushCount);
 
         // Verify that no flushes are triggered as long as frame are fresh
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, &fakeLayer, true));
+        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
         WebKit::Platform::current()->currentThread()->enterRunLoop();
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
-        EXPECT_EQ(0, fakeLayer.m_flushCount);
+        EXPECT_EQ(0, fake(layer)->m_flushCount);
 
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, &fakeLayer, true));
+        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
         WebKit::Platform::current()->currentThread()->enterRunLoop();
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
-        EXPECT_EQ(0, fakeLayer.m_flushCount);
+        EXPECT_EQ(0, fake(layer)->m_flushCount);
 
         // Verify that a flush is triggered when queue is accumulating a multi-frame backlog.
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, &fakeLayer, false));
+        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), false));
         WebKit::Platform::current()->currentThread()->enterRunLoop();
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
-        EXPECT_EQ(1, fakeLayer.m_flushCount);
+        EXPECT_EQ(1, fake(layer)->m_flushCount);
 
-        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, &fakeLayer, false));
+        WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), false));
         WebKit::Platform::current()->currentThread()->enterRunLoop();
         EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
-        EXPECT_EQ(2, fakeLayer.m_flushCount);
+        EXPECT_EQ(2, fake(layer)->m_flushCount);
     }
 };
 
diff --git a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
index 79b46e3..04eccf6 100644
--- a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
@@ -35,14 +35,15 @@
 #include <windows.h>
 #include <mlang.h>
 #include <objidl.h>
-#include "SkPaint.h"
-#include "SkTypeface_win.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/skia/SkiaFontWin.h"
 #include "core/platform/win/HWndDC.h"
 #include "public/platform/Platform.h"
 #include "public/platform/win/WebSandboxSupport.h"
+#include "third_party/skia/include/core/SkPaint.h"
+#include "third_party/skia/include/core/SkTypeface.h"
+#include "third_party/skia/include/ports/SkTypeface_win.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/StdLibExtras.h"
 
@@ -123,6 +124,7 @@
     , m_size(-1)
     , m_orientation(Horizontal)
     , m_scriptCache(0)
+    , m_typeface(SkTypeface::RefDefault())
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(true)
 {
@@ -133,6 +135,7 @@
     , m_size(0)
     , m_orientation(Horizontal)
     , m_scriptCache(0)
+    , m_typeface(SkTypeface::RefDefault())
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(false)
 {
@@ -154,7 +157,7 @@
     , m_size(size)
     , m_orientation(Horizontal)
     , m_scriptCache(0)
-    , m_typeface(0)
+    , m_typeface(SkTypeface::RefDefault())
     , m_paintTextFlags(0)
     , m_isHashTableDeletedValue(false)
 {
diff --git a/Source/core/platform/graphics/chromium/test/MockImageDecoder.h b/Source/core/platform/graphics/chromium/test/MockImageDecoder.h
index c6d0b33..7089f5f 100644
--- a/Source/core/platform/graphics/chromium/test/MockImageDecoder.h
+++ b/Source/core/platform/graphics/chromium/test/MockImageDecoder.h
@@ -45,7 +45,7 @@
     static PassOwnPtr<MockImageDecoder> create(MockImageDecoderClient* client) { return adoptPtr(new MockImageDecoder(client)); }
 
     MockImageDecoder(MockImageDecoderClient* client)
-        : ImageDecoder(ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileApplied)
+        : ImageDecoder(ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileApplied, IntSize())
         , m_client(client)
     { }
 
diff --git a/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm b/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
index ab3caf3..2faaf2b 100644
--- a/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
+++ b/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
@@ -28,7 +28,7 @@
 #import <AvailabilityMacros.h>
 #import <wtf/text/WTFString.h>
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 #import "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
 #endif
 
@@ -84,7 +84,7 @@
     m_cgFont = f.m_cgFont;
     m_CTFont = f.m_CTFont;
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     m_inMemoryFont = f.m_inMemoryFont;
     m_harfBuzzFace = f.m_harfBuzzFace;
 #endif
@@ -101,7 +101,7 @@
         CFRelease(m_font);
     m_font = f.m_font;
     m_CTFont = f.m_CTFont;
-#if OS(DARWIN)
+#if OS(MACOSX)
     m_inMemoryFont = f.m_inMemoryFont;
     m_harfBuzzFace = f.m_harfBuzzFace;
 #endif
@@ -133,7 +133,7 @@
     NSFont* loadedFont = 0;
     loadFont(m_font, m_size, loadedFont, cgFont);
     
-#if OS(DARWIN)
+#if OS(MACOSX)
     // If loadFont replaced m_font with a fallback font, then release the
     // previous font to counter the retain above. Then retain the new font.
     if (loadedFont != m_font) {
@@ -278,7 +278,7 @@
     return m_CTFont.get();
 }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 static bool isAATFont(CTFontRef ctFont)
 {
     CFDataRef table = CTFontCopyTable(ctFont, kCTFontTableMort, 0);
diff --git a/Source/core/platform/graphics/filters/FEColorMatrix.cpp b/Source/core/platform/graphics/filters/FEColorMatrix.cpp
index 9462e1c..4d8c45a 100644
--- a/Source/core/platform/graphics/filters/FEColorMatrix.cpp
+++ b/Source/core/platform/graphics/filters/FEColorMatrix.cpp
@@ -285,7 +285,8 @@
 {
     RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     SkAutoTUnref<SkColorFilter> filter(createColorFilter(m_type, m_values.data()));
-    return adoptRef(SkColorFilterImageFilter::Create(filter, input.get()));
+    SkIRect rect = getCropRect(builder->cropOffset());
+    return adoptRef(SkColorFilterImageFilter::Create(filter, input.get(), &rect));
 }
 
 static TextStream& operator<<(TextStream& ts, const ColorMatrixType& type)
diff --git a/Source/core/platform/graphics/filters/FEGaussianBlur.cpp b/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
index 0a8d60b..8c63185 100644
--- a/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
+++ b/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
@@ -343,7 +343,8 @@
     RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
     float stdX = filter()->applyHorizontalScale(m_stdX);
     float stdY = filter()->applyVerticalScale(m_stdY);
-    return adoptRef(new SkBlurImageFilter(SkFloatToScalar(stdX), SkFloatToScalar(stdY), input.get()));
+    SkIRect rect = getCropRect(builder->cropOffset());
+    return adoptRef(new SkBlurImageFilter(SkFloatToScalar(stdX), SkFloatToScalar(stdY), input.get(), &rect));
 }
 
 TextStream& FEGaussianBlur::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FELighting.cpp b/Source/core/platform/graphics/filters/FELighting.cpp
index cfe5880..7482550 100644
--- a/Source/core/platform/graphics/filters/FELighting.cpp
+++ b/Source/core/platform/graphics/filters/FELighting.cpp
@@ -416,6 +416,7 @@
 
 PassRefPtr<SkImageFilter> FELighting::createImageFilter(SkiaImageFilterBuilder* builder)
 {
+    SkIRect rect = getCropRect(builder->cropOffset());
     RefPtr<SkImageFilter> input(builder ? builder->build(inputEffect(0), operatingColorSpace()) : 0);
     switch (m_lightSource->type()) {
     case LS_DISTANT: {
@@ -426,18 +427,18 @@
                            sinf(azimuthRad) * cosf(elevationRad),
                            sinf(elevationRad));
         if (m_specularConstant > 0)
-            return adoptRef(SkLightingImageFilter::CreateDistantLitSpecular(direction, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get()));
+            return adoptRef(SkLightingImageFilter::CreateDistantLitSpecular(direction, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get(), &rect));
         else
-            return adoptRef(SkLightingImageFilter::CreateDistantLitDiffuse(direction, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get()));
+            return adoptRef(SkLightingImageFilter::CreateDistantLitDiffuse(direction, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get(), &rect));
     }
     case LS_POINT: {
         PointLightSource* pointLightSource = static_cast<PointLightSource*>(m_lightSource.get());
         FloatPoint3D position = pointLightSource->position();
         SkPoint3 skPosition(position.x(), position.y(), position.z());
         if (m_specularConstant > 0)
-            return adoptRef(SkLightingImageFilter::CreatePointLitSpecular(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get()));
+            return adoptRef(SkLightingImageFilter::CreatePointLitSpecular(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get(), &rect));
         else
-            return adoptRef(SkLightingImageFilter::CreatePointLitDiffuse(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get()));
+            return adoptRef(SkLightingImageFilter::CreatePointLitDiffuse(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get(), &rect));
     }
     case LS_SPOT: {
         SpotLightSource* spotLightSource = static_cast<SpotLightSource*>(m_lightSource.get());
@@ -448,9 +449,9 @@
         if (!limitingConeAngle || limitingConeAngle > 90 || limitingConeAngle < -90)
             limitingConeAngle = 90;
         if (m_specularConstant > 0)
-            return adoptRef(SkLightingImageFilter::CreateSpotLitSpecular(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get()));
+            return adoptRef(SkLightingImageFilter::CreateSpotLitSpecular(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get(), &rect));
         else
-            return adoptRef(SkLightingImageFilter::CreateSpotLitDiffuse(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get()));
+            return adoptRef(SkLightingImageFilter::CreateSpotLitDiffuse(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get(), &rect));
     }
     default:
         ASSERT_NOT_REACHED();
diff --git a/Source/core/platform/graphics/filters/FilterEffect.cpp b/Source/core/platform/graphics/filters/FilterEffect.cpp
index 01e4b0a..5972bcd 100644
--- a/Source/core/platform/graphics/filters/FilterEffect.cpp
+++ b/Source/core/platform/graphics/filters/FilterEffect.cpp
@@ -481,4 +481,17 @@
     return 0;
 }
 
+SkIRect FilterEffect::getCropRect(const FloatSize& cropOffset) const
+{
+    SkIRect rect;
+    FloatRect boundaries = effectBoundaries();
+    FloatSize resolution = filter()->filterResolution();
+    boundaries.scale(resolution.width(), resolution.height());
+    rect.fLeft = hasX() ? static_cast<int>(boundaries.x()) + cropOffset.width() : 0;
+    rect.fTop = hasY() ? static_cast<int>(boundaries.y()) + cropOffset.height() : 0;
+    rect.fRight = hasWidth() ? rect.fLeft + static_cast<int>(boundaries.width()) : SK_MaxS32;
+    rect.fBottom = hasHeight() ? rect.fTop + static_cast<int>(boundaries.height()) : SK_MaxS32;
+    return rect;
+}
+
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/filters/FilterEffect.h b/Source/core/platform/graphics/filters/FilterEffect.h
index 8353bf6..2aabe06 100644
--- a/Source/core/platform/graphics/filters/FilterEffect.h
+++ b/Source/core/platform/graphics/filters/FilterEffect.h
@@ -142,6 +142,7 @@
     void setEffectBoundaries(const FloatRect& effectBoundaries) { m_effectBoundaries = effectBoundaries; }
 
     Filter* filter() { return m_filter; }
+    const Filter* filter() const { return m_filter; }
 
     bool clipsToBounds() const { return m_clipsToBounds; }
     void setClipsToBounds(bool value) { m_clipsToBounds = value; }
@@ -169,6 +170,7 @@
 
     // If a pre-multiplied image, check every pixel for validity and correct if necessary.
     void forceValidPreMultipliedPixels();
+    SkIRect getCropRect(const FloatSize& cropOffset) const;
 
 private:
     virtual void applySoftware() = 0;
diff --git a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
index 8409396..f16dc22 100644
--- a/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
+++ b/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
@@ -27,6 +27,7 @@
 #define SkiaImageFilterBuilder_h
 
 #include "core/platform/graphics/ColorSpace.h"
+#include "core/platform/graphics/FloatSize.h"
 #include "wtf/HashMap.h"
 
 class SkImageFilter;
@@ -45,10 +46,15 @@
 
     PassRefPtr<SkImageFilter> transformColorSpace(
         SkImageFilter* input, ColorSpace srcColorSpace, ColorSpace dstColorSpace);
+
+    void setCropOffset(const FloatSize& cropOffset) { m_cropOffset = cropOffset; };
+    FloatSize cropOffset() { return m_cropOffset; }
+
 private:
     typedef std::pair<FilterEffect*, ColorSpace> FilterColorSpacePair;
     typedef HashMap<FilterColorSpacePair, RefPtr<SkImageFilter> > FilterBuilderHashMap;
     FilterBuilderHashMap m_map;
+    FloatSize m_cropOffset;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/gpu/DrawingBuffer.cpp b/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
index 0524092..11f4b50 100644
--- a/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
+++ b/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
@@ -650,7 +650,7 @@
                 continue;
             }
 
-#if OS(DARWIN)
+#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);
diff --git a/Source/core/platform/graphics/mac/FontMac.cpp b/Source/core/platform/graphics/mac/FontMac.cpp
index 4072c85..eb349ca 100644
--- a/Source/core/platform/graphics/mac/FontMac.cpp
+++ b/Source/core/platform/graphics/mac/FontMac.cpp
@@ -72,7 +72,7 @@
     paint->setLCDRenderText(shouldSmoothFonts);
     paint->setSubpixelText(true);
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     // When using CoreGraphics, disable hinting when webkit-font-smoothing:antialiased is used.
     // See crbug.com/152304
     if (font->fontDescription().fontSmoothing() == Antialiased)
diff --git a/Source/core/platform/graphics/skia/FontCacheSkia.cpp b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
index cba5deb..da1cc8e 100644
--- a/Source/core/platform/graphics/skia/FontCacheSkia.cpp
+++ b/Source/core/platform/graphics/skia/FontCacheSkia.cpp
@@ -29,7 +29,8 @@
  */
 
 #include "config.h"
-#include <unicode/locid.h>
+
+#include "SkFontMgr.h"
 #include "SkTypeface.h"
 #include "core/platform/NotImplemented.h"
 #include "core/platform/graphics/Font.h"
@@ -39,6 +40,7 @@
 #include "wtf/Assertions.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/CString.h"
+#include <unicode/locid.h>
 
 namespace WebCore {
 
@@ -46,7 +48,7 @@
 {
 }
 
-#if !OS(WINDOWS)
+#if !OS(WIN)
 PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 c)
 {
     icu::Locale locale = icu::Locale::getDefault();
@@ -146,10 +148,16 @@
     if (fontDescription.italic())
         style |= SkTypeface::kItalic;
 
+    // FIXME: Use SkFontStyle and matchFamilyStyle instead of legacyCreateTypeface.
+#if OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS)
+    if (m_fontManager)
+        return m_fontManager->legacyCreateTypeface(name.data(), style);
+#endif
+
     return SkTypeface::CreateFromName(name.data(), static_cast<SkTypeface::Style>(style));
 }
 
-#if !OS(WINDOWS)
+#if !OS(WIN)
 FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
 {
     CString name;
diff --git a/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
index 0120b9e..ac77135 100644
--- a/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
+++ b/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
@@ -32,6 +32,8 @@
 #include "config.h"
 #include "core/platform/graphics/FontCache.h"
 
+#include "SkFontMgr.h"
+#include "SkTypeface_win.h"
 #include "core/platform/NotImplemented.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/SimpleFontData.h"
@@ -40,6 +42,13 @@
 
 namespace WebCore {
 
+FontCache::FontCache()
+    : m_purgePreventCount(0)
+{
+    m_fontManager = adoptPtr(SkFontMgr_New_GDI());
+}
+
+
 static bool fontContainsCharacter(const FontPlatformData* fontData, const wchar_t* family, UChar32 character)
 {
     SkPaint paint;
diff --git a/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp b/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
index 7cf6034..e6f1915 100644
--- a/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
+++ b/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
@@ -50,7 +50,7 @@
     fontData->platformData().setupPaint(&paint);
     paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
 
-#if OS(WINDOWS)
+#if OS(WIN)
     // FIXME: For some reason SkAutoSTMalloc fails to link on Windows.
     // SkAutoSTArray works fine though...
     SkAutoSTArray<GlyphPage::size, uint16_t> glyphStorage(length);
diff --git a/Source/core/platform/graphics/skia/NativeImageSkia.cpp b/Source/core/platform/graphics/skia/NativeImageSkia.cpp
index dc81cd5..f43c483 100644
--- a/Source/core/platform/graphics/skia/NativeImageSkia.cpp
+++ b/Source/core/platform/graphics/skia/NativeImageSkia.cpp
@@ -320,11 +320,11 @@
     return !context->getTotalMatrix().rectStaysRect();
 }
 
-void NativeImageSkia::draw(GraphicsContext* context, const SkRect& srcRect, const SkRect& destRect, SkXfermode::Mode compOp) const
+void NativeImageSkia::draw(GraphicsContext* context, const SkRect& srcRect, const SkRect& destRect, PassRefPtr<SkXfermode> compOp) const
 {
     TRACE_EVENT0("skia", "NativeImageSkia::draw");
     SkPaint paint;
-    paint.setXfermodeMode(compOp);
+    paint.setXfermode(compOp.get());
     paint.setAlpha(context->getNormalizedAlpha());
     paint.setLooper(context->drawLooper());
     // only antialias if we're rotated or skewed
@@ -461,7 +461,7 @@
 
     SkPaint paint;
     paint.setShader(shader.get());
-    paint.setXfermodeMode(WebCoreCompositeToSkiaComposite(compositeOp, blendMode));
+    paint.setXfermode(WebCoreCompositeToSkiaComposite(compositeOp, blendMode).get());
 
     paint.setFilterBitmap(resampling == LinearResampling);
     if (useBicubicFilter)
diff --git a/Source/core/platform/graphics/skia/NativeImageSkia.h b/Source/core/platform/graphics/skia/NativeImageSkia.h
index c26cf10..683e91e 100644
--- a/Source/core/platform/graphics/skia/NativeImageSkia.h
+++ b/Source/core/platform/graphics/skia/NativeImageSkia.h
@@ -126,7 +126,7 @@
     // Rectangle of the subset in the scaled image.
     SkBitmap resizedBitmap(const SkISize& scaledImageSize, const SkIRect& scaledImageSubset) const;
 
-    void draw(GraphicsContext*, const SkRect& srcRect, const SkRect& destRect, SkXfermode::Mode) const;
+    void draw(GraphicsContext*, const SkRect& srcRect, const SkRect& destRect, PassRefPtr<SkXfermode>) const;
     void drawPattern(
         GraphicsContext*,
         const FloatRect& srcRect,
diff --git a/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp b/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
index 56eef1e..6a89201 100644
--- a/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
+++ b/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
@@ -40,7 +40,7 @@
 #include "core/platform/graphics/chromium/VDMXParser.h"
 #include "wtf/unicode/Unicode.h"
 
-#if OS(WINDOWS)
+#if OS(WIN)
 #include "core/platform/win/HWndDC.h"
 #endif
 
@@ -132,7 +132,7 @@
     // In WebKit/WebCore/platform/graphics/SimpleFontData.cpp, m_spaceWidth is
     // calculated for us, but we need to calculate m_maxCharWidth and
     // m_avgCharWidth in order for text entry widgets to be sized correctly.
-#if OS(WINDOWS)
+#if OS(WIN)
     m_maxCharWidth = SkScalarRound(metrics.fMaxCharWidth);
 #else
     // FIXME: This seems incorrect and should probably use fMaxCharWidth as
diff --git a/Source/core/platform/graphics/skia/SkiaUtils.cpp b/Source/core/platform/graphics/skia/SkiaUtils.cpp
index 56901f0..b094167 100644
--- a/Source/core/platform/graphics/skia/SkiaUtils.cpp
+++ b/Source/core/platform/graphics/skia/SkiaUtils.cpp
@@ -79,25 +79,26 @@
     SkXfermode::kLuminosity_Mode // BlendModeLuminosity
 };
 
-SkXfermode::Mode WebCoreCompositeToSkiaComposite(CompositeOperator op, BlendMode blendMode)
+PassRefPtr<SkXfermode> WebCoreCompositeToSkiaComposite(CompositeOperator op, BlendMode blendMode)
 {
     if (blendMode != BlendModeNormal) {
         if ((uint8_t)blendMode >= SK_ARRAY_COUNT(gMapBlendOpsToXfermodeModes)) {
             SkDEBUGF(("GraphicsContext::setPlatformCompositeOperation unknown BlendMode %d\n", blendMode));
-            return SkXfermode::kSrcOver_Mode;
+            return adoptRef(SkXfermode::Create(SkXfermode::kSrcOver_Mode));
         }
-        return (SkXfermode::Mode)gMapBlendOpsToXfermodeModes[(uint8_t)blendMode];
+        SkXfermode::Mode mode = (SkXfermode::Mode)gMapBlendOpsToXfermodeModes[(uint8_t)blendMode];
+        return adoptRef(SkXfermode::Create(mode));
     }
 
     const CompositOpToXfermodeMode* table = gMapCompositOpsToXfermodeModes;
 
     for (unsigned i = 0; i < SK_ARRAY_COUNT(gMapCompositOpsToXfermodeModes); i++) {
         if (table[i].mCompositOp == op)
-            return (SkXfermode::Mode)table[i].m_xfermodeMode;
+            return adoptRef(SkXfermode::Create((SkXfermode::Mode)table[i].m_xfermodeMode));
     }
 
     SkDEBUGF(("GraphicsContext::setPlatformCompositeOperation unknown CompositeOperator %d\n", op));
-    return SkXfermode::kSrcOver_Mode; // fall-back
+    return adoptRef(SkXfermode::Create(SkXfermode::kSrcOver_Mode)); // fall-back
 }
 
 static U8CPU InvScaleByte(U8CPU component, uint32_t scale)
diff --git a/Source/core/platform/graphics/skia/SkiaUtils.h b/Source/core/platform/graphics/skia/SkiaUtils.h
index d8a13e8..be27592 100644
--- a/Source/core/platform/graphics/skia/SkiaUtils.h
+++ b/Source/core/platform/graphics/skia/SkiaUtils.h
@@ -43,7 +43,7 @@
 
 namespace WebCore {
 
-SkXfermode::Mode WebCoreCompositeToSkiaComposite(CompositeOperator, BlendMode = BlendModeNormal);
+PassRefPtr<SkXfermode> WebCoreCompositeToSkiaComposite(CompositeOperator, BlendMode = BlendModeNormal);
 
 // move this guy into SkColor.h
 SkColor SkPMColorToColor(SkPMColor);
diff --git a/Source/core/platform/image-decoders/ImageDecoder.cpp b/Source/core/platform/image-decoders/ImageDecoder.cpp
index db18ed0..657ee4c 100644
--- a/Source/core/platform/image-decoders/ImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/ImageDecoder.cpp
@@ -92,22 +92,22 @@
         return nullptr;
 
     if (matchesJPEGSignature(contents))
-        return adoptPtr(new JPEGImageDecoder(alphaOption, gammaAndColorProfileOption));
+        return adoptPtr(new JPEGImageDecoder(alphaOption, gammaAndColorProfileOption, IntSize()));
 
     if (matchesPNGSignature(contents))
-        return adoptPtr(new PNGImageDecoder(alphaOption, gammaAndColorProfileOption));
+        return adoptPtr(new PNGImageDecoder(alphaOption, gammaAndColorProfileOption, IntSize()));
 
     if (matchesGIFSignature(contents))
-        return adoptPtr(new GIFImageDecoder(alphaOption, gammaAndColorProfileOption));
+        return adoptPtr(new GIFImageDecoder(alphaOption, gammaAndColorProfileOption, IntSize()));
 
     if (matchesICOSignature(contents) || matchesCURSignature(contents))
-        return adoptPtr(new ICOImageDecoder(alphaOption, gammaAndColorProfileOption));
+        return adoptPtr(new ICOImageDecoder(alphaOption, gammaAndColorProfileOption, IntSize()));
 
     if (matchesWebPSignature(contents))
-        return adoptPtr(new WEBPImageDecoder(alphaOption, gammaAndColorProfileOption));
+        return adoptPtr(new WEBPImageDecoder(alphaOption, gammaAndColorProfileOption, IntSize()));
 
     if (matchesBMPSignature(contents))
-        return adoptPtr(new BMPImageDecoder(alphaOption, gammaAndColorProfileOption));
+        return adoptPtr(new BMPImageDecoder(alphaOption, gammaAndColorProfileOption, IntSize()));
 
     return nullptr;
 }
diff --git a/Source/core/platform/image-decoders/ImageDecoder.h b/Source/core/platform/image-decoders/ImageDecoder.h
index eac2953..2beba3e 100644
--- a/Source/core/platform/image-decoders/ImageDecoder.h
+++ b/Source/core/platform/image-decoders/ImageDecoder.h
@@ -40,7 +40,7 @@
 
 #if USE(QCMSLIB)
 #include "qcms.h"
-#if OS(DARWIN)
+#if OS(MACOSX)
 #include <ApplicationServices/ApplicationServices.h>
 #include "core/platform/graphics/cg/GraphicsContextCG.h"
 #include "wtf/RetainPtr.h"
@@ -232,12 +232,23 @@
 
     // ImageDecoder is a base for all format-specific decoders
     // (e.g. JPEGImageDecoder). This base manages the ImageFrame cache.
+    //
+    // |maxDecodedSize| is used to limit decoded image sizes to no larger than
+    // the provided size. This is used to limit memory consumption when
+    // decoding large images. Image should be shrunk such that both width and
+    // height fit inside the specified size.
+    //
+    // Individual image decoders may ignore this entirely (which may result in
+    // excessive memory consumption) or shrink images even smaller than the
+    // provided size (which may result in decreased visual fidelity of the
+    // rendered page).
     class ImageDecoder {
         WTF_MAKE_NONCOPYABLE(ImageDecoder); WTF_MAKE_FAST_ALLOCATED;
     public:
-        ImageDecoder(ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
+    ImageDecoder(ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption, const IntSize& maxDecodedSize)
             : m_premultiplyAlpha(alphaOption == ImageSource::AlphaPremultiplied)
             , m_ignoreGammaAndColorProfile(gammaAndColorProfileOption == ImageSource::GammaAndColorProfileIgnored)
+            , m_maxDecodedSize(maxDecodedSize)
             , m_sizeAvailable(false)
             , m_isAllDataReceived(false)
             , m_failed(false) { }
@@ -346,7 +357,7 @@
             if (!qcmsInitialized) {
                 qcmsInitialized = true;
                 // FIXME: Add optional ICCv4 support.
-#if OS(DARWIN)
+#if OS(MACOSX)
                 RetainPtr<CGColorSpaceRef> monitorColorSpace(AdoptCF, CGDisplayCopyColorSpace(CGMainDisplayID()));
                 CFDataRef iccProfile(CGColorSpaceCopyICCProfile(monitorColorSpace.get()));
                 if (iccProfile) {
@@ -434,6 +445,7 @@
         bool m_premultiplyAlpha;
         bool m_ignoreGammaAndColorProfile;
         ImageOrientation m_orientation;
+        IntSize m_maxDecodedSize;
 
     private:
         // Some code paths compute the size of the image as "width * height * 4"
diff --git a/Source/core/platform/image-decoders/ImageDecoderTest.cpp b/Source/core/platform/image-decoders/ImageDecoderTest.cpp
index f916b8a..d25aeeb 100644
--- a/Source/core/platform/image-decoders/ImageDecoderTest.cpp
+++ b/Source/core/platform/image-decoders/ImageDecoderTest.cpp
@@ -42,7 +42,7 @@
 class TestImageDecoder : public ImageDecoder {
 public:
     TestImageDecoder()
-        : ImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied)
+        : ImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied, IntSize())
     {
     }
 
diff --git a/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp b/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp
index e4e1e90..053556b 100644
--- a/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp
@@ -43,8 +43,9 @@
 static const size_t sizeOfFileHeader = 14;
 
 BMPImageDecoder::BMPImageDecoder(ImageSource::AlphaOption alphaOption,
-                                 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
-    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
+    ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
+    const IntSize& maxDecodedSize)
+    : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedSize)
     , m_decodedOffset(0)
 {
 }
diff --git a/Source/core/platform/image-decoders/bmp/BMPImageDecoder.h b/Source/core/platform/image-decoders/bmp/BMPImageDecoder.h
index 1302484..0d13430 100644
--- a/Source/core/platform/image-decoders/bmp/BMPImageDecoder.h
+++ b/Source/core/platform/image-decoders/bmp/BMPImageDecoder.h
@@ -39,7 +39,7 @@
     // This class decodes the BMP image format.
     class BMPImageDecoder : public ImageDecoder {
     public:
-        BMPImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption);
+        BMPImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, const IntSize&);
 
         // ImageDecoder
         virtual String filenameExtension() const { return "bmp"; }
diff --git a/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp b/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
index 4e2db96..21ef4d1 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
@@ -35,8 +35,9 @@
 namespace WebCore {
 
 GIFImageDecoder::GIFImageDecoder(ImageSource::AlphaOption alphaOption,
-                                 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
-    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
+    ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
+    const IntSize& maxDecodedSize)
+    : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedSize)
     , m_repetitionCount(cAnimationLoopOnce)
 {
 }
diff --git a/Source/core/platform/image-decoders/gif/GIFImageDecoder.h b/Source/core/platform/image-decoders/gif/GIFImageDecoder.h
index 3159b7b..d0232a7 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageDecoder.h
+++ b/Source/core/platform/image-decoders/gif/GIFImageDecoder.h
@@ -36,7 +36,7 @@
     // This class decodes the GIF image format.
     class GIFImageDecoder : public ImageDecoder {
     public:
-        GIFImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption);
+        GIFImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, const IntSize&);
         virtual ~GIFImageDecoder();
 
         enum GIFParseQuery { GIFSizeQuery, GIFFrameCountQuery };
diff --git a/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp b/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp
index 090e0d9..c8f0263 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp
+++ b/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp
@@ -58,7 +58,7 @@
 
 PassOwnPtr<GIFImageDecoder> createDecoder()
 {
-    return adoptPtr(new GIFImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied));
+    return adoptPtr(new GIFImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied, IntSize()));
 }
 
 unsigned hashSkBitmap(const SkBitmap& bitmap)
diff --git a/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp b/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp
index a5f4f7f..7e713c3 100644
--- a/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp
@@ -47,8 +47,9 @@
 static const size_t sizeOfDirEntry = 16;
 
 ICOImageDecoder::ICOImageDecoder(ImageSource::AlphaOption alphaOption,
-                                 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
-    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
+    ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
+    const IntSize& maxDecodedSize)
+    : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedSize)
     , m_decodedOffset(0)
 {
 }
@@ -229,7 +230,7 @@
     if (!m_pngDecoders[index]) {
         m_pngDecoders[index] = adoptPtr(
             new PNGImageDecoder(m_premultiplyAlpha ? ImageSource::AlphaPremultiplied : ImageSource::AlphaNotPremultiplied,
-                                m_ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied));
+                m_ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied, m_maxDecodedSize));
         setDataForPNGDecoderAtIndex(index);
     }
     // Fail if the size the PNGImageDecoder calculated does not match the size
diff --git a/Source/core/platform/image-decoders/ico/ICOImageDecoder.h b/Source/core/platform/image-decoders/ico/ICOImageDecoder.h
index 4c27435..041affe 100644
--- a/Source/core/platform/image-decoders/ico/ICOImageDecoder.h
+++ b/Source/core/platform/image-decoders/ico/ICOImageDecoder.h
@@ -40,7 +40,7 @@
     // This class decodes the ICO and CUR image formats.
     class ICOImageDecoder : public ImageDecoder {
     public:
-        ICOImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption);
+        ICOImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, const IntSize&);
         virtual ~ICOImageDecoder();
 
         // ImageDecoder
diff --git a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
index 9d87086..cb36a28 100644
--- a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
@@ -241,12 +241,13 @@
 class JPEGImageReader {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    JPEGImageReader(JPEGImageDecoder* decoder)
+    JPEGImageReader(JPEGImageDecoder* decoder, const IntSize& maxDecodedSize)
         : m_decoder(decoder)
         , m_bufferLength(0)
         , m_bytesToSkip(0)
         , m_state(JPEG_HEADER)
         , m_samples(0)
+        , m_maxDecodedSize(maxDecodedSize)
 #if USE(QCMSLIB)
         , m_transform(0)
 #endif
@@ -394,17 +395,6 @@
             // image is a sequential JPEG.
             m_info.buffered_image = jpeg_has_multiple_scans(&m_info);
 
-            // Used to set up image size so arrays can be allocated.
-            jpeg_calc_output_dimensions(&m_info);
-
-            // Make a one-row-high sample array that will go away when done with
-            // image. Always make it big enough to hold an RGB row. Since this
-            // uses the IJG memory manager, it must be allocated before the call
-            // to jpeg_start_compress().
-            // FIXME: note that some output color spaces do not need the samples
-            // buffer. Remove this allocation for those color spaces.
-            m_samples = (*m_info.mem->alloc_sarray)((j_common_ptr) &m_info, JPOOL_IMAGE, m_info.output_width * 4, 1);
-
             if (m_decodingSizeOnly) {
                 // We can stop here. Reduce our buffer length and available data.
                 m_bufferLength -= m_info.src->bytes_in_buffer;
@@ -423,6 +413,28 @@
             m_info.enable_2pass_quant = false;
             m_info.do_block_smoothing = true;
 
+            // Enable downsampling if maximum decoded size is specified.
+            if (!m_maxDecodedSize.isEmpty()) {
+                // JPEG only supports a denominator of 8.
+                m_info.scale_denom = 8;
+                unsigned scaleNumerator = std::min(m_info.scale_denom * m_maxDecodedSize.width() / m_info.image_width,
+                    m_info.scale_denom * m_maxDecodedSize.height() / m_info.image_height);
+
+                // Don't upsample, and don't downsample to zero size.
+                m_info.scale_num = std::min(m_info.scale_denom, std::max(scaleNumerator, 1u));
+            }
+
+            // Used to set up image size so arrays can be allocated.
+            jpeg_calc_output_dimensions(&m_info);
+
+            // Make a one-row-high sample array that will go away when done with
+            // image. Always make it big enough to hold an RGB row. Since this
+            // uses the IJG memory manager, it must be allocated before the call
+            // to jpeg_start_compress().
+            // FIXME: note that some output color spaces do not need the samples
+            // buffer. Remove this allocation for those color spaces.
+            m_samples = (*m_info.mem->alloc_sarray)(reinterpret_cast<j_common_ptr>(&m_info), JPOOL_IMAGE, m_info.output_width * 4, 1);
+
             // Start decompressor.
             if (!jpeg_start_decompress(&m_info))
                 return false; // I/O suspension.
@@ -549,6 +561,7 @@
     jstate m_state;
 
     JSAMPARRAY m_samples;
+    IntSize m_maxDecodedSize;
 
 #if USE(QCMSLIB)
     qcms_transform* m_transform;
@@ -588,8 +601,9 @@
 }
 
 JPEGImageDecoder::JPEGImageDecoder(ImageSource::AlphaOption alphaOption,
-                                   ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
-    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
+    ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
+    const IntSize& maxDecodedSize)
+    : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedSize)
 {
 }
 
@@ -684,10 +698,12 @@
     if (m_frameBufferCache.isEmpty())
         return false;
 
+    jpeg_decompress_struct* info = m_reader->info();
+
     // Initialize the framebuffer if needed.
     ImageFrame& buffer = m_frameBufferCache[0];
     if (buffer.status() == ImageFrame::FrameEmpty) {
-        if (!buffer.setSize(size().width(), size().height()))
+        if (!buffer.setSize(info->output_width, info->output_height))
             return setFailed();
         buffer.setStatus(ImageFrame::FramePartial);
         // The buffer is transparent outside the decoded area while the image is
@@ -698,8 +714,6 @@
         buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
     }
 
-    jpeg_decompress_struct* info = m_reader->info();
-
 #if defined(TURBO_JPEG_RGB_SWIZZLE)
     if (turboSwizzled(info->out_color_space)) {
         while (info->output_scanline < info->output_height) {
@@ -744,8 +758,9 @@
     if (failed())
         return;
 
-    if (!m_reader)
-        m_reader = adoptPtr(new JPEGImageReader(this));
+    if (!m_reader) {
+        m_reader = adoptPtr(new JPEGImageReader(this, m_maxDecodedSize));
+    }
 
     // If we couldn't decode the image but we've received all the data, decoding
     // has failed.
diff --git a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.h b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.h
index b63f058..996ce65 100644
--- a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.h
+++ b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.h
@@ -38,7 +38,7 @@
     // This class decodes the JPEG image format.
     class JPEGImageDecoder : public ImageDecoder {
     public:
-        JPEGImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption);
+        JPEGImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, const IntSize&);
         virtual ~JPEGImageDecoder();
 
         // ImageDecoder
diff --git a/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp
new file mode 100644
index 0000000..a78d7d0
--- /dev/null
+++ b/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp
@@ -0,0 +1,147 @@
+/*
+ * 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/platform/image-decoders/jpeg/JPEGImageDecoder.h"
+
+#include "core/platform/SharedBuffer.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebData.h"
+#include "public/platform/WebSize.h"
+#include "public/platform/WebUnitTestSupport.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/StringHasher.h"
+#include "wtf/Vector.h"
+
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+using namespace WebKit;
+
+namespace {
+
+PassRefPtr<SharedBuffer> readFile(const char* fileName)
+{
+    String filePath = Platform::current()->unitTestSupport()->webKitRootDir();
+    filePath.append(fileName);
+
+    return Platform::current()->unitTestSupport()->readFromFile(filePath);
+}
+
+PassOwnPtr<JPEGImageDecoder> createDecoder(const IntSize& maxDecodedSize)
+{
+    return adoptPtr(new JPEGImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied, maxDecodedSize));
+}
+
+} // namespace
+
+void downsample(unsigned width, unsigned height, unsigned* outputWidth, unsigned* outputHeight)
+{
+    RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/lenna.jpg");
+    ASSERT_TRUE(data.get());
+
+    OwnPtr<JPEGImageDecoder> decoder = createDecoder(IntSize(width, height));
+    decoder->setData(data.get(), true);
+
+    ImageFrame* frame = decoder->frameBufferAtIndex(0);
+    ASSERT_TRUE(frame);
+    *outputWidth = frame->getSkBitmap().width();
+    *outputHeight = frame->getSkBitmap().height();
+}
+
+// Tests that a small size doesn't result in an empty image.
+TEST(JPEGImageDecoderTest, downsample0)
+{
+    unsigned outputWidth, outputHeight;
+    downsample(1, 1, &outputWidth, &outputHeight);
+    EXPECT_EQ(32u, outputWidth);
+    EXPECT_EQ(32u, outputHeight);
+}
+
+// Tests that JPEG decoder can downsample from 1/8 to 7/8.
+TEST(JPEGImageDecoderTest, downsample1Over8To7Over8)
+{
+    unsigned outputWidth, outputHeight;
+
+    // 1/8 downsample.
+    downsample(40, 40, &outputWidth, &outputHeight);
+    EXPECT_EQ(32u, outputWidth);
+    EXPECT_EQ(32u, outputHeight);
+
+    // 2/8 downsample.
+    downsample(70, 70, &outputWidth, &outputHeight);
+    EXPECT_EQ(64u, outputWidth);
+    EXPECT_EQ(64u, outputHeight);
+
+    // 3/8 downsample.
+    downsample(100, 100, &outputWidth, &outputHeight);
+    EXPECT_EQ(96u, outputWidth);
+    EXPECT_EQ(96u, outputHeight);
+
+    // 4/8 downsample.
+    downsample(130, 130, &outputWidth, &outputHeight);
+    EXPECT_EQ(128u, outputWidth);
+    EXPECT_EQ(128u, outputHeight);
+
+    // 5/8 downsample.
+    downsample(170, 170, &outputWidth, &outputHeight);
+    EXPECT_EQ(160u, outputWidth);
+    EXPECT_EQ(160u, outputHeight);
+
+    // 6/8 downsample.
+    downsample(200, 200, &outputWidth, &outputHeight);
+    EXPECT_EQ(192u, outputWidth);
+    EXPECT_EQ(192u, outputHeight);
+
+    // 7/8 downsample.
+    downsample(230, 230, &outputWidth, &outputHeight);
+    EXPECT_EQ(224u, outputWidth);
+    EXPECT_EQ(224u, outputHeight);
+}
+
+// Tests that output image fits in a rectangular size.
+TEST(JPEGImageDecoderTest, downsampleRectangle)
+{
+    unsigned outputWidth, outputHeight;
+    downsample(130, 256, &outputWidth, &outputHeight);
+    EXPECT_EQ(128u, outputWidth);
+    EXPECT_EQ(128u, outputHeight);
+}
+
+// Tests that upsampling is not allowed.
+TEST(JPEGImageDecoderTest, upsample)
+{
+    unsigned outputWidth, outputHeight;
+    downsample(1000, 1000, &outputWidth, &outputHeight);
+    EXPECT_EQ(256u, outputWidth);
+    EXPECT_EQ(256u, outputHeight);
+}
diff --git a/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp b/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp
index 828328b..2bdde69 100644
--- a/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp
@@ -216,8 +216,9 @@
 };
 
 PNGImageDecoder::PNGImageDecoder(ImageSource::AlphaOption alphaOption,
-                                 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
-    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
+    ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
+    const IntSize& maxDecodedSize)
+    : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedSize)
     , m_doNothingOnFailure(false)
 {
 }
diff --git a/Source/core/platform/image-decoders/png/PNGImageDecoder.h b/Source/core/platform/image-decoders/png/PNGImageDecoder.h
index bb771f6..1a4094e 100644
--- a/Source/core/platform/image-decoders/png/PNGImageDecoder.h
+++ b/Source/core/platform/image-decoders/png/PNGImageDecoder.h
@@ -36,7 +36,7 @@
     // This class decodes the PNG image format.
     class PNGImageDecoder : public ImageDecoder {
     public:
-        PNGImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption);
+        PNGImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, const IntSize&);
         virtual ~PNGImageDecoder();
 
         // ImageDecoder
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
index 3c3ec9c..c050942 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
@@ -48,8 +48,9 @@
 namespace WebCore {
 
 WEBPImageDecoder::WEBPImageDecoder(ImageSource::AlphaOption alphaOption,
-                                   ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
-    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
+    ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
+    const IntSize& maxDecodedSize)
+    : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedSize)
     , m_decoder(0)
     , m_formatFlags(0)
     , m_frameBackgroundHasAlpha(false)
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
index 2dabd16..ff184ce 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
@@ -38,7 +38,7 @@
 
 class WEBPImageDecoder : public ImageDecoder {
 public:
-    WEBPImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption);
+    WEBPImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, const IntSize&);
     virtual ~WEBPImageDecoder();
 
     virtual String filenameExtension() const OVERRIDE { return "webp"; }
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
index 033d970..de87b00 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
@@ -60,7 +60,7 @@
 
 PassOwnPtr<WEBPImageDecoder> createDecoder()
 {
-    return adoptPtr(new WEBPImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied));
+    return adoptPtr(new WEBPImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied, IntSize()));
 }
 
 unsigned hashSkBitmap(const SkBitmap& bitmap)
diff --git a/Source/core/platform/mac/NSScrollerImpDetails.mm b/Source/core/platform/mac/NSScrollerImpDetails.mm
index 06abe11..7556d76 100644
--- a/Source/core/platform/mac/NSScrollerImpDetails.mm
+++ b/Source/core/platform/mac/NSScrollerImpDetails.mm
@@ -26,6 +26,7 @@
 
 
 #include "config.h"
+#include "RuntimeEnabledFeatures.h"
 #include "core/page/Settings.h"
 #include "core/platform/mac/NSScrollerImpDetails.h"
 
@@ -46,7 +47,7 @@
 }
 
 NSScrollerStyle recommendedScrollerStyle() {
-    if (Settings::usesOverlayScrollbars())
+    if (RuntimeEnabledFeatures::overlayScrollbarsEnabled())
         return NSScrollerStyleOverlay;
     if ([NSScroller respondsToSelector:@selector(preferredScrollerStyle)])
         return [NSScroller preferredScrollerStyle];
diff --git a/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp b/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
index a213d88..4ade634 100644
--- a/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
+++ b/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
@@ -123,6 +123,11 @@
     return m_webHandler->addICECandidate(iceCandidate);
 }
 
+bool RTCPeerConnectionHandler::addIceCandidate(PassRefPtr<RTCVoidRequest> request, WebKit::WebRTCICECandidate iceCandidate)
+{
+    return m_webHandler->addICECandidate(request, iceCandidate);
+}
+
 WebKit::WebRTCSessionDescription RTCPeerConnectionHandler::localDescription()
 {
     return m_webHandler->localDescription();
diff --git a/Source/core/platform/mediastream/RTCPeerConnectionHandler.h b/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
index a08ac84..5b0d689 100644
--- a/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
+++ b/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
@@ -73,7 +73,11 @@
     WebKit::WebRTCSessionDescription localDescription();
     WebKit::WebRTCSessionDescription remoteDescription();
     bool updateIce(PassRefPtr<RTCConfiguration>, PassRefPtr<MediaConstraints>);
+
+    // DEPRECATED
     bool addIceCandidate(WebKit::WebRTCICECandidate);
+
+    bool addIceCandidate(PassRefPtr<RTCVoidRequest>, WebKit::WebRTCICECandidate);
     bool addStream(PassRefPtr<MediaStreamDescriptor>, PassRefPtr<MediaConstraints>);
     void removeStream(PassRefPtr<MediaStreamDescriptor>);
     void getStats(PassRefPtr<RTCStatsRequest>);
diff --git a/Source/core/platform/mock/ScrollbarThemeMock.cpp b/Source/core/platform/mock/ScrollbarThemeMock.cpp
index ef05118..28f9ce6 100644
--- a/Source/core/platform/mock/ScrollbarThemeMock.cpp
+++ b/Source/core/platform/mock/ScrollbarThemeMock.cpp
@@ -25,7 +25,8 @@
 
 #include "config.h"
 #include "core/platform/mock/ScrollbarThemeMock.h"
-#include "core/page/Settings.h"
+
+#include "RuntimeEnabledFeatures.h"
 #include "core/platform/Scrollbar.h"
 
 namespace WebCore {
@@ -44,7 +45,7 @@
 
 bool ScrollbarThemeMock::usesOverlayScrollbars() const
 {
-    return Settings::usesOverlayScrollbars();
+    return RuntimeEnabledFeatures::overlayScrollbarsEnabled();
 }
 
 void ScrollbarThemeMock::paintTrackBackground(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& trackRect)
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/platform/mock/ScrollbarThemeOverlayMock.h
similarity index 75%
copy from Source/core/loader/CachedMetadata.cpp
copy to Source/core/platform/mock/ScrollbarThemeOverlayMock.h
index f3f2a30..0a9a862 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/platform/mock/ScrollbarThemeOverlayMock.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * 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
@@ -28,9 +28,20 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/loader/CachedMetadata.h"
+#ifndef ScrollbarThemeOverlayMock_h
+#define ScrollbarThemeOverlayMock_h
+
+#include "core/platform/ScrollbarThemeOverlay.h"
 
 namespace WebCore {
 
+class ScrollbarThemeOverlayMock : public ScrollbarThemeOverlay {
+public:
+    ScrollbarThemeOverlayMock() : ScrollbarThemeOverlay(3, 4, DisallowHitTest, Color(128, 128, 128)) { }
+
+private:
+    virtual bool isMockTheme() const OVERRIDE FINAL { return true; }
+};
+
 } // namespace WebCore
+#endif // ScrollbarThemeOverlayMock_h
diff --git a/Source/core/platform/network/ResourceResponse.cpp b/Source/core/platform/network/ResourceResponse.cpp
index 4210a5f..db90cab 100644
--- a/Source/core/platform/network/ResourceResponse.cpp
+++ b/Source/core/platform/network/ResourceResponse.cpp
@@ -134,9 +134,11 @@
     response->m_responseTime = data->m_responseTime;
     response->m_remoteIPAddress = data->m_remoteIPAddress;
     response->m_remotePort = data->m_remotePort;
+    response->m_downloadedFilePath = data->m_downloadedFilePath;
+    response->m_downloadedFileHandle = data->m_downloadedFileHandle;
 
-    // Bug https://bugs.webkit.org/show_bug.cgi?id=60397 this doesn't support m_downloadedFile,
-    // or whatever values may be present in the opaque m_extraData structure.
+    // Bug https://bugs.webkit.org/show_bug.cgi?id=60397 this doesn't support
+    // whatever values may be present in the opaque m_extraData structure.
 
     return response.release();
 }
@@ -167,9 +169,11 @@
     data->m_responseTime = m_responseTime;
     data->m_remoteIPAddress = m_remoteIPAddress.string().isolatedCopy();
     data->m_remotePort = m_remotePort;
+    data->m_downloadedFilePath = m_downloadedFilePath.isolatedCopy();
+    data->m_downloadedFileHandle = m_downloadedFileHandle;
 
-    // Bug https://bugs.webkit.org/show_bug.cgi?id=60397 this doesn't support m_downloadedFile,
-    // or whatever values may be present in the opaque m_extraData structure.
+    // Bug https://bugs.webkit.org/show_bug.cgi?id=60397 this doesn't support
+    // whatever values may be present in the opaque m_extraData structure.
 
     return data.release();
 }
@@ -537,6 +541,19 @@
     m_resourceLoadInfo = loadInfo;
 }
 
+void ResourceResponse::setDownloadedFilePath(const String& downloadedFilePath)
+{
+    m_downloadedFilePath = downloadedFilePath;
+    if (m_downloadedFilePath.isEmpty()) {
+        m_downloadedFileHandle.clear();
+        return;
+    }
+    OwnPtr<BlobData> blobData = BlobData::create();
+    blobData->appendFile(m_downloadedFilePath);
+    blobData->detachFromCurrentThread();
+    m_downloadedFileHandle = BlobDataHandle::create(blobData.release(), -1);
+}
+
 bool ResourceResponse::compare(const ResourceResponse& a, const ResourceResponse& b)
 {
     if (a.isNull() != b.isNull())
diff --git a/Source/core/platform/network/ResourceResponse.h b/Source/core/platform/network/ResourceResponse.h
index eaf40ea..7ce23ae 100644
--- a/Source/core/platform/network/ResourceResponse.h
+++ b/Source/core/platform/network/ResourceResponse.h
@@ -27,7 +27,7 @@
 #ifndef ResourceResponse_h
 #define ResourceResponse_h
 
-#include "core/fileapi/File.h"
+#include "core/platform/network/BlobData.h"
 #include "core/platform/network/HTTPHeaderMap.h"
 #include "core/platform/network/ResourceLoadInfo.h"
 #include "core/platform/network/ResourceLoadTiming.h"
@@ -168,8 +168,8 @@
     unsigned short remotePort() const { return m_remotePort; }
     void setRemotePort(unsigned short value) { m_remotePort = value; }
 
-    const File* downloadedFile() const { return m_downloadedFile.get(); }
-    void setDownloadedFile(PassRefPtr<File> downloadedFile) { m_downloadedFile = downloadedFile; }
+    const String& downloadedFilePath() const { return m_downloadedFilePath; }
+    void setDownloadedFilePath(const String&);
 
     // Extra data associated with this response.
     ExtraData* extraData() const { return m_extraData.get(); }
@@ -263,8 +263,12 @@
     // Remote port number of the socket which fetched this resource.
     unsigned short m_remotePort;
 
-    // The downloaded file if the load streamed to a file.
-    RefPtr<File> m_downloadedFile;
+    // The downloaded file path if the load streamed to a file.
+    String m_downloadedFilePath;
+
+    // The handle to the downloaded file to ensure the underlying file will not
+    // be deleted.
+    RefPtr<BlobDataHandle> m_downloadedFileHandle;
 
     // ExtraData associated with the response.
     RefPtr<ExtraData> m_extraData;
@@ -299,7 +303,8 @@
     double m_responseTime;
     String m_remoteIPAddress;
     unsigned short m_remotePort;
-    String m_downloadFilePath;
+    String m_downloadedFilePath;
+    RefPtr<BlobDataHandle> m_downloadedFileHandle;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/sql/SQLiteDatabase.cpp b/Source/core/platform/sql/SQLiteDatabase.cpp
index 5035f1e..8aa6689 100644
--- a/Source/core/platform/sql/SQLiteDatabase.cpp
+++ b/Source/core/platform/sql/SQLiteDatabase.cpp
@@ -178,7 +178,7 @@
     SQLiteStatement statement(*this, "PRAGMA max_page_count = " + String::number(newMaxPageCount));
     statement.prepare();
     if (statement.step() != SQLResultRow)
-#if OS(WINDOWS)
+#if OS(WIN)
         LOG_ERROR("Failed to set maximum size of database to %I64i bytes", static_cast<long long>(size));
 #else
         LOG_ERROR("Failed to set maximum size of database to %lli bytes", static_cast<long long>(size));
diff --git a/Source/core/platform/text/LineEnding.cpp b/Source/core/platform/text/LineEnding.cpp
index 9cf7ffa..53d8be3 100644
--- a/Source/core/platform/text/LineEnding.cpp
+++ b/Source/core/platform/text/LineEnding.cpp
@@ -220,7 +220,7 @@
 
 void normalizeLineEndingsToNative(const CString& from, Vector<char>& result)
 {
-#if OS(WINDOWS)
+#if OS(WIN)
     VectorCharAppendBuffer buffer(result);
     internalNormalizeLineEndingsToCRLF(from, buffer);
 #else
diff --git a/Source/core/plugins/DOMMimeType.h b/Source/core/plugins/DOMMimeType.h
index 1fb941d..cf8fb89 100644
--- a/Source/core/plugins/DOMMimeType.h
+++ b/Source/core/plugins/DOMMimeType.h
@@ -21,7 +21,6 @@
 #define DOMMimeType_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/page/Frame.h"
 #include "core/page/FrameDestructionObserver.h"
 #include "core/plugins/PluginData.h"
 #include "wtf/Forward.h"
@@ -32,6 +31,7 @@
 namespace WebCore {
 
 class DOMPlugin;
+class Frame;
 
 class DOMMimeType : public RefCounted<DOMMimeType>, public ScriptWrappable, public FrameDestructionObserver {
 public:
diff --git a/Source/core/plugins/IFrameShimSupport.cpp b/Source/core/plugins/IFrameShimSupport.cpp
index b5f67cb..4d7af1e 100644
--- a/Source/core/plugins/IFrameShimSupport.cpp
+++ b/Source/core/plugins/IFrameShimSupport.cpp
@@ -143,11 +143,10 @@
         const FrameView* frameView = toFrameView((*it).get());
         // Check to make sure we can get both the element and the RenderObject
         // for this FrameView, if we can't just move on to the next object.
-        if (!frameView->frame() || !frameView->frame()->ownerElement()
-            || !frameView->frame()->ownerElement()->renderer())
+        HTMLElement* element = frameView->frame().ownerElement();
+        if (!element || element->renderer())
             continue;
 
-        HTMLElement* element = frameView->frame()->ownerElement();
         RenderObject* iframeRenderer = element->renderer();
 
         if (element->hasTagName(HTMLNames::iframeTag)
diff --git a/Source/core/rendering/AutoTableLayout.cpp b/Source/core/rendering/AutoTableLayout.cpp
index fbccbaa..2c290c6 100644
--- a/Source/core/rendering/AutoTableLayout.cpp
+++ b/Source/core/rendering/AutoTableLayout.cpp
@@ -126,7 +126,7 @@
 
     // Nav/IE weirdness
     if (columnLayout.logicalWidth.isFixed()) {
-        if (m_table->document()->inQuirksMode() && columnLayout.maxLogicalWidth > columnLayout.logicalWidth.value() && fixedContributor != maxContributor) {
+        if (m_table->document().inQuirksMode() && columnLayout.maxLogicalWidth > columnLayout.logicalWidth.value() && fixedContributor != maxContributor) {
             columnLayout.logicalWidth = Length();
             fixedContributor = 0;
         }
diff --git a/Source/core/rendering/CompositingReasons.h b/Source/core/rendering/CompositingReasons.h
index 792f3ed..47713ee 100644
--- a/Source/core/rendering/CompositingReasons.h
+++ b/Source/core/rendering/CompositingReasons.h
@@ -6,6 +6,7 @@
 #define CompositingReasons_h
 
 #include "wtf/MathExtras.h"
+#include <stdint.h>
 
 namespace WebCore {
 
diff --git a/Source/core/rendering/CounterNode.cpp b/Source/core/rendering/CounterNode.cpp
index 86419c0..53957f8 100644
--- a/Source/core/rendering/CounterNode.cpp
+++ b/Source/core/rendering/CounterNode.cpp
@@ -22,9 +22,12 @@
 #include "config.h"
 #include "core/rendering/CounterNode.h"
 
-#include <stdio.h>
 #include "core/rendering/RenderCounter.h"
 
+#ifndef NDEBUG
+#include <stdio.h>
+#endif
+
 namespace WebCore {
 
 CounterNode::CounterNode(RenderObject* o, bool hasResetType, int value)
diff --git a/Source/core/rendering/EllipsisBox.cpp b/Source/core/rendering/EllipsisBox.cpp
index 7dcc2a9..c5cb7cf 100644
--- a/Source/core/rendering/EllipsisBox.cpp
+++ b/Source/core/rendering/EllipsisBox.cpp
@@ -48,7 +48,7 @@
 
         // Select the correct color for painting the text.
         Color foreground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionForegroundColor();
-        if (foreground != Color::transparent && foreground != styleTextColor)
+        if (foreground.isValid() && foreground != styleTextColor)
             context->setFillColor(foreground);
     }
 
@@ -61,8 +61,7 @@
             int shadowX = isHorizontal() ? shadow->x() : shadow->y();
             int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
             FloatSize offset(shadowX, shadowY);
-            drawLooper.addShadow(offset, shadow->blur(),
-                m_renderer->resolveColor(shadow->color(), Color::stdShadowColor),
+            drawLooper.addShadow(offset, shadow->blur(), m_renderer->resolveColor(shadow->color()),
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
         } while ((shadow = shadow->next()));
         drawLooper.addUnmodifiedContent();
@@ -132,7 +131,7 @@
 {
     Color textColor = m_renderer->resolveColor(style, CSSPropertyColor);
     Color c = m_renderer->selectionBackgroundColor();
-    if (!c.alpha())
+    if (!c.isValid() || !c.alpha())
         return;
 
     // If the text color ends up being the same as the selection background, invert the selection
diff --git a/Source/core/rendering/FilterEffectRenderer.cpp b/Source/core/rendering/FilterEffectRenderer.cpp
index f578722..b389aa4 100644
--- a/Source/core/rendering/FilterEffectRenderer.cpp
+++ b/Source/core/rendering/FilterEffectRenderer.cpp
@@ -270,7 +270,7 @@
             break;
         case FilterOperation::VALIDATED_CUSTOM: {
             ValidatedCustomFilterOperation* customFilterOperation = static_cast<ValidatedCustomFilterOperation*>(filterOperation);
-            Document* document = renderer ? renderer->document() : 0;
+            Document* document = renderer ? &renderer->document() : 0;
             effect = createCustomFilterEffect(this, document, customFilterOperation);
             if (effect)
                 m_hasCustomShaderFilter = true;
diff --git a/Source/core/rendering/FlowThreadController.cpp b/Source/core/rendering/FlowThreadController.cpp
index c061075..d7f0559 100644
--- a/Source/core/rendering/FlowThreadController.cpp
+++ b/Source/core/rendering/FlowThreadController.cpp
@@ -67,12 +67,12 @@
         }
     }
 
-    NamedFlowCollection* namedFlows = m_view->document()->namedFlows();
+    NamedFlowCollection* namedFlows = m_view->document().namedFlows();
 
     // Sanity check for the absence of a named flow in the "CREATED" state with the same name.
     ASSERT(!namedFlows->flowByName(name));
 
-    RenderNamedFlowThread* flowRenderer = RenderNamedFlowThread::createAnonymous(m_view->document(), namedFlows->ensureFlowWithName(name));
+    RenderNamedFlowThread* flowRenderer = RenderNamedFlowThread::createAnonymous(&m_view->document(), namedFlows->ensureFlowWithName(name));
     flowRenderer->setStyle(RenderFlowThread::createFlowThreadStyle(m_view->style()));
     m_renderNamedFlowThreadList->add(flowRenderer);
 
diff --git a/Source/core/rendering/HitTestLocation.cpp b/Source/core/rendering/HitTestLocation.cpp
index d09665d..f532480 100644
--- a/Source/core/rendering/HitTestLocation.cpp
+++ b/Source/core/rendering/HitTestLocation.cpp
@@ -25,22 +25,6 @@
 #include "HTMLNames.h"
 #include "SVGNames.h"
 #include "XLinkNames.h"
-#include "core/dom/DocumentMarkerController.h"
-#include "core/editing/FrameSelection.h"
-#include "core/fetch/ImageResource.h"
-#include "core/html/HTMLAnchorElement.h"
-#include "core/html/HTMLImageElement.h"
-#include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLMediaElement.h"
-#include "core/html/HTMLPlugInImageElement.h"
-#include "core/html/HTMLVideoElement.h"
-#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameTree.h"
-#include "core/platform/Scrollbar.h"
-#include "core/rendering/RenderBlock.h"
-#include "core/rendering/RenderImage.h"
-#include "core/rendering/RenderInline.h"
 
 namespace WebCore {
 
diff --git a/Source/core/rendering/HitTestLocation.h b/Source/core/rendering/HitTestLocation.h
index bf03f0d..3be7377 100644
--- a/Source/core/rendering/HitTestLocation.h
+++ b/Source/core/rendering/HitTestLocation.h
@@ -26,8 +26,6 @@
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/graphics/RoundedRect.h"
-#include "core/platform/text/TextDirection.h"
-#include "core/rendering/HitTestRequest.h"
 #include "wtf/Forward.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/OwnPtr.h"
diff --git a/Source/core/rendering/HitTestResult.cpp b/Source/core/rendering/HitTestResult.cpp
index d312652..8dc1cfc 100644
--- a/Source/core/rendering/HitTestResult.cpp
+++ b/Source/core/rendering/HitTestResult.cpp
@@ -112,12 +112,12 @@
 void HitTestResult::setToNodesInDocumentTreeScope()
 {
     if (Node* node = innerNode()) {
-        node = node->document()->ancestorInThisScope(node);
+        node = node->document().ancestorInThisScope(node);
         setInnerNode(node);
     }
 
     if (Node* node = innerNonSharedNode()) {
-        node = node->document()->ancestorInThisScope(node);
+        node = node->document().ancestorInThisScope(node);
         setInnerNonSharedNode(node);
     }
 }
@@ -166,9 +166,9 @@
 Frame* HitTestResult::innerNodeFrame() const
 {
     if (m_innerNonSharedNode)
-        return m_innerNonSharedNode->document()->frame();
+        return m_innerNonSharedNode->document().frame();
     if (m_innerNode)
-        return m_innerNode->document()->frame();
+        return m_innerNode->document().frame();
     return 0;
 }
 
@@ -177,7 +177,7 @@
     if (!m_innerURLElement)
         return 0;
 
-    Frame* frame = m_innerURLElement->document()->frame();
+    Frame* frame = m_innerURLElement->document().frame();
     if (!frame)
         return 0;
 
@@ -189,11 +189,9 @@
     if (!m_innerNonSharedNode)
         return false;
 
-    Frame* frame = m_innerNonSharedNode->document()->frame();
-    if (!frame)
-        return false;
-
-    return frame->selection()->contains(m_hitTestLocation.point());
+    if (Frame* frame = m_innerNonSharedNode->document().frame())
+        return frame->selection().contains(m_hitTestLocation.point());
+    return false;
 }
 
 String HitTestResult::spellingToolTip(TextDirection& dir) const
@@ -204,7 +202,7 @@
     if (!m_innerNonSharedNode)
         return String();
 
-    DocumentMarker* marker = m_innerNonSharedNode->document()->markers()->markerContainingPoint(m_hitTestLocation.point(), DocumentMarker::Grammar);
+    DocumentMarker* marker = m_innerNonSharedNode->document().markers()->markerContainingPoint(m_hitTestLocation.point(), DocumentMarker::Grammar);
     if (!marker)
         return String();
 
@@ -235,7 +233,7 @@
 {
     if (!node)
         return string;
-    return node->document()->displayStringModifiedByEncoding(string);
+    return node->document().displayStringModifiedByEncoding(string);
 }
 
 String HitTestResult::altDisplayString() const
@@ -280,7 +278,7 @@
 
 KURL HitTestResult::absoluteImageURL() const
 {
-    if (!(m_innerNonSharedNode && m_innerNonSharedNode->document()))
+    if (!m_innerNonSharedNode)
         return KURL();
 
     if (!(m_innerNonSharedNode->renderer() && m_innerNonSharedNode->renderer()->isImage()))
@@ -298,7 +296,7 @@
     } else
         return KURL();
 
-    return m_innerNonSharedNode->document()->completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
+    return m_innerNonSharedNode->document().completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
 }
 
 KURL HitTestResult::absoluteMediaURL() const
@@ -310,7 +308,7 @@
 
 HTMLMediaElement* HitTestResult::mediaElement() const
 {
-    if (!(m_innerNonSharedNode && m_innerNonSharedNode->document()))
+    if (!m_innerNonSharedNode)
         return 0;
 
     if (!(m_innerNonSharedNode->renderer() && m_innerNonSharedNode->renderer()->isMedia()))
@@ -323,7 +321,7 @@
 
 KURL HitTestResult::absoluteLinkURL() const
 {
-    if (!(m_innerURLElement && m_innerURLElement->document()))
+    if (!m_innerURLElement)
         return KURL();
 
     AtomicString urlString;
@@ -334,12 +332,12 @@
     else
         return KURL();
 
-    return m_innerURLElement->document()->completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
+    return m_innerURLElement->document().completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
 }
 
 bool HitTestResult::isLiveLink() const
 {
-    if (!(m_innerURLElement && m_innerURLElement->document()))
+    if (!m_innerURLElement)
         return false;
 
     if (isHTMLAnchorElement(m_innerURLElement.get()))
@@ -358,7 +356,7 @@
     VisiblePosition pos(targetNode()->renderer()->positionForPoint(localPoint()));
     if (pos.isNull())
         return false;
-    return m_innerNonSharedNode->document()->markers()->markersInRange(
+    return m_innerNonSharedNode->document().markers()->markersInRange(
         makeRange(pos, pos).get(), DocumentMarker::Spelling | DocumentMarker::Grammar).size() > 0;
 }
 
@@ -407,7 +405,7 @@
         return true;
 
     if (request.disallowsShadowContent())
-        node = node->document()->ancestorInThisScope(node);
+        node = node->document().ancestorInThisScope(node);
 
     mutableRectBasedTestResult().add(node);
 
@@ -427,7 +425,7 @@
         return true;
 
     if (request.disallowsShadowContent())
-        node = node->document()->ancestorInThisScope(node);
+        node = node->document().ancestorInThisScope(node);
 
     mutableRectBasedTestResult().add(node);
 
diff --git a/Source/core/rendering/ImageQualityController.cpp b/Source/core/rendering/ImageQualityController.cpp
index 373f8bf..ebe6fd7 100644
--- a/Source/core/rendering/ImageQualityController.cpp
+++ b/Source/core/rendering/ImageQualityController.cpp
@@ -109,7 +109,7 @@
     m_animatedResizeIsActive = false;
 
     for (ObjectLayerSizeMap::iterator it = m_objectLayerSizeMap.begin(); it != m_objectLayerSizeMap.end(); ++it) {
-        if (Frame* frame = it->key->document()->frame()) {
+        if (Frame* frame = it->key->document().frame()) {
             // If this renderer's containing FrameView is in live resize, punt the timer and hold back for now.
             if (frame->view() && frame->view()->inLiveResize()) {
                 restartTimer();
@@ -159,7 +159,7 @@
     LayoutSize scaledLayoutSize = currentTransform.mapSize(roundedIntSize(layoutSize));
 
     // If the containing FrameView is being resized, paint at low quality until resizing is finished.
-    if (Frame* frame = object->document()->frame()) {
+    if (Frame* frame = object->document().frame()) {
         bool frameViewIsCurrentlyInLiveResize = frame->view() && frame->view()->inLiveResize();
         if (frameViewIsCurrentlyInLiveResize) {
             set(object, innerMap, layer, scaledLayoutSize);
diff --git a/Source/core/rendering/InlineBox.cpp b/Source/core/rendering/InlineBox.cpp
index bfd9db6..fec2de0 100644
--- a/Source/core/rendering/InlineBox.cpp
+++ b/Source/core/rendering/InlineBox.cpp
@@ -204,23 +204,7 @@
     if (parent()->renderer()->style()->isFlippedBlocksWritingMode()) // Faster than calling containingBlock().
         childPoint = renderer()->containingBlock()->flipForWritingModeForChild(toRenderBox(renderer()), childPoint);
 
-    // Paint all phases of replaced elements atomically, as though the replaced element established its
-    // own stacking context.  (See Appendix E.2, section 6.4 on inline block/table elements in the CSS2.1
-    // specification.)
-    bool preservePhase = paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip;
-    PaintInfo info(paintInfo);
-    info.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
-    renderer()->paint(info, childPoint);
-    if (!preservePhase) {
-        info.phase = PaintPhaseChildBlockBackgrounds;
-        renderer()->paint(info, childPoint);
-        info.phase = PaintPhaseFloat;
-        renderer()->paint(info, childPoint);
-        info.phase = PaintPhaseForeground;
-        renderer()->paint(info, childPoint);
-        info.phase = PaintPhaseOutline;
-        renderer()->paint(info, childPoint);
-    }
+    RenderBlock::paintAsInlineBlock(renderer(), paintInfo, childPoint);
 }
 
 bool InlineBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
diff --git a/Source/core/rendering/InlineFlowBox.cpp b/Source/core/rendering/InlineFlowBox.cpp
index 089b2c5..f33c69e 100644
--- a/Source/core/rendering/InlineFlowBox.cpp
+++ b/Source/core/rendering/InlineFlowBox.cpp
@@ -1040,7 +1040,7 @@
     LayoutUnit height = frameRect.height();
 
     // Constrain our hit testing to the line top and bottom if necessary.
-    bool noQuirksMode = renderer()->document()->inNoQuirksMode();
+    bool noQuirksMode = renderer()->document().inNoQuirksMode();
     if (!noQuirksMode && !hasTextChildren() && !(descendantsHaveSameLineHeightAndBaseline() && hasTextDescendants())) {
         RootInlineBox* rootBox = root();
         LayoutUnit& top = isHorizontal() ? minY : minX;
@@ -1208,7 +1208,7 @@
 
 void InlineFlowBox::constrainToLineTopAndBottomIfNeeded(LayoutRect& rect) const
 {
-    bool noQuirksMode = renderer()->document()->inNoQuirksMode();
+    bool noQuirksMode = renderer()->document().inNoQuirksMode();
     if (!noQuirksMode && !hasTextChildren() && !(descendantsHaveSameLineHeightAndBaseline() && hasTextDescendants())) {
         const RootInlineBox* rootBox = root();
         LayoutUnit logicalTop = isHorizontal() ? rect.y() : rect.x();
diff --git a/Source/core/rendering/InlineIterator.h b/Source/core/rendering/InlineIterator.h
index d88205a..f277912 100644
--- a/Source/core/rendering/InlineIterator.h
+++ b/Source/core/rendering/InlineIterator.h
@@ -35,6 +35,11 @@
 // optionally notifying a BidiResolver every time it steps into/out of a RenderInline.
 class InlineIterator {
 public:
+    enum IncrementRule {
+        FastIncrementInlineRenderer,
+        FastIncrementInTextNode
+    };
+
     InlineIterator()
         : m_root(0)
         , m_obj(0)
@@ -70,7 +75,7 @@
     RenderObject* root() const { return m_root; }
 
     void fastIncrementInTextNode();
-    void increment(InlineBidiResolver* = 0);
+    void increment(InlineBidiResolver* = 0, IncrementRule = FastIncrementInTextNode);
     bool atEnd() const;
 
     inline bool atTextParagraphSeparator()
@@ -352,11 +357,11 @@
     bool m_atEndOfInline;
 };
 
-inline void InlineIterator::increment(InlineBidiResolver* resolver)
+inline void InlineIterator::increment(InlineBidiResolver* resolver, IncrementRule rule)
 {
     if (!m_obj)
         return;
-    if (m_obj->isText()) {
+    if (m_obj->isText() && rule == FastIncrementInTextNode) {
         fastIncrementInTextNode();
         if (m_pos < toRenderText(m_obj)->textLength())
             return;
@@ -414,14 +419,11 @@
     return object->isRenderInline() && isIsolated(object->style()->unicodeBidi());
 }
 
-static inline RenderObject* containingIsolate(RenderObject* object, RenderObject* root)
+static inline RenderObject* highestContainingIsolateWithinRoot(RenderObject* object, RenderObject* root)
 {
     ASSERT(object);
     RenderObject* containingIsolateObj = 0;
     while (object && object != root) {
-        if (containingIsolateObj && !isIsolatedInline(object))
-            break;
-
         if (isIsolatedInline(object))
             containingIsolateObj = object;
 
diff --git a/Source/core/rendering/InlineTextBox.cpp b/Source/core/rendering/InlineTextBox.cpp
index 16eba2c..2f90980 100644
--- a/Source/core/rendering/InlineTextBox.cpp
+++ b/Source/core/rendering/InlineTextBox.cpp
@@ -401,8 +401,7 @@
             int shadowX = horizontal ? shadow->x() : shadow->y();
             int shadowY = horizontal ? shadow->y() : -shadow->x();
             FloatSize offset(shadowX, shadowY);
-            drawLooper.addShadow(offset, shadow->blur(),
-                renderer->resolveColor(shadow->color(), Color::stdShadowColor),
+            drawLooper.addShadow(offset, shadow->blur(), renderer->resolveColor(shadow->color()),
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
         } while ((shadow = shadow->next()));
         drawLooper.addUnmodifiedContent();
@@ -493,7 +492,7 @@
     if (logicalStart >= paintEnd || logicalStart + logicalExtent <= paintStart)
         return;
 
-    bool isPrinting = textRenderer()->document()->printing();
+    bool isPrinting = textRenderer()->document().printing();
 
     // Determine whether or not we're selected.
     bool haveSelection = !isPrinting && paintInfo.phase != PaintPhaseTextClip && selectionState() != RenderObject::SelectionNone;
@@ -560,7 +559,7 @@
         if (isPrinting) {
             if (styleToUse->printColorAdjust() == PrintColorAdjustEconomy)
                 forceBackgroundToWhite = true;
-            if (textRenderer()->document()->settings() && textRenderer()->document()->settings()->shouldPrintBackgrounds())
+            if (textRenderer()->document().settings() && textRenderer()->document().settings()->shouldPrintBackgrounds())
                 forceBackgroundToWhite = false;
         }
 
@@ -592,14 +591,14 @@
     if (haveSelection) {
         // Check foreground color first.
         Color foreground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionForegroundColor();
-        if (foreground != Color::transparent && foreground != selectionFillColor) {
+        if (foreground.isValid() && foreground != selectionFillColor && foreground != Color::transparent) {
             if (!paintSelectedTextOnly)
                 paintSelectedTextSeparately = true;
             selectionFillColor = foreground;
         }
 
         Color emphasisMarkForeground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionEmphasisMarkColor();
-        if (emphasisMarkForeground != Color::transparent && emphasisMarkForeground != selectionEmphasisMarkColor) {
+        if (emphasisMarkForeground.isValid() && emphasisMarkForeground != selectionEmphasisMarkColor) {
             if (!paintSelectedTextOnly)
                 paintSelectedTextSeparately = true;
             selectionEmphasisMarkColor = emphasisMarkForeground;
@@ -839,7 +838,7 @@
         return;
 
     Color c = renderer()->selectionBackgroundColor();
-    if (!c.alpha())
+    if (!c.isValid() || !c.alpha())
         return;
 
     // If the text color ends up being the same as the selection background, invert the selection
@@ -1099,7 +1098,7 @@
         renderer()->getTextDecorationColors(deco, underline, overline, linethrough, true, true);
 
     // Use a special function for underlines to get the positioning exactly right.
-    bool isPrinting = textRenderer()->document()->printing();
+    bool isPrinting = textRenderer()->document().printing();
     context->setStrokeThickness(textDecorationThickness);
 
     bool linesAreOpaque = !isPrinting && (!(deco & TextDecorationUnderline) || underline.alpha() == 255) && (!(deco & TextDecorationOverline) || overline.alpha() == 255) && (!(deco & TextDecorationLineThrough) || linethrough.alpha() == 255);
@@ -1133,8 +1132,7 @@
             }
             int shadowX = isHorizontal() ? shadow->x() : shadow->y();
             int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
-            context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow->blur(),
-                renderer()->resolveColor(shadow->color(), Color::stdShadowColor));
+            context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow->blur(), shadow->color());
             shadow = shadow->next();
         }
 
@@ -1213,7 +1211,7 @@
 void InlineTextBox::paintDocumentMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font, bool grammar)
 {
     // Never print spelling/grammar markers (5327887)
-    if (textRenderer()->document()->printing())
+    if (textRenderer()->document().printing())
         return;
 
     if (m_truncation == cFullTruncation)
@@ -1311,7 +1309,7 @@
     if (!renderer()->node())
         return;
 
-    Vector<DocumentMarker*> markers = renderer()->document()->markers()->markersFor(renderer()->node());
+    Vector<DocumentMarker*> markers = renderer()->document().markers()->markersFor(renderer()->node());
     Vector<DocumentMarker*>::const_iterator markerIt = markers.begin();
 
     // Give any document markers that touch this run a chance to draw before the text has been drawn.
@@ -1403,7 +1401,7 @@
 
     ctx->setStrokeColor(underline.color);
     ctx->setStrokeThickness(lineThickness);
-    ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, textRenderer()->document()->printing());
+    ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, textRenderer()->document().printing());
 }
 
 int InlineTextBox::caretMinOffset() const
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/rendering/LayoutIndicator.cpp
similarity index 89%
copy from Source/core/loader/CachedMetadata.cpp
copy to Source/core/rendering/LayoutIndicator.cpp
index f3f2a30..a57c53c 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/rendering/LayoutIndicator.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * 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
@@ -29,8 +29,14 @@
  */
 
 #include "config.h"
-#include "core/loader/CachedMetadata.h"
+#include "core/rendering/LayoutIndicator.h"
 
 namespace WebCore {
 
-} // namespace WebCore
+#ifndef NDEBUG
+
+size_t LayoutIndicator::s_inLayout = 0;
+
+#endif
+
+}
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/rendering/LayoutIndicator.h
similarity index 74%
copy from Source/core/loader/CachedMetadata.cpp
copy to Source/core/rendering/LayoutIndicator.h
index f3f2a30..6337da9 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/rendering/LayoutIndicator.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * 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
@@ -28,9 +28,36 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/loader/CachedMetadata.h"
+#ifndef LayoutIndicator_h
+#define LayoutIndicator_h
+
+#include "wtf/Assertions.h"
 
 namespace WebCore {
 
-} // namespace WebCore
+#ifndef NDEBUG
+
+class LayoutIndicator {
+public:
+    LayoutIndicator() { ++s_inLayout; }
+    ~LayoutIndicator() { --s_inLayout; }
+
+    static bool inLayout() { return s_inLayout; }
+
+private:
+    static size_t s_inLayout;
+};
+
+#else
+
+class LayoutIndicator {
+public:
+    LayoutIndicator() { }
+    ~LayoutIndicator() { }
+};
+
+#endif
+
+}
+
+#endif // LayoutIndicator_h
diff --git a/Source/core/rendering/LayoutState.cpp b/Source/core/rendering/LayoutState.cpp
index 6d1b6fa..445aa35 100644
--- a/Source/core/rendering/LayoutState.cpp
+++ b/Source/core/rendering/LayoutState.cpp
@@ -126,7 +126,7 @@
         computeLineGridPaginationOrigin(renderer);
 
     // If we have a new grid to track, then add it to our set.
-    if (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isBlockFlow())
+    if (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isRenderBlockFlow())
         establishLineGrid(toRenderBlock(renderer));
 
     // FIXME: <http://bugs.webkit.org/show_bug.cgi?id=13443> Apply control clip if present.
diff --git a/Source/core/rendering/LayoutState.h b/Source/core/rendering/LayoutState.h
index 1bd336c..3271905 100644
--- a/Source/core/rendering/LayoutState.h
+++ b/Source/core/rendering/LayoutState.h
@@ -90,6 +90,10 @@
     bool needsBlockDirectionLocationSetBeforeLayout() const { return m_lineGrid || (m_isPaginated && m_pageLogicalHeight); }
 
     ShapeInsideInfo* shapeInsideInfo() const { return m_shapeInsideInfo; }
+
+#ifndef NDEBUG
+    RenderObject* renderer() const { return m_renderer; }
+#endif
 private:
     void propagateLineGridInfo(RenderBox*);
     void establishLineGrid(RenderBlock*);
diff --git a/Source/core/rendering/PartialLayoutState.h b/Source/core/rendering/PartialLayoutState.h
new file mode 100644
index 0000000..1ac7a32
--- /dev/null
+++ b/Source/core/rendering/PartialLayoutState.h
@@ -0,0 +1,103 @@
+/*
+ * 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 PartialLayoutState_h
+#define PartialLayoutState_h
+
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+class PartialLayoutState {
+    friend class PartialLayoutDisabler;
+public:
+    PartialLayoutState()
+        : m_shouldStop(false)
+        , m_stopAtRenderer(0)
+        , m_disableCount(0)
+    {
+    }
+
+    // True if we plan to do a partial layout, or are in the process of stopping a partial layout.
+    bool isPartialLayout() const { return m_stopAtRenderer || m_shouldStop; }
+
+    bool isStopping() const { return m_shouldStop; }
+    bool checkPartialLayoutComplete(const RenderObject*);
+    void setStopAtRenderer(const RenderObject* renderer) { m_stopAtRenderer = renderer; }
+    void reset() { m_shouldStop = false; m_stopAtRenderer = 0; }
+
+private:
+    void disable() { ASSERT(!m_shouldStop); m_disableCount++; }
+    void enable() { ASSERT(m_disableCount > 0); m_disableCount--; }
+    const RenderObject* stopAtRenderer() const { return m_disableCount > 0 ? 0 : m_stopAtRenderer; }
+
+    bool m_shouldStop;
+    const RenderObject* m_stopAtRenderer;
+    int m_disableCount;
+};
+
+inline bool PartialLayoutState::checkPartialLayoutComplete(const RenderObject* renderer)
+{
+    if (m_shouldStop)
+        return true;
+
+    if (renderer == stopAtRenderer()) {
+        m_shouldStop = true;
+        m_stopAtRenderer = 0;
+        return true;
+    }
+
+    return false;
+}
+
+class PartialLayoutDisabler {
+    WTF_MAKE_NONCOPYABLE(PartialLayoutDisabler);
+public:
+    PartialLayoutDisabler(PartialLayoutState& partialLayout, bool disable = true)
+        : m_partialLayout(partialLayout)
+        , m_disable(disable)
+    {
+        if (m_disable)
+            m_partialLayout.disable();
+    }
+
+    ~PartialLayoutDisabler()
+    {
+        if (m_disable)
+            m_partialLayout.enable();
+    }
+private:
+    PartialLayoutState& m_partialLayout;
+    bool m_disable;
+};
+
+} // namespace WebCore
+
+#endif // PartialLayoutState_h
diff --git a/Source/core/rendering/RenderBR.cpp b/Source/core/rendering/RenderBR.cpp
index af3390a..785f654 100644
--- a/Source/core/rendering/RenderBR.cpp
+++ b/Source/core/rendering/RenderBR.cpp
@@ -23,6 +23,7 @@
 #include "core/rendering/RenderBR.h"
 
 #include "core/dom/Document.h"
+#include "core/rendering/RenderView.h"
 
 namespace WebCore {
 
@@ -44,7 +45,7 @@
 
 int RenderBR::lineHeight(bool firstLine) const
 {
-    if (firstLine && document()->styleSheetCollections()->usesFirstLineRules()) {
+    if (firstLine && document().styleSheetCollections()->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 12adb97..20ac848 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -117,7 +117,7 @@
         , m_hadHorizontalLayoutOverflow(false)
         , m_hadVerticalLayoutOverflow(false)
     {
-        m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document()->hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
+        m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document().hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
         if (m_shouldDispatchEvent) {
             m_hadHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
             m_hadVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
@@ -135,7 +135,7 @@
         bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
         bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
         if (horizontalLayoutOverflowChanged || verticalLayoutOverflowChanged) {
-            if (FrameView* frameView = m_block->document()->view())
+            if (FrameView* frameView = m_block->document().view())
                 frameView->scheduleEvent(OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow), m_block->node());
         }
     }
@@ -225,7 +225,7 @@
 
 RenderBlock* RenderBlock::createAnonymous(Document* document)
 {
-    RenderBlock* renderer = new RenderBlock(0);
+    RenderBlock* renderer = new RenderBlockFlow(0);
     renderer->setDocumentForAnonymous(document);
     return renderer;
 }
@@ -961,7 +961,7 @@
         m_floatingObjects->clearLineBoxTreePointers();
     m_lineBoxes.deleteLineBoxTree();
 
-    if (AXObjectCache* cache = document()->existingAXObjectCache())
+    if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->recomputeIsIgnored(this);
 }
 
@@ -976,7 +976,7 @@
     m_lineBoxes.appendLineBox(rootBox);
 
     if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
-        if (AXObjectCache* cache = document()->existingAXObjectCache())
+        if (AXObjectCache* cache = document().existingAXObjectCache())
             cache->recomputeIsIgnored(this);
     }
 
@@ -1109,8 +1109,13 @@
            && prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
 }
 
-void RenderBlock::collapseAnonymousBoxChild(RenderBlock* parent, RenderObject* child)
+void RenderBlock::collapseAnonymousBlockChild(RenderBlock* parent, RenderBlock* child)
 {
+    // It's possible that this block's destruction may have been triggered by the
+    // child's removal. Just bail if the anonymous child block is already being
+    // destroyed. See crbug.com/282088
+    if (child->beingDestroyed())
+        return;
     parent->setNeedsLayoutAndPrefWidthsRecalc();
     parent->setChildrenInline(child->childrenInline());
     RenderObject* nextSibling = child->nextSibling();
@@ -1118,13 +1123,14 @@
     RenderFlowThread* childFlowThread = child->flowThreadContainingBlock();
     CurrentRenderFlowThreadMaintainer flowThreadMaintainer(childFlowThread);
 
-    RenderBlock* anonBlock = toRenderBlock(parent->children()->removeChildNode(parent, child, child->hasLayer()));
-    anonBlock->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
-    // Delete the now-empty block's lines and nuke it.
-    anonBlock->deleteLineBoxTree();
+    parent->children()->removeChildNode(parent, child, child->hasLayer());
+    child->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
+    // Explicitly delete the child's line box tree, or the special anonymous
+    // block handling in willBeDestroyed will cause problems.
+    child->deleteLineBoxTree();
     if (childFlowThread && childFlowThread->isRenderNamedFlowThread())
-        toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(anonBlock);
-    anonBlock->destroy();
+        toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(child);
+    child->destroy();
 }
 
 void RenderBlock::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
@@ -1236,16 +1242,16 @@
         // The removal has knocked us down to containing only a single anonymous
         // box.  We can go ahead and pull the content right back up into our
         // box.
-        collapseAnonymousBoxChild(this, child);
+        collapseAnonymousBlockChild(this, toRenderBlock(child));
     } else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && canCollapseAnonymousBlockChild()) {
         // It's possible that the removal has knocked us down to a single anonymous
         // block with pseudo-style element siblings (e.g. first-letter). If these
         // are floating, then we need to pull the content up also.
-        RenderBlock* anonBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
-        if ((anonBlock->previousSibling() || anonBlock->nextSibling())
-            && (!anonBlock->previousSibling() || (anonBlock->previousSibling()->style()->styleType() != NOPSEUDO && anonBlock->previousSibling()->isFloating() && !anonBlock->previousSibling()->previousSibling()))
-            && (!anonBlock->nextSibling() || (anonBlock->nextSibling()->style()->styleType() != NOPSEUDO && anonBlock->nextSibling()->isFloating() && !anonBlock->nextSibling()->nextSibling()))) {
-            collapseAnonymousBoxChild(this, anonBlock);
+        RenderBlock* anonymousBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
+        if ((anonymousBlock->previousSibling() || anonymousBlock->nextSibling())
+            && (!anonymousBlock->previousSibling() || (anonymousBlock->previousSibling()->style()->styleType() != NOPSEUDO && anonymousBlock->previousSibling()->isFloating() && !anonymousBlock->previousSibling()->previousSibling()))
+            && (!anonymousBlock->nextSibling() || (anonymousBlock->nextSibling()->style()->styleType() != NOPSEUDO && anonymousBlock->nextSibling()->isFloating() && !anonymousBlock->nextSibling()->nextSibling()))) {
+            collapseAnonymousBlockChild(this, anonymousBlock);
         }
     }
 
@@ -1298,7 +1304,7 @@
 
     Length logicalHeightLength = style()->logicalHeight();
     bool hasAutoHeight = logicalHeightLength.isAuto();
-    if (logicalHeightLength.isPercent() && !document()->inQuirksMode()) {
+    if (logicalHeightLength.isPercent() && !document().inQuirksMode()) {
         hasAutoHeight = true;
         for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
             if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
@@ -1386,6 +1392,9 @@
     // layoutBlock().
     layoutBlock(false);
 
+    if (frameView()->partialLayout().isStopping())
+        return;
+
     // It's safe to check for control clip here, since controls can never be table cells.
     // If we have a lightweight clip, there can never be any overflow from children.
     if (hasControlClip() && m_overflow)
@@ -1528,173 +1537,9 @@
     }
 }
 
-void RenderBlock::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
+void RenderBlock::layoutBlock(bool, LayoutUnit)
 {
-    ASSERT(needsLayout());
-
-    if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can
-        return;                                      // cause us to come in here.  Just bail.
-
-    if (!relayoutChildren && simplifiedLayout())
-        return;
-
-    LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
-
-    if (updateLogicalWidthAndColumnWidth())
-        relayoutChildren = true;
-
-    clearFloats();
-
-    LayoutUnit previousHeight = logicalHeight();
-    // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
-    // for consistency with other render classes?
-    setLogicalHeight(0);
-
-    bool pageLogicalHeightChanged = false;
-    bool hasSpecifiedPageLogicalHeight = false;
-    checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
-
-    RenderView* renderView = view();
-    RenderStyle* styleToUse = style();
-    LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
-
-    // Regions changing widths can force us to relayout our children.
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (logicalWidthChangedInRegions(flowThread))
-        relayoutChildren = true;
-    if (updateRegionsAndShapesLogicalSize(flowThread))
-        relayoutChildren = true;
-
-    // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
-    // our current maximal positive and negative margins.  These values are used when we
-    // are collapsed with adjacent blocks, so for example, if you have block A and B
-    // collapsing together, then you'd take the maximal positive margin from both A and B
-    // and subtract it from the maximal negative margin from both A and B to get the
-    // true collapsed margin.  This algorithm is recursive, so when we finish layout()
-    // our block knows its current maximal positive/negative values.
-    //
-    // Start out by setting our margin values to our current margins.  Table cells have
-    // no margins, so we don't fill in the values for table cells.
-    bool isCell = isTableCell();
-    if (!isCell) {
-        initMaxMarginValues();
-
-        setHasMarginBeforeQuirk(styleToUse->hasMarginBeforeQuirk());
-        setHasMarginAfterQuirk(styleToUse->hasMarginAfterQuirk());
-        setPaginationStrut(0);
-    }
-
-    SubtreeLayoutScope layoutScope(this);
-
-    LayoutUnit repaintLogicalTop = 0;
-    LayoutUnit repaintLogicalBottom = 0;
-    LayoutUnit maxFloatLogicalBottom = 0;
-    if (!firstChild() && !isAnonymousBlock())
-        setChildrenInline(true);
-    if (childrenInline())
-        layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
-    else
-        layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom, layoutScope);
-
-    // Expand our intrinsic height to encompass floats.
-    LayoutUnit toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
-    if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
-        setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
-
-    if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher))
-        return;
-
-    // Calculate our new height.
-    LayoutUnit oldHeight = logicalHeight();
-    LayoutUnit oldClientAfterEdge = clientLogicalBottom();
-
-    // Before updating the final size of the flow thread make sure a forced break is applied after the content.
-    // This ensures the size information is correctly computed for the last auto-height region receiving content.
-    if (isRenderFlowThread())
-        toRenderFlowThread(this)->applyBreakAfterContent(oldClientAfterEdge);
-
-    updateLogicalHeight();
-    LayoutUnit newHeight = logicalHeight();
-    if (oldHeight != newHeight) {
-        if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
-            // One of our children's floats may have become an overhanging float for us. We need to look for it.
-            for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
-                if (child->isBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
-                    RenderBlock* block = toRenderBlock(child);
-                    if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
-                        addOverhangingFloats(block, false);
-                }
-            }
-        }
-    }
-
-    bool heightChanged = (previousHeight != newHeight);
-    if (heightChanged)
-        relayoutChildren = true;
-
-    layoutPositionedObjects(relayoutChildren || isRoot());
-
-    updateRegionsAndShapesAfterChildLayout(flowThread, heightChanged);
-
-    // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
-    computeOverflow(oldClientAfterEdge);
-
-    statePusher.pop();
-
-    fitBorderToLinesIfNeeded();
-
-    if (renderView->layoutState()->m_pageLogicalHeight)
-        setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
-
-    updateLayerTransform();
-
-    // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
-    // we overflow or not.
-    updateScrollInfoAfterLayout();
-
-    // FIXME: This repaint logic should be moved into a separate helper function!
-    // Repaint with our new bounds if they are different from our old bounds.
-    bool didFullRepaint = repainter.repaintAfterLayout();
-    if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
-        // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
-        // it had to lay out.  We wouldn't need the hasOverflowClip() hack in that case either.
-        LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
-        LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
-        if (hasOverflowClip()) {
-            // If we have clipped overflow, we should use layout overflow as well, since visual overflow from lines didn't propagate to our block's overflow.
-            // Note the old code did this as well but even for overflow:visible.  The addition of hasOverflowClip() at least tightens up the hack a bit.
-            // layoutInlineChildren should be patched to compute the entire repaint rect.
-            repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
-            repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
-        }
-
-        LayoutRect repaintRect;
-        if (isHorizontalWritingMode())
-            repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
-        else
-            repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
-
-        // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
-        adjustRectForColumns(repaintRect);
-
-        repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
-
-        if (hasOverflowClip()) {
-            // Adjust repaint rect for scroll offset
-            repaintRect.move(-scrolledContentOffset());
-
-            // Don't allow this rect to spill out of our overflow box.
-            repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
-        }
-
-        // Make sure the rect is still non-empty after intersecting for overflow above
-        if (!repaintRect.isEmpty()) {
-            repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
-            if (hasReflection())
-                repaintRectangle(reflectedRect(repaintRect));
-        }
-    }
-
+    ASSERT_NOT_REACHED();
     clearNeedsLayout();
 }
 
@@ -1898,8 +1743,8 @@
     ASSERT(runIn->node());
 
     RenderBoxModelObject* newRunIn = 0;
-    if (!runIn->isRenderBlock())
-        newRunIn = new RenderBlock(runIn->node());
+    if (!runIn->isRenderBlockFlow())
+        newRunIn = new RenderBlockFlow(runIn->node());
     else
         newRunIn = new RenderInline(toElement(runIn->node()));
 
@@ -1920,8 +1765,8 @@
     if (!runIn->childrenInline())
         return;
 
-    // FIXME: We don't handle non-block elements with run-in for now.
-    if (!runIn->isRenderBlock())
+    // FIXME: We don't handle non-block flow elements with run-in for now.
+    if (!runIn->isRenderBlockFlow())
         return;
 
     // FIXME: We don't support run-ins with or as part of a continuation
@@ -2037,7 +1882,7 @@
             // 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)
+            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
@@ -2106,7 +1951,7 @@
             logicalTop = logicalHeight();
         } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
             || (!marginInfo.canCollapseMarginBeforeWithChildren()
-            && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
+            && (!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));
@@ -2141,7 +1986,7 @@
     LayoutUnit oldLogicalHeight = logicalHeight();
     setLogicalHeight(logicalTop);
     RenderObject* prev = child->previousSibling();
-    if (prev && prev->isBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
+    if (prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
         RenderBlock* block = toRenderBlock(prev);
         if (block->containsFloats() && !block->avoidsFloats() && (block->logicalTop() + block->lowestFloatLogicalBottom()) > logicalTop)
             addOverhangingFloats(block, false);
@@ -2222,7 +2067,7 @@
     // 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)
+    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.
@@ -2324,10 +2169,9 @@
     return logicalTopEstimate;
 }
 
-LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart,
-    RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
+LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* region)
 {
-    LayoutUnit startPosition = startOffsetForContent(region, offsetFromLogicalTopOfFirstPage);
+    LayoutUnit startPosition = startOffsetForContent(region);
 
     // Add in our start margin.
     LayoutUnit oldPosition = startPosition + childMarginStart;
@@ -2335,9 +2179,9 @@
 
     LayoutUnit blockOffset = logicalTopForChild(child);
     if (region)
-        blockOffset = max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage));
+        blockOffset = max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage()));
 
-    LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, offsetFromLogicalTopOfFirstPage, logicalHeightForChild(child));
+    LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, logicalHeightForChild(child));
 
     if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
         if (childMarginStart < 0)
@@ -2399,7 +2243,7 @@
 
     // 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())))
+        && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
         setLogicalHeight(logicalHeight() + marginInfo.margin());
 
     // Now add in our bottom border/padding.
@@ -2451,77 +2295,6 @@
         child->setPreferredLogicalWidthsDirty(MarkOnlyThis);
 }
 
-void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope& layoutScope)
-{
-    if (gPercentHeightDescendantsMap) {
-        if (TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this)) {
-            TrackedRendererListHashSet::iterator end = descendants->end();
-            for (TrackedRendererListHashSet::iterator it = descendants->begin(); it != end; ++it) {
-                RenderBox* box = *it;
-                while (box != this) {
-                    if (box->normalChildNeedsLayout())
-                        break;
-                    layoutScope.setChildNeedsLayout(box);
-                    box = box->containingBlock();
-                    ASSERT(box);
-                    if (!box)
-                        break;
-                }
-            }
-        }
-    }
-
-    LayoutUnit beforeEdge = borderBefore() + paddingBefore();
-    LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
-
-    setLogicalHeight(beforeEdge);
-
-    // Lay out our hypothetical grid line as though it occurs at the top of the block.
-    if (view()->layoutState()->lineGrid() == this)
-        layoutLineGridBox();
-
-    // The margin struct caches all our current margin collapsing state.  The compact struct caches state when we encounter compacts,
-    MarginInfo marginInfo(this, beforeEdge, afterEdge);
-
-    // Fieldsets need to find their legend and position it inside the border of the object.
-    // The legend then gets skipped during normal layout.  The same is true for ruby text.
-    // It doesn't get included in the normal layout process but is instead skipped.
-    RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren, layoutScope);
-
-    LayoutUnit previousFloatLogicalBottom = 0;
-    maxFloatLogicalBottom = 0;
-
-    RenderBox* next = firstChildBox();
-
-    while (next) {
-        RenderBox* child = next;
-        next = child->nextSiblingBox();
-
-        if (childToExclude == child)
-            continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
-
-        updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
-
-        if (child->isOutOfFlowPositioned()) {
-            child->containingBlock()->insertPositionedObject(child);
-            adjustPositionedBlock(child, marginInfo);
-            continue;
-        }
-        if (child->isFloating()) {
-            insertFloatingObject(child);
-            adjustFloatingBlock(marginInfo);
-            continue;
-        }
-
-        // Lay out the child.
-        layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
-    }
-
-    // Now do the handling of the bottom of the block, adding in our bottom border/padding and
-    // determining the correct collapsed bottom margin information.
-    handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
-}
-
 void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
 {
     LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
@@ -2580,6 +2353,9 @@
     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();
 
@@ -3079,7 +2855,7 @@
     // Avoid painting descendants of the root element when stylesheets haven't loaded.  This eliminates FOUC.
     // It's ok not to draw, because later on, when all the stylesheets do load, styleResolverChanged() on the Document
     // will do a full repaint.
-    if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
+    if (document().didLayoutWithPendingStylesheets() && !isRenderView())
         return;
 
     if (childrenInline())
@@ -3109,6 +2885,38 @@
         child->paint(paintInfo, childPoint);
 }
 
+void RenderBlock::paintChildAsInlineBlock(RenderBox* child, PaintInfo& paintInfo, const LayoutPoint& paintOffset)
+{
+    LayoutPoint childPoint = flipForWritingModeForChild(child, paintOffset);
+    if (!child->hasSelfPaintingLayer() && !child->isFloating())
+        paintAsInlineBlock(child, paintInfo, childPoint);
+}
+
+void RenderBlock::paintAsInlineBlock(RenderObject* renderer, PaintInfo& paintInfo, const LayoutPoint& childPoint)
+{
+    if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection)
+        return;
+
+    // Paint all phases atomically, as though the element established its own
+    // stacking context.  (See Appendix E.2, section 7.2.1.4 on
+    // inline block/table/replaced elements in the CSS2.1 specification.)
+    // This is also used by other elements (e.g. flex items and grid items).
+    bool preservePhase = paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip;
+    PaintInfo info(paintInfo);
+    info.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
+    renderer->paint(info, childPoint);
+    if (!preservePhase) {
+        info.phase = PaintPhaseChildBlockBackgrounds;
+        renderer->paint(info, childPoint);
+        info.phase = PaintPhaseFloat;
+        renderer->paint(info, childPoint);
+        info.phase = PaintPhaseForeground;
+        renderer->paint(info, childPoint);
+        info.phase = PaintPhaseOutline;
+        renderer->paint(info, childPoint);
+    }
+}
+
 bool RenderBlock::hasCaret(CaretType type) const
 {
     // Paint the caret if the FrameSelection says so or if caret browsing is enabled
@@ -3116,8 +2924,8 @@
     RenderObject* caretPainter;
     bool isContentEditable;
     if (type == CursorCaret) {
-        caretPainter = frame()->selection()->caretRenderer();
-        isContentEditable = frame()->selection()->rendererIsEditable();
+        caretPainter = frame()->selection().caretRenderer();
+        isContentEditable = frame()->selection().rendererIsEditable();
     } else {
         caretPainter = frame()->page()->dragCaretController().caretRenderer();
         isContentEditable = frame()->page()->dragCaretController().isContentEditable();
@@ -3131,7 +2939,7 @@
         return;
 
     if (type == CursorCaret)
-        frame()->selection()->paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
+        frame()->selection().paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
     else
         frame()->page()->dragCaretController().paintDragCaret(frame(), paintInfo.context, paintOffset, paintInfo.rect);
 }
@@ -3172,7 +2980,7 @@
 
     // 3. paint selection
     // FIXME: Make this work with multi column layouts.  For now don't fill gaps.
-    bool isPrinting = document()->printing();
+    bool isPrinting = document().printing();
     if (!isPrinting && !hasColumns())
         paintSelection(paintInfo, scrolledOffset); // Fill in gaps in selection on lines and between blocks.
 
@@ -3485,7 +3293,7 @@
     // FIXME: overflow: auto/scroll regions need more math here, since painting in the border box is different from painting in the padding box (one is scrolled, the other is
     // fixed).
     GapRects result;
-    if (!isBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
+    if (!isRenderBlockFlow() && !isFlexibleBoxIncludingDeprecated()) // FIXME: Make multi-column selection gap filling work someday.
         return result;
 
     if (hasColumns() || hasTransform() || style()->columnSpan()) {
@@ -4206,6 +4014,30 @@
     return gPercentHeightContainerMap->contains(descendant);
 }
 
+void RenderBlock::dirtyForLayoutFromPercentageHeightDescendants(SubtreeLayoutScope& layoutScope)
+{
+    if (!gPercentHeightDescendantsMap)
+        return;
+
+    TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this);
+    if (!descendants)
+        return;
+
+    TrackedRendererListHashSet::iterator end = descendants->end();
+    for (TrackedRendererListHashSet::iterator it = descendants->begin(); it != end; ++it) {
+        RenderBox* box = *it;
+        while (box != this) {
+            if (box->normalChildNeedsLayout())
+                break;
+            layoutScope.setChildNeedsLayout(box);
+            box = box->containingBlock();
+            ASSERT(box);
+            if (!box)
+                break;
+        }
+    }
+}
+
 void RenderBlock::removePercentHeightDescendantIfNeeded(RenderBox* descendant)
 {
     // We query the map directly, rather than looking at style's
@@ -4246,22 +4078,22 @@
     return minimumValueForLength(style()->textIndent(), cw, renderView);
 }
 
-LayoutUnit RenderBlock::logicalLeftOffsetForContent(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+LayoutUnit RenderBlock::logicalLeftOffsetForContent(RenderRegion* region) const
 {
     LayoutUnit logicalLeftOffset = style()->isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
     if (!region)
         return logicalLeftOffset;
-    LayoutRect boxRect = borderBoxRectInRegion(region, offsetFromLogicalTopOfFirstPage);
+    LayoutRect boxRect = borderBoxRectInRegion(region);
     return logicalLeftOffset + (isHorizontalWritingMode() ? boxRect.x() : boxRect.y());
 }
 
-LayoutUnit RenderBlock::logicalRightOffsetForContent(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+LayoutUnit RenderBlock::logicalRightOffsetForContent(RenderRegion* region) const
 {
     LayoutUnit logicalRightOffset = style()->isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
     logicalRightOffset += availableLogicalWidth();
     if (!region)
         return logicalRightOffset;
-    LayoutRect boxRect = borderBoxRectInRegion(region, offsetFromLogicalTopOfFirstPage);
+    LayoutRect boxRect = borderBoxRectInRegion(region);
     return logicalRightOffset - (logicalWidth() - (isHorizontalWritingMode() ? boxRect.maxX() : boxRect.maxY()));
 }
 
@@ -4408,154 +4240,6 @@
     }
 }
 
-void RenderBlock::clearFloats()
-{
-    if (m_floatingObjects)
-        m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
-
-    HashSet<RenderBox*> oldIntrudingFloatSet;
-    if (!childrenInline() && m_floatingObjects) {
-        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-        FloatingObjectSetIterator end = floatingObjectSet.end();
-        for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-            FloatingObject* floatingObject = *it;
-            if (!floatingObject->isDescendant())
-                oldIntrudingFloatSet.add(floatingObject->renderer());
-        }
-    }
-
-    // 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())
-            markAllDescendantsWithFloatsForLayout();
-        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();
-    }
-
-    // We should not process floats if the parent node is not a RenderBlock. Otherwise, we will add
-    // floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
-    // See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
-    if (!parent() || !parent()->isRenderBlock())
-        return;
-
-    // Attempt to locate a previous sibling with overhanging floats.  We skip any elements that are
-    // out of flow (like floating/positioned elements), and we also skip over any objects that may have shifted
-    // to avoid floats.
-    RenderBlock* parentBlock = toRenderBlock(parent());
-    bool parentHasFloats = false;
-    RenderObject* prev = previousSibling();
-    while (prev && (prev->isFloatingOrOutOfFlowPositioned() || !prev->isBox() || !prev->isRenderBlock() || toRenderBlock(prev)->avoidsFloats())) {
-        if (prev->isFloating())
-            parentHasFloats = true;
-        prev = prev->previousSibling();
-    }
-
-    // First add in floats from the parent.
-    LayoutUnit logicalTopOffset = logicalTop();
-    if (parentHasFloats)
-        addIntrudingFloats(parentBlock, parentBlock->logicalLeftOffsetForContent(), logicalTopOffset);
-
-    LayoutUnit logicalLeftOffset = 0;
-    if (prev)
-        logicalTopOffset -= toRenderBox(prev)->logicalTop();
-    else {
-        prev = parentBlock;
-        logicalLeftOffset += parentBlock->logicalLeftOffsetForContent();
-    }
-
-    // Add overhanging floats from the previous RenderBlock, but only if it has a float that intrudes into our space.
-    RenderBlock* block = toRenderBlock(prev);
-    if (block->m_floatingObjects && block->lowestFloatLogicalBottom() > logicalTopOffset)
-        addIntrudingFloats(block, logicalLeftOffset, logicalTopOffset);
-
-    if (childrenInline()) {
-        LayoutUnit changeLogicalTop = LayoutUnit::max();
-        LayoutUnit changeLogicalBottom = LayoutUnit::min();
-        if (m_floatingObjects) {
-            const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-            FloatingObjectSetIterator end = floatingObjectSet.end();
-            for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
-                FloatingObject* f = *it;
-                FloatingObject* oldFloatingObject = floatMap.get(f->renderer());
-                LayoutUnit logicalBottom = f->logicalBottom(isHorizontalWritingMode());
-                if (oldFloatingObject) {
-                    LayoutUnit oldLogicalBottom = oldFloatingObject->logicalBottom(isHorizontalWritingMode());
-                    if (f->logicalWidth(isHorizontalWritingMode()) != oldFloatingObject->logicalWidth(isHorizontalWritingMode()) || f->logicalLeft(isHorizontalWritingMode()) != oldFloatingObject->logicalLeft(isHorizontalWritingMode())) {
-                        changeLogicalTop = 0;
-                        changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
-                    } else {
-                        if (logicalBottom != oldLogicalBottom) {
-                            changeLogicalTop = min(changeLogicalTop, min(logicalBottom, oldLogicalBottom));
-                            changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
-                        }
-                        LayoutUnit logicalTop = f->logicalTop(isHorizontalWritingMode());
-                        LayoutUnit oldLogicalTop = oldFloatingObject->logicalTop(isHorizontalWritingMode());
-                        if (logicalTop != oldLogicalTop) {
-                            changeLogicalTop = min(changeLogicalTop, min(logicalTop, oldLogicalTop));
-                            changeLogicalBottom = max(changeLogicalBottom, max(logicalTop, oldLogicalTop));
-                        }
-                    }
-
-                    floatMap.remove(f->renderer());
-                    if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
-                        ASSERT(oldFloatingObject->originatingLine()->renderer() == this);
-                        oldFloatingObject->originatingLine()->markDirty();
-                    }
-                    delete oldFloatingObject;
-                } else {
-                    changeLogicalTop = 0;
-                    changeLogicalBottom = max(changeLogicalBottom, logicalBottom);
-                }
-            }
-        }
-
-        RendererToFloatInfoMap::iterator end = floatMap.end();
-        for (RendererToFloatInfoMap::iterator it = floatMap.begin(); it != end; ++it) {
-            FloatingObject* floatingObject = (*it).value;
-            if (!floatingObject->isDescendant()) {
-                changeLogicalTop = 0;
-                changeLogicalBottom = max(changeLogicalBottom, floatingObject->logicalBottom(isHorizontalWritingMode()));
-            }
-        }
-        deleteAllValues(floatMap);
-
-        markLinesDirtyInBlockRange(changeLogicalTop, changeLogicalBottom);
-    } else if (!oldIntrudingFloatSet.isEmpty()) {
-        // If there are previously intruding floats that no longer intrude, then children with floats
-        // should also get layout because they might need their floating object lists cleared.
-        if (m_floatingObjects->set().size() < oldIntrudingFloatSet.size())
-            markAllDescendantsWithFloatsForLayout();
-        else {
-            const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
-            FloatingObjectSetIterator end = floatingObjectSet.end();
-            for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
-                oldIntrudingFloatSet.remove((*it)->renderer());
-            if (!oldIntrudingFloatSet.isEmpty())
-                markAllDescendantsWithFloatsForLayout();
-        }
-    }
-}
-
 LayoutUnit RenderBlock::addOverhangingFloats(RenderBlock* child, bool makeChildPaintOtherFloats)
 {
     // Prevent floats from being added to the canvas by the root element, e.g., <html>.
@@ -4780,7 +4464,7 @@
                 return newLogicalTop - logicalTop;
 
             RenderRegion* region = regionAtBlockOffset(logicalTopForChild(child));
-            LayoutRect borderBox = child->borderBoxRectInRegion(region, offsetFromLogicalTopOfFirstPage() + logicalTopForChild(child), DoNotCacheRenderBoxRegionInfo);
+            LayoutRect borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
             LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
 
             // FIXME: None of this is right for perpendicular writing-mode children.
@@ -4792,7 +4476,7 @@
             child->setLogicalTop(newLogicalTop);
             child->updateLogicalWidth();
             region = regionAtBlockOffset(logicalTopForChild(child));
-            borderBox = child->borderBoxRectInRegion(region, offsetFromLogicalTopOfFirstPage() + logicalTopForChild(child), DoNotCacheRenderBoxRegionInfo);
+            borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
             LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
 
             child->setLogicalTop(childOldLogicalTop);
@@ -5152,7 +4836,7 @@
         }
     }
 
-    bool moveCaretToBoundary = document()->frame()->editor().behavior().shouldMoveCaretToHorizontalBoundaryWhenPastTopOrBottom();
+    bool moveCaretToBoundary = document().frame()->editor().behavior().shouldMoveCaretToHorizontalBoundaryWhenPastTopOrBottom();
 
     if (!moveCaretToBoundary && !closestBox && lastRootBoxWithChildren) {
         // y coordinate is below last root line box, pretend we hit it
@@ -5212,9 +4896,13 @@
         LayoutUnit pointLogicalLeft = isHorizontalWritingMode() ? point.x() : point.y();
         LayoutUnit pointLogicalTop = isHorizontalWritingMode() ? point.y() : point.x();
 
-        if (pointLogicalTop < 0 || (pointLogicalTop < logicalHeight() && pointLogicalLeft < 0))
+        if (pointLogicalLeft < 0)
             return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
-        if (pointLogicalTop >= logicalHeight() || (pointLogicalTop >= 0 && pointLogicalLeft >= logicalWidth()))
+        if (pointLogicalLeft >= logicalWidth())
+            return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM);
+        if (pointLogicalTop < 0)
+            return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
+        if (pointLogicalTop >= logicalHeight())
             return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM);
     }
 
@@ -5282,7 +4970,7 @@
 
 void RenderBlock::calcColumnWidth()
 {
-    if (document()->regionBasedColumnsEnabled())
+    if (document().regionBasedColumnsEnabled())
         return;
 
     // Calculate our column width and column count.
@@ -5291,7 +4979,7 @@
     LayoutUnit desiredColumnWidth = contentLogicalWidth();
 
     // For now, we don't support multi-column layouts when printing, since we have to do a lot of work for proper pagination.
-    if (document()->paginated() || (style()->hasAutoColumnCount() && style()->hasAutoColumnWidth()) || !style()->hasInlineColumnAxis()) {
+    if (document().paginated() || (style()->hasAutoColumnCount() && style()->hasAutoColumnWidth()) || !style()->hasInlineColumnAxis()) {
         setDesiredColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
         return;
     }
@@ -5711,6 +5399,8 @@
 
     maxLogicalWidth = max(minLogicalWidth, maxLogicalWidth);
 
+    adjustIntrinsicLogicalWidthsForColumns(minLogicalWidth, maxLogicalWidth);
+
     // A horizontal marquee with inline children has no minimum width.
     if (childrenInline() && isMarquee() && toRenderMarquee(this)->isHorizontal())
         minLogicalWidth = 0;
@@ -5767,6 +5457,33 @@
     clearPreferredLogicalWidthsDirty();
 }
 
+void RenderBlock::adjustIntrinsicLogicalWidthsForColumns(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
+{
+    // FIXME: make this method virtual and move the code to RenderMultiColumnBlock once the old
+    // multicol code is gone.
+
+    if (!style()->hasAutoColumnCount() || !style()->hasAutoColumnWidth()) {
+        // The min/max intrinsic widths calculated really tell how much space elements need when
+        // laid out inside the columns. In order to eventually end up with the desired column width,
+        // we need to convert them to values pertaining to the multicol container.
+        int columnCount = style()->hasAutoColumnCount() ? 1 : style()->columnCount();
+        LayoutUnit columnWidth;
+        LayoutUnit gapExtra = (columnCount - 1) * columnGap();
+        if (style()->hasAutoColumnWidth()) {
+            minLogicalWidth = minLogicalWidth * columnCount + gapExtra;
+        } else {
+            columnWidth = style()->columnWidth();
+            minLogicalWidth = min(minLogicalWidth, columnWidth);
+        }
+        // FIXME: If column-count is auto here, we should resolve it to calculate the maximum
+        // intrinsic width, instead of pretending that it's 1. The only way to do that is by
+        // performing a layout pass, but this is not an appropriate time or place for layout. The
+        // good news is that if height is unconstrained and there are no explicit breaks, the
+        // resolved column-count really should be 1.
+        maxLogicalWidth = max(maxLogicalWidth, columnWidth) * columnCount + gapExtra;
+    }
+}
+
 struct InlineMinMaxIterator {
 /* InlineMinMaxIterator is a class that will iterate over all render objects that contribute to
    inline min/max width calculations.  Note the following about the way it walks:
@@ -5898,7 +5615,7 @@
     // Firefox and Opera will allow a table cell to grow to fit an image inside it under
     // very specific cirucumstances (in order to match common WinIE renderings).
     // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
-    bool allowImagesToBreak = !document()->inQuirksMode() || !isTableCell() || !styleToUse->logicalWidth().isIntrinsicOrAuto();
+    bool allowImagesToBreak = !document().inQuirksMode() || !isTableCell() || !styleToUse->logicalWidth().isIntrinsicOrAuto();
 
     bool autoWrap, oldAutoWrap;
     autoWrap = oldAutoWrap = styleToUse->autoWrap();
@@ -6301,7 +6018,7 @@
     if (isReplaced() && linePositionMode == PositionOnContainingLine)
         return RenderBox::lineHeight(firstLine, direction, linePositionMode);
 
-    if (firstLine && document()->styleSheetCollections()->usesFirstLineRules()) {
+    if (firstLine && document().styleSheetCollections()->usesFirstLineRules()) {
         RenderStyle* s = style(firstLine);
         if (s != style())
             return s->computedLineHeight(view());
@@ -6363,7 +6080,7 @@
 
 int RenderBlock::firstLineBoxBaseline() const
 {
-    if (!isBlockFlow() || (isWritingModeRoot() && !isRubyRun()))
+    if (isWritingModeRoot() && !isRubyRun())
         return -1;
 
     if (childrenInline()) {
@@ -6397,7 +6114,7 @@
 
 int RenderBlock::lastLineBoxBaseline(LineDirectionMode lineDirection) const
 {
-    if (!isBlockFlow() || (isWritingModeRoot() && !isRubyRun()))
+    if (isWritingModeRoot() && !isRubyRun())
         return -1;
 
     if (childrenInline()) {
@@ -6447,8 +6164,8 @@
         // FIXME: Remove when buttons are implemented with align-items instead
         // of flexbox.
         if (firstLineBlock->isReplaced() || firstLineBlock->isFloating()
-            || !parentBlock || parentBlock->firstChild() != firstLineBlock || !parentBlock->isBlockFlow()
-            || (parentBlock->isFlexibleBox() && !parentBlock->isRenderButton()))
+            || !parentBlock || parentBlock->firstChild() != firstLineBlock
+            || (!parentBlock->isRenderBlockFlow() && !parentBlock->isRenderButton()))
             break;
         ASSERT_WITH_SECURITY_IMPLICATION(parentBlock->isRenderBlock());
         firstLineBlock = toRenderBlock(parentBlock);
@@ -6506,7 +6223,7 @@
 
         RenderObject* parentBlock = firstLetterBlock->parent();
         if (firstLetterBlock->isReplaced() || !parentBlock || parentBlock->firstChild() != firstLetterBlock ||
-            !parentBlock->isBlockFlow() || (parentBlock->isFlexibleBox() && !parentBlock->isRenderButton()))
+            (!parentBlock->isRenderBlockFlow() && !parentBlock->isRenderButton()))
             return 0;
         firstLetterBlock = parentBlock;
     }
@@ -6521,13 +6238,13 @@
     RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
     ASSERT(firstLetter->isFloating() || firstLetter->isInline());
 
-    if (Node::diff(firstLetter->style(), pseudoStyle, document()) == Node::Reattach) {
+    if (RenderStyle::compare(firstLetter->style(), pseudoStyle) == Reattach) {
         // The first-letter renderer needs to be replaced. Create a new renderer of the right type.
         RenderObject* newFirstLetter;
         if (pseudoStyle->display() == INLINE)
-            newFirstLetter = RenderInline::createAnonymous(document());
+            newFirstLetter = RenderInline::createAnonymous(&document());
         else
-            newFirstLetter = RenderBlock::createAnonymous(document());
+            newFirstLetter = RenderBlock::createAnonymous(&document());
         newFirstLetter->setStyle(pseudoStyle);
 
         // Move the first letter into the new renderer.
@@ -6565,15 +6282,41 @@
     }
 }
 
+static inline unsigned firstLetterLength(const String& text)
+{
+    unsigned length = 0;
+
+    // Account for leading spaces and punctuation.
+    while (length < text.length() && shouldSkipForFirstLetter((text)[length]))
+        length++;
+
+    // Account for first letter.
+    length++;
+
+    // Keep looking for whitespace and allowed punctuation, but avoid
+    // accumulating just whitespace into the :first-letter.
+    for (unsigned scanLength = length; scanLength < text.length(); ++scanLength) {
+        UChar c = (text)[scanLength];
+
+        if (!shouldSkipForFirstLetter(c))
+            break;
+
+        if (isPunctuationForFirstLetter(c))
+            length = scanLength + 1;
+    }
+
+    return length;
+}
+
 void RenderBlock::createFirstLetterRenderer(RenderObject* firstLetterBlock, RenderObject* currentChild)
 {
     RenderObject* firstLetterContainer = currentChild->parent();
     RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
     RenderObject* firstLetter = 0;
     if (pseudoStyle->display() == INLINE)
-        firstLetter = RenderInline::createAnonymous(document());
+        firstLetter = RenderInline::createAnonymous(&document());
     else
-        firstLetter = RenderBlock::createAnonymous(document());
+        firstLetter = RenderBlock::createAnonymous(&document());
     firstLetter->setStyle(pseudoStyle);
     firstLetterContainer->addChild(firstLetter, currentChild);
 
@@ -6582,57 +6325,39 @@
     // The original string is going to be either a generated content string or a DOM node's
     // string.  We want the original string before it got transformed in case first-letter has
     // no text-transform or a different text-transform applied to it.
-    RefPtr<StringImpl> oldText = textObj->originalText();
-    ASSERT(oldText);
+    String oldText = textObj->originalText();
+    ASSERT(oldText.impl());
 
-    if (oldText && oldText->length() > 0) {
-        unsigned length = 0;
+    unsigned length = firstLetterLength(oldText);
 
-        // Account for leading spaces and punctuation.
-        while (length < oldText->length() && shouldSkipForFirstLetter((*oldText)[length]))
-            length++;
+    if (!length)
+        return;
 
-        // Account for first letter.
-        length++;
+    // Construct a text fragment for the text after the first letter.
+    // This text fragment might be empty.
+    RenderTextFragment* remainingText =
+        new RenderTextFragment(textObj->node() ? textObj->node() : &textObj->document(), oldText.impl(), length, oldText.length() - length);
+    remainingText->setStyle(textObj->style());
+    if (remainingText->node())
+        remainingText->node()->setRenderer(remainingText);
 
-        // Keep looking for whitespace and allowed punctuation, but avoid
-        // accumulating just whitespace into the :first-letter.
-        for (unsigned scanLength = length; scanLength < oldText->length(); ++scanLength) {
-            UChar c = (*oldText)[scanLength];
+    firstLetterContainer->addChild(remainingText, textObj);
+    firstLetterContainer->removeChild(textObj);
+    remainingText->setFirstLetter(firstLetter);
+    toRenderBoxModelObject(firstLetter)->setFirstLetterRemainingText(remainingText);
 
-            if (!shouldSkipForFirstLetter(c))
-                break;
+    // construct text fragment for the first letter
+    RenderTextFragment* letter =
+        new RenderTextFragment(remainingText->node() ? remainingText->node() : &remainingText->document(), oldText.impl(), 0, length);
+    letter->setStyle(pseudoStyle);
+    firstLetter->addChild(letter);
 
-            if (isPunctuationForFirstLetter(c))
-                length = scanLength + 1;
-         }
-
-        // Construct a text fragment for the text after the first letter.
-        // This text fragment might be empty.
-        RenderTextFragment* remainingText =
-            new RenderTextFragment(textObj->node() ? textObj->node() : textObj->document(), oldText.get(), length, oldText->length() - length);
-        remainingText->setStyle(textObj->style());
-        if (remainingText->node())
-            remainingText->node()->setRenderer(remainingText);
-
-        firstLetterContainer->addChild(remainingText, textObj);
-        firstLetterContainer->removeChild(textObj);
-        remainingText->setFirstLetter(firstLetter);
-        toRenderBoxModelObject(firstLetter)->setFirstLetterRemainingText(remainingText);
-
-        // construct text fragment for the first letter
-        RenderTextFragment* letter =
-            new RenderTextFragment(remainingText->node() ? remainingText->node() : remainingText->document(), oldText.get(), 0, length);
-        letter->setStyle(pseudoStyle);
-        firstLetter->addChild(letter);
-
-        textObj->destroy();
-    }
+    textObj->destroy();
 }
 
 void RenderBlock::updateFirstLetter()
 {
-    if (!document()->styleSheetCollections()->usesFirstLetterRules())
+    if (!document().styleSheetCollections()->usesFirstLetterRules())
         return;
     // Don't recur
     if (style()->styleType() == FIRST_LETTER)
@@ -6692,8 +6417,8 @@
 static bool shouldCheckLines(RenderObject* obj)
 {
     return !obj->isFloatingOrOutOfFlowPositioned() && !obj->isRunIn()
-            && obj->isBlockFlow() && obj->style()->height().isAuto()
-            && (!obj->isDeprecatedFlexibleBox() || obj->style()->boxOrient() == VERTICAL);
+        && obj->isRenderBlock() && obj->style()->height().isAuto()
+        && (!obj->isDeprecatedFlexibleBox() || obj->style()->boxOrient() == VERTICAL);
 }
 
 static int getHeightForLineCount(RenderBlock* block, int l, bool includeBottom, int& count)
@@ -6797,7 +6522,7 @@
         else {
             for (RenderBox* obj = firstChildBox(); obj; obj = obj->nextSiblingBox()) {
                 if (!obj->isFloatingOrOutOfFlowPositioned()) {
-                    if (obj->isBlockFlow() && !obj->hasOverflowClip())
+                    if (obj->isRenderBlockFlow() && !obj->hasOverflowClip())
                         toRenderBlock(obj)->adjustForBorderFit(x + obj->x(), left, right);
                     else if (obj->style()->visibility() == VISIBLE) {
                         // We are a replaced element or some kind of non-block-flow object.
@@ -7574,7 +7299,7 @@
     // Just bail if the region didn't change.
     if (rootBox->containingRegion() == currentRegion)
         return false;
-    return rootBox->paginatedLineWidth() != availableLogicalWidthForContent(currentRegion, offsetFromLogicalTopOfFirstPage());
+    return rootBox->paginatedLineWidth() != availableLogicalWidthForContent(currentRegion);
 }
 
 LayoutUnit RenderBlock::offsetFromLogicalTopOfFirstPage() const
@@ -7582,49 +7307,20 @@
     LayoutState* layoutState = view()->layoutState();
     if (layoutState && !layoutState->isPaginated())
         return 0;
+
+    RenderFlowThread* flowThread = flowThreadContainingBlock();
+    if (flowThread)
+        return flowThread->offsetFromLogicalTopOfFirstRegion(this);
+
     if (layoutState) {
-        // FIXME: Sanity check that the renderer in the layout state is ours, since otherwise the computation will be off.
-        // Right now this assert gets hit inside computeLogicalHeight for percentage margins, since they're computed using
-        // widths which can vary in each region. Until we patch that, we can't have this assert.
-        // ASSERT(layoutState->renderer() == this);
+        ASSERT(layoutState->renderer() == this);
 
         LayoutSize offsetDelta = layoutState->m_layoutOffset - layoutState->m_pageOffset;
         return isHorizontalWritingMode() ? offsetDelta.height() : offsetDelta.width();
     }
-    // FIXME: Right now, this assert is hit outside layout, from logicalLeftSelectionOffset in selectionGapRectsForRepaint (called from FrameSelection::selectAll).
-    // ASSERT(inRenderFlowThread());
 
-    // FIXME: This is a slower path that doesn't use layout state and relies on getting your logical top inside the enclosing flow thread. It doesn't
-    // work with columns or pages currently, but it should once they have been switched over to using flow threads.
-    RenderFlowThread* flowThread = flowThreadContainingBlock();
-    if (!flowThread)
-        return 0;
-
-    const RenderBlock* currentBlock = this;
-    LayoutRect blockRect(0, 0, width(), height());
-
-    while (currentBlock && !currentBlock->isRenderFlowThread()) {
-        RenderBlock* containerBlock = currentBlock->containingBlock();
-        ASSERT(containerBlock);
-        if (!containerBlock)
-            return 0;
-        LayoutPoint currentBlockLocation = currentBlock->location();
-
-        if (containerBlock->style()->writingMode() != currentBlock->style()->writingMode()) {
-            // We have to put the block rect in container coordinates
-            // and we have to take into account both the container and current block flipping modes
-            if (containerBlock->style()->isFlippedBlocksWritingMode()) {
-                if (containerBlock->isHorizontalWritingMode())
-                    blockRect.setY(currentBlock->height() - blockRect.maxY());
-                else
-                    blockRect.setX(currentBlock->width() - blockRect.maxX());
-            }
-            currentBlock->flipForWritingMode(blockRect);
-        }
-        blockRect.moveBy(currentBlockLocation);
-        currentBlock = containerBlock;
-    };
-    return currentBlock->isHorizontalWritingMode() ? blockRect.y() : blockRect.x();
+    ASSERT_NOT_REACHED();
+    return 0;
 }
 
 RenderRegion* RenderBlock::regionAtBlockOffset(LayoutUnit blockOffset) const
@@ -7658,7 +7354,7 @@
     if (!flowThread || !flowThread->hasValidRegionInfo())
         return false;
 
-    return flowThread->logicalWidthChangedInRegions(this, offsetFromLogicalTopOfFirstPage());
+    return flowThread->logicalWidthChangedInRegionsForBlock(this);
 }
 
 RenderRegion* RenderBlock::clampToStartAndEndRegions(RenderRegion* region) const
@@ -7924,13 +7620,13 @@
     RenderBlock* newBox = 0;
     if (display == BOX || display == INLINE_BOX) {
         // FIXME: Remove this case once we have eliminated all internal users of old flexbox
-        newBox = RenderDeprecatedFlexibleBox::createAnonymous(parent->document());
+        newBox = RenderDeprecatedFlexibleBox::createAnonymous(&parent->document());
         newDisplay = BOX;
     } else if (display == FLEX || display == INLINE_FLEX) {
-        newBox = RenderFlexibleBox::createAnonymous(parent->document());
+        newBox = RenderFlexibleBox::createAnonymous(&parent->document());
         newDisplay = FLEX;
     } else {
-        newBox = RenderBlock::createAnonymous(parent->document());
+        newBox = RenderBlock::createAnonymous(&parent->document());
         newDisplay = BLOCK;
     }
 
@@ -7944,7 +7640,7 @@
     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
     newStyle->inheritColumnPropertiesFrom(parent->style());
 
-    RenderBlock* newBox = RenderBlock::createAnonymous(parent->document());
+    RenderBlock* newBox = RenderBlock::createAnonymous(&parent->document());
     newBox->setStyle(newStyle.release());
     return newBox;
 }
@@ -7954,7 +7650,7 @@
     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
     newStyle->setColumnSpan(ColumnSpanAll);
 
-    RenderBlock* newBox = RenderBlock::createAnonymous(parent->document());
+    RenderBlock* newBox = RenderBlock::createAnonymous(&parent->document());
     newBox->setStyle(newStyle.release());
     return newBox;
 }
diff --git a/Source/core/rendering/RenderBlock.h b/Source/core/rendering/RenderBlock.h
index 24cc747..40c890f 100644
--- a/Source/core/rendering/RenderBlock.h
+++ b/Source/core/rendering/RenderBlock.h
@@ -49,6 +49,7 @@
 
 struct BidiRun;
 struct PaintInfo;
+class LineBreaker;
 class LineInfo;
 class RenderRubyRun;
 class TextLayout;
@@ -78,9 +79,12 @@
 class RenderBlock : public RenderBox {
 public:
     friend class LineLayoutState;
+
+protected:
     explicit RenderBlock(ContainerNode*);
     virtual ~RenderBlock();
 
+public:
     static RenderBlock* createAnonymous(Document*);
 
     RenderObject* firstChild() const { ASSERT(children() == virtualChildren()); return children()->firstChild(); }
@@ -158,33 +162,33 @@
 
     // Versions that can compute line offsets with the region and page offset passed in. Used for speed to avoid having to
     // compute the region all over again when you already know it.
-    LayoutUnit availableLogicalWidthForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage, LayoutUnit logicalHeight = 0) const
+    LayoutUnit availableLogicalWidthForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return max<LayoutUnit>(0, logicalRightOffsetForLine(position, shouldIndentText, region, offsetFromLogicalTopOfFirstPage, logicalHeight)
-            - logicalLeftOffsetForLine(position, shouldIndentText, region, offsetFromLogicalTopOfFirstPage, logicalHeight));
+        return max<LayoutUnit>(0, logicalRightOffsetForLine(position, shouldIndentText, region, logicalHeight)
+            - logicalLeftOffsetForLine(position, shouldIndentText, region, logicalHeight));
     }
-    LayoutUnit logicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage, LayoutUnit logicalHeight = 0) const
+    LayoutUnit logicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return logicalRightOffsetForLine(position, logicalRightOffsetForContent(region, offsetFromLogicalTopOfFirstPage), shouldIndentText, 0, logicalHeight);
+        return logicalRightOffsetForLine(position, logicalRightOffsetForContent(region), shouldIndentText, 0, logicalHeight);
     }
-    LayoutUnit logicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage, LayoutUnit logicalHeight = 0) const
+    LayoutUnit logicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(region, offsetFromLogicalTopOfFirstPage), shouldIndentText, 0, logicalHeight);
+        return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(region), shouldIndentText, 0, logicalHeight);
     }
-    LayoutUnit startOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage, LayoutUnit logicalHeight = 0) const
+    LayoutUnit startOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, region, offsetFromLogicalTopOfFirstPage, logicalHeight)
-            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, region, offsetFromLogicalTopOfFirstPage, logicalHeight);
+        return style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, region, logicalHeight)
+            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, region, logicalHeight);
     }
-    LayoutUnit endOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage, LayoutUnit logicalHeight = 0) const
+    LayoutUnit endOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
     {
-        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, region, offsetFromLogicalTopOfFirstPage, logicalHeight)
-            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, region, offsetFromLogicalTopOfFirstPage, logicalHeight);
+        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, region, logicalHeight)
+            : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, region, logicalHeight);
     }
 
     LayoutUnit availableLogicalWidthForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
     {
-        return availableLogicalWidthForLine(position, shouldIndentText, regionAtBlockOffset(position), offsetFromLogicalTopOfFirstPage(), logicalHeight);
+        return availableLogicalWidthForLine(position, shouldIndentText, regionAtBlockOffset(position), logicalHeight);
     }
     LayoutUnit logicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
     {
@@ -347,7 +351,7 @@
     LayoutUnit collapsedMarginBeforeForChild(const RenderBox* child) const;
     LayoutUnit collapsedMarginAfterForChild(const RenderBox* child) const;
 
-    void updateLogicalWidthForAlignment(const ETextAlign&, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount);
+    void updateLogicalWidthForAlignment(const ETextAlign&, const RootInlineBox*, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount);
 
     virtual void updateFirstLetter();
 
@@ -380,41 +384,38 @@
 
     virtual void scrollbarsChanged(bool /*horizontalScrollbarChanged*/, bool /*verticalScrollbarChanged*/) { };
 
-    LayoutUnit logicalLeftOffsetForContent(RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage) const;
-    LayoutUnit logicalRightOffsetForContent(RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage) const;
-    LayoutUnit availableLogicalWidthForContent(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+    LayoutUnit logicalLeftOffsetForContent(RenderRegion*) const;
+    LayoutUnit logicalRightOffsetForContent(RenderRegion*) const;
+    LayoutUnit availableLogicalWidthForContent(RenderRegion* region) const
     {
-        return max<LayoutUnit>(0, logicalRightOffsetForContent(region, offsetFromLogicalTopOfFirstPage) -
-            logicalLeftOffsetForContent(region, offsetFromLogicalTopOfFirstPage)); }
-    LayoutUnit startOffsetForContent(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+        return max<LayoutUnit>(0, logicalRightOffsetForContent(region) - logicalLeftOffsetForContent(region)); }
+    LayoutUnit startOffsetForContent(RenderRegion* region) const
     {
-        return style()->isLeftToRightDirection() ? logicalLeftOffsetForContent(region, offsetFromLogicalTopOfFirstPage)
-            : logicalWidth() - logicalRightOffsetForContent(region, offsetFromLogicalTopOfFirstPage);
+        return style()->isLeftToRightDirection() ? logicalLeftOffsetForContent(region) : logicalWidth() - logicalRightOffsetForContent(region);
     }
-    LayoutUnit endOffsetForContent(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+    LayoutUnit endOffsetForContent(RenderRegion* region) const
     {
-        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForContent(region, offsetFromLogicalTopOfFirstPage)
-            : logicalWidth() - logicalRightOffsetForContent(region, offsetFromLogicalTopOfFirstPage);
+        return !style()->isLeftToRightDirection() ? logicalLeftOffsetForContent(region) : logicalWidth() - logicalRightOffsetForContent(region);
     }
     LayoutUnit logicalLeftOffsetForContent(LayoutUnit blockOffset) const
     {
-        return logicalLeftOffsetForContent(regionAtBlockOffset(blockOffset), offsetFromLogicalTopOfFirstPage());
+        return logicalLeftOffsetForContent(regionAtBlockOffset(blockOffset));
     }
     LayoutUnit logicalRightOffsetForContent(LayoutUnit blockOffset) const
     {
-        return logicalRightOffsetForContent(regionAtBlockOffset(blockOffset), offsetFromLogicalTopOfFirstPage());
+        return logicalRightOffsetForContent(regionAtBlockOffset(blockOffset));
     }
     LayoutUnit availableLogicalWidthForContent(LayoutUnit blockOffset) const
     {
-        return availableLogicalWidthForContent(regionAtBlockOffset(blockOffset), offsetFromLogicalTopOfFirstPage());
+        return availableLogicalWidthForContent(regionAtBlockOffset(blockOffset));
     }
     LayoutUnit startOffsetForContent(LayoutUnit blockOffset) const
     {
-        return startOffsetForContent(regionAtBlockOffset(blockOffset), offsetFromLogicalTopOfFirstPage());
+        return startOffsetForContent(regionAtBlockOffset(blockOffset));
     }
     LayoutUnit endOffsetForContent(LayoutUnit blockOffset) const
     {
-        return endOffsetForContent(regionAtBlockOffset(blockOffset), offsetFromLogicalTopOfFirstPage());
+        return endOffsetForContent(regionAtBlockOffset(blockOffset));
     }
     LayoutUnit logicalLeftOffsetForContent() const { return isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop(); }
     LayoutUnit logicalRightOffsetForContent() const { return logicalLeftOffsetForContent() + availableLogicalWidth(); }
@@ -424,7 +425,7 @@
     void setStaticInlinePositionForChild(RenderBox*, LayoutUnit blockOffset, LayoutUnit inlinePosition);
     void updateStaticInlinePositionForChild(RenderBox*, LayoutUnit logicalTop);
 
-    LayoutUnit computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* = 0, LayoutUnit offsetFromLogicalTopOfFirstPage = 0);
+    LayoutUnit computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* = 0);
 
     void placeRunInIfNeeded(RenderObject* newChild);
     bool runInIsPlacedIntoSiblingBlock(RenderObject* runIn);
@@ -454,9 +455,15 @@
     bool allowsShapeInsideInfoSharing() const { return !isInline() && !isFloating(); }
     virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
 
+    // inline-block elements paint all phases atomically. This function ensures that. Certain other elements
+    // (grid items, flex items) require this behavior as well, and this function exists as a helper for them.
+    // It is expected that the caller will call this function independent of the value of paintInfo.phase.
+    static void paintAsInlineBlock(RenderObject*, PaintInfo&, const LayoutPoint&);
 protected:
     virtual void willBeDestroyed();
 
+    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); }
@@ -494,10 +501,13 @@
     void layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly = false);
     void markFixedPositionObjectForLayoutIfNeeded(RenderObject* child, SubtreeLayoutScope&);
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return true; };
+
     virtual void paint(PaintInfo&, const LayoutPoint&);
     virtual void paintObject(PaintInfo&, const LayoutPoint&);
     virtual void paintChildren(PaintInfo&, const LayoutPoint&);
     void paintChild(RenderBox*, PaintInfo&, const LayoutPoint&);
+    void paintChildAsInlineBlock(RenderBox*, PaintInfo&, const LayoutPoint&);
 
     LayoutUnit logicalRightOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining = 0, LayoutUnit logicalHeight = 0) const
     {
@@ -523,6 +533,7 @@
 
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE;
+    void adjustIntrinsicLogicalWidthsForColumns(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const;
 
     virtual int firstLineBoxBaseline() const;
     virtual int inlineBlockBaseline(LineDirectionMode) const OVERRIDE;
@@ -564,15 +575,6 @@
 
     virtual void computeSelfHitTestRects(Vector<LayoutRect>&, const LayoutPoint& layerOffset) const OVERRIDE;
 
-    // Only used by RenderSVGText, which explicitly overrides RenderBlock::layoutBlock(), do NOT use for anything else.
-    void forceLayoutInlineChildren()
-    {
-        LayoutUnit repaintLogicalTop = 0;
-        LayoutUnit repaintLogicalBottom = 0;
-        clearFloats();
-        layoutInlineChildren(true, repaintLogicalTop, repaintLogicalBottom);
-    }
-
     bool updateRegionsAndShapesLogicalSize(RenderFlowThread*);
     void computeRegionRangeForBlock(RenderFlowThread*);
 
@@ -596,13 +598,12 @@
     virtual const char* renderName() const;
 
     virtual bool isRenderBlock() const OVERRIDE FINAL { return true; }
-    virtual bool isBlockFlow() const OVERRIDE FINAL { return (!isInline() || isReplaced()) && !isTable(); }
     virtual bool isInlineBlockOrInlineTable() const OVERRIDE FINAL { return isInline() && isReplaced(); }
 
     void makeChildrenNonInline(RenderObject* insertionPoint = 0);
     virtual void removeLeftoverAnonymousBlock(RenderBlock* child);
 
-    static void collapseAnonymousBoxChild(RenderBlock* parent, RenderObject* child);
+    static void collapseAnonymousBlockChild(RenderBlock* parent, RenderBlock* child);
     void moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert);
 
     virtual void dirtyLinesFromChangedChild(RenderObject* child) OVERRIDE FINAL { m_lineBoxes.dirtyLinesFromChangedChild(this, child); }
@@ -620,8 +621,6 @@
 
     virtual void repaintOverhangingFloats(bool paintAllDescendants) OVERRIDE FINAL;
 
-    void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope&);
-    void layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom);
     BidiRun* handleTrailingSpaces(BidiRunList<BidiRun>&, BidiContext*);
 
     void insertIntoTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*&, TrackedContainerMap*&);
@@ -670,44 +669,6 @@
 
     LayoutPoint computeLogicalLocationForFloat(const FloatingObject*, LayoutUnit logicalTopOffset) const;
 
-    // The following functions' implementations are in RenderBlockLineLayout.cpp.
-    struct RenderTextInfo {
-        // Destruction of m_layout requires TextLayout to be a complete type, so the constructor and destructor are made non-inline to avoid compilation errors.
-        RenderTextInfo();
-        ~RenderTextInfo();
-
-        RenderText* m_text;
-        OwnPtr<TextLayout> m_layout;
-        LazyLineBreakIterator m_lineBreakIterator;
-        const Font* m_font;
-    };
-
-    class LineBreaker {
-    public:
-        LineBreaker(RenderBlock* block)
-            : m_block(block)
-        {
-            reset();
-        }
-
-        InlineIterator nextLineBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
-
-        bool lineWasHyphenated() { return m_hyphenated; }
-        const Vector<RenderBox*>& positionedObjects() { return m_positionedObjects; }
-        EClear clear() { return m_clear; }
-    private:
-        void reset();
-
-        InlineIterator nextSegmentBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
-        void skipTrailingWhitespace(InlineIterator&, const LineInfo&);
-        void skipLeadingWhitespace(InlineBidiResolver&, LineInfo&, FloatingObject* lastFloatFromPreviousLine, LineWidth&);
-
-        RenderBlock* m_block;
-        bool m_hyphenated;
-        EClear m_clear;
-        Vector<RenderBox*> m_positionedObjects;
-    };
-
     void checkFloatsInCleanLine(RootInlineBox*, Vector<FloatWithRect>&, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat);
     RootInlineBox* determineStartPosition(LineLayoutState&, InlineBidiResolver&);
     void determineEndPosition(LineLayoutState&, RootInlineBox* startBox, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus);
@@ -751,8 +712,6 @@
     // Returns true if and only if it has positioned any floats.
     bool positionNewFloats();
 
-    void clearFloats();
-
     LayoutUnit getClearDelta(RenderBox* child, LayoutUnit yPos);
 
     virtual bool avoidsFloats() const;
@@ -935,7 +894,7 @@
     // End helper functions and structs used by layoutBlockChildren.
 
     // Helper function for layoutInlineChildren()
-    RootInlineBox* createLineBoxesFromBidiRuns(BidiRunList<BidiRun>&, const InlineIterator& end, LineInfo&, VerticalPositionCache&, BidiRun* trailingSpaceRun, WordMeasurements&);
+    RootInlineBox* createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>&, const InlineIterator& end, LineInfo&, VerticalPositionCache&, BidiRun* trailingSpaceRun, WordMeasurements&);
     void layoutRunsAndFloats(LineLayoutState&, bool hasInlineChild);
     void layoutRunsAndFloatsInRange(LineLayoutState&, InlineBidiResolver&, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines);
     void updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*&, LayoutUnit&, LineLayoutState&);
@@ -1002,7 +961,7 @@
     virtual bool canCollapseAnonymousBlockChild() const { return true; }
 
 public:
-    LayoutUnit offsetFromLogicalTopOfFirstPage() const;
+    virtual LayoutUnit offsetFromLogicalTopOfFirstPage() const OVERRIDE FINAL;
     RenderRegion* regionAtBlockOffset(LayoutUnit) const;
     RenderRegion* clampToStartAndEndRegions(RenderRegion*) const;
 
@@ -1076,8 +1035,12 @@
     // RenderRubyBase objects need to be able to split and merge, moving their children around
     // (calling moveChildTo, moveAllChildrenTo, and makeChildrenNonInline).
     friend class RenderRubyBase;
+    friend class LineBreaker;
     friend class LineWidth; // Needs to know FloatingObject
 
+    // FIXME: This is temporary as we move code that accesses block flow
+    // member variables out of RenderBlock and into RenderBlockFlow.
+    friend class RenderBlockFlow;
 private:
     // Used to store state between styleWillChange and styleDidChange
     static bool s_canPropagateFloatIntoSibling;
diff --git a/Source/core/rendering/RenderBlockFlow.cpp b/Source/core/rendering/RenderBlockFlow.cpp
new file mode 100644
index 0000000..08b29b0
--- /dev/null
+++ b/Source/core/rendering/RenderBlockFlow.cpp
@@ -0,0 +1,438 @@
+/*
+ * 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/rendering/RenderBlockFlow.h"
+
+#include "core/page/FrameView.h"
+#include "core/rendering/LayoutRepainter.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderNamedFlowThread.h"
+#include "core/rendering/RenderView.h"
+
+using namespace std;
+
+namespace WebCore {
+
+RenderBlockFlow::RenderBlockFlow(ContainerNode* node)
+    : RenderBlock(node)
+{
+}
+
+RenderBlockFlow::~RenderBlockFlow()
+{
+}
+
+void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
+{
+    ASSERT(needsLayout());
+
+    if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can cause us to come in here. Bail.
+        return;
+
+    if (!relayoutChildren && simplifiedLayout())
+        return;
+
+    LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
+
+    if (updateLogicalWidthAndColumnWidth())
+        relayoutChildren = true;
+
+    clearFloats();
+
+    LayoutUnit previousHeight = logicalHeight();
+    // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
+    // for consistency with other render classes?
+    setLogicalHeight(0);
+
+    bool pageLogicalHeightChanged = false;
+    bool hasSpecifiedPageLogicalHeight = false;
+    checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
+
+    RenderView* renderView = view();
+    RenderStyle* styleToUse = style();
+    LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
+
+    // Regions changing widths can force us to relayout our children.
+    RenderFlowThread* flowThread = flowThreadContainingBlock();
+    if (logicalWidthChangedInRegions(flowThread))
+        relayoutChildren = true;
+    if (updateRegionsAndShapesLogicalSize(flowThread))
+        relayoutChildren = true;
+
+    // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
+    // our current maximal positive and negative margins. These values are used when we
+    // are collapsed with adjacent blocks, so for example, if you have block A and B
+    // collapsing together, then you'd take the maximal positive margin from both A and B
+    // and subtract it from the maximal negative margin from both A and B to get the
+    // true collapsed margin. This algorithm is recursive, so when we finish layout()
+    // our block knows its current maximal positive/negative values.
+    //
+    // Start out by setting our margin values to our current margins. Table cells have
+    // no margins, so we don't fill in the values for table cells.
+    bool isCell = isTableCell();
+    if (!isCell) {
+        initMaxMarginValues();
+
+        setHasMarginBeforeQuirk(styleToUse->hasMarginBeforeQuirk());
+        setHasMarginAfterQuirk(styleToUse->hasMarginAfterQuirk());
+        setPaginationStrut(0);
+    }
+
+    SubtreeLayoutScope layoutScope(this);
+
+    LayoutUnit repaintLogicalTop = 0;
+    LayoutUnit repaintLogicalBottom = 0;
+    LayoutUnit maxFloatLogicalBottom = 0;
+    if (!firstChild() && !isAnonymousBlock())
+        setChildrenInline(true);
+    if (childrenInline())
+        layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
+    else
+        layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom, layoutScope);
+
+    if (frameView()->partialLayout().isStopping()) {
+        statePusher.pop();
+        return;
+    }
+
+    // Expand our intrinsic height to encompass floats.
+    LayoutUnit toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
+    if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
+        setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
+
+    if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher))
+        return;
+
+    // Calculate our new height.
+    LayoutUnit oldHeight = logicalHeight();
+    LayoutUnit oldClientAfterEdge = clientLogicalBottom();
+
+    // Before updating the final size of the flow thread make sure a forced break is applied after the content.
+    // This ensures the size information is correctly computed for the last auto-height region receiving content.
+    if (isRenderFlowThread())
+        toRenderFlowThread(this)->applyBreakAfterContent(oldClientAfterEdge);
+
+    updateLogicalHeight();
+    LayoutUnit newHeight = logicalHeight();
+    if (oldHeight != newHeight) {
+        if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
+            // One of our children's floats may have become an overhanging float for us. We need to look for it.
+            for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
+                if (child->isRenderBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
+                    RenderBlock* block = toRenderBlock(child);
+                    if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
+                        addOverhangingFloats(block, false);
+                }
+            }
+        }
+    }
+
+    bool heightChanged = (previousHeight != newHeight);
+    if (heightChanged)
+        relayoutChildren = true;
+
+    layoutPositionedObjects(relayoutChildren || isRoot());
+
+    updateRegionsAndShapesAfterChildLayout(flowThread, heightChanged);
+
+    // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
+    computeOverflow(oldClientAfterEdge);
+
+    statePusher.pop();
+
+    fitBorderToLinesIfNeeded();
+
+    if (frameView()->partialLayout().isStopping())
+        return;
+
+    if (renderView->layoutState()->m_pageLogicalHeight)
+        setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
+
+    updateLayerTransform();
+
+    // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
+    // we overflow or not.
+    updateScrollInfoAfterLayout();
+
+    // FIXME: This repaint logic should be moved into a separate helper function!
+    // Repaint with our new bounds if they are different from our old bounds.
+    bool didFullRepaint = repainter.repaintAfterLayout();
+    if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
+        // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
+        // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
+        LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
+        LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
+        if (hasOverflowClip()) {
+            // If we have clipped overflow, we should use layout overflow as well, since visual overflow from lines didn't propagate to our block's overflow.
+            // Note the old code did this as well but even for overflow:visible. The addition of hasOverflowClip() at least tightens up the hack a bit.
+            // layoutInlineChildren should be patched to compute the entire repaint rect.
+            repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
+            repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
+        }
+
+        LayoutRect repaintRect;
+        if (isHorizontalWritingMode())
+            repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
+        else
+            repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
+
+        // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
+        adjustRectForColumns(repaintRect);
+
+        repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
+
+        if (hasOverflowClip()) {
+            // Adjust repaint rect for scroll offset
+            repaintRect.move(-scrolledContentOffset());
+
+            // Don't allow this rect to spill out of our overflow box.
+            repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
+        }
+
+        // Make sure the rect is still non-empty after intersecting for overflow above
+        if (!repaintRect.isEmpty()) {
+            repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
+            if (hasReflection())
+                repaintRectangle(reflectedRect(repaintRect));
+        }
+    }
+
+    clearNeedsLayout();
+}
+
+void RenderBlockFlow::clearFloats()
+{
+    if (m_floatingObjects)
+        m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
+
+    HashSet<RenderBox*> oldIntrudingFloatSet;
+    if (!childrenInline() && m_floatingObjects) {
+        const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+        FloatingObjectSetIterator end = floatingObjectSet.end();
+        for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+            FloatingObject* floatingObject = *it;
+            if (!floatingObject->isDescendant())
+                oldIntrudingFloatSet.add(floatingObject->renderer());
+        }
+    }
+
+    // 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())
+            markAllDescendantsWithFloatsForLayout();
+        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();
+    }
+
+    // We should not process floats if the parent node is not a RenderBlock. Otherwise, we will add
+    // floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
+    // See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
+    if (!parent() || !parent()->isRenderBlock())
+        return;
+
+    // Attempt to locate a previous sibling with overhanging floats. We skip any elements that are
+    // out of flow (like floating/positioned elements), and we also skip over any objects that may have shifted
+    // to avoid floats.
+    RenderBlock* parentBlock = toRenderBlock(parent());
+    bool parentHasFloats = false;
+    RenderObject* prev = previousSibling();
+    while (prev && (prev->isFloatingOrOutOfFlowPositioned() || !prev->isBox() || !prev->isRenderBlock() || toRenderBlock(prev)->avoidsFloats())) {
+        if (prev->isFloating())
+            parentHasFloats = true;
+        prev = prev->previousSibling();
+    }
+
+    // First add in floats from the parent.
+    LayoutUnit logicalTopOffset = logicalTop();
+    if (parentHasFloats)
+        addIntrudingFloats(parentBlock, parentBlock->logicalLeftOffsetForContent(), logicalTopOffset);
+
+    LayoutUnit logicalLeftOffset = 0;
+    if (prev) {
+        logicalTopOffset -= toRenderBox(prev)->logicalTop();
+    } else {
+        prev = parentBlock;
+        logicalLeftOffset += parentBlock->logicalLeftOffsetForContent();
+    }
+
+    // Add overhanging floats from the previous RenderBlock, but only if it has a float that intrudes into our space.
+    RenderBlock* block = toRenderBlock(prev);
+    if (block->m_floatingObjects && block->lowestFloatLogicalBottom() > logicalTopOffset)
+        addIntrudingFloats(block, logicalLeftOffset, logicalTopOffset);
+
+    if (childrenInline()) {
+        LayoutUnit changeLogicalTop = LayoutUnit::max();
+        LayoutUnit changeLogicalBottom = LayoutUnit::min();
+        if (m_floatingObjects) {
+            const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+            FloatingObjectSetIterator end = floatingObjectSet.end();
+            for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+                FloatingObject* f = *it;
+                FloatingObject* oldFloatingObject = floatMap.get(f->renderer());
+                LayoutUnit logicalBottom = f->logicalBottom(isHorizontalWritingMode());
+                if (oldFloatingObject) {
+                    LayoutUnit oldLogicalBottom = oldFloatingObject->logicalBottom(isHorizontalWritingMode());
+                    if (f->logicalWidth(isHorizontalWritingMode()) != oldFloatingObject->logicalWidth(isHorizontalWritingMode()) || f->logicalLeft(isHorizontalWritingMode()) != oldFloatingObject->logicalLeft(isHorizontalWritingMode())) {
+                        changeLogicalTop = 0;
+                        changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
+                    } else {
+                        if (logicalBottom != oldLogicalBottom) {
+                            changeLogicalTop = min(changeLogicalTop, min(logicalBottom, oldLogicalBottom));
+                            changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
+                        }
+                        LayoutUnit logicalTop = f->logicalTop(isHorizontalWritingMode());
+                        LayoutUnit oldLogicalTop = oldFloatingObject->logicalTop(isHorizontalWritingMode());
+                        if (logicalTop != oldLogicalTop) {
+                            changeLogicalTop = min(changeLogicalTop, min(logicalTop, oldLogicalTop));
+                            changeLogicalBottom = max(changeLogicalBottom, max(logicalTop, oldLogicalTop));
+                        }
+                    }
+
+                    floatMap.remove(f->renderer());
+                    if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
+                        ASSERT(oldFloatingObject->originatingLine()->renderer() == this);
+                        oldFloatingObject->originatingLine()->markDirty();
+                    }
+                    delete oldFloatingObject;
+                } else {
+                    changeLogicalTop = 0;
+                    changeLogicalBottom = max(changeLogicalBottom, logicalBottom);
+                }
+            }
+        }
+
+        RendererToFloatInfoMap::iterator end = floatMap.end();
+        for (RendererToFloatInfoMap::iterator it = floatMap.begin(); it != end; ++it) {
+            FloatingObject* floatingObject = (*it).value;
+            if (!floatingObject->isDescendant()) {
+                changeLogicalTop = 0;
+                changeLogicalBottom = max(changeLogicalBottom, floatingObject->logicalBottom(isHorizontalWritingMode()));
+            }
+        }
+        deleteAllValues(floatMap);
+
+        markLinesDirtyInBlockRange(changeLogicalTop, changeLogicalBottom);
+    } else if (!oldIntrudingFloatSet.isEmpty()) {
+        // If there are previously intruding floats that no longer intrude, then children with floats
+        // should also get layout because they might need their floating object lists cleared.
+        if (m_floatingObjects->set().size() < oldIntrudingFloatSet.size()) {
+            markAllDescendantsWithFloatsForLayout();
+        } else {
+            const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+            FloatingObjectSetIterator end = floatingObjectSet.end();
+            for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
+                oldIntrudingFloatSet.remove((*it)->renderer());
+            if (!oldIntrudingFloatSet.isEmpty())
+                markAllDescendantsWithFloatsForLayout();
+        }
+    }
+}
+
+void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope& layoutScope)
+{
+    dirtyForLayoutFromPercentageHeightDescendants(layoutScope);
+
+    LayoutUnit beforeEdge = borderBefore() + paddingBefore();
+    LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
+
+    setLogicalHeight(beforeEdge);
+
+    // Lay out our hypothetical grid line as though it occurs at the top of the block.
+    if (view()->layoutState()->lineGrid() == this)
+        layoutLineGridBox();
+
+    // The margin struct caches all our current margin collapsing state. The compact struct caches state when we encounter compacts,
+    MarginInfo marginInfo(this, beforeEdge, afterEdge);
+
+    // Fieldsets need to find their legend and position it inside the border of the object.
+    // The legend then gets skipped during normal layout. The same is true for ruby text.
+    // It doesn't get included in the normal layout process but is instead skipped.
+    RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren, layoutScope);
+
+    LayoutUnit previousFloatLogicalBottom = 0;
+    maxFloatLogicalBottom = 0;
+
+    RenderBox* next = firstChildBox();
+
+    while (next) {
+        RenderBox* child = next;
+        next = child->nextSiblingBox();
+
+        if (childToExclude == child)
+            continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
+
+        updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
+
+        if (child->isOutOfFlowPositioned()) {
+            child->containingBlock()->insertPositionedObject(child);
+            adjustPositionedBlock(child, marginInfo);
+            continue;
+        }
+        if (child->isFloating()) {
+            insertFloatingObject(child);
+            adjustFloatingBlock(marginInfo);
+            continue;
+        }
+
+        // Lay out the child.
+        layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
+
+        // If doing a partial layout and the child was the target renderer, early exit here.
+        if (frameView()->partialLayout().checkPartialLayoutComplete(child))
+            break;
+    }
+
+    // Now do the handling of the bottom of the block, adding in our bottom border/padding and
+    // determining the correct collapsed bottom margin information.
+    handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
+}
+
+} // namespace WebCore
diff --git a/Source/core/rendering/RenderBlockFlow.h b/Source/core/rendering/RenderBlockFlow.h
new file mode 100644
index 0000000..888698c
--- /dev/null
+++ b/Source/core/rendering/RenderBlockFlow.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2007 David Smith (catfish.man@gmail.com)
+ * Copyright (C) 2003-2013 Apple Inc. All rights reserved.
+ * Copyright (C) Research In Motion Limited 2010. All rights reserved.
+ * 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 RenderBlockFlow_h
+#define RenderBlockFlow_h
+
+#include "RenderBlock.h"
+
+namespace WebCore {
+
+class RenderBlockFlow : public RenderBlock {
+public:
+    explicit RenderBlockFlow(ContainerNode*);
+    virtual ~RenderBlockFlow();
+
+    virtual bool isRenderBlockFlow() const OVERRIDE FINAL { return true; }
+
+    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE;
+protected:
+    // Only used by RenderSVGText, which explicitly overrides RenderBlock::layoutBlock(), do NOT use for anything else.
+    void forceLayoutInlineChildren()
+    {
+        LayoutUnit repaintLogicalTop = 0;
+        LayoutUnit repaintLogicalBottom = 0;
+        clearFloats();
+        layoutInlineChildren(true, repaintLogicalTop, repaintLogicalBottom);
+    }
+
+private:
+    void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope&);
+    void layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom);
+
+    void clearFloats();
+};
+
+inline RenderBlockFlow& toRenderBlockFlow(RenderObject& object)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(object.isRenderBlockFlow());
+    return static_cast<RenderBlockFlow&>(object);
+}
+
+inline const RenderBlockFlow& toRenderBlockFlow(const RenderObject& object)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(object.isRenderBlockFlow());
+    return static_cast<const RenderBlockFlow&>(object);
+}
+
+inline RenderBlockFlow* toRenderBlockFlow(RenderObject* object)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderBlockFlow());
+    return static_cast<RenderBlockFlow*>(object);
+}
+
+inline const RenderBlockFlow* toRenderBlockFlow(const RenderObject* object)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderBlockFlow());
+    return static_cast<const RenderBlockFlow*>(object);
+}
+
+// This will catch anyone doing an unnecessary cast.
+void toRenderBlockFlow(const RenderBlockFlow*);
+void toRenderBlockFlow(const RenderBlockFlow&);
+
+} // namespace WebCore
+
+#endif // RenderBlockFlow_h
diff --git a/Source/core/rendering/RenderBlockLineLayout.cpp b/Source/core/rendering/RenderBlockLineLayout.cpp
index 5ecc8f9..1d0408e 100644
--- a/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -54,9 +54,46 @@
 // We don't let our line box tree for a single line get any deeper than this.
 const unsigned cMaxLineDepth = 200;
 
+struct RenderTextInfo {
+    // Destruction of m_layout requires TextLayout to be a complete type, so the constructor and destructor are made non-inline to avoid compilation errors.
+    RenderTextInfo();
+    ~RenderTextInfo();
+
+    RenderText* m_text;
+    OwnPtr<TextLayout> m_layout;
+    LazyLineBreakIterator m_lineBreakIterator;
+    const Font* m_font;
+};
+
+class LineBreaker {
+public:
+    LineBreaker(RenderBlock* block)
+        : m_block(block)
+    {
+        reset();
+    }
+
+    InlineIterator nextLineBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
+
+    bool lineWasHyphenated() { return m_hyphenated; }
+    const Vector<RenderBox*>& positionedObjects() { return m_positionedObjects; }
+    EClear clear() { return m_clear; }
+private:
+    void reset();
+
+    InlineIterator nextSegmentBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
+    void skipTrailingWhitespace(InlineIterator&, const LineInfo&);
+    void skipLeadingWhitespace(InlineBidiResolver&, LineInfo&, FloatingObject* lastFloatFromPreviousLine, LineWidth&);
+
+    RenderBlock* m_block;
+    bool m_hyphenated;
+    EClear m_clear;
+    Vector<RenderBox*> m_positionedObjects;
+};
+
 static LayoutUnit logicalHeightForLine(const RenderBlock* block, bool isFirstLine, LayoutUnit replacedHeight = 0)
 {
-    if (!block->document()->inNoQuirksMode() && replacedHeight)
+    if (!block->document().inNoQuirksMode() && replacedHeight)
         return replacedHeight;
 
     if (!(block->style(isFirstLine)->lineBoxContain() & LineBoxContainBlock))
@@ -396,7 +433,7 @@
     observer.setStatus(BidiStatus(root->style()->direction(), isOverride(root->style()->unicodeBidi())));
     while (!iter.atEnd()) {
         if (observer.inIsolate()) {
-            iter.increment(&observer);
+            iter.increment(&observer, InlineIterator::FastIncrementInlineRenderer);
             continue;
         }
         if (iter.atParagraphSeparator())
@@ -428,7 +465,7 @@
         if (currpoint == lBreak) {
             // We hit the line break before the start point.  Shave off the start point.
             lineMidpointState.numMidpoints--;
-            if (endpoint.m_obj->style()->collapseWhiteSpace())
+            if (endpoint.m_obj->style()->collapseWhiteSpace() && endpoint.m_obj->isText())
                 endpoint.m_pos--;
         }
     }
@@ -509,7 +546,7 @@
         if (static_cast<int>(nextMidpoint.m_pos + 1) <= end) {
             lineMidpointState.betweenMidpoints = true;
             lineMidpointState.currentMidpoint++;
-            if (nextMidpoint.m_pos != INT_MAX) { // INT_MAX means stop at the object and don't include any of it.
+            if (nextMidpoint.m_pos != UINT_MAX) { // UINT_MAX means stop at the object and don't include any of it.
                 if (static_cast<int>(nextMidpoint.m_pos + 1) > start)
                     runs.addRun(createRun(start, nextMidpoint.m_pos + 1, obj, resolver));
                 return appendRunsForObject(runs, nextMidpoint.m_pos + 1, end, obj, resolver);
@@ -529,7 +566,7 @@
         // We only treat a box as text for a <br> if we are on a line by ourself or in strict mode
         // (Note the use of strict mode.  In "almost strict" mode, we don't treat the box for <br> as text.)
         if (obj->isBR())
-            textBox->setIsText(isOnlyRun || obj->document()->inNoQuirksMode());
+            textBox->setIsText(isOnlyRun || obj->document().inNoQuirksMode());
         return textBox;
     }
 
@@ -539,20 +576,10 @@
     return toRenderInline(obj)->createAndAppendInlineFlowBox();
 }
 
-// FIXME: Don't let counters mark themselves as needing pref width recalcs during layout
-// so we don't need this hack.
-static inline void updateCounterIfNeeded(RenderText* o)
-{
-    if (!o->preferredLogicalWidthsDirty() || !o->isCounter())
-        return;
-    toRenderCounter(o)->updateCounter();
-}
-
 static inline void dirtyLineBoxesForRenderer(RenderObject* o, bool fullLayout)
 {
     if (o->isText()) {
         RenderText* renderText = toRenderText(o);
-        updateCounterIfNeeded(renderText);
         renderText->dirtyLineBoxes(fullLayout);
     } else
         toRenderInline(o)->dirtyLineBoxes(fullLayout);
@@ -867,7 +894,7 @@
 
     bool kerningIsEnabled = font.typesettingFeatures() & Kerning;
 
-#if OS(DARWIN)
+#if OS(MACOSX)
     // FIXME: Having any font feature settings enabled can lead to selection gaps on
     // Chromium-mac. https://bugs.webkit.org/show_bug.cgi?id=113418
     bool canUseSimpleFontCodePath = renderer->canUseSimpleFontCodePath() && !font.fontDescription().featureSettings();
@@ -959,8 +986,14 @@
     }
 }
 
-void RenderBlock::updateLogicalWidthForAlignment(const ETextAlign& textAlign, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount)
+void RenderBlock::updateLogicalWidthForAlignment(const ETextAlign& textAlign, const RootInlineBox* rootInlineBox, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount)
 {
+    TextDirection direction;
+    if (rootInlineBox && rootInlineBox->renderer()->style()->unicodeBidi() == Plaintext)
+        direction = rootInlineBox->direction();
+    else
+        direction = style()->direction();
+
     // Armed with the total width of the line (without justification),
     // we now examine our text-align property in order to determine where to position the
     // objects horizontally. The total width of the line can be increased if we end up
@@ -989,13 +1022,13 @@
         }
         // Fall through
     case TASTART:
-        if (style()->isLeftToRightDirection())
+        if (direction == LTR)
             updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
         else
             updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
         break;
     case TAEND:
-        if (style()->isLeftToRightDirection())
+        if (direction == LTR)
             updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
         else
             updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
@@ -1142,7 +1175,7 @@
         expansionOpportunityCount--;
     }
 
-    updateLogicalWidthForAlignment(textAlign, trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth, expansionOpportunityCount);
+    updateLogicalWidthForAlignment(textAlign, lineBox, trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth, expansionOpportunityCount);
 
     computeExpansionForJustifiedText(firstRun, trailingSpaceRun, expansionOpportunities, expansionOpportunityCount, totalLogicalWidth, availableLogicalWidth);
 
@@ -1317,7 +1350,8 @@
         // tree to see which parent inline is the isolate. We could change enterIsolate
         // to take a RenderObject and do this logic there, but that would be a layering
         // violation for BidiResolver (which knows nothing about RenderObject).
-        RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot));
+        RenderInline* isolatedInline = toRenderInline(highestContainingIsolateWithinRoot(startObj, currentRoot));
+        ASSERT(isolatedInline);
 
         InlineBidiResolver isolatedResolver;
         EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi();
@@ -1396,7 +1430,7 @@
 }
 
 // This function constructs line boxes for all of the text runs in the resolver and computes their position.
-RootInlineBox* RenderBlock::createLineBoxesFromBidiRuns(BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun, WordMeasurements& wordMeasurements)
+RootInlineBox* RenderBlock::createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun, WordMeasurements& wordMeasurements)
 {
     if (!bidiRuns.runCount())
         return 0;
@@ -1408,6 +1442,7 @@
     if (!lineBox)
         return 0;
 
+    lineBox->setBidiLevel(bidiLevel);
     lineBox->setEndsWithBreak(lineInfo.previousLineBrokeCleanly());
 
     bool isSVGRootInlineBox = lineBox->isSVGRootInlineBox();
@@ -1603,13 +1638,13 @@
     repaintDirtyFloats(layoutState.floats());
 }
 
-RenderBlock::RenderTextInfo::RenderTextInfo()
+RenderTextInfo::RenderTextInfo()
     : m_text(0)
     , m_font(0)
 {
 }
 
-RenderBlock::RenderTextInfo::~RenderTextInfo()
+RenderTextInfo::~RenderTextInfo()
 {
 }
 
@@ -1870,7 +1905,7 @@
             // inline flow boxes.
 
             LayoutUnit oldLogicalHeight = logicalHeight();
-            RootInlineBox* lineBox = createLineBoxesFromBidiRuns(bidiRuns, end, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun, wordMeasurements);
+            RootInlineBox* lineBox = createLineBoxesFromBidiRuns(resolver.status().context->level(), bidiRuns, end, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun, wordMeasurements);
 
             bidiRuns.deleteRuns();
             resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
@@ -2087,7 +2122,7 @@
     }
 }
 
-void RenderBlock::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
+void RenderBlockFlow::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
 {
     setLogicalHeight(borderBefore() + paddingBefore());
 
@@ -2164,7 +2199,7 @@
         }
 
         for (size_t i = 0; i < replacedChildren.size(); i++)
-             replacedChildren[i]->layoutIfNeeded();
+            replacedChildren[i]->layoutIfNeeded();
 
         layoutRunsAndFloats(layoutState, hasInlineChild);
     }
@@ -2476,7 +2511,7 @@
 static bool requiresLineBoxForContent(RenderInline* flow, const LineInfo& lineInfo)
 {
     RenderObject* parent = flow->parent();
-    if (flow->document()->inNoQuirksMode()
+    if (flow->document().inNoQuirksMode()
         && (flow->style(lineInfo.isFirstLine())->lineHeight() != parent->style(lineInfo.isFirstLine())->lineHeight()
         || flow->style()->verticalAlign() != parent->style()->verticalAlign()
         || !parent->style()->font().fontMetrics().hasIdenticalAscentDescentAndLineGap(flow->style()->font().fontMetrics())))
@@ -2526,7 +2561,7 @@
 // object iteration process.
 // NB. this function will insert any floating elements that would otherwise
 // be skipped but it will not position them.
-void RenderBlock::LineBreaker::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
+void LineBreaker::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
 {
     while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
         RenderObject* object = iterator.m_obj;
@@ -2538,7 +2573,7 @@
     }
 }
 
-void RenderBlock::LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo& lineInfo,
+void LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo& lineInfo,
                                                      FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
 {
     while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) {
@@ -2681,7 +2716,7 @@
         ASSERT(collapseFirstSpace == CollapseFirstSpace);
         // Add a new end midpoint that stops right at the very end.
         unsigned length = m_whitespace->textLength();
-        unsigned pos = length >= 2 ? length - 2 : INT_MAX;
+        unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
         InlineIterator endMid(0, m_whitespace, pos);
         startIgnoringSpaces(lineMidpointState, endMid);
         for (size_t i = 0; i < m_boxes.size(); ++i) {
@@ -2690,14 +2725,14 @@
     }
 }
 
-void RenderBlock::LineBreaker::reset()
+void LineBreaker::reset()
 {
     m_positionedObjects.clear();
     m_hyphenated = false;
     m_clear = CNONE;
 }
 
-InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
+InlineIterator LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
 {
     ShapeInsideInfo* shapeInsideInfo = m_block->layoutShapeInsideInfo();
 
@@ -2752,7 +2787,7 @@
     return iter.m_obj == renderer && iter.m_pos >= renderer->textLength();
 }
 
-InlineIterator RenderBlock::LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
+InlineIterator LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
 {
     reset();
 
@@ -2799,7 +2834,7 @@
     // very specific circumstances (in order to match common WinIE renderings).
     // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
     RenderStyle* blockStyle = m_block->style();
-    bool allowImagesToBreak = !m_block->document()->inQuirksMode() || !m_block->isTableCell() || !blockStyle->logicalWidth().isIntrinsicOrAuto();
+    bool allowImagesToBreak = !m_block->document().inQuirksMode() || !m_block->isTableCell() || !blockStyle->logicalWidth().isIntrinsicOrAuto();
 
     EWhiteSpace currWS = blockStyle->whiteSpace();
     EWhiteSpace lastWS = currWS;
@@ -3003,7 +3038,6 @@
             }
 
             if (renderTextInfo.m_text != t) {
-                updateCounterIfNeeded(t);
                 renderTextInfo.m_text = t;
                 renderTextInfo.m_font = &f;
                 renderTextInfo.m_layout = f.createLayout(t, width.currentWidth(), collapseWhiteSpace);
@@ -3017,7 +3051,7 @@
 
             // Non-zero only when kerning is enabled and TextLayout isn't used, in which case we measure
             // words with their trailing space, then subtract its width.
-            float wordTrailingSpaceWidth = (f.typesettingFeatures() & Kerning) && !textLayout ? f.width(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0;
+            float wordTrailingSpaceWidth = (f.typesettingFeatures() & Kerning) && !textLayout ? f.width(RenderBlock::constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0;
 
             UChar lastCharacter = renderTextInfo.m_lineBreakIterator.lastCharacter();
             UChar secondToLastCharacter = renderTextInfo.m_lineBreakIterator.secondToLastCharacter();
@@ -3378,7 +3412,7 @@
             float logicalLeft = pixelSnappedLogicalLeftOffsetForLine(curr->lineTop(), firstLine);
             float availableLogicalWidth = logicalRightOffsetForLine(curr->lineTop(), false) - logicalLeft;
             float totalLogicalWidth = curr->logicalWidth();
-            updateLogicalWidthForAlignment(textAlign, 0, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
+            updateLogicalWidthForAlignment(textAlign, curr, 0, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
 
             if (ltr)
                 curr->adjustLogicalPosition((logicalLeft - curr->logicalLeft()), 0);
@@ -3425,7 +3459,7 @@
 
                 float logicalLeft = 0; // We are only intersted in the delta from the base position.
                 float truncatedWidth = pixelSnappedLogicalRightOffsetForLine(curr->lineTop(), firstLine);
-                updateLogicalWidthForAlignment(textAlign, 0, logicalLeft, totalLogicalWidth, truncatedWidth, 0);
+                updateLogicalWidthForAlignment(textAlign, curr, 0, logicalLeft, totalLogicalWidth, truncatedWidth, 0);
                 if (ltr)
                     curr->adjustLogicalPosition(logicalLeft, 0);
                 else
@@ -3500,7 +3534,7 @@
     float totalLogicalWidth = 0;
     float logicalLeft = logicalLeftOffsetForLine(logicalHeight(), false);
     float availableLogicalWidth = logicalRightOffsetForLine(logicalHeight(), false) - logicalLeft;
-    updateLogicalWidthForAlignment(textAlign, 0, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
+    updateLogicalWidthForAlignment(textAlign, 0, 0, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
 
     if (!style()->isLeftToRightDirection())
         return logicalWidth() - logicalLeft;
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index 167899f..80e9c74 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -85,7 +85,7 @@
     ASSERT(bodyElementRenderer->isBody());
     // The <body> only paints its background if the root element has defined a background independent of the body,
     // or if the <body>'s parent is not the document element's renderer (e.g. inside SVG foreignObject).
-    RenderObject* documentElementRenderer = bodyElementRenderer->document()->documentElement()->renderer();
+    RenderObject* documentElementRenderer = bodyElementRenderer->document().documentElement()->renderer();
     return documentElementRenderer
         && !documentElementRenderer->hasBackground()
         && (documentElementRenderer == bodyElementRenderer->parent());
@@ -105,13 +105,13 @@
 {
 }
 
-LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, LayoutUnit offsetFromTopOfFirstPage, RenderBoxRegionInfoFlags cacheFlag) const
+LayoutRect RenderBox::borderBoxRectInRegion(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
 {
     if (!region)
         return borderBoxRect();
 
     // Compute the logical width and placement in this region.
-    RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, offsetFromTopOfFirstPage, cacheFlag);
+    RenderBoxRegionInfo* boxInfo = renderBoxRegionInfo(region, cacheFlag);
     if (!boxInfo)
         return borderBoxRect();
 
@@ -122,17 +122,15 @@
     // Now apply the parent inset since it is cumulative whenever anything in the containing block chain shifts.
     // FIXME: Doesn't work right with perpendicular writing modes.
     const RenderBlock* currentBox = containingBlock();
-    offsetFromTopOfFirstPage -= logicalTop();
-    RenderBoxRegionInfo* currentBoxInfo = currentBox->renderBoxRegionInfo(region, offsetFromTopOfFirstPage);
+    RenderBoxRegionInfo* currentBoxInfo = currentBox->renderBoxRegionInfo(region);
     while (currentBoxInfo && currentBoxInfo->isShifted()) {
         if (currentBox->style()->direction() == LTR)
             logicalLeft += currentBoxInfo->logicalLeft();
         else
             logicalLeft -= (currentBox->logicalWidth() - currentBoxInfo->logicalWidth()) - currentBoxInfo->logicalLeft();
-        offsetFromTopOfFirstPage -= logicalTop();
         currentBox = currentBox->containingBlock();
         region = currentBox->clampToStartAndEndRegions(region);
-        currentBoxInfo = currentBox->renderBoxRegionInfo(region, offsetFromTopOfFirstPage);
+        currentBoxInfo = currentBox->renderBoxRegionInfo(region);
     }
 
     if (cacheFlag == DoNotCacheRenderBoxRegionInfo)
@@ -276,33 +274,8 @@
         }
     }
 
-    bool isBodyRenderer = isBody();
-    bool isRootRenderer = isRoot();
-
-    if (isRootRenderer || isBodyRenderer) {
-        // Propagate the new writing mode and direction up to the RenderView.
-        RenderView* viewRenderer = view();
-        RenderStyle* viewStyle = viewRenderer->style();
-        if (viewStyle->direction() != newStyle->direction() && (isRootRenderer || !document()->directionSetOnDocumentElement())) {
-            viewStyle->setDirection(newStyle->direction());
-            if (isBodyRenderer)
-                document()->documentElement()->renderer()->style()->setDirection(newStyle->direction());
-            setNeedsLayoutAndPrefWidthsRecalc();
-        }
-
-        if (viewStyle->writingMode() != newStyle->writingMode() && (isRootRenderer || !document()->writingModeSetOnDocumentElement())) {
-            viewStyle->setWritingMode(newStyle->writingMode());
-            viewRenderer->setHorizontalWritingMode(newStyle->isHorizontalWritingMode());
-            viewRenderer->markAllDescendantsWithFloatsForLayout();
-            if (isBodyRenderer) {
-                document()->documentElement()->renderer()->style()->setWritingMode(newStyle->writingMode());
-                document()->documentElement()->renderer()->setHorizontalWritingMode(newStyle->isHorizontalWritingMode());
-            }
-            setNeedsLayoutAndPrefWidthsRecalc();
-        }
-
-        frame()->view()->recalculateScrollbarOverlayStyle();
-    }
+    if (isRoot() || isBody())
+        document().view()->recalculateScrollbarOverlayStyle();
 
     updateShapeOutsideInfoAfterStyleChange(style()->shapeOutside(), oldStyle ? oldStyle->shapeOutside() : 0);
     updateGridPositionAfterStyleChange(oldStyle);
@@ -331,7 +304,8 @@
         && oldStyle->gridColumnEnd() == style()->gridColumnEnd()
         && oldStyle->gridRowStart() == style()->gridRowStart()
         && oldStyle->gridRowEnd() == style()->gridRowEnd()
-        && oldStyle->order() == style()->order())
+        && oldStyle->order() == style()->order()
+        && oldStyle->hasOutOfFlowPosition() == style()->hasOutOfFlowPosition())
         return;
 
     // It should be possible to not dirty the grid in some cases (like moving an explicitly placed grid item).
@@ -361,9 +335,9 @@
             // (1) The root element is <html>.
             // (2) We are the primary <body> (can be checked by looking at document.body).
             // (3) The root element has visible overflow.
-            if (isHTMLHtmlElement(document()->documentElement())
-                && document()->body() == node()
-                && document()->documentElement()->renderer()->style()->overflowX() == OVISIBLE)
+            if (isHTMLHtmlElement(document().documentElement())
+                && document().body() == node()
+                && document().documentElement()->renderer()->style()->overflowX() == OVISIBLE)
                 boxHasOverflowClip = false;
         }
 
@@ -445,7 +419,7 @@
         || style->resize() != RESIZE_NONE
         || style->boxSizing() == BORDER_BOX
         || !isRenderBlock()
-        || !isBlockFlow()
+        || !isRenderBlockFlow()
         || isFlexItemIncludingDeprecated();
 }
 
@@ -498,13 +472,13 @@
 void RenderBox::setScrollLeft(int newLeft)
 {
     if (hasOverflowClip())
-        layer()->scrollToXOffset(newLeft, RenderLayer::ScrollOffsetClamped);
+        layer()->scrollToXOffset(newLeft, ScrollOffsetClamped);
 }
 
 void RenderBox::setScrollTop(int newTop)
 {
     if (hasOverflowClip())
-        layer()->scrollToYOffset(newTop, RenderLayer::ScrollOffsetClamped);
+        layer()->scrollToYOffset(newTop, ScrollOffsetClamped);
 }
 
 void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
@@ -524,12 +498,12 @@
         layer()->updateTransform();
 }
 
-LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+LayoutUnit RenderBox::constrainLogicalWidthInRegionByMinMax(LayoutUnit logicalWidth, LayoutUnit availableWidth, RenderBlock* cb, RenderRegion* region) const
 {
     RenderStyle* styleToUse = style();
     if (!styleToUse->logicalMaxWidth().isUndefined())
-        logicalWidth = min(logicalWidth, computeLogicalWidthInRegionUsing(MaxSize, styleToUse->logicalMaxWidth(), availableWidth, cb, region, offsetFromLogicalTopOfFirstPage));
-    return max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse->logicalMinWidth(), availableWidth, cb, region, offsetFromLogicalTopOfFirstPage));
+        logicalWidth = min(logicalWidth, computeLogicalWidthInRegionUsing(MaxSize, styleToUse->logicalMaxWidth(), availableWidth, cb, region));
+    return max(logicalWidth, computeLogicalWidthInRegionUsing(MinSize, styleToUse->logicalMinWidth(), availableWidth, cb, region));
 }
 
 LayoutUnit RenderBox::constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const
@@ -755,7 +729,18 @@
 
 bool RenderBox::canBeProgramaticallyScrolled() const
 {
-    return (hasOverflowClip() && (scrollsOverflow() || (node() && node()->rendererIsEditable()))) || (node() && node()->isDocumentNode());
+    Node* node = this->node();
+    if (node && node->isDocumentNode())
+        return true;
+
+    if (!hasOverflowClip())
+        return false;
+
+    bool hasScrollableOverflow = hasScrollableOverflowX() || hasScrollableOverflowY();
+    if (scrollsOverflow() && hasScrollableOverflow)
+        return true;
+
+    return node && node->rendererIsEditable();
 }
 
 bool RenderBox::usesCompositedScrolling() const
@@ -777,18 +762,11 @@
 // There are two kinds of renderer that can autoscroll.
 bool RenderBox::canAutoscroll() const
 {
-    // Check for a box that can be scrolled in its own right.
-    if (canBeScrolledAndHasScrollableArea())
-        return true;
+    if (node() && node()->isDocumentNode())
+        return view()->frameView()->isScrollable();
 
-    // Check for a box that represents the top level of a web page.
-    if (node() != document())
-        return false;
-    Frame* frame = this->frame();
-    if (!frame)
-        return false;
-    Page* page = frame->page();
-    return page && page->mainFrame() == frame && frame->view()->isScrollable();
+    // Check for a box that can be scrolled in its own right.
+    return canBeScrolledAndHasScrollableArea();
 }
 
 // If specified point is in border belt, returned offset denotes direction of
@@ -802,29 +780,30 @@
     if (!frameView)
         return IntSize();
 
-    IntSize offset;
-    IntPoint point = frameView->windowToContents(windowPoint);
     IntRect box(absoluteBoundingBoxRect());
-    if (isRenderView())
-        box.moveBy(frameView->windowToContents(IntPoint()));
+    box.move(view()->frameView()->scrollOffset());
+    IntRect windowBox = view()->frameView()->contentsToWindow(box);
 
-    if (point.x() < box.x() + autoscrollBeltSize)
-        point.move(-autoscrollBeltSize, 0);
-    else if (point.x() > box.maxX() - autoscrollBeltSize)
-        point.move(autoscrollBeltSize, 0);
+    IntPoint windowAutoscrollPoint = windowPoint;
 
-    if (point.y() < box.y() + autoscrollBeltSize)
-        point.move(0, -autoscrollBeltSize);
-    else if (point.y() > box.maxY() - autoscrollBeltSize)
-        point.move(0, autoscrollBeltSize);
-    return frameView->contentsToWindow(point) - windowPoint;
+    if (windowAutoscrollPoint.x() < windowBox.x() + autoscrollBeltSize)
+        windowAutoscrollPoint.move(-autoscrollBeltSize, 0);
+    else if (windowAutoscrollPoint.x() > windowBox.maxX() - autoscrollBeltSize)
+        windowAutoscrollPoint.move(autoscrollBeltSize, 0);
+
+    if (windowAutoscrollPoint.y() < windowBox.y() + autoscrollBeltSize)
+        windowAutoscrollPoint.move(0, -autoscrollBeltSize);
+    else if (windowAutoscrollPoint.y() > windowBox.maxY() - autoscrollBeltSize)
+        windowAutoscrollPoint.move(0, autoscrollBeltSize);
+
+    return windowAutoscrollPoint - windowPoint;
 }
 
 RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
 {
     while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) {
-        if (!renderer->parent() && renderer->node() == renderer->document() && renderer->document()->ownerElement())
-            renderer = renderer->document()->ownerElement()->renderer();
+        if (!renderer->parent() && renderer->node() == &renderer->document() && renderer->document().ownerElement())
+            renderer = renderer->document().ownerElement()->renderer();
         else
             renderer = renderer->parent();
     }
@@ -1188,7 +1167,7 @@
     ASSERT(hasBackground());
     LayoutRect backgroundRect = pixelSnappedIntRect(borderBoxRect());
 
-    StyleColor backgroundColor = resolveStyleColor(CSSPropertyBackgroundColor);
+    Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
     if (backgroundColor.isValid() && backgroundColor.alpha())
         return backgroundRect;
     if (!style()->backgroundLayers()->image() || style()->backgroundLayers()->next())
@@ -1203,7 +1182,7 @@
     if (isBody() && skipBodyBackground(this))
         return false;
 
-    StyleColor backgroundColor = resolveStyleColor(CSSPropertyBackgroundColor);
+    Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
     if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
         return false;
 
@@ -1321,7 +1300,7 @@
 
     // If there is only one layer and no image, check whether the background color is opaque
     if (!fillLayer->next() && !fillLayer->hasImage()) {
-        StyleColor bgColor = resolveStyleColor(CSSPropertyBackgroundColor);
+        Color bgColor = resolveColor(CSSPropertyBackgroundColor);
         if (bgColor.isValid() && bgColor.alpha() == 255)
             return true;
     }
@@ -1482,7 +1461,7 @@
             // Now that we know this image is being used, compute the renderer and the rect
             // if we haven't already
             if (!layerRenderer) {
-                bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document()->documentElement()->renderer()->hasBackground()));
+                bool drawingRootBackground = drawingBackground && (isRoot() || (isBody() && !document().documentElement()->renderer()->hasBackground()));
                 if (drawingRootBackground) {
                     layerRenderer = view();
 
@@ -1628,18 +1607,17 @@
     return clipRect;
 }
 
-LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region) const
 {
     RenderRegion* containingBlockRegion = 0;
     LayoutUnit logicalTopPosition = logicalTop();
-    LayoutUnit adjustedPageOffsetForContainingBlock = offsetFromLogicalTopOfFirstPage - logicalTop();
     if (region) {
-        LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage : LayoutUnit();
+        LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
         logicalTopPosition = max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
         containingBlockRegion = cb->clampToStartAndEndRegions(region);
     }
 
-    LayoutUnit result = cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion, adjustedPageOffsetForContainingBlock) - childMarginStart - childMarginEnd;
+    LayoutUnit result = cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion) - childMarginStart - childMarginEnd;
 
     // We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
     // then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
@@ -1647,9 +1625,9 @@
     // doesn't fit, we can use the line offset, but we need to grow it by the margin to reflect the fact that the margin was
     // "consumed" by the float. Negative margins aren't consumed by the float, and so we ignore them.
     if (childMarginStart > 0) {
-        LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion, adjustedPageOffsetForContainingBlock);
+        LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion);
         LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
-        LayoutUnit startOffset = cb->startOffsetForLine(logicalTopPosition, false, containingBlockRegion, adjustedPageOffsetForContainingBlock);
+        LayoutUnit startOffset = cb->startOffsetForLine(logicalTopPosition, false, containingBlockRegion);
         if (startOffset > startContentSideWithMargin)
             result += childMarginStart;
         else
@@ -1657,9 +1635,9 @@
     }
 
     if (childMarginEnd > 0) {
-        LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion, adjustedPageOffsetForContainingBlock);
+        LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion);
         LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
-        LayoutUnit endOffset = cb->endOffsetForLine(logicalTopPosition, false, containingBlockRegion, adjustedPageOffsetForContainingBlock);
+        LayoutUnit endOffset = cb->endOffsetForLine(logicalTopPosition, false, containingBlockRegion);
         if (endOffset > endContentSideWithMargin)
             result += childMarginEnd;
         else
@@ -1687,7 +1665,7 @@
     return cb->availableLogicalHeight(heightType);
 }
 
-LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+LayoutUnit RenderBox::containingBlockLogicalWidthForContentInRegion(RenderRegion* region) const
 {
     if (!region)
         return containingBlockLogicalWidthForContent();
@@ -1697,24 +1675,23 @@
     // FIXME: It's unclear if a region's content should use the containing block's override logical width.
     // If it should, the following line should call containingBlockLogicalWidthForContent.
     LayoutUnit result = cb->availableLogicalWidth();
-    RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
+    RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
     if (!boxInfo)
         return result;
     return max<LayoutUnit>(0, result - (cb->logicalWidth() - boxInfo->logicalWidth()));
 }
 
-LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* region) const
 {
     RenderBlock* cb = containingBlock();
     RenderRegion* containingBlockRegion = 0;
     LayoutUnit logicalTopPosition = logicalTop();
-    LayoutUnit adjustedPageOffsetForContainingBlock = offsetFromLogicalTopOfFirstPage - logicalTop();
     if (region) {
-        LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage : LayoutUnit();
+        LayoutUnit offsetFromLogicalTopOfRegion = region ? region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage() : LayoutUnit();
         logicalTopPosition = max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
         containingBlockRegion = cb->clampToStartAndEndRegions(region);
     }
-    return cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion, adjustedPageOffsetForContainingBlock, availableLogicalHeight(IncludeMarginBorderPadding));
+    return cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
 }
 
 LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
@@ -2012,7 +1989,7 @@
         topLeft += layer()->offsetForInFlowPosition();
     }
 
-    if (position != AbsolutePosition && position != FixedPosition && o->hasColumns() && o->isBlockFlow()) {
+    if (position != AbsolutePosition && position != FixedPosition && o->hasColumns() && o->isRenderBlockFlow()) {
         LayoutRect repaintRect(topLeft, rect.size());
         toRenderBlock(o)->adjustRectForColumns(repaintRect);
         topLeft = repaintRect.location();
@@ -2099,7 +2076,7 @@
     return maxWidth;
 }
 
-void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
 {
     computedValues.m_extent = logicalWidth();
     computedValues.m_position = logicalLeft();
@@ -2109,7 +2086,7 @@
     if (isOutOfFlowPositioned()) {
         // FIXME: This calculation is not patched for block-flow yet.
         // https://bugs.webkit.org/show_bug.cgi?id=46500
-        computePositionedLogicalWidth(computedValues, region, offsetFromLogicalTopOfFirstPage);
+        computePositionedLogicalWidth(computedValues, region);
         return;
     }
 
@@ -2136,7 +2113,7 @@
     Length logicalWidthLength = treatAsReplaced ? Length(computeReplacedLogicalWidth(), Fixed) : styleToUse->logicalWidth();
 
     RenderBlock* cb = containingBlock();
-    LayoutUnit containerLogicalWidth = max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region, offsetFromLogicalTopOfFirstPage));
+    LayoutUnit containerLogicalWidth = max<LayoutUnit>(0, containingBlockLogicalWidthForContentInRegion(region));
     bool hasPerpendicularContainingBlock = cb->isHorizontalWritingMode() != isHorizontalWritingMode();
 
     if (isInline() && !isInlineBlockOrInlineTable()) {
@@ -2156,8 +2133,8 @@
         LayoutUnit containerWidthInInlineDirection = containerLogicalWidth;
         if (hasPerpendicularContainingBlock)
             containerWidthInInlineDirection = perpendicularContainingBlockLogicalHeight();
-        LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse->logicalWidth(), containerWidthInInlineDirection, cb, region, offsetFromLogicalTopOfFirstPage);
-        computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region, offsetFromLogicalTopOfFirstPage);
+        LayoutUnit preferredWidth = computeLogicalWidthInRegionUsing(MainOrPreferredSize, styleToUse->logicalWidth(), containerWidthInInlineDirection, cb, region);
+        computedValues.m_extent = constrainLogicalWidthInRegionByMinMax(preferredWidth, containerWidthInInlineDirection, cb, region);
     }
 
     // Margin calculations.
@@ -2168,7 +2145,7 @@
     } else {
         LayoutUnit containerLogicalWidthForAutoMargins = containerLogicalWidth;
         if (avoidsFloats() && cb->containsFloats())
-            containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region, offsetFromLogicalTopOfFirstPage);
+            containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(region);
         bool hasInvertedDirection = cb->style()->isLeftToRightDirection() != style()->isLeftToRightDirection();
         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, computedValues.m_extent,
             hasInvertedDirection ? computedValues.m_margins.m_end : computedValues.m_margins.m_start,
@@ -2240,7 +2217,7 @@
 }
 
 LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Length logicalWidth, LayoutUnit availableLogicalWidth,
-    const RenderBlock* cb, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+    const RenderBlock* cb, RenderRegion* region) const
 {
     if (!logicalWidth.isIntrinsicOrAuto()) {
         // FIXME: If the containing block flow is perpendicular to our direction we need to use the available logical height instead.
@@ -2255,7 +2232,7 @@
     LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
 
     if (shrinkToAvoidFloats() && cb->containsFloats())
-        logicalWidthResult = min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region, offsetFromLogicalTopOfFirstPage));
+        logicalWidthResult = min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
 
     if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
         return max(minPreferredLogicalWidth(), min(maxPreferredLogicalWidth(), logicalWidthResult));
@@ -2399,7 +2376,7 @@
     marginEnd = minimumValueForLength(marginEndLength, containerWidth, renderView);
 }
 
-RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage, RenderBoxRegionInfoFlags cacheFlag) const
+RenderBoxRegionInfo* RenderBox::renderBoxRegionInfo(RenderRegion* region, RenderBoxRegionInfoFlags cacheFlag) const
 {
     // Make sure nobody is trying to call this with a null region.
     if (!region)
@@ -2419,13 +2396,12 @@
         return 0;
 
     LogicalExtentComputedValues computedValues;
-    computeLogicalWidthInRegion(computedValues, region, offsetFromLogicalTopOfFirstPage);
+    computeLogicalWidthInRegion(computedValues, region);
 
     // Now determine the insets based off where this object is supposed to be positioned.
     RenderBlock* cb = containingBlock();
     RenderRegion* clampedContainingBlockRegion = cb->clampToStartAndEndRegions(region);
-    RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion,
-        offsetFromLogicalTopOfFirstPage - logicalTop());
+    RenderBoxRegionInfo* containingBlockInfo = cb->renderBoxRegionInfo(clampedContainingBlockRegion);
     LayoutUnit containingBlockLogicalWidth = cb->logicalWidth();
     LayoutUnit containingBlockLogicalWidthInRegion = containingBlockInfo ? containingBlockInfo->logicalWidth() : containingBlockLogicalWidth;
 
@@ -2442,7 +2418,7 @@
     LayoutUnit logicalLeftOffset = 0;
 
     if (!isOutOfFlowPositioned() && avoidsFloats() && cb->containsFloats()) {
-        LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(this, marginStartInRegion, region, offsetFromLogicalTopOfFirstPage);
+        LayoutUnit startPositionDelta = cb->computeStartPositionDeltaForChildAvoidingFloats(this, marginStartInRegion, region);
         if (cb->style()->isLeftToRightDirection())
             logicalLeftDelta += startPositionDelta;
         else
@@ -2596,8 +2572,8 @@
     // is specified. When we're printing, we also need this quirk if the body or root has a percentage
     // height since we don't set a height in RenderView when we're printing. So without this quirk, the
     // height has nothing to be a percentage of, and it ends up being 0. That is bad.
-    bool paginatedContentNeedsBaseHeight = document()->printing() && h.isPercent()
-        && (isRoot() || (isBody() && document()->documentElement()->renderer()->style()->logicalHeight().isPercent())) && !isInline();
+    bool paginatedContentNeedsBaseHeight = document().printing() && h.isPercent()
+        && (isRoot() || (isBody() && document().documentElement()->renderer()->style()->logicalHeight().isPercent())) && !isInline();
     if (stretchesToViewport() || paginatedContentNeedsBaseHeight) {
         LayoutUnit margins = collapsedMarginBefore() + collapsedMarginAfter();
         LayoutUnit visibleHeight = viewLogicalHeightForPercentages();
@@ -2612,7 +2588,7 @@
 
 LayoutUnit RenderBox::viewLogicalHeightForPercentages() const
 {
-    if (document()->printing())
+    if (document().printing())
         return static_cast<LayoutUnit>(view()->pageLogicalHeight());
     return view()->viewLogicalHeight();
 }
@@ -2672,7 +2648,7 @@
 {
     // For quirks mode and anonymous blocks, we skip auto-height containingBlocks when computing percentages.
     // For standards mode, we treat the percentage as auto if it has an auto-height containing block.
-    if (!document()->inQuirksMode() && !containingBlock->isAnonymousBlock())
+    if (!document().inQuirksMode() && !containingBlock->isAnonymousBlock())
         return false;
     return !containingBlock->isTableCell() && !containingBlock->isOutOfFlowPositioned() && containingBlock->style()->logicalHeight().isAuto() && isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode();
 }
@@ -2935,7 +2911,7 @@
         return logicalHeight() - borderAndPaddingLogicalHeight();
     }
 
-    if (h.isPercent() && isOutOfFlowPositioned()) {
+    if (h.isPercent() && isOutOfFlowPositioned() && !isRenderFlowThread()) {
         // FIXME: This is wrong if the containingBlock has a perpendicular writing mode.
         LayoutUnit availableHeight = containingBlockLogicalHeightForPositioned(containingBlock());
         return adjustContentBoxLogicalHeightForBoxSizing(valueForLength(h, availableHeight));
@@ -2992,8 +2968,7 @@
     containingBlock->setMarginAfterForChild(this, marginAfter);
 }
 
-LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region,
-    LayoutUnit offsetFromLogicalTopOfFirstPage, bool checkForPerpendicularWritingMode) const
+LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* region, bool checkForPerpendicularWritingMode) const
 {
     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
         return containingBlockLogicalHeightForPositioned(containingBlock, false);
@@ -3018,16 +2993,16 @@
             if (containingBlock->isRenderFlowThread() && !checkForPerpendicularWritingMode)
                 return toRenderFlowThread(containingBlock)->contentLogicalWidthOfFirstRegion();
             if (isWritingModeRoot()) {
-                LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
+                LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage();
                 RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
                 if (cbRegion) {
                     cbRegion = cb->clampToStartAndEndRegions(cbRegion);
-                    boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
+                    boxInfo = cb->renderBoxRegionInfo(cbRegion);
                 }
             }
         } else if (region && flowThread->isHorizontalWritingMode() == containingBlock->isHorizontalWritingMode()) {
             RenderRegion* containingBlockRegion = cb->clampToStartAndEndRegions(region);
-            boxInfo = cb->renderBoxRegionInfo(containingBlockRegion, offsetFromLogicalTopOfFirstPage - logicalTop());
+            boxInfo = cb->renderBoxRegionInfo(containingBlockRegion);
         }
         return (boxInfo) ? max<LayoutUnit>(0, cb->clientLogicalWidth() - (cb->logicalWidth() - boxInfo->logicalWidth())) : cb->clientLogicalWidth();
     }
@@ -3058,7 +3033,7 @@
 LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode) const
 {
     if (checkForPerpendicularWritingMode && containingBlock->isHorizontalWritingMode() != isHorizontalWritingMode())
-        return containingBlockLogicalWidthForPositioned(containingBlock, 0, 0, false);
+        return containingBlockLogicalWidthForPositioned(containingBlock, 0, false);
 
     // Use viewport as container for top-level fixed-position elements.
     if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
@@ -3112,7 +3087,7 @@
                 if (region && curr->isRenderBlock()) {
                     const RenderBlock* cb = toRenderBlock(curr);
                     region = cb->clampToStartAndEndRegions(region);
-                    RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->logicalTopForFlowThreadContent());
+                    RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region);
                     if (boxInfo)
                         staticPosition += boxInfo->logicalLeft();
                 }
@@ -3129,10 +3104,10 @@
                 if (curr == enclosingBox)
                     staticPosition -= enclosingBox->logicalWidth();
                 if (region && curr->isRenderBlock()) {
-                     const RenderBlock* cb = toRenderBlock(curr);
-                     region = cb->clampToStartAndEndRegions(region);
-                     RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region, region->logicalTopForFlowThreadContent());
-                     if (boxInfo) {
+                    const RenderBlock* cb = toRenderBlock(curr);
+                    region = cb->clampToStartAndEndRegions(region);
+                    RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(region);
+                    if (boxInfo) {
                         if (curr != containerBlock)
                             staticPosition -= cb->logicalWidth() - (boxInfo->logicalLeft() + boxInfo->logicalWidth());
                         if (curr == enclosingBox)
@@ -3147,7 +3122,7 @@
     }
 }
 
-void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
+void RenderBox::computePositionedLogicalWidth(LogicalExtentComputedValues& computedValues, RenderRegion* region) const
 {
     if (isReplaced()) {
         // FIXME: Positioned replaced elements inside a flow thread are not working properly
@@ -3176,7 +3151,7 @@
     // relative positioned inline.
     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
 
-    const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region, offsetFromLogicalTopOfFirstPage);
+    const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, region);
 
     // Use the container block's direction except when calculating the static distance
     // This conforms with the reference results for abspos-replaced-width-margin-000.htm
@@ -3268,11 +3243,11 @@
         ASSERT(containerBlock->canHaveBoxInfoInRegion());
         LayoutUnit logicalLeftPos = computedValues.m_position;
         const RenderBlock* cb = toRenderBlock(containerBlock);
-        LayoutUnit cbPageOffset = offsetFromLogicalTopOfFirstPage - logicalTop();
+        LayoutUnit cbPageOffset = cb->offsetFromLogicalTopOfFirstPage();
         RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
         if (cbRegion) {
             cbRegion = cb->clampToStartAndEndRegions(cbRegion);
-            RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
+            RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion);
             if (boxInfo) {
                 logicalLeftPos += boxInfo->logicalLeft();
                 computedValues.m_position = logicalLeftPos;
@@ -3306,7 +3281,7 @@
 
     LayoutUnit logicalLeftValue = 0;
 
-    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, 0, false);
+    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
 
     bool logicalWidthIsAuto = logicalWidth.isIntrinsicOrAuto();
     bool logicalLeftIsAuto = logicalLeft.isAuto();
@@ -3591,7 +3566,7 @@
         RenderRegion* cbRegion = cb->regionAtBlockOffset(cbPageOffset);
         if (cbRegion) {
             cbRegion = cb->clampToStartAndEndRegions(cbRegion);
-            RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion, cbPageOffset);
+            RenderBoxRegionInfo* boxInfo = cb->renderBoxRegionInfo(cbRegion);
             if (boxInfo) {
                 logicalTopPos += boxInfo->logicalLeft();
                 computedValues.m_position = logicalTopPos;
@@ -3634,7 +3609,7 @@
     LayoutUnit logicalHeightValue;
     LayoutUnit contentLogicalHeight = logicalHeight - bordersPlusPadding;
 
-    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, 0, false);
+    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
 
     LayoutUnit logicalTopValue = 0;
 
@@ -3766,7 +3741,7 @@
     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
 
     const LayoutUnit containerLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock);
-    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, 0, false);
+    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
 
     // To match WinIE, in quirks mode use the parent's 'direction' property
     // instead of the the container block's.
@@ -3935,7 +3910,7 @@
     const RenderBoxModelObject* containerBlock = toRenderBoxModelObject(container());
 
     const LayoutUnit containerLogicalHeight = containingBlockLogicalHeightForPositioned(containerBlock);
-    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, 0, false);
+    const LayoutUnit containerRelativeLogicalWidth = containingBlockLogicalWidthForPositioned(containerBlock, 0, false);
 
     // Variables to solve.
     Length marginBefore = style()->marginBefore();
@@ -4130,7 +4105,7 @@
         adjustedPoint.moveBy(location());
 
     for (RenderObject* renderObject = firstChild(); renderObject; renderObject = renderObject->nextSibling()) {
-        if ((!renderObject->firstChild() && !renderObject->isInline() && !renderObject->isBlockFlow() )
+        if ((!renderObject->firstChild() && !renderObject->isInline() && !renderObject->isRenderBlockFlow() )
             || renderObject->style()->visibility() != VISIBLE)
             continue;
 
@@ -4372,7 +4347,7 @@
     // block has an auto height. We still skip anonymous containing blocks in both modes, though, and look
     // only at explicit containers.
     const RenderBlock* cb = containingBlock;
-    bool inQuirksMode = cb->document()->inQuirksMode();
+    bool inQuirksMode = cb->document().inQuirksMode();
     while (!cb->isRenderView() && !cb->isBody() && !cb->isTableCell() && !cb->isOutOfFlowPositioned() && cb->style()->logicalHeight().isAuto()) {
         if (!inQuirksMode && !cb->isAnonymousBlock())
             break;
@@ -4740,4 +4715,17 @@
     return beforeChild;
 }
 
+LayoutUnit RenderBox::offsetFromLogicalTopOfFirstPage() const
+{
+    LayoutState* layoutState = view()->layoutState();
+    if (layoutState && !layoutState->isPaginated())
+        return 0;
+
+    if (!layoutState && !flowThreadContainingBlock())
+        return 0;
+
+    RenderBlock* containerBlock = containingBlock();
+    return containerBlock->offsetFromLogicalTopOfFirstPage() + logicalTop();
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderBox.h b/Source/core/rendering/RenderBox.h
index 3a7f271..208cfe7 100644
--- a/Source/core/rendering/RenderBox.h
+++ b/Source/core/rendering/RenderBox.h
@@ -49,7 +49,7 @@
 
     // hasAutoZIndex only returns true if the element is positioned or a flex-item since
     // position:static elements that are not flex-items get their z-index coerced to auto.
-    virtual bool requiresLayer() const OVERRIDE { return isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasOverflowClip() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns() || !style()->hasAutoZIndex() || isFloatingWithShapeOutside(); }
+    virtual bool requiresLayer() const OVERRIDE { return isRoot() || isPositioned() || createsGroup() || hasClipPath() || hasOverflowClip() || hasTransform() || hasHiddenBackface() || hasReflection() || style()->specifiesColumns() || !style()->hasAutoZIndex(); }
 
     virtual bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const OVERRIDE;
 
@@ -82,7 +82,7 @@
     LayoutUnit logicalWidth() const { return style()->isHorizontalWritingMode() ? width() : height(); }
     LayoutUnit logicalHeight() const { return style()->isHorizontalWritingMode() ? height() : width(); }
 
-    LayoutUnit constrainLogicalWidthInRegionByMinMax(LayoutUnit, LayoutUnit, RenderBlock*, RenderRegion* = 0, LayoutUnit offsetFromLogicalTopOfFirstPage = 0) const;
+    LayoutUnit constrainLogicalWidthInRegionByMinMax(LayoutUnit, LayoutUnit, RenderBlock*, RenderRegion* = 0) const;
     LayoutUnit constrainLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const;
     LayoutUnit constrainContentBoxLogicalHeightByMinMax(LayoutUnit logicalHeight, LayoutUnit intrinsicContentHeight) const;
 
@@ -371,8 +371,9 @@
     void computeAndSetBlockDirectionMargins(const RenderBlock* containingBlock);
 
     enum RenderBoxRegionInfoFlags { CacheRenderBoxRegionInfo, DoNotCacheRenderBoxRegionInfo };
-    LayoutRect borderBoxRectInRegion(RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage = 0, RenderBoxRegionInfoFlags = CacheRenderBoxRegionInfo) const;
+    LayoutRect borderBoxRectInRegion(RenderRegion*, RenderBoxRegionInfoFlags = CacheRenderBoxRegionInfo) const;
     void clearRenderBoxRegionInfo();
+    virtual LayoutUnit offsetFromLogicalTopOfFirstPage() const;
 
     void positionLineBox(InlineBox*);
 
@@ -394,20 +395,20 @@
     virtual LayoutUnit containingBlockLogicalWidthForContent() const;
     LayoutUnit containingBlockLogicalHeightForContent(AvailableLogicalHeightType) const;
 
-    LayoutUnit containingBlockLogicalWidthForContentInRegion(RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage) const;
-    LayoutUnit containingBlockAvailableLineWidthInRegion(RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage) const;
+    LayoutUnit containingBlockLogicalWidthForContentInRegion(RenderRegion*) const;
+    LayoutUnit containingBlockAvailableLineWidthInRegion(RenderRegion*) const;
     LayoutUnit perpendicularContainingBlockLogicalHeight() const;
 
     virtual void updateLogicalWidth();
     virtual void updateLogicalHeight();
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const;
 
-    RenderBoxRegionInfo* renderBoxRegionInfo(RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage, RenderBoxRegionInfoFlags = CacheRenderBoxRegionInfo) const;
-    void computeLogicalWidthInRegion(LogicalExtentComputedValues&, RenderRegion* = 0, LayoutUnit offsetFromLogicalTopOfFirstPage = 0) const;
+    RenderBoxRegionInfo* renderBoxRegionInfo(RenderRegion*, RenderBoxRegionInfoFlags = CacheRenderBoxRegionInfo) const;
+    void computeLogicalWidthInRegion(LogicalExtentComputedValues&, RenderRegion* = 0) const;
 
     bool stretchesToViewport() const
     {
-        return document()->inQuirksMode() && style()->logicalHeight().isAuto() && !isFloatingOrOutOfFlowPositioned() && (isRoot() || isBody()) && !document()->shouldDisplaySeamlesslyWithParent() && !isInline();
+        return document().inQuirksMode() && style()->logicalHeight().isAuto() && !isFloatingOrOutOfFlowPositioned() && (isRoot() || isBody()) && !document().shouldDisplaySeamlesslyWithParent() && !isInline();
     }
 
     virtual LayoutSize intrinsicSize() const { return LayoutSize(); }
@@ -418,9 +419,9 @@
     // of a containing block).  HTML4 buttons, <select>s, <input>s, legends, and floating/compact elements do this.
     bool sizesLogicalWidthToFitContent(SizeType) const;
 
-    LayoutUnit shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage) const;
+    LayoutUnit shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion*) const;
 
-    LayoutUnit computeLogicalWidthInRegionUsing(SizeType, Length logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* containingBlock, RenderRegion*, LayoutUnit offsetFromLogicalTopOfFirstPage) const;
+    LayoutUnit computeLogicalWidthInRegionUsing(SizeType, Length logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* containingBlock, RenderRegion*) const;
     LayoutUnit computeLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const;
     LayoutUnit computeContentLogicalHeight(const Length& height, LayoutUnit intrinsicContentHeight) const;
     LayoutUnit computeContentAndScrollbarLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const;
@@ -464,6 +465,9 @@
     bool hasAutoVerticalScrollbar() const { return hasOverflowClip() && (style()->overflowY() == OAUTO || style()->overflowY() == OOVERLAY); }
     bool hasAutoHorizontalScrollbar() const { return hasOverflowClip() && (style()->overflowX() == OAUTO || style()->overflowX() == OOVERLAY); }
     bool scrollsOverflow() const { return scrollsOverflowX() || scrollsOverflowY(); }
+
+    bool hasScrollableOverflowX() const { return scrollsOverflowX() && scrollWidth() != clientWidth(); }
+    bool hasScrollableOverflowY() const { return scrollsOverflowY() && scrollHeight() != clientHeight(); }
     virtual bool scrollsOverflowX() const { return hasOverflowClip() && (style()->overflowX() == OSCROLL || hasAutoHorizontalScrollbar()); }
     virtual bool scrollsOverflowY() const { return hasOverflowClip() && (style()->overflowY() == OSCROLL || hasAutoVerticalScrollbar()); }
     bool usesCompositedScrolling() const;
@@ -590,7 +594,7 @@
 
     ShapeOutsideInfo* shapeOutsideInfo() const
     {
-        return isFloatingWithShapeOutside() && ShapeOutsideInfo::isEnabledFor(this) ? ShapeOutsideInfo::info(this) : 0;
+        return ShapeOutsideInfo::isEnabledFor(this) ? ShapeOutsideInfo::info(this) : 0;
     }
 
 protected:
@@ -614,7 +618,7 @@
     BackgroundBleedAvoidance determineBackgroundBleedAvoidance(GraphicsContext*) const;
     bool backgroundHasOpaqueTopLayer() const;
 
-    void computePositionedLogicalWidth(LogicalExtentComputedValues&, RenderRegion* = 0, LayoutUnit offsetFromLogicalTopOfFirstPage = 0) const;
+    void computePositionedLogicalWidth(LogicalExtentComputedValues&, RenderRegion* = 0) const;
 
     LayoutUnit computeIntrinsicLogicalWidthUsing(Length logicalWidthLength, LayoutUnit availableLogicalWidth, LayoutUnit borderAndPadding) const;
     LayoutUnit computeIntrinsicLogicalContentHeightUsing(Length logicalHeightLength, LayoutUnit intrinsicContentHeight, LayoutUnit borderAndPadding) const;
@@ -643,8 +647,7 @@
 
     bool skipContainingBlockForPercentHeightCalculation(const RenderBox* containingBlock) const;
 
-    LayoutUnit containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* = 0,
-        LayoutUnit offsetFromLogicalTopOfFirstPage = 0, bool checkForPerpendicularWritingMode = true) const;
+    LayoutUnit containingBlockLogicalWidthForPositioned(const RenderBoxModelObject* containingBlock, RenderRegion* = 0, bool checkForPerpendicularWritingMode = true) const;
     LayoutUnit containingBlockLogicalHeightForPositioned(const RenderBoxModelObject* containingBlock, bool checkForPerpendicularWritingMode = true) const;
 
     LayoutUnit viewLogicalHeightForPercentages() const;
diff --git a/Source/core/rendering/RenderBoxModelObject.cpp b/Source/core/rendering/RenderBoxModelObject.cpp
index 3a51da6..aada216 100644
--- a/Source/core/rendering/RenderBoxModelObject.cpp
+++ b/Source/core/rendering/RenderBoxModelObject.cpp
@@ -214,7 +214,7 @@
     // For percentage heights: The percentage is calculated with respect to the height of the generated box's
     // containing block. If the height of the containing block is not specified explicitly (i.e., it depends
     // on content height), and this element is not absolutely positioned, the value computes to 'auto'.
-    if (!logicalHeightLength.isPercent() || isOutOfFlowPositioned() || document()->inQuirksMode())
+    if (!logicalHeightLength.isPercent() || isOutOfFlowPositioned() || document().inQuirksMode())
         return false;
 
     // Anonymous block boxes are ignored when resolving percentage values that would refer to it:
@@ -540,10 +540,10 @@
     bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(this, style()->effectiveZoom());
 
     bool forceBackgroundToWhite = false;
-    if (document()->printing()) {
+    if (document().printing()) {
         if (style()->printColorAdjust() == PrintColorAdjustEconomy)
             forceBackgroundToWhite = true;
-        if (document()->settings() && document()->settings()->shouldPrintBackgrounds())
+        if (document().settings() && document().settings()->shouldPrintBackgrounds())
             forceBackgroundToWhite = false;
     }
 
@@ -556,14 +556,14 @@
     // while rendering.)
     if (forceBackgroundToWhite) {
         // Note that we can't reuse this variable below because the bgColor might be changed
-        bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.alpha();
+        bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha();
         if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
             bgColor = Color::white;
             shouldPaintBackgroundImage = false;
         }
     }
 
-    bool colorVisible = bgColor.alpha();
+    bool colorVisible = bgColor.isValid() && bgColor.alpha();
 
     // Fast path for drawing simple color backgrounds.
     if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
@@ -673,21 +673,21 @@
     bool isOpaqueRoot = false;
     if (isRoot) {
         isOpaqueRoot = true;
-        if (!bgLayer->next() && !(bgColor.alpha() == 255) && view()->frameView()) {
-            Element* ownerElement = document()->ownerElement();
+        if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255) && view()->frameView()) {
+            Element* ownerElement = document().ownerElement();
             if (ownerElement) {
                 if (!ownerElement->hasTagName(frameTag)) {
                     // Locate the <body> element using the DOM.  This is easier than trying
                     // to crawl around a render tree with potential :before/:after content and
                     // anonymous blocks created by inline <body> tags etc.  We can locate the <body>
                     // render object very easily via the DOM.
-                    HTMLElement* body = document()->body();
+                    HTMLElement* body = document().body();
                     if (body) {
                         // Can't scroll a frameset document anyway.
                         isOpaqueRoot = body->hasLocalName(framesetTag);
                     } else {
                         // SVG documents and XML documents with SVG root nodes are transparent.
-                        isOpaqueRoot = !document()->hasSVGRootNode();
+                        isOpaqueRoot = !document().hasSVGRootNode();
                     }
                 }
             } else
@@ -2401,7 +2401,7 @@
         return false;
 
     Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
-    if (backgroundColor.hasAlpha())
+    if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
         return false;
 
     const FillLayer* lastBackgroundLayer = style()->backgroundLayers();
@@ -2463,7 +2463,7 @@
         if (shadowOffset.isZero() && !shadowBlur && !shadowSpread)
             continue;
 
-        const Color& shadowColor = resolveColor(shadow->color(), Color::stdShadowColor);
+        const Color& shadowColor = resolveColor(shadow->color());
 
         if (shadow->style() == Normal) {
             RoundedRect fillRect = border;
diff --git a/Source/core/rendering/RenderBoxModelObject.h b/Source/core/rendering/RenderBoxModelObject.h
index 4fc1de9..bcbaf90 100644
--- a/Source/core/rendering/RenderBoxModelObject.h
+++ b/Source/core/rendering/RenderBoxModelObject.h
@@ -100,8 +100,8 @@
     LayoutUnit computedCSSPaddingStart() const { return computedCSSPadding(style()->paddingStart()); }
     LayoutUnit computedCSSPaddingEnd() const { return computedCSSPadding(style()->paddingEnd()); }
 
-    // These functions are used during layout. Table cells and the MathML
-    // code override them to include some extra intrinsic padding.
+    // These functions are used during layout. Table cells
+    // override them to include some extra intrinsic padding.
     virtual LayoutUnit paddingTop() const { return computedCSSPaddingTop(); }
     virtual LayoutUnit paddingBottom() const { return computedCSSPaddingBottom(); }
     virtual LayoutUnit paddingLeft() const { return computedCSSPaddingLeft(); }
@@ -175,7 +175,7 @@
 
     virtual void setSelectionState(SelectionState s);
 
-    bool canHaveBoxInfoInRegion() const { return !isFloating() && !isReplaced() && !isInline() && !hasColumns() && !isTableCell() && isBlockFlow() && !isRenderSVGBlock(); }
+    bool canHaveBoxInfoInRegion() const { return !isFloating() && !isReplaced() && !isInline() && !hasColumns() && !isTableCell() && isRenderBlock() && !isRenderSVGBlock(); }
 
     void contentChanged(ContentChangeType);
     bool hasAcceleratedCompositing() const;
diff --git a/Source/core/rendering/RenderCounter.cpp b/Source/core/rendering/RenderCounter.cpp
index 895d44f..224ca85 100644
--- a/Source/core/rendering/RenderCounter.cpp
+++ b/Source/core/rendering/RenderCounter.cpp
@@ -417,23 +417,7 @@
 
 void RenderCounter::updateCounter()
 {
-    computePreferredLogicalWidths(0);
-}
-
-void RenderCounter::computePreferredLogicalWidths(float lead)
-{
-#ifndef NDEBUG
-    // FIXME: We shouldn't be modifying the tree in computePreferredLogicalWidths.
-    // Instead, we should properly hook the appropriate changes in the DOM and modify
-    // the render tree then. When that's done, we also won't need to override
-    // computePreferredLogicalWidths at all.
-    // https://bugs.webkit.org/show_bug.cgi?id=104829
-    SetLayoutNeededForbiddenScope layoutForbiddenScope(this, false);
-#endif
-
     setTextInternal(originalText());
-
-    RenderText::computePreferredLogicalWidths(lead);
 }
 
 void RenderCounter::invalidate()
diff --git a/Source/core/rendering/RenderCounter.h b/Source/core/rendering/RenderCounter.h
index ee7943f..3fa3fdd 100644
--- a/Source/core/rendering/RenderCounter.h
+++ b/Source/core/rendering/RenderCounter.h
@@ -50,8 +50,6 @@
     virtual bool isCounter() const;
     virtual PassRefPtr<StringImpl> originalText() const;
 
-    virtual void computePreferredLogicalWidths(float leadWidth) OVERRIDE;
-
     // Removes the reference to the CounterNode associated with this renderer.
     // This is used to cause a counter display update when the CounterNode tree changes.
     void invalidate();
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
index d6de88a..24f9c3c 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
@@ -126,13 +126,13 @@
     setChildrenInline(false); // All of our children must be block-level
     m_stretchingChildren = false;
     if (!isAnonymous()) {
-        const KURL& url = document()->url();
+        const KURL& url = document().url();
         if (url.protocolIs("chrome"))
-            UseCounter::count(document(), UseCounter::DeprecatedFlexboxChrome);
+            UseCounter::count(&document(), UseCounter::DeprecatedFlexboxChrome);
         else if (url.protocolIs("chrome-extension"))
-            UseCounter::count(document(), UseCounter::DeprecatedFlexboxChromeExtension);
+            UseCounter::count(&document(), UseCounter::DeprecatedFlexboxChromeExtension);
         else
-            UseCounter::count(document(), UseCounter::DeprecatedFlexboxWebContent);
+            UseCounter::count(&document(), UseCounter::DeprecatedFlexboxWebContent);
     }
 }
 
@@ -900,7 +900,7 @@
 
 void RenderDeprecatedFlexibleBox::applyLineClamp(FlexBoxIterator& iterator, bool relayoutChildren)
 {
-    UseCounter::count(document(), UseCounter::LineClamp);
+    UseCounter::count(&document(), UseCounter::LineClamp);
 
     int maxLineCount = 0;
     for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
@@ -909,7 +909,7 @@
 
         child->clearOverrideSize();
         if (relayoutChildren || (child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent()))
-            || (child->style()->height().isAuto() && child->isBlockFlow())) {
+            || (child->style()->height().isAuto() && child->isRenderBlock())) {
             child->setChildNeedsLayout(MarkOnlyThis);
 
             // Dirty all the positioned objects.
@@ -919,7 +919,7 @@
             }
         }
         child->layoutIfNeeded();
-        if (child->style()->height().isAuto() && child->isBlockFlow())
+        if (child->style()->height().isAuto() && child->isRenderBlock())
             maxLineCount = max(maxLineCount, toRenderBlock(child)->lineCount());
     }
 
@@ -931,7 +931,7 @@
         return;
 
     for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
-        if (childDoesNotAffectWidthOrFlexing(child) || !child->style()->height().isAuto() || !child->isBlockFlow())
+        if (childDoesNotAffectWidthOrFlexing(child) || !child->style()->height().isAuto() || !child->isRenderBlock())
             continue;
 
         RenderBlock* blockChild = toRenderBlock(child);
@@ -1007,7 +1007,7 @@
 
         child->clearOverrideSize();
         if ((child->isReplaced() && (child->style()->width().isPercent() || child->style()->height().isPercent()))
-            || (child->style()->height().isAuto() && child->isBlockFlow())) {
+            || (child->style()->height().isAuto() && child->isRenderBlock())) {
             child->setChildNeedsLayout();
 
             if (child->isRenderBlock()) {
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.h b/Source/core/rendering/RenderDeprecatedFlexibleBox.h
index 7d3df07..ff039da 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.h
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.h
@@ -64,6 +64,8 @@
     bool m_stretchingChildren;
 
 private:
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     void applyLineClamp(FlexBoxIterator&, bool relayoutChildren);
     void clearLineClamp();
 };
diff --git a/Source/core/rendering/RenderDetailsMarker.cpp b/Source/core/rendering/RenderDetailsMarker.cpp
index b6ab9a2..f076294 100644
--- a/Source/core/rendering/RenderDetailsMarker.cpp
+++ b/Source/core/rendering/RenderDetailsMarker.cpp
@@ -31,7 +31,7 @@
 using namespace HTMLNames;
 
 RenderDetailsMarker::RenderDetailsMarker(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
 }
 
diff --git a/Source/core/rendering/RenderDetailsMarker.h b/Source/core/rendering/RenderDetailsMarker.h
index d93a629..8fa0f7e 100644
--- a/Source/core/rendering/RenderDetailsMarker.h
+++ b/Source/core/rendering/RenderDetailsMarker.h
@@ -21,11 +21,11 @@
 #ifndef RenderDetailsMarker_h
 #define RenderDetailsMarker_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
-class RenderDetailsMarker FINAL : public RenderBlock {
+class RenderDetailsMarker FINAL : public RenderBlockFlow {
 public:
     RenderDetailsMarker(Element*);
 
@@ -35,6 +35,7 @@
 
 private:
     virtual const char* renderName() const { return "RenderDetailsMarker"; }
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual bool isDetailsMarker() const { return true; }
     virtual void paint(PaintInfo&, const LayoutPoint&);
 
diff --git a/Source/core/rendering/RenderEmbeddedObject.cpp b/Source/core/rendering/RenderEmbeddedObject.cpp
index 3a5eaad..03b6f49 100644
--- a/Source/core/rendering/RenderEmbeddedObject.cpp
+++ b/Source/core/rendering/RenderEmbeddedObject.cpp
@@ -184,7 +184,7 @@
     FontDescription fontDescription;
     RenderTheme::theme().systemFont(CSSValueWebkitSmallControl, fontDescription);
     fontDescription.setWeight(FontWeightBold);
-    Settings* settings = document()->settings();
+    Settings* settings = document().settings();
     ASSERT(settings);
     if (!settings)
         return false;
diff --git a/Source/core/rendering/RenderFieldset.cpp b/Source/core/rendering/RenderFieldset.cpp
index ba01593..23a3cf9 100644
--- a/Source/core/rendering/RenderFieldset.cpp
+++ b/Source/core/rendering/RenderFieldset.cpp
@@ -37,7 +37,7 @@
 using namespace HTMLNames;
 
 RenderFieldset::RenderFieldset(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
 }
 
diff --git a/Source/core/rendering/RenderFieldset.h b/Source/core/rendering/RenderFieldset.h
index 0bfd538..65329bd 100644
--- a/Source/core/rendering/RenderFieldset.h
+++ b/Source/core/rendering/RenderFieldset.h
@@ -24,11 +24,11 @@
 #ifndef RenderFieldset_h
 #define RenderFieldset_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
-class RenderFieldset FINAL : public RenderBlock {
+class RenderFieldset FINAL : public RenderBlockFlow {
 public:
     explicit RenderFieldset(Element*);
 
@@ -44,6 +44,8 @@
     virtual void computePreferredLogicalWidths();
     virtual bool avoidsFloats() const { return true; }
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&);
     virtual void paintMask(PaintInfo&, const LayoutPoint&);
 };
diff --git a/Source/core/rendering/RenderFileUploadControl.cpp b/Source/core/rendering/RenderFileUploadControl.cpp
index 6a53083..64c1d92 100644
--- a/Source/core/rendering/RenderFileUploadControl.cpp
+++ b/Source/core/rendering/RenderFileUploadControl.cpp
@@ -45,7 +45,7 @@
 const int buttonShadowHeight = 2;
 
 RenderFileUploadControl::RenderFileUploadControl(HTMLInputElement* input)
-    : RenderBlock(input)
+    : RenderBlockFlow(input)
     , m_canReceiveDroppedFiles(input->canReceiveDroppedFiles())
 {
 }
diff --git a/Source/core/rendering/RenderFileUploadControl.h b/Source/core/rendering/RenderFileUploadControl.h
index 3a9e343..acc9713 100644
--- a/Source/core/rendering/RenderFileUploadControl.h
+++ b/Source/core/rendering/RenderFileUploadControl.h
@@ -21,7 +21,7 @@
 #ifndef RenderFileUploadControl_h
 #define RenderFileUploadControl_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
@@ -31,7 +31,7 @@
 // sufficient space to draw a file icon and filename. The RenderButton has a shadow node
 // associated with it to receive click/hover events.
 
-class RenderFileUploadControl FINAL : public RenderBlock {
+class RenderFileUploadControl FINAL : public RenderBlockFlow {
 public:
     RenderFileUploadControl(HTMLInputElement*);
     virtual ~RenderFileUploadControl();
@@ -52,6 +52,8 @@
 
     virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     int maxFilenameWidth() const;
 
     virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE FINAL;
diff --git a/Source/core/rendering/RenderFlexibleBox.cpp b/Source/core/rendering/RenderFlexibleBox.cpp
index 0dbf969..65f35a4 100644
--- a/Source/core/rendering/RenderFlexibleBox.cpp
+++ b/Source/core/rendering/RenderFlexibleBox.cpp
@@ -325,7 +325,7 @@
 void RenderFlexibleBox::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
-        paintChild(child, paintInfo, paintOffset);
+        paintChildAsInlineBlock(child, paintInfo, paintOffset);
 }
 
 void RenderFlexibleBox::repositionLogicalHeightDependentFlexItems(Vector<LineContext>& lineContexts)
@@ -455,9 +455,8 @@
         return child->computeContentLogicalHeight(size, child->logicalHeight() - child->borderAndPaddingLogicalHeight());
     }
     // FIXME: Figure out how this should work for regions and pass in the appropriate values.
-    LayoutUnit offsetFromLogicalTopOfFirstPage = 0;
     RenderRegion* region = 0;
-    return child->computeLogicalWidthInRegionUsing(sizeType, size, contentLogicalWidth(), this, region, offsetFromLogicalTopOfFirstPage) - child->borderAndPaddingLogicalWidth();
+    return child->computeLogicalWidthInRegionUsing(sizeType, size, contentLogicalWidth(), this, region) - child->borderAndPaddingLogicalWidth();
 }
 
 WritingMode RenderFlexibleBox::transformedWritingMode() const
diff --git a/Source/core/rendering/RenderFlexibleBox.h b/Source/core/rendering/RenderFlexibleBox.h
index b147b24..f82a445 100644
--- a/Source/core/rendering/RenderFlexibleBox.h
+++ b/Source/core/rendering/RenderFlexibleBox.h
@@ -61,6 +61,8 @@
 protected:
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
 
 private:
diff --git a/Source/core/rendering/RenderFlowThread.cpp b/Source/core/rendering/RenderFlowThread.cpp
index 40c5e56..5b46e85 100644
--- a/Source/core/rendering/RenderFlowThread.cpp
+++ b/Source/core/rendering/RenderFlowThread.cpp
@@ -47,7 +47,7 @@
 namespace WebCore {
 
 RenderFlowThread::RenderFlowThread()
-    : RenderBlock(0)
+    : RenderBlockFlow(0)
     , m_previousRegionCount(0)
     , m_autoLogicalHeightRegionsCount(0)
     , m_regionsInvalidated(false)
@@ -207,7 +207,7 @@
     m_needsTwoPhasesLayout = !inConstrainedLayoutPhase() && hasAutoLogicalHeightRegions();
 
     CurrentRenderFlowThreadMaintainer currentFlowThreadSetter(this);
-    RenderBlock::layout();
+    RenderBlockFlow::layout();
 
     m_pageLogicalSizeChanged = false;
 
@@ -434,7 +434,7 @@
         if (wasComputedRelativeToOtherRegion) {
             if (boxModelObject.isBox()) {
                 // Use borderBoxRectInRegion to account for variations such as percentage margins.
-                LayoutRect borderBoxRect = toRenderBox(&boxModelObject)->borderBoxRectInRegion(startRegion, 0, RenderBox::DoNotCacheRenderBoxRegionInfo);
+                LayoutRect borderBoxRect = toRenderBox(&boxModelObject)->borderBoxRectInRegion(startRegion, RenderBox::DoNotCacheRenderBoxRegionInfo);
                 referencePoint.move(borderBoxRect.location().x(), 0);
             }
 
@@ -571,7 +571,7 @@
     m_regionRangeMap.remove(box);
 }
 
-bool RenderFlowThread::logicalWidthChangedInRegions(const RenderBlock* block, LayoutUnit offsetFromLogicalTopOfFirstPage)
+bool RenderFlowThread::logicalWidthChangedInRegionsForBlock(const RenderBlock* block)
 {
     if (!hasRegions())
         return false;
@@ -597,7 +597,7 @@
             continue;
 
         LayoutUnit oldLogicalWidth = oldInfo->logicalWidth();
-        RenderBoxRegionInfo* newInfo = block->renderBoxRegionInfo(region, offsetFromLogicalTopOfFirstPage);
+        RenderBoxRegionInfo* newInfo = block->renderBoxRegionInfo(region);
         if (!newInfo || newInfo->logicalWidth() != oldLogicalWidth)
             return true;
 
@@ -1006,6 +1006,106 @@
     return result;
 }
 
+bool RenderFlowThread::cachedOffsetFromLogicalTopOfFirstRegion(const RenderBox* box, LayoutUnit& result) const
+{
+    RenderBoxToOffsetMap::const_iterator offsetIterator = m_boxesToOffsetMap.find(box);
+    if (offsetIterator == m_boxesToOffsetMap.end())
+        return false;
+
+    result = offsetIterator->value;
+    return true;
+}
+
+void RenderFlowThread::setOffsetFromLogicalTopOfFirstRegion(const RenderBox* box, LayoutUnit offset)
+{
+    m_boxesToOffsetMap.set(box, offset);
+}
+
+void RenderFlowThread::clearOffsetFromLogicalTopOfFirstRegion(const RenderBox* box)
+{
+    ASSERT(m_boxesToOffsetMap.contains(box));
+    m_boxesToOffsetMap.remove(box);
+}
+
+const RenderBox* RenderFlowThread::currentStatePusherRenderBox() const
+{
+    const RenderObject* currentObject = m_statePusherObjectsStack.isEmpty() ? 0 : m_statePusherObjectsStack.last();
+    if (currentObject && currentObject->isBox())
+        return toRenderBox(currentObject);
+
+    return 0;
+}
+
+void RenderFlowThread::pushFlowThreadLayoutState(const RenderObject* object)
+{
+    if (const RenderBox* currentBoxDescendant = currentStatePusherRenderBox()) {
+        LayoutState* layoutState = currentBoxDescendant->view()->layoutState();
+        if (layoutState && layoutState->isPaginated()) {
+            ASSERT(layoutState->renderer() == currentBoxDescendant);
+            LayoutSize offsetDelta = layoutState->m_layoutOffset - layoutState->m_pageOffset;
+            setOffsetFromLogicalTopOfFirstRegion(currentBoxDescendant, currentBoxDescendant->isHorizontalWritingMode() ? offsetDelta.height() : offsetDelta.width());
+        }
+    }
+
+    m_statePusherObjectsStack.add(object);
+}
+
+void RenderFlowThread::popFlowThreadLayoutState()
+{
+    m_statePusherObjectsStack.removeLast();
+
+    if (const RenderBox* currentBoxDescendant = currentStatePusherRenderBox()) {
+        LayoutState* layoutState = currentBoxDescendant->view()->layoutState();
+        if (layoutState && layoutState->isPaginated())
+            clearOffsetFromLogicalTopOfFirstRegion(currentBoxDescendant);
+    }
+}
+
+LayoutUnit RenderFlowThread::offsetFromLogicalTopOfFirstRegion(const RenderBlock* currentBlock) const
+{
+    // First check if we cached the offset for the block if it's an ancestor containing block of the box
+    // being currently laid out.
+    LayoutUnit offset;
+    if (cachedOffsetFromLogicalTopOfFirstRegion(currentBlock, offset))
+        return offset;
+
+    // If it's the current box being laid out, use the layout state.
+    const RenderBox* currentBoxDescendant = currentStatePusherRenderBox();
+    if (currentBlock == currentBoxDescendant) {
+        LayoutState* layoutState = view()->layoutState();
+        ASSERT(layoutState->renderer() == currentBlock);
+        ASSERT(layoutState && layoutState->isPaginated());
+        LayoutSize offsetDelta = layoutState->m_layoutOffset - layoutState->m_pageOffset;
+        return currentBoxDescendant->isHorizontalWritingMode() ? offsetDelta.height() : offsetDelta.width();
+    }
+
+    // As a last resort, take the slow path.
+    LayoutRect blockRect(0, 0, currentBlock->width(), currentBlock->height());
+    while (currentBlock && !currentBlock->isRenderFlowThread()) {
+        RenderBlock* containerBlock = currentBlock->containingBlock();
+        ASSERT(containerBlock);
+        if (!containerBlock)
+            return 0;
+        LayoutPoint currentBlockLocation = currentBlock->location();
+
+        if (containerBlock->style()->writingMode() != currentBlock->style()->writingMode()) {
+            // We have to put the block rect in container coordinates
+            // and we have to take into account both the container and current block flipping modes
+            if (containerBlock->style()->isFlippedBlocksWritingMode()) {
+                if (containerBlock->isHorizontalWritingMode())
+                    blockRect.setY(currentBlock->height() - blockRect.maxY());
+                else
+                    blockRect.setX(currentBlock->width() - blockRect.maxX());
+            }
+            currentBlock->flipForWritingMode(blockRect);
+        }
+        blockRect.moveBy(currentBlockLocation);
+        currentBlock = containerBlock;
+    }
+
+    return currentBlock->isHorizontalWritingMode() ? blockRect.y() : blockRect.x();
+}
+
 void RenderFlowThread::RegionSearchAdapter::collectIfNeeded(const RegionInterval& interval)
 {
     if (m_result)
diff --git a/Source/core/rendering/RenderFlowThread.h b/Source/core/rendering/RenderFlowThread.h
index 3da1907..c610604 100644
--- a/Source/core/rendering/RenderFlowThread.h
+++ b/Source/core/rendering/RenderFlowThread.h
@@ -31,7 +31,7 @@
 #define RenderFlowThread_h
 
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "wtf/HashCountedSet.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/PassRefPtr.h"
@@ -53,7 +53,7 @@
 // and nodeAtPoint methods to this object. Each RenderRegion will actually be a viewPort
 // of the RenderFlowThread.
 
-class RenderFlowThread: public RenderBlock {
+class RenderFlowThread: public RenderBlockFlow {
 public:
     RenderFlowThread();
     virtual ~RenderFlowThread() { };
@@ -121,7 +121,7 @@
     RenderRegion* mapFromFlowToRegion(TransformState&) const;
 
     void removeRenderBoxRegionInfo(RenderBox*);
-    bool logicalWidthChangedInRegions(const RenderBlock*, LayoutUnit offsetFromLogicalTopOfFirstPage);
+    bool logicalWidthChangedInRegionsForBlock(const RenderBlock*);
 
     LayoutUnit contentLogicalWidthOfFirstRegion() const;
     LayoutUnit contentLogicalHeightOfFirstRegion() const;
@@ -167,6 +167,10 @@
     bool needsTwoPhasesLayout() const { return m_needsTwoPhasesLayout; }
     void clearNeedsTwoPhasesLayout() { m_needsTwoPhasesLayout = false; }
 
+    void pushFlowThreadLayoutState(const RenderObject*);
+    void popFlowThreadLayoutState();
+    LayoutUnit offsetFromLogicalTopOfFirstRegion(const RenderBlock*) const;
+
 protected:
     virtual const char* renderName() const = 0;
 
@@ -196,6 +200,12 @@
 
     virtual void autoGenerateRegionsToBlockOffset(LayoutUnit) { };
 
+    bool cachedOffsetFromLogicalTopOfFirstRegion(const RenderBox*, LayoutUnit&) const;
+    void setOffsetFromLogicalTopOfFirstRegion(const RenderBox*, LayoutUnit);
+    void clearOffsetFromLogicalTopOfFirstRegion(const RenderBox*);
+
+    const RenderBox* currentStatePusherRenderBox() const;
+
     RenderRegionList m_regionList;
     unsigned short m_previousRegionCount;
 
@@ -255,6 +265,13 @@
     RenderObjectToRegionMap m_breakBeforeToRegionMap;
     RenderObjectToRegionMap m_breakAfterToRegionMap;
 
+    // Stack of objects that pushed a LayoutState object on the RenderView. The
+    // objects on the stack are the ones that are curently in the process of being
+    // laid out.
+    ListHashSet<const RenderObject*> m_statePusherObjectsStack;
+    typedef HashMap<const RenderBox*, LayoutUnit> RenderBoxToOffsetMap;
+    RenderBoxToOffsetMap m_boxesToOffsetMap;
+
     unsigned m_autoLogicalHeightRegionsCount;
 
     RegionIntervalTree m_regionIntervalTree;
@@ -268,6 +285,10 @@
     bool m_pageLogicalSizeChanged : 1;
     bool m_inConstrainedLayoutPhase : 1;
     bool m_needsTwoPhasesLayout : 1;
+
+private:
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
 };
 
 inline RenderFlowThread* toRenderFlowThread(RenderObject* object)
diff --git a/Source/core/rendering/RenderFrame.cpp b/Source/core/rendering/RenderFrame.cpp
index 32ff5fe..c67bd0a 100644
--- a/Source/core/rendering/RenderFrame.cpp
+++ b/Source/core/rendering/RenderFrame.cpp
@@ -37,7 +37,7 @@
 
 FrameEdgeInfo RenderFrame::edgeInfo() const
 {
-    HTMLFrameElement* element = static_cast<HTMLFrameElement*>(node());
+    HTMLFrameElement* element = toHTMLFrameElement(node());
     return FrameEdgeInfo(element->noResize(), element->hasFrameBorder());
 }
 
@@ -49,7 +49,7 @@
 
 void RenderFrame::viewCleared()
 {
-    HTMLFrameElement* element = static_cast<HTMLFrameElement*>(node());
+    HTMLFrameElement* element = toHTMLFrameElement(node());
     if (!element || !widget() || !widget()->isFrameView())
         return;
 
diff --git a/Source/core/rendering/RenderFrameSet.cpp b/Source/core/rendering/RenderFrameSet.cpp
index e0a7de7..86748fb 100644
--- a/Source/core/rendering/RenderFrameSet.cpp
+++ b/Source/core/rendering/RenderFrameSet.cpp
@@ -447,7 +447,7 @@
         oldBounds = clippedOverflowRectForRepaint(repaintContainer);
     }
 
-    if (!parent()->isFrameSet() && !document()->printing()) {
+    if (!parent()->isFrameSet() && !document().printing()) {
         setWidth(view()->viewWidth());
         setHeight(view()->viewHeight());
     }
@@ -482,6 +482,16 @@
     clearNeedsLayout();
 }
 
+static void clearNeedsLayoutOnHiddenFrames(RenderBox* frame)
+{
+    for (; frame; frame = frame->nextSiblingBox()) {
+        frame->setWidth(0);
+        frame->setHeight(0);
+        frame->clearNeedsLayout();
+        clearNeedsLayoutOnHiddenFrames(frame->firstChildBox());
+    }
+}
+
 void RenderFrameSet::positionFrames()
 {
     RenderBox* child = firstChildBox();
@@ -517,12 +527,8 @@
         yPos += height + borderThickness;
     }
 
-    // all the remaining frames are hidden to avoid ugly spurious unflowed frames
-    for (; child; child = child->nextSiblingBox()) {
-        child->setWidth(0);
-        child->setHeight(0);
-        child->clearNeedsLayout();
-    }
+    // All the remaining frames are hidden to avoid ugly spurious unflowed frames.
+    clearNeedsLayoutOnHiddenFrames(child);
 }
 
 void RenderFrameSet::startResizing(GridAxis& axis, int position)
diff --git a/Source/core/rendering/RenderFullScreen.cpp b/Source/core/rendering/RenderFullScreen.cpp
index b98c229..23fa992 100644
--- a/Source/core/rendering/RenderFullScreen.cpp
+++ b/Source/core/rendering/RenderFullScreen.cpp
@@ -26,19 +26,21 @@
 #include "core/rendering/RenderFullScreen.h"
 
 #include "core/dom/FullscreenElementStack.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 using namespace WebCore;
 
-class RenderFullScreenPlaceholder FINAL : public RenderBlock {
+class RenderFullScreenPlaceholder FINAL : public RenderBlockFlow {
 public:
     RenderFullScreenPlaceholder(RenderFullScreen* owner)
-        : RenderBlock(0)
+        : RenderBlockFlow(0)
         , m_owner(owner)
     {
-        setDocumentForAnonymous(owner->document());
+        setDocumentForAnonymous(&owner->document());
     }
 private:
     virtual bool isRenderFullScreenPlaceholder() const { return true; }
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual void willBeDestroyed();
     RenderFullScreen* m_owner;
 };
@@ -74,11 +76,9 @@
 
     // RenderObjects are unretained, so notify the document (which holds a pointer to a RenderFullScreen)
     // if it's RenderFullScreen is destroyed.
-    if (document()) {
-        FullscreenElementStack* controller = FullscreenElementStack::from(document());
-        if (controller->fullScreenRenderer() == this)
-            controller->fullScreenRendererDestroyed();
-    }
+    FullscreenElementStack* controller = FullscreenElementStack::from(&document());
+    if (controller->fullScreenRenderer() == this)
+        controller->fullScreenRendererDestroyed();
 
     RenderFlexibleBox::willBeDestroyed();
 }
@@ -162,7 +162,7 @@
     if (placeholder())
         placeholder()->remove();
     remove();
-    FullscreenElementStack::from(document())->setFullScreenRenderer(0);
+    FullscreenElementStack::from(&document())->setFullScreenRenderer(0);
 }
 
 void RenderFullScreen::setPlaceholder(RenderBlock* placeholder)
diff --git a/Source/core/rendering/RenderFullScreen.h b/Source/core/rendering/RenderFullScreen.h
index 66fbde6..65665d3 100644
--- a/Source/core/rendering/RenderFullScreen.h
+++ b/Source/core/rendering/RenderFullScreen.h
@@ -47,6 +47,7 @@
 
 private:
     RenderFullScreen();
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual void willBeDestroyed();
 
 protected:
diff --git a/Source/core/rendering/RenderGrid.cpp b/Source/core/rendering/RenderGrid.cpp
index cd2d268..4744fa6 100644
--- a/Source/core/rendering/RenderGrid.cpp
+++ b/Source/core/rendering/RenderGrid.cpp
@@ -870,7 +870,7 @@
         LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, rowTracks);
 
         SubtreeLayoutScope layoutScope(child);
-        if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight)
+        if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (child->hasRelativeLogicalHeight() && oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight))
             layoutScope.setNeedsLayout(child);
 
         child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
diff --git a/Source/core/rendering/RenderGrid.h b/Source/core/rendering/RenderGrid.h
index 5fea205..cc76159 100644
--- a/Source/core/rendering/RenderGrid.h
+++ b/Source/core/rendering/RenderGrid.h
@@ -92,6 +92,8 @@
 
     void layoutGridItems();
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     typedef LayoutUnit (RenderGrid::* SizingFunction)(RenderBox*, TrackSizingDirection, Vector<GridTrack>&);
     typedef LayoutUnit (GridTrack::* AccumulatorGetter)() const;
     typedef void (GridTrack::* AccumulatorGrowFunction)(LayoutUnit);
diff --git a/Source/core/rendering/RenderIFrame.cpp b/Source/core/rendering/RenderIFrame.cpp
index ffb8f5f..c632870 100644
--- a/Source/core/rendering/RenderIFrame.cpp
+++ b/Source/core/rendering/RenderIFrame.cpp
@@ -91,7 +91,7 @@
     // FIXME: Is this always a valid cast? What about plugins?
     ASSERT(!widget() || widget()->isFrameView());
     FrameView* childFrameView = toFrameView(widget());
-    return childFrameView ? childFrameView->frame()->contentRenderer() : 0;
+    return childFrameView ? childFrameView->frame().contentRenderer() : 0;
 }
 
 void RenderIFrame::layoutSeamlessly()
@@ -114,7 +114,7 @@
     updateWidgetPosition(); // Notify the Widget of our final height.
 
     // Assert that the child document did a complete layout.
-    RenderView* childRoot = childFrameView ? childFrameView->frame()->contentRenderer() : 0;
+    RenderView* childRoot = childFrameView ? childFrameView->frame().contentRenderer() : 0;
     ASSERT(!childFrameView || !childFrameView->layoutPending());
     ASSERT_UNUSED(childRoot, !childRoot || !childRoot->needsLayout());
 }
diff --git a/Source/core/rendering/RenderImage.cpp b/Source/core/rendering/RenderImage.cpp
index 084e5b4..e622c9c 100644
--- a/Source/core/rendering/RenderImage.cpp
+++ b/Source/core/rendering/RenderImage.cpp
@@ -35,6 +35,7 @@
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLMapElement.h"
+#include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/graphics/Font.h"
@@ -172,7 +173,7 @@
 
     // Set image dimensions, taking into account the size of the alt text.
     if (m_imageResource->errorOccurred() || !newImage) {
-        if (!m_altText.isEmpty() && document()->hasPendingStyleRecalc()) {
+        if (!m_altText.isEmpty() && document().hasPendingStyleRecalc()) {
             ASSERT(node());
             if (node()) {
                 m_needsToSetSizeForAltText = true;
@@ -251,9 +252,6 @@
             // (unless the box has already been scheduled for layout). In order to calculate it, we
             // may need values from the containing block, though, so make sure that we're not too
             // early. It may be that layout hasn't even taken place once yet.
-
-            // FIXME: we should not have to trigger another call to setContainerSizeForRenderer()
-            // from here, since it's already being done during layout (crbug.com/275755).
             updateInnerContentRect();
         }
     }
@@ -353,7 +351,7 @@
             }
 
             if (!m_altText.isEmpty()) {
-                String text = document()->displayStringModifiedByEncoding(m_altText);
+                String text = document().displayStringModifiedByEncoding(m_altText);
                 const Font& font = style()->font();
                 const FontMetrics& fontMetrics = font.fontMetrics();
                 LayoutUnit ascent = fontMetrics.ascent();
@@ -420,15 +418,15 @@
 
 void RenderImage::paintAreaElementFocusRing(PaintInfo& paintInfo)
 {
-    Document* document = this->document();
+    Document& document = this->document();
 
-    if (document->printing() || !document->frame()->selection()->isFocusedAndActive())
+    if (document.printing() || !document.frame()->selection().isFocusedAndActive())
         return;
 
     if (paintInfo.context->paintingDisabled() && !paintInfo.context->updatingControlTints())
         return;
 
-    Element* focusedElement = document->focusedElement();
+    Element* focusedElement = document.focusedElement();
     if (!focusedElement || !isHTMLAreaElement(focusedElement))
         return;
 
@@ -489,7 +487,10 @@
     CompositeOperator compositeOperator = imageElt ? imageElt->compositeOperator() : CompositeSourceOver;
     Image* image = m_imageResource->image().get();
     bool useLowQualityScaling = shouldPaintAtLowQuality(context, image, image, alignedRect.size());
+
+    InspectorInstrumentation::willPaintImage(this);
     context->drawImage(m_imageResource->image(alignedRect.width(), alignedRect.height()).get(), alignedRect, compositeOperator, shouldRespectImageOrientation(), useLowQualityScaling);
+    InspectorInstrumentation::didPaintImage(this);
 }
 
 bool RenderImage::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox*) const
@@ -539,7 +540,7 @@
 HTMLMapElement* RenderImage::imageMap() const
 {
     HTMLImageElement* i = node() && node()->hasTagName(imgTag) ? toHTMLImageElement(node()) : 0;
-    return i ? i->treeScope()->getImageMap(i->fastGetAttribute(usemapAttr)) : 0;
+    return i ? i->treeScope().getImageMap(i->fastGetAttribute(usemapAttr)) : 0;
 }
 
 bool RenderImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
@@ -617,7 +618,7 @@
 
     ImageResource* cachedImage = m_imageResource->cachedImage();
     if (cachedImage && cachedImage->image() && cachedImage->image()->isSVGImage())
-        return static_cast<SVGImage*>(cachedImage->image())->embeddedContentBox();
+        return toSVGImage(cachedImage->image())->embeddedContentBox();
 
     return 0;
 }
diff --git a/Source/core/rendering/RenderInline.cpp b/Source/core/rendering/RenderInline.cpp
index 101fdf7..e57e0b8 100644
--- a/Source/core/rendering/RenderInline.cpp
+++ b/Source/core/rendering/RenderInline.cpp
@@ -25,7 +25,6 @@
 
 #include "core/dom/FullscreenElementStack.h"
 #include "core/page/Chrome.h"
-#include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/GraphicsContext.h"
@@ -207,7 +206,7 @@
 
     RenderStyle* parentStyle = parent()->style();
     RenderInline* parentRenderInline = parent()->isRenderInline() ? toRenderInline(parent()) : 0;
-    bool checkFonts = document()->inNoQuirksMode();
+    bool checkFonts = document().inNoQuirksMode();
     RenderFlowThread* flowThread = flowThreadContainingBlock();
     bool alwaysCreateLineBoxes = (parentRenderInline && parentRenderInline->alwaysCreateLineBoxes())
         || (parentRenderInline && parentStyle->verticalAlign() != BASELINE)
@@ -217,7 +216,7 @@
         || parentStyle->lineHeight() != style()->lineHeight()))
         || (flowThread && flowThread->hasRegionsWithStyling());
 
-    if (!alwaysCreateLineBoxes && checkFonts && document()->styleSheetCollections()->usesFirstLineRules()) {
+    if (!alwaysCreateLineBoxes && checkFonts && document().styleSheetCollections()->usesFirstLineRules()) {
         // Have to check the first line style as well.
         parentStyle = parent()->style(true);
         RenderStyle* childStyle = style(true);
@@ -314,7 +313,7 @@
         if (RenderObject* positionedAncestor = inFlowPositionedInlineAncestor(this))
             newStyle->setPosition(positionedAncestor->style()->position());
 
-        RenderBlock* newBox = RenderBlock::createAnonymous(document());
+        RenderBlock* newBox = RenderBlock::createAnonymous(&document());
         newBox->setStyle(newStyle.release());
         RenderBoxModelObject* oldContinuation = continuation();
         setContinuation(newBox);
@@ -349,7 +348,7 @@
     // that renderer is wrapped in a RenderFullScreen, so |this| is not its
     // parent. Since the splitting logic expects |this| to be the parent, set
     // |beforeChild| to be the RenderFullScreen.
-    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(document())) {
+    if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(&document())) {
         const Element* fullScreenElement = fullscreen->webkitCurrentFullScreenElement();
         if (fullScreenElement && beforeChild && beforeChild->node() == fullScreenElement)
             beforeChild = fullscreen->fullScreenRenderer();
@@ -1083,7 +1082,7 @@
 
     LayoutPoint topLeft = rect.location();
 
-    if (o->isBlockFlow() && !style()->hasOutOfFlowPosition()) {
+    if (o->isRenderBlockFlow() && !style()->hasOutOfFlowPosition()) {
         RenderBlock* cb = toRenderBlock(o);
         if (cb->hasColumns()) {
             LayoutRect repaintRect(topLeft, rect.size());
@@ -1288,7 +1287,7 @@
 
 LayoutUnit RenderInline::lineHeight(bool firstLine, LineDirectionMode /*direction*/, LinePositionMode /*linePositionMode*/) const
 {
-    if (firstLine && document()->styleSheetCollections()->usesFirstLineRules()) {
+    if (firstLine && document().styleSheetCollections()->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 20a5ddf..921ed7a 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -52,10 +52,8 @@
 #include "core/dom/Document.h"
 #include "core/dom/DocumentEventQueue.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/FrameSelection.h"
 #include "core/html/HTMLFrameElement.h"
 #include "core/html/HTMLFrameOwnerElement.h"
-#include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FocusController.h"
 #include "core/page/Frame.h"
@@ -125,7 +123,6 @@
 
 RenderLayer::RenderLayer(RenderLayerModelObject* renderer)
     : m_inResizeMode(false)
-    , m_scrollDimensionsDirty(true)
     , m_normalFlowListDirty(true)
     , m_hasSelfPaintingLayerDescendant(false)
     , m_hasSelfPaintingLayerDescendantDirty(false)
@@ -134,6 +131,9 @@
     , m_hasUnclippedDescendant(false)
     , m_isUnclippedDescendant(false)
     , m_needsCompositedScrolling(false)
+    , m_needsCompositedScrollingHasBeenRecorded(false)
+    , m_willUseCompositedScrollingHasBeenRecorded(false)
+    , m_isScrollableAreaHasBeenRecorded(false)
     , m_canBePromotedToStackingContainer(false)
     , m_canBePromotedToStackingContainerDirty(true)
     , m_isRootLayer(renderer->isRenderView())
@@ -473,7 +473,7 @@
 
 bool RenderLayer::acceleratedCompositingForOverflowScrollEnabled() const
 {
-    const Settings* settings = renderer()->document()->settings();
+    const Settings* settings = renderer()->document().settings();
     return settings && settings->acceleratedCompositingForOverflowScrollEnabled();
 }
 
@@ -484,7 +484,7 @@
     if (!acceleratedCompositingForOverflowScrollEnabled())
         return false;
 
-    const Settings* settings = renderer()->document()->settings();
+    const Settings* settings = renderer()->document().settings();
     return settings && settings->isCompositorDrivenAcceleratedScrollingEnabled();
 }
 
@@ -938,7 +938,7 @@
 
 bool RenderLayer::useRegionBasedColumns() const
 {
-    const Settings* settings = renderer()->document()->settings();
+    const Settings* settings = renderer()->document().settings();
     return settings && settings->regionBasedColumnsEnabled();
 }
 
@@ -1363,9 +1363,9 @@
 
 RenderLayer* RenderLayer::enclosingScrollableLayer() const
 {
-    for (RenderObject* nextRenderer = renderer()->parent(); nextRenderer; nextRenderer = nextRenderer->parent()) {
-        if (nextRenderer->isBox() && toRenderBox(nextRenderer)->canBeScrolledAndHasScrollableArea())
-            return nextRenderer->enclosingLayer();
+    for (RenderLayer* nextLayer = parent(); nextLayer; nextLayer = nextLayer->parent()) {
+        if (nextLayer->renderer()->isBox() && toRenderBox(nextLayer->renderer())->canBeScrolledAndHasScrollableArea())
+            return nextLayer;
     }
 
     return 0;
@@ -1389,6 +1389,11 @@
     return (overflowStyle == OSCROLL || overflowStyle == OAUTO || overflowStyle == OOVERLAY);
 }
 
+bool RenderLayer::shouldPlaceVerticalScrollbarOnLeft() const
+{
+    return renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft();
+}
+
 int RenderLayer::pageStep(ScrollbarOrientation orientation) const
 {
     RenderBox* box = renderBox();
@@ -2084,11 +2089,40 @@
     setNeedsCompositedScrolling(needsCompositedScrolling);
 }
 
+enum CompositedScrollingHistogramBuckets {
+    IsScrollableAreaBucket = 0,
+    NeedsToBeStackingContainerBucket = 1,
+    WillUseCompositedScrollingBucket = 2,
+    CompositedScrollingHistogramMax = 3
+};
+
 void RenderLayer::setNeedsCompositedScrolling(bool needsCompositedScrolling)
 {
     if (m_needsCompositedScrolling == needsCompositedScrolling)
         return;
 
+    // Count the total number of RenderLayers which need to be stacking
+    // containers some point. This should be recorded at most once per
+    // RenderLayer, so we check m_needsCompositedScrollingHasBeenRecorded.
+    if (acceleratedCompositingForOverflowScrollEnabled() && !m_needsCompositedScrollingHasBeenRecorded) {
+        HistogramSupport::histogramEnumeration("Renderer.CompositedScrolling", NeedsToBeStackingContainerBucket, CompositedScrollingHistogramMax);
+        m_needsCompositedScrollingHasBeenRecorded = true;
+    }
+
+    // Count the total number of RenderLayers which need composited scrolling at
+    // some point. This should be recorded at most once per RenderLayer, so we
+    // check m_willUseCompositedScrollingHasBeenRecorded.
+    //
+    // FIXME: Currently, this computes the exact same value as the above.
+    // However, it will soon be expanded to cover more than just stacking
+    // containers (see crbug.com/249354). When this happens, we should see a
+    // spike in "WillUseCompositedScrolling", while "NeedsToBeStackingContainer"
+    // will remain relatively static.
+    if (acceleratedCompositingForOverflowScrollEnabled() && !m_willUseCompositedScrollingHasBeenRecorded) {
+        HistogramSupport::histogramEnumeration("Renderer.CompositedScrolling", WillUseCompositedScrollingBucket, CompositedScrollingHistogramMax);
+        m_willUseCompositedScrollingHasBeenRecorded = true;
+    }
+
     m_needsCompositedScrolling = needsCompositedScrolling;
 
     // Note, the z-order lists may need to be rebuilt, but our code guarantees
@@ -2178,7 +2212,7 @@
 
     if (renderer()->hasOverflowClip() && !restrictedByLineClamp) {
         IntSize newScrollOffset = adjustedScrollOffset() + delta;
-        scrollToOffset(newScrollOffset, clamp);
+        m_scrollableArea->scrollToOffset(newScrollOffset, clamp);
 
         // If this layer can't do the scroll we ask the next layer up that can scroll to try
         IntSize remainingScrollOffset = newScrollOffset - adjustedScrollOffset();
@@ -2200,90 +2234,9 @@
     }
 }
 
-IntSize RenderLayer::clampScrollOffset(const IntSize& scrollOffset) const
-{
-    RenderBox* box = renderBox();
-    ASSERT(box);
-
-    int maxX = scrollWidth() - box->pixelSnappedClientWidth();
-    int maxY = scrollHeight() - box->pixelSnappedClientHeight();
-
-    int x = max(min(scrollOffset.width(), maxX), 0);
-    int y = max(min(scrollOffset.height(), maxY), 0);
-    return IntSize(x, y);
-}
-
 void RenderLayer::scrollToOffset(const IntSize& scrollOffset, ScrollOffsetClamping clamp)
 {
-    IntSize newScrollOffset = clamp == ScrollOffsetClamped ? clampScrollOffset(scrollOffset) : scrollOffset;
-    if (newScrollOffset != adjustedScrollOffset())
-        m_scrollableArea->scrollToOffsetWithoutAnimation(-scrollOrigin() + newScrollOffset);
-}
-
-void RenderLayer::setScrollOffset(const IntPoint& newScrollOffset)
-{
-    RenderBox* box = renderBox();
-    if (!box)
-        return;
-
-    if (!box->isMarquee()) {
-        // Ensure that the dimensions will be computed if they need to be (for overflow:hidden blocks).
-        if (m_scrollDimensionsDirty)
-            computeScrollDimensions();
-    }
-
-    if (m_scrollableArea->scrollOffset() == toIntSize(newScrollOffset))
-        return;
-    m_scrollableArea->setScrollOffset(toIntSize(newScrollOffset));
-
-    Frame* frame = renderer()->frame();
-    InspectorInstrumentation::willScrollLayer(renderer());
-
-    RenderView* view = renderer()->view();
-
-    // We should have a RenderView if we're trying to scroll.
-    ASSERT(view);
-
-    // Update the positions of our child layers (if needed as only fixed layers should be impacted by a scroll).
-    // We don't update compositing layers, because we need to do a deep update from the compositing ancestor.
-    bool inLayout = view ? view->frameView()->isInLayout() : false;
-    if (!inLayout) {
-        // If we're in the middle of layout, we'll just update layers once layout has finished.
-        updateLayerPositionsAfterOverflowScroll();
-        if (view) {
-            // Update regions, scrolling may change the clip of a particular region.
-            view->frameView()->updateAnnotatedRegions();
-            view->updateWidgetPositions();
-        }
-
-        updateCompositingLayersAfterScroll();
-    }
-
-    RenderLayerModelObject* repaintContainer = renderer()->containerForRepaint();
-    if (frame) {
-        // The caret rect needs to be invalidated after scrolling
-        frame->selection()->setCaretRectNeedsUpdate();
-
-        FloatQuad quadForFakeMouseMoveEvent = FloatQuad(m_repaintRect);
-        if (repaintContainer)
-            quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
-        frame->eventHandler()->dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
-    }
-
-    bool requiresRepaint = true;
-
-    if (compositor()->inCompositingMode() && usesCompositedScrolling())
-        requiresRepaint = false;
-
-    // Just schedule a full repaint of our object.
-    if (view && requiresRepaint)
-        renderer()->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_repaintRect));
-
-    // Schedule the scroll DOM event.
-    if (renderer()->node())
-        renderer()->node()->document()->eventQueue()->enqueueOrDispatchScrollEvent(renderer()->node(), DocumentEventQueue::ScrollEventElementTarget);
-
-    InspectorInstrumentation::didScrollLayer(renderer());
+    m_scrollableArea->scrollToOffset(scrollOffset, clamp);
 }
 
 static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView)
@@ -2298,7 +2251,7 @@
 
     // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
     // like navigation to an anchor.
-    Page* page = frameView->frame()->page();
+    Page* page = frameView->frame().page();
     if (!page)
         return false;
     return !page->autoscrollInProgress();
@@ -2311,7 +2264,7 @@
 
     // We may end up propagating a scroll event. It is important that we suspend events until
     // the end of the function since they could delete the layer or the layer's renderer().
-    FrameView* frameView = renderer()->document()->view();
+    FrameView* frameView = renderer()->document().view();
     if (frameView)
         frameView->pauseScheduledEvents();
 
@@ -2330,19 +2283,17 @@
         LayoutRect layerBounds(0, 0, box->clientWidth(), box->clientHeight());
         LayoutRect r = getRectToExpose(layerBounds, localExposeRect, alignX, alignY);
 
-        IntSize clampedScrollOffset = clampScrollOffset(adjustedScrollOffset() + toIntSize(roundedIntRect(r).location()));
+        IntSize clampedScrollOffset = m_scrollableArea->clampScrollOffset(adjustedScrollOffset() + toIntSize(roundedIntRect(r).location()));
         if (clampedScrollOffset != adjustedScrollOffset()) {
             IntSize oldScrollOffset = adjustedScrollOffset();
-            scrollToOffset(clampedScrollOffset);
+            m_scrollableArea->scrollToOffset(clampedScrollOffset);
             IntSize scrollOffsetDifference = adjustedScrollOffset() - oldScrollOffset;
             localExposeRect.move(-scrollOffsetDifference);
             newRect = LayoutRect(box->localToAbsoluteQuad(FloatQuad(FloatRect(localExposeRect)), UseTransforms).boundingBox());
         }
     } else if (!parentLayer && renderer()->isBox() && renderBox()->canBeProgramaticallyScrolled()) {
         if (frameView) {
-            Element* ownerElement = 0;
-            if (renderer()->document())
-                ownerElement = renderer()->document()->ownerElement();
+            Element* ownerElement = renderer()->document().ownerElement();
 
             if (ownerElement && ownerElement->renderer()) {
                 HTMLFrameElementBase* frameElementBase = 0;
@@ -2378,6 +2329,9 @@
         }
     }
 
+    if (renderer()->frame()->page()->autoscrollInProgress())
+        parentLayer = enclosingScrollableLayer();
+
     if (parentLayer)
         parentLayer->scrollRectToVisible(newRect, alignX, alignY);
 
@@ -2506,14 +2460,14 @@
     Element* element = toElement(renderer()->node());
     RenderBox* renderer = toRenderBox(element->renderer());
 
-    Document* document = element->document();
+    Document& document = element->document();
 
     IntPoint pos;
     const PlatformGestureEvent* gevt = 0;
 
     switch (evt.type()) {
     case PlatformEvent::MouseMoved:
-        if (!document->frame()->eventHandler()->mousePressed())
+        if (!document.frame()->eventHandler()->mousePressed())
             return;
         pos = static_cast<const PlatformMouseEvent*>(&evt)->position();
         break;
@@ -2530,7 +2484,7 @@
 
     float zoomFactor = renderer->style()->effectiveZoom();
 
-    LayoutSize newOffset = offsetFromResizeCorner(document->view()->windowToContents(pos));
+    LayoutSize newOffset = offsetFromResizeCorner(document.view()->windowToContents(pos));
     newOffset.setWidth(newOffset.width() / zoomFactor);
     newOffset.setHeight(newOffset.height() / zoomFactor);
 
@@ -2571,31 +2525,17 @@
         element->setInlineStyleProperty(CSSPropertyHeight, roundToInt(baseHeight + difference.height()), CSSPrimitiveValue::CSS_PX);
     }
 
-    document->updateLayout();
+    document.updateLayout();
 
     // FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
 }
 
 int RenderLayer::scrollSize(ScrollbarOrientation orientation) const
 {
-    IntSize scrollDimensions = maximumScrollPosition() - minimumScrollPosition();
+    IntSize scrollDimensions = scrollableArea()->maximumScrollPosition() - scrollableArea()->minimumScrollPosition();
     return (orientation == HorizontalScrollbar) ? scrollDimensions.width() : scrollDimensions.height();
 }
 
-IntPoint RenderLayer::minimumScrollPosition() const
-{
-    return -scrollOrigin();
-}
-
-IntPoint RenderLayer::maximumScrollPosition() const
-{
-    RenderBox* box = renderBox();
-    if (!box || !box->hasOverflowClip())
-        return -scrollOrigin();
-
-    return -scrollOrigin() + enclosingIntRect(m_overflowRect).size() - enclosingIntRect(box->clientBoxRect()).size();
-}
-
 IntSize RenderLayer::overhangAmount() const
 {
     return IntSize();
@@ -2735,11 +2675,6 @@
     return point;
 }
 
-IntSize RenderLayer::contentsSize() const
-{
-    return IntSize(scrollWidth(), scrollHeight());
-}
-
 int RenderLayer::visibleHeight() const
 {
     return m_layerSize.height();
@@ -2891,13 +2826,13 @@
     if (hasCustomScrollbarStyle)
         widget = RenderScrollbar::createCustomScrollbar(scrollableArea(), orientation, actualRenderer->node());
     else {
-        widget = Scrollbar::createNativeScrollbar(scrollableArea(), orientation, RegularScrollbar);
+        widget = Scrollbar::create(scrollableArea(), orientation, RegularScrollbar);
         if (orientation == HorizontalScrollbar)
             scrollableArea()->didAddHorizontalScrollbar(widget.get());
         else
             scrollableArea()->didAddVerticalScrollbar(widget.get());
     }
-    renderer()->document()->view()->addChild(widget.get());
+    renderer()->document().view()->addChild(widget.get());
     return widget.release();
 }
 
@@ -2936,8 +2871,8 @@
         m_vBar->styleChanged();
 
     // Force an update since we know the scrollbars have changed things.
-    if (renderer()->document()->hasAnnotatedRegions())
-        renderer()->document()->setAnnotatedRegionsDirty(true);
+    if (renderer()->document().hasAnnotatedRegions())
+        renderer()->document().setAnnotatedRegionsDirty(true);
 }
 
 void RenderLayer::setHasVerticalScrollbar(bool hasScrollbar)
@@ -2957,8 +2892,8 @@
         m_vBar->styleChanged();
 
     // Force an update since we know the scrollbars have changed things.
-    if (renderer()->document()->hasAnnotatedRegions())
-        renderer()->document()->setAnnotatedRegionsDirty(true);
+    if (renderer()->document().hasAnnotatedRegions())
+        renderer()->document().setAnnotatedRegionsDirty(true);
 }
 
 ScrollableArea* RenderLayer::enclosingScrollableArea() const
@@ -3037,57 +2972,12 @@
 
 int RenderLayer::scrollWidth() const
 {
-    ASSERT(renderBox());
-    if (m_scrollDimensionsDirty)
-        const_cast<RenderLayer*>(this)->computeScrollDimensions();
-    return snapSizeToPixel(m_overflowRect.width(), renderBox()->clientLeft() + renderBox()->x());
+    return m_scrollableArea->scrollWidth();
 }
 
 int RenderLayer::scrollHeight() const
 {
-    ASSERT(renderBox());
-    if (m_scrollDimensionsDirty)
-        const_cast<RenderLayer*>(this)->computeScrollDimensions();
-    return snapSizeToPixel(m_overflowRect.height(), renderBox()->clientTop() + renderBox()->y());
-}
-
-void RenderLayer::computeScrollDimensions()
-{
-    RenderBox* box = renderBox();
-    ASSERT(box);
-
-    m_scrollDimensionsDirty = false;
-
-    m_overflowRect = box->layoutOverflowRect();
-    box->flipForWritingMode(m_overflowRect);
-
-    int scrollableLeftOverflow = m_overflowRect.x() - box->borderLeft();
-    int scrollableTopOverflow = m_overflowRect.y() - box->borderTop();
-    m_scrollableArea->setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
-}
-
-bool RenderLayer::hasScrollableHorizontalOverflow() const
-{
-    return hasHorizontalOverflow() && renderBox()->scrollsOverflowX();
-}
-
-bool RenderLayer::hasScrollableVerticalOverflow() const
-{
-    return hasVerticalOverflow() && renderBox()->scrollsOverflowY();
-}
-
-bool RenderLayer::hasHorizontalOverflow() const
-{
-    ASSERT(!m_scrollDimensionsDirty);
-
-    return scrollWidth() > renderBox()->pixelSnappedClientWidth();
-}
-
-bool RenderLayer::hasVerticalOverflow() const
-{
-    ASSERT(!m_scrollDimensionsDirty);
-
-    return scrollHeight() > renderBox()->pixelSnappedClientHeight();
+    return m_scrollableArea->scrollHeight();
 }
 
 void RenderLayer::updateScrollbarsAfterLayout()
@@ -3099,8 +2989,8 @@
     if (box->style()->appearance() == ListboxPart)
         return;
 
-    bool hasHorizontalOverflow = this->hasHorizontalOverflow();
-    bool hasVerticalOverflow = this->hasVerticalOverflow();
+    bool hasHorizontalOverflow = m_scrollableArea->hasHorizontalOverflow();
+    bool hasVerticalOverflow = m_scrollableArea->hasVerticalOverflow();
 
     // overflow:scroll should just enable/disable.
     if (renderer()->style()->overflowX() == OSCROLL)
@@ -3121,8 +3011,8 @@
         updateSelfPaintingLayer();
 
         // Force an update since we know the scrollbars have changed things.
-        if (renderer()->document()->hasAnnotatedRegions())
-            renderer()->document()->setAnnotatedRegionsDirty(true);
+        if (renderer()->document().hasAnnotatedRegions())
+            renderer()->document().setAnnotatedRegionsDirty(true);
 
         renderer()->repaint();
 
@@ -3146,14 +3036,14 @@
     // Set up the range (and page step/line step).
     if (m_hBar) {
         int clientWidth = box->pixelSnappedClientWidth();
-        m_hBar->setProportion(clientWidth, m_overflowRect.width());
+        m_hBar->setProportion(clientWidth, m_scrollableArea->overflowRect().width());
     }
     if (m_vBar) {
         int clientHeight = box->pixelSnappedClientHeight();
-        m_vBar->setProportion(clientHeight, m_overflowRect.height());
+        m_vBar->setProportion(clientHeight, m_scrollableArea->overflowRect().height());
     }
 
-    updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
+    updateScrollableAreaSet(m_scrollableArea->hasScrollableHorizontalOverflow() || m_scrollableArea->hasScrollableVerticalOverflow());
 }
 
 void RenderLayer::updateScrollInfoAfterLayout()
@@ -3162,24 +3052,9 @@
     if (!box)
         return;
 
-    m_scrollDimensionsDirty = true;
-    IntSize originalScrollOffset = adjustedScrollOffset();
-
-    computeScrollDimensions();
-
-    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());
-        if (clampedScrollOffset != adjustedScrollOffset())
-            scrollToOffset(clampedScrollOffset);
-    }
-
+    m_scrollableArea->updateAfterLayout();
     updateScrollbarsAfterLayout();
 
-    if (originalScrollOffset != adjustedScrollOffset())
-        scrollableArea()->scrollToOffsetWithoutAnimation(-scrollOrigin() + adjustedScrollOffset());
-
     // Composited scrolling may need to be enabled or disabled if the amount of overflow changed.
     if (renderer()->view() && compositor()->updateLayerCompositingState(this))
         compositor()->setCompositingLayersNeedRebuild();
@@ -3524,7 +3399,7 @@
     // Avoid painting descendants of the root layer when stylesheets haven't loaded. This eliminates FOUC.
     // It's ok not to draw, because later on, when all the stylesheets do load, updateStyleSelector on the Document
     // will do a full repaint().
-    if (layer->renderer()->document()->didLayoutWithPendingStylesheets() && !layer->isRootLayer() && !layer->renderer()->isRoot())
+    if (layer->renderer()->document().didLayoutWithPendingStylesheets() && !layer->isRootLayer() && !layer->renderer()->isRoot())
         return true;
 
     return false;
@@ -3690,17 +3565,16 @@
             context->clipPath(clipPath->path(rootRelativeBounds), clipPath->windRule());
         } else if (style->clipPath()->getOperationType() == ClipPathOperation::REFERENCE) {
             ReferenceClipPathOperation* referenceClipPathOperation = static_cast<ReferenceClipPathOperation*>(style->clipPath());
-            Document* document = renderer()->document();
+            Document& document = renderer()->document();
             // FIXME: It doesn't work with forward or external SVG references (https://bugs.webkit.org/show_bug.cgi?id=90405)
-            Element* element = document ? document->getElementById(referenceClipPathOperation->fragment()) : 0;
+            Element* element = document.getElementById(referenceClipPathOperation->fragment());
             if (element && element->hasTagName(SVGNames::clipPathTag) && element->renderer()) {
                 if (!rootRelativeBoundsComputed) {
                     rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, &offsetFromRoot, 0);
                     rootRelativeBoundsComputed = true;
                 }
 
-                // FIXME: This should use a safer cast such as toRenderSVGResourceContainer().
-                resourceClipper = static_cast<RenderSVGResourceClipper*>(element->renderer());
+                resourceClipper = toRenderSVGResourceClipper(element->renderer()->toRenderSVGResourceContainer());
                 if (!resourceClipper->applyClippingToContext(renderer(), rootRelativeBounds, paintingInfo.paintDirtyRect, context)) {
                     // No need to post-apply the clipper if this failed.
                     resourceClipper = 0;
@@ -4255,7 +4129,7 @@
 
 static inline LayoutRect frameVisibleRect(RenderObject* renderer)
 {
-    FrameView* frameView = renderer->document()->view();
+    FrameView* frameView = renderer->document().view();
     if (!frameView)
         return LayoutRect();
 
@@ -4273,7 +4147,7 @@
 
     // RenderView should make sure to update layout before entering hit testing
     ASSERT(!renderer()->frame()->view()->layoutPending());
-    ASSERT(!renderer()->document()->renderer()->needsLayout());
+    ASSERT(!renderer()->document().renderer()->needsLayout());
 
     LayoutRect hitTestArea = isOutOfFlowRenderFlowThread() ? toRenderFlowThread(renderer())->borderBoxRect() : renderer()->view()->documentRect();
     if (!request.ignoreClipping())
@@ -5998,8 +5872,7 @@
         m_vBar->setEnabled(true);
     }
 
-    if (!m_scrollDimensionsDirty)
-        updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
+    m_scrollableArea->updateAfterStyleChange(oldStyle);
 }
 
 void RenderLayer::updateOutOfFlowPositioned(const RenderStyle* oldStyle)
@@ -6124,7 +5997,7 @@
     else if (hasReflection()) {
         if (!m_reflection)
             createReflection();
-        UseCounter::count(renderer()->document(), UseCounter::Reflection);
+        UseCounter::count(&renderer()->document(), UseCounter::Reflection);
         updateReflectionStyle();
     }
 
@@ -6187,8 +6060,16 @@
         isVisibleToHitTest &= owner->renderer() && owner->renderer()->visibleToHitTesting();
 
     if (hasOverflow && isVisibleToHitTest) {
-        if (frameView->addScrollableArea(scrollableArea()))
+        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;
+            }
+        }
     } else {
         if (frameView->removeScrollableArea(scrollableArea()))
             setNeedsCompositedScrolling(false);
@@ -6201,7 +6082,7 @@
     RefPtr<RenderStyle> corner = renderer()->hasOverflowClip() ? actualRenderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), actualRenderer->style()) : PassRefPtr<RenderStyle>(0);
     if (corner) {
         if (!m_scrollCorner) {
-            m_scrollCorner = RenderScrollbarPart::createAnonymous(renderer()->document());
+            m_scrollCorner = RenderScrollbarPart::createAnonymous(&renderer()->document());
             m_scrollCorner->setParent(renderer());
         }
         m_scrollCorner->setStyle(corner.release());
@@ -6217,7 +6098,7 @@
     RefPtr<RenderStyle> resizer = renderer()->hasOverflowClip() ? actualRenderer->getUncachedPseudoStyle(PseudoStyleRequest(RESIZER), actualRenderer->style()) : PassRefPtr<RenderStyle>(0);
     if (resizer) {
         if (!m_resizer) {
-            m_resizer = RenderScrollbarPart::createAnonymous(renderer()->document());
+            m_resizer = RenderScrollbarPart::createAnonymous(&renderer()->document());
             m_resizer->setParent(renderer());
         }
         m_resizer->setStyle(resizer.release());
@@ -6235,7 +6116,7 @@
 void RenderLayer::createReflection()
 {
     ASSERT(!m_reflection);
-    m_reflection = RenderReplica::createAnonymous(renderer()->document());
+    m_reflection = RenderReplica::createAnonymous(&renderer()->document());
     m_reflection->setParent(renderer()); // We create a 1-way connection.
 }
 
@@ -6289,7 +6170,7 @@
 bool RenderLayer::isCSSCustomFilterEnabled() const
 {
     // We only want to enable shaders if WebGL is also enabled on this platform.
-    const Settings* settings = renderer()->document()->settings();
+    const Settings* settings = renderer()->document().settings();
     return settings && settings->isCSSCustomFilterEnabled() && settings->webGLEnabled();
 }
 
@@ -6388,7 +6269,7 @@
         filterInfo->setRenderer(filterRenderer.release());
 
         // We can optimize away code paths in other places if we know that there are no software filters.
-        renderer()->document()->view()->setHasSoftwareFilters(true);
+        renderer()->document().view()->setHasSoftwareFilters(true);
     }
 
     // If the filter fails to build, remove it from the layer. It will still attempt to
@@ -6413,7 +6294,7 @@
             // For scrolling layers, rects are taken to be in the space of the contents.
             // We need to include both the entire contents, and also the bounding box
             // of the layer in the space of it's parent (eg. for border / scroll bars).
-            rect.append(m_overflowRect);
+            rect.append(m_scrollableArea->overflowRect());
             rects.set(this, rect);
             if (const RenderLayer* parentLayer = parent()) {
                 LayerHitTestRects::iterator iter = rects.find(parentLayer);
diff --git a/Source/core/rendering/RenderLayer.h b/Source/core/rendering/RenderLayer.h
index a404cae..b2ec430 100644
--- a/Source/core/rendering/RenderLayer.h
+++ b/Source/core/rendering/RenderLayer.h
@@ -383,17 +383,11 @@
 
     void panScrollFromPoint(const IntPoint&);
 
-    enum ScrollOffsetClamping {
-        ScrollOffsetUnclamped,
-        ScrollOffsetClamped
-    };
-
     // Scrolling methods for layers that can scroll their overflow.
     void scrollByRecursively(const IntSize&, ScrollOffsetClamping = ScrollOffsetUnclamped);
     void scrollToOffset(const IntSize&, ScrollOffsetClamping = ScrollOffsetUnclamped);
     void scrollToXOffset(int x, ScrollOffsetClamping clamp = ScrollOffsetUnclamped) { scrollToOffset(IntSize(x, scrollYOffset()), clamp); }
     void scrollToYOffset(int y, ScrollOffsetClamping clamp = ScrollOffsetUnclamped) { scrollToOffset(IntSize(scrollXOffset(), y), clamp); }
-
     void scrollRectToVisible(const LayoutRect&, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
 
     LayoutRect getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
@@ -886,8 +880,6 @@
     typedef unsigned UpdateLayerPositionsAfterScrollFlags;
     void updateLayerPositionsAfterScroll(RenderGeometryMap*, UpdateLayerPositionsAfterScrollFlags = NoFlag);
 
-    IntSize clampScrollOffset(const IntSize&) const;
-
     void setNextSibling(RenderLayer* next) { m_next = next; }
     void setPreviousSibling(RenderLayer* prev) { m_previous = prev; }
     void setParent(RenderLayer* parent);
@@ -977,12 +969,6 @@
 
     bool listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayer*>*, const LayoutRect&) const;
 
-    void computeScrollDimensions();
-    bool hasHorizontalOverflow() const;
-    bool hasVerticalOverflow() const;
-    bool hasScrollableHorizontalOverflow() const;
-    bool hasScrollableVerticalOverflow() const;
-
     bool shouldBeNormalFlowOnly() const;
     bool shouldBeNormalFlowOnlyIgnoringCompositedScrolling() const;
 
@@ -1022,18 +1008,15 @@
     IntPoint convertFromScrollbarToContainingView(const Scrollbar*, const IntPoint&) const;
     IntPoint convertFromContainingViewToScrollbar(const Scrollbar*, const IntPoint&) const;
     int scrollSize(ScrollbarOrientation) const;
-    void setScrollOffset(const IntPoint&);
-    IntPoint minimumScrollPosition() const;
-    IntPoint maximumScrollPosition() const;
     int visibleHeight() const;
     int visibleWidth() const;
-    IntSize contentsSize() const;
     IntSize overhangAmount() const;
     IntPoint lastKnownMousePosition() const;
     bool shouldSuspendScrollAnimations() const;
     bool scrollbarsCanBeActive() const;
     IntRect scrollableAreaBoundingBox() const;
     bool userInputScrollable(ScrollbarOrientation) const;
+    bool shouldPlaceVerticalScrollbarOnLeft() const;
     int pageStep(ScrollbarOrientation) const;
     // End of ScrollableArea interface
 
@@ -1120,7 +1103,6 @@
     // Keeps track of whether the layer is currently resizing, so events can cause resizing to start and stop.
     unsigned m_inResizeMode : 1;
 
-    unsigned m_scrollDimensionsDirty : 1;
     unsigned m_zOrderListsDirty : 1;
     unsigned m_normalFlowListDirty: 1;
     unsigned m_isNormalFlowOnly : 1;
@@ -1144,6 +1126,10 @@
     unsigned m_isUnclippedDescendant : 1;
 
     unsigned m_needsCompositedScrolling : 1;
+    unsigned m_needsCompositedScrollingHasBeenRecorded : 1;
+    unsigned m_willUseCompositedScrollingHasBeenRecorded : 1;
+
+    unsigned m_isScrollableAreaHasBeenRecorded : 1;
 
     // If this is true, then no non-descendant appears between any of our
     // descendants in stacking order. This is one of the requirements of being
@@ -1206,9 +1192,6 @@
     // The layer's width/height
     IntSize m_layerSize;
 
-    // The width/height of our scrolled area.
-    LayoutRect m_overflowRect;
-
     // For layers with overflow, we have a pair of scrollbars.
     RefPtr<Scrollbar> m_hBar;
     RefPtr<Scrollbar> m_vBar;
diff --git a/Source/core/rendering/RenderLayerBacking.cpp b/Source/core/rendering/RenderLayerBacking.cpp
index 991d529..0bdbeee 100644
--- a/Source/core/rendering/RenderLayerBacking.cpp
+++ b/Source/core/rendering/RenderLayerBacking.cpp
@@ -40,6 +40,7 @@
 #include "core/page/Settings.h"
 #include "core/page/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
+#include "core/platform/animation/KeyframeValueList.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/GraphicsLayer.h"
@@ -159,9 +160,9 @@
     , m_backgroundLayerPaintsFixedRootBackground(false)
 {
     if (layer->isRootLayer()) {
-        Frame* frame = toRenderView(renderer())->frameView()->frame();
-        Page* page = frame ? frame->page() : 0;
-        if (page && frame && page->mainFrame() == frame) {
+        Frame& frame = toRenderView(renderer())->frameView()->frame();
+        Page* page = frame.page();
+        if (page && page->mainFrame() == &frame) {
             m_isMainFrameRenderViewLayer = true;
         }
     }
@@ -815,8 +816,7 @@
 
     bool hasPaintedContent = containsPaintedContent(isSimpleContainer);
     if (hasPaintedContent && isAcceleratedCanvas(renderer())) {
-        HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(renderer()->node());
-        CanvasRenderingContext* context = canvas->renderingContext();
+        CanvasRenderingContext* context = toHTMLCanvasElement(renderer()->node())->renderingContext();
         // Content layer may be null if context is lost.
         if (WebKit::WebLayer* contentLayer = context->platformLayer()) {
             Color bgColor;
@@ -1219,7 +1219,7 @@
 
     if (renderObject->node() && renderObject->node()->isDocumentNode()) {
         // Look to see if the root object has a non-simple background
-        RenderObject* rootObject = renderObject->document()->documentElement() ? renderObject->document()->documentElement()->renderer() : 0;
+        RenderObject* rootObject = renderObject->document().documentElement() ? renderObject->document().documentElement()->renderer() : 0;
         if (!rootObject)
             return false;
 
@@ -1231,7 +1231,7 @@
             return false;
 
         // Now look at the body's renderer.
-        HTMLElement* body = renderObject->document()->body();
+        HTMLElement* body = renderObject->document().body();
         RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
         if (!bodyObject)
             return false;
@@ -1695,7 +1695,7 @@
             continue;
 
         // Get timing function.
-        RefPtr<TimingFunction> tf = keyframeStyle->hasAnimations() ? (*keyframeStyle->animations()).animation(0)->timingFunction() : 0;
+        RefPtr<TimingFunction> tf = currentKeyframe.timingFunction(keyframes.animationName());
 
         bool isFirstOrLastKeyframe = key == 0 || key == 1;
         if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
diff --git a/Source/core/rendering/RenderLayerCompositor.cpp b/Source/core/rendering/RenderLayerCompositor.cpp
index d3d2033..ca69154 100644
--- a/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/RenderLayerCompositor.cpp
@@ -263,7 +263,7 @@
     bool showRepaintCounter = false;
     bool forceCompositingMode = false;
 
-    if (Settings* settings = m_renderView->document()->settings()) {
+    if (Settings* settings = m_renderView->document().settings()) {
         hasAcceleratedCompositing = settings->acceleratedCompositingEnabled();
 
         // We allow the chrome to override the settings, in case the page is rendered
@@ -362,7 +362,7 @@
     if (!m_reevaluateCompositingAfterLayout && !m_compositing)
         return;
 
-    AnimationUpdateBlock animationUpdateBlock(m_renderView->frameView()->frame()->animation());
+    AnimationUpdateBlock animationUpdateBlock(m_renderView->frameView()->frame().animation());
 
     TemporaryChange<bool> postLayoutChange(m_inPostLayoutUpdate, true);
 
@@ -431,8 +431,8 @@
         m_obligatoryBackingStoreBytes = 0;
         m_secondaryBackingStoreBytes = 0;
 
-        Frame* frame = m_renderView->frameView()->frame();
-        LOG(Compositing, "\nUpdate %d of %s.\n", m_rootLayerUpdateCount, isMainFrame() ? "main frame" : frame->tree()->uniqueName().string().utf8().data());
+        Frame& frame = m_renderView->frameView()->frame();
+        LOG(Compositing, "\nUpdate %d of %s.\n", m_rootLayerUpdateCount, isMainFrame() ? "main frame" : frame.tree()->uniqueName().string().utf8().data());
     }
 #endif
 
@@ -1193,6 +1193,13 @@
     }
 }
 
+enum AcceleratedFixedRootBackgroundHistogramBuckets {
+    ScrolledMainFrameBucket = 0,
+    ScrolledMainFrameWithAcceleratedFixedRootBackground = 1,
+    ScrolledMainFrameWithUnacceleratedFixedRootBackground = 2,
+    AcceleratedFixedRootBackgroundHistogramMax = 3
+};
+
 void RenderLayerCompositor::frameViewDidScroll()
 {
     FrameView* frameView = m_renderView->frameView();
@@ -1203,7 +1210,7 @@
 
     bool scrollingCoordinatorHandlesOffset = false;
     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
-        if (Settings* settings = m_renderView->document()->settings()) {
+        if (Settings* settings = m_renderView->document().settings()) {
             if (isMainFrame() || settings->compositedScrollingForFramesEnabled())
                 scrollingCoordinatorHandlesOffset = scrollingCoordinator->scrollableAreaScrollLayerDidChange(frameView);
         }
@@ -1216,6 +1223,20 @@
         m_scrollLayer->setPosition(-frameView->minimumScrollPosition());
     else
         m_scrollLayer->setPosition(-scrollPosition);
+
+
+    HistogramSupport::histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
+        ScrolledMainFrameBucket,
+        AcceleratedFixedRootBackgroundHistogramMax);
+
+    if (!m_renderView->rootBackgroundIsEntirelyFixed())
+        return;
+
+    HistogramSupport::histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
+        !!fixedRootBackgroundLayer()
+            ? ScrolledMainFrameWithAcceleratedFixedRootBackground
+            : ScrolledMainFrameWithUnacceleratedFixedRootBackground,
+        AcceleratedFixedRootBackgroundHistogramMax);
 }
 
 void RenderLayerCompositor::frameViewDidLayout()
@@ -1907,7 +1928,7 @@
     if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
         return false;
 
-    if (Settings* settings = m_renderView->document()->settings()) {
+    if (Settings* settings = m_renderView->document().settings()) {
         if (!settings->acceleratedCompositingForTransitionEnabled())
             return false;
     }
@@ -2030,7 +2051,7 @@
         return false;
 
     // FIXME: acceleratedCompositingForFixedPositionEnabled should probably be renamed acceleratedCompositingForViewportConstrainedPositionEnabled().
-    if (Settings* settings = m_renderView->document()->settings()) {
+    if (Settings* settings = m_renderView->document().settings()) {
         if (!settings->acceleratedCompositingForFixedPositionEnabled())
             return false;
     }
@@ -2098,8 +2119,10 @@
         LayoutRect layerBounds = layer->calculateLayerBounds(rootRenderLayer(), 0, RenderLayer::DefaultCalculateLayerBoundsFlags
             | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask | RenderLayer::IncludeCompositedDescendants);
         if (!viewBounds.intersects(enclosingIntRect(layerBounds))) {
-            if (viewportConstrainedNotCompositedReason)
+            if (viewportConstrainedNotCompositedReason) {
                 *viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForBoundsOutOfView;
+                m_reevaluateCompositingAfterLayout = true;
+            }
             return false;
         }
     }
@@ -2169,7 +2192,7 @@
 
 bool RenderLayerCompositor::supportsFixedRootBackgroundCompositing() const
 {
-    if (Settings* settings = m_renderView->document()->settings()) {
+    if (Settings* settings = m_renderView->document().settings()) {
         if (settings->acceleratedCompositingForFixedRootBackgroundEnabled())
             return true;
     }
@@ -2237,7 +2260,7 @@
 
 static bool shouldCompositeOverflowControls(FrameView* view)
 {
-    if (Page* page = view->frame()->page()) {
+    if (Page* page = view->frame().page()) {
         if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
             if (scrollingCoordinator->coordinatesScrollingForFrameView(view))
                 return true;
@@ -2464,17 +2487,17 @@
             ASSERT_NOT_REACHED();
             break;
         case RootLayerAttachedViaChromeClient: {
-            Frame* frame = m_renderView->frameView()->frame();
-            Page* page = frame ? frame->page() : 0;
+            Frame& frame = m_renderView->frameView()->frame();
+            Page* page = frame.page();
             if (!page)
                 return;
-            page->chrome().client().attachRootGraphicsLayer(frame, rootGraphicsLayer());
+            page->chrome().client().attachRootGraphicsLayer(&frame, rootGraphicsLayer());
             break;
         }
         case RootLayerAttachedViaEnclosingFrame: {
             // The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
             // for the frame's renderer in the parent document.
-            m_renderView->document()->ownerElement()->scheduleLayerUpdate();
+            m_renderView->document().ownerElement()->scheduleLayerUpdate();
             break;
         }
     }
@@ -2496,16 +2519,16 @@
         else
             m_rootContentLayer->removeFromParent();
 
-        if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
+        if (HTMLFrameOwnerElement* ownerElement = m_renderView->document().ownerElement())
             ownerElement->scheduleLayerUpdate();
         break;
     }
     case RootLayerAttachedViaChromeClient: {
-        Frame* frame = m_renderView->frameView()->frame();
-        Page* page = frame ? frame->page() : 0;
+        Frame& frame = m_renderView->frameView()->frame();
+        Page* page = frame.page();
         if (!page)
             return;
-        page->chrome().client().attachRootGraphicsLayer(frame, 0);
+        page->chrome().client().attachRootGraphicsLayer(&frame, 0);
     }
     break;
     case RootLayerUnattached:
@@ -2522,7 +2545,7 @@
 
 bool RenderLayerCompositor::isMainFrame() const
 {
-    return !m_renderView->document()->ownerElement();
+    return !m_renderView->document().ownerElement();
 }
 
 // IFrames are special, because we hook compositing layers together across iframe boundaries
@@ -2530,18 +2553,18 @@
 // to use a synthetic style change to get the iframes into RenderLayers in order to allow them to composite.
 void RenderLayerCompositor::notifyIFramesOfCompositingChange()
 {
-    Frame* frame = m_renderView->frameView() ? m_renderView->frameView()->frame() : 0;
-    if (!frame)
+    if (!m_renderView->frameView())
         return;
+    Frame& frame = m_renderView->frameView()->frame();
 
-    for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->traverseNext(frame)) {
+    for (Frame* child = frame.tree()->firstChild(); child; child = child->tree()->traverseNext(&frame)) {
         if (child->document() && child->document()->ownerElement())
             child->document()->ownerElement()->scheduleLayerUpdate();
     }
 
     // Compositing also affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so
     // we need to schedule a style recalc in our parent document.
-    if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
+    if (HTMLFrameOwnerElement* ownerElement = m_renderView->document().ownerElement())
         ownerElement->scheduleLayerUpdate();
 }
 
@@ -2705,10 +2728,7 @@
 
 Page* RenderLayerCompositor::page() const
 {
-    if (Frame* frame = m_renderView->frameView()->frame())
-        return frame->page();
-
-    return 0;
+    return m_renderView->frameView()->frame().page();
 }
 
 String RenderLayerCompositor::debugName(const GraphicsLayer* graphicsLayer)
diff --git a/Source/core/rendering/RenderLayerCompositor.h b/Source/core/rendering/RenderLayerCompositor.h
index 60c77ea..3496bdd 100644
--- a/Source/core/rendering/RenderLayerCompositor.h
+++ b/Source/core/rendering/RenderLayerCompositor.h
@@ -27,7 +27,6 @@
 #define RenderLayerCompositor_h
 
 #include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
 #include "core/platform/graphics/GraphicsLayerClient.h"
 #include "core/rendering/RenderLayer.h"
 #include "wtf/HashMap.h"
diff --git a/Source/core/rendering/RenderLayerFilterInfo.cpp b/Source/core/rendering/RenderLayerFilterInfo.cpp
index 89af942..effb585 100644
--- a/Source/core/rendering/RenderLayerFilterInfo.cpp
+++ b/Source/core/rendering/RenderLayerFilterInfo.cpp
@@ -37,7 +37,10 @@
 #include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
 #include "core/rendering/FilterEffectRenderer.h"
 #include "core/rendering/RenderLayer.h"
+#include "core/rendering/svg/RenderSVGResourceContainer.h"
 #include "core/svg/SVGFilterElement.h"
+#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "core/svg/graphics/filters/SVGFilter.h"
 
 namespace WebCore {
 
@@ -126,10 +129,13 @@
         } else {
             // Reference is internal; add layer as a client so we can trigger
             // filter repaint on SVG attribute change.
-            Element* filter = m_layer->renderer()->node()->document()->getElementById(referenceFilterOperation->fragment());
+            Element* filter = m_layer->renderer()->node()->document().getElementById(referenceFilterOperation->fragment());
             if (!filter || !filter->hasTagName(SVGNames::filterTag))
                 continue;
-            toSVGFilterElement(filter)->addClientRenderLayer(m_layer);
+            if (filter->renderer())
+                filter->renderer()->toRenderSVGResourceContainer()->addClientRenderLayer(m_layer);
+            else
+                toSVGFilterElement(filter)->addClient(m_layer->renderer()->node());
             m_internalSVGReferences.append(filter);
         }
     }
@@ -142,7 +148,10 @@
     m_externalSVGReferences.clear();
     for (size_t i = 0; i < m_internalSVGReferences.size(); ++i) {
         Element* filter = m_internalSVGReferences.at(i).get();
-        toSVGFilterElement(filter)->removeClientRenderLayer(m_layer);
+        if (filter->renderer())
+            filter->renderer()->toRenderSVGResourceContainer()->removeClientRenderLayer(m_layer);
+        else
+            toSVGFilterElement(filter)->removeClient(m_layer->renderer()->node());
     }
     m_internalSVGReferences.clear();
 }
diff --git a/Source/core/rendering/RenderLayerModelObject.cpp b/Source/core/rendering/RenderLayerModelObject.cpp
index 6e91511..dda32af 100644
--- a/Source/core/rendering/RenderLayerModelObject.cpp
+++ b/Source/core/rendering/RenderLayerModelObject.cpp
@@ -25,6 +25,7 @@
 #include "config.h"
 #include "core/rendering/RenderLayerModelObject.h"
 
+#include "core/page/Frame.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
 
diff --git a/Source/core/rendering/RenderLayerScrollableArea.cpp b/Source/core/rendering/RenderLayerScrollableArea.cpp
index acc68cb..24222c1 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.cpp
+++ b/Source/core/rendering/RenderLayerScrollableArea.cpp
@@ -44,16 +44,22 @@
 #include "config.h"
 #include "core/rendering/RenderLayer.h"
 
+#include "core/editing/FrameSelection.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/ScrollAnimator.h"
+#include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderView.h"
 
 namespace WebCore {
 
 RenderLayerScrollableArea::RenderLayerScrollableArea(RenderLayer* layer)
     : m_layer(layer)
+    , m_scrollDimensionsDirty(true)
 {
     ScrollableArea::setConstrainsScrollingToContentEdge(false);
 
@@ -185,9 +191,67 @@
     return m_layer->scrollSize(orientation);
 }
 
-void RenderLayerScrollableArea::setScrollOffset(const IntPoint& offset)
+void RenderLayerScrollableArea::setScrollOffset(const IntPoint& newScrollOffset)
 {
-    m_layer->setScrollOffset(offset);
+    if (!toRenderBox(renderer())->isMarquee()) {
+        // Ensure that the dimensions will be computed if they need to be (for overflow:hidden blocks).
+        if (m_scrollDimensionsDirty)
+            computeScrollDimensions();
+    }
+
+    if (scrollOffset() == toIntSize(newScrollOffset))
+        return;
+
+    setScrollOffset(toIntSize(newScrollOffset));
+
+    Frame* frame = renderer()->frame();
+    InspectorInstrumentation::willScrollLayer(renderer());
+
+    RenderView* view = renderer()->view();
+
+    // We should have a RenderView if we're trying to scroll.
+    ASSERT(view);
+
+    // Update the positions of our child layers (if needed as only fixed layers should be impacted by a scroll).
+    // We don't update compositing layers, because we need to do a deep update from the compositing ancestor.
+    bool inLayout = view ? view->frameView()->isInLayout() : false;
+    if (!inLayout) {
+        // If we're in the middle of layout, we'll just update layers once layout has finished.
+        m_layer->updateLayerPositionsAfterOverflowScroll();
+        if (view) {
+            // Update regions, scrolling may change the clip of a particular region.
+            view->frameView()->updateAnnotatedRegions();
+            view->updateWidgetPositions();
+        }
+
+        m_layer->updateCompositingLayersAfterScroll();
+    }
+
+    RenderLayerModelObject* repaintContainer = renderer()->containerForRepaint();
+    if (frame) {
+        // The caret rect needs to be invalidated after scrolling
+        frame->selection().setCaretRectNeedsUpdate();
+
+        FloatQuad quadForFakeMouseMoveEvent = FloatQuad(m_layer->m_repaintRect);
+        if (repaintContainer)
+            quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
+        frame->eventHandler()->dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
+    }
+
+    bool requiresRepaint = true;
+
+    if (m_layer->compositor()->inCompositingMode() && m_layer->usesCompositedScrolling())
+        requiresRepaint = false;
+
+    // Just schedule a full repaint of our object.
+    if (view && requiresRepaint)
+        renderer()->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_layer->m_repaintRect));
+
+    // Schedule the scroll DOM event.
+    if (renderer()->node())
+        renderer()->node()->document().eventQueue()->enqueueOrDispatchScrollEvent(renderer()->node(), DocumentEventQueue::ScrollEventElementTarget);
+
+    InspectorInstrumentation::didScrollLayer(renderer());
 }
 
 IntPoint RenderLayerScrollableArea::scrollPosition() const
@@ -197,12 +261,17 @@
 
 IntPoint RenderLayerScrollableArea::minimumScrollPosition() const
 {
-    return m_layer->minimumScrollPosition();
+    return -scrollOrigin();
 }
 
 IntPoint RenderLayerScrollableArea::maximumScrollPosition() const
 {
-    return m_layer->maximumScrollPosition();
+    RenderBox* box = toRenderBox(renderer());
+
+    if (!box->hasOverflowClip())
+        return -scrollOrigin();
+
+    return -scrollOrigin() + enclosingIntRect(m_overflowRect).size() - enclosingIntRect(box->clientBoxRect()).size();
 }
 
 IntRect RenderLayerScrollableArea::visibleContentRect(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
@@ -230,7 +299,7 @@
 
 IntSize RenderLayerScrollableArea::contentsSize() const
 {
-    return m_layer->contentsSize();
+    return IntSize(scrollWidth(), scrollHeight());
 }
 
 IntSize RenderLayerScrollableArea::overhangAmount() const
@@ -263,6 +332,11 @@
     return m_layer->userInputScrollable(orientation);
 }
 
+bool RenderLayerScrollableArea::shouldPlaceVerticalScrollbarOnLeft() const
+{
+    return m_layer->shouldPlaceVerticalScrollbarOnLeft();
+}
+
 int RenderLayerScrollableArea::pageStep(ScrollbarOrientation orientation) const
 {
     return m_layer->pageStep(orientation);
@@ -275,4 +349,102 @@
     return m_layer->renderer();
 }
 
+int RenderLayerScrollableArea::scrollWidth() const
+{
+    RenderBox* box = toRenderBox(renderer());
+    if (m_scrollDimensionsDirty)
+        const_cast<RenderLayerScrollableArea*>(this)->computeScrollDimensions();
+    return snapSizeToPixel(m_overflowRect.width(), box->clientLeft() + box->x());
+}
+
+int RenderLayerScrollableArea::scrollHeight() const
+{
+    RenderBox* box = toRenderBox(renderer());
+    if (m_scrollDimensionsDirty)
+        const_cast<RenderLayerScrollableArea*>(this)->computeScrollDimensions();
+    return snapSizeToPixel(m_overflowRect.height(), box->clientTop() + box->y());
+}
+
+void RenderLayerScrollableArea::computeScrollDimensions()
+{
+    RenderBox* box = toRenderBox(renderer());
+
+    m_scrollDimensionsDirty = false;
+
+    m_overflowRect = box->layoutOverflowRect();
+    box->flipForWritingMode(m_overflowRect);
+
+    int scrollableLeftOverflow = m_overflowRect.x() - box->borderLeft();
+    int scrollableTopOverflow = m_overflowRect.y() - box->borderTop();
+    setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
+}
+
+void RenderLayerScrollableArea::scrollToOffset(const IntSize& scrollOffset, ScrollOffsetClamping clamp)
+{
+    IntSize newScrollOffset = clamp == ScrollOffsetClamped ? clampScrollOffset(scrollOffset) : scrollOffset;
+    if (newScrollOffset != adjustedScrollOffset())
+        scrollToOffsetWithoutAnimation(-scrollOrigin() + newScrollOffset);
+}
+
+void RenderLayerScrollableArea::updateAfterLayout()
+{
+    m_scrollDimensionsDirty = true;
+    IntSize originalScrollOffset = adjustedScrollOffset();
+
+    computeScrollDimensions();
+
+    if (!toRenderBox(renderer())->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());
+        if (clampedScrollOffset != adjustedScrollOffset())
+            scrollToOffset(clampedScrollOffset);
+    }
+
+    if (originalScrollOffset != adjustedScrollOffset())
+        scrollToOffsetWithoutAnimation(-scrollOrigin() + adjustedScrollOffset());
+}
+
+bool RenderLayerScrollableArea::hasHorizontalOverflow() const
+{
+    ASSERT(!m_scrollDimensionsDirty);
+
+    return scrollWidth() > toRenderBox(renderer())->pixelSnappedClientWidth();
+}
+
+bool RenderLayerScrollableArea::hasVerticalOverflow() const
+{
+    ASSERT(!m_scrollDimensionsDirty);
+
+    return scrollHeight() > toRenderBox(renderer())->pixelSnappedClientHeight();
+}
+
+bool RenderLayerScrollableArea::hasScrollableHorizontalOverflow() const
+{
+    return hasHorizontalOverflow() && toRenderBox(renderer())->scrollsOverflowX();
+}
+
+bool RenderLayerScrollableArea::hasScrollableVerticalOverflow() const
+{
+    return hasVerticalOverflow() && toRenderBox(renderer())->scrollsOverflowY();
+}
+
+void RenderLayerScrollableArea::updateAfterStyleChange(const RenderStyle*)
+{
+    if (!m_scrollDimensionsDirty)
+        m_layer->updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
+}
+
+IntSize RenderLayerScrollableArea::clampScrollOffset(const IntSize& scrollOffset) const
+{
+    RenderBox* box = toRenderBox(renderer());
+
+    int maxX = scrollWidth() - box->pixelSnappedClientWidth();
+    int maxY = scrollHeight() - box->pixelSnappedClientHeight();
+
+    int x = std::max(std::min(scrollOffset.width(), maxX), 0);
+    int y = std::max(std::min(scrollOffset.height(), maxY), 0);
+    return IntSize(x, y);
+}
+
 } // Namespace WebCore
diff --git a/Source/core/rendering/RenderLayerScrollableArea.h b/Source/core/rendering/RenderLayerScrollableArea.h
index 215ef83..7d467fd 100644
--- a/Source/core/rendering/RenderLayerScrollableArea.h
+++ b/Source/core/rendering/RenderLayerScrollableArea.h
@@ -53,6 +53,11 @@
     ResizerForTouch
 };
 
+enum ScrollOffsetClamping {
+    ScrollOffsetUnclamped,
+    ScrollOffsetClamped
+};
+
 class RenderLayer;
 class RenderLayerModelObject;
 
@@ -98,6 +103,7 @@
     virtual bool scrollbarsCanBeActive() const OVERRIDE;
     virtual IntRect scrollableAreaBoundingBox() const OVERRIDE;
     virtual bool userInputScrollable(ScrollbarOrientation) const OVERRIDE;
+    virtual bool shouldPlaceVerticalScrollbarOnLeft() const OVERRIDE;
     virtual int pageStep(ScrollbarOrientation) const OVERRIDE;
 
     int scrollXOffset() const { return m_scrollOffset.width() + scrollOrigin().x(); }
@@ -105,13 +111,39 @@
 
     IntSize scrollOffset() const { return m_scrollOffset; }
 
+    // FIXME: We shouldn't allow access to m_overflowRect outside this class.
+    LayoutRect overflowRect() const { return m_overflowRect; }
+
+    void scrollToOffset(const IntSize& scrollOffset, ScrollOffsetClamping = ScrollOffsetUnclamped);
+
+    void updateAfterLayout();
+    void updateAfterStyleChange(const RenderStyle*);
+
 private:
+    bool hasHorizontalOverflow() const;
+    bool hasVerticalOverflow() const;
+    bool hasScrollableHorizontalOverflow() const;
+    bool hasScrollableVerticalOverflow() const;
+
+    int scrollWidth() const;
+    int scrollHeight() const;
+
+    void computeScrollDimensions();
+
+    IntSize clampScrollOffset(const IntSize&) const;
+    IntSize adjustedScrollOffset() const { return IntSize(scrollXOffset(), scrollYOffset()); }
+
     void setScrollOffset(const IntSize& scrollOffset) { m_scrollOffset = scrollOffset; }
 
     RenderLayerModelObject* renderer() const;
 
     RenderLayer* m_layer;
 
+    unsigned m_scrollDimensionsDirty : 1;
+
+    // The width/height of our scrolled area.
+    LayoutRect m_overflowRect;
+
     // This is the (scroll) offset from scrollOrigin().
     IntSize m_scrollOffset;
 };
diff --git a/Source/core/rendering/RenderLineBoxList.cpp b/Source/core/rendering/RenderLineBoxList.cpp
index 5030827..0852247 100644
--- a/Source/core/rendering/RenderLineBoxList.cpp
+++ b/Source/core/rendering/RenderLineBoxList.cpp
@@ -33,6 +33,7 @@
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderInline.h"
+#include "core/rendering/RenderView.h"
 #include "core/rendering/RootInlineBox.h"
 
 using namespace std;
@@ -274,7 +275,7 @@
 
 void RenderLineBoxList::dirtyLinesFromChangedChild(RenderObject* container, RenderObject* child)
 {
-    if (!container->parent() || (container->isRenderBlock() && (container->selfNeedsLayout() || !container->isBlockFlow())))
+    if (!container->parent() || (container->isRenderBlock() && (container->selfNeedsLayout() || !container->isRenderBlockFlow())))
         return;
 
     RenderInline* inlineContainer = container->isRenderInline() ? toRenderInline(container) : 0;
diff --git a/Source/core/rendering/RenderListBox.cpp b/Source/core/rendering/RenderListBox.cpp
index 2593e3c..8dedc00 100644
--- a/Source/core/rendering/RenderListBox.cpp
+++ b/Source/core/rendering/RenderListBox.cpp
@@ -80,7 +80,7 @@
 const int baselineAdjustment = 7;
 
 RenderListBox::RenderListBox(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
     , m_optionsChanged(true)
     , m_scrollToRevealSelectionAfterLayout(true)
     , m_inAutoscroll(false)
@@ -128,7 +128,7 @@
                 FontDescription d = itemFont.fontDescription();
                 d.setWeight(d.bolderWeight());
                 itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
-                itemFont.update(document()->styleResolver()->fontSelector());
+                itemFont.update(document().styleResolver()->fontSelector());
             }
 
             if (!text.isEmpty()) {
@@ -164,13 +164,13 @@
             scrollToRevealSelection();
     }
 
-    if (AXObjectCache* cache = document()->existingAXObjectCache())
+    if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->selectedChildrenChanged(this);
 }
 
 void RenderListBox::layout()
 {
-    RenderBlock::layout();
+    RenderBlockFlow::layout();
 
     if (m_vBar) {
         bool enabled = numVisibleItems() < numItems();
@@ -276,8 +276,8 @@
 LayoutRect RenderListBox::itemBoundingBoxRect(const LayoutPoint& additionalOffset, int index)
 {
     return LayoutRect(additionalOffset.x() + borderLeft() + paddingLeft(),
-                   additionalOffset.y() + borderTop() + paddingTop() + itemHeight() * (index - m_indexOffset),
-                   contentWidth(), itemHeight());
+        additionalOffset.y() + borderTop() + paddingTop() + itemHeight() * (index - m_indexOffset),
+        contentWidth(), itemHeight());
 }
 
 void RenderListBox::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
@@ -407,7 +407,7 @@
 
     Color textColor = element->renderStyle() ? resolveColor(element->renderStyle(), CSSPropertyColor) : resolveColor(CSSPropertyColor);
     if (isOptionElement && toHTMLOptionElement(element)->selected()) {
-        if (frame()->selection()->isFocusedAndActive() && document()->focusedElement() == node())
+        if (frame()->selection().isFocusedAndActive() && document().focusedElement() == node())
             textColor = RenderTheme::theme().activeListBoxSelectionForegroundColor();
         // Honor the foreground color for disabled items
         else if (!element->isDisabledFormControl() && !select->isDisabledFormControl())
@@ -425,7 +425,7 @@
         FontDescription d = itemFont.fontDescription();
         d.setWeight(d.bolderWeight());
         itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
-        itemFont.update(document()->styleResolver()->fontSelector());
+        itemFont.update(document().styleResolver()->fontSelector());
     }
 
     // Draw the item text
@@ -441,7 +441,7 @@
 
     Color backColor;
     if (element->hasTagName(optionTag) && toHTMLOptionElement(element)->selected()) {
-        if (frame()->selection()->isFocusedAndActive() && document()->focusedElement() == node())
+        if (frame()->selection().isFocusedAndActive() && document().focusedElement() == node())
             backColor = RenderTheme::theme().activeListBoxSelectionBackgroundColor();
         else
             backColor = RenderTheme::theme().inactiveListBoxSelectionBackgroundColor();
@@ -638,7 +638,7 @@
 
     m_indexOffset = newOffset;
     repaint();
-    node()->document()->eventQueue()->enqueueOrDispatchScrollEvent(node(), DocumentEventQueue::ScrollEventElementTarget);
+    node()->document().eventQueue()->enqueueOrDispatchScrollEvent(node(), DocumentEventQueue::ScrollEventElementTarget);
 }
 
 LayoutUnit RenderListBox::itemHeight() const
@@ -843,6 +843,11 @@
     return orientation == VerticalScrollbar;
 }
 
+bool RenderListBox::shouldPlaceVerticalScrollbarOnLeft() const
+{
+    return false;
+}
+
 int RenderListBox::lineStep(ScrollbarOrientation) const
 {
     return 1;
@@ -876,10 +881,10 @@
     if (hasCustomScrollbarStyle)
         widget = RenderScrollbar::createCustomScrollbar(this, VerticalScrollbar, this->node());
     else {
-        widget = Scrollbar::createNativeScrollbar(this, VerticalScrollbar, RenderTheme::theme().scrollbarControlSizeForPart(ListboxPart));
+        widget = Scrollbar::create(this, VerticalScrollbar, RenderTheme::theme().scrollbarControlSizeForPart(ListboxPart));
         didAddVerticalScrollbar(widget.get());
     }
-    document()->view()->addChild(widget.get());
+    document().view()->addChild(widget.get());
     return widget.release();
 }
 
@@ -909,8 +914,8 @@
         m_vBar->styleChanged();
 
     // Force an update since we know the scrollbars have changed things.
-    if (document()->hasAnnotatedRegions())
-        document()->setAnnotatedRegionsDirty(true);
+    if (document().hasAnnotatedRegions())
+        document().setAnnotatedRegionsDirty(true);
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderListBox.h b/Source/core/rendering/RenderListBox.h
index 11d461d..9c4eceb 100644
--- a/Source/core/rendering/RenderListBox.h
+++ b/Source/core/rendering/RenderListBox.h
@@ -32,13 +32,13 @@
 #define RenderListBox_h
 
 #include "core/platform/ScrollableArea.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
 class HTMLSelectElement;
 
-class RenderListBox FINAL : public RenderBlock, private ScrollableArea {
+class RenderListBox FINAL : public RenderBlockFlow, private ScrollableArea {
 public:
     explicit RenderListBox(Element*);
     virtual ~RenderListBox();
@@ -81,6 +81,8 @@
 
     virtual void layout();
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer = 0) OVERRIDE;
 
     virtual bool canBeProgramaticallyScrolled() const { return true; }
@@ -123,6 +125,7 @@
     virtual IntPoint minimumScrollPosition() const OVERRIDE;
     virtual IntPoint maximumScrollPosition() const OVERRIDE;
     virtual bool userInputScrollable(ScrollbarOrientation) const OVERRIDE;
+    virtual bool shouldPlaceVerticalScrollbarOnLeft() const OVERRIDE;
     virtual int lineStep(ScrollbarOrientation) const;
     virtual int pageStep(ScrollbarOrientation) const;
     virtual float pixelStep(ScrollbarOrientation) const;
diff --git a/Source/core/rendering/RenderListItem.cpp b/Source/core/rendering/RenderListItem.cpp
index 62df763..d88a48f 100644
--- a/Source/core/rendering/RenderListItem.cpp
+++ b/Source/core/rendering/RenderListItem.cpp
@@ -39,7 +39,7 @@
 using namespace HTMLNames;
 
 RenderListItem::RenderListItem(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
     , m_marker(0)
     , m_hasExplicitValue(false)
     , m_isValueUpToDate(false)
@@ -73,7 +73,7 @@
         m_marker->destroy();
         m_marker = 0;
     }
-    RenderBlock::willBeDestroyed();
+    RenderBlockFlow::willBeDestroyed();
 }
 
 void RenderListItem::insertedIntoTree()
@@ -85,7 +85,7 @@
 
 void RenderListItem::willBeRemovedFromTree()
 {
-    RenderBlock::willBeRemovedFromTree();
+    RenderBlockFlow::willBeRemovedFromTree();
 
     updateListMarkerNumbers();
 }
@@ -221,7 +221,7 @@
     if (!firstChild)
         return 0;
 
-    bool inQuirksMode = curr->document()->inQuirksMode();
+    bool inQuirksMode = curr->document().inQuirksMode();
     for (RenderObject* currChild = firstChild; currChild; currChild = currChild->nextSibling()) {
         if (currChild == marker)
             continue;
@@ -296,6 +296,11 @@
             // If markerParent is an anonymous block that has lost all its children, destroy it.
             if (markerParent && markerParent->isAnonymousBlock() && !markerParent->firstChild() && !toRenderBlock(markerParent)->continuation())
                 markerParent->destroy();
+
+            // If the marker is inside we need to redo the preferred width calculations
+            // as the size of the item now includes the size of the list marker.
+            if (m_marker->isInside())
+                containingBlock()->updateLogicalWidth();
         }
     }
 }
@@ -305,12 +310,12 @@
     ASSERT(needsLayout());
 
     updateMarkerLocation();
-    RenderBlock::layout();
+    RenderBlockFlow::layout();
 }
 
 void RenderListItem::addOverflowFromChildren()
 {
-    RenderBlock::addOverflowFromChildren();
+    RenderBlockFlow::addOverflowFromChildren();
     positionListMarker();
 }
 
@@ -414,7 +419,7 @@
     if (!logicalHeight() && hasOverflowClip())
         return;
 
-    RenderBlock::paint(paintInfo, paintOffset);
+    RenderBlockFlow::paint(paintInfo, paintOffset);
 }
 
 const String& RenderListItem::markerText() const
diff --git a/Source/core/rendering/RenderListItem.h b/Source/core/rendering/RenderListItem.h
index 44731aa..9e5d42e 100644
--- a/Source/core/rendering/RenderListItem.h
+++ b/Source/core/rendering/RenderListItem.h
@@ -23,14 +23,14 @@
 #ifndef RenderListItem_h
 #define RenderListItem_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
 class HTMLOListElement;
 class RenderListMarker;
 
-class RenderListItem FINAL : public RenderBlock {
+class RenderListItem FINAL : public RenderBlockFlow {
 public:
     explicit RenderListItem(Element*);
 
@@ -68,6 +68,8 @@
 
     virtual void layout();
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     void positionListMarker();
 
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
diff --git a/Source/core/rendering/RenderListMarker.cpp b/Source/core/rendering/RenderListMarker.cpp
index 930b587..48c7676 100644
--- a/Source/core/rendering/RenderListMarker.cpp
+++ b/Source/core/rendering/RenderListMarker.cpp
@@ -1070,9 +1070,9 @@
 
 RenderListMarker* RenderListMarker::createAnonymous(RenderListItem* item)
 {
-    Document* document = item->document();
+    Document& document = item->document();
     RenderListMarker* renderer = new RenderListMarker(item);
-    renderer->setDocumentForAnonymous(document);
+    renderer->setDocumentForAnonymous(&document);
     return renderer;
 }
 
@@ -1601,7 +1601,7 @@
     LayoutUnit marginStart = 0;
     LayoutUnit marginEnd = 0;
 
-    if (isInside() && !m_listItem->isFloating()) {
+    if (isInside()) {
         if (isImage())
             marginEnd = cMarkerPadding;
         else switch (style()->listStyleType()) {
diff --git a/Source/core/rendering/RenderMarquee.cpp b/Source/core/rendering/RenderMarquee.cpp
index ecfff0d..5849222 100644
--- a/Source/core/rendering/RenderMarquee.cpp
+++ b/Source/core/rendering/RenderMarquee.cpp
@@ -60,7 +60,7 @@
 using namespace HTMLNames;
 
 RenderMarquee::RenderMarquee(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
     , m_currentLoop(0)
     , m_totalLoops(0)
     , m_timer(this, &RenderMarquee::timerFired)
@@ -72,7 +72,7 @@
     , m_stopped(false)
     , m_direction(MAUTO)
 {
-    UseCounter::count(document(), UseCounter::HTMLMarqueeElement);
+    UseCounter::count(&document(), UseCounter::HTMLMarqueeElement);
 }
 
 RenderMarquee::~RenderMarquee()
@@ -82,11 +82,8 @@
 int RenderMarquee::marqueeSpeed() const
 {
     int result = style()->marqueeSpeed();
-    if (Node* node = this->node()) {
-        ASSERT(node->hasTagName(marqueeTag));
-        HTMLMarqueeElement* marqueeElt = static_cast<HTMLMarqueeElement*>(node);
-        result = max(result, marqueeElt->minimumDelay());
-    }
+    if (Node* node = this->node())
+        result = std::max(result, toHTMLMarqueeElement(node)->minimumDelay());
     return result;
 }
 
@@ -167,7 +164,7 @@
 
     // We may end up propagating a scroll event. It is important that we suspend events until
     // the end of the function since they could delete the layer, including the marquee.
-    FrameView* frameView = document()->view();
+    FrameView* frameView = document().view();
     if (frameView)
         frameView->pauseScheduledEvents();
 
@@ -276,7 +273,7 @@
 
 void RenderMarquee::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
 {
-    RenderBlock::layoutBlock(relayoutChildren, pageLogicalHeight);
+    RenderBlockFlow::layoutBlock(relayoutChildren, pageLogicalHeight);
 
     updateMarqueePosition();
 }
diff --git a/Source/core/rendering/RenderMarquee.h b/Source/core/rendering/RenderMarquee.h
index e956a00..8cf3a79 100644
--- a/Source/core/rendering/RenderMarquee.h
+++ b/Source/core/rendering/RenderMarquee.h
@@ -46,7 +46,7 @@
 
 #include "core/platform/Length.h"
 #include "core/platform/Timer.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 
 namespace WebCore {
@@ -54,7 +54,7 @@
 class RenderLayer;
 
 // This class handles the auto-scrolling for <marquee>
-class RenderMarquee FINAL : public RenderBlock {
+class RenderMarquee FINAL : public RenderBlockFlow {
 public:
     explicit RenderMarquee(Element*);
     virtual ~RenderMarquee();
@@ -88,6 +88,8 @@
 
     virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE FINAL;
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     void timerFired(Timer<RenderMarquee>*);
 
     int m_currentLoop;
diff --git a/Source/core/rendering/RenderMediaControlElements.cpp b/Source/core/rendering/RenderMediaControlElements.cpp
index d2b5f55..4e14e90 100644
--- a/Source/core/rendering/RenderMediaControlElements.cpp
+++ b/Source/core/rendering/RenderMediaControlElements.cpp
@@ -34,7 +34,7 @@
 namespace WebCore {
 
 RenderTextTrackContainerElement::RenderTextTrackContainerElement(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
 }
 
diff --git a/Source/core/rendering/RenderMediaControlElements.h b/Source/core/rendering/RenderMediaControlElements.h
index 863a9cf..90a7d5e 100644
--- a/Source/core/rendering/RenderMediaControlElements.h
+++ b/Source/core/rendering/RenderMediaControlElements.h
@@ -29,17 +29,18 @@
 #define RenderMediaControlElements_h
 
 #include "core/html/shadow/MediaControlElements.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderFlexibleBox.h"
 
 namespace WebCore {
 
-class RenderTextTrackContainerElement FINAL : public RenderBlock {
+class RenderTextTrackContainerElement FINAL : public RenderBlockFlow {
 public:
     RenderTextTrackContainerElement(Element*);
 
 private:
     virtual void layout();
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 };
 
 
diff --git a/Source/core/rendering/RenderMenuList.cpp b/Source/core/rendering/RenderMenuList.cpp
index f614d03..bb7451e 100644
--- a/Source/core/rendering/RenderMenuList.cpp
+++ b/Source/core/rendering/RenderMenuList.cpp
@@ -45,6 +45,7 @@
 #include "core/rendering/RenderBR.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderTheme.h"
+#include "core/rendering/RenderView.h"
 
 using namespace std;
 
@@ -135,7 +136,7 @@
     m_innerBlock->addChild(newChild, beforeChild);
     ASSERT(m_innerBlock == firstChild());
 
-    if (AXObjectCache* cache = document()->existingAXObjectCache())
+    if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->childrenChanged(this);
 }
 
@@ -236,7 +237,7 @@
         if (!m_buttonText || !m_buttonText->isBR()) {
             if (m_buttonText)
                 m_buttonText->destroy();
-            m_buttonText = new RenderBR(document());
+            m_buttonText = new RenderBR(&document());
             m_buttonText->setStyle(style());
             addChild(m_buttonText);
         }
@@ -246,7 +247,7 @@
         else {
             if (m_buttonText)
                 m_buttonText->destroy();
-            m_buttonText = new RenderText(document(), s.impl());
+            m_buttonText = new RenderText(&document(), s.impl());
             m_buttonText->setStyle(style());
             // We need to set the text explicitly though it was specified in the
             // constructor because RenderText doesn't refer to the text
@@ -320,7 +321,7 @@
     if (m_popupIsVisible)
         return;
 
-    if (document()->page()->chrome().hasOpenedPopup())
+    if (document().page()->chrome().hasOpenedPopup())
         return;
 
     // Create m_innerBlock here so it ends up as the first child.
@@ -328,7 +329,7 @@
     // inside the showPopup call and it would fail.
     createInnerBlock();
     if (!m_popup)
-        m_popup = document()->page()->chrome().createPopupMenu(*document()->frame(), this);
+        m_popup = document().page()->chrome().createPopupMenu(*document().frame(), this);
     m_popupIsVisible = true;
 
     FloatQuad quad(localToAbsoluteQuad(FloatQuad(borderBoundingBox())));
@@ -347,8 +348,8 @@
 {
     // Check to ensure a page navigation has not occurred while
     // the popup was up.
-    Document* doc = toElement(node())->document();
-    if (!doc || doc != doc->frame()->document())
+    Document& doc = toElement(node())->document();
+    if (&doc != doc.frame()->document())
         return;
 
     HTMLSelectElement* select = selectElement();
@@ -372,7 +373,7 @@
 
 void RenderMenuList::didUpdateActiveOption(int optionIndex)
 {
-    if (!AXObjectCache::accessibilityEnabled() || !document()->existingAXObjectCache())
+    if (!AXObjectCache::accessibilityEnabled() || !document().existingAXObjectCache())
         return;
 
     if (m_lastActiveIndex == optionIndex)
@@ -387,7 +388,7 @@
     HTMLElement* listItem = select->listItems()[listIndex];
     ASSERT(listItem);
     if (listItem->attached()) {
-        if (AccessibilityMenuList* menuList = static_cast<AccessibilityMenuList*>(document()->axObjectCache()->get(this)))
+        if (AccessibilityMenuList* menuList = static_cast<AccessibilityMenuList*>(document().axObjectCache()->get(this)))
             menuList->didUpdateActiveOption(optionIndex);
     }
 }
@@ -493,13 +494,9 @@
     HTMLElement* element = listItems[listIndex];
 
     Color backgroundColor;
-    if (element->renderStyle()) {
+    if (element->renderStyle())
         backgroundColor = resolveColor(element->renderStyle(), CSSPropertyBackgroundColor);
-        itemHasCustomBackgroundColor = backgroundColor.alpha();
-    } else {
-        itemHasCustomBackgroundColor = false;
-    }
-
+    itemHasCustomBackgroundColor = backgroundColor.isValid() && backgroundColor.alpha();
     // If the item has an opaque background color, return that.
     if (!backgroundColor.hasAlpha()) {
         itemBackgroundColor = backgroundColor;
@@ -527,7 +524,7 @@
 
 HostWindow* RenderMenuList::hostWindow() const
 {
-    return document()->view()->hostWindow();
+    return document().view()->hostWindow();
 }
 
 PassRefPtr<Scrollbar> RenderMenuList::createScrollbar(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, ScrollbarControlSize controlSize)
@@ -537,7 +534,7 @@
     if (hasCustomScrollbarStyle)
         widget = RenderScrollbar::createCustomScrollbar(scrollableArea, orientation, this->node());
     else
-        widget = Scrollbar::createNativeScrollbar(scrollableArea, orientation, controlSize);
+        widget = Scrollbar::create(scrollableArea, orientation, controlSize);
     return widget.release();
 }
 
@@ -616,7 +613,7 @@
 
 FontSelector* RenderMenuList::fontSelector() const
 {
-    return document()->styleResolver()->fontSelector();
+    return document().styleResolver()->fontSelector();
 }
 
 }
diff --git a/Source/core/rendering/RenderMeter.cpp b/Source/core/rendering/RenderMeter.cpp
index 9a0fb9e..a4982a9 100644
--- a/Source/core/rendering/RenderMeter.cpp
+++ b/Source/core/rendering/RenderMeter.cpp
@@ -32,7 +32,7 @@
 using namespace HTMLNames;
 
 RenderMeter::RenderMeter(HTMLElement* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
 }
 
diff --git a/Source/core/rendering/RenderMeter.h b/Source/core/rendering/RenderMeter.h
index 0c5f80a..4dfcaca 100644
--- a/Source/core/rendering/RenderMeter.h
+++ b/Source/core/rendering/RenderMeter.h
@@ -21,14 +21,14 @@
 #ifndef RenderMeter_h
 #define RenderMeter_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderWidget.h"
 
 namespace WebCore {
 
 class HTMLMeterElement;
 
-class RenderMeter FINAL : public RenderBlock {
+class RenderMeter FINAL : public RenderBlockFlow {
 public:
     explicit RenderMeter(HTMLElement*);
     virtual ~RenderMeter();
@@ -40,6 +40,8 @@
     virtual void updateLogicalWidth() OVERRIDE;
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     virtual const char* renderName() const { return "RenderMeter"; }
     virtual bool isMeter() const { return true; }
     virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
diff --git a/Source/core/rendering/RenderMultiColumnBlock.cpp b/Source/core/rendering/RenderMultiColumnBlock.cpp
index ebcf426..53c1fe8 100644
--- a/Source/core/rendering/RenderMultiColumnBlock.cpp
+++ b/Source/core/rendering/RenderMultiColumnBlock.cpp
@@ -35,7 +35,7 @@
 namespace WebCore {
 
 RenderMultiColumnBlock::RenderMultiColumnBlock(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
     , m_flowThread(0)
     , m_columnCount(1)
     , m_columnWidth(0)
@@ -139,7 +139,7 @@
 void RenderMultiColumnBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
 {
     if (!m_flowThread) {
-        m_flowThread = RenderMultiColumnFlowThread::createAnonymous(document());
+        m_flowThread = RenderMultiColumnFlowThread::createAnonymous(&document());
         m_flowThread->setStyle(RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK));
         RenderBlock::addChild(m_flowThread);
     }
diff --git a/Source/core/rendering/RenderMultiColumnBlock.h b/Source/core/rendering/RenderMultiColumnBlock.h
index 881bd8a..1ca4701 100644
--- a/Source/core/rendering/RenderMultiColumnBlock.h
+++ b/Source/core/rendering/RenderMultiColumnBlock.h
@@ -27,13 +27,13 @@
 #ifndef RenderMultiColumnBlock_h
 #define RenderMultiColumnBlock_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
 class RenderMultiColumnFlowThread;
 
-class RenderMultiColumnBlock FINAL : public RenderBlock {
+class RenderMultiColumnBlock FINAL : public RenderBlockFlow {
 public:
     RenderMultiColumnBlock(Element*);
 
@@ -59,6 +59,8 @@
     virtual void checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight) OVERRIDE;
     virtual bool relayoutForPagination(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer&) OVERRIDE;
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0) OVERRIDE;
 
     void computeColumnCountAndWidth();
diff --git a/Source/core/rendering/RenderMultiColumnSet.cpp b/Source/core/rendering/RenderMultiColumnSet.cpp
index f53e156..e968725 100644
--- a/Source/core/rendering/RenderMultiColumnSet.cpp
+++ b/Source/core/rendering/RenderMultiColumnSet.cpp
@@ -51,9 +51,9 @@
 
 RenderMultiColumnSet* RenderMultiColumnSet::createAnonymous(RenderFlowThread* flowThread)
 {
-    Document* document = flowThread->document();
+    Document& document = flowThread->document();
     RenderMultiColumnSet* renderer = new RenderMultiColumnSet(flowThread);
-    renderer->setDocumentForAnonymous(document);
+    renderer->setDocumentForAnonymous(&document);
     return renderer;
 }
 
diff --git a/Source/core/rendering/RenderNamedFlowThread.cpp b/Source/core/rendering/RenderNamedFlowThread.cpp
index bc72e9a..8df2c92 100644
--- a/Source/core/rendering/RenderNamedFlowThread.cpp
+++ b/Source/core/rendering/RenderNamedFlowThread.cpp
@@ -82,7 +82,7 @@
 
         ASSERT(contentNode && contentNode->isElementNode());
         ASSERT(contentNode->inNamedFlow());
-        ASSERT(contentNode->document() == document());
+        ASSERT(&contentNode->document() == &document());
 
         contentNode->clearInNamedFlow();
     }
@@ -92,14 +92,16 @@
 
 void RenderNamedFlowThread::updateWritingMode()
 {
-    if (RenderRegion* firstRegion = m_regionList.first()) {
-        if (style()->writingMode() != firstRegion->style()->writingMode()) {
-            // The first region defines the principal writing mode for the entire flow.
-            RefPtr<RenderStyle> newStyle = RenderStyle::clone(style());
-            newStyle->setWritingMode(firstRegion->style()->writingMode());
-            setStyle(newStyle);
-        }
-    }
+    RenderRegion* firstRegion = m_regionList.first();
+    if (!firstRegion)
+        return;
+    if (style()->writingMode() == firstRegion->style()->writingMode())
+        return;
+
+    // The first region defines the principal writing mode for the entire flow.
+    RefPtr<RenderStyle> newStyle = RenderStyle::clone(style());
+    newStyle->setWritingMode(firstRegion->style()->writingMode());
+    setStyle(newStyle.release());
 }
 
 RenderObject* RenderNamedFlowThread::nextRendererForNode(Node* node) const
@@ -440,7 +442,7 @@
 void RenderNamedFlowThread::registerNamedFlowContentNode(Node* contentNode)
 {
     ASSERT(contentNode && contentNode->isElementNode());
-    ASSERT(contentNode->document() == document());
+    ASSERT(&contentNode->document() == &document());
 
     contentNode->setInNamedFlow();
 
@@ -463,7 +465,7 @@
     ASSERT(contentNode && contentNode->isElementNode());
     ASSERT(m_contentNodes.contains(contentNode));
     ASSERT(contentNode->inNamedFlow());
-    ASSERT(contentNode->document() == document());
+    ASSERT(&contentNode->document() == &document());
 
     contentNode->clearInNamedFlow();
     m_contentNodes.remove(contentNode);
@@ -493,7 +495,7 @@
 void RenderNamedFlowThread::dispatchRegionLayoutUpdateEvent()
 {
     RenderFlowThread::dispatchRegionLayoutUpdateEvent();
-    InspectorInstrumentation::didUpdateRegionLayout(document(), m_namedFlow.get());
+    InspectorInstrumentation::didUpdateRegionLayout(&document(), m_namedFlow.get());
 
     if (!m_regionLayoutUpdateEventTimer.isActive() && m_namedFlow->hasEventListeners())
         m_regionLayoutUpdateEventTimer.startOneShot(0);
@@ -502,7 +504,7 @@
 void RenderNamedFlowThread::dispatchRegionOversetChangeEvent()
 {
     RenderFlowThread::dispatchRegionOversetChangeEvent();
-    InspectorInstrumentation::didChangeRegionOverset(document(), m_namedFlow.get());
+    InspectorInstrumentation::didChangeRegionOverset(&document(), m_namedFlow.get());
 
     if (!m_regionOversetChangeEventTimer.isActive() && m_namedFlow->hasEventListeners())
         m_regionOversetChangeEventTimer.startOneShot(0);
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index 99218f8..c479fff 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -84,7 +84,9 @@
 #include "wtf/UnusedParam.h"
 #include "wtf/text/StringBuilder.h"
 #include <algorithm>
+#ifndef NDEBUG
 #include <stdio.h>
+#endif
 
 using namespace std;
 
@@ -94,11 +96,11 @@
 
 #ifndef NDEBUG
 
-RenderObject::SetLayoutNeededForbiddenScope::SetLayoutNeededForbiddenScope(RenderObject* renderObject, bool isForbidden)
+RenderObject::SetLayoutNeededForbiddenScope::SetLayoutNeededForbiddenScope(RenderObject* renderObject)
     : m_renderObject(renderObject)
     , m_preexistingForbidden(m_renderObject->isSetNeedsLayoutForbidden())
 {
-    m_renderObject->setNeedsLayoutIsForbidden(isForbidden);
+    m_renderObject->setNeedsLayoutIsForbidden(true);
 }
 
 RenderObject::SetLayoutNeededForbiddenScope::~SetLayoutNeededForbiddenScope()
@@ -136,7 +138,7 @@
 
 RenderObject* RenderObject::createObject(Element* element, RenderStyle* style)
 {
-    Document* doc = element->document();
+    Document& doc = element->document();
 
     // Minimal support for content properties replacing an entire element.
     // Works only if we have exactly one piece of content and it's a URL.
@@ -166,13 +168,13 @@
     // treat <rt> as ruby text ONLY if it still has its default treatment of block
     if (element->hasTagName(rtTag) && style->display() == BLOCK)
         return new RenderRubyText(element);
-    if (RuntimeEnabledFeatures::cssRegionsEnabled() && style->isDisplayRegionType() && !style->regionThread().isEmpty() && doc->renderView())
+    if (RuntimeEnabledFeatures::cssRegionsEnabled() && style->isDisplayRegionType() && !style->regionThread().isEmpty() && doc.renderView())
         return new RenderRegion(element, 0);
 
     if (style->display() == RUN_IN)
-        UseCounter::count(doc, UseCounter::CSSDisplayRunIn);
+        UseCounter::count(&doc, UseCounter::CSSDisplayRunIn);
     else if (style->display() == COMPACT)
-        UseCounter::count(doc, UseCounter::CSSDisplayCompact);
+        UseCounter::count(&doc, UseCounter::CSSDisplayCompact);
 
     switch (style->display()) {
     case NONE:
@@ -183,9 +185,9 @@
     case INLINE_BLOCK:
     case RUN_IN:
     case COMPACT:
-        if ((!style->hasAutoColumnCount() || !style->hasAutoColumnWidth()) && doc->regionBasedColumnsEnabled())
+        if ((!style->hasAutoColumnCount() || !style->hasAutoColumnWidth()) && doc.regionBasedColumnsEnabled())
             return new RenderMultiColumnBlock(element);
-        return new RenderBlock(element);
+        return new RenderBlockFlow(element);
     case LIST_ITEM:
         return new RenderListItem(element);
     case TABLE:
@@ -223,7 +225,7 @@
 RenderObject::RenderObject(Node* node)
     : ImageResourceClient()
     , m_style(0)
-    , m_node(node)
+    , m_nodeProxy(node)
     , m_parent(0)
     , m_previous(0)
     , m_next(0)
@@ -674,12 +676,6 @@
     bool simplifiedNormalFlowLayout = needsSimplifiedNormalFlowLayout() && !selfNeedsLayout() && !normalChildNeedsLayout();
 
     while (object) {
-#ifndef NDEBUG
-        // FIXME: Remove this once we remove the special cases for counters, quotes and mathml
-        // calling setNeedsLayout during preferred width computation.
-        SetLayoutNeededForbiddenScope layoutForbiddenScope(object, isSetNeedsLayoutForbidden());
-#endif
-
         if (object->selfNeedsLayout())
             return;
 
@@ -739,6 +735,12 @@
     if (isRenderBlock())
         toRenderBlock(this)->checkPositionedObjectsNeedLayout();
 }
+
+void RenderObject::checkNotInPartialLayout()
+{
+    // During partial layout, setNeedsLayout(true or false) should not be called.
+    ASSERT(!frameView()->partialLayout().isStopping());
+}
 #endif
 
 void RenderObject::setPreferredLogicalWidthsDirty(MarkingBehavior markParents)
@@ -1139,12 +1141,12 @@
     const AtomicString& href = toElement(n)->getAttribute(hrefAttr);
     if (href.isNull())
         return;
-    KURL url = n->document()->completeURL(href);
+    KURL url = n->document().completeURL(href);
     if (!url.isValid())
         return;
-    if (context->supportsURLFragments() && url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(url, n->document()->baseURL())) {
+    if (context->supportsURLFragments() && url.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(url, n->document().baseURL())) {
         String name = url.fragmentIdentifier();
-        if (document()->findAnchor(name))
+        if (document().findAnchor(name))
             context->setURLFragmentForRect(name, pixelSnappedIntRect(rect));
         return;
     }
@@ -1270,8 +1272,7 @@
     if (!range || !range->startContainer())
         return FloatRect();
 
-    if (range->ownerDocument())
-        range->ownerDocument()->updateLayout();
+    range->ownerDocument().updateLayout();
 
     Vector<FloatQuad> quads;
     range->textQuads(quads);
@@ -1320,7 +1321,7 @@
         }
     }
 
-    if (document()->view()->hasSoftwareFilters()) {
+    if (document().view()->hasSoftwareFilters()) {
         if (RenderLayer* parentLayer = enclosingLayer()) {
             RenderLayer* enclosingFilterLayer = parentLayer->enclosingFilterLayer();
             if (enclosingFilterLayer)
@@ -1335,7 +1336,7 @@
     if (parentRenderFlowThread) {
         // The ancestor document will do the reparenting when the repaint propagates further up.
         // We're just a seamless child document, and we don't need to do the hacking.
-        if (parentRenderFlowThread && parentRenderFlowThread->document() != document())
+        if (&parentRenderFlowThread && &parentRenderFlowThread->document() != &document())
             return repaintContainer;
         // If we have already found a repaint container then we will repaint into that container only if it is part of the same
         // flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread.
@@ -1542,7 +1543,7 @@
 
 bool RenderObject::checkForRepaintDuringLayout() const
 {
-    return !document()->view()->needsFullRepaint() && !hasLayer() && everHadLayout();
+    return !document().view()->needsFullRepaint() && !hasLayer() && everHadLayout();
 }
 
 LayoutRect RenderObject::rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const
@@ -1564,7 +1565,7 @@
         return;
 
     if (RenderObject* o = parent()) {
-        if (o->isBlockFlow()) {
+        if (o->isRenderBlockFlow()) {
             RenderBlock* cb = toRenderBlock(o);
             if (cb->hasColumns())
                 cb->adjustRectForColumns(rect);
@@ -1662,18 +1663,16 @@
 
 Color RenderObject::selectionBackgroundColor() const
 {
-    Color backgroundColor= Color::transparent;
+    Color backgroundColor;
     if (isSelectable()) {
         RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
-        if (pseudoStyle) {
-            StyleColor styleColor = resolveCurrentColor(pseudoStyle.get(), CSSPropertyBackgroundColor);
-            if (styleColor.isValid())
-                return styleColor.color().blendWithWhite();
+        if (pseudoStyle && resolveColor(pseudoStyle.get(), CSSPropertyBackgroundColor).isValid()) {
+            backgroundColor = resolveColor(pseudoStyle.get(), CSSPropertyBackgroundColor).blendWithWhite();
+        } else {
+            backgroundColor = frame()->selection().isFocusedAndActive() ?
+                RenderTheme::theme().activeSelectionBackgroundColor() :
+                RenderTheme::theme().inactiveSelectionBackgroundColor();
         }
-
-        backgroundColor = frame()->selection()->isFocusedAndActive() ?
-            RenderTheme::theme().activeSelectionBackgroundColor() :
-            RenderTheme::theme().inactiveSelectionBackgroundColor();
     }
 
     return backgroundColor;
@@ -1688,12 +1687,13 @@
 
     Color color;
     if (RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION))) {
-        StyleColor styleColor = resolveCurrentColor(pseudoStyle.get(), colorProperty);
-        color = styleColor.isValid() ? styleColor.color() : resolveColor(pseudoStyle.get(), CSSPropertyColor);
-    } else
-        color = frame()->selection()->isFocusedAndActive() ?
+        Color selectionColor = resolveColor(pseudoStyle.get(), colorProperty);
+        color = selectionColor.isValid() ? selectionColor : resolveColor(pseudoStyle.get(), CSSPropertyColor);
+    } else {
+        color = frame()->selection().isFocusedAndActive() ?
             RenderTheme::theme().activeSelectionForegroundColor() :
             RenderTheme::theme().inactiveSelectionForegroundColor();
+    }
 
     return color;
 }
@@ -1914,8 +1914,8 @@
                 || m_style->zIndex() != newStyle->zIndex()
                 || m_style->hasAutoZIndex() != newStyle->hasAutoZIndex();
             if (visibilityChanged) {
-                document()->setAnnotatedRegionsDirty(true);
-                if (AXObjectCache* cache = document()->existingAXObjectCache())
+                document().setAnnotatedRegionsDirty(true);
+                if (AXObjectCache* cache = document().existingAXObjectCache())
                     cache->childrenChanged(parent());
             }
 
@@ -1946,7 +1946,7 @@
 
         s_affectsParentBlock = isFloatingOrOutOfFlowPositioned()
             && (!newStyle->isFloating() && !newStyle->hasOutOfFlowPosition())
-            && parent() && (parent()->isBlockFlow() || parent()->isRenderInline());
+            && parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
 
         // reset style flags
         if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
@@ -1974,7 +1974,7 @@
         bool newStyleSlowScroll = newStyle && !shouldBlitOnFixedBackgroundImage && newStyle->hasFixedBackgroundImage();
         bool oldStyleSlowScroll = m_style && !shouldBlitOnFixedBackgroundImage && m_style->hasFixedBackgroundImage();
 
-        bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document()->documentElement()->renderer()));
+        bool drawsRootBackground = isRoot() || (isBody() && !rendererHasBackground(document().documentElement()->renderer()));
         if (drawsRootBackground && !shouldBlitOnFixedBackgroundImage) {
             if (view()->compositor()->supportsFixedRootBackgroundCompositing()) {
                 if (newStyleSlowScroll && newStyle->hasEntirelyFixedBackground())
@@ -2299,8 +2299,13 @@
         RenderObject* container = this->container();
         if (container) {
             currentLayer = container->enclosingLayer();
-            if (currentLayer && currentLayer->renderer() != container)
+            if (currentLayer && currentLayer->renderer() != container) {
                 layerOffset.move(container->offsetFromAncestorContainer(currentLayer->renderer()));
+                // If the layer itself is scrolled, we have to undo the subtraction of its scroll
+                // offset since we want the offset relative to the scrolling content, not the
+                // element itself.
+                layerOffset.move(currentLayer->scrolledContentOffset());
+            }
         } else {
             currentLayer = enclosingLayer();
         }
@@ -2373,7 +2378,7 @@
         // to crawl around a render tree with potential :before/:after content and
         // anonymous blocks created by inline <body> tags etc. We can locate the <body>
         // render object very easily via the DOM.
-        HTMLElement* body = document()->body();
+        HTMLElement* body = document().body();
         RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
         if (bodyObject)
             return bodyObject;
@@ -2386,13 +2391,13 @@
 {
     // Respect the image's orientation if it's being used as a full-page image or it's
     // an <img> and the setting to respect it everywhere is set.
-    return document()->isImageDocument() ||
-        (document()->settings() && document()->settings()->shouldRespectImageOrientation() && node() && node()->hasTagName(HTMLNames::imgTag)) ? RespectImageOrientation : DoNotRespectImageOrientation;
+    return document().isImageDocument()
+        || (document().settings() && document().settings()->shouldRespectImageOrientation() && node() && node()->hasTagName(HTMLNames::imgTag)) ? RespectImageOrientation : DoNotRespectImageOrientation;
 }
 
 bool RenderObject::hasOutlineAnnotation() const
 {
-    return node() && node()->isLink() && document()->printing();
+    return node() && node()->isLink() && document().printing();
 }
 
 bool RenderObject::hasEntirelyFixedBackground() const
@@ -2504,14 +2509,14 @@
 
     // For accessibility management, notify the parent of the imminent change to its child set.
     // We do it now, before remove(), while the parent pointer is still available.
-    if (AXObjectCache* cache = document()->existingAXObjectCache())
+    if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->childrenChanged(this->parent());
 
     remove();
 
     // The remove() call above may invoke axObjectCache()->childrenChanged() on the parent, which may require the AX render
     // object for this renderer. So we remove the AX render object now, after the renderer is removed.
-    if (AXObjectCache* cache = document()->existingAXObjectCache())
+    if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->remove(this);
 
 #ifndef NDEBUG
@@ -2821,7 +2826,7 @@
     if (renderer->isBeforeOrAfterContent())
         rendererForFirstLineStyle = renderer->parent();
 
-    if (rendererForFirstLineStyle->isBlockFlow()) {
+    if (rendererForFirstLineStyle->isRenderBlockFlow() || rendererForFirstLineStyle->isRenderButton()) {
         if (RenderBlock* firstLineBlock = rendererForFirstLineStyle->firstLineBlock()) {
             if (type == Cached)
                 return firstLineBlock->getCachedPseudoStyle(FIRST_LINE, style);
@@ -2843,7 +2848,7 @@
 
 PassRefPtr<RenderStyle> RenderObject::uncachedFirstLineStyle(RenderStyle* style) const
 {
-    if (!document()->styleSheetCollections()->usesFirstLineRules())
+    if (!document().styleSheetCollections()->usesFirstLineRules())
         return 0;
 
     ASSERT(!isText());
@@ -2853,7 +2858,7 @@
 
 RenderStyle* RenderObject::cachedFirstLineStyle() const
 {
-    ASSERT(document()->styleSheetCollections()->usesFirstLineRules());
+    ASSERT(document().styleSheetCollections()->usesFirstLineRules());
 
     if (RefPtr<RenderStyle> style = firstLineStyleForCachedUncachedType(Cached, isText() ? parent() : this, m_style.get()))
         return style.get();
@@ -2895,12 +2900,12 @@
     Element* element = toElement(n);
 
     if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
-        RefPtr<RenderStyle> result = document()->styleResolver()->styleForElement(element, parentStyle, DisallowStyleSharing);
+        RefPtr<RenderStyle> result = document().styleResolver()->styleForElement(element, parentStyle, DisallowStyleSharing);
         result->setStyleType(FIRST_LINE_INHERITED);
         return result.release();
     }
 
-    return document()->styleResolver()->pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
+    return document().styleResolver()->pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
 }
 
 bool RenderObject::hasBlendMode() const
@@ -2910,20 +2915,20 @@
 
 static Color decorationColor(const RenderObject* object, RenderStyle* style)
 {
-    StyleColor result;
+    Color result;
     // Check for text decoration color first.
-    result = object->resolveStyleColor(style, CSSPropertyTextDecorationColor);
+    result = object->resolveColor(style, CSSPropertyTextDecorationColor);
     if (result.isValid())
-        return result.color();
+        return result;
     if (style->textStrokeWidth() > 0) {
         // Prefer stroke color if possible but not if it's fully transparent.
         result = object->resolveColor(style, CSSPropertyWebkitTextStrokeColor);
         if (result.alpha())
-            return result.color();
+            return result;
     }
 
     result = object->resolveColor(style, CSSPropertyWebkitTextFillColor);
-    return result.color();
+    return result;
 }
 
 void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
@@ -3008,12 +3013,12 @@
         return false;
 
     // We will not render a new image when Active DOM is suspended
-    if (document()->activeDOMObjectsAreSuspended())
+    if (document().activeDOMObjectsAreSuspended())
         return false;
 
     // If we're not in a window (i.e., we're dormant from being in a background tab)
     // then we don't want to render either.
-    return !document()->view()->isOffscreen();
+    return !document().view()->isOffscreen();
 }
 
 int RenderObject::maximalOutlineSize(PaintPhase p) const
@@ -3127,7 +3132,7 @@
 
         // CSS regions specification says that region flows should return the body element as their offsetParent.
         if (ancestor->isRenderNamedFlowThread())
-            return document()->body();
+            return document().body();
 
         node = ancestor->node();
 
diff --git a/Source/core/rendering/RenderObject.h b/Source/core/rendering/RenderObject.h
index 27427ae..004d59b 100644
--- a/Source/core/rendering/RenderObject.h
+++ b/Source/core/rendering/RenderObject.h
@@ -33,8 +33,10 @@
 #include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/graphics/transforms/TransformationMatrix.h"
+#include "core/rendering/LayoutIndicator.h"
 #include "core/rendering/PaintPhase.h"
 #include "core/rendering/RenderObjectChildList.h"
+#include "core/rendering/RenderingNodeProxy.h"
 #include "core/rendering/ScrollBehavior.h"
 #include "core/rendering/SubtreeLayoutScope.h"
 #include "core/rendering/style/RenderStyle.h"
@@ -64,6 +66,8 @@
 class RenderNamedFlowThread;
 class RenderSVGResourceContainer;
 class RenderTable;
+class RenderTheme;
+class RenderView;
 class TransformState;
 
 struct PaintInfo;
@@ -221,7 +225,7 @@
     // Helper class forbidding calls to setNeedsLayout() during its lifetime.
     class SetLayoutNeededForbiddenScope {
     public:
-        explicit SetLayoutNeededForbiddenScope(RenderObject*, bool isForbidden = true);
+        explicit SetLayoutNeededForbiddenScope(RenderObject*);
         ~SetLayoutNeededForbiddenScope();
     private:
         RenderObject* m_renderObject;
@@ -301,7 +305,6 @@
     bool isPseudoElement() const { return node() && node()->isPseudoElement(); }
 
     virtual bool isBR() const { return false; }
-    virtual bool isBlockFlow() const { return false; }
     virtual bool isBoxModelObject() const { return false; }
     virtual bool isCounter() const { return false; }
     virtual bool isDialog() const { return false; }
@@ -325,6 +328,7 @@
     virtual bool isMeter() const { return false; }
     virtual bool isProgress() const { return false; }
     virtual bool isRenderBlock() const { return false; }
+    virtual bool isRenderBlockFlow() const { return false; }
     virtual bool isRenderSVGBlock() const { return false; };
     virtual bool isRenderButton() const { return false; }
     virtual bool isRenderIFrame() const { return false; }
@@ -369,7 +373,7 @@
 
     virtual bool isRenderScrollbarPart() const { return false; }
 
-    bool isRoot() const { return document()->documentElement() == m_node; }
+    bool isRoot() const { return document().documentElement() == m_nodeProxy.unsafeNode(); }
     bool isBody() const;
     bool isHR() const;
     bool isLegend() const;
@@ -530,13 +534,7 @@
     bool backgroundIsKnownToBeObscured();
     bool borderImageIsLoadedAndCanBeRendered() const;
     bool mustRepaintBackgroundOrBorder() const;
-    bool hasBackground() const
-    {
-        StyleColor color = resolveColor(CSSPropertyBackgroundColor);
-        if (color.isValid() && color.alpha())
-            return true;
-        return style()->hasBackgroundImage();
-    }
+    bool hasBackground() const { return style()->hasBackground(); }
     bool hasEntirelyFixedBackground() const;
 
     bool needsLayout() const
@@ -583,24 +581,29 @@
 
     virtual void updateDragState(bool dragOn);
 
-    RenderView* view() const { return document()->renderView(); };
+    RenderView* view() const { return document().renderView(); };
+    FrameView* frameView() const { return document().view(); };
 
     // Returns true if this renderer is rooted, and optionally returns the hosting view (the root of the hierarchy).
     bool isRooted(RenderView** = 0) const;
 
-    Node* node() const { return isAnonymous() ? 0 : m_node; }
-    Node* nonPseudoNode() const { return isPseudoElement() ? 0 : node(); }
+    Node* node() const { return isAnonymous() ? 0 : m_nodeProxy.unsafeNode(); }
+    Node* nonPseudoNode() const
+    {
+        ASSERT(!LayoutIndicator::inLayout());
+        return isPseudoElement() ? 0 : node();
+    }
 
     // FIXME: Why does RenderWidget need this?
-    void clearNode() { m_node = 0; }
+    void clearNode() { m_nodeProxy.clear(); }
 
     // Returns the styled node that caused the generation of this renderer.
     // This is the same as node() except for renderers of :before and :after
     // pseudo elements for which their parent node is returned.
     Node* generatingNode() const { return isPseudoElement() ? node()->parentOrShadowHostNode() : node(); }
 
-    Document* document() const { return m_node->document(); }
-    Frame* frame() const { return document()->frame(); }
+    Document& document() const { return m_nodeProxy.unsafeNode()->document(); }
+    Frame* frame() const { return document().frame(); }
 
     bool hasOutlineAnnotation() const;
     bool hasOutline() const { return style()->hasOutline() || hasOutlineAnnotation(); }
@@ -670,6 +673,9 @@
     void forceLayout();
     void forceChildLayout();
 
+    // True if we can abort layout, leaving a partially laid out tree.
+    virtual bool supportsPartialLayout() const { return false; }
+
     // used for element state updates that cannot be fixed with a
     // repaint and do not need a relayout
     virtual void updateFromElement() { }
@@ -755,46 +761,28 @@
     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().styleSheetCollections()->usesFirstLineRules() ? cachedFirstLineStyle() : style(); }
     RenderStyle* style(bool firstLine) const { return firstLine ? firstLineStyle() : style(); }
 
     inline Color resolveColor(const RenderStyle* styleToUse, int colorProperty) const
     {
-        StyleColor styleColor = resolveCurrentColor(styleToUse, colorProperty);
-        return styleColor.color();
+        return styleToUse->visitedDependentColor(colorProperty);
     }
 
     inline Color resolveColor(int colorProperty) const
     {
-        StyleColor styleColor = resolveCurrentColor(style(), colorProperty);
-        return styleColor.color();
+        return style()->visitedDependentColor(colorProperty);
     }
 
-    inline Color resolveColor(int colorProperty, Color fallbackIfInvalid) const
+    inline Color resolveColor(int colorProperty, Color fallback) const
     {
-        StyleColor styleColor = resolveCurrentColor(style(), colorProperty);
-        return styleColor.isValid() ? styleColor.color() : fallbackIfInvalid;
+        Color color = resolveColor(colorProperty);
+        return color.isValid() ? color : fallback;
     }
 
-    inline Color resolveColor(StyleColor color) const
+    inline Color resolveColor(Color color) const
     {
-        return resolveCurrentColor(color).color();
-    }
-
-    inline Color resolveColor(StyleColor color, Color fallbackIfInvalid) const
-    {
-        StyleColor styleColor = resolveCurrentColor(color);
-        return styleColor.isValid() ? styleColor.color() : fallbackIfInvalid;
-    }
-
-    inline StyleColor resolveStyleColor(int colorProperty) const
-    {
-        return resolveCurrentColor(style(), colorProperty);
-    }
-
-    inline StyleColor resolveStyleColor(const RenderStyle* styleToUse, int colorProperty) const
-    {
-        return resolveCurrentColor(styleToUse, colorProperty);
+        return color;
     }
 
     // Used only by Element::pseudoStyleCacheIsInvalid to get a first line style based off of a
@@ -864,7 +852,6 @@
     virtual unsigned int length() const { return 1; }
 
     bool isFloatingOrOutOfFlowPositioned() const { return (isFloating() || isOutOfFlowPositioned()); }
-    bool isFloatingWithShapeOutside() const { return isBox() && isFloating() && style()->shapeOutside(); }
 
     bool isTransparent() const { return style()->opacity() < 1.0f; }
     float opacity() const { return style()->opacity(); }
@@ -1015,7 +1002,7 @@
     virtual void insertedIntoTree();
     virtual void willBeRemovedFromTree();
 
-    void setDocumentForAnonymous(Document* document) { ASSERT(isAnonymous()); m_node = document; }
+    void setDocumentForAnonymous(Document* document) { ASSERT(isAnonymous()); m_nodeProxy.set(document); }
 
     // Add hit-test rects for the render tree rooted at this node to the provided collection on a
     // per-RenderLayer basis.
@@ -1044,37 +1031,16 @@
 
     Color selectionColor(int colorProperty) const;
 
-    inline StyleColor resolveCurrentColor(const RenderStyle* styleToUse, int colorProperty) const
-    {
-        StyleColor styleColor = styleToUse->visitedDependentColor(colorProperty);
-        if (UNLIKELY(styleColor.isCurrentColor()))
-            styleColor = styleToUse->visitedDependentColor(CSSPropertyColor);
-
-        // In the unlikely case that CSSPropertyColor is also 'currentColor'
-        // the color of the nearest ancestor with a valid color is used.
-        for (const RenderObject* object = this; UNLIKELY(styleColor.isCurrentColor()) && object && object->style(); object = object->parent())
-            styleColor = object->style()->visitedDependentColor(CSSPropertyColor);
-
-        return styleColor;
-    }
-
-    inline StyleColor resolveCurrentColor(StyleColor color) const
-    {
-        StyleColor styleColor = color;
-        for (const RenderObject* object = this; UNLIKELY(styleColor.isCurrentColor()) && object && object->style(); object = object->parent())
-            styleColor = object->style()->visitedDependentColor(CSSPropertyColor);
-        return styleColor;
-    }
-
     void removeShapeImageClient(ShapeValue*);
 
 #ifndef NDEBUG
     void checkBlockPositionedObjectsNeedLayout();
+    void checkNotInPartialLayout();
 #endif
 
     RefPtr<RenderStyle> m_style;
 
-    Node* m_node;
+    RenderingNodeProxy m_nodeProxy;
 
     RenderObject* m_parent;
     RenderObject* m_previous;
@@ -1210,7 +1176,7 @@
 
 inline bool RenderObject::documentBeingDestroyed() const
 {
-    return !document()->renderer();
+    return !document().renderer();
 }
 
 inline bool RenderObject::isBeforeContent() const
@@ -1240,6 +1206,9 @@
 
 inline void RenderObject::setNeedsLayout(MarkingBehavior markParents, SubtreeLayoutScope* layouter)
 {
+#ifndef NDEBUG
+    checkNotInPartialLayout();
+#endif
     ASSERT(!isSetNeedsLayoutForbidden());
     bool alreadyNeededLayout = m_bitfields.selfNeedsLayout();
     setSelfNeedsLayout(true);
@@ -1253,6 +1222,9 @@
 
 inline void RenderObject::clearNeedsLayout()
 {
+#ifndef NDEBUG
+    checkNotInPartialLayout();
+#endif
     setSelfNeedsLayout(false);
     setEverHadLayout(true);
     setPosChildNeedsLayout(false);
diff --git a/Source/core/rendering/RenderObjectChildList.cpp b/Source/core/rendering/RenderObjectChildList.cpp
index 2f3b471..ebb86f7 100644
--- a/Source/core/rendering/RenderObjectChildList.cpp
+++ b/Source/core/rendering/RenderObjectChildList.cpp
@@ -109,7 +109,7 @@
     if (!owner->documentBeingDestroyed())
         RenderCounter::rendererRemovedFromTree(oldChild);
 
-    if (AXObjectCache* cache = owner->document()->existingAXObjectCache())
+    if (AXObjectCache* cache = owner->document().existingAXObjectCache())
         cache->childrenChanged(owner);
 
     return oldChild;
@@ -118,7 +118,7 @@
 void RenderObjectChildList::insertChildNode(RenderObject* owner, RenderObject* newChild, RenderObject* beforeChild, bool notifyRenderer)
 {
     ASSERT(!newChild->parent());
-    ASSERT(!owner->isBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
+    ASSERT(!owner->isRenderBlockFlow() || (!newChild->isTableSection() && !newChild->isTableRow() && !newChild->isTableCell()));
 
     while (beforeChild && beforeChild->parent() && beforeChild->parent() != owner)
         beforeChild = beforeChild->parent();
@@ -161,7 +161,7 @@
     if (!owner->normalChildNeedsLayout())
         owner->setChildNeedsLayout(); // We may supply the static position for an absolute positioned child.
 
-    if (AXObjectCache* cache = owner->document()->axObjectCache())
+    if (AXObjectCache* cache = owner->document().axObjectCache())
         cache->childrenChanged(owner);
 }
 
diff --git a/Source/core/rendering/RenderPart.cpp b/Source/core/rendering/RenderPart.cpp
index fa73e5e..4670fc7 100644
--- a/Source/core/rendering/RenderPart.cpp
+++ b/Source/core/rendering/RenderPart.cpp
@@ -26,7 +26,6 @@
 #include "core/rendering/RenderPart.h"
 
 #include "core/html/HTMLFrameElementBase.h"
-#include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/plugins/PluginView.h"
 #include "core/rendering/HitTestResult.h"
diff --git a/Source/core/rendering/RenderProgress.cpp b/Source/core/rendering/RenderProgress.cpp
index 88b961f..1454d3c 100644
--- a/Source/core/rendering/RenderProgress.cpp
+++ b/Source/core/rendering/RenderProgress.cpp
@@ -32,7 +32,7 @@
 namespace WebCore {
 
 RenderProgress::RenderProgress(HTMLElement* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
     , m_position(HTMLProgressElement::InvalidPosition)
     , m_animationStartTime(0)
     , m_animationRepeatInterval(0)
diff --git a/Source/core/rendering/RenderProgress.h b/Source/core/rendering/RenderProgress.h
index 6484536..aa7a052 100644
--- a/Source/core/rendering/RenderProgress.h
+++ b/Source/core/rendering/RenderProgress.h
@@ -21,13 +21,13 @@
 #ifndef RenderProgress_h
 #define RenderProgress_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
 class HTMLProgressElement;
 
-class RenderProgress FINAL : public RenderBlock {
+class RenderProgress FINAL : public RenderBlockFlow {
 public:
     explicit RenderProgress(HTMLElement*);
     virtual ~RenderProgress();
@@ -45,6 +45,7 @@
     virtual const char* renderName() const { return "RenderProgress"; }
     virtual bool isProgress() const { return true; }
     virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual bool canBeReplacedWithInlineRunIn() const OVERRIDE;
 
     void animationTimerFired(Timer<RenderProgress>*);
diff --git a/Source/core/rendering/RenderQuote.cpp b/Source/core/rendering/RenderQuote.cpp
index 22623c6..d6e308e 100644
--- a/Source/core/rendering/RenderQuote.cpp
+++ b/Source/core/rendering/RenderQuote.cpp
@@ -266,7 +266,7 @@
     while (RenderObject* child = lastChild())
         child->destroy();
 
-    RenderTextFragment* fragment = new RenderTextFragment(document(), m_text.impl());
+    RenderTextFragment* fragment = new RenderTextFragment(&document(), m_text.impl());
     fragment->setStyle(style());
     addChild(fragment);
 }
diff --git a/Source/core/rendering/RenderRegion.cpp b/Source/core/rendering/RenderRegion.cpp
index 1654c72..651b888 100644
--- a/Source/core/rendering/RenderRegion.cpp
+++ b/Source/core/rendering/RenderRegion.cpp
@@ -42,7 +42,7 @@
 namespace WebCore {
 
 RenderRegion::RenderRegion(Element* element, RenderFlowThread* flowThread)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
     , m_flowThread(flowThread)
     , m_parentNamedFlowThread(0)
     , m_computedAutoHeight(-1)
@@ -209,7 +209,7 @@
     // FIXME: Region styling doesn't work for pseudo elements.
     if (node()) {
         Element* regionElement = toElement(node());
-        customRegionStyle = view()->document()->styleResolver()->checkRegionStyle(regionElement);
+        customRegionStyle = view()->document().styleResolver()->checkRegionStyle(regionElement);
     }
     setHasCustomRegionStyle(customRegionStyle);
     m_flowThread->checkRegionsWithStyling();
@@ -253,7 +253,9 @@
 {
     bool hasSpecifiedEndpointsForHeight = style()->logicalTop().isSpecified() && style()->logicalBottom().isSpecified();
     bool hasAnchoredEndpointsForHeight = isOutOfFlowPositioned() && hasSpecifiedEndpointsForHeight;
-    return style()->logicalHeight().isAuto() && !hasAnchoredEndpointsForHeight;
+    bool hasAutoHeightStyle = style()->logicalHeight().isAuto() || style()->logicalHeight().isFitContent()
+        || style()->logicalHeight().isMaxContent() || style()->logicalHeight().isMinContent();
+    return hasAutoHeightStyle && !hasAnchoredEndpointsForHeight;
 }
 
 void RenderRegion::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
@@ -277,7 +279,7 @@
 
 void RenderRegion::layoutBlock(bool relayoutChildren, LayoutUnit)
 {
-    RenderBlock::layoutBlock(relayoutChildren);
+    RenderBlockFlow::layoutBlock(relayoutChildren);
 
     if (isValid()) {
         LayoutRect oldRegionRect(flowThreadPortionRect());
@@ -536,13 +538,12 @@
 {
     ASSERT(object);
     ASSERT(object->view());
-    ASSERT(object->view()->document());
     ASSERT(!object->isAnonymous());
     ASSERT(object->node() && object->node()->isElementNode());
 
     // FIXME: Region styling fails for pseudo-elements because the renderers don't have a node.
     Element* element = toElement(object->node());
-    RefPtr<RenderStyle> renderObjectRegionStyle = object->view()->document()->styleResolver()->styleForElement(element, 0, DisallowStyleSharing, MatchAllRules, this);
+    RefPtr<RenderStyle> renderObjectRegionStyle = object->view()->document().styleResolver()->styleForElement(element, 0, DisallowStyleSharing, MatchAllRules, this);
 
     return renderObjectRegionStyle.release();
 }
diff --git a/Source/core/rendering/RenderRegion.h b/Source/core/rendering/RenderRegion.h
index 052c059..2d9988d 100644
--- a/Source/core/rendering/RenderRegion.h
+++ b/Source/core/rendering/RenderRegion.h
@@ -30,7 +30,7 @@
 #ifndef RenderRegion_h
 #define RenderRegion_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/style/StyleInheritedData.h"
 
 namespace WebCore {
@@ -42,7 +42,7 @@
 class RenderFlowThread;
 class RenderNamedFlowThread;
 
-class RenderRegion : public RenderBlock {
+class RenderRegion : public RenderBlockFlow {
 public:
     explicit RenderRegion(Element*, RenderFlowThread*);
 
@@ -164,6 +164,7 @@
     virtual void willBeRemovedFromTree() OVERRIDE;
 
     virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE;
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual void paintObject(PaintInfo&, const LayoutPoint&) OVERRIDE;
 
     virtual void installFlowThread();
diff --git a/Source/core/rendering/RenderReplaced.cpp b/Source/core/rendering/RenderReplaced.cpp
index 328ad77..596957a 100644
--- a/Source/core/rendering/RenderReplaced.cpp
+++ b/Source/core/rendering/RenderReplaced.cpp
@@ -128,7 +128,7 @@
     if (!paintInfo.shouldPaintWithinRoot(this))
         return;
 
-    bool drawSelectionTint = selectionState() != SelectionNone && !document()->printing();
+    bool drawSelectionTint = selectionState() != SelectionNone && !document().printing();
     if (paintInfo.phase == PaintPhaseSelection) {
         if (selectionState() == SelectionNone)
             return;
diff --git a/Source/core/rendering/RenderRuby.cpp b/Source/core/rendering/RenderRuby.cpp
index 3459add..13e2b04 100644
--- a/Source/core/rendering/RenderRuby.cpp
+++ b/Source/core/rendering/RenderRuby.cpp
@@ -85,7 +85,7 @@
 static RenderBlock* createAnonymousRubyInlineBlock(RenderObject* ruby)
 {
     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(ruby->style(), INLINE_BLOCK);
-    RenderBlock* newBlock = RenderBlock::createAnonymous(ruby->document());
+    RenderBlock* newBlock = RenderBlock::createAnonymous(&ruby->document());
     newBlock->setStyle(newStyle.release());
     return newBlock;
 }
@@ -215,7 +215,7 @@
 //=== ruby as block object ===
 
 RenderRubyAsBlock::RenderRubyAsBlock(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
 }
 
diff --git a/Source/core/rendering/RenderRuby.h b/Source/core/rendering/RenderRuby.h
index e254b05..d9da35b 100644
--- a/Source/core/rendering/RenderRuby.h
+++ b/Source/core/rendering/RenderRuby.h
@@ -31,7 +31,7 @@
 #ifndef RenderRuby_h
 #define RenderRuby_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderInline.h"
 
 namespace WebCore {
@@ -65,12 +65,13 @@
 private:
     virtual bool isRuby() const { return true; }
     virtual const char* renderName() const { return "RenderRuby (inline)"; }
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual bool createsAnonymousWrapper() const { return true; }
     virtual void removeLeftoverAnonymousBlock(RenderBlock*) { ASSERT_NOT_REACHED(); }
 };
 
 // <ruby> when used as 'display:block' or 'display:inline-block'
-class RenderRubyAsBlock FINAL : public RenderBlock {
+class RenderRubyAsBlock FINAL : public RenderBlockFlow {
 public:
     RenderRubyAsBlock(Element*);
     virtual ~RenderRubyAsBlock();
@@ -84,6 +85,7 @@
 private:
     virtual bool isRuby() const { return true; }
     virtual const char* renderName() const { return "RenderRuby (block)"; }
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual bool createsAnonymousWrapper() const { return true; }
     virtual void removeLeftoverAnonymousBlock(RenderBlock*) { ASSERT_NOT_REACHED(); }
 };
diff --git a/Source/core/rendering/RenderRubyBase.cpp b/Source/core/rendering/RenderRubyBase.cpp
index 2de4aeb..e32478e 100644
--- a/Source/core/rendering/RenderRubyBase.cpp
+++ b/Source/core/rendering/RenderRubyBase.cpp
@@ -38,7 +38,7 @@
 namespace WebCore {
 
 RenderRubyBase::RenderRubyBase()
-    : RenderBlock(0)
+    : RenderBlockFlow(0)
 {
     setInline(false);
 }
diff --git a/Source/core/rendering/RenderRubyBase.h b/Source/core/rendering/RenderRubyBase.h
index 4d1f56d..197aebb 100644
--- a/Source/core/rendering/RenderRubyBase.h
+++ b/Source/core/rendering/RenderRubyBase.h
@@ -31,13 +31,13 @@
 #ifndef RenderRubyBase_h
 #define RenderRubyBase_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
 class RenderRubyRun;
 
-class RenderRubyBase FINAL : public RenderBlock {
+class RenderRubyBase FINAL : public RenderBlockFlow {
 public:
     virtual ~RenderRubyBase();
 
@@ -55,6 +55,8 @@
     virtual ETextAlign textAlignmentForLine(bool endsWithSoftBreak) const;
     virtual void adjustInlineDirectionLineBounds(int expansionOpportunityCount, float& logicalLeft, float& logicalWidth) const;
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     void moveChildren(RenderRubyBase* toBase, RenderObject* beforeChild = 0);
     void moveInlineChildren(RenderRubyBase* toBase, RenderObject* beforeChild = 0);
     void moveBlockChildren(RenderRubyBase* toBase, RenderObject* beforeChild = 0);
diff --git a/Source/core/rendering/RenderRubyRun.cpp b/Source/core/rendering/RenderRubyRun.cpp
index ac71877..85d00e2 100644
--- a/Source/core/rendering/RenderRubyRun.cpp
+++ b/Source/core/rendering/RenderRubyRun.cpp
@@ -41,7 +41,7 @@
 namespace WebCore {
 
 RenderRubyRun::RenderRubyRun()
-    : RenderBlock(0)
+    : RenderBlockFlow(0)
 {
     setReplaced(true);
     setInline(true);
@@ -197,7 +197,7 @@
 
 RenderRubyBase* RenderRubyRun::createRubyBase() const
 {
-    RenderRubyBase* renderer = RenderRubyBase::createAnonymous(document());
+    RenderRubyBase* renderer = RenderRubyBase::createAnonymous(&document());
     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK);
     newStyle->setTextAlign(CENTER); // FIXME: use WEBKIT_CENTER?
     renderer->setStyle(newStyle.release());
@@ -208,7 +208,7 @@
 {
     ASSERT(parentRuby && parentRuby->isRuby());
     RenderRubyRun* rr = new RenderRubyRun();
-    rr->setDocumentForAnonymous(parentRuby->document());
+    rr->setDocumentForAnonymous(&parentRuby->document());
     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parentRuby->style(), INLINE_BLOCK);
     rr->setStyle(newStyle.release());
     return rr;
diff --git a/Source/core/rendering/RenderRubyRun.h b/Source/core/rendering/RenderRubyRun.h
index 37a1ee3..ebf642b 100644
--- a/Source/core/rendering/RenderRubyRun.h
+++ b/Source/core/rendering/RenderRubyRun.h
@@ -31,7 +31,7 @@
 #ifndef RenderRubyRun_h
 #define RenderRubyRun_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
@@ -41,7 +41,7 @@
 // RenderRubyRun are 'inline-block/table' like objects,and wrap a single pairing of a ruby base with its ruby text(s).
 // See RenderRuby.h for further comments on the structure
 
-class RenderRubyRun FINAL : public RenderBlock {
+class RenderRubyRun FINAL : public RenderBlockFlow {
 public:
     virtual ~RenderRubyRun();
 
@@ -74,6 +74,7 @@
 
     virtual bool isRubyRun() const { return true; }
     virtual const char* renderName() const { return "RenderRubyRun (anonymous)"; }
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual bool createsAnonymousWrapper() const { return true; }
     virtual void removeLeftoverAnonymousBlock(RenderBlock*) { }
 };
diff --git a/Source/core/rendering/RenderRubyText.cpp b/Source/core/rendering/RenderRubyText.cpp
index 0d4dba1..585205f 100644
--- a/Source/core/rendering/RenderRubyText.cpp
+++ b/Source/core/rendering/RenderRubyText.cpp
@@ -38,7 +38,7 @@
 namespace WebCore {
 
 RenderRubyText::RenderRubyText(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
 }
 
diff --git a/Source/core/rendering/RenderRubyText.h b/Source/core/rendering/RenderRubyText.h
index 3d38776..b1cb992 100644
--- a/Source/core/rendering/RenderRubyText.h
+++ b/Source/core/rendering/RenderRubyText.h
@@ -31,11 +31,11 @@
 #ifndef RenderRubyText_h
 #define RenderRubyText_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
-class RenderRubyText FINAL : public RenderBlock {
+class RenderRubyText FINAL : public RenderBlockFlow {
 public:
     RenderRubyText(Element*);
     virtual ~RenderRubyText();
@@ -49,6 +49,8 @@
 private:
     virtual bool avoidsFloats() const;
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     virtual ETextAlign textAlignmentForLine(bool endsWithSoftBreak) const;
     virtual void adjustInlineDirectionLineBounds(int expansionOpportunityCount, float& logicalLeft, float& logicalWidth) const;
 };
diff --git a/Source/core/rendering/RenderScrollbar.cpp b/Source/core/rendering/RenderScrollbar.cpp
index 9612040..2cef428 100644
--- a/Source/core/rendering/RenderScrollbar.cpp
+++ b/Source/core/rendering/RenderScrollbar.cpp
@@ -252,7 +252,7 @@
 
     RenderScrollbarPart* partRenderer = m_parts.get(partType);
     if (!partRenderer && needRenderer) {
-        partRenderer = RenderScrollbarPart::createAnonymous(owningRenderer()->document(), this, partType);
+        partRenderer = RenderScrollbarPart::createAnonymous(&owningRenderer()->document(), this, partType);
         m_parts.set(partType, partRenderer);
     } else if (partRenderer && !needRenderer) {
         m_parts.remove(partType);
diff --git a/Source/core/rendering/RenderScrollbarPart.h b/Source/core/rendering/RenderScrollbarPart.h
index b2331cd..fadaea7 100644
--- a/Source/core/rendering/RenderScrollbarPart.h
+++ b/Source/core/rendering/RenderScrollbarPart.h
@@ -66,6 +66,8 @@
 
     virtual void computePreferredLogicalWidths();
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     void layoutHorizontalPart();
     void layoutVerticalPart();
 
diff --git a/Source/core/rendering/RenderTable.cpp b/Source/core/rendering/RenderTable.cpp
index b86ee3c..bf35210 100644
--- a/Source/core/rendering/RenderTable.cpp
+++ b/Source/core/rendering/RenderTable.cpp
@@ -267,7 +267,7 @@
         LayoutUnit availableContentLogicalWidth = max<LayoutUnit>(0, containerWidthInInlineDirection - marginTotal);
         if (shrinkToAvoidFloats() && cb->containsFloats() && !hasPerpendicularContainingBlock) {
             // FIXME: Work with regions someday.
-            availableContentLogicalWidth = shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, 0, 0);
+            availableContentLogicalWidth = shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, 0);
         }
 
         // Ensure we aren't bigger than our available width.
@@ -298,7 +298,7 @@
     if (!hasPerpendicularContainingBlock) {
         LayoutUnit containerLogicalWidthForAutoMargins = availableLogicalWidth;
         if (avoidsFloats() && cb->containsFloats())
-            containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(0, 0); // FIXME: Work with regions someday.
+            containerLogicalWidthForAutoMargins = containingBlockAvailableLineWidthInRegion(0); // FIXME: Work with regions someday.
         ComputedMarginValues marginValues;
         bool hasInvertedDirection =  cb->style()->isLeftToRightDirection() == style()->isLeftToRightDirection();
         computeInlineDirectionMargins(cb, containerLogicalWidthForAutoMargins, logicalWidth(),
@@ -508,7 +508,7 @@
     for (RenderTableSection* section = topSection(); section; section = sectionBelow(section))
         section->layoutRows();
 
-    if (!topSection() && computedLogicalHeight > totalSectionLogicalHeight && !document()->inQuirksMode()) {
+    if (!topSection() && computedLogicalHeight > totalSectionLogicalHeight && !document().inQuirksMode()) {
         // Completely empty tables (with no sections or anything) should at least honor specified height
         // in strict mode.
         setLogicalHeight(logicalHeight() + computedLogicalHeight);
@@ -1424,7 +1424,7 @@
 {
     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), TABLE);
     RenderTable* newTable = new RenderTable(0);
-    newTable->setDocumentForAnonymous(parent->document());
+    newTable->setDocumentForAnonymous(&parent->document());
     newTable->setStyle(newStyle.release());
     return newTable;
 }
diff --git a/Source/core/rendering/RenderTable.h b/Source/core/rendering/RenderTable.h
index bdc1a3d..686d943 100644
--- a/Source/core/rendering/RenderTable.h
+++ b/Source/core/rendering/RenderTable.h
@@ -278,6 +278,7 @@
     virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&);
     virtual void paintMask(PaintInfo&, const LayoutPoint&);
     virtual void layout();
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth) const OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE;
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
diff --git a/Source/core/rendering/RenderTableCaption.cpp b/Source/core/rendering/RenderTableCaption.cpp
index 171ebb2..e35acc5 100644
--- a/Source/core/rendering/RenderTableCaption.cpp
+++ b/Source/core/rendering/RenderTableCaption.cpp
@@ -25,7 +25,7 @@
 namespace WebCore {
 
 RenderTableCaption::RenderTableCaption(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
 }
 
diff --git a/Source/core/rendering/RenderTableCaption.h b/Source/core/rendering/RenderTableCaption.h
index 79b894d..711bbb7 100644
--- a/Source/core/rendering/RenderTableCaption.h
+++ b/Source/core/rendering/RenderTableCaption.h
@@ -20,13 +20,13 @@
 #ifndef RenderTableCaption_h
 #define RenderTableCaption_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
 class RenderTable;
 
-class RenderTableCaption FINAL : public RenderBlock {
+class RenderTableCaption FINAL : public RenderBlockFlow {
 public:
     explicit RenderTableCaption(Element*);
     virtual ~RenderTableCaption();
@@ -35,6 +35,8 @@
 private:
     virtual bool isTableCaption() const OVERRIDE { return true; }
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     virtual void insertedIntoTree() OVERRIDE;
     virtual void willBeRemovedFromTree() OVERRIDE;
 
diff --git a/Source/core/rendering/RenderTableCell.cpp b/Source/core/rendering/RenderTableCell.cpp
index b1badb2..3782283 100644
--- a/Source/core/rendering/RenderTableCell.cpp
+++ b/Source/core/rendering/RenderTableCell.cpp
@@ -43,7 +43,7 @@
 
 using namespace HTMLNames;
 
-struct SameSizeAsRenderTableCell : public RenderBlock {
+struct SameSizeAsRenderTableCell : public RenderBlockFlow {
     unsigned bitfields;
     int paddings[2];
 };
@@ -52,7 +52,7 @@
 COMPILE_ASSERT(sizeof(CollapsedBorderValue) == 8, CollapsedBorderValue_should_stay_small);
 
 RenderTableCell::RenderTableCell(Element* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
     , m_column(unsetColumnIndex)
     , m_cellWidthChanged(false)
     , m_intrinsicPaddingBefore(0)
@@ -1170,7 +1170,7 @@
     if (backgroundObject != this)
         adjustedPaintOffset.moveBy(location());
 
-    StyleColor c = backgroundObject->resolveStyleColor(CSSPropertyBackgroundColor);
+    Color c = backgroundObject->resolveColor(CSSPropertyBackgroundColor);
     const FillLayer* bgLayer = backgroundObject->style()->backgroundLayers();
 
     if (bgLayer->hasImage() || c.isValid()) {
@@ -1183,7 +1183,7 @@
                 width() - borderLeft() - borderRight(), height() - borderTop() - borderBottom());
             paintInfo.context->clip(clipRect);
         }
-        paintFillLayers(paintInfo, c.color(), bgLayer, LayoutRect(adjustedPaintOffset, pixelSnappedSize()), BackgroundBleedNone, CompositeSourceOver, backgroundObject);
+        paintFillLayers(paintInfo, c, bgLayer, LayoutRect(adjustedPaintOffset, pixelSnappedSize()), BackgroundBleedNone, CompositeSourceOver, backgroundObject);
     }
 }
 
@@ -1260,7 +1260,7 @@
 
 RenderTableCell* RenderTableCell::createAnonymousWithParentRenderer(const RenderObject* parent)
 {
-    RenderTableCell* newCell = RenderTableCell::createAnonymous(parent->document());
+    RenderTableCell* newCell = RenderTableCell::createAnonymous(&parent->document());
     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), TABLE_CELL);
     newCell->setStyle(newStyle.release());
     return newCell;
diff --git a/Source/core/rendering/RenderTableCell.h b/Source/core/rendering/RenderTableCell.h
index 9a0da52..29439c5 100644
--- a/Source/core/rendering/RenderTableCell.h
+++ b/Source/core/rendering/RenderTableCell.h
@@ -25,6 +25,7 @@
 #ifndef RenderTableCell_h
 #define RenderTableCell_h
 
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderTableRow.h"
 #include "core/rendering/RenderTableSection.h"
 
@@ -37,7 +38,7 @@
 
 class SubtreeLayoutScope;
 
-class RenderTableCell FINAL : public RenderBlock {
+class RenderTableCell FINAL : public RenderBlockFlow {
 public:
     explicit RenderTableCell(Element*);
 
@@ -99,7 +100,7 @@
         int styleLogicalHeight = valueForLength(style()->logicalHeight(), 0, view());
         // In strict mode, box-sizing: content-box do the right thing and actually add in the border and padding.
         // Call computedCSSPadding* directly to avoid including implicitPadding.
-        if (!document()->inQuirksMode() && style()->boxSizing() != BORDER_BOX)
+        if (!document().inQuirksMode() && style()->boxSizing() != BORDER_BOX)
             styleLogicalHeight += (computedCSSPaddingBefore() + computedCSSPaddingAfter()).floor() + borderBefore() + borderAfter();
         return max(styleLogicalHeight, adjustedLogicalHeight);
     }
@@ -121,6 +122,8 @@
 
     virtual void layout();
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     virtual void paint(PaintInfo&, const LayoutPoint&);
 
     void paintCollapsedBorders(PaintInfo&, const LayoutPoint&);
diff --git a/Source/core/rendering/RenderTableCol.cpp b/Source/core/rendering/RenderTableCol.cpp
index 92d444b..48a537d 100644
--- a/Source/core/rendering/RenderTableCol.cpp
+++ b/Source/core/rendering/RenderTableCol.cpp
@@ -61,7 +61,7 @@
     unsigned oldSpan = m_span;
     Node* n = node();
     if (n && (n->hasTagName(colTag) || n->hasTagName(colgroupTag))) {
-        HTMLTableColElement* tc = static_cast<HTMLTableColElement*>(n);
+        HTMLTableColElement* tc = toHTMLTableColElement(n);
         m_span = tc->span();
     } else
         m_span = !(style() && style()->display() == TABLE_COLUMN_GROUP);
diff --git a/Source/core/rendering/RenderTableRow.cpp b/Source/core/rendering/RenderTableRow.cpp
index 27de4d7..d3f45f7 100644
--- a/Source/core/rendering/RenderTableRow.cpp
+++ b/Source/core/rendering/RenderTableRow.cpp
@@ -275,7 +275,7 @@
 
 RenderTableRow* RenderTableRow::createAnonymousWithParentRenderer(const RenderObject* parent)
 {
-    RenderTableRow* newRow = RenderTableRow::createAnonymous(parent->document());
+    RenderTableRow* newRow = RenderTableRow::createAnonymous(&parent->document());
     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), TABLE_ROW);
     newRow->setStyle(newStyle.release());
     return newRow;
diff --git a/Source/core/rendering/RenderTableSection.cpp b/Source/core/rendering/RenderTableSection.cpp
index fb22ad1..4fb5a07 100644
--- a/Source/core/rendering/RenderTableSection.cpp
+++ b/Source/core/rendering/RenderTableSection.cpp
@@ -370,20 +370,29 @@
     extraRowSpanningHeight -= accumulatedPositionIncrease;
 }
 
-// To avoid unneeded extra height distributions, we apply the following sorting algorithm:
-// 1. We sort by increasing start row but decreasing last row (ie the top-most, shortest cells first).
-// 2. For cells spanning the same rows, we sort by intrinsic size.
-static bool compareRowSpanCellsInHeightDistributionOrder(const RenderTableCell* cell2, const RenderTableCell* cell1)
+static bool cellIsFullyIncludedInOtherCell(const RenderTableCell* cell1, const RenderTableCell* cell2)
 {
-    unsigned cellRowIndex1 = cell1->rowIndex();
-    unsigned cellRowSpan1 = cell1->rowSpan();
-    unsigned cellRowIndex2 = cell2->rowIndex();
-    unsigned cellRowSpan2 = cell2->rowSpan();
+    return (cell1->rowIndex() >= cell2->rowIndex() && (cell1->rowIndex() + cell1->rowSpan()) <= (cell2->rowIndex() + cell2->rowSpan()));
+}
 
-    if (cellRowIndex1 == cellRowIndex2 && cellRowSpan1 == cellRowSpan2)
-        return (cell2->logicalHeightForRowSizing() > cell1->logicalHeightForRowSizing());
+// To avoid unneeded extra height distributions, we apply the following sorting algorithm:
+static bool compareRowSpanCellsInHeightDistributionOrder(const RenderTableCell* cell1, const RenderTableCell* cell2)
+{
+    // Sorting bigger height cell first if cells are at same index with same span because we will skip smaller
+    // height cell to distribute it's extra height.
+    if (cell1->rowIndex() == cell2->rowIndex() && cell1->rowSpan() == cell2->rowSpan())
+        return (cell1->logicalHeightForRowSizing() > cell2->logicalHeightForRowSizing());
+    // Sorting inner most cell first because if inner spanning cell'e extra height is distributed then outer
+    // spanning cell's extra height will adjust accordingly. In reverse order, there is more chances that outer
+    // spanning cell's height will exceed than defined by user.
+    if (cellIsFullyIncludedInOtherCell(cell1, cell2))
+        return true;
+    // Sorting lower row index first because first we need to apply the extra height of spanning cell which
+    // comes first in the table so lower rows's position would increment in sequence.
+    if (cellIsFullyIncludedInOtherCell(cell2, cell1))
+        return (cell1->rowIndex() < cell2->rowIndex());
 
-    return (cellRowIndex2 >= cellRowIndex1 && (cellRowIndex2 + cellRowSpan2) <= (cellRowIndex1 + cellRowSpan1));
+    return false;
 }
 
 // Distribute rowSpan cell height in rows those comes in rowSpan cell based on the ratio of row's height if
@@ -511,7 +520,12 @@
     LayoutStateMaintainer statePusher(viewRenderer);
 
     m_rowPos.resize(m_grid.size() + 1);
-    m_rowPos[0] = table()->vBorderSpacing();
+
+    // We ignore the border-spacing on any non-top section as it is already included in the previous section's last row position.
+    if (this == table()->topSection())
+        m_rowPos[0] = table()->vBorderSpacing();
+    else
+        m_rowPos[0] = 0;
 
     SpanningRenderTableCells rowSpanCells;
 
@@ -1157,11 +1171,7 @@
 {
     ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
 
-    // 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;
+    ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
 
     unsigned totalRows = m_grid.size();
     unsigned totalCols = table()->columns().size();
@@ -1667,7 +1677,7 @@
 {
     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), TABLE_ROW_GROUP);
     RenderTableSection* newSection = new RenderTableSection(0);
-    newSection->setDocumentForAnonymous(parent->document());
+    newSection->setDocumentForAnonymous(&parent->document());
     newSection->setStyle(newStyle.release());
     return newSection;
 }
diff --git a/Source/core/rendering/RenderText.cpp b/Source/core/rendering/RenderText.cpp
index d070190..6e1703a 100644
--- a/Source/core/rendering/RenderText.cpp
+++ b/Source/core/rendering/RenderText.cpp
@@ -27,7 +27,7 @@
 
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/Text.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/page/FrameView.h"
 #include "core/page/Settings.h"
 #include "core/platform/graphics/FloatQuad.h"
@@ -74,7 +74,7 @@
     void restartWithNewText(unsigned lastTypedCharacterOffset)
     {
         m_lastTypedCharacterOffset = lastTypedCharacterOffset;
-        if (Settings* settings = m_renderText->document()->settings())
+        if (Settings* settings = m_renderText->document().settings())
             startOneShot(settings->passwordEchoDurationInSeconds());
     }
     void invalidate() { m_lastTypedCharacterOffset = -1; }
@@ -186,7 +186,7 @@
 
 void RenderText::updateNeedsTranscoding()
 {
-    const WTF::TextEncoding* encoding = document()->decoder() ? &document()->decoder()->encoding() : 0;
+    const WTF::TextEncoding* encoding = document().decoder() ? &document().decoder()->encoding() : 0;
     m_needsTranscoding = fontTranscoder().needsTranscoding(style()->font().fontDescription(), encoding);
 }
 
@@ -1329,7 +1329,7 @@
     ASSERT(text);
     m_text = text;
     if (m_needsTranscoding) {
-        const WTF::TextEncoding* encoding = document()->decoder() ? &document()->decoder()->encoding() : 0;
+        const WTF::TextEncoding* encoding = document().decoder() ? &document().decoder()->encoding() : 0;
         fontTranscoder().convert(m_text, style()->font().fontDescription(), encoding);
     }
     ASSERT(m_text);
@@ -1393,7 +1393,7 @@
     setNeedsLayoutAndPrefWidthsRecalc();
     m_knownToHaveNoOverflowAndNoFallbackFonts = false;
 
-    if (AXObjectCache* cache = document()->existingAXObjectCache())
+    if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->textChanged(this);
 }
 
@@ -1671,7 +1671,7 @@
     return result;
 }
 
-#if OS(DARWIN)
+#if OS(MACOSX)
 
 #define HANGUL_CHOSEONG_START (0x1100)
 #define HANGUL_CHOSEONG_END (0x115F)
@@ -1713,7 +1713,7 @@
 
 int RenderText::previousOffsetForBackwardDeletion(int current) const
 {
-#if OS(DARWIN)
+#if OS(MACOSX)
     ASSERT(m_text);
     StringImpl& text = *m_text.impl();
     UChar32 character;
diff --git a/Source/core/rendering/RenderText.h b/Source/core/rendering/RenderText.h
index 7579704..1a49794 100644
--- a/Source/core/rendering/RenderText.h
+++ b/Source/core/rendering/RenderText.h
@@ -24,7 +24,6 @@
 #define RenderText_h
 
 #include "core/rendering/RenderObject.h"
-#include "core/rendering/RenderView.h"
 #include "wtf/Forward.h"
 
 namespace WebCore {
diff --git a/Source/core/rendering/RenderTextControl.cpp b/Source/core/rendering/RenderTextControl.cpp
index 55e49e1..38e54c6 100644
--- a/Source/core/rendering/RenderTextControl.cpp
+++ b/Source/core/rendering/RenderTextControl.cpp
@@ -33,7 +33,7 @@
 namespace WebCore {
 
 RenderTextControl::RenderTextControl(HTMLTextFormControlElement* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
     ASSERT(element);
 }
diff --git a/Source/core/rendering/RenderTextControl.h b/Source/core/rendering/RenderTextControl.h
index d4d46c3..baf8e77 100644
--- a/Source/core/rendering/RenderTextControl.h
+++ b/Source/core/rendering/RenderTextControl.h
@@ -22,14 +22,14 @@
 #ifndef RenderTextControl_h
 #define RenderTextControl_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderFlexibleBox.h"
 
 namespace WebCore {
 
 class HTMLTextFormControlElement;
 
-class RenderTextControl : public RenderBlock {
+class RenderTextControl : public RenderBlockFlow {
 public:
     virtual ~RenderTextControl();
 
@@ -67,6 +67,7 @@
 private:
     virtual const char* renderName() const { return "RenderTextControl"; }
     virtual bool isTextControl() const { return true; }
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
     virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
     virtual void computePreferredLogicalWidths() OVERRIDE;
     virtual void removeLeftoverAnonymousBlock(RenderBlock*) { }
@@ -115,7 +116,7 @@
     }
     virtual int firstLineBoxBaseline() const OVERRIDE { return RenderBlock::firstLineBoxBaseline(); }
     virtual int inlineBlockBaseline(LineDirectionMode direction) const OVERRIDE { return lastLineBoxBaseline(direction); }
-
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 };
 
 
diff --git a/Source/core/rendering/RenderTextControlSingleLine.cpp b/Source/core/rendering/RenderTextControlSingleLine.cpp
index 49611a6..98fcf40 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.cpp
+++ b/Source/core/rendering/RenderTextControlSingleLine.cpp
@@ -116,7 +116,7 @@
         layoutScope.setNeedsLayout(innerBlockRenderer);
     }
 
-    RenderBlock::layoutBlock(false);
+    RenderBlockFlow::layoutBlock(false);
 
     HTMLElement* container = containerElement();
     RenderBox* containerRenderer = container ? container->renderBox() : 0;
@@ -153,7 +153,7 @@
 
     // If we need another layout pass, we have changed one of children's height so we need to relayout them.
     if (needsLayout())
-        RenderBlock::layoutBlock(true);
+        RenderBlockFlow::layoutBlock(true);
 
     // Center the child block in the block progression direction (vertical centering for horizontal text fields).
     if (!container && innerTextRenderer && innerTextRenderer->height() != contentLogicalHeight()) {
@@ -253,7 +253,7 @@
 
 void RenderTextControlSingleLine::capsLockStateMayHaveChanged()
 {
-    if (!node() || !document())
+    if (!node())
         return;
 
     // Only draw the caps lock indicator if these things are true:
@@ -263,8 +263,8 @@
     // 4) The caps lock is on
     bool shouldDrawCapsLockIndicator = false;
 
-    if (Frame* frame = document()->frame())
-        shouldDrawCapsLockIndicator = inputElement()->isPasswordField() && frame->selection()->isFocusedAndActive() && document()->focusedElement() == node() && PlatformKeyboardEvent::currentCapsLockState();
+    if (Frame* frame = document().frame())
+        shouldDrawCapsLockIndicator = inputElement()->isPasswordField() && frame->selection().isFocusedAndActive() && document().focusedElement() == node() && PlatformKeyboardEvent::currentCapsLockState();
 
     if (shouldDrawCapsLockIndicator != m_shouldDrawCapsLockIndicator) {
         m_shouldDrawCapsLockIndicator = shouldDrawCapsLockIndicator;
@@ -372,7 +372,7 @@
 
 bool RenderTextControlSingleLine::textShouldBeTruncated() const
 {
-    return document()->focusedElement() != node() && style()->textOverflow() == TextOverflowEllipsis;
+    return document().focusedElement() != node() && style()->textOverflow() == TextOverflowEllipsis;
 }
 
 void RenderTextControlSingleLine::autoscroll(const IntPoint& position)
diff --git a/Source/core/rendering/RenderTextControlSingleLine.h b/Source/core/rendering/RenderTextControlSingleLine.h
index 7f36979..31f5b52 100644
--- a/Source/core/rendering/RenderTextControlSingleLine.h
+++ b/Source/core/rendering/RenderTextControlSingleLine.h
@@ -105,9 +105,9 @@
 
 // ----------------------------
 
-class RenderTextControlInnerBlock : public RenderBlock {
+class RenderTextControlInnerBlock : public RenderBlockFlow {
 public:
-    RenderTextControlInnerBlock(Element* element) : RenderBlock(element) { }
+    RenderTextControlInnerBlock(Element* element) : RenderBlockFlow(element) { }
     virtual int inlineBlockBaseline(LineDirectionMode direction) const OVERRIDE { return lastLineBoxBaseline(direction); }
 
 private:
diff --git a/Source/core/rendering/RenderTextTrackCue.cpp b/Source/core/rendering/RenderTextTrackCue.cpp
index 1f95620..e54e923 100644
--- a/Source/core/rendering/RenderTextTrackCue.cpp
+++ b/Source/core/rendering/RenderTextTrackCue.cpp
@@ -29,18 +29,19 @@
 
 #include "core/html/track/TextTrackCue.h"
 #include "core/html/track/TextTrackCueGeneric.h"
+#include "core/rendering/RenderView.h"
 
 namespace WebCore {
 
 RenderTextTrackCue::RenderTextTrackCue(TextTrackCueBox* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
     , m_cue(element->getCue())
 {
 }
 
 void RenderTextTrackCue::layout()
 {
-    RenderBlock::layout();
+    RenderBlockFlow::layout();
 
 #if ENABLE(WEBVTT_REGIONS)
     // If WebVTT Regions are used, the regular WebVTT layout algorithm is no
diff --git a/Source/core/rendering/RenderTextTrackCue.h b/Source/core/rendering/RenderTextTrackCue.h
index 850ba80..fb71e4c 100644
--- a/Source/core/rendering/RenderTextTrackCue.h
+++ b/Source/core/rendering/RenderTextTrackCue.h
@@ -27,20 +27,20 @@
 #define RenderTextTrackCue_h
 
 #include "core/platform/graphics/FloatPoint.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "core/rendering/RenderInline.h"
-#include "core/rendering/RenderView.h"
 
 namespace WebCore {
 
 class TextTrackCueBox;
 
-class RenderTextTrackCue FINAL : public RenderBlock {
+class RenderTextTrackCue FINAL : public RenderBlockFlow {
 public:
     explicit RenderTextTrackCue(TextTrackCueBox*);
 
 private:
     virtual void layout() OVERRIDE;
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
 
     bool isOutside() const;
     bool isOverlapping() const;
diff --git a/Source/core/rendering/RenderTheme.cpp b/Source/core/rendering/RenderTheme.cpp
index 22db462..3af370b 100644
--- a/Source/core/rendering/RenderTheme.cpp
+++ b/Source/core/rendering/RenderTheme.cpp
@@ -69,9 +69,9 @@
 
 using namespace HTMLNames;
 
-static StyleColor& customFocusRingColor()
+static Color& customFocusRingColor()
 {
-    DEFINE_STATIC_LOCAL(StyleColor, color, ());
+    DEFINE_STATIC_LOCAL(Color, color, ());
     return color;
 }
 
@@ -92,7 +92,6 @@
     : m_platformTheme(platformTheme())
 #endif
 {
-    m_selectionColorsValid = 0;
 }
 
 void RenderTheme::adjustStyle(RenderStyle* style, Element* e, const CachedUAStyle& uaStyle)
@@ -527,88 +526,59 @@
     return formatMediaControlsTime(currentTime);
 }
 
-namespace SelectionColors {
-enum {
-    ActiveBackground = 1,
-    InactiveBackground = 2,
-    ActiveForeground = 4,
-    InactiveForeground = 8,
-    ActiveListBoxBackground = 16,
-    InactiveListBoxBackground = 32,
-    ActiveListBoxForeground = 64,
-    InactiveListBoxForeground = 128
-};
-};
-
 Color RenderTheme::activeSelectionBackgroundColor() const
 {
-    if (!(m_selectionColorsValid & SelectionColors::ActiveBackground)) {
+    if (!m_activeSelectionBackgroundColor.isValid())
         m_activeSelectionBackgroundColor = platformActiveSelectionBackgroundColor().blendWithWhite();
-        m_selectionColorsValid |= SelectionColors::ActiveBackground;
-    }
     return m_activeSelectionBackgroundColor;
 }
 
 Color RenderTheme::inactiveSelectionBackgroundColor() const
 {
-    if (!(m_selectionColorsValid & SelectionColors::InactiveBackground)) {
+    if (!m_inactiveSelectionBackgroundColor.isValid())
         m_inactiveSelectionBackgroundColor = platformInactiveSelectionBackgroundColor().blendWithWhite();
-        m_selectionColorsValid |= SelectionColors::InactiveBackground;
-    }
     return m_inactiveSelectionBackgroundColor;
 }
 
 Color RenderTheme::activeSelectionForegroundColor() const
 {
-    if (!(m_selectionColorsValid & SelectionColors::ActiveForeground) && supportsSelectionForegroundColors()) {
+    if (!m_activeSelectionForegroundColor.isValid() && supportsSelectionForegroundColors())
         m_activeSelectionForegroundColor = platformActiveSelectionForegroundColor();
-        m_selectionColorsValid |= SelectionColors::ActiveForeground;
-    }
     return m_activeSelectionForegroundColor;
 }
 
 Color RenderTheme::inactiveSelectionForegroundColor() const
 {
-    if (!(m_selectionColorsValid & SelectionColors::InactiveForeground) && supportsSelectionForegroundColors()) {
+    if (!m_inactiveSelectionForegroundColor.isValid() && supportsSelectionForegroundColors())
         m_inactiveSelectionForegroundColor = platformInactiveSelectionForegroundColor();
-        m_selectionColorsValid |= SelectionColors::InactiveForeground;
-    }
     return m_inactiveSelectionForegroundColor;
 }
 
 Color RenderTheme::activeListBoxSelectionBackgroundColor() const
 {
-    if (!(m_selectionColorsValid & SelectionColors::ActiveListBoxBackground)) {
+    if (!m_activeListBoxSelectionBackgroundColor.isValid())
         m_activeListBoxSelectionBackgroundColor = platformActiveListBoxSelectionBackgroundColor();
-        m_selectionColorsValid |= SelectionColors::ActiveListBoxBackground;
-    }
     return m_activeListBoxSelectionBackgroundColor;
 }
 
 Color RenderTheme::inactiveListBoxSelectionBackgroundColor() const
 {
-    if (!(m_selectionColorsValid & SelectionColors::InactiveListBoxBackground)) {
+    if (!m_inactiveListBoxSelectionBackgroundColor.isValid())
         m_inactiveListBoxSelectionBackgroundColor = platformInactiveListBoxSelectionBackgroundColor();
-        m_selectionColorsValid |= SelectionColors::InactiveListBoxBackground;
-    }
     return m_inactiveListBoxSelectionBackgroundColor;
 }
 
 Color RenderTheme::activeListBoxSelectionForegroundColor() const
 {
-    if (!(m_selectionColorsValid & SelectionColors::ActiveListBoxForeground) && supportsListBoxSelectionForegroundColors()) {
+    if (!m_activeListBoxSelectionForegroundColor.isValid() && supportsListBoxSelectionForegroundColors())
         m_activeListBoxSelectionForegroundColor = platformActiveListBoxSelectionForegroundColor();
-        m_selectionColorsValid |= SelectionColors::ActiveListBoxForeground;
-    }
     return m_activeListBoxSelectionForegroundColor;
 }
 
 Color RenderTheme::inactiveListBoxSelectionForegroundColor() const
 {
-    if (!(m_selectionColorsValid & SelectionColors::InactiveListBoxForeground) && supportsListBoxSelectionForegroundColors()) {
+    if (!m_inactiveListBoxSelectionForegroundColor.isValid() && supportsListBoxSelectionForegroundColors())
         m_inactiveListBoxSelectionForegroundColor = platformInactiveListBoxSelectionForegroundColor();
-        m_selectionColorsValid |= SelectionColors::InactiveListBoxForeground;
-    }
     return m_inactiveListBoxSelectionForegroundColor;
 }
 
@@ -690,7 +660,7 @@
     // Test the style to see if the UA border and background match.
     return style.border() != uaStyle.border
         || backgroundLayersCopy != backgroundCopy
-        || style.visitedDependentColor(CSSPropertyBackgroundColor).color() != uaStyle.backgroundColor;
+        || style.visitedDependentColor(CSSPropertyBackgroundColor) != uaStyle.backgroundColor;
 }
 
 bool RenderTheme::isControlStyled(const RenderStyle* style, const CachedUAStyle& uaStyle) const
@@ -803,7 +773,7 @@
     if (!node)
         return false;
 
-    Page* page = node->document()->page();
+    Page* page = node->document().page();
     if (!page)
         return false;
 
@@ -839,9 +809,9 @@
         return false;
 
     node = node->focusDelegate();
-    Document* document = node->document();
-    Frame* frame = document->frame();
-    return node == document->focusedElement() && node->shouldHaveFocusAppearance() && frame && frame->selection()->isFocusedAndActive();
+    Document& document = node->document();
+    Frame* frame = document.frame();
+    return node == document.focusedElement() && node->shouldHaveFocusAppearance() && frame && frame->selection().isFocusedAndActive();
 }
 
 bool RenderTheme::isPressed(const RenderObject* o) const
@@ -1119,7 +1089,16 @@
 
 void RenderTheme::platformColorsDidChange()
 {
-    m_selectionColorsValid = 0;
+    m_activeSelectionForegroundColor = Color();
+    m_inactiveSelectionForegroundColor = Color();
+    m_activeSelectionBackgroundColor = Color();
+    m_inactiveSelectionBackgroundColor = Color();
+
+    m_activeListBoxSelectionForegroundColor = Color();
+    m_inactiveListBoxSelectionForegroundColor = Color();
+    m_activeListBoxSelectionBackgroundColor = Color();
+    m_inactiveListBoxSelectionForegroundColor = Color();
+
     Page::scheduleForcedStyleRecalcForAllPages();
 }
 
@@ -1224,7 +1203,7 @@
 
 Color RenderTheme::focusRingColor()
 {
-    return customFocusRingColor().isValid() ? customFocusRingColor().color() : theme().platformFocusRingColor();
+    return customFocusRingColor().isValid() ? customFocusRingColor() : theme().platformFocusRingColor();
 }
 
 String RenderTheme::fileListDefaultLabel(bool multipleFilesAllowed) const
diff --git a/Source/core/rendering/RenderTheme.h b/Source/core/rendering/RenderTheme.h
index 1a7b7d5..fc70621 100644
--- a/Source/core/rendering/RenderTheme.h
+++ b/Source/core/rendering/RenderTheme.h
@@ -342,8 +342,6 @@
     mutable Color m_activeListBoxSelectionForegroundColor;
     mutable Color m_inactiveListBoxSelectionForegroundColor;
 
-    mutable unsigned m_selectionColorsValid;
-
     // This color is expected to be drawn on a semi-transparent overlay,
     // making it more transparent than its alpha value indicates.
     static const RGBA32 defaultTapHighlightColor = 0x66000000;
diff --git a/Source/core/rendering/RenderThemeChromiumDefault.cpp b/Source/core/rendering/RenderThemeChromiumDefault.cpp
index b5f15a4..adaa2d4 100644
--- a/Source/core/rendering/RenderThemeChromiumDefault.cpp
+++ b/Source/core/rendering/RenderThemeChromiumDefault.cpp
@@ -101,7 +101,7 @@
 
 String RenderThemeChromiumDefault::extraDefaultStyleSheet()
 {
-#if !OS(WINDOWS)
+#if !OS(WIN)
     return RenderTheme::extraDefaultStyleSheet() +
         RenderThemeChromiumSkia::extraDefaultStyleSheet() +
         String(themeChromiumLinuxUserAgentStyleSheet, sizeof(themeChromiumLinuxUserAgentStyleSheet));
diff --git a/Source/core/rendering/RenderThemeChromiumMac.mm b/Source/core/rendering/RenderThemeChromiumMac.mm
index 6f5ab4f..c0d52c6 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.mm
+++ b/Source/core/rendering/RenderThemeChromiumMac.mm
@@ -394,7 +394,7 @@
             return it->value;
     }
 
-    Color color = Color::transparent;
+    Color color;
     switch (cssValueId) {
         case CSSValueActiveborder:
             color = convertNSColorToColor([NSColor keyboardFocusIndicatorColor]);
@@ -495,10 +495,10 @@
             break;
     }
 
-    if (!color.alpha())
+    if (!color.isValid())
         color = RenderTheme::systemColor(cssValueId);
 
-    if (color.alpha())
+    if (color.isValid())
         m_systemColorCache.set(cssValueId, color.rgb());
 
     return color;
@@ -1247,7 +1247,7 @@
 
     GraphicsContextStateSaver stateSaver(*paintInfo.context);
 
-    paintInfo.context->setFillColor(o->resolveColor(CSSPropertyColor));
+    paintInfo.context->setFillColor(o->style()->visitedDependentColor(CSSPropertyColor));
     paintInfo.context->setStrokeStyle(NoStroke);
 
     FloatPoint arrow1[3];
diff --git a/Source/core/rendering/RenderThemeChromiumWin.cpp b/Source/core/rendering/RenderThemeChromiumWin.cpp
index 78f94e7..1abbd9f 100644
--- a/Source/core/rendering/RenderThemeChromiumWin.cpp
+++ b/Source/core/rendering/RenderThemeChromiumWin.cpp
@@ -552,7 +552,7 @@
     // Fallback to white if the specified color object is invalid.
     Color backgroundColor(Color::white);
     if (o->style()->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
-        backgroundColor = o->resolveColor(CSSPropertyBackgroundColor);
+        backgroundColor = o->style()->visitedDependentColor(CSSPropertyBackgroundColor);
 
     // If we have background-image, don't fill the content area to expose the
     // parent's background. Also, we shouldn't fill the content area if the
diff --git a/Source/core/rendering/RenderTreeAsText.cpp b/Source/core/rendering/RenderTreeAsText.cpp
index e22b2c9..319f752 100644
--- a/Source/core/rendering/RenderTreeAsText.cpp
+++ b/Source/core/rendering/RenderTreeAsText.cpp
@@ -261,17 +261,17 @@
             // Do not dump invalid or transparent backgrounds, since that is the default.
             Color backgroundColor = o.resolveColor(CSSPropertyBackgroundColor);
             if (o.parent()->resolveColor(CSSPropertyBackgroundColor) != backgroundColor
-                && backgroundColor.rgb())
+                && backgroundColor.isValid() && backgroundColor.rgb())
                 ts << " [bgcolor=" << backgroundColor.nameForRenderTreeAsText() << "]";
 
             Color textFillColor = o.resolveColor(CSSPropertyWebkitTextFillColor);
             if (o.parent()->resolveColor(CSSPropertyWebkitTextFillColor) != textFillColor
-                && textFillColor != color && textFillColor.rgb())
+                && textFillColor.isValid() && textFillColor != color && textFillColor.rgb())
                 ts << " [textFillColor=" << textFillColor.nameForRenderTreeAsText() << "]";
 
             Color textStrokeColor = o.resolveColor(CSSPropertyWebkitTextStrokeColor);
             if (o.parent()->resolveColor(CSSPropertyWebkitTextStrokeColor) != textStrokeColor
-                && textStrokeColor != color && textStrokeColor.rgb())
+                && textStrokeColor.isValid() && textStrokeColor != color && textStrokeColor.rgb())
                 ts << " [textStrokeColor=" << textStrokeColor.nameForRenderTreeAsText() << "]";
 
             if (o.parent()->style()->textStrokeWidth() != o.style()->textStrokeWidth() && o.style()->textStrokeWidth() > 0)
@@ -519,7 +519,7 @@
         Widget* widget = toRenderWidget(&o)->widget();
         if (widget && widget->isFrameView()) {
             FrameView* view = toFrameView(widget);
-            RenderView* root = view->frame()->contentRenderer();
+            RenderView* root = view->frame().contentRenderer();
             if (root) {
                 view->layout();
                 RenderLayer* l = root->layer();
@@ -720,7 +720,7 @@
 {
     StringBuilder result;
 
-    Element* body = node->document()->body();
+    Element* body = node->document().body();
     Node* parent;
     for (Node* n = node; n; n = parent) {
         parent = n->parentOrShadowHostNode();
@@ -761,7 +761,7 @@
     if (!frame)
         return;
 
-    VisibleSelection selection = frame->selection()->selection();
+    VisibleSelection selection = frame->selection().selection();
     if (selection.isCaret()) {
         ts << "caret: position " << selection.start().deprecatedEditingOffset() << " of " << nodePosition(selection.start().deprecatedNode());
         if (selection.affinity() == UPSTREAM)
@@ -804,8 +804,8 @@
 {
     // Doesn't support printing mode.
     ASSERT(!(behavior & RenderAsTextPrintingMode));
-    if (!(behavior & RenderAsTextDontUpdateLayout) && element->document())
-        element->document()->updateLayout();
+    if (!(behavior & RenderAsTextDontUpdateLayout))
+        element->document().updateLayout();
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox())
@@ -831,7 +831,7 @@
 {
     // Make sure the element is not freed during the layout.
     RefPtr<Element> elementRef(element);
-    element->document()->updateLayout();
+    element->document().updateLayout();
     TextStream stream;
     bool isFirstCounter = true;
     // The counter renderers should be children of :before or :after pseudo-elements.
@@ -846,7 +846,7 @@
 {
     // Make sure the element is not freed during the layout.
     RefPtr<Element> elementRef(element);
-    element->document()->updateLayout();
+    element->document().updateLayout();
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isListItem())
diff --git a/Source/core/rendering/RenderVideo.cpp b/Source/core/rendering/RenderVideo.cpp
index 49d9588..f551f99 100644
--- a/Source/core/rendering/RenderVideo.cpp
+++ b/Source/core/rendering/RenderVideo.cpp
@@ -189,7 +189,7 @@
 
     if (displayingPoster)
         paintIntoRect(context, rect);
-    else if (document()->view() && document()->view()->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
+    else if (document().view() && document().view()->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
         mediaPlayer->paintCurrentFrameInContext(context, pixelSnappedIntRect(rect));
     else
         mediaPlayer->paint(context, pixelSnappedIntRect(rect));
@@ -200,8 +200,8 @@
 
 void RenderVideo::layout()
 {
-    RenderMedia::layout();
     updatePlayer();
+    RenderMedia::layout();
 }
 
 HTMLVideoElement* RenderVideo::videoElement() const
diff --git a/Source/core/rendering/RenderView.cpp b/Source/core/rendering/RenderView.cpp
index cae73a2..c676442 100644
--- a/Source/core/rendering/RenderView.cpp
+++ b/Source/core/rendering/RenderView.cpp
@@ -35,6 +35,7 @@
 #include "core/rendering/ColumnInfo.h"
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/HitTestResult.h"
+#include "core/rendering/RenderFlowThread.h"
 #include "core/rendering/RenderGeometryMap.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerBacking.h"
@@ -45,7 +46,7 @@
 namespace WebCore {
 
 RenderView::RenderView(Document* document)
-    : RenderBlock(document)
+    : RenderBlockFlow(document)
     , m_frameView(document->view())
     , m_selectionStart(0)
     , m_selectionEnd(0)
@@ -120,8 +121,13 @@
     ASSERT(needsLayout());
 
     RenderBlock::layout();
+
+    if (m_frameView->partialLayout().isStopping())
+        return;
+
     if (hasRenderNamedFlowThreads())
         flowThreadController()->layoutRenderNamedFlowThreads();
+
 #ifndef NDEBUG
     checkLayoutState(state);
 #endif
@@ -136,11 +142,9 @@
 }
 #endif
 
-static RenderBox* enclosingSeamlessRenderer(Document* doc)
+static RenderBox* enclosingSeamlessRenderer(const Document& doc)
 {
-    if (!doc)
-        return 0;
-    Element* ownerElement = doc->seamlessParentIFrame();
+    Element* ownerElement = doc.seamlessParentIFrame();
     if (!ownerElement)
         return 0;
     return ownerElement->renderBox();
@@ -214,6 +218,11 @@
 // as detected in the previous step.
 void RenderView::layoutContentInAutoLogicalHeightRegions(const LayoutState& state)
 {
+    if (!m_frameView->partialLayout().isStopping()) {
+        // Disable partial layout for any two-pass layout algorithm.
+        m_frameView->partialLayout().reset();
+    }
+
     // We need to invalidate all the flows with auto-height regions if one such flow needs layout.
     // If none is found we do a layout a check back again afterwards.
     if (!flowThreadController()->updateFlowThreadsNeedingLayout()) {
@@ -242,7 +251,7 @@
 
 void RenderView::layout()
 {
-    if (!document()->paginated())
+    if (!document().paginated())
         setPageLogicalHeight(0);
 
     if (shouldUsePrintingLayout())
@@ -282,6 +291,11 @@
     else
         layoutContent(state);
 
+    if (m_frameView->partialLayout().isStopping()) {
+        m_layoutState = 0;
+        return;
+    }
+
 #ifndef NDEBUG
     checkLayoutState(state);
 #endif
@@ -451,7 +465,7 @@
     // FIXME: This needs to be dynamic.  We should be able to go back to blitting if we ever stop being inside
     // a transform, transparency layer, etc.
     Element* elt;
-    for (elt = document()->ownerElement(); view() && elt && elt->renderer(); elt = elt->document()->ownerElement()) {
+    for (elt = document().ownerElement(); view() && elt && elt->renderer(); elt = elt->document().ownerElement()) {
         RenderLayer* layer = elt->renderer()->enclosingLayer();
         if (layer->cannotBlitToWindow()) {
             frameView()->setCannotBlitToWindow();
@@ -464,7 +478,7 @@
         }
     }
 
-    if (document()->ownerElement() || !view())
+    if (document().ownerElement() || !view())
         return;
 
     if (paintInfo.skipRootBackground())
@@ -472,7 +486,7 @@
 
     bool rootFillsViewport = false;
     bool rootObscuresBackground = false;
-    Node* documentElement = document()->documentElement();
+    Node* documentElement = document().documentElement();
     if (RenderObject* rootRenderer = documentElement ? documentElement->renderer() : 0) {
         // The document element's renderer is currently forced to be a block, but may not always be.
         RenderBox* rootBox = rootRenderer->isBox() ? toRenderBox(rootRenderer) : 0;
@@ -480,7 +494,7 @@
         rootObscuresBackground = rendererObscuresBackground(rootRenderer);
     }
 
-    Page* page = document()->page();
+    Page* page = document().page();
     float pageScaleFactor = page ? page->pageScaleFactor() : 1;
 
     // If painting will entirely fill the view, no need to fill the background.
@@ -527,7 +541,7 @@
 
     // We always just invalidate the root view, since we could be an iframe that is clipped out
     // or even invisible.
-    Element* elt = document()->ownerElement();
+    Element* elt = document().ownerElement();
     if (!elt)
         m_frameView->repaintContentRectangle(pixelSnappedIntRect(ur));
     else if (RenderBox* obj = elt->renderBox()) {
@@ -614,7 +628,7 @@
 
 IntRect RenderView::selectionBounds(bool clipToVisibleContent) const
 {
-    document()->updateStyleIfNeeded();
+    document().updateStyleIfNeeded();
 
     typedef HashMap<RenderObject*, OwnPtr<RenderSelectionInfo> > SelectionMap;
     SelectionMap selectedObjects;
@@ -656,7 +670,7 @@
 
 void RenderView::repaintSelection() const
 {
-    document()->updateStyleIfNeeded();
+    document().updateStyleIfNeeded();
 
     HashSet<RenderBlock*> processedBlocks;
 
@@ -867,15 +881,14 @@
 
 bool RenderView::printing() const
 {
-    return document()->printing();
+    return document().printing();
 }
 
 bool RenderView::shouldUsePrintingLayout() const
 {
     if (!printing() || !m_frameView)
         return false;
-    Frame* frame = m_frameView->frame();
-    return frame && frame->shouldUsePrintingLayout();
+    return m_frameView->frame().shouldUsePrintingLayout();
 }
 
 size_t RenderView::getRetainedWidgets(Vector<RenderWidget*>& renderWidgets)
@@ -947,7 +960,7 @@
 
 bool RenderView::rootBackgroundIsEntirelyFixed() const
 {
-    RenderObject* rootObject = document()->documentElement() ? document()->documentElement()->renderer() : 0;
+    RenderObject* rootObject = document().documentElement() ? document().documentElement()->renderer() : 0;
     if (!rootObject)
         return false;
 
@@ -1011,8 +1024,7 @@
 
 float RenderView::zoomFactor() const
 {
-    Frame* frame = m_frameView->frame();
-    return frame ? frame->pageZoomFactor() : 1;
+    return m_frameView->frame().pageZoomFactor();
 }
 
 void RenderView::pushLayoutState(RenderObject* root)
@@ -1020,6 +1032,7 @@
     ASSERT(m_layoutStateDisableCount == 0);
     ASSERT(m_layoutState == 0);
 
+    pushLayoutStateForCurrentFlowThread(root);
     m_layoutState = new LayoutState(root);
 }
 
@@ -1039,7 +1052,7 @@
     if (result.innerNode())
         return;
 
-    Node* node = document()->documentElement();
+    Node* node = document().documentElement();
     if (node) {
         result.setInnerNode(node);
         if (!result.innerNonSharedNode())
@@ -1103,6 +1116,30 @@
     return m_flowThreadController.get();
 }
 
+void RenderView::pushLayoutStateForCurrentFlowThread(const RenderObject* object)
+{
+    if (!m_flowThreadController)
+        return;
+
+    RenderFlowThread* currentFlowThread = m_flowThreadController->currentRenderFlowThread();
+    if (!currentFlowThread)
+        return;
+
+    currentFlowThread->pushFlowThreadLayoutState(object);
+}
+
+void RenderView::popLayoutStateForCurrentFlowThread()
+{
+    if (!m_flowThreadController)
+        return;
+
+    RenderFlowThread* currentFlowThread = m_flowThreadController->currentRenderFlowThread();
+    if (!currentFlowThread)
+        return;
+
+    currentFlowThread->popFlowThreadLayoutState();
+}
+
 IntervalArena* RenderView::intervalArena()
 {
     if (!m_intervalArena)
@@ -1113,9 +1150,9 @@
 bool RenderView::backgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const
 {
     // FIXME: Remove this main frame check. Same concept applies to subframes too.
-    Page* page = document()->page();
+    Page* page = document().page();
     Frame* mainFrame = page ? page->mainFrame() : 0;
-    if (!m_frameView || m_frameView->frame() != mainFrame)
+    if (!m_frameView || &m_frameView->frame() != mainFrame)
         return false;
 
     return m_frameView->hasOpaqueBackground();
diff --git a/Source/core/rendering/RenderView.h b/Source/core/rendering/RenderView.h
index 21ba4f4..5bc7ae0 100644
--- a/Source/core/rendering/RenderView.h
+++ b/Source/core/rendering/RenderView.h
@@ -25,7 +25,7 @@
 #include "core/page/FrameView.h"
 #include "core/platform/PODFreeListArena.h"
 #include "core/rendering/LayoutState.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 #include "wtf/OwnPtr.h"
 
 namespace WebCore {
@@ -39,7 +39,7 @@
 // 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)
 // relative to the document (and so isn't necessarily in view).
-class RenderView FINAL : public RenderBlock {
+class RenderView FINAL : public RenderBlockFlow {
 public:
     explicit RenderView(Document*);
     virtual ~RenderView();
@@ -59,6 +59,8 @@
     virtual void updateLogicalWidth() OVERRIDE;
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return true; }
+
     virtual LayoutUnit availableLogicalHeight(AvailableLogicalHeightType) const OVERRIDE;
 
     // The same as the FrameView's layoutHeight/layoutWidth but with null check guards.
@@ -179,7 +181,7 @@
 
     IntervalArena* intervalArena();
 
-    IntSize viewportSize() const { return document()->viewportSize(); }
+    IntSize viewportSize() const { return document().viewportSize(); }
 
     void setRenderQuoteHead(RenderQuote* head) { m_renderQuoteHead = head; }
     RenderQuote* renderQuoteHead() const { return m_renderQuoteHead; }
@@ -216,10 +218,11 @@
     {
         // We push LayoutState even if layoutState is disabled because it stores layoutDelta too.
         if (!doingFullRepaint() || m_layoutState->isPaginated() || renderer->hasColumns() || renderer->flowThreadContainingBlock()
-            || m_layoutState->lineGrid() || (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isBlockFlow())
+            || m_layoutState->lineGrid() || (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isRenderBlockFlow())
             || (renderer->isRenderBlock() && toRenderBlock(renderer)->shapeInsideInfo())
             || (m_layoutState->shapeInsideInfo() && renderer->isRenderBlock() && !toRenderBlock(renderer)->allowsShapeInsideInfoSharing())
             ) {
+            pushLayoutStateForCurrentFlowThread(renderer);
             m_layoutState = new LayoutState(m_layoutState, renderer, offset, pageHeight, pageHeightChanged, colInfo);
             return true;
         }
@@ -231,6 +234,7 @@
         LayoutState* state = m_layoutState;
         m_layoutState = state->m_next;
         delete state;
+        popLayoutStateForCurrentFlowThread();
     }
 
     // Suspends the LayoutState optimization. Used under transforms that cannot be represented by
@@ -250,6 +254,9 @@
     size_t getRetainedWidgets(Vector<RenderWidget*>&);
     void releaseWidgets(Vector<RenderWidget*>&);
 
+    void pushLayoutStateForCurrentFlowThread(const RenderObject*);
+    void popLayoutStateForCurrentFlowThread();
+
     friend class LayoutStateMaintainer;
     friend class LayoutStateDisabler;
 
diff --git a/Source/core/rendering/RenderWidget.cpp b/Source/core/rendering/RenderWidget.cpp
index f8572e6..51f879a 100644
--- a/Source/core/rendering/RenderWidget.cpp
+++ b/Source/core/rendering/RenderWidget.cpp
@@ -83,7 +83,7 @@
 RenderWidget::RenderWidget(Element* element)
     : RenderReplaced(element)
     , m_widget(0)
-    , m_frameView(element->document()->view())
+    , m_frameView(element->document().view())
     // Reference counting is used to prevent the widget from being
     // destroyed while inside the Widget code, which might not be
     // able to handle that.
@@ -97,7 +97,7 @@
     if (RenderView* v = view())
         v->removeWidget(this);
 
-    if (AXObjectCache* cache = document()->existingAXObjectCache()) {
+    if (AXObjectCache* cache = document().existingAXObjectCache()) {
         cache->childrenChanged(this->parent());
         cache->remove(this);
     }
@@ -198,7 +198,7 @@
         moveWidgetToParentSoon(m_widget.get(), m_frameView);
     }
 
-    if (AXObjectCache* cache = document()->existingAXObjectCache())
+    if (AXObjectCache* cache = document().existingAXObjectCache())
         cache->childrenChanged(this);
 }
 
@@ -296,7 +296,7 @@
         paintInfo.context->restore();
 
     // Paint a partially transparent wash over selected widgets.
-    if (isSelected() && !document()->printing()) {
+    if (isSelected() && !document().printing()) {
         // FIXME: selectionRect() is in absolute, not painting coordinates.
         paintInfo.context->fillRect(pixelSnappedIntRect(selectionRect()), selectionBackgroundColor());
     }
@@ -330,7 +330,7 @@
     if (m_widget && m_widget->isFrameView()) {
         FrameView* frameView = toFrameView(m_widget.get());
         // Check the frame's page to make sure that the frame isn't in the process of being destroyed.
-        if ((boundsChanged || frameView->needsLayout()) && frameView->frame()->page())
+        if ((boundsChanged || frameView->needsLayout()) && frameView->frame().page())
             frameView->layout();
     }
 }
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/rendering/RenderingNodeProxy.cpp
similarity index 80%
copy from Source/core/loader/CachedMetadata.cpp
copy to Source/core/rendering/RenderingNodeProxy.cpp
index f3f2a30..303972b 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/rendering/RenderingNodeProxy.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * 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
@@ -29,8 +29,24 @@
  */
 
 #include "config.h"
-#include "core/loader/CachedMetadata.h"
+#include "core/rendering/RenderingNodeProxy.h"
+
+#include "core/dom/Node.h"
 
 namespace WebCore {
 
-} // namespace WebCore
+RenderingNodeProxy::RenderingNodeProxy(Node* node)
+    : m_node(node)
+{
+}
+
+RenderingNodeProxy::~RenderingNodeProxy()
+{
+}
+
+bool RenderingNodeProxy::hasTagName(const QualifiedName& tagName) const
+{
+    return m_node->hasTagName(tagName);
+}
+
+}
diff --git a/Source/core/loader/CachedMetadata.cpp b/Source/core/rendering/RenderingNodeProxy.h
similarity index 75%
copy from Source/core/loader/CachedMetadata.cpp
copy to Source/core/rendering/RenderingNodeProxy.h
index f3f2a30..30e73bf 100644
--- a/Source/core/loader/CachedMetadata.cpp
+++ b/Source/core/rendering/RenderingNodeProxy.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
+ * 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
@@ -28,9 +28,29 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/loader/CachedMetadata.h"
+#ifndef RenderingNodeProxy_h
+#define RenderingNodeProxy_h
 
 namespace WebCore {
 
-} // namespace WebCore
+class QualifiedName;
+class Node;
+
+class RenderingNodeProxy {
+public:
+    explicit RenderingNodeProxy(Node*);
+    ~RenderingNodeProxy();
+
+    bool hasTagName(const QualifiedName&) const;
+
+    Node* unsafeNode() const { return m_node; }
+    void clear() { m_node = 0; }
+    void set(Node* node) { m_node = node; }
+
+private:
+    Node* m_node;
+};
+
+}
+
+#endif // RenderingNodeProxy_h
diff --git a/Source/core/rendering/RootInlineBox.cpp b/Source/core/rendering/RootInlineBox.cpp
index 9a3da5d..5ad1318 100644
--- a/Source/core/rendering/RootInlineBox.cpp
+++ b/Source/core/rendering/RootInlineBox.cpp
@@ -21,11 +21,6 @@
 #include "core/rendering/RootInlineBox.h"
 
 #include "core/dom/Document.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/text/BidiResolver.h"
 #include "core/rendering/EllipsisBox.h"
 #include "core/rendering/HitTestResult.h"
@@ -250,7 +245,7 @@
     bool setMaxDescent = false;
 
     // Figure out if we're in no-quirks mode.
-    bool noQuirksMode = renderer()->document()->inNoQuirksMode();
+    bool noQuirksMode = renderer()->document().inNoQuirksMode();
 
     m_baselineType = requiresIdeographicBaseline(textBoxDataMap) ? IdeographicBaseline : AlphabeticBaseline;
 
@@ -842,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().styleSheetCollections()->usesFirstLineRules())
         firstLine = false;
 
     // Check the cache.
diff --git a/Source/core/rendering/SubtreeLayoutScope.cpp b/Source/core/rendering/SubtreeLayoutScope.cpp
index c3bfefe..716421f 100644
--- a/Source/core/rendering/SubtreeLayoutScope.cpp
+++ b/Source/core/rendering/SubtreeLayoutScope.cpp
@@ -39,11 +39,17 @@
 SubtreeLayoutScope::SubtreeLayoutScope(RenderObject* root)
     : m_root(root)
 {
-    RELEASE_ASSERT(m_root->document()->view()->isInLayout());
+    RELEASE_ASSERT(m_root->document().view()->isInLayout());
 }
 
 SubtreeLayoutScope::~SubtreeLayoutScope()
 {
+    // Partial layout early-exits layout and will leave the tree as needing layout.
+    if (m_root->frameView()->partialLayout().isStopping()) {
+        ASSERT(m_root->needsLayout());
+        return;
+    }
+
     RELEASE_ASSERT(!m_root->needsLayout());
 
 #ifndef NDEBUG
diff --git a/Source/core/rendering/shapes/PolygonShape.cpp b/Source/core/rendering/shapes/PolygonShape.cpp
index 06f525a..e1f429a 100644
--- a/Source/core/rendering/shapes/PolygonShape.cpp
+++ b/Source/core/rendering/shapes/PolygonShape.cpp
@@ -31,6 +31,7 @@
 #include "core/rendering/shapes/PolygonShape.h"
 
 #include "core/platform/graphics/LayoutPoint.h"
+#include "core/rendering/shapes/ShapeInterval.h"
 #include "wtf/MathExtras.h"
 
 namespace WebCore {
@@ -225,12 +226,12 @@
     return true;
 }
 
-static inline bool appendIntervalX(float x, bool inside, Vector<ShapeInterval>& result)
+static inline bool appendIntervalX(float x, bool inside, FloatShapeIntervals& result)
 {
     if (!inside)
-        result.append(ShapeInterval(x));
+        result.append(FloatShapeInterval(x, x));
     else
-        result[result.size() - 1].x2 = x;
+        result.last().setX2(x);
 
     return !inside;
 }
@@ -242,7 +243,7 @@
     return (x1 == x2) ? intersection1.type < intersection2.type : x1 < x2;
 }
 
-static void computeXIntersections(const FloatPolygon& polygon, float y, bool isMinY, Vector<ShapeInterval>& result)
+static void computeXIntersections(const FloatPolygon& polygon, float y, bool isMinY, FloatShapeIntervals& result)
 {
     Vector<const FloatPolygonEdge*> edges;
     if (!polygon.overlappingEdges(y, y, edges))
@@ -312,7 +313,25 @@
     }
 }
 
-static void computeOverlappingEdgeXProjections(const FloatPolygon& polygon, float y1, float y2, Vector<ShapeInterval>& result)
+static bool compareX1(const FloatShapeInterval a, const FloatShapeInterval& b) { return a.x1() < b.x1(); }
+
+static void sortAndMergeShapeIntervals(FloatShapeIntervals& intervals)
+{
+    std::sort(intervals.begin(), intervals.end(), compareX1);
+
+    for (unsigned i = 1; i < intervals.size(); ) {
+        const FloatShapeInterval& thisInterval = intervals[i];
+        FloatShapeInterval& previousInterval = intervals[i - 1];
+        if (thisInterval.overlaps(previousInterval)) {
+            previousInterval.setX2(std::max<float>(previousInterval.x2(), thisInterval.x2()));
+            intervals.remove(i);
+        } else {
+            ++i;
+        }
+    }
+}
+
+static void computeOverlappingEdgeXProjections(const FloatPolygon& polygon, float y1, float y2, FloatShapeIntervals& result)
 {
     Vector<const FloatPolygonEdge*> edges;
     if (!polygon.overlappingEdges(y1, y2, edges))
@@ -342,10 +361,10 @@
             std::swap(x1, x2);
 
         if (x2 > x1)
-            result.append(ShapeInterval(x1, x2));
+            result.append(FloatShapeInterval(x1, x2));
     }
 
-    sortShapeIntervals(result);
+    sortAndMergeShapeIntervals(result);
 }
 
 void PolygonShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
@@ -357,22 +376,22 @@
     float y1 = logicalTop;
     float y2 = logicalTop + logicalHeight;
 
-    Vector<ShapeInterval> y1XIntervals, y2XIntervals;
+    FloatShapeIntervals y1XIntervals, y2XIntervals;
     computeXIntersections(polygon, y1, true, y1XIntervals);
     computeXIntersections(polygon, y2, false, y2XIntervals);
 
-    Vector<ShapeInterval> mergedIntervals;
-    mergeShapeIntervals(y1XIntervals, y2XIntervals, mergedIntervals);
+    FloatShapeIntervals mergedIntervals;
+    FloatShapeInterval::uniteShapeIntervals(y1XIntervals, y2XIntervals, mergedIntervals);
 
-    Vector<ShapeInterval> edgeIntervals;
+    FloatShapeIntervals edgeIntervals;
     computeOverlappingEdgeXProjections(polygon, y1, y2, edgeIntervals);
 
-    Vector<ShapeInterval> excludedIntervals;
-    mergeShapeIntervals(mergedIntervals, edgeIntervals, excludedIntervals);
+    FloatShapeIntervals excludedIntervals;
+    FloatShapeInterval::uniteShapeIntervals(mergedIntervals, edgeIntervals, excludedIntervals);
 
     for (unsigned i = 0; i < excludedIntervals.size(); ++i) {
-        ShapeInterval interval = excludedIntervals[i];
-        result.append(LineSegment(interval.x1, interval.x2));
+        const FloatShapeInterval& interval = excludedIntervals[i];
+        result.append(LineSegment(interval.x1(), interval.x2()));
     }
 }
 
@@ -385,22 +404,22 @@
     float y1 = logicalTop;
     float y2 = logicalTop + logicalHeight;
 
-    Vector<ShapeInterval> y1XIntervals, y2XIntervals;
+    FloatShapeIntervals y1XIntervals, y2XIntervals;
     computeXIntersections(polygon, y1, true, y1XIntervals);
     computeXIntersections(polygon, y2, false, y2XIntervals);
 
-    Vector<ShapeInterval> commonIntervals;
-    intersectShapeIntervals(y1XIntervals, y2XIntervals, commonIntervals);
+    FloatShapeIntervals commonIntervals;
+    FloatShapeInterval::intersectShapeIntervals(y1XIntervals, y2XIntervals, commonIntervals);
 
-    Vector<ShapeInterval> edgeIntervals;
+    FloatShapeIntervals edgeIntervals;
     computeOverlappingEdgeXProjections(polygon, y1, y2, edgeIntervals);
 
-    Vector<ShapeInterval> includedIntervals;
-    subtractShapeIntervals(commonIntervals, edgeIntervals, includedIntervals);
+    FloatShapeIntervals includedIntervals;
+    FloatShapeInterval::subtractShapeIntervals(commonIntervals, edgeIntervals, includedIntervals);
 
     for (unsigned i = 0; i < includedIntervals.size(); ++i) {
-        ShapeInterval interval = includedIntervals[i];
-        result.append(LineSegment(interval.x1, interval.x2));
+        const FloatShapeInterval& interval = includedIntervals[i];
+        result.append(LineSegment(interval.x1(), interval.x2()));
     }
 }
 
diff --git a/Source/core/rendering/shapes/PolygonShape.h b/Source/core/rendering/shapes/PolygonShape.h
index ea7241f..14cd30d 100644
--- a/Source/core/rendering/shapes/PolygonShape.h
+++ b/Source/core/rendering/shapes/PolygonShape.h
@@ -32,7 +32,6 @@
 
 #include "core/platform/graphics/FloatPolygon.h"
 #include "core/rendering/shapes/Shape.h"
-#include "core/rendering/shapes/ShapeInterval.h"
 
 namespace WebCore {
 
diff --git a/Source/core/rendering/shapes/ShapeInterval.cpp b/Source/core/rendering/shapes/ShapeInterval.cpp
deleted file mode 100644
index 071005b..0000000
--- a/Source/core/rendering/shapes/ShapeInterval.cpp
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2012 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/shapes/ShapeInterval.h"
-
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-struct IntervalX1Comparator {
-    bool operator() (const ShapeInterval& i1, const ShapeInterval& i2) const
-    {
-        return i1.x1 < i2.x1;
-    }
-};
-
-bool ShapeInterval::intersect(const ShapeInterval& i, ShapeInterval& rv) const
-{
-    if (x2 < i.x1 || x1 > i.x2)
-        return false;
-    rv.x1 = std::max(x1, i.x1);
-    rv.x2 = std::min(x2, i.x2);
-    return true;
-}
-
-void sortShapeIntervals(Vector<ShapeInterval>& v)
-{
-    std::sort(v.begin(), v.end(), IntervalX1Comparator());
-}
-
-void mergeShapeIntervals(const Vector<ShapeInterval>& v1, const Vector<ShapeInterval>& v2, Vector<ShapeInterval>& rv)
-{
-    if (!v1.size()) {
-        rv.appendRange(v2.begin(), v2.end());
-    } else if (!v2.size()) {
-        rv.appendRange(v1.begin(), v1.end());
-    } else {
-        Vector<ShapeInterval> v(v1.size() + v2.size());
-        ShapeInterval* interval = 0;
-
-        std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v.begin(), IntervalX1Comparator());
-
-        for (size_t i = 0; i < v.size(); i++) {
-            if (!interval) {
-                interval = &v[i];
-            } else if (v[i].x1 >= interval->x1 && v[i].x1 <= interval->x2) { // FIXME: 1st <= test not needed?
-                interval->x2 = std::max(interval->x2, v[i].x2);
-            } else {
-                rv.append(*interval);
-                interval = &v[i];
-            }
-        }
-
-        if (interval)
-            rv.append(*interval);
-    }
-}
-
-void intersectShapeIntervals(const Vector<ShapeInterval>& v1, const Vector<ShapeInterval>& v2, Vector<ShapeInterval>& rv)
-{
-    size_t v1Size = v1.size();
-    size_t v2Size = v2.size();
-
-    if (!v1Size || !v2Size)
-        return;
-
-    ShapeInterval interval;
-    bool overlap = false;
-    size_t i1 = 0;
-    size_t i2 = 0;
-
-    while (i1 < v1Size && i2 < v2Size) {
-        ShapeInterval v12;
-        if (v1[i1].intersect(v2[i2], v12)) {
-            if (!overlap || !v12.intersect(interval, interval)) {
-                if (overlap)
-                    rv.append(interval);
-                interval = v12;
-                overlap = true;
-            }
-            if (v1[i1].x2 < v2[i2].x2)
-                i1++;
-            else
-                i2++;
-        } else {
-            if (overlap)
-                rv.append(interval);
-            overlap = false;
-            if (v1[i1].x1 < v2[i2].x1)
-                i1++;
-            else
-                i2++;
-        }
-    }
-
-    if (overlap)
-        rv.append(interval);
-}
-
-void subtractShapeIntervals(const Vector<ShapeInterval>& v1, const Vector<ShapeInterval>& v2, Vector<ShapeInterval>& rv)
-{
-    size_t v1Size = v1.size();
-    size_t v2Size = v2.size();
-
-    if (!v1Size)
-        return;
-
-    if (!v2Size) {
-        rv.appendRange(v1.begin(), v1.end());
-    } else {
-        size_t i1 = 0, i2 = 0;
-        rv.appendRange(v1.begin(), v1.end());
-
-        while (i1 < rv.size() && i2 < v2Size) {
-            ShapeInterval& interval1 = rv[i1];
-            const ShapeInterval& interval2 = v2[i2];
-
-            if (interval2.x1 <= interval1.x1 && interval2.x2 >= interval1.x2) {
-                rv.remove(i1);
-            } else if (interval2.x2 < interval1.x1) {
-                i2 += 1;
-            } else if (interval2.x1 > interval1.x2) {
-                i1 += 1;
-            } else if (interval2.x1 > interval1.x1 && interval2.x2 < interval1.x2) {
-                rv.insert(i1, ShapeInterval(interval1.x1, interval2.x1));
-                interval1.x1 = interval2.x2;
-                i2 += 1;
-            } else if (interval2.x1 <= interval1.x1) {
-                interval1.x1 = interval2.x2;
-                i2 += 1;
-            } else  { // (interval2.x2 >= interval1.x2)
-                interval1.x2 = interval2.x1;
-                i1 += 1;
-            }
-        }
-    }
-}
-
-} // namespace WebCore
diff --git a/Source/core/rendering/shapes/ShapeInterval.h b/Source/core/rendering/shapes/ShapeInterval.h
index e0c165e..e4308e5 100644
--- a/Source/core/rendering/shapes/ShapeInterval.h
+++ b/Source/core/rendering/shapes/ShapeInterval.h
@@ -34,24 +34,197 @@
 
 namespace WebCore {
 
-struct ShapeInterval {
+template <typename T>
+class ShapeInterval {
+    WTF_MAKE_FAST_ALLOCATED;
 public:
-    float x1;
-    float x2;
-
-    ShapeInterval(float x1 = 0, float x2 = 0)
-        : x1(x1)
-        , x2(x2)
+    ShapeInterval(T x1 = 0, T x2 = 0)
+        : m_x1(x1)
+        , m_x2(x2)
     {
+        ASSERT(x2 >= x1);
     }
 
-    bool intersect(const ShapeInterval&, ShapeInterval&) const;
+    T x1() const { return m_x1; }
+    T x2() const { return m_x2; }
+
+    void setX1(T x1)
+    {
+        ASSERT(m_x2 >= x1);
+        m_x1 = x1;
+    }
+
+    void setX2(T x2)
+    {
+        ASSERT(x2 >= m_x1);
+        m_x2 = x2;
+    }
+
+    void set(T x1, T x2)
+    {
+        ASSERT(x2 >= x1);
+        m_x1 = x1;
+        m_x2 = x2;
+    }
+
+    bool overlaps(const ShapeInterval<T>& interval) const
+    {
+        return x2() >= interval.x1() && x1() <= interval.x2();
+    }
+
+    bool contains(const ShapeInterval<T>& interval) const
+    {
+        return x1() <= interval.x1() && x2() >= interval.x2();
+    }
+
+    ShapeInterval<T> intersect(const ShapeInterval<T>& interval) const
+    {
+        ASSERT(overlaps(interval));
+        return ShapeInterval<T>(std::max<T>(x1(), interval.x1()), std::min<T>(x2(), interval.x2()));
+    }
+
+    typedef Vector<ShapeInterval<T> > ShapeIntervals;
+    typedef typename ShapeIntervals::const_iterator const_iterator;
+    typedef typename ShapeIntervals::iterator iterator;
+
+    static void uniteShapeIntervals(const ShapeIntervals& a, const ShapeIntervals& b, ShapeIntervals& result)
+    {
+        ASSERT(shapeIntervalsAreSortedAndDisjoint(a) && shapeIntervalsAreSortedAndDisjoint(b));
+
+        if (a.isEmpty() || a == b) {
+            result.appendRange(b.begin(), b.end());
+            return;
+        }
+
+        if (b.isEmpty()) {
+            result.appendRange(a.begin(), a.end());
+            return;
+        }
+
+        const_iterator aNext = a.begin();
+        const_iterator bNext = b.begin();
+
+        while (aNext != a.end() || bNext != b.end()) {
+            const_iterator next = (bNext == b.end() || (aNext != a.end() && aNext->x1() < bNext->x1())) ? aNext++ : bNext++;
+            if (result.isEmpty() || !result.last().overlaps(*next))
+                result.append(*next);
+            else
+                result.last().setX2(std::max<T>(result.last().x2(), next->x2()));
+        }
+    }
+
+    static void intersectShapeIntervals(const ShapeIntervals& a, const ShapeIntervals& b, ShapeIntervals& result)
+    {
+        ASSERT(shapeIntervalsAreSortedAndDisjoint(a) && shapeIntervalsAreSortedAndDisjoint(b));
+
+        if (a.isEmpty() || b.isEmpty())
+            return;
+
+        if (a == b) {
+            result.appendRange(a.begin(), a.end());
+            return;
+        }
+
+        const_iterator aNext = a.begin();
+        const_iterator bNext = b.begin();
+        const_iterator working = aNext->x1() < bNext->x1() ? aNext++ : bNext++;
+
+        while (aNext != a.end() || bNext != b.end()) {
+            const_iterator next = (bNext == b.end() || (aNext != a.end() && aNext->x1() < bNext->x1())) ? aNext++ : bNext++;
+            if (working->overlaps(*next)) {
+                result.append(working->intersect(*next));
+                if (next->x2() > working->x2())
+                    working = next;
+            } else {
+                working = next;
+            }
+        }
+    }
+
+    static void subtractShapeIntervals(const ShapeIntervals& a, const ShapeIntervals& b, ShapeIntervals& result)
+    {
+        ASSERT(shapeIntervalsAreSortedAndDisjoint(a) && shapeIntervalsAreSortedAndDisjoint(b));
+
+        if (a.isEmpty() || a == b)
+            return;
+
+        if (b.isEmpty()) {
+            result.appendRange(a.begin(), a.end());
+            return;
+        }
+
+        const_iterator aNext = a.begin();
+        const_iterator bNext = b.begin();
+        ShapeInterval<T> aValue = *aNext;
+        ShapeInterval<T> bValue = *bNext;
+
+        do {
+            bool aIncrement = false;
+            bool bIncrement = false;
+
+            if (bValue.contains(aValue)) {
+                aIncrement = true;
+            } else if (aValue.contains(bValue)) {
+                if (bValue.x1() > aValue.x1())
+                    result.append(ShapeInterval<T>(aValue.x1(), bValue.x1()));
+                if (aValue.x2() > bValue.x2())
+                    aValue.setX1(bValue.x2());
+                else
+                    aIncrement = true;
+                bIncrement = true;
+            } else if (aValue.overlaps(bValue)) {
+                if (aValue.x1() < bValue.x1()) {
+                    result.append(ShapeInterval<T>(aValue.x1(), bValue.x1()));
+                    aIncrement = true;
+                } else {
+                    aValue.setX1(bValue.x2());
+                    bIncrement = true;
+                }
+            } else {
+                if (aValue.x1() < bValue.x1()) {
+                    result.append(aValue);
+                    aIncrement = true;
+                } else {
+                    bIncrement = true;
+                }
+            }
+
+            if (aIncrement && ++aNext != a.end())
+                aValue = *aNext;
+            if (bIncrement && ++bNext != b.end())
+                bValue = *bNext;
+
+        } while (aNext != a.end() && bNext != b.end());
+
+        if (aNext != a.end()) {
+            result.append(aValue);
+            result.appendRange(++aNext, a.end());
+        }
+    }
+
+    bool operator==(const ShapeInterval<T>& other) const { return x1() == other.x1() && x2() == other.x2(); }
+    bool operator!=(const ShapeInterval<T>& other) const { return !operator==(other); }
+
+private:
+    T m_x1;
+    T m_x2;
+
+    static bool shapeIntervalsAreSortedAndDisjoint(const ShapeIntervals& intervals)
+    {
+        for (unsigned i = 1; i < intervals.size(); i++) {
+            if (intervals[i - 1].x2() > intervals[i].x1())
+                return false;
+        }
+
+        return true;
+    }
 };
 
-void sortShapeIntervals(Vector<ShapeInterval>&);
-void mergeShapeIntervals(const Vector<ShapeInterval>&, const Vector<ShapeInterval>&, Vector<ShapeInterval>&);
-void intersectShapeIntervals(const Vector<ShapeInterval>&, const Vector<ShapeInterval>&, Vector<ShapeInterval>&);
-void subtractShapeIntervals(const Vector<ShapeInterval>&, const Vector<ShapeInterval>&, Vector<ShapeInterval>&);
+typedef ShapeInterval<int> IntShapeInterval;
+typedef ShapeInterval<float> FloatShapeInterval;
+
+typedef Vector<IntShapeInterval> IntShapeIntervals;
+typedef Vector<FloatShapeInterval> FloatShapeIntervals;
 
 } // namespace WebCore
 
diff --git a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
index 5888fe8..4993a5f 100644
--- a/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
@@ -36,7 +36,7 @@
 bool ShapeOutsideInfo::isEnabledFor(const RenderBox* box)
 {
     ShapeValue* shapeValue = box->style()->shapeOutside();
-    if (!box->isFloatingWithShapeOutside() || !shapeValue)
+    if (!box->isFloating() || !shapeValue)
         return false;
 
     switch (shapeValue->type()) {
diff --git a/Source/core/rendering/style/BorderValue.h b/Source/core/rendering/style/BorderValue.h
index 689f17e..fb8c61c 100644
--- a/Source/core/rendering/style/BorderValue.h
+++ b/Source/core/rendering/style/BorderValue.h
@@ -25,7 +25,7 @@
 #ifndef BorderValue_h
 #define BorderValue_h
 
-#include "core/css/StyleColor.h"
+#include "core/platform/graphics/Color.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 
 namespace WebCore {
@@ -36,7 +36,6 @@
     BorderValue()
         : m_color(0)
         , m_colorIsValid(false)
-        , m_currentColor(false)
         , m_width(3)
         , m_style(BNONE)
         , m_isAuto(AUTO_OFF)
@@ -50,7 +49,7 @@
 
     bool isTransparent() const
     {
-        return m_colorIsValid && !m_currentColor && !m_color.alpha();
+        return m_colorIsValid && !alphaChannel(m_color);
     }
 
     bool isVisible(bool checkStyle = true) const
@@ -60,7 +59,7 @@
 
     bool operator==(const BorderValue& o) const
     {
-        return m_width == o.m_width && m_style == o.m_style && m_color == o.m_color && m_colorIsValid == o.m_colorIsValid && m_currentColor == o.m_currentColor;
+        return m_width == o.m_width && m_style == o.m_style && m_color == o.m_color && m_colorIsValid == o.m_colorIsValid;
     }
 
     bool operator!=(const BorderValue& o) const
@@ -68,24 +67,22 @@
         return !(*this == o);
     }
 
-    void setColor(const StyleColor& color)
+    void setColor(const Color& color)
     {
-        m_color = color.color();
+        m_color = color.rgb();
         m_colorIsValid = color.isValid();
-        m_currentColor = color.isCurrentColor();
     }
 
-    StyleColor color() const { return StyleColor(m_color, m_colorIsValid, m_currentColor); }
+    Color color() const { return Color(m_color, m_colorIsValid); }
 
     unsigned width() const { return m_width; }
     EBorderStyle style() const { return static_cast<EBorderStyle>(m_style); }
 
 protected:
-    Color m_color;
+    RGBA32 m_color;
     unsigned m_colorIsValid : 1;
-    unsigned m_currentColor : 1;
 
-    unsigned m_width : 25;
+    unsigned m_width : 26;
     unsigned m_style : 4; // EBorderStyle
 
     // This is only used by OutlineValue but moved here to keep the bits packed.
diff --git a/Source/core/rendering/style/CachedUAStyle.h b/Source/core/rendering/style/CachedUAStyle.h
index 863212b..f56d66f 100644
--- a/Source/core/rendering/style/CachedUAStyle.h
+++ b/Source/core/rendering/style/CachedUAStyle.h
@@ -54,7 +54,7 @@
     bool hasAppearance;
     BorderData border;
     FillLayer backgroundLayers;
-    StyleColor backgroundColor;
+    Color backgroundColor;
 };
 
 
diff --git a/Source/core/rendering/style/CollapsedBorderValue.h b/Source/core/rendering/style/CollapsedBorderValue.h
index 30716ec..ef16dba 100644
--- a/Source/core/rendering/style/CollapsedBorderValue.h
+++ b/Source/core/rendering/style/CollapsedBorderValue.h
@@ -34,7 +34,6 @@
     CollapsedBorderValue()
         : m_color(0)
         , m_colorIsValid(false)
-        , m_currentColor(false)
         , m_width(0)
         , m_style(BNONE)
         , m_precedence(BOFF)
@@ -42,10 +41,9 @@
     {
     }
 
-    CollapsedBorderValue(const BorderValue& border, const StyleColor& color, EBorderPrecedence precedence)
-        : m_color(color.color())
+    CollapsedBorderValue(const BorderValue& border, const Color& color, EBorderPrecedence precedence)
+        : m_color(color.rgb())
         , m_colorIsValid(color.isValid())
-        , m_currentColor(color.isCurrentColor())
         , m_width(border.nonZero() ? border.width() : 0)
         , m_style(border.style())
         , m_precedence(precedence)
@@ -56,7 +54,7 @@
     unsigned width() const { return m_style > BHIDDEN ? m_width : 0; }
     EBorderStyle style() const { return static_cast<EBorderStyle>(m_style); }
     bool exists() const { return m_precedence != BOFF; }
-    StyleColor color() const { return StyleColor(m_color, m_colorIsValid, m_currentColor); }
+    Color color() const { return Color(m_color, m_colorIsValid); }
     bool isTransparent() const { return m_transparent; }
     EBorderPrecedence precedence() const { return static_cast<EBorderPrecedence>(m_precedence); }
 
@@ -66,10 +64,9 @@
     }
 
 private:
-    Color m_color;
+    RGBA32 m_color;
     unsigned m_colorIsValid : 1;
-    unsigned m_currentColor : 1;
-    unsigned m_width : 22;
+    unsigned m_width : 23;
     unsigned m_style : 4; // EBorderStyle
     unsigned m_precedence : 3; // EBorderPrecedence
     unsigned m_transparent : 1;
diff --git a/Source/core/rendering/style/ContentData.cpp b/Source/core/rendering/style/ContentData.cpp
index 828568f..b75880c 100644
--- a/Source/core/rendering/style/ContentData.cpp
+++ b/Source/core/rendering/style/ContentData.cpp
@@ -66,9 +66,9 @@
     return result.release();
 }
 
-RenderObject* ImageContentData::createRenderer(Document* doc, RenderStyle* pseudoStyle) const
+RenderObject* ImageContentData::createRenderer(Document& doc, RenderStyle* pseudoStyle) const
 {
-    RenderImage* image = RenderImage::createAnonymous(doc);
+    RenderImage* image = RenderImage::createAnonymous(&doc);
     image->setPseudoStyle(pseudoStyle);
     if (m_image)
         image->setImageResource(RenderImageResourceStyleImage::create(m_image.get()));
@@ -77,23 +77,23 @@
     return image;
 }
 
-RenderObject* TextContentData::createRenderer(Document* doc, RenderStyle* pseudoStyle) const
+RenderObject* TextContentData::createRenderer(Document& doc, RenderStyle* pseudoStyle) const
 {
-    RenderObject* renderer = new RenderTextFragment(doc, m_text.impl());
+    RenderObject* renderer = new RenderTextFragment(&doc, m_text.impl());
     renderer->setPseudoStyle(pseudoStyle);
     return renderer;
 }
 
-RenderObject* CounterContentData::createRenderer(Document* doc, RenderStyle* pseudoStyle) const
+RenderObject* CounterContentData::createRenderer(Document& doc, RenderStyle* pseudoStyle) const
 {
-    RenderObject* renderer = new RenderCounter(doc, *m_counter);
+    RenderObject* renderer = new RenderCounter(&doc, *m_counter);
     renderer->setPseudoStyle(pseudoStyle);
     return renderer;
 }
 
-RenderObject* QuoteContentData::createRenderer(Document* doc, RenderStyle* pseudoStyle) const
+RenderObject* QuoteContentData::createRenderer(Document& doc, RenderStyle* pseudoStyle) const
 {
-    RenderObject* renderer = new RenderQuote(doc, m_quote);
+    RenderObject* renderer = new RenderQuote(&doc, m_quote);
     renderer->setPseudoStyle(pseudoStyle);
     return renderer;
 }
diff --git a/Source/core/rendering/style/ContentData.h b/Source/core/rendering/style/ContentData.h
index 00053a7..77dd561 100644
--- a/Source/core/rendering/style/ContentData.h
+++ b/Source/core/rendering/style/ContentData.h
@@ -51,7 +51,7 @@
     virtual bool isQuote() const { return false; }
     virtual bool isText() const { return false; }
 
-    virtual RenderObject* createRenderer(Document*, RenderStyle*) const = 0;
+    virtual RenderObject* createRenderer(Document&, RenderStyle*) const = 0;
 
     virtual PassOwnPtr<ContentData> clone() const;
 
@@ -74,7 +74,7 @@
     void setImage(PassRefPtr<StyleImage> image) { m_image = image; }
 
     virtual bool isImage() const OVERRIDE { return true; }
-    virtual RenderObject* createRenderer(Document*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(Document&, RenderStyle*) const OVERRIDE;
 
     virtual bool equals(const ContentData& data) const OVERRIDE
     {
@@ -105,7 +105,7 @@
     void setText(const String& text) { m_text = text; }
 
     virtual bool isText() const OVERRIDE { return true; }
-    virtual RenderObject* createRenderer(Document*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(Document&, RenderStyle*) const OVERRIDE;
 
     virtual bool equals(const ContentData& data) const OVERRIDE
     {
@@ -132,7 +132,7 @@
     void setCounter(PassOwnPtr<CounterContent> counter) { m_counter = counter; }
 
     virtual bool isCounter() const OVERRIDE { return true; }
-    virtual RenderObject* createRenderer(Document*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(Document&, RenderStyle*) const OVERRIDE;
 
 private:
     CounterContentData(PassOwnPtr<CounterContent> counter)
@@ -163,7 +163,7 @@
     void setQuote(QuoteType quote) { m_quote = quote; }
 
     virtual bool isQuote() const OVERRIDE { return true; }
-    virtual RenderObject* createRenderer(Document*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(Document&, RenderStyle*) const OVERRIDE;
 
     virtual bool equals(const ContentData& data) const OVERRIDE
     {
diff --git a/Source/core/rendering/style/FillLayer.cpp b/Source/core/rendering/style/FillLayer.cpp
index e93d0a1..ca66f47 100644
--- a/Source/core/rendering/style/FillLayer.cpp
+++ b/Source/core/rendering/style/FillLayer.cpp
@@ -54,6 +54,7 @@
     , m_composite(FillLayer::initialFillComposite(type))
     , m_sizeType(FillLayer::initialFillSizeType(type))
     , m_blendMode(FillLayer::initialFillBlendMode(type))
+    , m_maskSourceType(FillLayer::initialFillMaskSourceType(type))
     , m_imageSet(false)
     , m_attachmentSet(false)
     , m_clipSet(false)
@@ -67,6 +68,7 @@
     , m_backgroundYOrigin(TopEdge)
     , m_compositeSet(type == MaskFillLayer)
     , m_blendModeSet(false)
+    , m_maskSourceTypeSet(false)
     , m_type(type)
 {
 }
@@ -85,6 +87,7 @@
     , m_composite(o.m_composite)
     , m_sizeType(o.m_sizeType)
     , m_blendMode(o.m_blendMode)
+    , m_maskSourceType(o.m_maskSourceType)
     , m_imageSet(o.m_imageSet)
     , m_attachmentSet(o.m_attachmentSet)
     , m_clipSet(o.m_clipSet)
@@ -98,6 +101,7 @@
     , m_backgroundYOrigin(o.m_backgroundYOrigin)
     , m_compositeSet(o.m_compositeSet)
     , m_blendModeSet(o.m_blendModeSet)
+    , m_maskSourceTypeSet(o.m_maskSourceTypeSet)
     , m_type(o.m_type)
 {
 }
@@ -129,6 +133,7 @@
     m_repeatX = o.m_repeatX;
     m_repeatY = o.m_repeatY;
     m_sizeType = o.m_sizeType;
+    m_maskSourceType = o.m_maskSourceType;
 
     m_imageSet = o.m_imageSet;
     m_attachmentSet = o.m_attachmentSet;
@@ -140,6 +145,7 @@
     m_repeatYSet = o.m_repeatYSet;
     m_xPosSet = o.m_xPosSet;
     m_yPosSet = o.m_yPosSet;
+    m_maskSourceTypeSet = o.m_maskSourceTypeSet;
 
     m_type = o.m_type;
 
@@ -154,8 +160,9 @@
             && m_backgroundXOrigin == o.m_backgroundXOrigin && m_backgroundYOrigin == o.m_backgroundYOrigin
             && m_attachment == o.m_attachment && m_clip == o.m_clip && m_composite == o.m_composite
             && m_blendMode == o.m_blendMode && m_origin == o.m_origin && m_repeatX == o.m_repeatX
-            && m_repeatY == o.m_repeatY && m_sizeType == o.m_sizeType && m_sizeLength == o.m_sizeLength
-            && m_type == o.m_type && ((m_next && o.m_next) ? *m_next == *o.m_next : m_next == o.m_next);
+            && m_repeatY == o.m_repeatY && m_sizeType == o.m_sizeType && m_maskSourceType == o.m_maskSourceType
+            && m_sizeLength == o.m_sizeLength && m_type == o.m_type
+            && ((m_next && o.m_next) ? *m_next == *o.m_next : m_next == o.m_next);
 }
 
 void FillLayer::fillUnsetProperties()
diff --git a/Source/core/rendering/style/FillLayer.h b/Source/core/rendering/style/FillLayer.h
index 003572f..b0167ee 100644
--- a/Source/core/rendering/style/FillLayer.h
+++ b/Source/core/rendering/style/FillLayer.h
@@ -80,6 +80,7 @@
     LengthSize sizeLength() const { return m_sizeLength; }
     EFillSizeType sizeType() const { return static_cast<EFillSizeType>(m_sizeType); }
     FillSize size() const { return FillSize(static_cast<EFillSizeType>(m_sizeType), m_sizeLength); }
+    EMaskSourceType maskSourceType() const { return static_cast<EMaskSourceType>(m_maskSourceType); }
 
     const FillLayer* next() const { return m_next; }
     FillLayer* next() { return m_next; }
@@ -96,6 +97,7 @@
     bool isCompositeSet() const { return m_compositeSet; }
     bool isBlendModeSet() const { return m_blendModeSet; }
     bool isSizeSet() const { return m_sizeType != SizeNone; }
+    bool isMaskSourceTypeSet() const { return m_maskSourceTypeSet; }
 
     void setImage(PassRefPtr<StyleImage> i) { m_image = i; m_imageSet = true; }
     void setXPosition(Length l) { m_xPosition = l; m_xPosSet = true; }
@@ -112,6 +114,7 @@
     void setSizeType(EFillSizeType b) { m_sizeType = b; }
     void setSizeLength(LengthSize l) { m_sizeLength = l; }
     void setSize(FillSize f) { m_sizeType = f.type; m_sizeLength = f.size; }
+    void setMaskSourceType(EMaskSourceType m) { m_maskSourceType = m; m_maskSourceTypeSet = true; }
 
     void clearImage() { m_image.clear(); m_imageSet = false; }
     void clearXPosition()
@@ -133,6 +136,7 @@
     void clearComposite() { m_compositeSet = false; }
     void clearBlendMode() { m_blendModeSet = false; }
     void clearSize() { m_sizeType = SizeNone; }
+    void clearMaskSourceType() { m_maskSourceTypeSet = false; }
 
     void setNext(FillLayer* n) { if (m_next != n) { delete m_next; m_next = n; } }
 
@@ -184,6 +188,7 @@
     static Length initialFillXPosition(EFillLayerType) { return Length(0.0, Percent); }
     static Length initialFillYPosition(EFillLayerType) { return Length(0.0, Percent); }
     static StyleImage* initialFillImage(EFillLayerType) { return 0; }
+    static EMaskSourceType initialFillMaskSourceType(EFillLayerType) { return MaskAlpha; }
 
 private:
     friend class RenderStyle;
@@ -209,6 +214,7 @@
     unsigned m_composite : 4; // CompositeOperator
     unsigned m_sizeType : 2; // EFillSizeType
     unsigned m_blendMode : 5; // BlendMode
+    unsigned m_maskSourceType : 1; // EMaskSourceType
 
     unsigned m_imageSet : 1;
     unsigned m_attachmentSet : 1;
@@ -223,6 +229,7 @@
     unsigned m_backgroundYOrigin : 2; // BackgroundEdgeOrigin
     unsigned m_compositeSet : 1;
     unsigned m_blendModeSet : 1;
+    unsigned m_maskSourceTypeSet : 1;
 
     unsigned m_type : 1; // EFillLayerType
 
diff --git a/Source/core/rendering/style/KeyframeList.cpp b/Source/core/rendering/style/KeyframeList.cpp
index 093d796..feaf484 100644
--- a/Source/core/rendering/style/KeyframeList.cpp
+++ b/Source/core/rendering/style/KeyframeList.cpp
@@ -22,6 +22,7 @@
 #include "config.h"
 #include "core/rendering/style/KeyframeList.h"
 
+#include "core/animation/Animation.h"
 #include "core/css/StylePropertySet.h"
 #include "core/rendering/RenderObject.h"
 
@@ -41,6 +42,18 @@
     }
 }
 
+TimingFunction* KeyframeValue::timingFunction(const AtomicString& name) const
+{
+    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())
+            return keyframeStyle->animations()->animation(i)->timingFunction();
+    }
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
 KeyframeList::~KeyframeList()
 {
     clear();
diff --git a/Source/core/rendering/style/KeyframeList.h b/Source/core/rendering/style/KeyframeList.h
index 4d5e207..85df598 100644
--- a/Source/core/rendering/style/KeyframeList.h
+++ b/Source/core/rendering/style/KeyframeList.h
@@ -37,6 +37,7 @@
 class RenderObject;
 class RenderStyle;
 class StylePropertySet;
+class TimingFunction;
 
 class KeyframeValue {
 public:
@@ -57,6 +58,8 @@
     const RenderStyle* style() const { return m_style.get(); }
     void setStyle(PassRefPtr<RenderStyle> style) { m_style = style; }
 
+    TimingFunction* timingFunction(const AtomicString& name) const;
+
 private:
     double m_key;
     HashSet<CSSPropertyID> m_properties; // The properties specified in this keyframe.
diff --git a/Source/core/rendering/style/RenderStyle.cpp b/Source/core/rendering/style/RenderStyle.cpp
index 69c874b..659d99e 100644
--- a/Source/core/rendering/style/RenderStyle.cpp
+++ b/Source/core/rendering/style/RenderStyle.cpp
@@ -80,7 +80,7 @@
 
 PassRefPtr<RenderStyle> RenderStyle::createDefaultStyle()
 {
-    return adoptRef(new RenderStyle(true));
+    return adoptRef(new RenderStyle(DefaultStyle));
 }
 
 PassRefPtr<RenderStyle> RenderStyle::createAnonymousStyleWithDisplay(const RenderStyle* parentStyle, EDisplay display)
@@ -112,7 +112,7 @@
     COMPILE_ASSERT((sizeof(NonInheritedFlags) <= 8), NonInheritedFlags_does_not_grow);
 }
 
-ALWAYS_INLINE RenderStyle::RenderStyle(bool)
+ALWAYS_INLINE RenderStyle::RenderStyle(DefaultStyleTag)
 {
     setBitDefaults();
 
@@ -149,6 +149,54 @@
 {
 }
 
+static StyleRecalcChange comparePseudoStyles(const RenderStyle* oldStyle, const RenderStyle* newStyle)
+{
+    // If the pseudoStyles have changed, we want any StyleRecalcChange that is not NoChange
+    // because setStyle will do the right thing with anything else.
+    if (!oldStyle->hasAnyPublicPseudoStyles())
+        return NoChange;
+    for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; pseudoId < FIRST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
+        if (!oldStyle->hasPseudoStyle(pseudoId))
+            continue;
+        RenderStyle* newPseudoStyle = newStyle->getCachedPseudoStyle(pseudoId);
+        if (!newPseudoStyle)
+            return NoInherit;
+        RenderStyle* oldPseudoStyle = oldStyle->getCachedPseudoStyle(pseudoId);
+        if (oldPseudoStyle && *oldPseudoStyle != *newPseudoStyle)
+            return NoInherit;
+    }
+    return NoChange;
+}
+
+StyleRecalcChange RenderStyle::compare(const RenderStyle* oldStyle, const RenderStyle* newStyle)
+{
+    if ((!oldStyle && newStyle) || (oldStyle && !newStyle))
+        return Reattach;
+
+    if (!oldStyle && !newStyle)
+        return NoChange;
+
+    if (oldStyle->display() != newStyle->display()
+        || oldStyle->hasPseudoStyle(FIRST_LETTER) != newStyle->hasPseudoStyle(FIRST_LETTER)
+        || oldStyle->columnSpan() != newStyle->columnSpan()
+        || oldStyle->specifiesAutoColumns() != newStyle->specifiesAutoColumns()
+        || !oldStyle->contentDataEquivalent(newStyle)
+        || oldStyle->hasTextCombine() != newStyle->hasTextCombine()
+        || oldStyle->flowThread() != newStyle->flowThread()
+        || oldStyle->regionThread() != newStyle->regionThread())
+        return Reattach;
+
+    if (*oldStyle == *newStyle)
+        return comparePseudoStyles(oldStyle, newStyle);
+
+    if (oldStyle->inheritedNotEqual(newStyle)
+        || oldStyle->hasExplicitlyInheritedProperties()
+        || newStyle->hasExplicitlyInheritedProperties())
+        return Inherit;
+
+    return NoInherit;
+}
+
 void RenderStyle::inheritFrom(const RenderStyle* inheritParent, IsAtShadowBoundary isAtShadowBoundary)
 {
     if (isAtShadowBoundary == AtShadowBoundary) {
@@ -186,6 +234,7 @@
     noninherited_flags._page_break_after = other->noninherited_flags._page_break_after;
     noninherited_flags._page_break_inside = other->noninherited_flags._page_break_inside;
     noninherited_flags.explicitInheritance = other->noninherited_flags.explicitInheritance;
+    noninherited_flags.currentColor = other->noninherited_flags.currentColor;
     if (m_svgStyle != other->m_svgStyle)
         m_svgStyle.access()->copyNonInheritedFrom(other->m_svgStyle.get());
     ASSERT(zoom() == initialZoom());
@@ -543,8 +592,7 @@
     if ((visibility() == COLLAPSE) != (other->visibility() == COLLAPSE))
         return StyleDifferenceLayout;
 
-    if ((rareNonInheritedData->opacity == 1 && other->rareNonInheritedData->opacity < 1)
-        || (rareNonInheritedData->opacity < 1 && other->rareNonInheritedData->opacity == 1)) {
+    if (rareNonInheritedData->hasOpacity() != other->rareNonInheritedData->hasOpacity()) {
         // FIXME: We would like to use SimplifiedLayout here, but we can't quite do that yet.
         // We need to make sure SimplifiedLayout can operate correctly on RenderInlines (we will need
         // to add a selfNeedsSimplifiedLayout bit in order to not get confused and taint every line).
@@ -553,6 +601,9 @@
         return StyleDifferenceLayout;
     }
 
+    if (rareNonInheritedData->hasFilters() != other->rareNonInheritedData->hasFilters())
+        return StyleDifferenceLayout;
+
     if (!QuotesData::equals(rareInheritedData->quotes.get(), other->rareInheritedData->quotes.get()))
         return StyleDifferenceLayout;
 
@@ -916,10 +967,10 @@
         rareInheritedData.access()->listStyleImage = v;
 }
 
-StyleColor RenderStyle::color() const { return inherited->color; }
-StyleColor RenderStyle::visitedLinkColor() const { return inherited->visitedLinkColor; }
-void RenderStyle::setColor(const StyleColor& v) { SET_VAR(inherited, color, v); }
-void RenderStyle::setVisitedLinkColor(const StyleColor& v) { SET_VAR(inherited, visitedLinkColor, v); }
+Color RenderStyle::color() const { return inherited->color; }
+Color RenderStyle::visitedLinkColor() const { return inherited->visitedLinkColor; }
+void RenderStyle::setColor(const Color& v) { SET_VAR(inherited, color, v); }
+void RenderStyle::setVisitedLinkColor(const Color& v) { SET_VAR(inherited, visitedLinkColor, v); }
 
 short RenderStyle::horizontalBorderSpacing() const { return inherited->horizontal_border_spacing; }
 short RenderStyle::verticalBorderSpacing() const { return inherited->vertical_border_spacing; }
@@ -1291,9 +1342,9 @@
     }
 }
 
-StyleColor RenderStyle::colorIncludingFallback(int colorProperty, bool visitedLink) const
+Color RenderStyle::colorIncludingFallback(int colorProperty, bool visitedLink) const
 {
-    StyleColor result;
+    Color result;
     EBorderStyle borderStyle = BNONE;
     switch (colorProperty) {
     case CSSPropertyBackgroundColor:
@@ -1352,7 +1403,7 @@
         break;
     }
 
-    if (!result.isValid() && !result.isCurrentColor()) {
+    if (!result.isValid()) {
         if (!visitedLink && (borderStyle == INSET || borderStyle == OUTSET || borderStyle == RIDGE || borderStyle == GROOVE))
             result.setRGB(238, 238, 238);
         else
@@ -1361,13 +1412,13 @@
     return result;
 }
 
-StyleColor RenderStyle::visitedDependentColor(int colorProperty) const
+Color RenderStyle::visitedDependentColor(int colorProperty) const
 {
-    StyleColor unvisitedColor = colorIncludingFallback(colorProperty, false);
+    Color unvisitedColor = colorIncludingFallback(colorProperty, false);
     if (insideLink() != InsideVisitedLink)
         return unvisitedColor;
 
-    StyleColor visitedColor = colorIncludingFallback(colorProperty, true);
+    Color visitedColor = colorIncludingFallback(colorProperty, true);
 
     // Text decoration color validity is preserved (checked in RenderObject::decorationColor).
     if (colorProperty == CSSPropertyTextDecorationColor)
@@ -1381,12 +1432,8 @@
     if (colorProperty == CSSPropertyBackgroundColor && visitedColor == Color::transparent)
         return unvisitedColor;
 
-    // Unless the visitied color is 'currentColor'; take the alpha from the unvisited color,
-    // but get the RGB values from the visited color.
-    if (visitedColor.isCurrentColor())
-        return visitedColor;
-
-    return StyleColor(visitedColor.red(), visitedColor.green(), visitedColor.blue(), unvisitedColor.alpha());
+    // Take the alpha from the unvisited color, but get the RGB values from the visited color.
+    return Color(visitedColor.red(), visitedColor.green(), visitedColor.blue(), unvisitedColor.alpha());
 }
 
 const BorderValue& RenderStyle::borderBefore() const
diff --git a/Source/core/rendering/style/RenderStyle.h b/Source/core/rendering/style/RenderStyle.h
index 00d3baa..290cf26 100644
--- a/Source/core/rendering/style/RenderStyle.h
+++ b/Source/core/rendering/style/RenderStyle.h
@@ -29,7 +29,6 @@
 #include "core/css/CSSLineBoxContainValue.h"
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/css/LengthFunctions.h"
-#include "core/css/StyleColor.h"
 #include "core/platform/Length.h"
 #include "core/platform/LengthBox.h"
 #include "core/platform/LengthSize.h"
@@ -217,6 +216,7 @@
                 && _pseudoBits == other._pseudoBits
                 && _unicodeBidi == other._unicodeBidi
                 && explicitInheritance == other.explicitInheritance
+                && currentColor == other.currentColor
                 && unique == other.unique
                 && emptyState == other.emptyState
                 && firstChildState == other.firstChildState
@@ -245,6 +245,7 @@
         unsigned _styleType : 6; // PseudoId
         unsigned _pseudoBits : 8;
         unsigned explicitInheritance : 1; // Explicitly inherits a non-inherited property
+        unsigned currentColor : 1; // At least one color has the value 'currentColor'
         unsigned unique : 1; // Style can not be shared.
         unsigned emptyState : 1;
         unsigned firstChildState : 1;
@@ -306,6 +307,7 @@
         noninherited_flags._styleType = NOPSEUDO;
         noninherited_flags._pseudoBits = 0;
         noninherited_flags.explicitInheritance = false;
+        noninherited_flags.currentColor = false;
         noninherited_flags.unique = false;
         noninherited_flags.emptyState = false;
         noninherited_flags.firstChildState = false;
@@ -318,8 +320,11 @@
 
 private:
     ALWAYS_INLINE RenderStyle();
-    // used to create the default style.
-    ALWAYS_INLINE RenderStyle(bool);
+
+    enum DefaultStyleTag {
+        DefaultStyle
+    };
+    ALWAYS_INLINE explicit RenderStyle(DefaultStyleTag);
     ALWAYS_INLINE RenderStyle(const RenderStyle&);
 
 public:
@@ -328,6 +333,8 @@
     static PassRefPtr<RenderStyle> createAnonymousStyleWithDisplay(const RenderStyle* parentStyle, EDisplay);
     static PassRefPtr<RenderStyle> clone(const RenderStyle*);
 
+    static StyleRecalcChange compare(const RenderStyle* oldStyle, const RenderStyle* newStyle);
+
     enum IsAtShadowBoundary {
         AtShadowBoundary,
         NotAtShadowBoundary,
@@ -375,8 +382,8 @@
 
     bool hasBackground() const
     {
-        StyleColor color = visitedDependentColor(CSSPropertyBackgroundColor);
-        if ((color.isValid() && color.alpha()) || color.isCurrentColor())
+        Color color = visitedDependentColor(CSSPropertyBackgroundColor);
+        if (color.isValid() && color.alpha())
             return true;
         return hasBackgroundImage();
     }
@@ -791,6 +798,7 @@
     bool hasAutoColumnWidth() const { return rareNonInheritedData->m_multiCol->m_autoWidth; }
     unsigned short columnCount() const { return rareNonInheritedData->m_multiCol->m_count; }
     bool hasAutoColumnCount() const { return rareNonInheritedData->m_multiCol->m_autoCount; }
+    bool specifiesAutoColumns() const { return hasAutoColumnCount() && hasAutoColumnWidth(); }
     bool specifiesColumns() const { return !hasAutoColumnCount() || !hasAutoColumnWidth() || !hasInlineColumnAxis(); }
     float columnGap() const { return rareNonInheritedData->m_multiCol->m_gap; }
     bool hasNormalColumnGap() const { return rareNonInheritedData->m_multiCol->m_normalGap; }
@@ -879,7 +887,7 @@
 
     LineBoxContain lineBoxContain() const { return rareInheritedData->m_lineBoxContain; }
     const LineClampValue& lineClamp() const { return rareNonInheritedData->lineClamp; }
-    StyleColor tapHighlightColor() const { return rareInheritedData->tapHighlightColor; }
+    Color tapHighlightColor() const { return rareInheritedData->tapHighlightColor; }
     ETextSecurity textSecurity() const { return static_cast<ETextSecurity>(rareInheritedData->textSecurity); }
 
     WritingMode writingMode() const { return static_cast<WritingMode>(inherited_flags.m_writingMode); }
@@ -956,7 +964,7 @@
     void resetBorderBottomLeftRadius() { SET_VAR(surround, border.m_bottomLeft, initialBorderRadius()); }
     void resetBorderBottomRightRadius() { SET_VAR(surround, border.m_bottomRight, initialBorderRadius()); }
 
-    void setBackgroundColor(const StyleColor& v) { SET_VAR(m_background, m_color, v); }
+    void setBackgroundColor(const Color& v) { SET_VAR(m_background, m_color, v); }
 
     void setBackgroundXPosition(Length length) { SET_VAR(m_background, m_background.m_xPosition, length); }
     void setBackgroundYPosition(Length length) { SET_VAR(m_background, m_background.m_yPosition, length); }
@@ -994,21 +1002,21 @@
 
     void setBorderLeftWidth(unsigned v) { SET_VAR(surround, border.m_left.m_width, v); }
     void setBorderLeftStyle(EBorderStyle v) { SET_VAR(surround, border.m_left.m_style, v); }
-    void setBorderLeftColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(surround, border.m_left, v); }
+    void setBorderLeftColor(const Color& v) { SET_BORDERVALUE_COLOR(surround, border.m_left, v); }
     void setBorderRightWidth(unsigned v) { SET_VAR(surround, border.m_right.m_width, v); }
     void setBorderRightStyle(EBorderStyle v) { SET_VAR(surround, border.m_right.m_style, v); }
-    void setBorderRightColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(surround, border.m_right, v); }
+    void setBorderRightColor(const Color& v) { SET_BORDERVALUE_COLOR(surround, border.m_right, v); }
     void setBorderTopWidth(unsigned v) { SET_VAR(surround, border.m_top.m_width, v); }
     void setBorderTopStyle(EBorderStyle v) { SET_VAR(surround, border.m_top.m_style, v); }
-    void setBorderTopColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(surround, border.m_top, v); }
+    void setBorderTopColor(const Color& v) { SET_BORDERVALUE_COLOR(surround, border.m_top, v); }
     void setBorderBottomWidth(unsigned v) { SET_VAR(surround, border.m_bottom.m_width, v); }
     void setBorderBottomStyle(EBorderStyle v) { SET_VAR(surround, border.m_bottom.m_style, v); }
-    void setBorderBottomColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(surround, border.m_bottom, v); }
+    void setBorderBottomColor(const Color& v) { SET_BORDERVALUE_COLOR(surround, border.m_bottom, v); }
 
     void setOutlineWidth(unsigned short v) { SET_VAR(m_background, m_outline.m_width, v); }
     void setOutlineStyleIsAuto(OutlineIsAuto isAuto) { SET_VAR(m_background, m_outline.m_isAuto, isAuto); }
     void setOutlineStyle(EBorderStyle v) { SET_VAR(m_background, m_outline.m_style, v); }
-    void setOutlineColor(const StyleColor& v) { SET_BORDERVALUE_COLOR(m_background, m_outline, v); }
+    void setOutlineColor(const Color& v) { SET_BORDERVALUE_COLOR(m_background, m_outline, v); }
 
     void setOverflowX(EOverflow v) { noninherited_flags._overflowX = v; }
     void setOverflowY(EOverflow v) { noninherited_flags._overflowY = v; }
@@ -1030,7 +1038,7 @@
     void setTableLayout(ETableLayout v) { noninherited_flags._table_layout = v; }
 
     bool setFontDescription(const FontDescription&);
-    // Only used for blending font sizes when animating, for MathML anonymous blocks, and for text autosizing.
+    // Only used for blending font sizes when animating and for text autosizing.
     void setFontSize(float);
 
     void setTextAutosizingMultiplier(float v)
@@ -1039,7 +1047,7 @@
         setFontSize(fontDescription().specifiedSize());
     }
 
-    void setColor(const StyleColor&);
+    void setColor(const Color&);
     void setTextIndent(Length v) { SET_VAR(rareInheritedData, indent, v); }
     void setTextIndentLine(TextIndentLine v) { SET_VAR(rareInheritedData, m_textIndentLine, v); }
     void setTextAlign(ETextAlign v) { inherited_flags._text_align = v; }
@@ -1154,9 +1162,9 @@
     // CSS3 Setters
     void setOutlineOffset(int v) { SET_VAR(m_background, m_outline.m_offset, v); }
     void setTextShadow(PassOwnPtr<ShadowData>, bool add = false);
-    void setTextStrokeColor(const StyleColor& c) { SET_VAR(rareInheritedData, textStrokeColor, c); }
+    void setTextStrokeColor(const Color& c) { SET_VAR(rareInheritedData, textStrokeColor, c); }
     void setTextStrokeWidth(float w) { SET_VAR(rareInheritedData, textStrokeWidth, w); }
-    void setTextFillColor(const StyleColor& c) { SET_VAR(rareInheritedData, textFillColor, c); }
+    void setTextFillColor(const Color& c) { SET_VAR(rareInheritedData, textFillColor, c); }
     void setOpacity(float f) { float v = clampTo<float>(f, 0, 1); SET_VAR(rareNonInheritedData, opacity, v); }
     void setAppearance(ControlPart a) { SET_VAR(rareNonInheritedData, m_appearance, a); }
     // For valid values of box-align see http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#alignment
@@ -1228,7 +1236,7 @@
     void setHasAutoColumnCount() { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_autoCount, true); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_count, 0); }
     void setColumnGap(float f) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_normalGap, false); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_gap, f); }
     void setHasNormalColumnGap() { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_normalGap, true); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_gap, 0); }
-    void setColumnRuleColor(const StyleColor& c) { SET_BORDERVALUE_COLOR(rareNonInheritedData.access()->m_multiCol, m_rule, c); }
+    void setColumnRuleColor(const Color& c) { SET_BORDERVALUE_COLOR(rareNonInheritedData.access()->m_multiCol, m_rule, c); }
     void setColumnRuleStyle(EBorderStyle b) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_rule.m_style, b); }
     void setColumnRuleWidth(unsigned short w) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_rule.m_width, w); }
     void resetColumnRule() { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_rule, BorderValue()); }
@@ -1247,8 +1255,8 @@
     void setTransformOriginZ(float f) { SET_VAR(rareNonInheritedData.access()->m_transform, m_z, f); }
     void setSpeak(ESpeak s) { SET_VAR(rareInheritedData, speak, s); }
     void setTextCombine(TextCombine v) { SET_VAR(rareNonInheritedData, m_textCombine, v); }
-    void setTextDecorationColor(const StyleColor& c) { SET_VAR(rareNonInheritedData, m_textDecorationColor, c); }
-    void setTextEmphasisColor(const StyleColor& c) { SET_VAR(rareInheritedData, textEmphasisColor, c); }
+    void setTextDecorationColor(const Color& c) { SET_VAR(rareNonInheritedData, m_textDecorationColor, c); }
+    void setTextEmphasisColor(const Color& c) { SET_VAR(rareInheritedData, textEmphasisColor, c); }
     void setTextEmphasisFill(TextEmphasisFill fill) { SET_VAR(rareInheritedData, textEmphasisFill, fill); }
     void setTextEmphasisMark(TextEmphasisMark mark) { SET_VAR(rareInheritedData, textEmphasisMark, mark); }
     void setTextEmphasisCustomMark(const AtomicString& mark) { SET_VAR(rareInheritedData, textEmphasisCustomMark, mark); }
@@ -1305,7 +1313,7 @@
 
     void setLineBoxContain(LineBoxContain c) { SET_VAR(rareInheritedData, m_lineBoxContain, c); }
     void setLineClamp(LineClampValue c) { SET_VAR(rareNonInheritedData, lineClamp, c); }
-    void setTapHighlightColor(const StyleColor& c) { SET_VAR(rareInheritedData, tapHighlightColor, c); }
+    void setTapHighlightColor(const Color& c) { SET_VAR(rareInheritedData, tapHighlightColor, c); }
     void setTextSecurity(ETextSecurity aTextSecurity) { SET_VAR(rareInheritedData, textSecurity, aTextSecurity); }
     void setTouchAction(TouchAction t) { SET_VAR(rareNonInheritedData, m_touchAction, t); }
 
@@ -1313,14 +1321,14 @@
     SVGRenderStyle* accessSVGStyle() { return m_svgStyle.access(); }
 
     const SVGPaint::SVGPaintType& fillPaintType() const { return svgStyle()->fillPaintType(); }
-    StyleColor fillPaintColor() const { return svgStyle()->fillPaintColor(); }
-    void setFillPaintColor(const StyleColor& c) { accessSVGStyle()->setFillPaint(SVGPaint::SVG_PAINTTYPE_RGBCOLOR, c.color(), ""); }
+    Color fillPaintColor() const { return svgStyle()->fillPaintColor(); }
+    void setFillPaintColor(const Color& c) { accessSVGStyle()->setFillPaint(SVGPaint::SVG_PAINTTYPE_RGBCOLOR, c, ""); }
     float fillOpacity() const { return svgStyle()->fillOpacity(); }
     void setFillOpacity(float f) { accessSVGStyle()->setFillOpacity(f); }
 
     const SVGPaint::SVGPaintType& strokePaintType() const { return svgStyle()->strokePaintType(); }
-    StyleColor strokePaintColor() const { return svgStyle()->strokePaintColor(); }
-    void setStrokePaintColor(const StyleColor& c) { accessSVGStyle()->setStrokePaint(SVGPaint::SVG_PAINTTYPE_RGBCOLOR, c.color(), ""); }
+    Color strokePaintColor() const { return svgStyle()->strokePaintColor(); }
+    void setStrokePaintColor(const Color& c) { accessSVGStyle()->setStrokePaint(SVGPaint::SVG_PAINTTYPE_RGBCOLOR, c, ""); }
     float strokeOpacity() const { return svgStyle()->strokeOpacity(); }
     void setStrokeOpacity(float f) { accessSVGStyle()->setStrokeOpacity(f); }
     SVGLength strokeWidth() const { return svgStyle()->strokeWidth(); }
@@ -1338,9 +1346,9 @@
     float stopOpacity() const { return svgStyle()->stopOpacity(); }
     void setStopOpacity(float f) { accessSVGStyle()->setStopOpacity(f); }
 
-    void setStopColor(const StyleColor& c) { accessSVGStyle()->setStopColor(c.color()); }
-    void setFloodColor(const StyleColor& c) { accessSVGStyle()->setFloodColor(c.color()); }
-    void setLightingColor(const StyleColor& c) { accessSVGStyle()->setLightingColor(c.color()); }
+    void setStopColor(const Color& c) { accessSVGStyle()->setStopColor(c); }
+    void setFloodColor(const Color& c) { accessSVGStyle()->setFloodColor(c); }
+    void setLightingColor(const Color& c) { accessSVGStyle()->setLightingColor(c); }
 
     SVGLength baselineShiftValue() const { return svgStyle()->baselineShiftValue(); }
     void setBaselineShiftValue(SVGLength s) { accessSVGStyle()->setBaselineShiftValue(s); }
@@ -1443,11 +1451,14 @@
     bool lastChildState() const { return noninherited_flags.lastChildState; }
     void setLastChildState() { setUnique(); noninherited_flags.lastChildState = true; }
 
-    StyleColor visitedDependentColor(int colorProperty) const;
+    Color visitedDependentColor(int colorProperty) const;
 
     void setHasExplicitlyInheritedProperties() { noninherited_flags.explicitInheritance = true; }
     bool hasExplicitlyInheritedProperties() const { return noninherited_flags.explicitInheritance; }
 
+    void setHasCurrentColor() { noninherited_flags.currentColor = true; }
+    bool hasCurrentColor() const { return noninherited_flags.currentColor; }
+
     // Initial values for all the properties
     static EBorderCollapse initialBorderCollapse() { return BSEPARATE; }
     static EBorderStyle initialBorderStyle() { return BNONE; }
@@ -1632,18 +1643,18 @@
     static const FilterOperations& initialFilter() { DEFINE_STATIC_LOCAL(FilterOperations, ops, ()); return ops; }
     static BlendMode initialBlendMode() { return BlendModeNormal; }
 private:
-    void setVisitedLinkColor(const StyleColor&);
-    void setVisitedLinkBackgroundColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBackgroundColor, v); }
-    void setVisitedLinkBorderLeftColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderLeftColor, v); }
-    void setVisitedLinkBorderRightColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderRightColor, v); }
-    void setVisitedLinkBorderBottomColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderBottomColor, v); }
-    void setVisitedLinkBorderTopColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderTopColor, v); }
-    void setVisitedLinkOutlineColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkOutlineColor, v); }
-    void setVisitedLinkColumnRuleColor(const StyleColor& v) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_visitedLinkColumnRuleColor, v); }
-    void setVisitedLinkTextDecorationColor(const StyleColor& v) { SET_VAR(rareNonInheritedData, m_visitedLinkTextDecorationColor, v); }
-    void setVisitedLinkTextEmphasisColor(const StyleColor& v) { SET_VAR(rareInheritedData, visitedLinkTextEmphasisColor, v); }
-    void setVisitedLinkTextFillColor(const StyleColor& v) { SET_VAR(rareInheritedData, visitedLinkTextFillColor, v); }
-    void setVisitedLinkTextStrokeColor(const StyleColor& v) { SET_VAR(rareInheritedData, visitedLinkTextStrokeColor, v); }
+    void setVisitedLinkColor(const Color&);
+    void setVisitedLinkBackgroundColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBackgroundColor, v); }
+    void setVisitedLinkBorderLeftColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderLeftColor, v); }
+    void setVisitedLinkBorderRightColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderRightColor, v); }
+    void setVisitedLinkBorderBottomColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderBottomColor, v); }
+    void setVisitedLinkBorderTopColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkBorderTopColor, v); }
+    void setVisitedLinkOutlineColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkOutlineColor, v); }
+    void setVisitedLinkColumnRuleColor(const Color& v) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_visitedLinkColumnRuleColor, v); }
+    void setVisitedLinkTextDecorationColor(const Color& v) { SET_VAR(rareNonInheritedData, m_visitedLinkTextDecorationColor, v); }
+    void setVisitedLinkTextEmphasisColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextEmphasisColor, v); }
+    void setVisitedLinkTextFillColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextFillColor, v); }
+    void setVisitedLinkTextStrokeColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextStrokeColor, v); }
 
     void inheritUnicodeBidiFrom(const RenderStyle* parent) { noninherited_flags._unicodeBidi = parent->noninherited_flags._unicodeBidi; }
     void getShadowExtent(const ShadowData*, LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const;
@@ -1671,37 +1682,37 @@
     }
 
     // Color accessors are all private to make sure callers use visitedDependentColor instead to access them.
-    StyleColor invalidColor() const { static Color invalid; return invalid; }
-    StyleColor borderLeftColor() const { return surround->border.left().color(); }
-    StyleColor borderRightColor() const { return surround->border.right().color(); }
-    StyleColor borderTopColor() const { return surround->border.top().color(); }
-    StyleColor borderBottomColor() const { return surround->border.bottom().color(); }
-    StyleColor backgroundColor() const { return m_background->color(); }
-    StyleColor color() const;
-    StyleColor columnRuleColor() const { return rareNonInheritedData->m_multiCol->m_rule.color(); }
-    StyleColor outlineColor() const { return m_background->outline().color(); }
-    StyleColor textEmphasisColor() const { return rareInheritedData->textEmphasisColor; }
-    StyleColor textFillColor() const { return rareInheritedData->textFillColor; }
-    StyleColor textStrokeColor() const { return rareInheritedData->textStrokeColor; }
-    StyleColor visitedLinkColor() const;
-    StyleColor visitedLinkBackgroundColor() const { return rareNonInheritedData->m_visitedLinkBackgroundColor; }
-    StyleColor visitedLinkBorderLeftColor() const { return rareNonInheritedData->m_visitedLinkBorderLeftColor; }
-    StyleColor visitedLinkBorderRightColor() const { return rareNonInheritedData->m_visitedLinkBorderRightColor; }
-    StyleColor visitedLinkBorderBottomColor() const { return rareNonInheritedData->m_visitedLinkBorderBottomColor; }
-    StyleColor visitedLinkBorderTopColor() const { return rareNonInheritedData->m_visitedLinkBorderTopColor; }
-    StyleColor visitedLinkOutlineColor() const { return rareNonInheritedData->m_visitedLinkOutlineColor; }
-    StyleColor visitedLinkColumnRuleColor() const { return rareNonInheritedData->m_multiCol->m_visitedLinkColumnRuleColor; }
-    StyleColor textDecorationColor() const { return rareNonInheritedData->m_textDecorationColor; }
-    StyleColor visitedLinkTextDecorationColor() const { return rareNonInheritedData->m_visitedLinkTextDecorationColor; }
-    StyleColor visitedLinkTextEmphasisColor() const { return rareInheritedData->visitedLinkTextEmphasisColor; }
-    StyleColor visitedLinkTextFillColor() const { return rareInheritedData->visitedLinkTextFillColor; }
-    StyleColor visitedLinkTextStrokeColor() const { return rareInheritedData->visitedLinkTextStrokeColor; }
+    Color invalidColor() const { static Color invalid; return invalid; }
+    Color borderLeftColor() const { return surround->border.left().color(); }
+    Color borderRightColor() const { return surround->border.right().color(); }
+    Color borderTopColor() const { return surround->border.top().color(); }
+    Color borderBottomColor() const { return surround->border.bottom().color(); }
+    Color backgroundColor() const { return m_background->color(); }
+    Color color() const;
+    Color columnRuleColor() const { return rareNonInheritedData->m_multiCol->m_rule.color(); }
+    Color outlineColor() const { return m_background->outline().color(); }
+    Color textEmphasisColor() const { return rareInheritedData->textEmphasisColor; }
+    Color textFillColor() const { return rareInheritedData->textFillColor; }
+    Color textStrokeColor() const { return rareInheritedData->textStrokeColor; }
+    Color visitedLinkColor() const;
+    Color visitedLinkBackgroundColor() const { return rareNonInheritedData->m_visitedLinkBackgroundColor; }
+    Color visitedLinkBorderLeftColor() const { return rareNonInheritedData->m_visitedLinkBorderLeftColor; }
+    Color visitedLinkBorderRightColor() const { return rareNonInheritedData->m_visitedLinkBorderRightColor; }
+    Color visitedLinkBorderBottomColor() const { return rareNonInheritedData->m_visitedLinkBorderBottomColor; }
+    Color visitedLinkBorderTopColor() const { return rareNonInheritedData->m_visitedLinkBorderTopColor; }
+    Color visitedLinkOutlineColor() const { return rareNonInheritedData->m_visitedLinkOutlineColor; }
+    Color visitedLinkColumnRuleColor() const { return rareNonInheritedData->m_multiCol->m_visitedLinkColumnRuleColor; }
+    Color textDecorationColor() const { return rareNonInheritedData->m_textDecorationColor; }
+    Color visitedLinkTextDecorationColor() const { return rareNonInheritedData->m_visitedLinkTextDecorationColor; }
+    Color visitedLinkTextEmphasisColor() const { return rareInheritedData->visitedLinkTextEmphasisColor; }
+    Color visitedLinkTextFillColor() const { return rareInheritedData->visitedLinkTextFillColor; }
+    Color visitedLinkTextStrokeColor() const { return rareInheritedData->visitedLinkTextStrokeColor; }
 
-    StyleColor colorIncludingFallback(int colorProperty, bool visitedLink) const;
+    Color colorIncludingFallback(int colorProperty, bool visitedLink) const;
 
-    StyleColor stopColor() const { return svgStyle()->stopColor(); }
-    StyleColor floodColor() const { return svgStyle()->floodColor(); }
-    StyleColor lightingColor() const { return svgStyle()->lightingColor(); }
+    Color stopColor() const { return svgStyle()->stopColor(); }
+    Color floodColor() const { return svgStyle()->floodColor(); }
+    Color lightingColor() const { return svgStyle()->lightingColor(); }
 
     void appendContent(PassOwnPtr<ContentData>);
 };
diff --git a/Source/core/rendering/style/RenderStyleConstants.h b/Source/core/rendering/style/RenderStyleConstants.h
index 2cdaf36..e96f5d8 100644
--- a/Source/core/rendering/style/RenderStyleConstants.h
+++ b/Source/core/rendering/style/RenderStyleConstants.h
@@ -28,6 +28,14 @@
 
 namespace WebCore {
 
+enum StyleRecalcChange {
+    NoChange,
+    NoInherit,
+    Inherit,
+    Force,
+    Reattach,
+};
+
 static const size_t PrintColorAdjustBits = 1;
 enum PrintColorAdjust {
     PrintColorAdjustEconomy,
@@ -162,6 +170,9 @@
 // CSS3 Background Position
 enum BackgroundEdgeOrigin { TopEdge, RightEdge, BottomEdge, LeftEdge };
 
+// CSS Mask Source Types
+enum EMaskSourceType { MaskAlpha, MaskLuminance };
+
 // CSS3 Marquee Properties
 
 enum EMarqueeBehavior { MNONE, MSCROLL, MSLIDE, MALTERNATE };
diff --git a/Source/core/rendering/style/ShadowData.h b/Source/core/rendering/style/ShadowData.h
index 30a981f..86377c2 100644
--- a/Source/core/rendering/style/ShadowData.h
+++ b/Source/core/rendering/style/ShadowData.h
@@ -25,7 +25,7 @@
 #ifndef ShadowData_h
 #define ShadowData_h
 
-#include "core/css/StyleColor.h"
+#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "wtf/OwnPtr.h"
@@ -40,7 +40,7 @@
     WTF_MAKE_FAST_ALLOCATED;
 public:
     static PassOwnPtr<ShadowData> create() { return adoptPtr(new ShadowData); }
-    static PassOwnPtr<ShadowData> create(const IntPoint& location, int blur, int spread, ShadowStyle style, const StyleColor& color)
+    static PassOwnPtr<ShadowData> create(const IntPoint& location, int blur, int spread, ShadowStyle style, const Color& color)
     {
         return adoptPtr(new ShadowData(location, blur, spread, style, color));
     }
@@ -59,7 +59,7 @@
     int blur() const { return m_blur; }
     int spread() const { return m_spread; }
     ShadowStyle style() const { return m_style; }
-    const StyleColor& color() const { return m_color; }
+    const Color& color() const { return m_color; }
 
     const ShadowData* next() const { return m_next.get(); }
     void setNext(PassOwnPtr<ShadowData> shadow) { m_next = shadow; }
@@ -75,7 +75,7 @@
     {
     }
 
-    ShadowData(const IntPoint& location, int blur, int spread, ShadowStyle style, const StyleColor& color)
+    ShadowData(const IntPoint& location, int blur, int spread, ShadowStyle style, const Color& color)
         : m_location(location)
         , m_blur(blur)
         , m_spread(spread)
@@ -89,7 +89,7 @@
     IntPoint m_location;
     int m_blur;
     int m_spread;
-    StyleColor m_color;
+    Color m_color;
     ShadowStyle m_style;
     OwnPtr<ShadowData> m_next;
 };
diff --git a/Source/core/rendering/style/StyleBackgroundData.h b/Source/core/rendering/style/StyleBackgroundData.h
index cbc668d..78f2042 100644
--- a/Source/core/rendering/style/StyleBackgroundData.h
+++ b/Source/core/rendering/style/StyleBackgroundData.h
@@ -25,7 +25,7 @@
 #ifndef StyleBackgroundData_h
 #define StyleBackgroundData_h
 
-#include "core/css/StyleColor.h"
+#include "core/platform/graphics/Color.h"
 #include "core/rendering/style/FillLayer.h"
 #include "core/rendering/style/OutlineValue.h"
 #include "wtf/PassRefPtr.h"
@@ -46,7 +46,7 @@
     }
 
     const FillLayer& background() const { return m_background; }
-    const StyleColor& color() const { return m_color; }
+    const Color& color() const { return m_color; }
     const OutlineValue& outline() const { return m_outline; }
 
 private:
@@ -56,7 +56,7 @@
     StyleBackgroundData(const StyleBackgroundData&);
 
     FillLayer m_background;
-    StyleColor m_color;
+    Color m_color;
     OutlineValue m_outline;
 };
 
diff --git a/Source/core/rendering/style/StyleInheritedData.h b/Source/core/rendering/style/StyleInheritedData.h
index 80bd3ec..54dc7d7 100644
--- a/Source/core/rendering/style/StyleInheritedData.h
+++ b/Source/core/rendering/style/StyleInheritedData.h
@@ -25,8 +25,8 @@
 #ifndef StyleInheritedData_h
 #define StyleInheritedData_h
 
-#include "core/css/StyleColor.h"
 #include "core/platform/Length.h"
+#include "core/platform/graphics/Color.h"
 #include "core/platform/graphics/Font.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
@@ -54,8 +54,8 @@
     Length line_height;
 
     Font font;
-    StyleColor color;
-    StyleColor visitedLinkColor;
+    Color color;
+    Color visitedLinkColor;
 
 private:
     StyleInheritedData();
diff --git a/Source/core/rendering/style/StyleMultiColData.h b/Source/core/rendering/style/StyleMultiColData.h
index bc97184..dcd1478 100644
--- a/Source/core/rendering/style/StyleMultiColData.h
+++ b/Source/core/rendering/style/StyleMultiColData.h
@@ -25,7 +25,6 @@
 #ifndef StyleMultiColData_h
 #define StyleMultiColData_h
 
-#include "core/css/StyleColor.h"
 #include "core/platform/Length.h"
 #include "core/rendering/style/BorderValue.h"
 #include "core/rendering/style/RenderStyleConstants.h"
@@ -58,7 +57,7 @@
     unsigned short m_count;
     float m_gap;
     BorderValue m_rule;
-    StyleColor m_visitedLinkColumnRuleColor;
+    Color m_visitedLinkColumnRuleColor;
 
     bool m_autoWidth : 1;
     bool m_autoCount : 1;
diff --git a/Source/core/rendering/style/StyleRareInheritedData.cpp b/Source/core/rendering/style/StyleRareInheritedData.cpp
index 8db21a0..3ca9ff2 100644
--- a/Source/core/rendering/style/StyleRareInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareInheritedData.cpp
@@ -33,9 +33,9 @@
 
 struct SameSizeAsStyleRareInheritedData : public RefCounted<SameSizeAsStyleRareInheritedData> {
     void* styleImage;
-    StyleColor firstColor;
+    Color firstColor;
     float firstFloat;
-    StyleColor colors[5];
+    Color colors[5];
     void* ownPtrs[1];
     AtomicString atomicStrings[5];
     void* refPtrs[2];
@@ -46,7 +46,7 @@
     unsigned unsigneds[1];
     short hyphenationShorts[3];
 
-    StyleColor touchColors;
+    Color touchColors;
 
     void* variableDataRefs[1];
 };
diff --git a/Source/core/rendering/style/StyleRareInheritedData.h b/Source/core/rendering/style/StyleRareInheritedData.h
index ddf3a86..2e0bbb5 100644
--- a/Source/core/rendering/style/StyleRareInheritedData.h
+++ b/Source/core/rendering/style/StyleRareInheritedData.h
@@ -25,8 +25,8 @@
 #ifndef StyleRareInheritedData_h
 #define StyleRareInheritedData_h
 
-#include "core/css/StyleColor.h"
 #include "core/platform/Length.h"
+#include "core/platform/graphics/Color.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/AtomicString.h"
@@ -59,14 +59,14 @@
 
     RefPtr<StyleImage> listStyleImage;
 
-    StyleColor textStrokeColor;
+    Color textStrokeColor;
     float textStrokeWidth;
-    StyleColor textFillColor;
-    StyleColor textEmphasisColor;
+    Color textFillColor;
+    Color textEmphasisColor;
 
-    StyleColor visitedLinkTextStrokeColor;
-    StyleColor visitedLinkTextFillColor;
-    StyleColor visitedLinkTextEmphasisColor;
+    Color visitedLinkTextStrokeColor;
+    Color visitedLinkTextFillColor;
+    Color visitedLinkTextEmphasisColor;
 
     OwnPtr<ShadowData> textShadow; // Our text shadow information for shadowed text drawing.
     AtomicString highlight; // Apple-specific extension for custom highlight rendering.
@@ -119,7 +119,7 @@
     AtomicString m_lineGrid;
     unsigned m_tabSize;
 
-    StyleColor tapHighlightColor;
+    Color tapHighlightColor;
 
     DataRef<StyleVariableData> m_variables;
 
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.cpp b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
index 3539ba1..bb79aab 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.cpp
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.cpp
@@ -288,4 +288,9 @@
     return true;
 }
 
+bool StyleRareNonInheritedData::hasFilters() const
+{
+    return m_filter.get() && !m_filter->m_operations.isEmpty();
+}
+
 } // namespace WebCore
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.h b/Source/core/rendering/style/StyleRareNonInheritedData.h
index 340357a..07c7bd3 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.h
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.h
@@ -25,7 +25,6 @@
 #ifndef StyleRareNonInheritedData_h
 #define StyleRareNonInheritedData_h
 
-#include "core/css/StyleColor.h"
 #include "core/rendering/ClipPathOperation.h"
 #include "core/rendering/style/BasicShapes.h"
 #include "core/rendering/style/CounterDirectives.h"
@@ -85,6 +84,8 @@
     bool reflectionDataEquivalent(const StyleRareNonInheritedData&) const;
     bool animationDataEquivalent(const StyleRareNonInheritedData&) const;
     bool transitionDataEquivalent(const StyleRareNonInheritedData&) const;
+    bool hasFilters() const;
+    bool hasOpacity() const { return opacity < 1; }
 
     float opacity; // Whether or not we're transparent.
 
@@ -131,14 +132,14 @@
 
     RefPtr<ClipPathOperation> m_clipPath;
 
-    StyleColor m_textDecorationColor;
-    StyleColor m_visitedLinkTextDecorationColor;
-    StyleColor m_visitedLinkBackgroundColor;
-    StyleColor m_visitedLinkOutlineColor;
-    StyleColor m_visitedLinkBorderLeftColor;
-    StyleColor m_visitedLinkBorderRightColor;
-    StyleColor m_visitedLinkBorderTopColor;
-    StyleColor m_visitedLinkBorderBottomColor;
+    Color m_textDecorationColor;
+    Color m_visitedLinkTextDecorationColor;
+    Color m_visitedLinkBackgroundColor;
+    Color m_visitedLinkOutlineColor;
+    Color m_visitedLinkBorderLeftColor;
+    Color m_visitedLinkBorderRightColor;
+    Color m_visitedLinkBorderTopColor;
+    Color m_visitedLinkBorderBottomColor;
 
     int m_order;
 
diff --git a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
index b2a9feb..e9c656c 100644
--- a/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
+++ b/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
@@ -89,8 +89,7 @@
     if (!renderer)
         return 0;
 
-    Document* document = renderer->document();
-    ASSERT(document);
+    Document* document = &renderer->document();
 
     DocumentResourceReference* documentResourceReference = filterOperation->documentResourceReference();
     DocumentResource* cachedSVGDocument = documentResourceReference ? documentResourceReference->document() : 0;
diff --git a/Source/core/rendering/svg/RenderSVGBlock.cpp b/Source/core/rendering/svg/RenderSVGBlock.cpp
index 1db2a55..c3bed7e 100644
--- a/Source/core/rendering/svg/RenderSVGBlock.cpp
+++ b/Source/core/rendering/svg/RenderSVGBlock.cpp
@@ -29,7 +29,7 @@
 namespace WebCore {
 
 RenderSVGBlock::RenderSVGBlock(SVGElement* element)
-    : RenderBlock(element)
+    : RenderBlockFlow(element)
 {
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGBlock.h b/Source/core/rendering/svg/RenderSVGBlock.h
index 4468a20..7963e73 100644
--- a/Source/core/rendering/svg/RenderSVGBlock.h
+++ b/Source/core/rendering/svg/RenderSVGBlock.h
@@ -20,13 +20,13 @@
 #ifndef RenderSVGBlock_h
 #define RenderSVGBlock_h
 
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
 
 namespace WebCore {
 
 class SVGElement;
 
-class RenderSVGBlock : public RenderBlock {
+class RenderSVGBlock : public RenderBlockFlow {
 public:
     explicit RenderSVGBlock(SVGElement*);
 
@@ -41,6 +41,8 @@
 
     virtual bool isRenderSVGBlock() const OVERRIDE FINAL { return true; };
 
+    virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
     virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE FINAL;
 
     virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE FINAL;
diff --git a/Source/core/rendering/svg/RenderSVGEllipse.cpp b/Source/core/rendering/svg/RenderSVGEllipse.cpp
index 7542fa6..ac5c649 100644
--- a/Source/core/rendering/svg/RenderSVGEllipse.cpp
+++ b/Source/core/rendering/svg/RenderSVGEllipse.cpp
@@ -75,9 +75,9 @@
 
 void RenderSVGEllipse::calculateRadiiAndCenter()
 {
-    ASSERT(node());
-    if (node()->hasTagName(SVGNames::circleTag)) {
-        SVGCircleElement* circle = toSVGCircleElement(node());
+    ASSERT(element());
+    if (element()->hasTagName(SVGNames::circleTag)) {
+        SVGCircleElement* circle = toSVGCircleElement(element());
 
         SVGLengthContext lengthContext(circle);
         float radius = circle->rCurrentValue().value(lengthContext);
@@ -86,7 +86,7 @@
         return;
     }
 
-    SVGEllipseElement* ellipse = toSVGEllipseElement(node());
+    SVGEllipseElement* ellipse = toSVGEllipseElement(element());
 
     SVGLengthContext lengthContext(ellipse);
     m_radii = FloatSize(ellipse->rxCurrentValue().value(lengthContext), ellipse->ryCurrentValue().value(lengthContext));
diff --git a/Source/core/rendering/svg/RenderSVGImage.cpp b/Source/core/rendering/svg/RenderSVGImage.cpp
index b9754ce..7cf2388 100644
--- a/Source/core/rendering/svg/RenderSVGImage.cpp
+++ b/Source/core/rendering/svg/RenderSVGImage.cpp
@@ -57,7 +57,7 @@
 
 bool RenderSVGImage::updateImageViewport()
 {
-    SVGImageElement* image = toSVGImageElement(node());
+    SVGImageElement* image = toSVGImageElement(element());
     FloatRect oldBoundaries = m_objectBoundingBox;
     bool updatedViewport = false;
 
@@ -96,7 +96,7 @@
 
     bool transformOrBoundariesUpdate = m_needsTransformUpdate || m_needsBoundariesUpdate;
     if (m_needsTransformUpdate) {
-        m_localTransform = toSVGImageElement(node())->animatedLocalTransform();
+        m_localTransform = toSVGImageElement(element())->animatedLocalTransform();
         m_needsTransformUpdate = false;
     }
 
@@ -158,7 +158,7 @@
     FloatRect destRect = m_objectBoundingBox;
     FloatRect srcRect(0, 0, image->width(), image->height());
 
-    SVGImageElement* imageElement = toSVGImageElement(node());
+    SVGImageElement* imageElement = toSVGImageElement(element());
     imageElement->preserveAspectRatioCurrentValue().transformRect(destRect, srcRect);
 
     bool useLowQualityScaling = false;
diff --git a/Source/core/rendering/svg/RenderSVGInlineText.cpp b/Source/core/rendering/svg/RenderSVGInlineText.cpp
index 1141a56..521d6a5 100644
--- a/Source/core/rendering/svg/RenderSVGInlineText.cpp
+++ b/Source/core/rendering/svg/RenderSVGInlineText.cpp
@@ -219,10 +219,9 @@
     ASSERT(style);
     ASSERT(renderer);
 
-    Document* document = renderer->document();
-    ASSERT(document);
+    Document& document = renderer->document();
 
-    StyleResolver* styleResolver = document->styleResolver();
+    StyleResolver* styleResolver = document.styleResolver();
     ASSERT(styleResolver);
 
     // Alter font-size to the right on-screen value to avoid scaling the glyphs themselves, except when GeometricPrecision is specified.
@@ -239,7 +238,7 @@
     FontDescription fontDescription(style->fontDescription());
 
     // FIXME: We need to better handle the case when we compute very small fonts below (below 1pt).
-    fontDescription.setComputedSize(FontSize::getComputedSizeFromSpecifiedSize(document, scalingFactor, fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), DoNotUseSmartMinimumForFontSize));
+    fontDescription.setComputedSize(FontSize::getComputedSizeFromSpecifiedSize(&document, scalingFactor, fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), DoNotUseSmartMinimumForFontSize));
 
     scaledFont = Font(fontDescription, 0, 0);
     scaledFont.update(styleResolver->fontSelector());
diff --git a/Source/core/rendering/svg/RenderSVGModelObject.cpp b/Source/core/rendering/svg/RenderSVGModelObject.cpp
index 10f3d8f..124f5a0 100644
--- a/Source/core/rendering/svg/RenderSVGModelObject.cpp
+++ b/Source/core/rendering/svg/RenderSVGModelObject.cpp
@@ -130,7 +130,7 @@
 static void getElementCTM(SVGElement* element, AffineTransform& transform)
 {
     ASSERT(element);
-    element->document()->updateLayoutIgnorePendingStylesheets();
+    element->document().updateLayoutIgnorePendingStylesheets();
 
     SVGElement* stopAtElement = SVGLocatable::nearestViewportElement(element);
     ASSERT(stopAtElement);
diff --git a/Source/core/rendering/svg/RenderSVGModelObject.h b/Source/core/rendering/svg/RenderSVGModelObject.h
index 0a36ff8..e06d688 100644
--- a/Source/core/rendering/svg/RenderSVGModelObject.h
+++ b/Source/core/rendering/svg/RenderSVGModelObject.h
@@ -33,6 +33,7 @@
 
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/svg/SVGRenderSupport.h"
+#include "core/svg/SVGElement.h"
 #include "core/svg/SVGRect.h"
 
 namespace WebCore {
@@ -65,11 +66,16 @@
 
     virtual void computeLayerHitTestRects(LayerHitTestRects&) const OVERRIDE;
 
+    SVGElement* element() const { return toSVGElement(RenderObject::node()); }
+
 protected:
     virtual void addLayerHitTestRects(LayerHitTestRects&, const RenderLayer* currentCompositedLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const OVERRIDE;
     virtual void willBeDestroyed();
 
 private:
+    // RenderSVGModelObject subclasses should use element() instead.
+    void node() const WTF_DELETED_FUNCTION;
+
     // This method should never be called, SVG uses a different nodeAtPoint method
     bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
     virtual void absoluteFocusRingQuads(Vector<FloatQuad>&) OVERRIDE FINAL;
diff --git a/Source/core/rendering/svg/RenderSVGRect.cpp b/Source/core/rendering/svg/RenderSVGRect.cpp
index 9d1457e..dfe4471 100644
--- a/Source/core/rendering/svg/RenderSVGRect.cpp
+++ b/Source/core/rendering/svg/RenderSVGRect.cpp
@@ -50,7 +50,7 @@
     m_fillBoundingBox = FloatRect();
     m_innerStrokeRect = FloatRect();
     m_outerStrokeRect = FloatRect();
-    SVGRectElement* rect = toSVGRectElement(node());
+    SVGRectElement* rect = toSVGRectElement(element());
     ASSERT(rect);
 
     SVGLengthContext lengthContext(rect);
diff --git a/Source/core/rendering/svg/RenderSVGResource.cpp b/Source/core/rendering/svg/RenderSVGResource.cpp
index 6a2d951..ea7931a 100644
--- a/Source/core/rendering/svg/RenderSVGResource.cpp
+++ b/Source/core/rendering/svg/RenderSVGResource.cpp
@@ -24,6 +24,7 @@
 
 #include "core/rendering/svg/RenderSVGResource.h"
 
+#include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/rendering/svg/RenderSVGResourceClipper.h"
 #include "core/rendering/svg/RenderSVGResourceFilter.h"
@@ -34,7 +35,7 @@
 
 namespace WebCore {
 
-static inline bool inheritColorFromParentStyleIfNeeded(RenderObject* object, bool applyToFill, StyleColor& color)
+static inline bool inheritColorFromParentStyleIfNeeded(RenderObject* object, bool applyToFill, Color& color)
 {
     if (color.isValid())
         return true;
@@ -45,7 +46,7 @@
     return true;
 }
 
-static inline RenderSVGResource* requestPaintingResource(RenderSVGResourceMode mode, RenderObject* object, const RenderStyle* style, StyleColor& fallbackColor)
+static inline RenderSVGResource* requestPaintingResource(RenderSVGResourceMode mode, RenderObject* object, const RenderStyle* style, Color& fallbackColor)
 {
     ASSERT(object);
     ASSERT(style);
@@ -80,7 +81,7 @@
     if (paintType == SVGPaint::SVG_PAINTTYPE_NONE)
         return 0;
 
-    StyleColor color;
+    Color color;
     switch (paintType) {
     case SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR:
     case SVGPaint::SVG_PAINTTYPE_RGBCOLOR:
@@ -100,7 +101,8 @@
         // For SVG_PAINTTYPE_CURRENTCOLOR, 'color' already contains the 'visitedColor'.
         if (visitedPaintType < SVGPaint::SVG_PAINTTYPE_URI_NONE && visitedPaintType != SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR) {
             const Color& visitedColor = applyToFill ? svgStyle->visitedLinkFillPaintColor() : svgStyle->visitedLinkStrokePaintColor();
-            color = Color(visitedColor.red(), visitedColor.green(), visitedColor.blue(), color.alpha());
+            if (visitedColor.isValid())
+                color = Color(visitedColor.red(), visitedColor.green(), visitedColor.blue(), color.alpha());
         }
     }
 
@@ -110,7 +112,7 @@
         if (!inheritColorFromParentStyleIfNeeded(object, applyToFill, color))
             return 0;
 
-        colorResource->setColor(color.color());
+        colorResource->setColor(color);
         return colorResource;
     }
 
@@ -120,7 +122,7 @@
         if (paintType == SVGPaint::SVG_PAINTTYPE_URI_NONE || !inheritColorFromParentStyleIfNeeded(object, applyToFill, color))
             return 0;
 
-        colorResource->setColor(color.color());
+        colorResource->setColor(color);
         return colorResource;
     }
 
@@ -130,7 +132,7 @@
         if (!inheritColorFromParentStyleIfNeeded(object, applyToFill, color))
             return 0;
 
-        colorResource->setColor(color.color());
+        colorResource->setColor(color);
         return colorResource;
     }
 
@@ -140,12 +142,12 @@
     return uriResource;
 }
 
-RenderSVGResource* RenderSVGResource::fillPaintingResource(RenderObject* object, const RenderStyle* style, StyleColor& fallbackColor)
+RenderSVGResource* RenderSVGResource::fillPaintingResource(RenderObject* object, const RenderStyle* style, Color& fallbackColor)
 {
     return requestPaintingResource(ApplyToFillMode, object, style, fallbackColor);
 }
 
-RenderSVGResource* RenderSVGResource::strokePaintingResource(RenderObject* object, const RenderStyle* style, StyleColor& fallbackColor)
+RenderSVGResource* RenderSVGResource::strokePaintingResource(RenderObject* object, const RenderStyle* style, Color& fallbackColor)
 {
     return requestPaintingResource(ApplyToStrokeMode, object, style, fallbackColor);
 }
@@ -174,7 +176,7 @@
 
     if (!object->node() || !object->node()->isSVGElement())
         return;
-    HashSet<SVGElement*>* dependencies = object->document()->accessSVGExtensions()->setOfElementsReferencingTarget(toSVGElement(object->node()));
+    HashSet<SVGElement*>* dependencies = object->document().accessSVGExtensions()->setOfElementsReferencingTarget(toSVGElement(object->node()));
     if (!dependencies)
         return;
     HashSet<SVGElement*>::iterator end = dependencies->end();
@@ -187,10 +189,9 @@
 void RenderSVGResource::markForLayoutAndParentResourceInvalidation(RenderObject* object, bool needsLayout)
 {
     ASSERT(object);
-    ASSERT(object->document());
     ASSERT(object->node());
 
-    if (needsLayout)
+    if (needsLayout && !object->documentBeingDestroyed())
         object->setNeedsLayout();
 
     removeFromCacheAndInvalidateDependencies(object, needsLayout);
diff --git a/Source/core/rendering/svg/RenderSVGResource.h b/Source/core/rendering/svg/RenderSVGResource.h
index e9bccc7..5feaa1a 100644
--- a/Source/core/rendering/svg/RenderSVGResource.h
+++ b/Source/core/rendering/svg/RenderSVGResource.h
@@ -76,8 +76,8 @@
     }
 
     // Helper utilities used in the render tree to access resources used for painting shapes/text (gradients & patterns & solid colors only)
-    static RenderSVGResource* fillPaintingResource(RenderObject*, const RenderStyle*, StyleColor& fallbackColor);
-    static RenderSVGResource* strokePaintingResource(RenderObject*, const RenderStyle*, StyleColor& fallbackColor);
+    static RenderSVGResource* fillPaintingResource(RenderObject*, const RenderStyle*, Color& fallbackColor);
+    static RenderSVGResource* strokePaintingResource(RenderObject*, const RenderStyle*, Color& fallbackColor);
     static RenderSVGResourceSolidColor* sharedSolidPaintingResource();
 
     static void markForLayoutAndParentResourceInvalidation(RenderObject*, bool needsLayout = true);
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
index 7a05282..588a6a6 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
@@ -26,6 +26,7 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
+#include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/HitTestResult.h"
@@ -80,7 +81,7 @@
     WindRule clipRule = RULE_NONZERO;
     Path clipPath = Path();
 
-    for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
+    for (Node* childNode = element()->firstChild(); childNode; childNode = childNode->nextSibling()) {
         RenderObject* renderer = childNode->renderer();
         if (!renderer)
             continue;
@@ -118,7 +119,7 @@
         }
     }
     // Only one visible shape/path was found. Directly continue clipping and transform the content to userspace if necessary.
-    if (toSVGClipPathElement(node())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
+    if (toSVGClipPathElement(element())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
         AffineTransform transform;
         transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
         transform.scaleNonUniform(objectBoundingBox.width(), objectBoundingBox.height());
@@ -152,7 +153,7 @@
         clipperData = adoptPtr(new ClipperData);
 
     // First, try to apply the clip as a clipPath.
-    AffineTransform animatedLocalTransform = toSVGClipPathElement(node())->animatedLocalTransform();
+    AffineTransform animatedLocalTransform = toSVGClipPathElement(element())->animatedLocalTransform();
     if (tryPathOnlyClipping(context, animatedLocalTransform, targetBoundingBox)) {
         clipperData->clipMode = ClipperData::PathOnlyClipMode;
         return true;
@@ -218,7 +219,7 @@
 
     // Adjust the mask image context according to the target objectBoundingBox.
     AffineTransform maskContentTransformation;
-    if (toSVGClipPathElement(node())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
+    if (toSVGClipPathElement(element())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
         maskContentTransformation.translate(targetBoundingBox.x(), targetBoundingBox.y());
         maskContentTransformation.scaleNonUniform(targetBoundingBox.width(), targetBoundingBox.height());
         context->concatCTM(maskContentTransformation);
@@ -232,7 +233,7 @@
     PaintBehavior oldBehavior = frame()->view()->paintBehavior();
     frame()->view()->setPaintBehavior(oldBehavior | PaintBehaviorRenderingSVGMask);
 
-    for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
+    for (Node* childNode = element()->firstChild(); childNode; childNode = childNode->nextSibling()) {
         RenderObject* renderer = childNode->renderer();
         if (!childNode->isSVGElement() || !renderer)
             continue;
@@ -270,7 +271,7 @@
 void RenderSVGResourceClipper::calculateClipContentRepaintRect()
 {
     // This is a rough heuristic to appraise the clip size and doesn't consider clip on clip.
-    for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
+    for (Node* childNode = element()->firstChild(); childNode; childNode = childNode->nextSibling()) {
         RenderObject* renderer = childNode->renderer();
         if (!childNode->isSVGElement() || !renderer)
             continue;
@@ -281,7 +282,7 @@
              continue;
         m_clipBoundaries.unite(renderer->localToParentTransform().mapRect(renderer->repaintRectInLocalCoordinates()));
     }
-    m_clipBoundaries = toSVGClipPathElement(node())->animatedLocalTransform().mapRect(m_clipBoundaries);
+    m_clipBoundaries = toSVGClipPathElement(element())->animatedLocalTransform().mapRect(m_clipBoundaries);
 }
 
 bool RenderSVGResourceClipper::hitTestClipContent(const FloatRect& objectBoundingBox, const FloatPoint& nodeAtPoint)
@@ -290,7 +291,7 @@
     if (!SVGRenderSupport::pointInClippingArea(this, point))
         return false;
 
-    SVGClipPathElement* clipPathElement = toSVGClipPathElement(node());
+    SVGClipPathElement* clipPathElement = toSVGClipPathElement(element());
     if (clipPathElement->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
         AffineTransform transform;
         transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
@@ -300,7 +301,7 @@
 
     point = clipPathElement->animatedLocalTransform().inverse().mapPoint(point);
 
-    for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
+    for (Node* childNode = element()->firstChild(); childNode; childNode = childNode->nextSibling()) {
         RenderObject* renderer = childNode->renderer();
         if (!childNode->isSVGElement() || !renderer)
             continue;
@@ -324,7 +325,7 @@
     if (m_clipBoundaries.isEmpty())
         calculateClipContentRepaintRect();
 
-    if (toSVGClipPathElement(node())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
+    if (toSVGClipPathElement(element())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
         FloatRect objectBoundingBox = object->objectBoundingBox();
         AffineTransform transform;
         transform.translate(objectBoundingBox.x(), objectBoundingBox.y());
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.h b/Source/core/rendering/svg/RenderSVGResourceClipper.h
index 7344e7e..02ce712 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.h
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.h
@@ -58,7 +58,7 @@
 
     bool hitTestClipContent(const FloatRect&, const FloatPoint&);
 
-    SVGUnitTypes::SVGUnitType clipPathUnits() const { return toSVGClipPathElement(node())->clipPathUnitsCurrentValue(); }
+    SVGUnitTypes::SVGUnitType clipPathUnits() const { return toSVGClipPathElement(element())->clipPathUnitsCurrentValue(); }
 
     static RenderSVGResourceType s_resourceType;
 private:
@@ -73,6 +73,12 @@
     bool m_inClipExpansion;
 };
 
+inline RenderSVGResourceClipper* toRenderSVGResourceClipper(RenderSVGResource* resource)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == ClipperResourceType);
+    return static_cast<RenderSVGResourceClipper*>(resource);
+}
+
 }
 
 #endif
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
index eb17d7a..575266e 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
@@ -30,11 +30,10 @@
 
 namespace WebCore {
 
-static inline SVGDocumentExtensions* svgExtensionsFromNode(Node* node)
+static inline SVGDocumentExtensions* svgExtensionsFromElement(SVGElement* element)
 {
-    ASSERT(node);
-    ASSERT(node->document());
-    return node->document()->accessSVGExtensions();
+    ASSERT(element);
+    return element->document().accessSVGExtensions();
 }
 
 RenderSVGResourceContainer::RenderSVGResourceContainer(SVGElement* node)
@@ -48,7 +47,7 @@
 RenderSVGResourceContainer::~RenderSVGResourceContainer()
 {
     if (m_registered)
-        svgExtensionsFromNode(node())->removeResource(m_id);
+        svgExtensionsFromElement(element())->removeResource(m_id);
 }
 
 void RenderSVGResourceContainer::layout()
@@ -82,9 +81,9 @@
     removeAllClientsFromCache();
 
     // Remove old id, that is guaranteed to be present in cache.
-    SVGDocumentExtensions* extensions = svgExtensionsFromNode(node());
+    SVGDocumentExtensions* extensions = svgExtensionsFromElement(element());
     extensions->removeResource(m_id);
-    m_id = toElement(node())->getIdAttribute();
+    m_id = element()->getIdAttribute();
 
     registerResource();
 }
@@ -156,6 +155,14 @@
     m_clients.remove(client);
 }
 
+void RenderSVGResourceContainer::addClientRenderLayer(Node* node)
+{
+    ASSERT(node);
+    if (!node->renderer() || !node->renderer()->hasLayer())
+        return;
+    m_clientLayers.add(toRenderLayerModelObject(node->renderer())->layer());
+}
+
 void RenderSVGResourceContainer::addClientRenderLayer(RenderLayer* client)
 {
     ASSERT(client);
@@ -170,7 +177,7 @@
 
 void RenderSVGResourceContainer::registerResource()
 {
-    SVGDocumentExtensions* extensions = svgExtensionsFromNode(node());
+    SVGDocumentExtensions* extensions = svgExtensionsFromElement(element());
     if (!extensions->hasPendingResource(m_id)) {
         extensions->addResource(m_id, this);
         return;
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.h b/Source/core/rendering/svg/RenderSVGResourceContainer.h
index a2e4bd1..5b8cdc2 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.h
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.h
@@ -43,6 +43,7 @@
     static AffineTransform transformOnNonScalingStroke(RenderObject*, const AffineTransform& resourceTransform);
 
     void idChanged();
+    void addClientRenderLayer(Node*);
     void addClientRenderLayer(RenderLayer*);
     void removeClientRenderLayer(RenderLayer*);
 
@@ -75,19 +76,19 @@
     HashSet<RenderLayer*> m_clientLayers;
 };
 
-inline RenderSVGResourceContainer* getRenderSVGResourceContainerById(Document* document, const AtomicString& id)
+inline RenderSVGResourceContainer* getRenderSVGResourceContainerById(Document& document, const AtomicString& id)
 {
     if (id.isEmpty())
         return 0;
 
-    if (RenderSVGResourceContainer* renderResource = document->accessSVGExtensions()->resourceById(id))
+    if (RenderSVGResourceContainer* renderResource = document.accessSVGExtensions()->resourceById(id))
         return renderResource;
 
     return 0;
 }
 
 template<typename Renderer>
-Renderer* getRenderSVGResourceById(Document* document, const AtomicString& id)
+Renderer* getRenderSVGResourceById(Document& document, const AtomicString& id)
 {
     if (RenderSVGResourceContainer* container = getRenderSVGResourceContainerById(document, id))
         return container->cast<Renderer>();
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
index aef216a..09494b3 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
@@ -79,7 +79,7 @@
 
 PassRefPtr<SVGFilterBuilder> RenderSVGResourceFilter::buildPrimitives(SVGFilter* filter)
 {
-    SVGFilterElement* filterElement = toSVGFilterElement(node());
+    SVGFilterElement* filterElement = toSVGFilterElement(element());
     FloatRect targetBoundingBox = filter->targetBoundingBox();
 
     // Add effects to the builder
@@ -123,6 +123,28 @@
     return matchesFilterSize;
 }
 
+static bool createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform,
+    OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
+{
+    IntRect paintRect = SVGRenderingContext::calculateImageBufferRect(targetRect, absoluteTransform);
+    // Don't create empty ImageBuffers.
+    if (paintRect.isEmpty())
+        return false;
+
+    OwnPtr<ImageBuffer> image = ImageBuffer::create(paintRect.size(), 1, renderingMode);
+    if (!image)
+        return false;
+
+    GraphicsContext* imageContext = image->context();
+    ASSERT(imageContext);
+
+    imageContext->translate(-paintRect.x(), -paintRect.y());
+    imageContext->concatCTM(absoluteTransform);
+
+    imageBuffer = image.release();
+    return true;
+}
+
 bool RenderSVGResourceFilter::applyResource(RenderObject* object, RenderStyle*, GraphicsContext*& context, unsigned short resourceMode)
 {
     ASSERT(object);
@@ -139,7 +161,7 @@
     OwnPtr<FilterData> filterData(adoptPtr(new FilterData));
     FloatRect targetBoundingBox = object->objectBoundingBox();
 
-    SVGFilterElement* filterElement = toSVGFilterElement(node());
+    SVGFilterElement* filterElement = toSVGFilterElement(element());
     filterData->boundaries = SVGLengthContext::resolveRectangle<SVGFilterElement>(filterElement, filterElement->filterUnitsCurrentValue(), targetBoundingBox);
     if (filterData->boundaries.isEmpty())
         return false;
@@ -215,8 +237,8 @@
     effectiveTransform.multiply(filterData->shearFreeAbsoluteTransform);
 
     OwnPtr<ImageBuffer> sourceGraphic;
-    RenderingMode renderingMode = object->document()->page()->settings().acceleratedFiltersEnabled() ? Accelerated : Unaccelerated;
-    if (!SVGRenderingContext::createImageBuffer(filterData->drawingRegion, effectiveTransform, sourceGraphic, renderingMode)) {
+    RenderingMode renderingMode = object->document().page()->settings().acceleratedFiltersEnabled() ? Accelerated : Unaccelerated;
+    if (!createImageBuffer(filterData->drawingRegion, effectiveTransform, sourceGraphic, renderingMode)) {
         ASSERT(!m_filter.contains(object));
         filterData->savedContext = context;
         m_filter.set(object, filterData.leakPtr());
@@ -311,7 +333,7 @@
 
 FloatRect RenderSVGResourceFilter::resourceBoundingBox(RenderObject* object)
 {
-    if (SVGFilterElement* element = toSVGFilterElement(node()))
+    if (SVGFilterElement* element = toSVGFilterElement(this->element()))
         return SVGLengthContext::resolveRectangle<SVGFilterElement>(element, element->filterUnitsCurrentValue(), object->objectBoundingBox());
 
     return FloatRect();
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilter.h b/Source/core/rendering/svg/RenderSVGResourceFilter.h
index 9022067..36b91ae 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilter.h
+++ b/Source/core/rendering/svg/RenderSVGResourceFilter.h
@@ -73,8 +73,8 @@
 
     PassRefPtr<SVGFilterBuilder> buildPrimitives(SVGFilter*);
 
-    SVGUnitTypes::SVGUnitType filterUnits() const { return toSVGFilterElement(node())->filterUnitsCurrentValue(); }
-    SVGUnitTypes::SVGUnitType primitiveUnits() const { return toSVGFilterElement(node())->primitiveUnitsCurrentValue(); }
+    SVGUnitTypes::SVGUnitType filterUnits() const { return toSVGFilterElement(element())->filterUnitsCurrentValue(); }
+    SVGUnitTypes::SVGUnitType primitiveUnits() const { return toSVGFilterElement(element())->primitiveUnitsCurrentValue(); }
 
     void primitiveAttributeChanged(RenderObject*, const QualifiedName&);
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp b/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp
index 0f14cc6..44e2d0b 100644
--- a/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp
@@ -44,12 +44,12 @@
         return;
 
     const SVGRenderStyle* newStyle = this->style()->svgStyle();
-    if (node()->hasTagName(SVGNames::feFloodTag)) {
+    if (element()->hasTagName(SVGNames::feFloodTag)) {
         if (newStyle->floodColor() != oldStyle->svgStyle()->floodColor())
             toRenderSVGFilter(filter)->primitiveAttributeChanged(this, SVGNames::flood_colorAttr);
         if (newStyle->floodOpacity() != oldStyle->svgStyle()->floodOpacity())
             toRenderSVGFilter(filter)->primitiveAttributeChanged(this, SVGNames::flood_opacityAttr);
-    } else if (node()->hasTagName(SVGNames::feDiffuseLightingTag) || node()->hasTagName(SVGNames::feSpecularLightingTag)) {
+    } else if (element()->hasTagName(SVGNames::feDiffuseLightingTag) || element()->hasTagName(SVGNames::feSpecularLightingTag)) {
         if (newStyle->lightingColor() != oldStyle->svgStyle()->lightingColor())
             toRenderSVGFilter(filter)->primitiveAttributeChanged(this, SVGNames::lighting_colorAttr);
     }
diff --git a/Source/core/rendering/svg/RenderSVGResourceGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
index 51e6782..7cd75f1 100644
--- a/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
@@ -62,7 +62,7 @@
     // Otherwhise the call to collectGradientAttributes() in createTileImage(), may cause the SVG DOM property
     // synchronization to kick in, which causes removeAllClientsFromCache() to be called, which in turn deletes our
     // GradientData object! Leaving out the line below will cause svg/dynamic-updates/SVG*GradientElement-svgdom* to crash.
-    SVGGradientElement* gradientElement = toSVGGradientElement(node());
+    SVGGradientElement* gradientElement = toSVGGradientElement(element());
     if (!gradientElement)
         return false;
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
index 4a0b52f..c8936a6 100644
--- a/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
@@ -46,12 +46,12 @@
 
 FloatPoint RenderSVGResourceLinearGradient::startPoint(const LinearGradientAttributes& attributes) const
 {
-    return SVGLengthContext::resolvePoint(static_cast<const SVGElement*>(node()), attributes.gradientUnits(), attributes.x1(), attributes.y1());
+    return SVGLengthContext::resolvePoint(element(), attributes.gradientUnits(), attributes.x1(), attributes.y1());
 }
 
 FloatPoint RenderSVGResourceLinearGradient::endPoint(const LinearGradientAttributes& attributes) const
 {
-    return SVGLengthContext::resolvePoint(static_cast<const SVGElement*>(node()), attributes.gradientUnits(), attributes.x2(), attributes.y2());
+    return SVGLengthContext::resolvePoint(element(), attributes.gradientUnits(), attributes.x2(), attributes.y2());
 }
 
 void RenderSVGResourceLinearGradient::buildGradient(GradientData* gradientData) const
diff --git a/Source/core/rendering/svg/RenderSVGResourceMarker.cpp b/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
index 399ce27..4b56522 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
@@ -92,7 +92,7 @@
 
 FloatPoint RenderSVGResourceMarker::referencePoint() const
 {
-    SVGMarkerElement* marker = toSVGMarkerElement(node());
+    SVGMarkerElement* marker = toSVGMarkerElement(element());
     ASSERT(marker);
 
     SVGLengthContext lengthContext(marker);
@@ -101,7 +101,7 @@
 
 float RenderSVGResourceMarker::angle() const
 {
-    SVGMarkerElement* marker = toSVGMarkerElement(node());
+    SVGMarkerElement* marker = toSVGMarkerElement(element());
     ASSERT(marker);
 
     float angle = -1;
@@ -113,7 +113,7 @@
 
 AffineTransform RenderSVGResourceMarker::markerTransformation(const FloatPoint& origin, float autoAngle, float strokeWidth) const
 {
-    SVGMarkerElement* marker = toSVGMarkerElement(node());
+    SVGMarkerElement* marker = toSVGMarkerElement(element());
     ASSERT(marker);
 
     float markerAngle = angle();
@@ -129,7 +129,7 @@
 void RenderSVGResourceMarker::draw(PaintInfo& paintInfo, const AffineTransform& transform)
 {
     // An empty viewBox disables rendering.
-    SVGMarkerElement* marker = toSVGMarkerElement(toSVGElement(node()));
+    SVGMarkerElement* marker = toSVGMarkerElement(element());
     ASSERT(marker);
     if (marker->hasAttribute(SVGNames::viewBoxAttr) && marker->viewBoxIsValid() && marker->viewBoxCurrentValue().isEmpty())
         return;
@@ -155,7 +155,7 @@
 
 AffineTransform RenderSVGResourceMarker::viewportTransform() const
 {
-    SVGMarkerElement* marker = toSVGMarkerElement(node());
+    SVGMarkerElement* marker = toSVGMarkerElement(element());
     ASSERT(marker);
 
     return marker->viewBoxToViewTransform(m_viewport.width(), m_viewport.height());
@@ -166,7 +166,7 @@
     if (!selfNeedsLayout())
         return;
 
-    SVGMarkerElement* marker = toSVGMarkerElement(node());
+    SVGMarkerElement* marker = toSVGMarkerElement(element());
     ASSERT(marker);
 
     SVGLengthContext lengthContext(marker);
diff --git a/Source/core/rendering/svg/RenderSVGResourceMarker.h b/Source/core/rendering/svg/RenderSVGResourceMarker.h
index 528f1f1..7a38f1e 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMarker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMarker.h
@@ -59,7 +59,7 @@
 
     FloatPoint referencePoint() const;
     float angle() const;
-    SVGMarkerUnitsType markerUnits() const { return toSVGMarkerElement(node())->markerUnitsCurrentValue(); }
+    SVGMarkerUnitsType markerUnits() const { return toSVGMarkerElement(element())->markerUnitsCurrentValue(); }
 
     virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
     static RenderSVGResourceType s_resourceType;
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
index 6a599a8..0aae387 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
@@ -70,7 +70,7 @@
     ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
 
     FloatRect repaintRect = object->repaintRectInLocalCoordinates();
-    if (repaintRect.isEmpty() || !node()->hasChildNodes())
+    if (repaintRect.isEmpty() || !element()->hasChildNodes())
         return false;
 
     const SVGRenderStyle* svgStyle = style()->svgStyle();
@@ -113,13 +113,13 @@
 
     // Adjust the mask image context according to the target objectBoundingBox.
     AffineTransform maskContentTransformation;
-    if (toSVGMaskElement(node())->maskContentUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
+    if (toSVGMaskElement(element())->maskContentUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
         maskContentTransformation.translate(targetBoundingBox.x(), targetBoundingBox.y());
         maskContentTransformation.scaleNonUniform(targetBoundingBox.width(), targetBoundingBox.height());
         context->concatCTM(maskContentTransformation);
     }
 
-    for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
+    for (Node* childNode = element()->firstChild(); childNode; childNode = childNode->nextSibling()) {
         RenderObject* renderer = childNode->renderer();
         if (!childNode->isSVGElement() || !renderer)
             continue;
@@ -133,7 +133,7 @@
 
 void RenderSVGResourceMasker::calculateMaskContentRepaintRect()
 {
-    for (Node* childNode = node()->firstChild(); childNode; childNode = childNode->nextSibling()) {
+    for (Node* childNode = element()->firstChild(); childNode; childNode = childNode->nextSibling()) {
         RenderObject* renderer = childNode->renderer();
         if (!childNode->isSVGElement() || !renderer)
             continue;
@@ -146,7 +146,7 @@
 
 FloatRect RenderSVGResourceMasker::resourceBoundingBox(RenderObject* object)
 {
-    SVGMaskElement* maskElement = toSVGMaskElement(node());
+    SVGMaskElement* maskElement = toSVGMaskElement(element());
     ASSERT(maskElement);
 
     FloatRect objectBoundingBox = object->objectBoundingBox();
diff --git a/Source/core/rendering/svg/RenderSVGResourceMasker.h b/Source/core/rendering/svg/RenderSVGResourceMasker.h
index 44b2f56..f834bee 100644
--- a/Source/core/rendering/svg/RenderSVGResourceMasker.h
+++ b/Source/core/rendering/svg/RenderSVGResourceMasker.h
@@ -46,8 +46,8 @@
     virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short, const Path*, const RenderSVGShape*) OVERRIDE;
     virtual FloatRect resourceBoundingBox(RenderObject*);
 
-    SVGUnitTypes::SVGUnitType maskUnits() const { return toSVGMaskElement(node())->maskUnitsCurrentValue(); }
-    SVGUnitTypes::SVGUnitType maskContentUnits() const { return toSVGMaskElement(node())->maskContentUnitsCurrentValue(); }
+    SVGUnitTypes::SVGUnitType maskUnits() const { return toSVGMaskElement(element())->maskUnitsCurrentValue(); }
+    SVGUnitTypes::SVGUnitType maskContentUnits() const { return toSVGMaskElement(element())->maskContentUnitsCurrentValue(); }
 
     virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
     static RenderSVGResourceType s_resourceType;
diff --git a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
index 83f4848..74c11c5 100644
--- a/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
@@ -58,7 +58,7 @@
     if (currentData && currentData->pattern)
         return currentData;
 
-    SVGPatternElement* patternElement = toSVGPatternElement(node());
+    SVGPatternElement* patternElement = toSVGPatternElement(element());
     if (!patternElement)
         return 0;
 
diff --git a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
index e10f289..f9b9359 100644
--- a/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
@@ -47,22 +47,22 @@
 
 FloatPoint RenderSVGResourceRadialGradient::centerPoint(const RadialGradientAttributes& attributes) const
 {
-    return SVGLengthContext::resolvePoint(static_cast<const SVGElement*>(node()), attributes.gradientUnits(), attributes.cx(), attributes.cy());
+    return SVGLengthContext::resolvePoint(element(), attributes.gradientUnits(), attributes.cx(), attributes.cy());
 }
 
 FloatPoint RenderSVGResourceRadialGradient::focalPoint(const RadialGradientAttributes& attributes) const
 {
-    return SVGLengthContext::resolvePoint(static_cast<const SVGElement*>(node()), attributes.gradientUnits(), attributes.fx(), attributes.fy());
+    return SVGLengthContext::resolvePoint(element(), attributes.gradientUnits(), attributes.fx(), attributes.fy());
 }
 
 float RenderSVGResourceRadialGradient::radius(const RadialGradientAttributes& attributes) const
 {
-    return SVGLengthContext::resolveLength(static_cast<const SVGElement*>(node()), attributes.gradientUnits(), attributes.r());
+    return SVGLengthContext::resolveLength(element(), attributes.gradientUnits(), attributes.r());
 }
 
 float RenderSVGResourceRadialGradient::focalRadius(const RadialGradientAttributes& attributes) const
 {
-    return SVGLengthContext::resolveLength(static_cast<const SVGElement*>(node()), attributes.gradientUnits(), attributes.fr());
+    return SVGLengthContext::resolveLength(element(), attributes.gradientUnits(), attributes.fr());
 }
 
 void RenderSVGResourceRadialGradient::buildGradient(GradientData* gradientData) const
diff --git a/Source/core/rendering/svg/RenderSVGRoot.cpp b/Source/core/rendering/svg/RenderSVGRoot.cpp
index 0b2d79e..a664493 100644
--- a/Source/core/rendering/svg/RenderSVGRoot.cpp
+++ b/Source/core/rendering/svg/RenderSVGRoot.cpp
@@ -119,7 +119,7 @@
     if (!node())
         return false;
 
-    Frame* frame = node()->document()->frame();
+    Frame* frame = node()->document().frame();
     if (!frame)
         return false;
 
@@ -152,7 +152,7 @@
 
     // SVG embedded through object/embed/iframe.
     if (isEmbeddedThroughFrameContainingSVGDocument())
-        return document()->frame()->ownerRenderer()->availableLogicalWidth();
+        return document().frame()->ownerRenderer()->availableLogicalWidth();
 
     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
     return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
@@ -187,7 +187,7 @@
 
     // SVG embedded through object/embed/iframe.
     if (isEmbeddedThroughFrameContainingSVGDocument())
-        return document()->frame()->ownerRenderer()->availableLogicalHeight(IncludeMarginBorderPadding);
+        return document().frame()->ownerRenderer()->availableLogicalHeight(IncludeMarginBorderPadding);
 
     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
     return RenderReplaced::computeReplacedLogicalHeight();
diff --git a/Source/core/rendering/svg/RenderSVGShape.cpp b/Source/core/rendering/svg/RenderSVGShape.cpp
index 6ef2308..12b90a3 100644
--- a/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -63,8 +63,7 @@
     m_path = adoptPtr(new Path);
     ASSERT(RenderSVGShape::isEmpty());
 
-    SVGGraphicsElement* element = toSVGGraphicsElement(node());
-    updatePathFromGraphicsElement(element, path());
+    updatePathFromGraphicsElement(toSVGGraphicsElement(element()), path());
     processMarkerPositions();
 
     m_fillBoundingBox = calculateObjectBoundingBox();
@@ -118,7 +117,7 @@
     if (!m_fillBoundingBox.contains(point))
         return false;
 
-    StyleColor fallbackColor;
+    Color fallbackColor;
     if (requiresFill && !RenderSVGResource::fillPaintingResource(this, style(), fallbackColor))
         return false;
 
@@ -130,7 +129,7 @@
     if (!strokeBoundingBox().contains(point))
         return false;
 
-    StyleColor fallbackColor;
+    Color fallbackColor;
     if (requiresStroke && !RenderSVGResource::strokePaintingResource(this, style(), fallbackColor))
         return false;
 
@@ -140,7 +139,6 @@
 void RenderSVGShape::layout()
 {
     LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this) && selfNeedsLayout());
-    SVGGraphicsElement* element = toSVGGraphicsElement(node());
 
     bool updateCachedBoundariesInParents = false;
 
@@ -153,7 +151,7 @@
     }
 
     if (m_needsTransformUpdate) {
-        m_localTransform = element->animatedLocalTransform();
+        m_localTransform =  toSVGGraphicsElement(element())->animatedLocalTransform();
         m_needsTransformUpdate = false;
         updateCachedBoundariesInParents = true;
     }
@@ -192,8 +190,7 @@
 
 AffineTransform RenderSVGShape::nonScalingStrokeTransform() const
 {
-    SVGGraphicsElement* element = toSVGGraphicsElement(node());
-    return element->getScreenCTM(SVGLocatable::DisallowStyleUpdate);
+    return toSVGGraphicsElement(element())->getScreenCTM(SVGLocatable::DisallowStyleUpdate);
 }
 
 bool RenderSVGShape::shouldGenerateMarkerPositions() const
@@ -201,8 +198,7 @@
     if (!style()->svgStyle()->hasMarkers())
         return false;
 
-    SVGGraphicsElement* element = toSVGGraphicsElement(node());
-    if (!element->supportsMarkers())
+    if (!toSVGGraphicsElement(element())->supportsMarkers())
         return false;
 
     SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
@@ -214,13 +210,13 @@
 
 void RenderSVGShape::fillShape(RenderStyle* style, GraphicsContext* context)
 {
-    StyleColor fallbackColor;
+    Color fallbackColor;
     if (RenderSVGResource* fillPaintingResource = RenderSVGResource::fillPaintingResource(this, style, fallbackColor)) {
         if (fillPaintingResource->applyResource(this, style, context, ApplyToFillMode))
             fillPaintingResource->postApplyResource(this, context, ApplyToFillMode, 0, this);
         else if (fallbackColor.isValid()) {
             RenderSVGResourceSolidColor* fallbackResource = RenderSVGResource::sharedSolidPaintingResource();
-            fallbackResource->setColor(fallbackColor.color());
+            fallbackResource->setColor(fallbackColor);
             if (fallbackResource->applyResource(this, style, context, ApplyToFillMode))
                 fallbackResource->postApplyResource(this, context, ApplyToFillMode, 0, this);
         }
@@ -229,13 +225,13 @@
 
 void RenderSVGShape::strokeShape(RenderStyle* style, GraphicsContext* context)
 {
-    StyleColor fallbackColor;
+    Color fallbackColor;
     if (RenderSVGResource* strokePaintingResource = RenderSVGResource::strokePaintingResource(this, style, fallbackColor)) {
         if (strokePaintingResource->applyResource(this, style, context, ApplyToStrokeMode))
             strokePaintingResource->postApplyResource(this, context, ApplyToStrokeMode, 0, this);
         else if (fallbackColor.isValid()) {
             RenderSVGResourceSolidColor* fallbackResource = RenderSVGResource::sharedSolidPaintingResource();
-            fallbackResource->setColor(fallbackColor.color());
+            fallbackResource->setColor(fallbackColor);
             if (fallbackResource->applyResource(this, style, context, ApplyToStrokeMode))
                 fallbackResource->postApplyResource(this, context, ApplyToStrokeMode, 0, this);
         }
@@ -414,8 +410,7 @@
 
 float RenderSVGShape::strokeWidth() const
 {
-    SVGElement* svgElement = toSVGElement(node());
-    SVGLengthContext lengthContext(svgElement);
+    SVGLengthContext lengthContext(element());
     return style()->svgStyle()->strokeWidth().value(lengthContext);
 }
 
diff --git a/Source/core/rendering/svg/RenderSVGText.cpp b/Source/core/rendering/svg/RenderSVGText.cpp
index 14bc52f..6552c0b 100644
--- a/Source/core/rendering/svg/RenderSVGText.cpp
+++ b/Source/core/rendering/svg/RenderSVGText.cpp
@@ -350,8 +350,7 @@
 
     bool updateCachedBoundariesInParents = false;
     if (m_needsTransformUpdate) {
-        SVGTextElement* text = static_cast<SVGTextElement*>(node());
-        m_localTransform = text->animatedLocalTransform();
+        m_localTransform = toSVGTextElement(node())->animatedLocalTransform();
         m_needsTransformUpdate = false;
         updateCachedBoundariesInParents = true;
     }
diff --git a/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp b/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp
index 4b7bb9f..52516c4 100644
--- a/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp
@@ -39,7 +39,7 @@
 
 bool RenderSVGTransformableContainer::calculateLocalTransform()
 {
-    SVGGraphicsElement* element = toSVGGraphicsElement(node());
+    SVGGraphicsElement* element = toSVGGraphicsElement(this->element());
 
     // If we're either the renderer for a <use> element, or for any <g> element inside the shadow
     // tree, that was created during the use/symbol/svg expansion in SVGUseElement. These containers
diff --git a/Source/core/rendering/svg/RenderSVGViewportContainer.cpp b/Source/core/rendering/svg/RenderSVGViewportContainer.cpp
index 3b79919..112cb56 100644
--- a/Source/core/rendering/svg/RenderSVGViewportContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGViewportContainer.cpp
@@ -42,10 +42,10 @@
 
 void RenderSVGViewportContainer::determineIfLayoutSizeChanged()
 {
-    if (!node()->hasTagName(SVGNames::svgTag))
+    if (!element()->hasTagName(SVGNames::svgTag))
         return;
 
-    m_isLayoutSizeChanged = toSVGSVGElement(node())->hasRelativeLengths() && selfNeedsLayout();
+    m_isLayoutSizeChanged = toSVGSVGElement(element())->hasRelativeLengths() && selfNeedsLayout();
 }
 
 void RenderSVGViewportContainer::applyViewportClip(PaintInfo& paintInfo)
@@ -56,7 +56,7 @@
 
 void RenderSVGViewportContainer::calcViewport()
 {
-    SVGElement* element = toSVGElement(node());
+    SVGElement* element = this->element();
     if (!element->hasTagName(SVGNames::svgTag))
         return;
     SVGSVGElement* svg = toSVGSVGElement(element);
@@ -130,8 +130,8 @@
 
 AffineTransform RenderSVGViewportContainer::viewportTransform() const
 {
-    if (node()->hasTagName(SVGNames::svgTag)) {
-        SVGSVGElement* svg = toSVGSVGElement(node());
+    if (element()->hasTagName(SVGNames::svgTag)) {
+        SVGSVGElement* svg = toSVGSVGElement(element());
         return svg->viewBoxToViewTransform(m_viewport.width(), m_viewport.height());
     }
 
@@ -150,8 +150,8 @@
 void RenderSVGViewportContainer::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     // An empty viewBox disables rendering.
-    if (node()->hasTagName(SVGNames::svgTag)) {
-        if (toSVGSVGElement(node())->hasEmptyViewBox())
+    if (element()->hasTagName(SVGNames::svgTag)) {
+        if (toSVGSVGElement(element())->hasEmptyViewBox())
             return;
     }
 
diff --git a/Source/core/rendering/svg/SVGInlineFlowBox.cpp b/Source/core/rendering/svg/SVGInlineFlowBox.cpp
index 66b93be..c4f5cdb 100644
--- a/Source/core/rendering/svg/SVGInlineFlowBox.cpp
+++ b/Source/core/rendering/svg/SVGInlineFlowBox.cpp
@@ -89,8 +89,8 @@
     ASSERT(style);
 
     AffineTransform fragmentTransform;
-    Document* document = textRenderer->document();
-    Vector<DocumentMarker*> markers = document->markers()->markersFor(textRenderer->node());
+    Document& document = textRenderer->document();
+    Vector<DocumentMarker*> markers = document.markers()->markersFor(textRenderer->node());
 
     Vector<DocumentMarker*>::iterator markerEnd = markers.end();
     for (Vector<DocumentMarker*>::iterator markerIt = markers.begin(); markerIt != markerEnd; ++markerIt) {
diff --git a/Source/core/rendering/svg/SVGInlineTextBox.cpp b/Source/core/rendering/svg/SVGInlineTextBox.cpp
index 0a08afb..d15a979 100644
--- a/Source/core/rendering/svg/SVGInlineTextBox.cpp
+++ b/Source/core/rendering/svg/SVGInlineTextBox.cpp
@@ -197,7 +197,7 @@
 
     RenderObject* parentRenderer = parent()->renderer();
     ASSERT(parentRenderer);
-    ASSERT(!parentRenderer->document()->printing());
+    ASSERT(!parentRenderer->document().printing());
 
     // Determine whether or not we're selected.
     bool paintSelectedTextOnly = paintInfo.phase == PaintPhaseSelection;
@@ -206,7 +206,7 @@
         return;
 
     Color backgroundColor = renderer()->selectionBackgroundColor();
-    if (!backgroundColor.alpha())
+    if (!backgroundColor.isValid() || !backgroundColor.alpha())
         return;
 
     RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer());
@@ -270,7 +270,7 @@
     ASSERT(parentRenderer);
 
     bool paintSelectedTextOnly = paintInfo.phase == PaintPhaseSelection;
-    bool hasSelection = !parentRenderer->document()->printing() && selectionState() != RenderObject::SelectionNone;
+    bool hasSelection = !parentRenderer->document().printing() && selectionState() != RenderObject::SelectionNone;
     if (!hasSelection && paintSelectedTextOnly)
         return;
 
@@ -368,7 +368,7 @@
     ASSERT(style);
     ASSERT(m_paintingResourceMode != ApplyToDefaultMode);
 
-    StyleColor fallbackColor;
+    Color fallbackColor;
     if (m_paintingResourceMode & ApplyToFillMode)
         m_paintingResource = RenderSVGResource::fillPaintingResource(renderer, style, fallbackColor);
     else if (m_paintingResourceMode & ApplyToStrokeMode)
@@ -384,7 +384,7 @@
     if (!m_paintingResource->applyResource(renderer, style, context, m_paintingResourceMode)) {
         if (fallbackColor.isValid()) {
             RenderSVGResourceSolidColor* fallbackResource = RenderSVGResource::sharedSolidPaintingResource();
-            fallbackResource->setColor(fallbackColor.color());
+            fallbackResource->setColor(fallbackColor);
 
             m_paintingResource = fallbackResource;
             m_paintingResource->applyResource(renderer, style, context, m_paintingResourceMode);
@@ -641,7 +641,7 @@
         DrawLooper drawLooper;
         do {
             FloatSize offset(shadow->x(), shadow->y());
-            drawLooper.addShadow(offset, shadow->blur(), textRenderer->resolveColor(shadow->color(), Color::stdShadowColor),
+            drawLooper.addShadow(offset, shadow->blur(), shadow->color(),
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowRespectsAlpha);
         } while ((shadow = shadow->next()));
         drawLooper.addUnmodifiedContent();
diff --git a/Source/core/rendering/svg/SVGPathData.cpp b/Source/core/rendering/svg/SVGPathData.cpp
index f6ccd95..d9085d6 100644
--- a/Source/core/rendering/svg/SVGPathData.cpp
+++ b/Source/core/rendering/svg/SVGPathData.cpp
@@ -89,10 +89,7 @@
 
 static void updatePathFromPolylineElement(SVGElement* element, Path& path)
 {
-    ASSERT(element->hasTagName(SVGNames::polylineTag));
-    SVGPolylineElement* polyline = static_cast<SVGPolylineElement*>(element);
-
-    SVGPointList& points = polyline->pointList();
+    SVGPointList& points = toSVGPolylineElement(element)->pointList();
     if (points.isEmpty())
         return;
 
diff --git a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
index b4ebbd0..56be0a9 100644
--- a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
+++ b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
@@ -242,9 +242,8 @@
 
     // All other resources derive from RenderSVGResourceContainer
     RenderSVGResourceContainer* container = static_cast<RenderSVGResourceContainer*>(resource);
-    Node* node = container->node();
-    ASSERT(node);
-    ASSERT(node->isSVGElement());
+    SVGElement* element = container->element();
+    ASSERT(element);
 
     if (resource->resourceType() == PatternResourceType)
         ts << "[type=PATTERN]";
@@ -253,7 +252,7 @@
     else if (resource->resourceType() == RadialGradientResourceType)
         ts << "[type=RADIAL-GRADIENT]";
 
-    ts << " [id=\"" << toSVGElement(node)->getIdAttribute() << "\"]";
+    ts << " [id=\"" << element->getIdAttribute() << "\"]";
 }
 
 static void writeStyle(TextStream& ts, const RenderObject& object)
@@ -267,16 +266,15 @@
     writeIfNotDefault(ts, "opacity", style->opacity(), RenderStyle::initialOpacity());
     if (object.isSVGShape()) {
         const RenderSVGShape& shape = static_cast<const RenderSVGShape&>(object);
-        ASSERT(shape.node());
-        ASSERT(shape.node()->isSVGElement());
+        ASSERT(shape.element());
 
-        StyleColor fallbackColor;
+        Color fallbackColor;
         if (RenderSVGResource* strokePaintingResource = RenderSVGResource::strokePaintingResource(const_cast<RenderSVGShape*>(&shape), shape.style(), fallbackColor)) {
             TextStreamSeparator s(" ");
             ts << " [stroke={" << s;
             writeSVGPaintingResource(ts, strokePaintingResource);
 
-            SVGLengthContext lengthContext(toSVGElement(shape.node()));
+            SVGLengthContext lengthContext(toSVGElement(shape.element()));
             double dashOffset = svgStyle->strokeDashOffset().value(lengthContext);
             double strokeWidth = svgStyle->strokeWidth().value(lengthContext);
             const Vector<SVGLength>& dashes = svgStyle->strokeDashArray();
@@ -326,8 +324,7 @@
 {
     writePositionAndStyle(ts, shape);
 
-    ASSERT(shape.node()->isSVGElement());
-    SVGElement* svgElement = toSVGElement(shape.node());
+    SVGElement* svgElement = shape.element();
     SVGLengthContext lengthContext(svgElement);
 
     if (svgElement->hasTagName(SVGNames::rectTag)) {
@@ -507,8 +504,7 @@
                 lastEffect->externalRepresentation(ts, indent + 1);
         }
     } else if (resource->resourceType() == ClipperResourceType) {
-        RenderSVGResourceClipper* clipper = static_cast<RenderSVGResourceClipper*>(resource);
-        writeNameValuePair(ts, "clipPathUnits", clipper->clipPathUnits());
+        writeNameValuePair(ts, "clipPathUnits", toRenderSVGResourceClipper(resource)->clipPathUnits());
         ts << "\n";
     } else if (resource->resourceType() == MarkerResourceType) {
         RenderSVGResourceMarker* marker = static_cast<RenderSVGResourceMarker*>(resource);
@@ -525,7 +521,7 @@
         // Dump final results that are used for rendering. No use in asking SVGPatternElement for its patternUnits(), as it may
         // link to other patterns using xlink:href, we need to build the full inheritance chain, aka. collectPatternProperties()
         PatternAttributes attributes;
-        toSVGPatternElement(pattern->node())->collectPatternAttributes(attributes);
+        toSVGPatternElement(pattern->element())->collectPatternAttributes(attributes);
 
         writeNameValuePair(ts, "patternUnits", attributes.patternUnits());
         writeNameValuePair(ts, "patternContentUnits", attributes.patternContentUnits());
@@ -540,7 +536,7 @@
         // 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()
         LinearGradientAttributes attributes;
-        toSVGLinearGradientElement(gradient->node())->collectGradientAttributes(attributes);
+        toSVGLinearGradientElement(gradient->element())->collectGradientAttributes(attributes);
         writeCommonGradientProperties(ts, attributes.spreadMethod(), attributes.gradientTransform(), attributes.gradientUnits());
 
         ts << " [start=" << gradient->startPoint(attributes) << "] [end=" << gradient->endPoint(attributes) << "]\n";
@@ -550,7 +546,7 @@
         // 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()
         RadialGradientAttributes attributes;
-        toSVGRadialGradientElement(gradient->node())->collectGradientAttributes(attributes);
+        toSVGRadialGradientElement(gradient->element())->collectGradientAttributes(attributes);
         writeCommonGradientProperties(ts, attributes.spreadMethod(), attributes.gradientTransform(), attributes.gradientUnits());
 
         FloatPoint focalPoint = gradient->focalPoint(attributes);
diff --git a/Source/core/rendering/svg/SVGRenderingContext.cpp b/Source/core/rendering/svg/SVGRenderingContext.cpp
index 89aceef..216a847 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.cpp
+++ b/Source/core/rendering/svg/SVGRenderingContext.cpp
@@ -28,6 +28,7 @@
 
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
+#include "core/page/Page.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/svg/RenderSVGImage.h"
 #include "core/rendering/svg/RenderSVGResource.h"
@@ -206,6 +207,10 @@
     ASSERT(renderer);
     absoluteTransform = currentContentTransformation();
 
+    float deviceScaleFactor = 1;
+    if (Page* page = renderer->document().page())
+        deviceScaleFactor = page->deviceScaleFactor();
+
     // Walk up the render tree, accumulating SVG transforms.
     while (renderer) {
         absoluteTransform = renderer->localToParentTransform() * absoluteTransform;
@@ -226,30 +231,9 @@
 
         layer = layer->parent();
     }
-}
 
-bool SVGRenderingContext::createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform, OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
-{
-    IntRect paintRect = calculateImageBufferRect(targetRect, absoluteTransform);
-    // Don't create empty ImageBuffers.
-    if (paintRect.isEmpty())
-        return false;
-
-    IntSize clampedSize = clampedAbsoluteSize(paintRect.size());
-    OwnPtr<ImageBuffer> image = ImageBuffer::create(clampedSize, 1, renderingMode);
-    if (!image)
-        return false;
-
-    GraphicsContext* imageContext = image->context();
-    ASSERT(imageContext);
-
-    imageContext->scale(FloatSize(static_cast<float>(clampedSize.width()) / paintRect.width(),
-                                  static_cast<float>(clampedSize.height()) / paintRect.height()));
-    imageContext->translate(-paintRect.x(), -paintRect.y());
-    imageContext->concatCTM(absoluteTransform);
-
-    imageBuffer = image.release();
-    return true;
+    if (deviceScaleFactor != 1)
+        absoluteTransform.scale(deviceScaleFactor);
 }
 
 bool SVGRenderingContext::createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
diff --git a/Source/core/rendering/svg/SVGRenderingContext.h b/Source/core/rendering/svg/SVGRenderingContext.h
index 3bc88c1..3d063f5 100644
--- a/Source/core/rendering/svg/SVGRenderingContext.h
+++ b/Source/core/rendering/svg/SVGRenderingContext.h
@@ -76,7 +76,6 @@
     void prepareToRenderSVGContent(RenderObject*, PaintInfo&, NeedsGraphicsContextSave = DontSaveGraphicsContext);
     bool isRenderingPrepared() const { return m_renderingFlags & RenderingPrepared; }
 
-    static bool createImageBuffer(const FloatRect& paintRect, const AffineTransform& absoluteTransform, OwnPtr<ImageBuffer>&, RenderingMode);
     // Patterns need a different float-to-integer coordinate mapping.
     static bool createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>&, RenderingMode);
 
diff --git a/Source/core/rendering/svg/SVGResources.cpp b/Source/core/rendering/svg/SVGResources.cpp
index 3fd84a8..b5b42ba 100644
--- a/Source/core/rendering/svg/SVGResources.cpp
+++ b/Source/core/rendering/svg/SVGResources.cpp
@@ -77,7 +77,6 @@
         // (Already mailed SVG WG, waiting for a solution)
         s_tagList.add(SVGNames::altGlyphTag.localName());
         s_tagList.add(SVGNames::textPathTag.localName());
-        s_tagList.add(SVGNames::trefTag.localName());
         s_tagList.add(SVGNames::tspanTag.localName());
 
         // Not listed in the definitions is the foreignObject element, but clip-path
@@ -119,7 +118,6 @@
         s_tagList.add(SVGNames::rectTag.localName());
         s_tagList.add(SVGNames::textTag.localName());
         s_tagList.add(SVGNames::textPathTag.localName());
-        s_tagList.add(SVGNames::trefTag.localName());
         s_tagList.add(SVGNames::tspanTag.localName());
     }
 
@@ -154,7 +152,7 @@
     return SVGURIReference::fragmentIdentifierFromIRIString(target, element->document());
 }
 
-static inline RenderSVGResourceContainer* paintingResourceFromSVGPaint(Document* document, const SVGPaint::SVGPaintType& paintType, const String& paintUri, AtomicString& id, bool& hasPendingResource)
+static inline RenderSVGResourceContainer* paintingResourceFromSVGPaint(Document& document, const SVGPaint::SVGPaintType& paintType, const String& paintUri, AtomicString& id, bool& hasPendingResource)
 {
     if (paintType != SVGPaint::SVG_PAINTTYPE_URI && paintType != SVGPaint::SVG_PAINTTYPE_URI_RGBCOLOR)
         return 0;
@@ -192,10 +190,9 @@
     if (!element)
         return false;
 
-    Document* document = object->document();
-    ASSERT(document);
+    Document& document = object->document();
 
-    SVGDocumentExtensions* extensions = document->accessSVGExtensions();
+    SVGDocumentExtensions* extensions = document.accessSVGExtensions();
     ASSERT(extensions);
 
     const AtomicString& tagName = element->localName();
@@ -633,31 +630,31 @@
     fprintf(stderr, "\n | List of resources:\n");
     if (m_clipperFilterMaskerData) {
         if (RenderSVGResourceClipper* clipper = m_clipperFilterMaskerData->clipper)
-            fprintf(stderr, " |-> Clipper    : %p (node=%p)\n", clipper, clipper->node());
+            fprintf(stderr, " |-> Clipper    : %p (node=%p)\n", clipper, clipper->element());
         if (RenderSVGResourceFilter* filter = m_clipperFilterMaskerData->filter)
-            fprintf(stderr, " |-> Filter     : %p (node=%p)\n", filter, filter->node());
+            fprintf(stderr, " |-> Filter     : %p (node=%p)\n", filter, filter->element());
         if (RenderSVGResourceMasker* masker = m_clipperFilterMaskerData->masker)
-            fprintf(stderr, " |-> Masker     : %p (node=%p)\n", masker, masker->node());
+            fprintf(stderr, " |-> Masker     : %p (node=%p)\n", masker, masker->element());
     }
 
     if (m_markerData) {
         if (RenderSVGResourceMarker* markerStart = m_markerData->markerStart)
-            fprintf(stderr, " |-> MarkerStart: %p (node=%p)\n", markerStart, markerStart->node());
+            fprintf(stderr, " |-> MarkerStart: %p (node=%p)\n", markerStart, markerStart->element());
         if (RenderSVGResourceMarker* markerMid = m_markerData->markerMid)
-            fprintf(stderr, " |-> MarkerMid  : %p (node=%p)\n", markerMid, markerMid->node());
+            fprintf(stderr, " |-> MarkerMid  : %p (node=%p)\n", markerMid, markerMid->element());
         if (RenderSVGResourceMarker* markerEnd = m_markerData->markerEnd)
-            fprintf(stderr, " |-> MarkerEnd  : %p (node=%p)\n", markerEnd, markerEnd->node());
+            fprintf(stderr, " |-> MarkerEnd  : %p (node=%p)\n", markerEnd, markerEnd->element());
     }
 
     if (m_fillStrokeData) {
         if (RenderSVGResourceContainer* fill = m_fillStrokeData->fill)
-            fprintf(stderr, " |-> Fill       : %p (node=%p)\n", fill, fill->node());
+            fprintf(stderr, " |-> Fill       : %p (node=%p)\n", fill, fill->element());
         if (RenderSVGResourceContainer* stroke = m_fillStrokeData->stroke)
-            fprintf(stderr, " |-> Stroke     : %p (node=%p)\n", stroke, stroke->node());
+            fprintf(stderr, " |-> Stroke     : %p (node=%p)\n", stroke, stroke->element());
     }
 
     if (m_linkedResource)
-        fprintf(stderr, " |-> xlink:href : %p (node=%p)\n", m_linkedResource, m_linkedResource->node());
+        fprintf(stderr, " |-> xlink:href : %p (node=%p)\n", m_linkedResource, m_linkedResource->element());
 }
 #endif
 
diff --git a/Source/core/rendering/svg/SVGResources.h b/Source/core/rendering/svg/SVGResources.h
index 7fba577..ec911bb 100644
--- a/Source/core/rendering/svg/SVGResources.h
+++ b/Source/core/rendering/svg/SVGResources.h
@@ -150,7 +150,7 @@
     // From SVG 1.1 2nd Edition
     // fill:       'shapes' and 'text content elements'
     // stroke:     'shapes' and 'text content elements'
-    // -> altGlyph, circle, ellipse, line, path, polygon, polyline, rect, text, textPath, tref, tspan
+    // -> altGlyph, circle, ellipse, line, path, polygon, polyline, rect, text, textPath, tspan
     struct FillStrokeData {
         WTF_MAKE_FAST_ALLOCATED;
     public:
diff --git a/Source/core/rendering/svg/SVGResourcesCache.cpp b/Source/core/rendering/svg/SVGResourcesCache.cpp
index 9f89a41..330ee7f 100644
--- a/Source/core/rendering/svg/SVGResourcesCache.cpp
+++ b/Source/core/rendering/svg/SVGResourcesCache.cpp
@@ -84,10 +84,9 @@
 
 static inline SVGResourcesCache* resourcesCacheFromRenderObject(const RenderObject* renderer)
 {
-    Document* document = renderer->document();
-    ASSERT(document);
+    Document& document = renderer->document();
 
-    SVGDocumentExtensions* extensions = document->accessSVGExtensions();
+    SVGDocumentExtensions* extensions = document.accessSVGExtensions();
     ASSERT(extensions);
 
     SVGResourcesCache* cache = extensions->resourcesCache();
@@ -197,9 +196,9 @@
         it->value->resourceDestroyed(resource);
 
         // Mark users of destroyed resources as pending resolution based on the id of the old resource.
-        Element* resourceElement = toElement(resource->node());
+        Element* resourceElement = resource->element();
         Element* clientElement = toElement(it->key->node());
-        SVGDocumentExtensions* extensions = clientElement->document()->accessSVGExtensions();
+        SVGDocumentExtensions* extensions = clientElement->document().accessSVGExtensions();
 
         extensions->addPendingResource(resourceElement->fastGetAttribute(HTMLNames::idAttr), clientElement);
     }
diff --git a/Source/core/rendering/svg/SVGRootInlineBox.cpp b/Source/core/rendering/svg/SVGRootInlineBox.cpp
index f81e128..d9e6ec7 100644
--- a/Source/core/rendering/svg/SVGRootInlineBox.cpp
+++ b/Source/core/rendering/svg/SVGRootInlineBox.cpp
@@ -41,7 +41,7 @@
     RenderObject* boxRenderer = renderer();
     ASSERT(boxRenderer);
 
-    bool isPrinting = renderer()->document()->printing();
+    bool isPrinting = renderer()->document().printing();
     bool hasSelection = !isPrinting && selectionState() != RenderObject::SelectionNone;
 
     PaintInfo childPaintInfo(paintInfo);
diff --git a/Source/core/scripts/make_event_factory.py b/Source/core/scripts/make_event_factory.py
index d34e4be..ace45ab 100644
--- a/Source/core/scripts/make_event_factory.py
+++ b/Source/core/scripts/make_event_factory.py
@@ -33,6 +33,7 @@
 
 from in_file import InFile
 import name_macros
+from name_utilities import lower_first
 import license
 
 
@@ -73,9 +74,10 @@
         return self.in_file.name_dictionaries
 
     def _factory_implementation(self, event):
-        runtime_condition = ''
         if event['EnabledAtRuntime']:
-            runtime_condition = ' && RuntimeEnabledFeatures::' + event['EnabledAtRuntime'] + '()'
+            runtime_condition = ' && RuntimeEnabledFeatures::%s()' % lower_first(event['EnabledAtRuntime'])
+        else:
+            runtime_condition = ''
         name = os.path.basename(event['name'])
         class_name = self._class_name_for_entry(event)
         implementation = """    if (type == "%(name)s"%(runtime_condition)s)
diff --git a/Source/core/scripts/make_names.pl b/Source/core/scripts/make_names.pl
index c237fe4..1748ca6 100755
--- a/Source/core/scripts/make_names.pl
+++ b/Source/core/scripts/make_names.pl
@@ -339,7 +339,7 @@
 {
     my ($F, $tagName, $constructorName, $constructorTagName) = @_;
 
-    print F "static PassRefPtr<$parameters{namespace}Element> ${constructorName}Constructor(const QualifiedName& $constructorTagName, Document* document";
+    print F "static PassRefPtr<$parameters{namespace}Element> ${constructorName}Constructor(const QualifiedName& $constructorTagName, Document& document";
     if ($parameters{namespace} eq "HTML") {
         print F ", HTMLFormElement*";
         print F " formElement" if $enabledTags{$tagName}{constructorNeedsFormElement};
@@ -359,7 +359,7 @@
     # Handle media elements.
     if ($enabledTags{$tagName}{wrapperOnlyIfMediaIsAvailable}) {
         print F <<END
-    Settings* settings = document->settings();
+    Settings* settings = document.settings();
     if (!RuntimeEnabledFeatures::mediaEnabled() || (settings && !settings->mediaEnabled()))
         return 0;
 
@@ -370,7 +370,7 @@
     my $contextConditional = $enabledTags{$tagName}{contextConditional};
     if ($contextConditional) {
         print F <<END
-    if (!ContextFeatures::${contextConditional}Enabled(document))
+    if (!ContextFeatures::${contextConditional}Enabled(&document))
         return 0;
 END
 ;
@@ -803,6 +803,7 @@
 
 #include "ContextFeatures.h"
 #include "CustomElement.h"
+#include "CustomElementRegistrationContext.h"
 #include "Document.h"
 #include "RuntimeEnabledFeatures.h"
 #include "Settings.h"
@@ -814,7 +815,7 @@
 END
 ;
 
-print F "typedef PassRefPtr<$parameters{namespace}Element> (*ConstructorFunction)(const QualifiedName&, Document*";
+print F "typedef PassRefPtr<$parameters{namespace}Element> (*ConstructorFunction)(const QualifiedName&, Document&";
 print F ", HTMLFormElement*" if $parameters{namespace} eq "HTML";
 print F ", bool createdByParser);\n";
 print F <<END
@@ -860,7 +861,7 @@
         return 0;
 
     if (CustomElement::isValidName(qName.localName()) && document->registrationContext()) {
-        RefPtr<Element> element = document->registrationContext()->createCustomTagElement(document, qName, createdByParser ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
+        RefPtr<Element> element = document->registrationContext()->createCustomTagElement(*document, qName, createdByParser ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
         ASSERT_WITH_SECURITY_IMPLICATION(element->is$parameters{namespace}Element());
         return static_pointer_cast<$parameters{namespace}Element>(element.release());
     }
@@ -872,16 +873,16 @@
 ;
 
 if ($parameters{namespace} eq "HTML") {
-    print F "        if (PassRefPtr<$parameters{namespace}Element> element = function(qName, document, formElement, createdByParser))\n";
+    print F "        if (PassRefPtr<$parameters{namespace}Element> element = function(qName, *document, formElement, createdByParser))\n";
     print F "            return element;\n";
 } else {
-    print F "        if (PassRefPtr<$parameters{namespace}Element> element = function(qName, document, createdByParser))\n";
+    print F "        if (PassRefPtr<$parameters{namespace}Element> element = function(qName, *document, createdByParser))\n";
     print F "            return element;\n";
 }
 print F <<END
     }
 
-    return $parameters{fallbackInterfaceName}::create(qName, document);
+    return $parameters{fallbackInterfaceName}::create(qName, *document);
 }
 
 } // namespace WebCore
@@ -978,7 +979,7 @@
             print F <<END
 static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
 {
-    Settings* settings = element->document()->settings();
+    Settings* settings = element->document().settings();
     if (!RuntimeEnabledFeatures::mediaEnabled() || (settings && !settings->mediaEnabled()))
         return createV8$parameters{namespace}DirectWrapper(element, creationContext, isolate);
     return wrap(static_cast<${JSInterfaceName}*>(element), creationContext, isolate);
@@ -991,7 +992,7 @@
             print F <<END
 static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
 {
-    if (!ContextFeatures::${contextConditional}Enabled(element->document()))
+    if (!ContextFeatures::${contextConditional}Enabled(&element->document()))
         return createV8$parameters{namespace}FallbackWrapper(to$parameters{fallbackInterfaceName}(element), creationContext, isolate);
     return wrap(static_cast<${JSInterfaceName}*>(element), creationContext, isolate);
 }
@@ -1143,13 +1144,19 @@
 END
 ;
     }
+
+    my $fallbackWrapper = $parameters{fallbackInterfaceName};
+    if ($parameters{namespace} eq "SVG") {
+        $fallbackWrapper = "SVGElement";
+    }
+
     print F <<END
 }
 
-const QualifiedName* find$parameters{namespace}TagNameOfV8Type(const WrapperTypeInfo* type)
+WrapperTypeInfo* findWrapperTypeFor$parameters{namespace}TagName(const AtomicString& name)
 {
-    typedef HashMap<const WrapperTypeInfo*, const QualifiedName*> TypeNameMap;
-    DEFINE_STATIC_LOCAL(TypeNameMap, map, ());
+    typedef HashMap<WTF::StringImpl*, WrapperTypeInfo*> NameTypeMap;
+    DEFINE_STATIC_LOCAL(NameTypeMap, map, ());
     if (map.isEmpty()) {
 END
 ;
@@ -1163,7 +1170,7 @@
             }
 
             my $JSInterfaceName = $enabledTags{$tagName}{JSInterfaceName};
-            print F "       map.set(WrapperTypeTraits<${JSInterfaceName}>::info(), &${tagName}Tag);\n";
+            print F "       map.set(${tagName}Tag.localName().impl(), WrapperTypeTraits<${JSInterfaceName}>::info());\n";
 
             if ($conditional) {
                 print F "#endif\n";
@@ -1174,7 +1181,10 @@
     print F <<END
     }
 
-    return map.get(type);
+    if (WrapperTypeInfo* result = map.get(name.impl()))
+        return result;
+
+    return WrapperTypeTraits<$fallbackWrapper>::info();
 }
 
 END
@@ -1209,7 +1219,8 @@
 
     class $parameters{namespace}Element;
 
-    const QualifiedName* find$parameters{namespace}TagNameOfV8Type(const WrapperTypeInfo*);
+    WrapperTypeInfo* findWrapperTypeFor$parameters{namespace}TagName(const AtomicString& name);
+
     v8::Handle<v8::Object> createV8$parameters{namespace}Wrapper($parameters{namespace}Element*, v8::Handle<v8::Object> creationContext, v8::Isolate*);
     inline v8::Handle<v8::Object> createV8$parameters{namespace}DirectWrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
     {
diff --git a/Source/core/scripts/make_runtime_features.py b/Source/core/scripts/make_runtime_features.py
index 6ec681b..ad84a25 100755
--- a/Source/core/scripts/make_runtime_features.py
+++ b/Source/core/scripts/make_runtime_features.py
@@ -32,6 +32,7 @@
 
 from in_file import InFile
 import in_generator
+from name_utilities import lower_first
 import template_expander
 
 
@@ -47,7 +48,6 @@
         'depends_on' : [],
         'custom': False,
         'status': None,
-        'writeable': False,
     }
 
     def __init__(self, in_file_path, enabled_conditions):
@@ -59,7 +59,7 @@
         self._features = self.in_file.name_dictionaries
         # Make sure the resulting dictionaries have all the keys we expect.
         for feature in self._features:
-            feature['first_lowered_name'] = self._lower_first(feature['name'])
+            feature['first_lowered_name'] = lower_first(feature['name'])
             # Most features just check their isFooEnabled bool
             # but some depend on more than one bool.
             enabled_condition = "is%sEnabled" % feature['name']
@@ -68,15 +68,6 @@
             feature['enabled_condition'] = enabled_condition
         self._non_custom_features = filter(lambda feature: not feature['custom'], self._features)
 
-    def _lower_first(self, string):
-        lowered = string[0].lower() + string[1:]
-        lowered = lowered.replace("cSS", "css")
-        lowered = lowered.replace("iME", "ime")
-        lowered = lowered.replace("hTML", "html")
-        lowered = lowered.replace("sVG", "svg")
-        lowered = lowered.replace("wOFF", "woff")
-        return lowered
-
     def _feature_sets(self):
         # Another way to think of the status levels is as "sets of features"
         # which is how we're referring to them in this generator.
diff --git a/Source/core/scripts/name_utilities.py b/Source/core/scripts/name_utilities.py
new file mode 100644
index 0000000..c4993b0
--- /dev/null
+++ b/Source/core/scripts/name_utilities.py
@@ -0,0 +1,40 @@
+# 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.
+
+ACRONYMS = ['CSS', 'HTML', 'IME', 'JS', 'SVG', 'URL', 'WOFF', 'XML', 'XSLT']
+
+
+def lower_first(name):
+    """Return name with first letter or initial acronym lowercased.
+
+    E.g., 'SetURL' becomes 'setURL', but 'URLFoo' becomes 'urlFoo'.
+    """
+    for acronym in ACRONYMS:
+        if name.startswith(acronym):
+            return name.replace(acronym, acronym.lower())
+    return name[0].lower() + name[1:]
diff --git a/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl b/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
index f33a3b3..fe77d0c 100644
--- a/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
+++ b/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
@@ -27,9 +27,6 @@
 {% for feature in features if not feature.custom %}
 {%- call wrap_with_condition(feature.condition) %}
     bool {{feature.first_lowered_name}}Enabled() { return RuntimeEnabledFeatures::{{feature.first_lowered_name}}Enabled(); }
-    {% if feature.writeable %}
-    void set{{feature.name}}Enabled(bool isEnabled) { RuntimeEnabledFeatures::set{{feature.name}}Enabled(isEnabled); }
-    {% endif %}
 {%- endcall %}
 {% endfor %}
 
diff --git a/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl b/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl
index f0161f9..92838f2 100644
--- a/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl
+++ b/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl
@@ -9,10 +9,6 @@
     it's possible that some can be and should be conditionally readonly.
 #}
     {% if feature.condition -%} [Conditional={{feature.condition}}] {% endif -%}
-    {% if feature.writeable %}
-    attribute boolean {{feature.first_lowered_name}}Enabled;
-    {% else %}
     readonly attribute boolean {{feature.first_lowered_name}}Enabled;
-    {% endif %}
 {%- endfor %}
 };
diff --git a/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl b/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
index f9a486a..c6182dd 100644
--- a/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
+++ b/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
@@ -63,7 +63,8 @@
     const CSSAnimationDataList* parentList = state.parentStyle()->{{animation|lower}}();
     size_t i = 0, parentSize = parentList ? parentList->size() : 0;
     for ( ; i < parentSize && parentList->animation(i)->is{{attribute}}Set(); ++i) {
-        if (list->size() <= i)
+        ASSERT(list->size() >= i);
+        if (list->size() == i)
             list->append(CSSAnimationData::create());
         list->animation(i)->set{{attribute}}(parentList->animation(i)->{{lower_first(attribute)}}());
         list->animation(i)->setAnimationMode(parentList->animation(i)->animationMode());
@@ -81,7 +82,8 @@
     if (value->isValueList()) {
         // Walk each value and put it into an animation, creating new animations as needed.
         for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
-            if (childIndex <= list->size())
+            ASSERT(list->size() >= childIndex);
+            if (list->size() == childIndex)
                 list->append(CSSAnimationData::create());
             state.styleMap().mapAnimation{{attribute}}(list->animation(childIndex), i.value());
             ++childIndex;
@@ -248,7 +250,7 @@
 {%- set visited_link_setter = "setVisitedLink" + property.camel_case_name %}
 {{ declare_initial_function(property_id) }}
 {
-    StyleColor color = {{ initial_color or "StyleColor" -}}();
+    Color color = {{ initial_color or "Color" -}}();
     if (state.applyPropertyToRegularStyle())
         {{ set_value(property) }}(color);
     if (state.applyPropertyToVisitedLinkStyle())
@@ -258,7 +260,7 @@
 {{ declare_inherit_function(property_id) }}
 {
     // Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
-    StyleColor color = state.parentStyle()->{{property.getter}}();
+    Color color = state.parentStyle()->{{property.getter}}();
     if (!color.isValid())
         color = state.parentStyle()->{{default_getter}}();
     if (state.applyPropertyToRegularStyle())
@@ -282,9 +284,9 @@
 {%- endif %}
 
     if (state.applyPropertyToRegularStyle())
-        {{ set_value(property) }}(state.document()->textLinkColors().colorFromPrimitiveValue(primitiveValue));
+        {{ set_value(property) }}(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->visitedDependentColor(CSSPropertyColor)));
     if (state.applyPropertyToVisitedLinkStyle())
-        state.style()->{{visited_link_setter}}(state.document()->textLinkColors().colorFromPrimitiveValue(primitiveValue, state.element()->isLink() /* forVisitedLink */));
+        state.style()->{{visited_link_setter}}(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->visitedDependentColor(CSSPropertyColor), state.element()->isLink() /* forVisitedLink */));
 }
 {%- endmacro %}
 
@@ -433,6 +435,7 @@
 {{ apply_fill_layer("CSSPropertyBackgroundRepeatX", "RepeatX") }}
 {{ apply_fill_layer("CSSPropertyBackgroundRepeatY", "RepeatY") }}
 {{ apply_fill_layer("CSSPropertyBackgroundSize", "Size") }}
+{{ apply_fill_layer("CSSPropertyMaskSourceType", "MaskSourceType") }}
 {{ apply_fill_layer("CSSPropertyWebkitBackgroundComposite", "Composite") }}
 {{ apply_fill_layer("CSSPropertyWebkitMaskClip", "Clip") }}
 {{ apply_fill_layer("CSSPropertyWebkitMaskComposite", "Composite") }}
diff --git a/Source/core/inspector/xxd.pl b/Source/core/scripts/xxd.pl
similarity index 100%
rename from Source/core/inspector/xxd.pl
rename to Source/core/scripts/xxd.pl
diff --git a/Source/core/svg/SVGAElement.cpp b/Source/core/svg/SVGAElement.cpp
index c1d88fb..84fa34d 100644
--- a/Source/core/svg/SVGAElement.cpp
+++ b/Source/core/svg/SVGAElement.cpp
@@ -32,7 +32,6 @@
 #include "core/dom/EventNames.h"
 #include "core/dom/KeyboardEvent.h"
 #include "core/dom/MouseEvent.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
@@ -67,7 +66,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGAElement::SVGAElement(const QualifiedName& tagName, Document* document)
+inline SVGAElement::SVGAElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::aTag));
@@ -75,7 +74,7 @@
     registerAnimatedPropertiesForSVGAElement();
 }
 
-PassRefPtr<SVGAElement> SVGAElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGAElement> SVGAElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGAElement(tagName, document));
 }
@@ -163,7 +162,7 @@
             String url = stripLeadingAndTrailingHTMLSpaces(hrefCurrentValue());
 
             if (url[0] == '#') {
-                Element* targetElement = treeScope()->getElementById(url.substring(1));
+                Element* targetElement = treeScope().getElementById(url.substring(1));
                 if (SVGSMILElement::isSMILElement(targetElement)) {
                     toSVGSMILElement(targetElement)->beginByLinkActivation();
                     event->setDefaultHandled();
@@ -179,10 +178,10 @@
                 target = "_blank";
             event->setDefaultHandled();
 
-            Frame* frame = document()->frame();
+            Frame* frame = document().frame();
             if (!frame)
                 return;
-            FrameLoadRequest frameRequest(document()->securityOrigin(), ResourceRequest(document()->completeURL(url)), target);
+            FrameLoadRequest frameRequest(document().securityOrigin(), ResourceRequest(document().completeURL(url)), target);
             frameRequest.setTriggeringEvent(event);
             frame->loader()->load(frameRequest);
             return;
@@ -222,21 +221,21 @@
     if (!isFocusable())
         return false;
 
-    if (Page* page = document()->page())
+    if (Page* page = document().page())
         return page->chrome().client().tabsToLinks();
     return false;
 }
 
-bool SVGAElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGAElement::childShouldCreateRenderer(const Node& child) const
 {
     // http://www.w3.org/2003/01/REC-SVG11-20030114-errata#linking-text-environment
     // The 'a' element may contain any element that its parent may contain, except itself.
-    if (childContext.node()->hasTagName(SVGNames::aTag))
+    if (child.hasTagName(SVGNames::aTag))
         return false;
     if (parentNode() && parentNode()->isSVGElement())
-        return parentNode()->childShouldCreateRenderer(childContext);
+        return parentNode()->childShouldCreateRenderer(child);
 
-    return SVGElement::childShouldCreateRenderer(childContext);
+    return SVGElement::childShouldCreateRenderer(child);
 }
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGAElement.h b/Source/core/svg/SVGAElement.h
index 8fa4b67..b3d0743 100644
--- a/Source/core/svg/SVGAElement.h
+++ b/Source/core/svg/SVGAElement.h
@@ -33,10 +33,10 @@
                           public SVGURIReference,
                           public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGAElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGAElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGAElement(const QualifiedName&, Document*);
+    SVGAElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
 
@@ -57,7 +57,7 @@
     virtual bool rendererIsFocusable() const OVERRIDE;
     virtual bool isURLAttribute(const Attribute&) const;
 
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
+    virtual bool childShouldCreateRenderer(const Node& child) const;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGAElement)
         // This declaration used to define a non-virtual "String& target() const" method, that clashes with "virtual String Element::target() const".
diff --git a/Source/core/svg/SVGAltGlyphDefElement.cpp b/Source/core/svg/SVGAltGlyphDefElement.cpp
index e5a1831..b632087 100644
--- a/Source/core/svg/SVGAltGlyphDefElement.cpp
+++ b/Source/core/svg/SVGAltGlyphDefElement.cpp
@@ -28,14 +28,14 @@
 
 namespace WebCore {
 
-inline SVGAltGlyphDefElement::SVGAltGlyphDefElement(const QualifiedName& tagName, Document* document)
+inline SVGAltGlyphDefElement::SVGAltGlyphDefElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::altGlyphDefTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGAltGlyphDefElement> SVGAltGlyphDefElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGAltGlyphDefElement> SVGAltGlyphDefElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGAltGlyphDefElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGAltGlyphDefElement.h b/Source/core/svg/SVGAltGlyphDefElement.h
index 8e083fc..f3b1fd8 100644
--- a/Source/core/svg/SVGAltGlyphDefElement.h
+++ b/Source/core/svg/SVGAltGlyphDefElement.h
@@ -28,14 +28,14 @@
 
 class SVGAltGlyphDefElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGAltGlyphDefElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGAltGlyphDefElement> create(const QualifiedName&, Document&);
 
     bool hasValidGlyphElements(Vector<String>& glyphNames) const;
 
 private:
-    SVGAltGlyphDefElement(const QualifiedName&, Document*);
+    SVGAltGlyphDefElement(const QualifiedName&, Document&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 }
diff --git a/Source/core/svg/SVGAltGlyphElement.cpp b/Source/core/svg/SVGAltGlyphElement.cpp
index c5224b8..691b8f4 100644
--- a/Source/core/svg/SVGAltGlyphElement.cpp
+++ b/Source/core/svg/SVGAltGlyphElement.cpp
@@ -29,7 +29,6 @@
 #include "XLinkNames.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/rendering/svg/RenderSVGTSpan.h"
 #include "core/svg/SVGAltGlyphDefElement.h"
 
@@ -43,7 +42,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextPositioningElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGAltGlyphElement::SVGAltGlyphElement(const QualifiedName& tagName, Document* document)
+inline SVGAltGlyphElement::SVGAltGlyphElement(const QualifiedName& tagName, Document& document)
     : SVGTextPositioningElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::altGlyphTag));
@@ -51,7 +50,7 @@
     registerAnimatedPropertiesForSVGAltGlyphElement();
 }
 
-PassRefPtr<SVGAltGlyphElement> SVGAltGlyphElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGAltGlyphElement> SVGAltGlyphElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGAltGlyphElement(tagName, document));
 }
@@ -76,9 +75,9 @@
     return fastGetAttribute(SVGNames::formatAttr);
 }
 
-bool SVGAltGlyphElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGAltGlyphElement::childShouldCreateRenderer(const Node& child) const
 {
-    if (childContext.node()->isTextNode())
+    if (child.isTextNode())
         return true;
     return false;
 }
diff --git a/Source/core/svg/SVGAltGlyphElement.h b/Source/core/svg/SVGAltGlyphElement.h
index 9ab0bca..2ab0ee7 100644
--- a/Source/core/svg/SVGAltGlyphElement.h
+++ b/Source/core/svg/SVGAltGlyphElement.h
@@ -35,7 +35,7 @@
 class SVGAltGlyphElement FINAL : public SVGTextPositioningElement,
                                  public SVGURIReference {
 public:
-    static PassRefPtr<SVGAltGlyphElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGAltGlyphElement> create(const QualifiedName&, Document&);
 
     const AtomicString& glyphRef() const;
     void setGlyphRef(const AtomicString&, ExceptionState&);
@@ -45,10 +45,10 @@
     bool hasValidGlyphElements(Vector<String>& glyphNames) const;
 
 private:
-    SVGAltGlyphElement(const QualifiedName&, Document*);
+    SVGAltGlyphElement(const QualifiedName&, Document&);
 
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
+    virtual bool childShouldCreateRenderer(const Node& child) const;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGAltGlyphElement)
         DECLARE_ANIMATED_STRING(Href, href)
diff --git a/Source/core/svg/SVGAltGlyphItemElement.cpp b/Source/core/svg/SVGAltGlyphItemElement.cpp
index c4867e6..347233b 100644
--- a/Source/core/svg/SVGAltGlyphItemElement.cpp
+++ b/Source/core/svg/SVGAltGlyphItemElement.cpp
@@ -27,14 +27,14 @@
 
 namespace WebCore {
 
-inline SVGAltGlyphItemElement::SVGAltGlyphItemElement(const QualifiedName& tagName, Document* document)
+inline SVGAltGlyphItemElement::SVGAltGlyphItemElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::altGlyphItemTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGAltGlyphItemElement> SVGAltGlyphItemElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGAltGlyphItemElement> SVGAltGlyphItemElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGAltGlyphItemElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGAltGlyphItemElement.h b/Source/core/svg/SVGAltGlyphItemElement.h
index 8d22813..18223d7 100644
--- a/Source/core/svg/SVGAltGlyphItemElement.h
+++ b/Source/core/svg/SVGAltGlyphItemElement.h
@@ -28,14 +28,14 @@
 
 class SVGAltGlyphItemElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGAltGlyphItemElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGAltGlyphItemElement> create(const QualifiedName&, Document&);
 
     bool hasValidGlyphElements(Vector<String>& glyphNames) const;
 
 private:
-    SVGAltGlyphItemElement(const QualifiedName&, Document*);
+    SVGAltGlyphItemElement(const QualifiedName&, Document&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 }
diff --git a/Source/core/svg/SVGAnimateColorElement.cpp b/Source/core/svg/SVGAnimateColorElement.cpp
index 0b97115..ce8d772 100644
--- a/Source/core/svg/SVGAnimateColorElement.cpp
+++ b/Source/core/svg/SVGAnimateColorElement.cpp
@@ -22,18 +22,21 @@
 #include "config.h"
 
 #include "SVGNames.h"
+#include "core/page/UseCounter.h"
 #include "core/svg/SVGAnimateColorElement.h"
 
 namespace WebCore {
 
-inline SVGAnimateColorElement::SVGAnimateColorElement(const QualifiedName& tagName, Document* document)
+inline SVGAnimateColorElement::SVGAnimateColorElement(const QualifiedName& tagName, Document& document)
     : SVGAnimateElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::animateColorTag));
     ScriptWrappable::init(this);
+
+    UseCounter::count(&document, UseCounter::SVGAnimateColorElement);
 }
 
-PassRefPtr<SVGAnimateColorElement> SVGAnimateColorElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGAnimateColorElement> SVGAnimateColorElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGAnimateColorElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGAnimateColorElement.h b/Source/core/svg/SVGAnimateColorElement.h
index d592047..160b1c6 100644
--- a/Source/core/svg/SVGAnimateColorElement.h
+++ b/Source/core/svg/SVGAnimateColorElement.h
@@ -28,10 +28,10 @@
 
 class SVGAnimateColorElement FINAL : public SVGAnimateElement {
 public:
-    static PassRefPtr<SVGAnimateColorElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGAnimateColorElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGAnimateColorElement(const QualifiedName&, Document*);
+    SVGAnimateColorElement(const QualifiedName&, Document&);
     virtual void determinePropertyValueTypes(const String& from, const String& to);
 };
 
diff --git a/Source/core/svg/SVGAnimateElement.cpp b/Source/core/svg/SVGAnimateElement.cpp
index e3af159..d3f1b23 100644
--- a/Source/core/svg/SVGAnimateElement.cpp
+++ b/Source/core/svg/SVGAnimateElement.cpp
@@ -35,7 +35,7 @@
 
 namespace WebCore {
 
-SVGAnimateElement::SVGAnimateElement(const QualifiedName& tagName, Document* document)
+SVGAnimateElement::SVGAnimateElement(const QualifiedName& tagName, Document& document)
     : SVGAnimationElement(tagName, document)
     , m_animatedPropertyType(AnimatedString)
 {
@@ -43,7 +43,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGAnimateElement> SVGAnimateElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGAnimateElement> SVGAnimateElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGAnimateElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGAnimateElement.h b/Source/core/svg/SVGAnimateElement.h
index f53a5bb..16ae80d 100644
--- a/Source/core/svg/SVGAnimateElement.h
+++ b/Source/core/svg/SVGAnimateElement.h
@@ -35,13 +35,13 @@
 
 class SVGAnimateElement : public SVGAnimationElement {
 public:
-    static PassRefPtr<SVGAnimateElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGAnimateElement> create(const QualifiedName&, Document&);
     virtual ~SVGAnimateElement();
 
     AnimatedPropertyType determineAnimatedPropertyType(SVGElement*) const;
 
 protected:
-    SVGAnimateElement(const QualifiedName&, Document*);
+    SVGAnimateElement(const QualifiedName&, Document&);
 
     virtual void resetAnimatedType();
     virtual void clearAnimatedType(SVGElement* targetElement);
diff --git a/Source/core/svg/SVGAnimateMotionElement.cpp b/Source/core/svg/SVGAnimateMotionElement.cpp
index f8a929b..faf7056 100644
--- a/Source/core/svg/SVGAnimateMotionElement.cpp
+++ b/Source/core/svg/SVGAnimateMotionElement.cpp
@@ -40,7 +40,7 @@
 
 using namespace SVGNames;
 
-inline SVGAnimateMotionElement::SVGAnimateMotionElement(const QualifiedName& tagName, Document* document)
+inline SVGAnimateMotionElement::SVGAnimateMotionElement(const QualifiedName& tagName, Document& document)
     : SVGAnimationElement(tagName, document)
     , m_hasToPointAtEndOfDuration(false)
 {
@@ -49,7 +49,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGAnimateMotionElement> SVGAnimateMotionElement::create(const QualifiedName& tagName, Document* document)
+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 3f7a579..79c8415 100644
--- a/Source/core/svg/SVGAnimateMotionElement.h
+++ b/Source/core/svg/SVGAnimateMotionElement.h
@@ -30,11 +30,11 @@
 
 class SVGAnimateMotionElement FINAL : public SVGAnimationElement {
 public:
-    static PassRefPtr<SVGAnimateMotionElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGAnimateMotionElement> create(const QualifiedName&, Document&);
     void updateAnimationPath();
 
 private:
-    SVGAnimateMotionElement(const QualifiedName&, Document*);
+    SVGAnimateMotionElement(const QualifiedName&, Document&);
 
     virtual bool hasValidAttributeType();
     virtual bool hasValidAttributeName();
diff --git a/Source/core/svg/SVGAnimateTransformElement.cpp b/Source/core/svg/SVGAnimateTransformElement.cpp
index 3f36f43..e6a1bd4 100644
--- a/Source/core/svg/SVGAnimateTransformElement.cpp
+++ b/Source/core/svg/SVGAnimateTransformElement.cpp
@@ -29,7 +29,7 @@
 
 namespace WebCore {
 
-inline SVGAnimateTransformElement::SVGAnimateTransformElement(const QualifiedName& tagName, Document* document)
+inline SVGAnimateTransformElement::SVGAnimateTransformElement(const QualifiedName& tagName, Document& document)
     : SVGAnimateElement(tagName, document)
     , m_type(SVGTransform::SVG_TRANSFORM_UNKNOWN)
 {
@@ -37,7 +37,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGAnimateTransformElement> SVGAnimateTransformElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGAnimateTransformElement> SVGAnimateTransformElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGAnimateTransformElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGAnimateTransformElement.h b/Source/core/svg/SVGAnimateTransformElement.h
index cb19200..21c80f2 100644
--- a/Source/core/svg/SVGAnimateTransformElement.h
+++ b/Source/core/svg/SVGAnimateTransformElement.h
@@ -32,12 +32,12 @@
 
 class SVGAnimateTransformElement FINAL : public SVGAnimateElement {
 public:
-    static PassRefPtr<SVGAnimateTransformElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGAnimateTransformElement> create(const QualifiedName&, Document&);
 
     SVGTransform::SVGTransformType transformType() const { return m_type; }
 
 private:
-    SVGAnimateTransformElement(const QualifiedName&, Document*);
+    SVGAnimateTransformElement(const QualifiedName&, Document&);
 
     virtual bool hasValidAttributeType();
 
diff --git a/Source/core/svg/SVGAnimatedColor.cpp b/Source/core/svg/SVGAnimatedColor.cpp
index 9f48b7f..ad478af 100644
--- a/Source/core/svg/SVGAnimatedColor.cpp
+++ b/Source/core/svg/SVGAnimatedColor.cpp
@@ -52,7 +52,7 @@
     ASSERT(targetElement);
 
     if (RenderObject* targetRenderer = targetElement->renderer())
-        color = targetRenderer->resolveColor(CSSPropertyColor);
+        color = targetRenderer->style()->visitedDependentColor(CSSPropertyColor);
     else
         color = Color();
 }
@@ -100,11 +100,11 @@
 float SVGAnimatedColorAnimator::calculateDistance(const String& fromString, const String& toString)
 {
     ASSERT(m_contextElement);
-    Color from;
-    if (!SVGColor::colorFromRGBColorString(fromString, from))
+    Color from = SVGColor::colorFromRGBColorString(fromString);
+    if (!from.isValid())
         return -1;
-    Color to;
-    if (!SVGColor::colorFromRGBColorString(toString, to))
+    Color to = SVGColor::colorFromRGBColorString(toString);
+    if (!to.isValid())
         return -1;
     return ColorDistance(from, to).distance();
 }
diff --git a/Source/core/svg/SVGAnimationElement.cpp b/Source/core/svg/SVGAnimationElement.cpp
index 9351da4..21873d7 100644
--- a/Source/core/svg/SVGAnimationElement.cpp
+++ b/Source/core/svg/SVGAnimationElement.cpp
@@ -47,7 +47,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGAnimationElement::SVGAnimationElement(const QualifiedName& tagName, Document* document)
+SVGAnimationElement::SVGAnimationElement(const QualifiedName& tagName, Document& document)
     : SVGSMILElement(tagName, document)
     , m_fromPropertyValueType(RegularPropertyValue)
     , m_toPropertyValueType(RegularPropertyValue)
@@ -60,7 +60,7 @@
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGAnimationElement();
 
-    UseCounter::count(document, UseCounter::SVGAnimationElement);
+    UseCounter::count(&document, UseCounter::SVGAnimationElement);
 }
 
 static void parseKeyTimes(const String& string, Vector<float>& result, bool verifyOrder)
diff --git a/Source/core/svg/SVGAnimationElement.h b/Source/core/svg/SVGAnimationElement.h
index a2d9ac4..11410e1 100644
--- a/Source/core/svg/SVGAnimationElement.h
+++ b/Source/core/svg/SVGAnimationElement.h
@@ -162,7 +162,7 @@
     }
 
 protected:
-    SVGAnimationElement(const QualifiedName&, Document*);
+    SVGAnimationElement(const QualifiedName&, Document&);
 
     void computeCSSPropertyValue(SVGElement*, CSSPropertyID, String& value);
     virtual void determinePropertyValueTypes(const String& from, const String& to);
diff --git a/Source/core/svg/SVGCircleElement.cpp b/Source/core/svg/SVGCircleElement.cpp
index 42cbb92..8852d8c 100644
--- a/Source/core/svg/SVGCircleElement.cpp
+++ b/Source/core/svg/SVGCircleElement.cpp
@@ -44,7 +44,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGCircleElement::SVGCircleElement(const QualifiedName& tagName, Document* document)
+inline SVGCircleElement::SVGCircleElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
     , m_cx(LengthModeWidth)
     , m_cy(LengthModeHeight)
@@ -55,7 +55,7 @@
     registerAnimatedPropertiesForSVGCircleElement();
 }
 
-PassRefPtr<SVGCircleElement> SVGCircleElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGCircleElement> SVGCircleElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGCircleElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGCircleElement.h b/Source/core/svg/SVGCircleElement.h
index 99dc642..ae702f6 100644
--- a/Source/core/svg/SVGCircleElement.h
+++ b/Source/core/svg/SVGCircleElement.h
@@ -32,10 +32,10 @@
 class SVGCircleElement FINAL : public SVGGraphicsElement,
                                public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGCircleElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGCircleElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGCircleElement(const QualifiedName&, Document*);
+    SVGCircleElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGClipPathElement.cpp b/Source/core/svg/SVGClipPathElement.cpp
index fffc54d..de8058f 100644
--- a/Source/core/svg/SVGClipPathElement.cpp
+++ b/Source/core/svg/SVGClipPathElement.cpp
@@ -39,7 +39,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGClipPathElement::SVGClipPathElement(const QualifiedName& tagName, Document* document)
+inline SVGClipPathElement::SVGClipPathElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
     , m_clipPathUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
 {
@@ -48,7 +48,7 @@
     registerAnimatedPropertiesForSVGClipPathElement();
 }
 
-PassRefPtr<SVGClipPathElement> SVGClipPathElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGClipPathElement> SVGClipPathElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGClipPathElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGClipPathElement.h b/Source/core/svg/SVGClipPathElement.h
index 5667aa7..80f6be9 100644
--- a/Source/core/svg/SVGClipPathElement.h
+++ b/Source/core/svg/SVGClipPathElement.h
@@ -35,10 +35,10 @@
 class SVGClipPathElement FINAL : public SVGGraphicsElement,
                                  public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGClipPathElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGClipPathElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGClipPathElement(const QualifiedName&, Document*);
+    SVGClipPathElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool needsPendingResourceHandling() const { return false; }
diff --git a/Source/core/svg/SVGColor.cpp b/Source/core/svg/SVGColor.cpp
index 933f44f..5253f89 100644
--- a/Source/core/svg/SVGColor.cpp
+++ b/Source/core/svg/SVGColor.cpp
@@ -31,14 +31,12 @@
 SVGColor::SVGColor(const SVGColorType& colorType)
     : CSSValue(SVGColorClass)
     , m_colorType(colorType)
-    , m_valid(false)
 {
 }
 
 SVGColor::SVGColor(ClassType classType, const SVGColorType& colorType)
     : CSSValue(classType)
     , m_colorType(colorType)
-    , m_valid(false)
 {
 }
 
@@ -47,15 +45,13 @@
     return RGBColor::create(m_color.rgb());
 }
 
-bool SVGColor::colorFromRGBColorString(const String& colorString, Color& color)
+Color SVGColor::colorFromRGBColorString(const String& colorString)
 {
     // FIXME: Rework css parser so it is more SVG aware.
-    RGBA32 rgba;
-    if (CSSParser::parseColor(rgba, colorString.stripWhiteSpace())) {
-        color = rgba;
-        return true;
-    }
-    return false;
+    RGBA32 color;
+    if (CSSParser::parseColor(color, colorString.stripWhiteSpace()))
+        return color;
+    return Color();
 }
 
 void SVGColor::setRGBColor(const String&, ExceptionState& es)
@@ -85,7 +81,7 @@
         // FIXME: No ICC color support.
         return m_color.serialized();
     case SVG_COLORTYPE_CURRENTCOLOR:
-        if (m_valid)
+        if (m_color.isValid())
             return m_color.serialized();
         return "currentColor";
     }
diff --git a/Source/core/svg/SVGColor.h b/Source/core/svg/SVGColor.h
index 0622a70..554fe77 100644
--- a/Source/core/svg/SVGColor.h
+++ b/Source/core/svg/SVGColor.h
@@ -43,7 +43,7 @@
     static PassRefPtr<SVGColor> createFromString(const String& rgbColor)
     {
         RefPtr<SVGColor> color = adoptRef(new SVGColor(SVG_COLORTYPE_RGBCOLOR));
-        color->m_valid = colorFromRGBColorString(rgbColor, color->m_color);
+        color->setColor(colorFromRGBColorString(rgbColor));
         return color.release();
     }
 
@@ -63,13 +63,7 @@
     const SVGColorType& colorType() const { return m_colorType; }
     PassRefPtr<RGBColor> rgbColor() const;
 
-    static bool colorFromRGBColorString(const String&, Color&);
-    static Color colorFromRGBColorString(const String& s)
-    {
-        Color color;
-        colorFromRGBColorString(s, color);
-        return color;
-    }
+    static Color colorFromRGBColorString(const String&);
 
     void setRGBColor(const String& rgbColor, ExceptionState&);
     void setRGBColorICCColor(const String& rgbColor, const String& iccColor, ExceptionState&);
@@ -89,7 +83,7 @@
     SVGColor(ClassType, const SVGColorType&);
     SVGColor(ClassType, const SVGColor& cloneFrom);
 
-    void setColor(const Color& color) { m_color = color; m_valid = true; }
+    void setColor(const Color& color) { m_color = color; }
     void setColorType(const SVGColorType& type) { m_colorType = type; }
 
 private:
@@ -97,7 +91,6 @@
 
     Color m_color;
     SVGColorType m_colorType;
-    bool m_valid;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGComponentTransferFunctionElement.cpp b/Source/core/svg/SVGComponentTransferFunctionElement.cpp
index d4449e2..2e8818d 100644
--- a/Source/core/svg/SVGComponentTransferFunctionElement.cpp
+++ b/Source/core/svg/SVGComponentTransferFunctionElement.cpp
@@ -49,7 +49,7 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(offset)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGComponentTransferFunctionElement::SVGComponentTransferFunctionElement(const QualifiedName& tagName, Document* document)
+SVGComponentTransferFunctionElement::SVGComponentTransferFunctionElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_type(FECOMPONENTTRANSFER_TYPE_IDENTITY)
     , m_slope(1)
diff --git a/Source/core/svg/SVGComponentTransferFunctionElement.h b/Source/core/svg/SVGComponentTransferFunctionElement.h
index 2ffaeb7..8a6bbd9 100644
--- a/Source/core/svg/SVGComponentTransferFunctionElement.h
+++ b/Source/core/svg/SVGComponentTransferFunctionElement.h
@@ -74,13 +74,13 @@
     ComponentTransferFunction transferFunction() const;
 
 protected:
-    SVGComponentTransferFunctionElement(const QualifiedName&, Document*);
+    SVGComponentTransferFunctionElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
 private:
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGComponentTransferFunctionElement)
diff --git a/Source/core/svg/SVGCursorElement.cpp b/Source/core/svg/SVGCursorElement.cpp
index a016614..f83ffa9 100644
--- a/Source/core/svg/SVGCursorElement.cpp
+++ b/Source/core/svg/SVGCursorElement.cpp
@@ -43,7 +43,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGCursorElement::SVGCursorElement(const QualifiedName& tagName, Document* document)
+inline SVGCursorElement::SVGCursorElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
@@ -53,7 +53,7 @@
     registerAnimatedPropertiesForSVGCursorElement();
 }
 
-PassRefPtr<SVGCursorElement> SVGCursorElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGCursorElement> SVGCursorElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGCursorElement(tagName, document));
 }
@@ -138,7 +138,7 @@
 {
     SVGElement::addSubresourceAttributeURLs(urls);
 
-    addSubresourceURL(urls, document()->completeURL(hrefCurrentValue()));
+    addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
 }
 
 }
diff --git a/Source/core/svg/SVGCursorElement.h b/Source/core/svg/SVGCursorElement.h
index 825b940..eb93d4a 100644
--- a/Source/core/svg/SVGCursorElement.h
+++ b/Source/core/svg/SVGCursorElement.h
@@ -36,7 +36,7 @@
                                public SVGExternalResourcesRequired,
                                public SVGURIReference {
 public:
-    static PassRefPtr<SVGCursorElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGCursorElement> create(const QualifiedName&, Document&);
 
     virtual ~SVGCursorElement();
 
@@ -45,7 +45,7 @@
     void removeReferencedElement(SVGElement*);
 
 private:
-    SVGCursorElement(const QualifiedName&, Document*);
+    SVGCursorElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
 
@@ -55,7 +55,7 @@
 
     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGCursorElement)
         DECLARE_ANIMATED_LENGTH(X, x)
diff --git a/Source/core/svg/SVGDefsElement.cpp b/Source/core/svg/SVGDefsElement.cpp
index 222a28c..4b2d39b 100644
--- a/Source/core/svg/SVGDefsElement.cpp
+++ b/Source/core/svg/SVGDefsElement.cpp
@@ -35,7 +35,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGDefsElement::SVGDefsElement(const QualifiedName& tagName, Document* document)
+inline SVGDefsElement::SVGDefsElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::defsTag));
@@ -43,7 +43,7 @@
     registerAnimatedPropertiesForSVGDefsElement();
 }
 
-PassRefPtr<SVGDefsElement> SVGDefsElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGDefsElement> SVGDefsElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGDefsElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGDefsElement.h b/Source/core/svg/SVGDefsElement.h
index 0b60150..b29d526 100644
--- a/Source/core/svg/SVGDefsElement.h
+++ b/Source/core/svg/SVGDefsElement.h
@@ -30,10 +30,10 @@
 class SVGDefsElement FINAL : public SVGGraphicsElement,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGDefsElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGDefsElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGDefsElement(const QualifiedName&, Document*);
+    SVGDefsElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const;
 
diff --git a/Source/core/svg/SVGDescElement.cpp b/Source/core/svg/SVGDescElement.cpp
index 6da4709..219beda 100644
--- a/Source/core/svg/SVGDescElement.cpp
+++ b/Source/core/svg/SVGDescElement.cpp
@@ -24,14 +24,14 @@
 
 namespace WebCore {
 
-inline SVGDescElement::SVGDescElement(const QualifiedName& tagName, Document* document)
+inline SVGDescElement::SVGDescElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::descTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGDescElement> SVGDescElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGDescElement> SVGDescElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGDescElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGDescElement.h b/Source/core/svg/SVGDescElement.h
index e22fcd7..2c8cfa6 100644
--- a/Source/core/svg/SVGDescElement.h
+++ b/Source/core/svg/SVGDescElement.h
@@ -27,14 +27,14 @@
 
 class SVGDescElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGDescElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGDescElement> create(const QualifiedName&, Document&);
 
     String description() const;
 
 private:
-    SVGDescElement(const QualifiedName&, Document*);
+    SVGDescElement(const QualifiedName&, Document&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGDocument.cpp b/Source/core/svg/SVGDocument.cpp
index ddab3c4..c82b6e7 100644
--- a/Source/core/svg/SVGDocument.cpp
+++ b/Source/core/svg/SVGDocument.cpp
@@ -24,7 +24,6 @@
 #include "SVGNames.h"
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/EventNames.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/page/FrameView.h"
 #include "core/rendering/RenderView.h"
 #include "core/svg/SVGElement.h"
@@ -68,12 +67,13 @@
 
 bool SVGDocument::zoomAndPanEnabled() const
 {
-    if (rootElement()) {
-        if (rootElement()->useCurrentView()) {
-            if (rootElement()->currentView())
-                return rootElement()->currentView()->zoomAndPan() == SVGZoomAndPanMagnify;
-        } else
-            return rootElement()->zoomAndPan() == SVGZoomAndPanMagnify;
+    if (SVGSVGElement* svg = rootElement()) {
+        if (svg->useCurrentView()) {
+            if (svg->currentView())
+                return svg->currentView()->zoomAndPan() == SVGZoomAndPanMagnify;
+        } else {
+            return svg->zoomAndPan() == SVGZoomAndPanMagnify;
+        }
     }
 
     return false;
@@ -81,23 +81,23 @@
 
 void SVGDocument::startPan(const FloatPoint& start)
 {
-    if (rootElement())
-        m_translate = FloatPoint(start.x() - rootElement()->currentTranslate().x(), start.y() - rootElement()->currentTranslate().y());
+    if (SVGSVGElement* svg = rootElement())
+        m_translate = FloatPoint(start.x() - svg->currentTranslate().x(), start.y() - svg->currentTranslate().y());
 }
 
 void SVGDocument::updatePan(const FloatPoint& pos) const
 {
-    if (rootElement()) {
-        rootElement()->setCurrentTranslate(FloatPoint(pos.x() - m_translate.x(), pos.y() - m_translate.y()));
+    if (SVGSVGElement* svg = rootElement()) {
+        svg->setCurrentTranslate(FloatPoint(pos.x() - m_translate.x(), pos.y() - m_translate.y()));
         if (renderer())
             renderer()->repaint();
     }
 }
 
-bool SVGDocument::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGDocument::childShouldCreateRenderer(const Node& child) const
 {
-    if (childContext.node()->hasTagName(SVGNames::svgTag))
-        return toSVGSVGElement(childContext.node())->isValid();
+    if (child.hasTagName(SVGNames::svgTag))
+        return toSVGSVGElement(&child)->isValid();
     return true;
 }
 
diff --git a/Source/core/svg/SVGDocument.h b/Source/core/svg/SVGDocument.h
index 273db02..bddf66f 100644
--- a/Source/core/svg/SVGDocument.h
+++ b/Source/core/svg/SVGDocument.h
@@ -26,8 +26,6 @@
 
 namespace WebCore {
 
-class DOMImplementation;
-class SVGElement;
 class SVGSVGElement;
 
 class SVGDocument FINAL : public Document {
@@ -48,9 +46,9 @@
     void updatePan(const FloatPoint& pos) const;
 
 private:
-    SVGDocument(const DocumentInit&);
+    explicit SVGDocument(const DocumentInit&);
 
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
+    virtual bool childShouldCreateRenderer(const Node& child) const;
 
     FloatPoint m_translate;
 };
diff --git a/Source/core/svg/SVGElement.cpp b/Source/core/svg/SVGElement.cpp
index 0e63172..9524f05 100644
--- a/Source/core/svg/SVGElement.cpp
+++ b/Source/core/svg/SVGElement.cpp
@@ -36,7 +36,6 @@
 #include "core/dom/Document.h"
 #include "core/dom/ElementTraversal.h"
 #include "core/dom/Event.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/svg/RenderSVGResourceContainer.h"
@@ -70,25 +69,19 @@
     propertyNameToIdMap->set(attrName.localName().impl(), propertyId);
 }
 
-SVGElement::SVGElement(const QualifiedName& tagName, Document* document, ConstructionType constructionType)
-    : Element(tagName, document, constructionType)
+SVGElement::SVGElement(const QualifiedName& tagName, Document& document, ConstructionType constructionType)
+    : Element(tagName, &document, constructionType)
 {
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGElement();
     setHasCustomStyleCallbacks();
 }
 
-PassRefPtr<SVGElement> SVGElement::create(const QualifiedName& tagName, Document* document)
-{
-    return adoptRef(new SVGElement(tagName, document));
-}
-
 SVGElement::~SVGElement()
 {
     if (!hasSVGRareData())
         ASSERT(!SVGElementRareData::rareDataMap().contains(this));
     else {
-        ASSERT(document());
         SVGElementRareData::SVGElementRareDataMap& rareDataMap = SVGElementRareData::rareDataMap();
         SVGElementRareData::SVGElementRareDataMap::iterator it = rareDataMap.find(this);
         ASSERT(it != rareDataMap.end());
@@ -111,12 +104,11 @@
         // removeAllElementReferencesForTarget() below.
         clearHasSVGRareData();
     }
-    ASSERT(document());
-    document()->accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
-    document()->accessSVGExtensions()->removeAllElementReferencesForTarget(this);
+    document().accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
+    document().accessSVGExtensions()->removeAllElementReferencesForTarget(this);
 }
 
-void SVGElement::willRecalcStyle(StyleChange change)
+void SVGElement::willRecalcStyle(StyleRecalcChange change)
 {
     // FIXME: This assumes that when shouldNotifyRendererWithIdenticalStyles() is true
     // the change came from a SMIL animation, but what if there were non-SMIL changes
@@ -132,11 +124,11 @@
 
 void SVGElement::buildPendingResourcesIfNeeded()
 {
-    Document* document = this->document();
-    if (!needsPendingResourceHandling() || !document || !inDocument() || isInShadowTree())
+    Document& document = this->document();
+    if (!needsPendingResourceHandling() || !inDocument() || isInShadowTree())
         return;
 
-    SVGDocumentExtensions* extensions = document->accessSVGExtensions();
+    SVGDocumentExtensions* extensions = document.accessSVGExtensions();
     String resourceId = getIdAttribute();
     if (!extensions->hasPendingResource(resourceId))
         return;
@@ -154,7 +146,7 @@
     }
 }
 
-bool SVGElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool SVGElement::rendererIsNeeded(const RenderStyle& style)
 {
     // http://www.w3.org/TR/SVG/extend.html#PrivateData
     // Prevent anything other than SVG renderers from appearing in our render tree
@@ -162,7 +154,7 @@
     // with the SVG content. In general, the SVG user agent will include the unknown
     // elements in the DOM but will otherwise ignore unknown elements.
     if (!parentOrShadowHostElement() || parentOrShadowHostElement()->isSVGElement())
-        return Element::rendererIsNeeded(context);
+        return Element::rendererIsNeeded(style);
 
     return false;
 }
@@ -214,7 +206,7 @@
         return;
 
     String errorString = "<" + tagName() + "> attribute " + name.toString() + "=\"" + value + "\"";
-    SVGDocumentExtensions* extensions = document()->accessSVGExtensions();
+    SVGDocumentExtensions* extensions = document().accessSVGExtensions();
 
     if (error == NegativeValueForbiddenError) {
         extensions->reportError("Invalid negative value for " + errorString);
@@ -244,7 +236,7 @@
 
     // Walk up the tree, to find out whether we're inside a <use> shadow tree, to find the right title.
     if (isInShadowTree()) {
-        Element* shadowHostElement = toShadowRoot(treeScope()->rootNode())->host();
+        Element* shadowHostElement = toShadowRoot(treeScope().rootNode())->host();
         // At this time, SVG nodes are not allowed in non-<use> shadow trees, so any shadow root we do
         // have should be a use. The assert and following test is here to catch future shadow DOM changes
         // that do enable SVG in a shadow tree.
@@ -342,8 +334,8 @@
     Element::removedFrom(rootParent);
 
     if (wasInDocument) {
-        document()->accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
-        document()->accessSVGExtensions()->removeAllElementReferencesForTarget(this);
+        document().accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
+        document().accessSVGExtensions()->removeAllElementReferencesForTarget(this);
     }
 
     SVGElementInstance::invalidateAllInstancesOfElement(this);
@@ -501,7 +493,7 @@
 {
     // This function is provided for use by SVGAnimatedProperty to avoid
     // global inclusion of core/dom/Document.h in SVG code.
-    return document() ? document()->accessSVGExtensions() : 0;
+    return document().accessSVGExtensions();
 }
 
 void SVGElement::mapInstanceToElement(SVGElementInstance* instance)
@@ -858,7 +850,7 @@
         // If the load event was not sent yet by Document::implicitClose(), but the <image> from the example
         // above, just appeared, don't send the SVGLoad event to the outermost <svg>, but wait for the document
         // to be "ready to render", first.
-        if (!document()->loadEventFinished())
+        if (!document().loadEventFinished())
             break;
     }
 }
@@ -892,7 +884,7 @@
     sendSVGLoadEventIfPossible();
 }
 
-bool SVGElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGElement::childShouldCreateRenderer(const Node& child) const
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, invalidTextContent, ());
 
@@ -901,11 +893,10 @@
 #if ENABLE(SVG_FONTS)
         invalidTextContent.add(SVGNames::altGlyphTag);
 #endif
-        invalidTextContent.add(SVGNames::trefTag);
         invalidTextContent.add(SVGNames::tspanTag);
     }
-    if (childContext.node()->isSVGElement()) {
-        SVGElement* svgChild = toSVGElement(childContext.node());
+    if (child.isSVGElement()) {
+        const SVGElement* svgChild = toSVGElement(&child);
         if (invalidTextContent.contains(svgChild->tagQName()))
             return false;
 
@@ -919,7 +910,7 @@
     Element::attributeChanged(name, newValue);
 
     if (isIdAttributeName(name))
-        document()->accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
+        document().accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
 
     // Changes to the style attribute are processed lazily (see Element::getAttribute() and related methods),
     // so we don't want changes to the style attribute to result in extra work here.
@@ -987,7 +978,7 @@
 PassRefPtr<RenderStyle> SVGElement::customStyleForRenderer()
 {
     if (!correspondingElement())
-        return document()->styleResolver()->styleForElement(this);
+        return document().styleResolver()->styleForElement(this);
 
     RenderStyle* style = 0;
     if (Element* parent = parentOrShadowHostElement()) {
@@ -995,7 +986,7 @@
             style = renderer->style();
     }
 
-    return document()->styleResolver()->styleForElement(correspondingElement(), style, DisallowStyleSharing);
+    return document().styleResolver()->styleForElement(correspondingElement(), style, DisallowStyleSharing);
 }
 
 MutableStylePropertySet* SVGElement::animatedSMILStyleProperties() const
diff --git a/Source/core/svg/SVGElement.h b/Source/core/svg/SVGElement.h
index e493ab2..1f22c61 100644
--- a/Source/core/svg/SVGElement.h
+++ b/Source/core/svg/SVGElement.h
@@ -48,7 +48,6 @@
 
 class SVGElement : public Element, public SVGLangSpace {
 public:
-    static PassRefPtr<SVGElement> create(const QualifiedName&, Document*);
     virtual ~SVGElement();
 
     bool isOutermostSVGSVGElement() const;
@@ -135,17 +134,17 @@
     virtual bool shouldMoveToFlowThread(RenderStyle*) const OVERRIDE;
 
 protected:
-    SVGElement(const QualifiedName&, Document*, ConstructionType = CreateSVGElement);
+    SVGElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
     virtual void finishParsingChildren();
     virtual void attributeChanged(const QualifiedName&, const AtomicString&, AttributeModificationReason = ModifiedDirectly) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
+    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
 
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -172,7 +171,7 @@
 
     RenderStyle* computedStyle(PseudoId = NOPSEUDO);
     virtual RenderStyle* virtualComputedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) { return computedStyle(pseudoElementSpecifier); }
-    virtual void willRecalcStyle(StyleChange) OVERRIDE;
+    virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
     virtual bool isKeyboardFocusable() const OVERRIDE;
 
     void buildPendingResourcesIfNeeded();
diff --git a/Source/core/svg/SVGElementInstance.cpp b/Source/core/svg/SVGElementInstance.cpp
index 26e57cc..e93740c 100644
--- a/Source/core/svg/SVGElementInstance.cpp
+++ b/Source/core/svg/SVGElementInstance.cpp
@@ -195,7 +195,7 @@
         }
     }
 
-    element->document()->updateStyleIfNeeded();
+    element->document().updateStyleIfNeeded();
 }
 
 const AtomicString& SVGElementInstance::interfaceName() const
@@ -205,7 +205,7 @@
 
 ScriptExecutionContext* SVGElementInstance::scriptExecutionContext() const
 {
-    return m_element->document();
+    return &m_element->document();
 }
 
 bool SVGElementInstance::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
diff --git a/Source/core/svg/SVGElementRareData.h b/Source/core/svg/SVGElementRareData.h
index 262000a..6f3b38d 100644
--- a/Source/core/svg/SVGElementRareData.h
+++ b/Source/core/svg/SVGElementRareData.h
@@ -90,11 +90,11 @@
     RenderStyle* overrideComputedStyle(Element* element, RenderStyle* parentStyle)
     {
         ASSERT(element);
-        if (!element->document() || !m_useOverrideComputedStyle)
+        if (!m_useOverrideComputedStyle)
             return 0;
         if (!m_overrideComputedStyle || m_needsOverrideComputedStyleUpdate) {
             // The style computed here contains no CSS Animations/Transitions or SMIL induced rules - this is needed to compute the "base value" for the SMIL animation sandwhich model.
-            m_overrideComputedStyle = element->document()->styleResolver()->styleForElement(element, parentStyle, DisallowStyleSharing, MatchAllRulesExcludingSMIL);
+            m_overrideComputedStyle = element->document().styleResolver()->styleForElement(element, parentStyle, DisallowStyleSharing, MatchAllRulesExcludingSMIL);
             m_needsOverrideComputedStyleUpdate = false;
         }
         ASSERT(m_overrideComputedStyle);
diff --git a/Source/core/svg/SVGEllipseElement.cpp b/Source/core/svg/SVGEllipseElement.cpp
index eef94a2..8002b06 100644
--- a/Source/core/svg/SVGEllipseElement.cpp
+++ b/Source/core/svg/SVGEllipseElement.cpp
@@ -46,7 +46,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGEllipseElement::SVGEllipseElement(const QualifiedName& tagName, Document* document)
+inline SVGEllipseElement::SVGEllipseElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
     , m_cx(LengthModeWidth)
     , m_cy(LengthModeHeight)
@@ -58,7 +58,7 @@
     registerAnimatedPropertiesForSVGEllipseElement();
 }
 
-PassRefPtr<SVGEllipseElement> SVGEllipseElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGEllipseElement> SVGEllipseElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGEllipseElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGEllipseElement.h b/Source/core/svg/SVGEllipseElement.h
index 8d98e10..dcfc5ec 100644
--- a/Source/core/svg/SVGEllipseElement.h
+++ b/Source/core/svg/SVGEllipseElement.h
@@ -32,10 +32,10 @@
 class SVGEllipseElement FINAL : public SVGGraphicsElement,
                                 public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGEllipseElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGEllipseElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGEllipseElement(const QualifiedName&, Document*);
+    SVGEllipseElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGFEBlendElement.cpp b/Source/core/svg/SVGFEBlendElement.cpp
index d943e05..1719515 100644
--- a/Source/core/svg/SVGFEBlendElement.cpp
+++ b/Source/core/svg/SVGFEBlendElement.cpp
@@ -41,7 +41,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEBlendElement::SVGFEBlendElement(const QualifiedName& tagName, Document* document)
+inline SVGFEBlendElement::SVGFEBlendElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_mode(FEBLEND_MODE_NORMAL)
 {
@@ -50,7 +50,7 @@
     registerAnimatedPropertiesForSVGFEBlendElement();
 }
 
-PassRefPtr<SVGFEBlendElement> SVGFEBlendElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEBlendElement> SVGFEBlendElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEBlendElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEBlendElement.h b/Source/core/svg/SVGFEBlendElement.h
index 0c54b06..af78dd9 100644
--- a/Source/core/svg/SVGFEBlendElement.h
+++ b/Source/core/svg/SVGFEBlendElement.h
@@ -70,10 +70,10 @@
 
 class SVGFEBlendElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEBlendElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEBlendElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEBlendElement(const QualifiedName&, Document*);
+    SVGFEBlendElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEColorMatrixElement.cpp b/Source/core/svg/SVGFEColorMatrixElement.cpp
index ec17b18..1ecb088 100644
--- a/Source/core/svg/SVGFEColorMatrixElement.cpp
+++ b/Source/core/svg/SVGFEColorMatrixElement.cpp
@@ -41,7 +41,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEColorMatrixElement::SVGFEColorMatrixElement(const QualifiedName& tagName, Document* document)
+inline SVGFEColorMatrixElement::SVGFEColorMatrixElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_type(FECOLORMATRIX_TYPE_MATRIX)
 {
@@ -50,7 +50,7 @@
     registerAnimatedPropertiesForSVGFEColorMatrixElement();
 }
 
-PassRefPtr<SVGFEColorMatrixElement> SVGFEColorMatrixElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEColorMatrixElement> SVGFEColorMatrixElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEColorMatrixElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEColorMatrixElement.h b/Source/core/svg/SVGFEColorMatrixElement.h
index 095e514..acd3616 100644
--- a/Source/core/svg/SVGFEColorMatrixElement.h
+++ b/Source/core/svg/SVGFEColorMatrixElement.h
@@ -67,10 +67,10 @@
 
 class SVGFEColorMatrixElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEColorMatrixElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEColorMatrixElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEColorMatrixElement(const QualifiedName&, Document*);
+    SVGFEColorMatrixElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEComponentTransferElement.cpp b/Source/core/svg/SVGFEComponentTransferElement.cpp
index 90408fe..96cfa14 100644
--- a/Source/core/svg/SVGFEComponentTransferElement.cpp
+++ b/Source/core/svg/SVGFEComponentTransferElement.cpp
@@ -40,7 +40,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEComponentTransferElement::SVGFEComponentTransferElement(const QualifiedName& tagName, Document* document)
+inline SVGFEComponentTransferElement::SVGFEComponentTransferElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feComponentTransferTag));
@@ -48,7 +48,7 @@
     registerAnimatedPropertiesForSVGFEComponentTransferElement();
 }
 
-PassRefPtr<SVGFEComponentTransferElement> SVGFEComponentTransferElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEComponentTransferElement> SVGFEComponentTransferElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEComponentTransferElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEComponentTransferElement.h b/Source/core/svg/SVGFEComponentTransferElement.h
index cfd6fac..f9d212b 100644
--- a/Source/core/svg/SVGFEComponentTransferElement.h
+++ b/Source/core/svg/SVGFEComponentTransferElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEComponentTransferElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEComponentTransferElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEComponentTransferElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEComponentTransferElement(const QualifiedName&, Document*);
+    SVGFEComponentTransferElement(const QualifiedName&, Document&);
 
     // FIXME: svgAttributeChanged missing.
     bool isSupportedAttribute(const QualifiedName&);
diff --git a/Source/core/svg/SVGFECompositeElement.cpp b/Source/core/svg/SVGFECompositeElement.cpp
index 1af2fc9..343ca10 100644
--- a/Source/core/svg/SVGFECompositeElement.cpp
+++ b/Source/core/svg/SVGFECompositeElement.cpp
@@ -49,7 +49,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFECompositeElement::SVGFECompositeElement(const QualifiedName& tagName, Document* document)
+inline SVGFECompositeElement::SVGFECompositeElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_svgOperator(FECOMPOSITE_OPERATOR_OVER)
 {
@@ -58,7 +58,7 @@
     registerAnimatedPropertiesForSVGFECompositeElement();
 }
 
-PassRefPtr<SVGFECompositeElement> SVGFECompositeElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFECompositeElement> SVGFECompositeElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFECompositeElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFECompositeElement.h b/Source/core/svg/SVGFECompositeElement.h
index 6a760f1..7b7b943 100644
--- a/Source/core/svg/SVGFECompositeElement.h
+++ b/Source/core/svg/SVGFECompositeElement.h
@@ -75,10 +75,10 @@
 
 class SVGFECompositeElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFECompositeElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFECompositeElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFECompositeElement(const QualifiedName&, Document*);
+    SVGFECompositeElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEConvolveMatrixElement.cpp b/Source/core/svg/SVGFEConvolveMatrixElement.cpp
index 59cb12f..9453bf7 100644
--- a/Source/core/svg/SVGFEConvolveMatrixElement.cpp
+++ b/Source/core/svg/SVGFEConvolveMatrixElement.cpp
@@ -62,7 +62,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEConvolveMatrixElement::SVGFEConvolveMatrixElement(const QualifiedName& tagName, Document* document)
+inline SVGFEConvolveMatrixElement::SVGFEConvolveMatrixElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_edgeMode(EDGEMODE_DUPLICATE)
 {
@@ -71,7 +71,7 @@
     registerAnimatedPropertiesForSVGFEConvolveMatrixElement();
 }
 
-PassRefPtr<SVGFEConvolveMatrixElement> SVGFEConvolveMatrixElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEConvolveMatrixElement> SVGFEConvolveMatrixElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEConvolveMatrixElement(tagName, document));
 }
@@ -135,10 +135,11 @@
         if (parseNumberOptionalNumber(value, x, y) && x >= 1 && y >= 1) {
             setOrderXBaseValue(x);
             setOrderYBaseValue(y);
-        } else
-            document()->accessSVGExtensions()->reportWarning(
+        } else {
+            document().accessSVGExtensions()->reportWarning(
                 "feConvolveMatrix: problem parsing order=\"" + value
                 + "\". Filtered element will not be displayed.");
+        }
         return;
     }
 
@@ -147,7 +148,7 @@
         if (propertyValue > 0)
             setEdgeModeBaseValue(propertyValue);
         else
-            document()->accessSVGExtensions()->reportWarning(
+            document().accessSVGExtensions()->reportWarning(
                 "feConvolveMatrix: problem parsing edgeMode=\"" + value
                 + "\". Filtered element will not be displayed.");
         return;
@@ -166,7 +167,7 @@
         if (divisor)
             setDivisorBaseValue(divisor);
         else
-            document()->accessSVGExtensions()->reportWarning(
+            document().accessSVGExtensions()->reportWarning(
                 "feConvolveMatrix: problem parsing divisor=\"" + value
                 + "\". Filtered element will not be displayed.");
         return;
@@ -192,10 +193,11 @@
         if (parseNumberOptionalNumber(value, x, y) && x > 0 && y > 0) {
             setKernelUnitLengthXBaseValue(x);
             setKernelUnitLengthYBaseValue(y);
-        } else
-            document()->accessSVGExtensions()->reportWarning(
+        } else {
+            document().accessSVGExtensions()->reportWarning(
                 "feConvolveMatrix: problem parsing kernelUnitLength=\"" + value
                 + "\". Filtered element will not be displayed.");
+        }
         return;
     }
 
@@ -205,7 +207,7 @@
         else if (value == "false")
             setPreserveAlphaBaseValue(false);
         else
-            document()->accessSVGExtensions()->reportWarning(
+            document().accessSVGExtensions()->reportWarning(
                 "feConvolveMatrix: problem parsing preserveAlphaAttr=\"" + value
                 + "\". Filtered element will not be displayed.");
         return;
diff --git a/Source/core/svg/SVGFEConvolveMatrixElement.h b/Source/core/svg/SVGFEConvolveMatrixElement.h
index 886acfb..f1faec5 100644
--- a/Source/core/svg/SVGFEConvolveMatrixElement.h
+++ b/Source/core/svg/SVGFEConvolveMatrixElement.h
@@ -65,13 +65,13 @@
 
 class SVGFEConvolveMatrixElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEConvolveMatrixElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEConvolveMatrixElement> create(const QualifiedName&, Document&);
 
     void setOrder(float orderX, float orderY);
     void setKernelUnitLength(float kernelUnitLengthX, float kernelUnitLengthY);
 
 private:
-    SVGFEConvolveMatrixElement(const QualifiedName&, Document*);
+    SVGFEConvolveMatrixElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEDiffuseLightingElement.cpp b/Source/core/svg/SVGFEDiffuseLightingElement.cpp
index 0166cab..7f14645 100644
--- a/Source/core/svg/SVGFEDiffuseLightingElement.cpp
+++ b/Source/core/svg/SVGFEDiffuseLightingElement.cpp
@@ -48,7 +48,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(const QualifiedName& tagName, Document* document)
+inline SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_diffuseConstant(1)
     , m_surfaceScale(1)
@@ -58,7 +58,7 @@
     registerAnimatedPropertiesForSVGFEDiffuseLightingElement();
 }
 
-PassRefPtr<SVGFEDiffuseLightingElement> SVGFEDiffuseLightingElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEDiffuseLightingElement> SVGFEDiffuseLightingElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEDiffuseLightingElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEDiffuseLightingElement.h b/Source/core/svg/SVGFEDiffuseLightingElement.h
index 9f43877..efd8e3f 100644
--- a/Source/core/svg/SVGFEDiffuseLightingElement.h
+++ b/Source/core/svg/SVGFEDiffuseLightingElement.h
@@ -22,6 +22,7 @@
 #ifndef SVGFEDiffuseLightingElement_h
 #define SVGFEDiffuseLightingElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGFELightElement.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
 
@@ -32,11 +33,11 @@
 
 class SVGFEDiffuseLightingElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEDiffuseLightingElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEDiffuseLightingElement> create(const QualifiedName&, Document&);
     void lightElementAttributeChanged(const SVGFELightElement*, const QualifiedName&);
 
 private:
-    SVGFEDiffuseLightingElement(const QualifiedName&, Document*);
+    SVGFEDiffuseLightingElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -56,6 +57,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGFEDiffuseLightingElement* toSVGFEDiffuseLightingElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feDiffuseLightingTag));
+    return static_cast<SVGFEDiffuseLightingElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFEDisplacementMapElement.cpp b/Source/core/svg/SVGFEDisplacementMapElement.cpp
index c6b51e9..61fc8a9 100644
--- a/Source/core/svg/SVGFEDisplacementMapElement.cpp
+++ b/Source/core/svg/SVGFEDisplacementMapElement.cpp
@@ -44,7 +44,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(const QualifiedName& tagName, Document* document)
+inline SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_xChannelSelector(CHANNEL_A)
     , m_yChannelSelector(CHANNEL_A)
@@ -54,7 +54,7 @@
     registerAnimatedPropertiesForSVGFEDisplacementMapElement();
 }
 
-PassRefPtr<SVGFEDisplacementMapElement> SVGFEDisplacementMapElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEDisplacementMapElement> SVGFEDisplacementMapElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEDisplacementMapElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEDisplacementMapElement.h b/Source/core/svg/SVGFEDisplacementMapElement.h
index ad03ccb..0aa95c1 100644
--- a/Source/core/svg/SVGFEDisplacementMapElement.h
+++ b/Source/core/svg/SVGFEDisplacementMapElement.h
@@ -66,12 +66,12 @@
 
 class SVGFEDisplacementMapElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEDisplacementMapElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEDisplacementMapElement> create(const QualifiedName&, Document&);
 
     static ChannelSelectorType stringToChannel(const String&);
 
 private:
-    SVGFEDisplacementMapElement(const QualifiedName& tagName, Document*);
+    SVGFEDisplacementMapElement(const QualifiedName& tagName, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEDistantLightElement.cpp b/Source/core/svg/SVGFEDistantLightElement.cpp
index 9a93c7c..d453563 100644
--- a/Source/core/svg/SVGFEDistantLightElement.cpp
+++ b/Source/core/svg/SVGFEDistantLightElement.cpp
@@ -26,14 +26,14 @@
 
 namespace WebCore {
 
-inline SVGFEDistantLightElement::SVGFEDistantLightElement(const QualifiedName& tagName, Document* document)
+inline SVGFEDistantLightElement::SVGFEDistantLightElement(const QualifiedName& tagName, Document& document)
     : SVGFELightElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feDistantLightTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEDistantLightElement> SVGFEDistantLightElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEDistantLightElement> SVGFEDistantLightElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEDistantLightElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEDistantLightElement.h b/Source/core/svg/SVGFEDistantLightElement.h
index 8fc105f..df1b9c2 100644
--- a/Source/core/svg/SVGFEDistantLightElement.h
+++ b/Source/core/svg/SVGFEDistantLightElement.h
@@ -26,10 +26,10 @@
 
 class SVGFEDistantLightElement FINAL : public SVGFELightElement {
 public:
-    static PassRefPtr<SVGFEDistantLightElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEDistantLightElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEDistantLightElement(const QualifiedName&, Document*);
+    SVGFEDistantLightElement(const QualifiedName&, Document&);
 
     virtual PassRefPtr<LightSource> lightSource() const;
 };
diff --git a/Source/core/svg/SVGFEDropShadowElement.cpp b/Source/core/svg/SVGFEDropShadowElement.cpp
index 946ffce..d5a5d29 100644
--- a/Source/core/svg/SVGFEDropShadowElement.cpp
+++ b/Source/core/svg/SVGFEDropShadowElement.cpp
@@ -46,7 +46,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEDropShadowElement::SVGFEDropShadowElement(const QualifiedName& tagName, Document* document)
+inline SVGFEDropShadowElement::SVGFEDropShadowElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_dx(2)
     , m_dy(2)
@@ -58,7 +58,7 @@
     registerAnimatedPropertiesForSVGFEDropShadowElement();
 }
 
-PassRefPtr<SVGFEDropShadowElement> SVGFEDropShadowElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEDropShadowElement> SVGFEDropShadowElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEDropShadowElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEDropShadowElement.h b/Source/core/svg/SVGFEDropShadowElement.h
index 75e7add..352f602 100644
--- a/Source/core/svg/SVGFEDropShadowElement.h
+++ b/Source/core/svg/SVGFEDropShadowElement.h
@@ -28,12 +28,12 @@
 
 class SVGFEDropShadowElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEDropShadowElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEDropShadowElement> create(const QualifiedName&, Document&);
 
     void setStdDeviation(float stdDeviationX, float stdDeviationY);
 
 private:
-    SVGFEDropShadowElement(const QualifiedName&, Document*);
+    SVGFEDropShadowElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEFloodElement.cpp b/Source/core/svg/SVGFEFloodElement.cpp
index f8cac52..33d3aa3 100644
--- a/Source/core/svg/SVGFEFloodElement.cpp
+++ b/Source/core/svg/SVGFEFloodElement.cpp
@@ -28,14 +28,14 @@
 
 namespace WebCore {
 
-inline SVGFEFloodElement::SVGFEFloodElement(const QualifiedName& tagName, Document* document)
+inline SVGFEFloodElement::SVGFEFloodElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feFloodTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFloodElement> SVGFEFloodElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEFloodElement> SVGFEFloodElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEFloodElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEFloodElement.h b/Source/core/svg/SVGFEFloodElement.h
index 2deab5f..378533e 100644
--- a/Source/core/svg/SVGFEFloodElement.h
+++ b/Source/core/svg/SVGFEFloodElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEFloodElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEFloodElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEFloodElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEFloodElement(const QualifiedName&, Document*);
+    SVGFEFloodElement(const QualifiedName&, Document&);
 
     virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName);
     virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
diff --git a/Source/core/svg/SVGFEFuncAElement.cpp b/Source/core/svg/SVGFEFuncAElement.cpp
index 35eb1fd..4d35ab7 100644
--- a/Source/core/svg/SVGFEFuncAElement.cpp
+++ b/Source/core/svg/SVGFEFuncAElement.cpp
@@ -25,14 +25,14 @@
 
 namespace WebCore {
 
-inline SVGFEFuncAElement::SVGFEFuncAElement(const QualifiedName& tagName, Document* document)
+inline SVGFEFuncAElement::SVGFEFuncAElement(const QualifiedName& tagName, Document& document)
     : SVGComponentTransferFunctionElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feFuncATag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFuncAElement> SVGFEFuncAElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEFuncAElement> SVGFEFuncAElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEFuncAElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEFuncAElement.h b/Source/core/svg/SVGFEFuncAElement.h
index 18f5746..db63a15 100644
--- a/Source/core/svg/SVGFEFuncAElement.h
+++ b/Source/core/svg/SVGFEFuncAElement.h
@@ -27,10 +27,10 @@
 
 class SVGFEFuncAElement FINAL : public SVGComponentTransferFunctionElement {
 public:
-    static PassRefPtr<SVGFEFuncAElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEFuncAElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEFuncAElement(const QualifiedName&, Document*);
+    SVGFEFuncAElement(const QualifiedName&, Document&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFEFuncBElement.cpp b/Source/core/svg/SVGFEFuncBElement.cpp
index b70ff65..abca696 100644
--- a/Source/core/svg/SVGFEFuncBElement.cpp
+++ b/Source/core/svg/SVGFEFuncBElement.cpp
@@ -25,14 +25,14 @@
 
 namespace WebCore {
 
-inline SVGFEFuncBElement::SVGFEFuncBElement(const QualifiedName& tagName, Document* document)
+inline SVGFEFuncBElement::SVGFEFuncBElement(const QualifiedName& tagName, Document& document)
     : SVGComponentTransferFunctionElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feFuncBTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFuncBElement> SVGFEFuncBElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEFuncBElement> SVGFEFuncBElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEFuncBElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEFuncBElement.h b/Source/core/svg/SVGFEFuncBElement.h
index c9820a5..3c0fbce 100644
--- a/Source/core/svg/SVGFEFuncBElement.h
+++ b/Source/core/svg/SVGFEFuncBElement.h
@@ -27,10 +27,10 @@
 
 class SVGFEFuncBElement FINAL : public SVGComponentTransferFunctionElement {
 public:
-    static PassRefPtr<SVGFEFuncBElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEFuncBElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEFuncBElement(const QualifiedName&, Document*);
+    SVGFEFuncBElement(const QualifiedName&, Document&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFEFuncGElement.cpp b/Source/core/svg/SVGFEFuncGElement.cpp
index 7ae8c47..f7de1f3 100644
--- a/Source/core/svg/SVGFEFuncGElement.cpp
+++ b/Source/core/svg/SVGFEFuncGElement.cpp
@@ -25,14 +25,14 @@
 
 namespace WebCore {
 
-inline SVGFEFuncGElement::SVGFEFuncGElement(const QualifiedName& tagName, Document* document)
+inline SVGFEFuncGElement::SVGFEFuncGElement(const QualifiedName& tagName, Document& document)
     : SVGComponentTransferFunctionElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feFuncGTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFuncGElement> SVGFEFuncGElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEFuncGElement> SVGFEFuncGElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEFuncGElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEFuncGElement.h b/Source/core/svg/SVGFEFuncGElement.h
index 523f8be..3121aea 100644
--- a/Source/core/svg/SVGFEFuncGElement.h
+++ b/Source/core/svg/SVGFEFuncGElement.h
@@ -27,10 +27,10 @@
 
 class SVGFEFuncGElement FINAL : public SVGComponentTransferFunctionElement {
 public:
-    static PassRefPtr<SVGFEFuncGElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEFuncGElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEFuncGElement(const QualifiedName&, Document*);
+    SVGFEFuncGElement(const QualifiedName&, Document&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFEFuncRElement.cpp b/Source/core/svg/SVGFEFuncRElement.cpp
index d6527cb..cf059b6 100644
--- a/Source/core/svg/SVGFEFuncRElement.cpp
+++ b/Source/core/svg/SVGFEFuncRElement.cpp
@@ -25,14 +25,14 @@
 
 namespace WebCore {
 
-inline SVGFEFuncRElement::SVGFEFuncRElement(const QualifiedName& tagName, Document* document)
+inline SVGFEFuncRElement::SVGFEFuncRElement(const QualifiedName& tagName, Document& document)
     : SVGComponentTransferFunctionElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feFuncRTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEFuncRElement> SVGFEFuncRElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEFuncRElement> SVGFEFuncRElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEFuncRElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEFuncRElement.h b/Source/core/svg/SVGFEFuncRElement.h
index f467f5f..8b76e46 100644
--- a/Source/core/svg/SVGFEFuncRElement.h
+++ b/Source/core/svg/SVGFEFuncRElement.h
@@ -27,10 +27,10 @@
 
 class SVGFEFuncRElement FINAL : public SVGComponentTransferFunctionElement {
 public:
-    static PassRefPtr<SVGFEFuncRElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEFuncRElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEFuncRElement(const QualifiedName&, Document*);
+    SVGFEFuncRElement(const QualifiedName&, Document&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFEGaussianBlurElement.cpp b/Source/core/svg/SVGFEGaussianBlurElement.cpp
index 0028fda..3611e96 100644
--- a/Source/core/svg/SVGFEGaussianBlurElement.cpp
+++ b/Source/core/svg/SVGFEGaussianBlurElement.cpp
@@ -42,7 +42,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEGaussianBlurElement::SVGFEGaussianBlurElement(const QualifiedName& tagName, Document* document)
+inline SVGFEGaussianBlurElement::SVGFEGaussianBlurElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feGaussianBlurTag));
@@ -50,7 +50,7 @@
     registerAnimatedPropertiesForSVGFEGaussianBlurElement();
 }
 
-PassRefPtr<SVGFEGaussianBlurElement> SVGFEGaussianBlurElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEGaussianBlurElement> SVGFEGaussianBlurElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEGaussianBlurElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEGaussianBlurElement.h b/Source/core/svg/SVGFEGaussianBlurElement.h
index c703e88..317addc 100644
--- a/Source/core/svg/SVGFEGaussianBlurElement.h
+++ b/Source/core/svg/SVGFEGaussianBlurElement.h
@@ -29,12 +29,12 @@
 
 class SVGFEGaussianBlurElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEGaussianBlurElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEGaussianBlurElement> create(const QualifiedName&, Document&);
 
     void setStdDeviation(float stdDeviationX, float stdDeviationY);
 
 private:
-    SVGFEGaussianBlurElement(const QualifiedName&, Document*);
+    SVGFEGaussianBlurElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEImageElement.cpp b/Source/core/svg/SVGFEImageElement.cpp
index c1d0e37..e164c65 100644
--- a/Source/core/svg/SVGFEImageElement.cpp
+++ b/Source/core/svg/SVGFEImageElement.cpp
@@ -48,7 +48,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEImageElement::SVGFEImageElement(const QualifiedName& tagName, Document* document)
+inline SVGFEImageElement::SVGFEImageElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feImageTag));
@@ -56,7 +56,7 @@
     registerAnimatedPropertiesForSVGFEImageElement();
 }
 
-PassRefPtr<SVGFEImageElement> SVGFEImageElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEImageElement> SVGFEImageElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEImageElement(tagName, document));
 }
@@ -66,6 +66,14 @@
     clearResourceReferences();
 }
 
+bool SVGFEImageElement::currentFrameHasSingleSecurityOrigin() const
+{
+    if (m_cachedImage && m_cachedImage->image())
+        return m_cachedImage->image()->currentFrameHasSingleSecurityOrigin();
+
+    return true;
+}
+
 void SVGFEImageElement::clearResourceReferences()
 {
     if (m_cachedImage) {
@@ -73,14 +81,13 @@
         m_cachedImage = 0;
     }
 
-    ASSERT(document());
-    document()->accessSVGExtensions()->removeAllTargetReferencesForElement(this);
+    document().accessSVGExtensions()->removeAllTargetReferencesForElement(this);
 }
 
 void SVGFEImageElement::fetchImageResource()
 {
     FetchRequest request(ResourceRequest(ownerDocument()->completeURL(hrefCurrentValue())), localName());
-    m_cachedImage = document()->fetcher()->fetchImage(request);
+    m_cachedImage = document().fetcher()->fetchImage(request);
 
     if (m_cachedImage)
         m_cachedImage->addClient(this);
@@ -98,13 +105,13 @@
         if (id.isEmpty())
             fetchImageResource();
         else {
-            document()->accessSVGExtensions()->addPendingResource(id, this);
+            document().accessSVGExtensions()->addPendingResource(id, this);
             ASSERT(hasPendingResources());
         }
     } else if (target->isSVGElement()) {
         // Register us with the target in the dependencies map. Any change of hrefElement
         // that leads to relayout/repainting now informs us, so we can react to it.
-        document()->accessSVGExtensions()->addElementReferencingTarget(this, toSVGElement(target));
+        document().accessSVGExtensions()->addElementReferencingTarget(this, toSVGElement(target));
     }
 
     invalidate();
@@ -208,7 +215,7 @@
 {
     SVGFilterPrimitiveStandardAttributes::addSubresourceAttributeURLs(urls);
 
-    addSubresourceURL(urls, document()->completeURL(hrefCurrentValue()));
+    addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
 }
 
 }
diff --git a/Source/core/svg/SVGFEImageElement.h b/Source/core/svg/SVGFEImageElement.h
index 69af339..c769e55 100644
--- a/Source/core/svg/SVGFEImageElement.h
+++ b/Source/core/svg/SVGFEImageElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGFEImageElement_h
 #define SVGFEImageElement_h
 
+#include "SVGNames.h"
 #include "core/fetch/ImageResource.h"
 #include "core/fetch/ResourcePtr.h"
 #include "core/platform/graphics/ImageBuffer.h"
@@ -38,12 +39,14 @@
                                 public SVGExternalResourcesRequired,
                                 public ImageResourceClient {
 public:
-    static PassRefPtr<SVGFEImageElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEImageElement> create(const QualifiedName&, Document&);
+
+    bool currentFrameHasSingleSecurityOrigin() const;
 
     virtual ~SVGFEImageElement();
 
 private:
-    SVGFEImageElement(const QualifiedName&, Document*);
+    SVGFEImageElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -69,6 +72,12 @@
     ResourcePtr<ImageResource> m_cachedImage;
 };
 
+inline SVGFEImageElement* toSVGFEImageElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feImageTag));
+    return static_cast<SVGFEImageElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFELightElement.cpp b/Source/core/svg/SVGFELightElement.cpp
index 9cb96d9..4429044 100644
--- a/Source/core/svg/SVGFELightElement.cpp
+++ b/Source/core/svg/SVGFELightElement.cpp
@@ -57,7 +57,7 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(limitingConeAngle)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGFELightElement::SVGFELightElement(const QualifiedName& tagName, Document* document)
+SVGFELightElement::SVGFELightElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_specularExponent(1)
 {
@@ -190,12 +190,10 @@
             return;
 
         if (parent->hasTagName(SVGNames::feDiffuseLightingTag)) {
-            SVGFEDiffuseLightingElement* diffuseLighting = static_cast<SVGFEDiffuseLightingElement*>(parent);
-            diffuseLighting->lightElementAttributeChanged(this, attrName);
+            toSVGFEDiffuseLightingElement(parent)->lightElementAttributeChanged(this, attrName);
             return;
         } else if (parent->hasTagName(SVGNames::feSpecularLightingTag)) {
-            SVGFESpecularLightingElement* specularLighting = static_cast<SVGFESpecularLightingElement*>(parent);
-            specularLighting->lightElementAttributeChanged(this, attrName);
+            toSVGFESpecularLightingElement(parent)->lightElementAttributeChanged(this, attrName);
             return;
         }
     }
diff --git a/Source/core/svg/SVGFELightElement.h b/Source/core/svg/SVGFELightElement.h
index 4d84041..4d14e30 100644
--- a/Source/core/svg/SVGFELightElement.h
+++ b/Source/core/svg/SVGFELightElement.h
@@ -35,7 +35,7 @@
     static PassRefPtr<LightSource> findLightSource(const SVGElement*);
 
 protected:
-    SVGFELightElement(const QualifiedName&, Document*);
+    SVGFELightElement(const QualifiedName&, Document&);
 
 private:
     bool isSupportedAttribute(const QualifiedName&);
@@ -43,7 +43,7 @@
     virtual void svgAttributeChanged(const QualifiedName&);
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFELightElement)
         DECLARE_ANIMATED_NUMBER(Azimuth, azimuth)
diff --git a/Source/core/svg/SVGFEMergeElement.cpp b/Source/core/svg/SVGFEMergeElement.cpp
index f632e3f..caeb9ff 100644
--- a/Source/core/svg/SVGFEMergeElement.cpp
+++ b/Source/core/svg/SVGFEMergeElement.cpp
@@ -29,14 +29,14 @@
 
 namespace WebCore {
 
-inline SVGFEMergeElement::SVGFEMergeElement(const QualifiedName& tagName, Document* document)
+inline SVGFEMergeElement::SVGFEMergeElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feMergeTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEMergeElement> SVGFEMergeElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEMergeElement> SVGFEMergeElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEMergeElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEMergeElement.h b/Source/core/svg/SVGFEMergeElement.h
index 87c6fcc..ab682bb 100644
--- a/Source/core/svg/SVGFEMergeElement.h
+++ b/Source/core/svg/SVGFEMergeElement.h
@@ -28,10 +28,10 @@
 
 class SVGFEMergeElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEMergeElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEMergeElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEMergeElement(const QualifiedName&, Document*);
+    SVGFEMergeElement(const QualifiedName&, Document&);
 
     virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
 };
diff --git a/Source/core/svg/SVGFEMergeNodeElement.cpp b/Source/core/svg/SVGFEMergeNodeElement.cpp
index 508c60b..648f22e 100644
--- a/Source/core/svg/SVGFEMergeNodeElement.cpp
+++ b/Source/core/svg/SVGFEMergeNodeElement.cpp
@@ -35,7 +35,7 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEMergeNodeElement::SVGFEMergeNodeElement(const QualifiedName& tagName, Document* document)
+inline SVGFEMergeNodeElement::SVGFEMergeNodeElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feMergeNodeTag));
@@ -43,7 +43,7 @@
     registerAnimatedPropertiesForSVGFEMergeNodeElement();
 }
 
-PassRefPtr<SVGFEMergeNodeElement> SVGFEMergeNodeElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEMergeNodeElement> SVGFEMergeNodeElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEMergeNodeElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEMergeNodeElement.h b/Source/core/svg/SVGFEMergeNodeElement.h
index 6e1f408..bd90db7 100644
--- a/Source/core/svg/SVGFEMergeNodeElement.h
+++ b/Source/core/svg/SVGFEMergeNodeElement.h
@@ -28,16 +28,16 @@
 
 class SVGFEMergeNodeElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFEMergeNodeElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEMergeNodeElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEMergeNodeElement(const QualifiedName&, Document*);
+    SVGFEMergeNodeElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFEMergeNodeElement)
         DECLARE_ANIMATED_STRING(In1, in1)
diff --git a/Source/core/svg/SVGFEMorphologyElement.cpp b/Source/core/svg/SVGFEMorphologyElement.cpp
index 8af7444..4502e22 100644
--- a/Source/core/svg/SVGFEMorphologyElement.cpp
+++ b/Source/core/svg/SVGFEMorphologyElement.cpp
@@ -43,7 +43,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEMorphologyElement::SVGFEMorphologyElement(const QualifiedName& tagName, Document* document)
+inline SVGFEMorphologyElement::SVGFEMorphologyElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_svgOperator(FEMORPHOLOGY_OPERATOR_ERODE)
 {
@@ -52,7 +52,7 @@
     registerAnimatedPropertiesForSVGFEMorphologyElement();
 }
 
-PassRefPtr<SVGFEMorphologyElement> SVGFEMorphologyElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEMorphologyElement> SVGFEMorphologyElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEMorphologyElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEMorphologyElement.h b/Source/core/svg/SVGFEMorphologyElement.h
index 0c7ab3d..38dede0 100644
--- a/Source/core/svg/SVGFEMorphologyElement.h
+++ b/Source/core/svg/SVGFEMorphologyElement.h
@@ -58,12 +58,12 @@
 
 class SVGFEMorphologyElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEMorphologyElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEMorphologyElement> create(const QualifiedName&, Document&);
 
     void setRadius(float radiusX, float radiusY);
 
 private:
-    SVGFEMorphologyElement(const QualifiedName&, Document*);
+    SVGFEMorphologyElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEOffsetElement.cpp b/Source/core/svg/SVGFEOffsetElement.cpp
index 19b9424..a110b83 100644
--- a/Source/core/svg/SVGFEOffsetElement.cpp
+++ b/Source/core/svg/SVGFEOffsetElement.cpp
@@ -41,7 +41,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFEOffsetElement::SVGFEOffsetElement(const QualifiedName& tagName, Document* document)
+inline SVGFEOffsetElement::SVGFEOffsetElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feOffsetTag));
@@ -49,7 +49,7 @@
     registerAnimatedPropertiesForSVGFEOffsetElement();
 }
 
-PassRefPtr<SVGFEOffsetElement> SVGFEOffsetElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEOffsetElement> SVGFEOffsetElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEOffsetElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEOffsetElement.h b/Source/core/svg/SVGFEOffsetElement.h
index 9a8517e..a0489a4 100644
--- a/Source/core/svg/SVGFEOffsetElement.h
+++ b/Source/core/svg/SVGFEOffsetElement.h
@@ -29,10 +29,10 @@
 
 class SVGFEOffsetElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFEOffsetElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEOffsetElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEOffsetElement(const QualifiedName&, Document*);
+    SVGFEOffsetElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFEPointLightElement.cpp b/Source/core/svg/SVGFEPointLightElement.cpp
index d98c1fc..0f971b1 100644
--- a/Source/core/svg/SVGFEPointLightElement.cpp
+++ b/Source/core/svg/SVGFEPointLightElement.cpp
@@ -26,14 +26,14 @@
 
 namespace WebCore {
 
-inline SVGFEPointLightElement::SVGFEPointLightElement(const QualifiedName& tagName, Document* document)
+inline SVGFEPointLightElement::SVGFEPointLightElement(const QualifiedName& tagName, Document& document)
     : SVGFELightElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::fePointLightTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFEPointLightElement> SVGFEPointLightElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFEPointLightElement> SVGFEPointLightElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFEPointLightElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFEPointLightElement.h b/Source/core/svg/SVGFEPointLightElement.h
index b27f823..10bdec9 100644
--- a/Source/core/svg/SVGFEPointLightElement.h
+++ b/Source/core/svg/SVGFEPointLightElement.h
@@ -26,10 +26,10 @@
 
 class SVGFEPointLightElement FINAL : public SVGFELightElement {
 public:
-    static PassRefPtr<SVGFEPointLightElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFEPointLightElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFEPointLightElement(const QualifiedName&, Document*);
+    SVGFEPointLightElement(const QualifiedName&, Document&);
 
     virtual PassRefPtr<LightSource> lightSource() const;
 };
diff --git a/Source/core/svg/SVGFESpecularLightingElement.cpp b/Source/core/svg/SVGFESpecularLightingElement.cpp
index 4d51a63..12cd0c7 100644
--- a/Source/core/svg/SVGFESpecularLightingElement.cpp
+++ b/Source/core/svg/SVGFESpecularLightingElement.cpp
@@ -51,7 +51,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFESpecularLightingElement::SVGFESpecularLightingElement(const QualifiedName& tagName, Document* document)
+inline SVGFESpecularLightingElement::SVGFESpecularLightingElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_specularConstant(1)
     , m_specularExponent(1)
@@ -62,7 +62,7 @@
     registerAnimatedPropertiesForSVGFESpecularLightingElement();
 }
 
-PassRefPtr<SVGFESpecularLightingElement> SVGFESpecularLightingElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFESpecularLightingElement> SVGFESpecularLightingElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFESpecularLightingElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFESpecularLightingElement.h b/Source/core/svg/SVGFESpecularLightingElement.h
index 3e10c9d..38d5d62 100644
--- a/Source/core/svg/SVGFESpecularLightingElement.h
+++ b/Source/core/svg/SVGFESpecularLightingElement.h
@@ -22,6 +22,7 @@
 #ifndef SVGFESpecularLightingElement_h
 #define SVGFESpecularLightingElement_h
 
+#include "SVGNames.h"
 #include "core/platform/graphics/filters/FESpecularLighting.h"
 #include "core/svg/SVGAnimatedNumber.h"
 #include "core/svg/SVGFELightElement.h"
@@ -31,11 +32,11 @@
 
 class SVGFESpecularLightingElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFESpecularLightingElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFESpecularLightingElement> create(const QualifiedName&, Document&);
     void lightElementAttributeChanged(const SVGFELightElement*, const QualifiedName&);
 
 private:
-    SVGFESpecularLightingElement(const QualifiedName&, Document*);
+    SVGFESpecularLightingElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -56,6 +57,12 @@
     END_DECLARE_ANIMATED_PROPERTIES
 };
 
+inline SVGFESpecularLightingElement* toSVGFESpecularLightingElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feSpecularLightingTag));
+    return static_cast<SVGFESpecularLightingElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGFESpotLightElement.cpp b/Source/core/svg/SVGFESpotLightElement.cpp
index aa09fb1..c41e52a 100644
--- a/Source/core/svg/SVGFESpotLightElement.cpp
+++ b/Source/core/svg/SVGFESpotLightElement.cpp
@@ -26,14 +26,14 @@
 
 namespace WebCore {
 
-inline SVGFESpotLightElement::SVGFESpotLightElement(const QualifiedName& tagName, Document* document)
+inline SVGFESpotLightElement::SVGFESpotLightElement(const QualifiedName& tagName, Document& document)
     : SVGFELightElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feSpotLightTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFESpotLightElement> SVGFESpotLightElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFESpotLightElement> SVGFESpotLightElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFESpotLightElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFESpotLightElement.h b/Source/core/svg/SVGFESpotLightElement.h
index 2b46665..3b0ca9c 100644
--- a/Source/core/svg/SVGFESpotLightElement.h
+++ b/Source/core/svg/SVGFESpotLightElement.h
@@ -26,10 +26,10 @@
 
 class SVGFESpotLightElement FINAL : public SVGFELightElement {
 public:
-    static PassRefPtr<SVGFESpotLightElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFESpotLightElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFESpotLightElement(const QualifiedName&, Document*);
+    SVGFESpotLightElement(const QualifiedName&, Document&);
 
     virtual PassRefPtr<LightSource> lightSource() const;
 };
diff --git a/Source/core/svg/SVGFETileElement.cpp b/Source/core/svg/SVGFETileElement.cpp
index 59587bb..44b94a0 100644
--- a/Source/core/svg/SVGFETileElement.cpp
+++ b/Source/core/svg/SVGFETileElement.cpp
@@ -37,7 +37,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFETileElement::SVGFETileElement(const QualifiedName& tagName, Document* document)
+inline SVGFETileElement::SVGFETileElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::feTileTag));
@@ -45,7 +45,7 @@
     registerAnimatedPropertiesForSVGFETileElement();
 }
 
-PassRefPtr<SVGFETileElement> SVGFETileElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFETileElement> SVGFETileElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFETileElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFETileElement.h b/Source/core/svg/SVGFETileElement.h
index e616a21..005c53b 100644
--- a/Source/core/svg/SVGFETileElement.h
+++ b/Source/core/svg/SVGFETileElement.h
@@ -28,10 +28,10 @@
 
 class SVGFETileElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFETileElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFETileElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFETileElement(const QualifiedName&, Document*);
+    SVGFETileElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFETurbulenceElement.cpp b/Source/core/svg/SVGFETurbulenceElement.cpp
index 3c95c2c..14236b2 100644
--- a/Source/core/svg/SVGFETurbulenceElement.cpp
+++ b/Source/core/svg/SVGFETurbulenceElement.cpp
@@ -46,7 +46,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFETurbulenceElement::SVGFETurbulenceElement(const QualifiedName& tagName, Document* document)
+inline SVGFETurbulenceElement::SVGFETurbulenceElement(const QualifiedName& tagName, Document& document)
     : SVGFilterPrimitiveStandardAttributes(tagName, document)
     , m_numOctaves(1)
     , m_stitchTiles(SVG_STITCHTYPE_NOSTITCH)
@@ -57,7 +57,7 @@
     registerAnimatedPropertiesForSVGFETurbulenceElement();
 }
 
-PassRefPtr<SVGFETurbulenceElement> SVGFETurbulenceElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFETurbulenceElement> SVGFETurbulenceElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFETurbulenceElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFETurbulenceElement.h b/Source/core/svg/SVGFETurbulenceElement.h
index a4c942d..c77eceb 100644
--- a/Source/core/svg/SVGFETurbulenceElement.h
+++ b/Source/core/svg/SVGFETurbulenceElement.h
@@ -95,10 +95,10 @@
 
 class SVGFETurbulenceElement FINAL : public SVGFilterPrimitiveStandardAttributes {
 public:
-    static PassRefPtr<SVGFETurbulenceElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFETurbulenceElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFETurbulenceElement(const QualifiedName&, Document*);
+    SVGFETurbulenceElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGFilterElement.cpp b/Source/core/svg/SVGFilterElement.cpp
index 881b08e..391a1d8 100644
--- a/Source/core/svg/SVGFilterElement.cpp
+++ b/Source/core/svg/SVGFilterElement.cpp
@@ -27,7 +27,6 @@
 
 #include "SVGNames.h"
 #include "XLinkNames.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/rendering/svg/RenderSVGResourceFilter.h"
 #include "core/svg/SVGElementInstance.h"
 #include "core/svg/SVGParserUtilities.h"
@@ -59,7 +58,7 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFilterElement::SVGFilterElement(const QualifiedName& tagName, Document* document)
+inline SVGFilterElement::SVGFilterElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_filterUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
     , m_primitiveUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
@@ -75,7 +74,7 @@
     registerAnimatedPropertiesForSVGFilterElement();
 }
 
-PassRefPtr<SVGFilterElement> SVGFilterElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFilterElement> SVGFilterElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFilterElement(tagName, document));
 }
@@ -188,20 +187,20 @@
 {
     RenderSVGResourceFilter* renderer = new RenderSVGResourceFilter(this);
 
-    HashSet<RenderLayer*>::iterator layerEnd = m_clientLayers.end();
-    for (HashSet<RenderLayer*>::iterator it = m_clientLayers.begin(); it != layerEnd; ++it)
-        renderer->addClientRenderLayer(*it);
-    m_clientLayers.clear();
+    HashSet<RefPtr<Node> >::iterator layerEnd = m_clientsToAdd.end();
+    for (HashSet<RefPtr<Node> >::iterator it = m_clientsToAdd.begin(); it != layerEnd; ++it)
+        renderer->addClientRenderLayer((*it).get());
+    m_clientsToAdd.clear();
 
     return renderer;
 }
 
-bool SVGFilterElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGFilterElement::childShouldCreateRenderer(const Node& child) const
 {
-    if (!childContext.node()->isSVGElement())
+    if (!child.isSVGElement())
         return false;
 
-    SVGElement* svgElement = toSVGElement(childContext.node());
+    const SVGElement* svgElement = toSVGElement(&child);
 
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, allowedChildElementTags, ());
     if (allowedChildElementTags.isEmpty()) {
@@ -243,24 +242,16 @@
         || heightCurrentValue().isRelative();
 }
 
-void SVGFilterElement::addClientRenderLayer(RenderLayer* client)
+void SVGFilterElement::addClient(Node* client)
 {
     ASSERT(client);
-    RenderSVGResourceFilter* filterRenderer = toRenderSVGFilter(renderer());
-    if (filterRenderer)
-        filterRenderer->addClientRenderLayer(client);
-    else
-        m_clientLayers.add(client);
+    m_clientsToAdd.add(client);
 }
 
-void SVGFilterElement::removeClientRenderLayer(RenderLayer* client)
+void SVGFilterElement::removeClient(Node* client)
 {
     ASSERT(client);
-    RenderSVGResourceFilter* filterRenderer = toRenderSVGFilter(renderer());
-    if (filterRenderer)
-        filterRenderer->removeClientRenderLayer(client);
-    else
-        m_clientLayers.add(client);
+    m_clientsToAdd.remove(client);
 }
 
 }
diff --git a/Source/core/svg/SVGFilterElement.h b/Source/core/svg/SVGFilterElement.h
index e7b0b52..d344fd2 100644
--- a/Source/core/svg/SVGFilterElement.h
+++ b/Source/core/svg/SVGFilterElement.h
@@ -35,20 +35,18 @@
 
 namespace WebCore {
 
-class RenderLayer;
-
 class SVGFilterElement FINAL : public SVGElement,
                                public SVGURIReference,
                                public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGFilterElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFilterElement> create(const QualifiedName&, Document&);
 
     void setFilterRes(unsigned filterResX, unsigned filterResY);
-    void addClientRenderLayer(RenderLayer*);
-    void removeClientRenderLayer(RenderLayer*);
+    void addClient(Node*);
+    void removeClient(Node*);
 
 private:
-    SVGFilterElement(const QualifiedName&, Document*);
+    SVGFilterElement(const QualifiedName&, Document&);
 
     virtual bool needsPendingResourceHandling() const { return false; }
 
@@ -58,7 +56,7 @@
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
+    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
 
     virtual bool selfHasRelativeLengths() const;
 
@@ -78,7 +76,7 @@
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    HashSet<RenderLayer*> m_clientLayers;
+    HashSet<RefPtr<Node> > m_clientsToAdd;
 };
 
 inline SVGFilterElement* toSVGFilterElement(Node* node)
diff --git a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
index 9a8b8b8..5299939 100644
--- a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
+++ b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
@@ -47,7 +47,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGFilterPrimitiveStandardAttributes::SVGFilterPrimitiveStandardAttributes(const QualifiedName& tagName, Document* document)
+SVGFilterPrimitiveStandardAttributes::SVGFilterPrimitiveStandardAttributes(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_x(LengthModeWidth, "0%")
     , m_y(LengthModeHeight, "0%")
@@ -141,10 +141,10 @@
     return new RenderSVGResourceFilterPrimitive(this);
 }
 
-bool SVGFilterPrimitiveStandardAttributes::rendererIsNeeded(const NodeRenderingContext& context)
+bool SVGFilterPrimitiveStandardAttributes::rendererIsNeeded(const RenderStyle& style)
 {
     if (parentNode() && (parentNode()->hasTagName(SVGNames::filterTag)))
-        return SVGElement::rendererIsNeeded(context);
+        return SVGElement::rendererIsNeeded(style);
 
     return false;
 }
diff --git a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h
index 82c3a92..bbdc8ff 100644
--- a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h
+++ b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h
@@ -44,7 +44,7 @@
     virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName&);
 
 protected:
-    SVGFilterPrimitiveStandardAttributes(const QualifiedName&, Document*);
+    SVGFilterPrimitiveStandardAttributes(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -63,8 +63,8 @@
     virtual bool isFilterEffect() const { return true; }
 
     virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
+    virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE { return false; }
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
         DECLARE_ANIMATED_LENGTH(X, x)
diff --git a/Source/core/svg/SVGFitToViewBox.h b/Source/core/svg/SVGFitToViewBox.h
index 736eca6..6528445 100644
--- a/Source/core/svg/SVGFitToViewBox.h
+++ b/Source/core/svg/SVGFitToViewBox.h
@@ -43,10 +43,9 @@
     static bool parseAttribute(SVGElementTarget* target, const QualifiedName& name, const AtomicString& value)
     {
         ASSERT(target);
-        ASSERT(target->document());
         if (name == SVGNames::viewBoxAttr) {
             FloatRect viewBox;
-            bool valueIsValid = !value.isNull() && parseViewBox(target->document(), value, viewBox);
+            bool valueIsValid = !value.isNull() && parseViewBox(&target->document(), value, viewBox);
             target->setViewBoxBaseValue(viewBox, valueIsValid);
             return true;
         }
diff --git a/Source/core/svg/SVGFontElement.cpp b/Source/core/svg/SVGFontElement.cpp
index e076129..ab333c0 100644
--- a/Source/core/svg/SVGFontElement.cpp
+++ b/Source/core/svg/SVGFontElement.cpp
@@ -42,7 +42,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGFontElement::SVGFontElement(const QualifiedName& tagName, Document* document)
+inline SVGFontElement::SVGFontElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_missingGlyph(0)
     , m_isGlyphCacheValid(false)
@@ -51,10 +51,10 @@
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGFontElement();
 
-    UseCounter::count(document, UseCounter::SVGFontElement);
+    UseCounter::count(&document, UseCounter::SVGFontElement);
 }
 
-PassRefPtr<SVGFontElement> SVGFontElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFontElement> SVGFontElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFontElement(tagName, document));
 }
@@ -124,7 +124,7 @@
     Vector<String> ligatures;
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
         if (child->hasTagName(SVGNames::glyphTag)) {
-            SVGGlyphElement* glyph = static_cast<SVGGlyphElement*>(child);
+            SVGGlyphElement* glyph = toSVGGlyphElement(child);
             AtomicString unicode = glyph->fastGetAttribute(SVGNames::unicodeAttr);
             AtomicString glyphId = glyph->getIdAttribute();
             if (glyphId.isEmpty() && unicode.isEmpty())
@@ -136,11 +136,9 @@
             if (unicode.length() > 1 && !U16_IS_SURROGATE(unicode[0]))
                 ligatures.append(unicode.string());
         } else if (child->hasTagName(SVGNames::hkernTag)) {
-            SVGHKernElement* hkern = static_cast<SVGHKernElement*>(child);
-            hkern->buildHorizontalKerningPair(m_horizontalKerningPairs);
+            toSVGHKernElement(child)->buildHorizontalKerningPair(m_horizontalKerningPairs);
         } else if (child->hasTagName(SVGNames::vkernTag)) {
-            SVGVKernElement* vkern = static_cast<SVGVKernElement*>(child);
-            vkern->buildVerticalKerningPair(m_verticalKerningPairs);
+            toSVGVKernElement(child)->buildVerticalKerningPair(m_verticalKerningPairs);
         } else if (child->hasTagName(SVGNames::missing_glyphTag) && !firstMissingGlyphElement) {
             firstMissingGlyphElement = toSVGMissingGlyphElement(child);
         }
diff --git a/Source/core/svg/SVGFontElement.h b/Source/core/svg/SVGFontElement.h
index 1d3b570..fefa0a5 100644
--- a/Source/core/svg/SVGFontElement.h
+++ b/Source/core/svg/SVGFontElement.h
@@ -55,7 +55,7 @@
 class SVGFontElement FINAL : public SVGElement
                            , public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGFontElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFontElement> create(const QualifiedName&, Document&);
 
     void invalidateGlyphCache();
     void collectGlyphsForString(const String&, Vector<SVGGlyph>&);
@@ -71,9 +71,9 @@
     SVGMissingGlyphElement* firstMissingGlyphElement() const;
 
 private:
-    SVGFontElement(const QualifiedName&, Document*);
+    SVGFontElement(const QualifiedName&, Document&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 
     void ensureGlyphCache();
     void registerLigaturesInGlyphCache(Vector<String>&);
diff --git a/Source/core/svg/SVGFontFaceElement.cpp b/Source/core/svg/SVGFontFaceElement.cpp
index 9c77958..430dfb9 100644
--- a/Source/core/svg/SVGFontFaceElement.cpp
+++ b/Source/core/svg/SVGFontFaceElement.cpp
@@ -46,7 +46,7 @@
 
 using namespace SVGNames;
 
-inline SVGFontFaceElement::SVGFontFaceElement(const QualifiedName& tagName, Document* document)
+inline SVGFontFaceElement::SVGFontFaceElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_fontFaceRule(StyleRuleFontFace::create())
     , m_fontElement(0)
@@ -57,7 +57,7 @@
     m_fontFaceRule->setProperties(styleDeclaration.release());
 }
 
-PassRefPtr<SVGFontFaceElement> SVGFontFaceElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFontFaceElement> SVGFontFaceElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFontFaceElement(tagName, document));
 }
@@ -316,7 +316,7 @@
         }
     }
 
-    document()->styleResolverChanged(RecalcStyleDeferred);
+    document().styleResolverChanged(RecalcStyleDeferred);
 }
 
 Node::InsertionNotificationRequest SVGFontFaceElement::insertedInto(ContainerNode* rootParent)
@@ -326,7 +326,7 @@
         ASSERT(!m_fontElement);
         return InsertionDone;
     }
-    document()->accessSVGExtensions()->registerSVGFontFaceElement(this);
+    document().accessSVGExtensions()->registerSVGFontFaceElement(this);
 
     rebuildFontFace();
     return InsertionDone;
@@ -338,10 +338,10 @@
 
     if (rootParent->inDocument()) {
         m_fontElement = 0;
-        document()->accessSVGExtensions()->unregisterSVGFontFaceElement(this);
+        document().accessSVGExtensions()->unregisterSVGFontFaceElement(this);
         m_fontFaceRule->mutableProperties()->clear();
 
-        document()->styleResolverChanged(RecalcStyleDeferred);
+        document().styleResolverChanged(RecalcStyleDeferred);
     } else
         ASSERT(!m_fontElement);
 }
diff --git a/Source/core/svg/SVGFontFaceElement.h b/Source/core/svg/SVGFontFaceElement.h
index 086a793..5e77bd7 100644
--- a/Source/core/svg/SVGFontFaceElement.h
+++ b/Source/core/svg/SVGFontFaceElement.h
@@ -33,7 +33,7 @@
 
 class SVGFontFaceElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFontFaceElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFontFaceElement> create(const QualifiedName&, Document&);
 
     unsigned unitsPerEm() const;
     int xHeight() const;
@@ -53,7 +53,7 @@
     StyleRuleFontFace* fontFaceRule() const { return m_fontFaceRule.get(); }
 
 private:
-    SVGFontFaceElement(const QualifiedName&, Document*);
+    SVGFontFaceElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
@@ -61,7 +61,7 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     RefPtr<StyleRuleFontFace> m_fontFaceRule;
     SVGFontElement* m_fontElement;
diff --git a/Source/core/svg/SVGFontFaceFormatElement.cpp b/Source/core/svg/SVGFontFaceFormatElement.cpp
index ed83472..94970cc 100644
--- a/Source/core/svg/SVGFontFaceFormatElement.cpp
+++ b/Source/core/svg/SVGFontFaceFormatElement.cpp
@@ -29,14 +29,14 @@
 
 using namespace SVGNames;
 
-inline SVGFontFaceFormatElement::SVGFontFaceFormatElement(const QualifiedName& tagName, Document* document)
+inline SVGFontFaceFormatElement::SVGFontFaceFormatElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(font_face_formatTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFontFaceFormatElement> SVGFontFaceFormatElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFontFaceFormatElement> SVGFontFaceFormatElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFontFaceFormatElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFontFaceFormatElement.h b/Source/core/svg/SVGFontFaceFormatElement.h
index 4370a27..33e7502 100644
--- a/Source/core/svg/SVGFontFaceFormatElement.h
+++ b/Source/core/svg/SVGFontFaceFormatElement.h
@@ -27,13 +27,13 @@
 
 class SVGFontFaceFormatElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFontFaceFormatElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFontFaceFormatElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGFontFaceFormatElement(const QualifiedName&, Document*);
+    SVGFontFaceFormatElement(const QualifiedName&, Document&);
 
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFontFaceNameElement.cpp b/Source/core/svg/SVGFontFaceNameElement.cpp
index e989e99..8157a5e 100644
--- a/Source/core/svg/SVGFontFaceNameElement.cpp
+++ b/Source/core/svg/SVGFontFaceNameElement.cpp
@@ -27,14 +27,14 @@
 
 namespace WebCore {
 
-inline SVGFontFaceNameElement::SVGFontFaceNameElement(const QualifiedName& tagName, Document* document)
+inline SVGFontFaceNameElement::SVGFontFaceNameElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::font_face_nameTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFontFaceNameElement> SVGFontFaceNameElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFontFaceNameElement> SVGFontFaceNameElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFontFaceNameElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFontFaceNameElement.h b/Source/core/svg/SVGFontFaceNameElement.h
index 9a1e96d..92cadec 100644
--- a/Source/core/svg/SVGFontFaceNameElement.h
+++ b/Source/core/svg/SVGFontFaceNameElement.h
@@ -29,14 +29,14 @@
 
 class SVGFontFaceNameElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFontFaceNameElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFontFaceNameElement> create(const QualifiedName&, Document&);
 
     PassRefPtr<CSSFontFaceSrcValue> srcValue() const;
 
 private:
-    SVGFontFaceNameElement(const QualifiedName&, Document*);
+    SVGFontFaceNameElement(const QualifiedName&, Document&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFontFaceSrcElement.cpp b/Source/core/svg/SVGFontFaceSrcElement.cpp
index 3a64896..849a2a4 100644
--- a/Source/core/svg/SVGFontFaceSrcElement.cpp
+++ b/Source/core/svg/SVGFontFaceSrcElement.cpp
@@ -33,14 +33,14 @@
 
 using namespace SVGNames;
 
-inline SVGFontFaceSrcElement::SVGFontFaceSrcElement(const QualifiedName& tagName, Document* document)
+inline SVGFontFaceSrcElement::SVGFontFaceSrcElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(font_face_srcTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFontFaceSrcElement> SVGFontFaceSrcElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFontFaceSrcElement> SVGFontFaceSrcElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFontFaceSrcElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGFontFaceSrcElement.h b/Source/core/svg/SVGFontFaceSrcElement.h
index 5f47b8a..eb11d7b 100644
--- a/Source/core/svg/SVGFontFaceSrcElement.h
+++ b/Source/core/svg/SVGFontFaceSrcElement.h
@@ -29,15 +29,15 @@
 
 class SVGFontFaceSrcElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGFontFaceSrcElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFontFaceSrcElement> create(const QualifiedName&, Document&);
 
     PassRefPtr<CSSValueList> srcValue() const;
 
 private:
-    SVGFontFaceSrcElement(const QualifiedName&, Document*);
+    SVGFontFaceSrcElement(const QualifiedName&, Document&);
 
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGFontFaceUriElement.cpp b/Source/core/svg/SVGFontFaceUriElement.cpp
index 94deeff..f5168be 100644
--- a/Source/core/svg/SVGFontFaceUriElement.cpp
+++ b/Source/core/svg/SVGFontFaceUriElement.cpp
@@ -36,14 +36,14 @@
 
 using namespace SVGNames;
 
-inline SVGFontFaceUriElement::SVGFontFaceUriElement(const QualifiedName& tagName, Document* document)
+inline SVGFontFaceUriElement::SVGFontFaceUriElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(font_face_uriTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGFontFaceUriElement> SVGFontFaceUriElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGFontFaceUriElement> SVGFontFaceUriElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGFontFaceUriElement(tagName, document));
 }
@@ -95,8 +95,8 @@
 
     const AtomicString& href = getAttribute(XLinkNames::hrefAttr);
     if (!href.isNull()) {
-        ResourceFetcher* fetcher = document()->fetcher();
-        FetchRequest request(ResourceRequest(document()->completeURL(href)), localName());
+        ResourceFetcher* fetcher = document().fetcher();
+        FetchRequest request(ResourceRequest(document().completeURL(href)), localName());
         m_resource = fetcher->fetchFont(request);
         if (m_resource) {
             m_resource->addClient(this);
diff --git a/Source/core/svg/SVGFontFaceUriElement.h b/Source/core/svg/SVGFontFaceUriElement.h
index 6101a5c..fb4f8c8 100644
--- a/Source/core/svg/SVGFontFaceUriElement.h
+++ b/Source/core/svg/SVGFontFaceUriElement.h
@@ -31,20 +31,20 @@
 
 class SVGFontFaceUriElement FINAL : public SVGElement, public FontResourceClient {
 public:
-    static PassRefPtr<SVGFontFaceUriElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGFontFaceUriElement> create(const QualifiedName&, Document&);
 
     virtual ~SVGFontFaceUriElement();
 
     PassRefPtr<CSSFontFaceSrcValue> srcValue() const;
 
 private:
-    SVGFontFaceUriElement(const QualifiedName&, Document*);
+    SVGFontFaceUriElement(const QualifiedName&, Document&);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     void loadFont();
 
diff --git a/Source/core/svg/SVGForeignObjectElement.cpp b/Source/core/svg/SVGForeignObjectElement.cpp
index 80a895e..e8a99a2 100644
--- a/Source/core/svg/SVGForeignObjectElement.cpp
+++ b/Source/core/svg/SVGForeignObjectElement.cpp
@@ -23,7 +23,6 @@
 
 #include "SVGNames.h"
 #include "XLinkNames.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/rendering/svg/RenderSVGForeignObject.h"
 #include "core/rendering/svg/RenderSVGResource.h"
 #include "core/svg/SVGElementInstance.h"
@@ -50,7 +49,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGForeignObjectElement::SVGForeignObjectElement(const QualifiedName& tagName, Document* document)
+inline SVGForeignObjectElement::SVGForeignObjectElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
@@ -62,7 +61,7 @@
     registerAnimatedPropertiesForSVGForeignObjectElement();
 }
 
-PassRefPtr<SVGForeignObjectElement> SVGForeignObjectElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGForeignObjectElement> SVGForeignObjectElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGForeignObjectElement(tagName, document));
 }
@@ -127,17 +126,17 @@
     return new RenderSVGForeignObject(this);
 }
 
-bool SVGForeignObjectElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGForeignObjectElement::childShouldCreateRenderer(const Node& child) const
 {
     // Disallow arbitary SVG content. Only allow proper <svg xmlns="svgNS"> subdocuments.
-    if (childContext.node()->isSVGElement())
-        return childContext.node()->hasTagName(SVGNames::svgTag);
+    if (child.isSVGElement())
+        return child.hasTagName(SVGNames::svgTag);
 
     // Skip over SVG rules which disallow non-SVG kids
-    return Element::childShouldCreateRenderer(childContext);
+    return Element::childShouldCreateRenderer(child);
 }
 
-bool SVGForeignObjectElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool SVGForeignObjectElement::rendererIsNeeded(const RenderStyle& style)
 {
     // Suppress foreignObject renderers in SVG hidden containers.
     // (https://bugs.webkit.org/show_bug.cgi?id=87297)
@@ -152,7 +151,7 @@
         ancestor = ancestor->parentElement();
     }
 
-    return SVGGraphicsElement::rendererIsNeeded(context);
+    return SVGGraphicsElement::rendererIsNeeded(style);
 }
 
 bool SVGForeignObjectElement::selfHasRelativeLengths() const
diff --git a/Source/core/svg/SVGForeignObjectElement.h b/Source/core/svg/SVGForeignObjectElement.h
index 8b2a536..48dcd35 100644
--- a/Source/core/svg/SVGForeignObjectElement.h
+++ b/Source/core/svg/SVGForeignObjectElement.h
@@ -31,18 +31,18 @@
 class SVGForeignObjectElement FINAL : public SVGGraphicsElement,
                                       public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGForeignObjectElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGForeignObjectElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGForeignObjectElement(const QualifiedName&, Document*);
+    SVGForeignObjectElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
+    virtual bool childShouldCreateRenderer(const Node& child) const;
     virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual bool selfHasRelativeLengths() const;
diff --git a/Source/core/svg/SVGGElement.cpp b/Source/core/svg/SVGGElement.cpp
index b53f0bb..20e2dd8 100644
--- a/Source/core/svg/SVGGElement.cpp
+++ b/Source/core/svg/SVGGElement.cpp
@@ -38,7 +38,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGGElement::SVGGElement(const QualifiedName& tagName, Document* document, ConstructionType constructionType)
+SVGGElement::SVGGElement(const QualifiedName& tagName, Document& document, ConstructionType constructionType)
     : SVGGraphicsElement(tagName, document, constructionType)
 {
     ASSERT(hasTagName(SVGNames::gTag));
@@ -46,7 +46,7 @@
     registerAnimatedPropertiesForSVGGElement();
 }
 
-PassRefPtr<SVGGElement> SVGGElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGGElement> SVGGElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGGElement(tagName, document));
 }
@@ -97,7 +97,7 @@
     return new RenderSVGTransformableContainer(this);
 }
 
-bool SVGGElement::rendererIsNeeded(const NodeRenderingContext&)
+bool SVGGElement::rendererIsNeeded(const RenderStyle&)
 {
     // Unlike SVGElement::rendererIsNeeded(), we still create renderers, even if
     // display is set to 'none' - which is special to SVG <g> container elements.
diff --git a/Source/core/svg/SVGGElement.h b/Source/core/svg/SVGGElement.h
index 9acf1ac..ee1e91a 100644
--- a/Source/core/svg/SVGGElement.h
+++ b/Source/core/svg/SVGGElement.h
@@ -30,10 +30,10 @@
 class SVGGElement FINAL : public SVGGraphicsElement,
                           public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGGElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGGElement> create(const QualifiedName&, Document&);
 
 protected:
-    SVGGElement(const QualifiedName&, Document*, ConstructionType = CreateSVGElement);
+    SVGGElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
 
     virtual RenderObject* createRenderer(RenderStyle*);
 
@@ -45,7 +45,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool rendererIsNeeded(const RenderStyle&);
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGGElement)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
diff --git a/Source/core/svg/SVGGlyphElement.cpp b/Source/core/svg/SVGGlyphElement.cpp
index 31bcc2d..93263a2 100644
--- a/Source/core/svg/SVGGlyphElement.cpp
+++ b/Source/core/svg/SVGGlyphElement.cpp
@@ -31,14 +31,14 @@
 
 namespace WebCore {
 
-inline SVGGlyphElement::SVGGlyphElement(const QualifiedName& tagName, Document* document)
+inline SVGGlyphElement::SVGGlyphElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::glyphTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGGlyphElement> SVGGlyphElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGGlyphElement> SVGGlyphElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGGlyphElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGGlyphElement.h b/Source/core/svg/SVGGlyphElement.h
index 9723787..2598356 100644
--- a/Source/core/svg/SVGGlyphElement.h
+++ b/Source/core/svg/SVGGlyphElement.h
@@ -23,6 +23,7 @@
 #define SVGGlyphElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/platform/graphics/SVGGlyph.h"
 #include "core/svg/SVGElement.h"
 
@@ -32,7 +33,7 @@
 
 class SVGGlyphElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGGlyphElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGGlyphElement> create(const QualifiedName&, Document&);
 
     SVGGlyph buildGlyphIdentifier() const;
 
@@ -44,7 +45,7 @@
     static SVGGlyph buildGenericGlyphIdentifier(const SVGElement*);
 
 private:
-    SVGGlyphElement(const QualifiedName&, Document*);
+    SVGGlyphElement(const QualifiedName&, Document&);
 
     // FIXME: svgAttributeChanged missing.
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -52,11 +53,17 @@
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 
     void invalidateGlyphCache();
 };
 
+inline SVGGlyphElement* toSVGGlyphElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::glyphTag));
+    return static_cast<SVGGlyphElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(SVG_FONTS)
diff --git a/Source/core/svg/SVGGlyphRefElement.cpp b/Source/core/svg/SVGGlyphRefElement.cpp
index 4594e31..159a20b 100644
--- a/Source/core/svg/SVGGlyphRefElement.cpp
+++ b/Source/core/svg/SVGGlyphRefElement.cpp
@@ -37,7 +37,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGGlyphRefElement::SVGGlyphRefElement(const QualifiedName& tagName, Document* document)
+inline SVGGlyphRefElement::SVGGlyphRefElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_x(0)
     , m_y(0)
@@ -49,7 +49,7 @@
     registerAnimatedPropertiesForSVGGlyphRefElement();
 }
 
-PassRefPtr<SVGGlyphRefElement> SVGGlyphRefElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGGlyphRefElement> SVGGlyphRefElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGGlyphRefElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGGlyphRefElement.h b/Source/core/svg/SVGGlyphRefElement.h
index 078e04b..62e1cfe 100644
--- a/Source/core/svg/SVGGlyphRefElement.h
+++ b/Source/core/svg/SVGGlyphRefElement.h
@@ -29,7 +29,7 @@
 class SVGGlyphRefElement FINAL : public SVGElement,
                                  public SVGURIReference {
 public:
-    static PassRefPtr<SVGGlyphRefElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGGlyphRefElement> create(const QualifiedName&, Document&);
 
     bool hasValidGlyphElement(String& glyphName) const;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -47,12 +47,12 @@
     void setDy(float);
 
 private:
-    SVGGlyphRefElement(const QualifiedName&, Document*);
+    SVGGlyphRefElement(const QualifiedName&, Document&);
 
     template<typename CharType>
     void parseAttributeInternal(const QualifiedName&, const AtomicString&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGGlyphRefElement)
         DECLARE_ANIMATED_STRING(Href, href)
diff --git a/Source/core/svg/SVGGradientElement.cpp b/Source/core/svg/SVGGradientElement.cpp
index 17d6658..2b8f617 100644
--- a/Source/core/svg/SVGGradientElement.cpp
+++ b/Source/core/svg/SVGGradientElement.cpp
@@ -53,7 +53,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGGradientElement::SVGGradientElement(const QualifiedName& tagName, Document* document)
+SVGGradientElement::SVGGradientElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_spreadMethod(SVGSpreadMethodPad)
     , m_gradientUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
diff --git a/Source/core/svg/SVGGradientElement.h b/Source/core/svg/SVGGradientElement.h
index 404e586..65f92d0 100644
--- a/Source/core/svg/SVGGradientElement.h
+++ b/Source/core/svg/SVGGradientElement.h
@@ -87,7 +87,7 @@
     Vector<Gradient::ColorStop> buildStops();
 
 protected:
-    SVGGradientElement(const QualifiedName&, Document*);
+    SVGGradientElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGGraphicsElement.cpp b/Source/core/svg/SVGGraphicsElement.cpp
index 42180a9..2fec716 100644
--- a/Source/core/svg/SVGGraphicsElement.cpp
+++ b/Source/core/svg/SVGGraphicsElement.cpp
@@ -40,7 +40,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGGraphicsElement::SVGGraphicsElement(const QualifiedName& tagName, Document* document, ConstructionType constructionType)
+SVGGraphicsElement::SVGGraphicsElement(const QualifiedName& tagName, Document& document, ConstructionType constructionType)
     : SVGElement(tagName, document, constructionType)
 {
     registerAnimatedPropertiesForSVGGraphicsElement();
diff --git a/Source/core/svg/SVGGraphicsElement.h b/Source/core/svg/SVGGraphicsElement.h
index 103a524..d02a8db 100644
--- a/Source/core/svg/SVGGraphicsElement.h
+++ b/Source/core/svg/SVGGraphicsElement.h
@@ -51,7 +51,7 @@
     virtual RenderObject* createRenderer(RenderStyle*);
 
 protected:
-    SVGGraphicsElement(const QualifiedName&, Document*, ConstructionType = CreateSVGElement);
+    SVGGraphicsElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGHKernElement.cpp b/Source/core/svg/SVGHKernElement.cpp
index 70cec60..d927727 100644
--- a/Source/core/svg/SVGHKernElement.cpp
+++ b/Source/core/svg/SVGHKernElement.cpp
@@ -29,14 +29,14 @@
 
 namespace WebCore {
 
-inline SVGHKernElement::SVGHKernElement(const QualifiedName& tagName, Document* document)
+inline SVGHKernElement::SVGHKernElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::hkernTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGHKernElement> SVGHKernElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGHKernElement> SVGHKernElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGHKernElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGHKernElement.h b/Source/core/svg/SVGHKernElement.h
index 6146e97..c60d624 100644
--- a/Source/core/svg/SVGHKernElement.h
+++ b/Source/core/svg/SVGHKernElement.h
@@ -23,25 +23,32 @@
 #define SVGHKernElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/svg/SVGFontElement.h"
 
 namespace WebCore {
 
 class SVGHKernElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGHKernElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGHKernElement> create(const QualifiedName&, Document&);
 
     void buildHorizontalKerningPair(KerningPairVector&);
 
 private:
-    SVGHKernElement(const QualifiedName&, Document*);
+    SVGHKernElement(const QualifiedName&, Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 };
 
+inline SVGHKernElement* toSVGHKernElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::hkernTag));
+    return static_cast<SVGHKernElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(SVG_FONTS)
diff --git a/Source/core/svg/SVGImageElement.cpp b/Source/core/svg/SVGImageElement.cpp
index 33cca0b..d2ce3c0 100644
--- a/Source/core/svg/SVGImageElement.cpp
+++ b/Source/core/svg/SVGImageElement.cpp
@@ -53,7 +53,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGImageElement::SVGImageElement(const QualifiedName& tagName, Document* document)
+inline SVGImageElement::SVGImageElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
@@ -66,11 +66,23 @@
     registerAnimatedPropertiesForSVGImageElement();
 }
 
-PassRefPtr<SVGImageElement> SVGImageElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGImageElement> SVGImageElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGImageElement(tagName, document));
 }
 
+bool SVGImageElement::currentFrameHasSingleSecurityOrigin() const
+{
+    if (RenderSVGImage* renderSVGImage = toRenderSVGImage(renderer())) {
+        if (renderSVGImage->imageResource()->hasImage()) {
+            if (Image* image = renderSVGImage->imageResource()->cachedImage()->image())
+                return image->currentFrameHasSingleSecurityOrigin();
+        }
+    }
+
+    return true;
+}
+
 bool SVGImageElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
@@ -214,16 +226,16 @@
     return InsertionDone;
 }
 
-const AtomicString& SVGImageElement::imageSourceURL() const
+const AtomicString SVGImageElement::imageSourceURL() const
 {
-    return getAttribute(XLinkNames::hrefAttr);
+    return hrefCurrentValue();
 }
 
 void SVGImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
 {
     SVGGraphicsElement::addSubresourceAttributeURLs(urls);
 
-    addSubresourceURL(urls, document()->completeURL(hrefCurrentValue()));
+    addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
 }
 
 void SVGImageElement::didMoveToNewDocument(Document* oldDocument)
diff --git a/Source/core/svg/SVGImageElement.h b/Source/core/svg/SVGImageElement.h
index 1573668..fc4e157 100644
--- a/Source/core/svg/SVGImageElement.h
+++ b/Source/core/svg/SVGImageElement.h
@@ -36,10 +36,12 @@
                               public SVGExternalResourcesRequired,
                               public SVGURIReference {
 public:
-    static PassRefPtr<SVGImageElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGImageElement> create(const QualifiedName&, Document&);
+
+    bool currentFrameHasSingleSecurityOrigin() const;
 
 private:
-    SVGImageElement(const QualifiedName&, Document*);
+    SVGImageElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -55,7 +57,7 @@
 
     virtual RenderObject* createRenderer(RenderStyle*);
 
-    virtual const AtomicString& imageSourceURL() const OVERRIDE;
+    virtual const AtomicString imageSourceURL() const OVERRIDE;
     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
 
     virtual bool haveLoadedRequiredResources();
diff --git a/Source/core/svg/SVGImageLoader.cpp b/Source/core/svg/SVGImageLoader.cpp
index 7ab088e..6b503e2 100644
--- a/Source/core/svg/SVGImageLoader.cpp
+++ b/Source/core/svg/SVGImageLoader.cpp
@@ -51,7 +51,7 @@
     KURL base = element()->baseURI();
     if (base.isValid())
         return KURL(base, stripLeadingAndTrailingHTMLSpaces(attribute)).string();
-    return element()->document()->completeURL(stripLeadingAndTrailingHTMLSpaces(attribute));
+    return element()->document().completeURL(stripLeadingAndTrailingHTMLSpaces(attribute));
 }
 
 }
diff --git a/Source/core/svg/SVGLengthContext.cpp b/Source/core/svg/SVGLengthContext.cpp
index 7f214a3..1c8ed6a 100644
--- a/Source/core/svg/SVGLengthContext.cpp
+++ b/Source/core/svg/SVGLengthContext.cpp
@@ -27,7 +27,6 @@
 #include "bindings/v8/ExceptionState.h"
 #include "core/css/CSSHelper.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/page/Frame.h"
 #include "core/platform/graphics/FontMetrics.h"
 #include "core/rendering/RenderPart.h"
 #include "core/rendering/RenderView.h"
@@ -294,7 +293,7 @@
 
     // SVGLengthContext should NEVER be used to resolve width/height values for <svg> elements,
     // as they require special treatment, due the relationship with the CSS width/height properties.
-    ASSERT(m_context->document()->documentElement() != m_context);
+    ASSERT(m_context->document().documentElement() != m_context);
 
     // Take size from nearest viewport element.
     SVGElement* viewportElement = m_context->viewportElement();
diff --git a/Source/core/svg/SVGLineElement.cpp b/Source/core/svg/SVGLineElement.cpp
index c699f21..fe21256 100644
--- a/Source/core/svg/SVGLineElement.cpp
+++ b/Source/core/svg/SVGLineElement.cpp
@@ -45,7 +45,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGLineElement::SVGLineElement(const QualifiedName& tagName, Document* document)
+inline SVGLineElement::SVGLineElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
     , m_x1(LengthModeWidth)
     , m_y1(LengthModeHeight)
@@ -57,7 +57,7 @@
     registerAnimatedPropertiesForSVGLineElement();
 }
 
-PassRefPtr<SVGLineElement> SVGLineElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGLineElement> SVGLineElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGLineElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGLineElement.h b/Source/core/svg/SVGLineElement.h
index c1e8a51..af514be 100644
--- a/Source/core/svg/SVGLineElement.h
+++ b/Source/core/svg/SVGLineElement.h
@@ -32,10 +32,10 @@
 class SVGLineElement FINAL : public SVGGraphicsElement,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGLineElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGLineElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGLineElement(const QualifiedName&, Document*);
+    SVGLineElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGLinearGradientElement.cpp b/Source/core/svg/SVGLinearGradientElement.cpp
index 5d5a807..cd1d6ea 100644
--- a/Source/core/svg/SVGLinearGradientElement.cpp
+++ b/Source/core/svg/SVGLinearGradientElement.cpp
@@ -48,7 +48,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGradientElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGLinearGradientElement::SVGLinearGradientElement(const QualifiedName& tagName, Document* document)
+inline SVGLinearGradientElement::SVGLinearGradientElement(const QualifiedName& tagName, Document& document)
     : SVGGradientElement(tagName, document)
     , m_x1(LengthModeWidth)
     , m_y1(LengthModeHeight)
@@ -61,7 +61,7 @@
     registerAnimatedPropertiesForSVGLinearGradientElement();
 }
 
-PassRefPtr<SVGLinearGradientElement> SVGLinearGradientElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGLinearGradientElement> SVGLinearGradientElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGLinearGradientElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGLinearGradientElement.h b/Source/core/svg/SVGLinearGradientElement.h
index c80d6ff..7f5f5eb 100644
--- a/Source/core/svg/SVGLinearGradientElement.h
+++ b/Source/core/svg/SVGLinearGradientElement.h
@@ -31,12 +31,12 @@
 
 class SVGLinearGradientElement FINAL : public SVGGradientElement {
 public:
-    static PassRefPtr<SVGLinearGradientElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGLinearGradientElement> create(const QualifiedName&, Document&);
 
     bool collectGradientAttributes(LinearGradientAttributes&);
 
 private:
-    SVGLinearGradientElement(const QualifiedName&, Document*);
+    SVGLinearGradientElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGLocatable.cpp b/Source/core/svg/SVGLocatable.cpp
index e8ce64a..c3354c9 100644
--- a/Source/core/svg/SVGLocatable.cpp
+++ b/Source/core/svg/SVGLocatable.cpp
@@ -65,7 +65,7 @@
 {
     ASSERT(element);
     if (styleUpdateStrategy == AllowStyleUpdate)
-        element->document()->updateLayoutIgnorePendingStylesheets();
+        element->document().updateLayoutIgnorePendingStylesheets();
 
     // FIXME: Eventually we should support getBBox for detached elements.
     if (!element->renderer())
@@ -78,7 +78,7 @@
 {
     ASSERT(element);
     if (styleUpdateStrategy == AllowStyleUpdate)
-        element->document()->updateLayoutIgnorePendingStylesheets();
+        element->document().updateLayoutIgnorePendingStylesheets();
 
     AffineTransform ctm;
 
diff --git a/Source/core/svg/SVGMPathElement.cpp b/Source/core/svg/SVGMPathElement.cpp
index 5930ccc..b766818 100644
--- a/Source/core/svg/SVGMPathElement.cpp
+++ b/Source/core/svg/SVGMPathElement.cpp
@@ -39,7 +39,7 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGMPathElement::SVGMPathElement(const QualifiedName& tagName, Document* document)
+inline SVGMPathElement::SVGMPathElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::mpathTag));
@@ -47,7 +47,7 @@
     registerAnimatedPropertiesForSVGMPathElement();
 }
 
-PassRefPtr<SVGMPathElement> SVGMPathElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGMPathElement> SVGMPathElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGMPathElement(tagName, document));
 }
@@ -67,17 +67,17 @@
     Element* target = SVGURIReference::targetElementFromIRIString(hrefCurrentValue(), document(), &id);
     if (!target) {
         // Do not register as pending if we are already pending this resource.
-        if (document()->accessSVGExtensions()->isElementPendingResource(this, id))
+        if (document().accessSVGExtensions()->isElementPendingResource(this, id))
             return;
 
         if (!id.isEmpty()) {
-            document()->accessSVGExtensions()->addPendingResource(id, this);
+            document().accessSVGExtensions()->addPendingResource(id, this);
             ASSERT(hasPendingResources());
         }
     } else if (target->isSVGElement()) {
         // Register us with the target in the dependencies map. Any change of hrefElement
         // that leads to relayout/repainting now informs us, so we can react to it.
-        document()->accessSVGExtensions()->addElementReferencingTarget(this, toSVGElement(target));
+        document().accessSVGExtensions()->addElementReferencingTarget(this, toSVGElement(target));
     }
 
     targetPathChanged();
@@ -85,8 +85,7 @@
 
 void SVGMPathElement::clearResourceReferences()
 {
-    ASSERT(document());
-    document()->accessSVGExtensions()->removeAllTargetReferencesForElement(this);
+    document().accessSVGExtensions()->removeAllTargetReferencesForElement(this);
 }
 
 Node::InsertionNotificationRequest SVGMPathElement::insertedInto(ContainerNode* rootParent)
diff --git a/Source/core/svg/SVGMPathElement.h b/Source/core/svg/SVGMPathElement.h
index bd412a8..62e50a5 100644
--- a/Source/core/svg/SVGMPathElement.h
+++ b/Source/core/svg/SVGMPathElement.h
@@ -35,7 +35,7 @@
                               public SVGURIReference,
                               public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGMPathElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGMPathElement> create(const QualifiedName&, Document&);
 
     virtual ~SVGMPathElement();
 
@@ -44,7 +44,7 @@
     void targetPathChanged();
 
 private:
-    SVGMPathElement(const QualifiedName&, Document*);
+    SVGMPathElement(const QualifiedName&, Document&);
 
     void buildPendingResource();
     void clearResourceReferences();
@@ -55,7 +55,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
     void notifyParentOfPathChange(ContainerNode*);
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGMPathElement)
diff --git a/Source/core/svg/SVGMarkerElement.cpp b/Source/core/svg/SVGMarkerElement.cpp
index f872911..9c62bac 100644
--- a/Source/core/svg/SVGMarkerElement.cpp
+++ b/Source/core/svg/SVGMarkerElement.cpp
@@ -70,7 +70,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGMarkerElement::SVGMarkerElement(const QualifiedName& tagName, Document* document)
+inline SVGMarkerElement::SVGMarkerElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_refX(LengthModeWidth)
     , m_refY(LengthModeHeight)
@@ -85,7 +85,7 @@
     registerAnimatedPropertiesForSVGMarkerElement();
 }
 
-PassRefPtr<SVGMarkerElement> SVGMarkerElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGMarkerElement> SVGMarkerElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGMarkerElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGMarkerElement.h b/Source/core/svg/SVGMarkerElement.h
index 3372c3b..05e50e2 100644
--- a/Source/core/svg/SVGMarkerElement.h
+++ b/Source/core/svg/SVGMarkerElement.h
@@ -111,7 +111,7 @@
         SVG_MARKER_ORIENT_ANGLE = SVGMarkerOrientAngle
     };
 
-    static PassRefPtr<SVGMarkerElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGMarkerElement> create(const QualifiedName&, Document&);
 
     AffineTransform viewBoxToViewTransform(float viewWidth, float viewHeight) const;
 
@@ -121,7 +121,7 @@
     static const SVGPropertyInfo* orientTypePropertyInfo();
 
 private:
-    SVGMarkerElement(const QualifiedName&, Document*);
+    SVGMarkerElement(const QualifiedName&, Document&);
 
     virtual bool needsPendingResourceHandling() const { return false; }
 
@@ -131,7 +131,7 @@
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return true; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return true; }
 
     virtual bool selfHasRelativeLengths() const;
 
diff --git a/Source/core/svg/SVGMaskElement.cpp b/Source/core/svg/SVGMaskElement.cpp
index 2726fc1..ecae018 100644
--- a/Source/core/svg/SVGMaskElement.cpp
+++ b/Source/core/svg/SVGMaskElement.cpp
@@ -53,7 +53,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGMaskElement::SVGMaskElement(const QualifiedName& tagName, Document* document)
+inline SVGMaskElement::SVGMaskElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_maskUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
     , m_maskContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
@@ -69,7 +69,7 @@
     registerAnimatedPropertiesForSVGMaskElement();
 }
 
-PassRefPtr<SVGMaskElement> SVGMaskElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGMaskElement> SVGMaskElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGMaskElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGMaskElement.h b/Source/core/svg/SVGMaskElement.h
index 6d120bc..dd4043a 100644
--- a/Source/core/svg/SVGMaskElement.h
+++ b/Source/core/svg/SVGMaskElement.h
@@ -35,10 +35,10 @@
                              public SVGTests,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGMaskElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGMaskElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGMaskElement(const QualifiedName&, Document*);
+    SVGMaskElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool needsPendingResourceHandling() const { return false; }
diff --git a/Source/core/svg/SVGMetadataElement.cpp b/Source/core/svg/SVGMetadataElement.cpp
index a8432b1..a02eb31 100644
--- a/Source/core/svg/SVGMetadataElement.cpp
+++ b/Source/core/svg/SVGMetadataElement.cpp
@@ -24,14 +24,14 @@
 
 namespace WebCore {
 
-inline SVGMetadataElement::SVGMetadataElement(const QualifiedName& tagName, Document* document)
+inline SVGMetadataElement::SVGMetadataElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::metadataTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGMetadataElement> SVGMetadataElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGMetadataElement> SVGMetadataElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGMetadataElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGMetadataElement.h b/Source/core/svg/SVGMetadataElement.h
index 736e3b3..596f317 100644
--- a/Source/core/svg/SVGMetadataElement.h
+++ b/Source/core/svg/SVGMetadataElement.h
@@ -27,12 +27,12 @@
 
 class SVGMetadataElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGMetadataElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGMetadataElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGMetadataElement(const QualifiedName&, Document*);
+    SVGMetadataElement(const QualifiedName&, Document&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGMissingGlyphElement.cpp b/Source/core/svg/SVGMissingGlyphElement.cpp
index 893ff75..f426e6b 100644
--- a/Source/core/svg/SVGMissingGlyphElement.cpp
+++ b/Source/core/svg/SVGMissingGlyphElement.cpp
@@ -25,14 +25,14 @@
 
 namespace WebCore {
 
-inline SVGMissingGlyphElement::SVGMissingGlyphElement(const QualifiedName& tagName, Document* document)
+inline SVGMissingGlyphElement::SVGMissingGlyphElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::missing_glyphTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGMissingGlyphElement> SVGMissingGlyphElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGMissingGlyphElement> SVGMissingGlyphElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGMissingGlyphElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGMissingGlyphElement.h b/Source/core/svg/SVGMissingGlyphElement.h
index 9437431..6ff776d 100644
--- a/Source/core/svg/SVGMissingGlyphElement.h
+++ b/Source/core/svg/SVGMissingGlyphElement.h
@@ -28,12 +28,12 @@
 
 class SVGMissingGlyphElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGMissingGlyphElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGMissingGlyphElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGMissingGlyphElement(const QualifiedName&, Document*);
+    SVGMissingGlyphElement(const QualifiedName&, Document&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 };
 
 inline SVGMissingGlyphElement* toSVGMissingGlyphElement(Node* node)
diff --git a/Source/core/svg/SVGPathElement.cpp b/Source/core/svg/SVGPathElement.cpp
index 8d16bbf..33b20a2 100644
--- a/Source/core/svg/SVGPathElement.cpp
+++ b/Source/core/svg/SVGPathElement.cpp
@@ -78,7 +78,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGPathElement::SVGPathElement(const QualifiedName& tagName, Document* document)
+inline SVGPathElement::SVGPathElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
     , m_pathByteStream(SVGPathByteStream::create())
     , m_pathSegList(PathSegUnalteredRole)
@@ -89,7 +89,7 @@
     registerAnimatedPropertiesForSVGPathElement();
 }
 
-PassRefPtr<SVGPathElement> SVGPathElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGPathElement> SVGPathElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGPathElement(tagName, document));
 }
@@ -230,14 +230,14 @@
 
     if (name == SVGNames::dAttr) {
         if (!buildSVGPathByteStreamFromString(value, m_pathByteStream.get(), UnalteredParsing))
-            document()->accessSVGExtensions()->reportError("Problem parsing d=\"" + value + "\"");
+            document().accessSVGExtensions()->reportError("Problem parsing d=\"" + value + "\"");
         return;
     }
 
     if (name == SVGNames::pathLengthAttr) {
         setPathLengthBaseValue(value.toFloat());
         if (pathLengthBaseValue() < 0)
-            document()->accessSVGExtensions()->reportError("A negative value for path attribute <pathLength> is not allowed");
+            document().accessSVGExtensions()->reportError("A negative value for path attribute <pathLength> is not allowed");
         return;
     }
 
@@ -279,8 +279,7 @@
 {
     // <mpath> can only reference <path> but this dependency is not handled in
     // markForLayoutAndParentResourceInvalidation so we update any mpath dependencies manually.
-    ASSERT(document());
-    if (HashSet<SVGElement*>* dependencies = document()->accessSVGExtensions()->setOfElementsReferencingTarget(this)) {
+    if (HashSet<SVGElement*>* dependencies = document().accessSVGExtensions()->setOfElementsReferencingTarget(this)) {
         HashSet<SVGElement*>::iterator end = dependencies->end();
         for (HashSet<SVGElement*>::iterator it = dependencies->begin(); it != end; ++it) {
             if ((*it)->hasTagName(SVGNames::mpathTag))
@@ -389,7 +388,7 @@
 FloatRect SVGPathElement::getBBox(StyleUpdateStrategy styleUpdateStrategy)
 {
     if (styleUpdateStrategy == AllowStyleUpdate)
-        this->document()->updateLayoutIgnorePendingStylesheets();
+        this->document().updateLayoutIgnorePendingStylesheets();
 
     RenderSVGPath* renderer = toRenderSVGPath(this->renderer());
 
diff --git a/Source/core/svg/SVGPathElement.h b/Source/core/svg/SVGPathElement.h
index 6e1ea50..3065a0e 100644
--- a/Source/core/svg/SVGPathElement.h
+++ b/Source/core/svg/SVGPathElement.h
@@ -55,7 +55,7 @@
 class SVGPathElement FINAL : public SVGGraphicsElement,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGPathElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGPathElement> create(const QualifiedName&, Document&);
 
     float getTotalLength();
     SVGPoint getPointAtLength(float distance);
@@ -98,7 +98,7 @@
     bool isAnimValObserved() const { return m_isAnimValObserved; }
 
 private:
-    SVGPathElement(const QualifiedName&, Document*);
+    SVGPathElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGPatternElement.cpp b/Source/core/svg/SVGPatternElement.cpp
index aeedfb4..0fdf163 100644
--- a/Source/core/svg/SVGPatternElement.cpp
+++ b/Source/core/svg/SVGPatternElement.cpp
@@ -62,7 +62,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGPatternElement::SVGPatternElement(const QualifiedName& tagName, Document* document)
+inline SVGPatternElement::SVGPatternElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
@@ -76,7 +76,7 @@
     registerAnimatedPropertiesForSVGPatternElement();
 }
 
-PassRefPtr<SVGPatternElement> SVGPatternElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGPatternElement> SVGPatternElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGPatternElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGPatternElement.h b/Source/core/svg/SVGPatternElement.h
index ac3d502..2afb90d 100644
--- a/Source/core/svg/SVGPatternElement.h
+++ b/Source/core/svg/SVGPatternElement.h
@@ -45,14 +45,14 @@
                                 public SVGExternalResourcesRequired,
                                 public SVGFitToViewBox {
 public:
-    static PassRefPtr<SVGPatternElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGPatternElement> create(const QualifiedName&, Document&);
 
     void collectPatternAttributes(PatternAttributes&) const;
 
     virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;
 
 private:
-    SVGPatternElement(const QualifiedName&, Document*);
+    SVGPatternElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool needsPendingResourceHandling() const { return false; }
diff --git a/Source/core/svg/SVGPolyElement.cpp b/Source/core/svg/SVGPolyElement.cpp
index 78c95aa..a6eec9b 100644
--- a/Source/core/svg/SVGPolyElement.cpp
+++ b/Source/core/svg/SVGPolyElement.cpp
@@ -55,7 +55,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGPolyElement::SVGPolyElement(const QualifiedName& tagName, Document* document)
+SVGPolyElement::SVGPolyElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
 {
     registerAnimatedPropertiesForSVGPolyElement();
@@ -82,7 +82,7 @@
     if (name == SVGNames::pointsAttr) {
         SVGPointList newList;
         if (!pointsListFromSVGData(newList, value))
-            document()->accessSVGExtensions()->reportError("Problem parsing points=\"" + value + "\"");
+            document().accessSVGExtensions()->reportError("Problem parsing points=\"" + value + "\"");
 
         if (SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGPolyElement, SVGAnimatedPointList>(this, pointsPropertyInfo()))
             static_cast<SVGAnimatedPointList*>(wrapper)->detachListWrappers(newList.size());
diff --git a/Source/core/svg/SVGPolyElement.h b/Source/core/svg/SVGPolyElement.h
index f7bb439..617de15 100644
--- a/Source/core/svg/SVGPolyElement.h
+++ b/Source/core/svg/SVGPolyElement.h
@@ -40,7 +40,7 @@
     static const SVGPropertyInfo* pointsPropertyInfo();
 
 protected:
-    SVGPolyElement(const QualifiedName&, Document*);
+    SVGPolyElement(const QualifiedName&, Document&);
 
 private:
     virtual bool isValid() const { return SVGTests::isValid(); }
diff --git a/Source/core/svg/SVGPolygonElement.cpp b/Source/core/svg/SVGPolygonElement.cpp
index 8888126..28175e4 100644
--- a/Source/core/svg/SVGPolygonElement.cpp
+++ b/Source/core/svg/SVGPolygonElement.cpp
@@ -25,14 +25,14 @@
 
 namespace WebCore {
 
-inline SVGPolygonElement::SVGPolygonElement(const QualifiedName& tagName, Document* document)
+inline SVGPolygonElement::SVGPolygonElement(const QualifiedName& tagName, Document& document)
     : SVGPolyElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::polygonTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGPolygonElement> SVGPolygonElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGPolygonElement> SVGPolygonElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGPolygonElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGPolygonElement.h b/Source/core/svg/SVGPolygonElement.h
index dfa85d7..0076f64 100644
--- a/Source/core/svg/SVGPolygonElement.h
+++ b/Source/core/svg/SVGPolygonElement.h
@@ -28,10 +28,10 @@
 
 class SVGPolygonElement FINAL : public SVGPolyElement {
 public:
-    static PassRefPtr<SVGPolygonElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGPolygonElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGPolygonElement(const QualifiedName&, Document*);
+    SVGPolygonElement(const QualifiedName&, Document&);
 };
 
 inline SVGPolygonElement* toSVGPolygonElement(Node* node)
diff --git a/Source/core/svg/SVGPolylineElement.cpp b/Source/core/svg/SVGPolylineElement.cpp
index a770f8c..15b878d 100644
--- a/Source/core/svg/SVGPolylineElement.cpp
+++ b/Source/core/svg/SVGPolylineElement.cpp
@@ -25,14 +25,14 @@
 
 namespace WebCore {
 
-inline SVGPolylineElement::SVGPolylineElement(const QualifiedName& tagName, Document* document)
+inline SVGPolylineElement::SVGPolylineElement(const QualifiedName& tagName, Document& document)
     : SVGPolyElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::polylineTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGPolylineElement> SVGPolylineElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGPolylineElement> SVGPolylineElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGPolylineElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGPolylineElement.h b/Source/core/svg/SVGPolylineElement.h
index 3f64854..fe1a5c0 100644
--- a/Source/core/svg/SVGPolylineElement.h
+++ b/Source/core/svg/SVGPolylineElement.h
@@ -21,18 +21,25 @@
 #ifndef SVGPolylineElement_h
 #define SVGPolylineElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGPolyElement.h"
 
 namespace WebCore {
 
 class SVGPolylineElement FINAL : public SVGPolyElement {
 public:
-    static PassRefPtr<SVGPolylineElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGPolylineElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGPolylineElement(const QualifiedName&, Document*);
+    SVGPolylineElement(const QualifiedName&, Document&);
 };
 
+inline SVGPolylineElement* toSVGPolylineElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::polylineTag));
+    return static_cast<SVGPolylineElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGRadialGradientElement.cpp b/Source/core/svg/SVGRadialGradientElement.cpp
index 4929cc2..cb286b1 100644
--- a/Source/core/svg/SVGRadialGradientElement.cpp
+++ b/Source/core/svg/SVGRadialGradientElement.cpp
@@ -51,7 +51,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGradientElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGRadialGradientElement::SVGRadialGradientElement(const QualifiedName& tagName, Document* document)
+inline SVGRadialGradientElement::SVGRadialGradientElement(const QualifiedName& tagName, Document& document)
     : SVGGradientElement(tagName, document)
     , m_cx(LengthModeWidth, "50%")
     , m_cy(LengthModeHeight, "50%")
@@ -66,7 +66,7 @@
     registerAnimatedPropertiesForSVGRadialGradientElement();
 }
 
-PassRefPtr<SVGRadialGradientElement> SVGRadialGradientElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGRadialGradientElement> SVGRadialGradientElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGRadialGradientElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGRadialGradientElement.h b/Source/core/svg/SVGRadialGradientElement.h
index 20be564..4b7c376 100644
--- a/Source/core/svg/SVGRadialGradientElement.h
+++ b/Source/core/svg/SVGRadialGradientElement.h
@@ -31,12 +31,12 @@
 
 class SVGRadialGradientElement FINAL : public SVGGradientElement {
 public:
-    static PassRefPtr<SVGRadialGradientElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGRadialGradientElement> create(const QualifiedName&, Document&);
 
     bool collectGradientAttributes(RadialGradientAttributes&);
 
 private:
-    SVGRadialGradientElement(const QualifiedName&, Document*);
+    SVGRadialGradientElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGRectElement.cpp b/Source/core/svg/SVGRectElement.cpp
index 6838a48..2f0e12c 100644
--- a/Source/core/svg/SVGRectElement.cpp
+++ b/Source/core/svg/SVGRectElement.cpp
@@ -50,7 +50,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGRectElement::SVGRectElement(const QualifiedName& tagName, Document* document)
+inline SVGRectElement::SVGRectElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
@@ -64,7 +64,7 @@
     registerAnimatedPropertiesForSVGRectElement();
 }
 
-PassRefPtr<SVGRectElement> SVGRectElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGRectElement> SVGRectElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGRectElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGRectElement.h b/Source/core/svg/SVGRectElement.h
index eaf2c1f..2c631b8 100644
--- a/Source/core/svg/SVGRectElement.h
+++ b/Source/core/svg/SVGRectElement.h
@@ -32,10 +32,10 @@
 class SVGRectElement FINAL : public SVGGraphicsElement,
                              public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGRectElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGRectElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGRectElement(const QualifiedName&, Document*);
+    SVGRectElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/Source/core/svg/SVGSVGElement.cpp b/Source/core/svg/SVGSVGElement.cpp
index 708e209..4f4638c 100644
--- a/Source/core/svg/SVGSVGElement.cpp
+++ b/Source/core/svg/SVGSVGElement.cpp
@@ -37,6 +37,7 @@
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/page/FrameView.h"
+#include "core/page/UseCounter.h"
 #include "core/platform/FloatConversion.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/transforms/AffineTransform.h"
@@ -79,7 +80,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGSVGElement::SVGSVGElement(const QualifiedName& tagName, Document* doc)
+inline SVGSVGElement::SVGSVGElement(const QualifiedName& tagName, Document& doc)
     : SVGGraphicsElement(tagName, doc)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
@@ -92,9 +93,11 @@
     ASSERT(hasTagName(SVGNames::svgTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGSVGElement();
+
+    UseCounter::count(&doc, UseCounter::SVGSVGElement);
 }
 
-PassRefPtr<SVGSVGElement> SVGSVGElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGSVGElement> SVGSVGElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGSVGElement(tagName, document));
 }
@@ -105,7 +108,7 @@
         m_viewSpec->resetContextElement();
     // There are cases where removedFromDocument() is not called.
     // see ContainerNode::removeAllChildren, called by its destructor.
-    document()->accessSVGExtensions()->removeTimeContainer(this);
+    document().accessSVGExtensions()->removeTimeContainer(this);
 }
 
 const AtomicString& SVGSVGElement::contentScriptType() const
@@ -173,7 +176,7 @@
     if (!inDocument() || !isOutermostSVGSVGElement())
         return 1;
 
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return 1;
 
@@ -191,7 +194,7 @@
     if (!inDocument() || !isOutermostSVGSVGElement())
         return;
 
-    Frame* frame = document()->frame();
+    Frame* frame = document().frame();
     if (!frame)
         return;
 
@@ -218,8 +221,8 @@
     if (RenderObject* object = renderer())
         object->setNeedsLayout();
 
-    if (parentNode() == document() && document()->renderer())
-        document()->renderer()->repaint();
+    if (parentNode() == &document() && document().renderer())
+        document().renderer()->repaint();
 }
 
 void SVGSVGElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -231,13 +234,13 @@
 
         // Only handle events if we're the outermost <svg> element
         if (name == HTMLNames::onunloadAttr)
-            document()->setWindowAttributeEventListener(eventNames().unloadEvent, createAttributeEventListener(document()->frame(), name, value));
+            document().setWindowAttributeEventListener(eventNames().unloadEvent, createAttributeEventListener(document().frame(), name, value));
         else if (name == HTMLNames::onresizeAttr)
-            document()->setWindowAttributeEventListener(eventNames().resizeEvent, createAttributeEventListener(document()->frame(), name, value));
+            document().setWindowAttributeEventListener(eventNames().resizeEvent, createAttributeEventListener(document().frame(), name, value));
         else if (name == HTMLNames::onscrollAttr)
-            document()->setWindowAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(document()->frame(), name, value));
+            document().setWindowAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(document().frame(), name, value));
         else if (name == SVGNames::onzoomAttr)
-            document()->setWindowAttributeEventListener(eventNames().zoomEvent, createAttributeEventListener(document()->frame(), name, value));
+            document().setWindowAttributeEventListener(eventNames().zoomEvent, createAttributeEventListener(document().frame(), name, value));
         else
             setListener = false;
 
@@ -246,9 +249,9 @@
     }
 
     if (name == HTMLNames::onabortAttr)
-        document()->setWindowAttributeEventListener(eventNames().abortEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().abortEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == HTMLNames::onerrorAttr)
-        document()->setWindowAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(document()->frame(), name, value));
+        document().setWindowAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(document().frame(), name, value));
     else if (name == SVGNames::xAttr)
         setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::yAttr)
@@ -375,8 +378,8 @@
 
 void SVGSVGElement::deselectAll()
 {
-    if (Frame* frame = document()->frame())
-        frame->selection()->clear();
+    if (Frame* frame = document().frame())
+        frame->selection().clear();
 }
 
 float SVGSVGElement::createSVGNumber()
@@ -455,7 +458,7 @@
             transform.translate(location.x() - viewBoxTransform.e(), location.y() - viewBoxTransform.f());
 
             // Respect scroll offset.
-            if (FrameView* view = document()->view()) {
+            if (FrameView* view = document().view()) {
                 LayoutSize scrollOffset = view->scrollOffset();
                 scrollOffset.scale(zoomFactor);
                 transform.translate(-scrollOffset.width(), -scrollOffset.height());
@@ -466,15 +469,15 @@
     return transform.multiply(viewBoxTransform);
 }
 
-bool SVGSVGElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool SVGSVGElement::rendererIsNeeded(const RenderStyle& style)
 {
     // FIXME: We should respect display: none on the documentElement svg element
     // but many things in FrameView and SVGImage depend on the RenderSVGRoot when
     // they should instead depend on the RenderView.
     // https://bugs.webkit.org/show_bug.cgi?id=103493
-    if (document()->documentElement() == this)
+    if (document().documentElement() == this)
         return true;
-    return Element::rendererIsNeeded(context);
+    return Element::rendererIsNeeded(style);
 }
 
 RenderObject* SVGSVGElement::createRenderer(RenderStyle*)
@@ -488,12 +491,12 @@
 Node::InsertionNotificationRequest SVGSVGElement::insertedInto(ContainerNode* rootParent)
 {
     if (rootParent->inDocument()) {
-        document()->accessSVGExtensions()->addTimeContainer(this);
+        document().accessSVGExtensions()->addTimeContainer(this);
 
         // Animations are started at the end of document parsing and after firing the load event,
         // but if we miss that train (deferred programmatic element insertion for example) we need
         // to initialize the time container here.
-        if (!document()->parsing() && !document()->processingLoadEvent() && document()->loadEventFinished() && !timeContainer()->isStarted())
+        if (!document().parsing() && !document().processingLoadEvent() && document().loadEventFinished() && !timeContainer()->isStarted())
             timeContainer()->begin();
     }
     return SVGGraphicsElement::insertedInto(rootParent);
@@ -502,7 +505,7 @@
 void SVGSVGElement::removedFrom(ContainerNode* rootParent)
 {
     if (rootParent->inDocument())
-        document()->accessSVGExtensions()->removeTimeContainer(this);
+        document().accessSVGExtensions()->removeTimeContainer(this);
     SVGGraphicsElement::removedFrom(rootParent);
 }
 
@@ -604,10 +607,10 @@
 
     // SVG embedded through object/embed/iframe.
     if (root->isEmbeddedThroughFrameContainingSVGDocument())
-        return !root->hasReplacedLogicalWidth() && !document()->frame()->ownerRenderer()->hasReplacedLogicalWidth();
+        return !root->hasReplacedLogicalWidth() && !document().frame()->ownerRenderer()->hasReplacedLogicalWidth();
 
     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
-    if (root->isEmbeddedThroughSVGImage() || document()->documentElement() != this)
+    if (root->isEmbeddedThroughSVGImage() || document().documentElement() != this)
         return !root->hasReplacedLogicalWidth();
 
     return true;
@@ -626,10 +629,10 @@
 
     // SVG embedded through object/embed/iframe.
     if (root->isEmbeddedThroughFrameContainingSVGDocument())
-        return !root->hasReplacedLogicalHeight() && !document()->frame()->ownerRenderer()->hasReplacedLogicalHeight();
+        return !root->hasReplacedLogicalHeight() && !document().frame()->ownerRenderer()->hasReplacedLogicalHeight();
 
     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
-    if (root->isEmbeddedThroughSVGImage() || document()->documentElement() != this)
+    if (root->isEmbeddedThroughSVGImage() || document().documentElement() != this)
         return !root->hasReplacedLogicalHeight();
 
     return true;
@@ -716,17 +719,18 @@
     // Any view specification attributes included on the given ‘view’ element override the corresponding view specification
     // attributes on the closest ancestor ‘svg’ element.
     if (anchorNode && anchorNode->hasTagName(SVGNames::viewTag)) {
-        if (SVGViewElement* viewElement = anchorNode->hasTagName(SVGNames::viewTag) ? static_cast<SVGViewElement*>(anchorNode) : 0) {
-            SVGElement* element = SVGLocatable::nearestViewportElement(viewElement);
-            if (element->hasTagName(SVGNames::svgTag)) {
-                SVGSVGElement* svg = toSVGSVGElement(element);
-                svg->inheritViewAttributes(viewElement);
+        SVGViewElement* viewElement = toSVGViewElement(anchorNode);
+        if (!viewElement)
+            return;
 
-                if (RenderObject* renderer = svg->renderer())
-                    RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
-            }
+        SVGElement* element = SVGLocatable::nearestViewportElement(viewElement);
+        if (element->hasTagName(SVGNames::svgTag)) {
+            SVGSVGElement* svg = toSVGSVGElement(element);
+            svg->inheritViewAttributes(viewElement);
+
+            if (RenderObject* renderer = svg->renderer())
+                RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
         }
-        return;
     }
 
     // FIXME: We need to decide which <svg> to focus on, and zoom to it.
@@ -758,7 +762,7 @@
 // See http://www.w3.org/TR/SVG11/struct.html#InterfaceSVGSVGElement
 Element* SVGSVGElement::getElementById(const AtomicString& id) const
 {
-    Element* element = treeScope()->getElementById(id);
+    Element* element = treeScope().getElementById(id);
     if (element && element->isDescendantOf(this))
         return element;
 
diff --git a/Source/core/svg/SVGSVGElement.h b/Source/core/svg/SVGSVGElement.h
index fca2053..54b39de 100644
--- a/Source/core/svg/SVGSVGElement.h
+++ b/Source/core/svg/SVGSVGElement.h
@@ -44,7 +44,7 @@
                             public SVGFitToViewBox,
                             public SVGZoomAndPan {
 public:
-    static PassRefPtr<SVGSVGElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGSVGElement> create(const QualifiedName&, Document&);
 
     using SVGGraphicsElement::ref;
     using SVGGraphicsElement::deref;
@@ -133,14 +133,14 @@
     bool hasEmptyViewBox() const { return viewBoxIsValid() && viewBoxCurrentValue().isEmpty(); }
 
 private:
-    SVGSVGElement(const QualifiedName&, Document*);
+    SVGSVGElement(const QualifiedName&, Document&);
     virtual ~SVGSVGElement();
 
     virtual bool isSVGSVGElement() const OVERRIDE { return true; }
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
     virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
@@ -180,11 +180,16 @@
 
 inline SVGSVGElement* toSVGSVGElement(Node* node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isSVGElement());
     ASSERT_WITH_SECURITY_IMPLICATION(!node || toSVGElement(node)->isSVGSVGElement());
     return static_cast<SVGSVGElement*>(node);
 }
 
+inline const SVGSVGElement* toSVGSVGElement(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || toSVGElement(node)->isSVGSVGElement());
+    return static_cast<const SVGSVGElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGScriptElement.cpp b/Source/core/svg/SVGScriptElement.cpp
index 2441228..c7d8482 100644
--- a/Source/core/svg/SVGScriptElement.cpp
+++ b/Source/core/svg/SVGScriptElement.cpp
@@ -43,7 +43,7 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGScriptElement::SVGScriptElement(const QualifiedName& tagName, Document* document, bool wasInsertedByParser, bool alreadyStarted)
+inline SVGScriptElement::SVGScriptElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser, bool alreadyStarted)
     : SVGElement(tagName, document)
     , m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
     , m_loader(ScriptLoader::create(this, wasInsertedByParser, alreadyStarted))
@@ -53,7 +53,7 @@
     registerAnimatedPropertiesForSVGScriptElement();
 }
 
-PassRefPtr<SVGScriptElement> SVGScriptElement::create(const QualifiedName& tagName, Document* document, bool insertedByParser)
+PassRefPtr<SVGScriptElement> SVGScriptElement::create(const QualifiedName& tagName, Document& document, bool insertedByParser)
 {
     return adoptRef(new SVGScriptElement(tagName, document, insertedByParser, false));
 }
@@ -121,10 +121,13 @@
 Node::InsertionNotificationRequest SVGScriptElement::insertedInto(ContainerNode* rootParent)
 {
     SVGElement::insertedInto(rootParent);
-    m_loader->insertedInto(rootParent);
-    if (rootParent->inDocument())
-        SVGExternalResourcesRequired::insertedIntoDocument(this);
-    return InsertionDone;
+    return InsertionShouldCallDidNotifySubtreeInsertions;
+}
+
+void SVGScriptElement::didNotifySubtreeInsertionsToDocument()
+{
+    m_loader->didNotifySubtreeInsertionsToDocument();
+    SVGExternalResourcesRequired::insertedIntoDocument(this);
 }
 
 void SVGScriptElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -158,7 +161,7 @@
 {
     SVGElement::addSubresourceAttributeURLs(urls);
 
-    addSubresourceURL(urls, document()->completeURL(hrefCurrentValue()));
+    addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
 }
 
 String SVGScriptElement::sourceAttributeValue() const
diff --git a/Source/core/svg/SVGScriptElement.h b/Source/core/svg/SVGScriptElement.h
index b5529f0..10c5d45 100644
--- a/Source/core/svg/SVGScriptElement.h
+++ b/Source/core/svg/SVGScriptElement.h
@@ -39,7 +39,7 @@
     , public SVGExternalResourcesRequired
     , public ScriptLoaderClient {
 public:
-    static PassRefPtr<SVGScriptElement> create(const QualifiedName&, Document*, bool wasInsertedByParser);
+    static PassRefPtr<SVGScriptElement> create(const QualifiedName&, Document&, bool wasInsertedByParser);
 
     String type() const;
     void setType(const String&);
@@ -47,11 +47,12 @@
     ScriptLoader* loader() const { return m_loader.get(); }
 
 private:
-    SVGScriptElement(const QualifiedName&, Document*, bool wasInsertedByParser, bool alreadyStarted);
+    SVGScriptElement(const QualifiedName&, Document&, bool wasInsertedByParser, bool alreadyStarted);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
+    virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
     virtual void svgAttributeChanged(const QualifiedName&);
@@ -75,7 +76,7 @@
     virtual void dispatchLoadEvent() { SVGExternalResourcesRequired::dispatchLoadEvent(this); }
 
     virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren();
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     // SVGExternalResourcesRequired
     virtual void setHaveFiredLoadEvent(bool) OVERRIDE;
diff --git a/Source/core/svg/SVGSetElement.cpp b/Source/core/svg/SVGSetElement.cpp
index af88be9..934ed56 100644
--- a/Source/core/svg/SVGSetElement.cpp
+++ b/Source/core/svg/SVGSetElement.cpp
@@ -24,7 +24,7 @@
 
 namespace WebCore {
 
-inline SVGSetElement::SVGSetElement(const QualifiedName& tagName, Document* document)
+inline SVGSetElement::SVGSetElement(const QualifiedName& tagName, Document& document)
     : SVGAnimateElement(tagName, document)
 {
     setAnimationMode(ToAnimation);
@@ -32,7 +32,7 @@
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGSetElement> SVGSetElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGSetElement> SVGSetElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGSetElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGSetElement.h b/Source/core/svg/SVGSetElement.h
index 7089630..7ff5a57 100644
--- a/Source/core/svg/SVGSetElement.h
+++ b/Source/core/svg/SVGSetElement.h
@@ -28,10 +28,10 @@
 // SVGAnimateElement implements superset of the functionality.
 class SVGSetElement FINAL : public SVGAnimateElement {
 public:
-    static PassRefPtr<SVGSetElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGSetElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGSetElement(const QualifiedName&, Document*);
+    SVGSetElement(const QualifiedName&, Document&);
     virtual void updateAnimationMode() OVERRIDE;
 };
 
diff --git a/Source/core/svg/SVGStopElement.cpp b/Source/core/svg/SVGStopElement.cpp
index 23883c1..0751619 100644
--- a/Source/core/svg/SVGStopElement.cpp
+++ b/Source/core/svg/SVGStopElement.cpp
@@ -37,7 +37,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGStopElement::SVGStopElement(const QualifiedName& tagName, Document* document)
+inline SVGStopElement::SVGStopElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_offset(0)
 {
@@ -46,7 +46,7 @@
     registerAnimatedPropertiesForSVGStopElement();
 }
 
-PassRefPtr<SVGStopElement> SVGStopElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGStopElement> SVGStopElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGStopElement(tagName, document));
 }
@@ -102,7 +102,7 @@
     return new RenderSVGGradientStop(this);
 }
 
-bool SVGStopElement::rendererIsNeeded(const NodeRenderingContext&)
+bool SVGStopElement::rendererIsNeeded(const RenderStyle&)
 {
     return true;
 }
@@ -114,7 +114,7 @@
     // which the renderer or style is null. This entire class is scheduled for removal (Bug WK 86941)
     // and we will tolerate this null check until then.
     if (!style || !style->svgStyle())
-        return Color(Color::transparent); // Transparent black.
+        return Color(Color::transparent, true); // Transparent black.
 
     const SVGRenderStyle* svgStyle = style->svgStyle();
     return colorWithOverrideAlpha(svgStyle->stopColor().rgb(), svgStyle->stopOpacity());
diff --git a/Source/core/svg/SVGStopElement.h b/Source/core/svg/SVGStopElement.h
index 828c7f7..98b0dfe 100644
--- a/Source/core/svg/SVGStopElement.h
+++ b/Source/core/svg/SVGStopElement.h
@@ -29,12 +29,12 @@
 
 class SVGStopElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGStopElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGStopElement> create(const QualifiedName&, Document&);
 
     Color stopColorIncludingOpacity() const;
 
 private:
-    SVGStopElement(const QualifiedName&, Document*);
+    SVGStopElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -43,7 +43,7 @@
     virtual bool isGradientStop() const OVERRIDE { return true; }
 
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGStopElement)
         DECLARE_ANIMATED_NUMBER(Offset, offset)
diff --git a/Source/core/svg/SVGStyleElement.cpp b/Source/core/svg/SVGStyleElement.cpp
index 1ae0149..adb399d 100644
--- a/Source/core/svg/SVGStyleElement.cpp
+++ b/Source/core/svg/SVGStyleElement.cpp
@@ -29,9 +29,9 @@
 
 namespace WebCore {
 
-inline SVGStyleElement::SVGStyleElement(const QualifiedName& tagName, Document* document, bool createdByParser)
+inline SVGStyleElement::SVGStyleElement(const QualifiedName& tagName, Document& document, bool createdByParser)
     : SVGElement(tagName, document)
-    , StyleElement(document, createdByParser)
+    , StyleElement(&document, createdByParser)
     , m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
 {
     ASSERT(hasTagName(SVGNames::styleTag));
@@ -43,7 +43,7 @@
     StyleElement::clearDocumentData(document(), this);
 }
 
-PassRefPtr<SVGStyleElement> SVGStyleElement::create(const QualifiedName& tagName, Document* document, bool createdByParser)
+PassRefPtr<SVGStyleElement> SVGStyleElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
 {
     return adoptRef(new SVGStyleElement(tagName, document, createdByParser));
 }
@@ -129,12 +129,10 @@
 Node::InsertionNotificationRequest SVGStyleElement::insertedInto(ContainerNode* rootParent)
 {
     SVGElement::insertedInto(rootParent);
-    if (rootParent->inDocument())
-        return InsertionShouldCallDidNotifySubtreeInsertions;
-    return InsertionDone;
+    return InsertionShouldCallDidNotifySubtreeInsertions;
 }
 
-void SVGStyleElement::didNotifySubtreeInsertions(ContainerNode* insertionPoint)
+void SVGStyleElement::didNotifySubtreeInsertionsToDocument()
 {
     StyleElement::processStyleSheet(document(), this);
 }
diff --git a/Source/core/svg/SVGStyleElement.h b/Source/core/svg/SVGStyleElement.h
index 17f89d7..e263f90 100644
--- a/Source/core/svg/SVGStyleElement.h
+++ b/Source/core/svg/SVGStyleElement.h
@@ -29,7 +29,7 @@
 class SVGStyleElement FINAL : public SVGElement
                             , public StyleElement {
 public:
-    static PassRefPtr<SVGStyleElement> create(const QualifiedName&, Document*, bool createdByParser);
+    static PassRefPtr<SVGStyleElement> create(const QualifiedName&, Document&, bool createdByParser);
     virtual ~SVGStyleElement();
 
     using StyleElement::sheet;
@@ -47,17 +47,17 @@
     void setTitle(const AtomicString&);
 
 private:
-    SVGStyleElement(const QualifiedName&, Document*, bool createdByParser);
+    SVGStyleElement(const QualifiedName&, Document&, bool createdByParser);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    virtual void didNotifySubtreeInsertions(ContainerNode*) OVERRIDE;
+    virtual void didNotifySubtreeInsertionsToDocument() OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
     virtual void finishParsingChildren();
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     virtual bool isLoading() const { return StyleElement::isLoading(); }
     virtual bool sheetLoaded() { return StyleElement::sheetLoaded(document()); }
diff --git a/Source/core/svg/SVGSwitchElement.cpp b/Source/core/svg/SVGSwitchElement.cpp
index c1ef2a6..0791666 100644
--- a/Source/core/svg/SVGSwitchElement.cpp
+++ b/Source/core/svg/SVGSwitchElement.cpp
@@ -23,7 +23,6 @@
 #include "core/svg/SVGSwitchElement.h"
 
 #include "SVGNames.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/page/UseCounter.h"
 #include "core/rendering/svg/RenderSVGTransformableContainer.h"
 
@@ -37,22 +36,22 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGSwitchElement::SVGSwitchElement(const QualifiedName& tagName, Document* document)
+inline SVGSwitchElement::SVGSwitchElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::switchTag));
     ScriptWrappable::init(this);
     registerAnimatedPropertiesForSVGSwitchElement();
 
-    UseCounter::count(document, UseCounter::SVGSwitchElement);
+    UseCounter::count(&document, UseCounter::SVGSwitchElement);
 }
 
-PassRefPtr<SVGSwitchElement> SVGSwitchElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGSwitchElement> SVGSwitchElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGSwitchElement(tagName, document));
 }
 
-bool SVGSwitchElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGSwitchElement::childShouldCreateRenderer(const Node& child) const
 {
     // FIXME: This function does not do what the comment below implies it does.
     // It will create a renderer for any valid SVG element children, not just the first one.
@@ -64,7 +63,7 @@
         if (!element || !element->isValid())
             continue;
 
-        return node == childContext.node(); // Only allow this child if it's the first valid child
+        return node == &child; // Only allow this child if it's the first valid child
     }
 
     return false;
diff --git a/Source/core/svg/SVGSwitchElement.h b/Source/core/svg/SVGSwitchElement.h
index 99cf956..d7af51c 100644
--- a/Source/core/svg/SVGSwitchElement.h
+++ b/Source/core/svg/SVGSwitchElement.h
@@ -30,15 +30,15 @@
 class SVGSwitchElement FINAL : public SVGGraphicsElement,
                                public SVGExternalResourcesRequired {
 public:
-    static PassRefPtr<SVGSwitchElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGSwitchElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGSwitchElement(const QualifiedName&, Document*);
+    SVGSwitchElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
+    virtual bool childShouldCreateRenderer(const Node& child) const;
 
     virtual RenderObject* createRenderer(RenderStyle*);
 
diff --git a/Source/core/svg/SVGSymbolElement.cpp b/Source/core/svg/SVGSymbolElement.cpp
index acbb57f..2d65a2d 100644
--- a/Source/core/svg/SVGSymbolElement.cpp
+++ b/Source/core/svg/SVGSymbolElement.cpp
@@ -41,7 +41,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGSymbolElement::SVGSymbolElement(const QualifiedName& tagName, Document* document)
+inline SVGSymbolElement::SVGSymbolElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::symbolTag));
@@ -49,7 +49,7 @@
     registerAnimatedPropertiesForSVGSymbolElement();
 }
 
-PassRefPtr<SVGSymbolElement> SVGSymbolElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGSymbolElement> SVGSymbolElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGSymbolElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGSymbolElement.h b/Source/core/svg/SVGSymbolElement.h
index a5a1068..9d010de 100644
--- a/Source/core/svg/SVGSymbolElement.h
+++ b/Source/core/svg/SVGSymbolElement.h
@@ -34,10 +34,10 @@
                                public SVGExternalResourcesRequired,
                                public SVGFitToViewBox {
 public:
-    static PassRefPtr<SVGSymbolElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGSymbolElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGSymbolElement(const QualifiedName&, Document*);
+    SVGSymbolElement(const QualifiedName&, Document&);
 
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
diff --git a/Source/core/svg/SVGTRefElement.cpp b/Source/core/svg/SVGTRefElement.cpp
deleted file mode 100644
index a5fffce..0000000
--- a/Source/core/svg/SVGTRefElement.cpp
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- * Copyright (C) Research In Motion Limited 2011. 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/svg/SVGTRefElement.h"
-
-#include "SVGNames.h"
-#include "XLinkNames.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/MutationEvent.h"
-#include "core/dom/NodeRenderingContext.h"
-#include "core/dom/Text.h"
-#include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/markup.h"
-#include "core/page/UseCounter.h"
-#include "core/rendering/style/StyleInheritedData.h"
-#include "core/rendering/svg/RenderSVGInline.h"
-#include "core/rendering/svg/RenderSVGInlineText.h"
-#include "core/rendering/svg/RenderSVGResource.h"
-#include "core/svg/SVGDocument.h"
-#include "core/svg/SVGElementInstance.h"
-
-namespace WebCore {
-
-// Animated property definitions
-DEFINE_ANIMATED_STRING(SVGTRefElement, XLinkNames::hrefAttr, Href, href)
-
-BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTRefElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextPositioningElement)
-END_REGISTER_ANIMATED_PROPERTIES
-
-PassRefPtr<SVGTRefElement> SVGTRefElement::create(const QualifiedName& tagName, Document* document)
-{
-    RefPtr<SVGTRefElement> element = adoptRef(new SVGTRefElement(tagName, document));
-    element->ensureUserAgentShadowRoot();
-    return element.release();
-}
-
-class SVGTRefTargetEventListener : public EventListener {
-public:
-    static PassRefPtr<SVGTRefTargetEventListener> create(SVGTRefElement* trefElement)
-    {
-        return adoptRef(new SVGTRefTargetEventListener(trefElement));
-    }
-
-    static const SVGTRefTargetEventListener* cast(const EventListener* listener)
-    {
-        return listener->type() == SVGTRefTargetEventListenerType
-                ? static_cast<const SVGTRefTargetEventListener*>(listener) : 0;
-    }
-
-    void attach(PassRefPtr<Element> target);
-    void detach();
-    bool isAttached() const { return m_target.get(); }
-
-private:
-    SVGTRefTargetEventListener(SVGTRefElement* trefElement);
-
-    virtual void handleEvent(ScriptExecutionContext*, Event*) OVERRIDE;
-    virtual bool operator==(const EventListener&) OVERRIDE;
-
-    SVGTRefElement* m_trefElement;
-    RefPtr<Element> m_target;
-};
-
-SVGTRefTargetEventListener::SVGTRefTargetEventListener(SVGTRefElement* trefElement)
-    : EventListener(SVGTRefTargetEventListenerType)
-    , m_trefElement(trefElement)
-    , m_target(0)
-{
-    ASSERT(m_trefElement);
-}
-
-void SVGTRefTargetEventListener::attach(PassRefPtr<Element> target)
-{
-    ASSERT(!isAttached());
-    ASSERT(target.get());
-    ASSERT(target->inDocument());
-
-    target->addEventListener(eventNames().DOMSubtreeModifiedEvent, this, false);
-    target->addEventListener(eventNames().DOMNodeRemovedFromDocumentEvent, this, false);
-    m_target = target;
-}
-
-void SVGTRefTargetEventListener::detach()
-{
-    if (!isAttached())
-        return;
-
-    m_target->removeEventListener(eventNames().DOMSubtreeModifiedEvent, this, false);
-    m_target->removeEventListener(eventNames().DOMNodeRemovedFromDocumentEvent, this, false);
-    m_target.clear();
-}
-
-bool SVGTRefTargetEventListener::operator==(const EventListener& listener)
-{
-    if (const SVGTRefTargetEventListener* targetListener = SVGTRefTargetEventListener::cast(&listener))
-        return m_trefElement == targetListener->m_trefElement;
-    return false;
-}
-
-void SVGTRefTargetEventListener::handleEvent(ScriptExecutionContext*, Event* event)
-{
-    ASSERT(isAttached());
-
-    if (event->type() == eventNames().DOMSubtreeModifiedEvent && m_trefElement != event->target())
-        m_trefElement->updateReferencedText(m_target.get());
-    else if (event->type() == eventNames().DOMNodeRemovedFromDocumentEvent)
-        m_trefElement->detachTarget();
-}
-
-inline SVGTRefElement::SVGTRefElement(const QualifiedName& tagName, Document* document)
-    : SVGTextPositioningElement(tagName, document)
-    , m_targetListener(SVGTRefTargetEventListener::create(this))
-{
-    ASSERT(hasTagName(SVGNames::trefTag));
-    ScriptWrappable::init(this);
-    registerAnimatedPropertiesForSVGTRefElement();
-
-    UseCounter::count(document, UseCounter::SVGTRefElement);
-}
-
-SVGTRefElement::~SVGTRefElement()
-{
-    m_targetListener->detach();
-}
-
-void SVGTRefElement::updateReferencedText(Element* target)
-{
-    if (target)
-        replaceChildrenWithText(userAgentShadowRoot(), target->textContent(), ASSERT_NO_EXCEPTION);
-    else
-        userAgentShadowRoot()->removeChildren();
-}
-
-void SVGTRefElement::detachTarget()
-{
-    // Remove active listeners and clear the text content.
-    m_targetListener->detach();
-
-    userAgentShadowRoot()->removeChildren();
-
-    if (!inDocument())
-        return;
-
-    // Mark the referenced ID as pending.
-    String id;
-    SVGURIReference::targetElementFromIRIString(hrefCurrentValue(), document(), &id);
-    if (!id.isEmpty())
-        document()->accessSVGExtensions()->addPendingResource(id, this);
-}
-
-bool SVGTRefElement::isSupportedAttribute(const QualifiedName& attrName)
-{
-    DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
-    if (supportedAttributes.isEmpty())
-        SVGURIReference::addSupportedAttributes(supportedAttributes);
-    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
-}
-
-void SVGTRefElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
-{
-    if (!isSupportedAttribute(name)) {
-        SVGTextPositioningElement::parseAttribute(name, value);
-        return;
-    }
-
-    if (SVGURIReference::parseAttribute(name, value))
-        return;
-
-    ASSERT_NOT_REACHED();
-}
-
-void SVGTRefElement::svgAttributeChanged(const QualifiedName& attrName)
-{
-    if (!isSupportedAttribute(attrName)) {
-        SVGTextPositioningElement::svgAttributeChanged(attrName);
-        return;
-    }
-
-    SVGElementInstance::InvalidationGuard invalidationGuard(this);
-
-    if (SVGURIReference::isKnownAttribute(attrName)) {
-        buildPendingResource();
-        if (RenderObject* renderer = this->renderer())
-            RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
-}
-
-RenderObject* SVGTRefElement::createRenderer(RenderStyle*)
-{
-    return new RenderSVGInline(this);
-}
-
-bool SVGTRefElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
-{
-    return childContext.node()->isInShadowTree();
-}
-
-bool SVGTRefElement::rendererIsNeeded(const NodeRenderingContext& context)
-{
-    if (parentNode()
-        && (parentNode()->hasTagName(SVGNames::aTag)
-#if ENABLE(SVG_FONTS)
-            || parentNode()->hasTagName(SVGNames::altGlyphTag)
-#endif
-            || parentNode()->hasTagName(SVGNames::textTag)
-            || parentNode()->hasTagName(SVGNames::textPathTag)
-            || parentNode()->hasTagName(SVGNames::tspanTag)))
-        return Element::rendererIsNeeded(context);
-
-    return false;
-}
-
-void SVGTRefElement::buildPendingResource()
-{
-    // Remove any existing event listener.
-    m_targetListener->detach();
-
-    // If we're not yet in a document, this function will be called again from insertedInto().
-    if (!inDocument())
-        return;
-
-    String id;
-    RefPtr<Element> target = SVGURIReference::targetElementFromIRIString(hrefCurrentValue(), document(), &id);
-    if (!target.get()) {
-        if (id.isEmpty())
-            return;
-
-        document()->accessSVGExtensions()->addPendingResource(id, this);
-        ASSERT(hasPendingResources());
-        return;
-    }
-
-    // Don't set up event listeners if this is a shadow tree node.
-    // SVGUseElement::transferEventListenersToShadowTree() handles this task, and addEventListener()
-    // expects every element instance to have an associated shadow tree element - which is not the
-    // case when we land here from SVGUseElement::buildShadowTree().
-    if (!isInShadowTree())
-        m_targetListener->attach(target);
-
-    updateReferencedText(target.get());
-}
-
-Node::InsertionNotificationRequest SVGTRefElement::insertedInto(ContainerNode* rootParent)
-{
-    SVGElement::insertedInto(rootParent);
-    if (rootParent->inDocument())
-        buildPendingResource();
-    return InsertionDone;
-}
-
-void SVGTRefElement::removedFrom(ContainerNode* rootParent)
-{
-    SVGElement::removedFrom(rootParent);
-    if (rootParent->inDocument())
-        m_targetListener->detach();
-}
-
-}
diff --git a/Source/core/svg/SVGTRefElement.h b/Source/core/svg/SVGTRefElement.h
deleted file mode 100644
index 2ca2ac7..0000000
--- a/Source/core/svg/SVGTRefElement.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- *
- * 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 SVGTRefElement_h
-#define SVGTRefElement_h
-
-#include "core/svg/SVGTextPositioningElement.h"
-#include "core/svg/SVGURIReference.h"
-
-namespace WebCore {
-
-class SVGTRefTargetEventListener;
-
-class SVGTRefElement FINAL : public SVGTextPositioningElement,
-                             public SVGURIReference {
-public:
-    static PassRefPtr<SVGTRefElement> create(const QualifiedName&, Document*);
-
-private:
-    friend class SVGTRefTargetEventListener;
-
-    SVGTRefElement(const QualifiedName&, Document*);
-    virtual ~SVGTRefElement();
-
-    bool isSupportedAttribute(const QualifiedName&);
-    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual void svgAttributeChanged(const QualifiedName&);
-
-    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
-
-    virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
-    virtual void removedFrom(ContainerNode*) OVERRIDE;
-
-    void updateReferencedText(Element*);
-
-    void detachTarget();
-
-    virtual void buildPendingResource();
-
-    BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGTRefElement)
-        DECLARE_ANIMATED_STRING(Href, href)
-    END_DECLARE_ANIMATED_PROPERTIES
-
-    RefPtr<SVGTRefTargetEventListener> m_targetListener;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/svg/SVGTRefElement.idl b/Source/core/svg/SVGTRefElement.idl
deleted file mode 100644
index 4fb97b0..0000000
--- a/Source/core/svg/SVGTRefElement.idl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2006 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 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.
- */
-
-interface SVGTRefElement : SVGTextPositioningElement {
-};
-
-SVGTRefElement implements SVGURIReference;
-
diff --git a/Source/core/svg/SVGTSpanElement.cpp b/Source/core/svg/SVGTSpanElement.cpp
index 44f3490..7b47b96 100644
--- a/Source/core/svg/SVGTSpanElement.cpp
+++ b/Source/core/svg/SVGTSpanElement.cpp
@@ -23,19 +23,18 @@
 #include "core/svg/SVGTSpanElement.h"
 
 #include "SVGNames.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/rendering/svg/RenderSVGTSpan.h"
 
 namespace WebCore {
 
-inline SVGTSpanElement::SVGTSpanElement(const QualifiedName& tagName, Document* document)
+inline SVGTSpanElement::SVGTSpanElement(const QualifiedName& tagName, Document& document)
     : SVGTextPositioningElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::tspanTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGTSpanElement> SVGTSpanElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGTSpanElement> SVGTSpanElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGTSpanElement(tagName, document));
 }
@@ -45,21 +44,20 @@
     return new RenderSVGTSpan(this);
 }
 
-bool SVGTSpanElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGTSpanElement::childShouldCreateRenderer(const Node& child) const
 {
-    if (childContext.node()->isTextNode()
-        || childContext.node()->hasTagName(SVGNames::aTag)
+    if (child.isTextNode()
+        || child.hasTagName(SVGNames::aTag)
 #if ENABLE(SVG_FONTS)
-        || childContext.node()->hasTagName(SVGNames::altGlyphTag)
+        || child.hasTagName(SVGNames::altGlyphTag)
 #endif
-        || childContext.node()->hasTagName(SVGNames::trefTag)
-        || childContext.node()->hasTagName(SVGNames::tspanTag))
+        || child.hasTagName(SVGNames::tspanTag))
         return true;
 
     return false;
 }
 
-bool SVGTSpanElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool SVGTSpanElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (parentNode()
         && (parentNode()->hasTagName(SVGNames::aTag)
@@ -69,7 +67,7 @@
             || parentNode()->hasTagName(SVGNames::textTag)
             || parentNode()->hasTagName(SVGNames::textPathTag)
             || parentNode()->hasTagName(SVGNames::tspanTag)))
-        return Element::rendererIsNeeded(context);
+        return Element::rendererIsNeeded(style);
 
     return false;
 }
diff --git a/Source/core/svg/SVGTSpanElement.h b/Source/core/svg/SVGTSpanElement.h
index 05236fe..2861f85 100644
--- a/Source/core/svg/SVGTSpanElement.h
+++ b/Source/core/svg/SVGTSpanElement.h
@@ -27,14 +27,14 @@
 
 class SVGTSpanElement FINAL : public SVGTextPositioningElement {
 public:
-    static PassRefPtr<SVGTSpanElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGTSpanElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGTSpanElement(const QualifiedName&, Document*);
+    SVGTSpanElement(const QualifiedName&, Document&);
 
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool childShouldCreateRenderer(const Node& child) const;
+    virtual bool rendererIsNeeded(const RenderStyle&);
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGTextContentElement.cpp b/Source/core/svg/SVGTextContentElement.cpp
index 48c806a..4f7a3a8 100644
--- a/Source/core/svg/SVGTextContentElement.cpp
+++ b/Source/core/svg/SVGTextContentElement.cpp
@@ -62,7 +62,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGTextContentElement::SVGTextContentElement(const QualifiedName& tagName, Document* document)
+SVGTextContentElement::SVGTextContentElement(const QualifiedName& tagName, Document& document)
     : SVGGraphicsElement(tagName, document)
     , m_textLength(LengthModeOther)
     , m_specifiedTextLength(LengthModeOther)
@@ -103,19 +103,19 @@
 
 unsigned SVGTextContentElement::getNumberOfChars()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     return SVGTextQuery(renderer()).numberOfCharacters();
 }
 
 float SVGTextContentElement::getComputedTextLength()
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     return SVGTextQuery(renderer()).textLength();
 }
 
 float SVGTextContentElement::getSubStringLength(unsigned charnum, unsigned nchars, ExceptionState& es)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     unsigned numberOfChars = getNumberOfChars();
     if (charnum >= numberOfChars) {
@@ -131,7 +131,7 @@
 
 SVGPoint SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionState& es)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
         es.throwDOMException(IndexSizeError);
@@ -143,7 +143,7 @@
 
 SVGPoint SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionState& es)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
         es.throwDOMException(IndexSizeError);
@@ -155,7 +155,7 @@
 
 SVGRect SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionState& es)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
         es.throwDOMException(IndexSizeError);
@@ -167,7 +167,7 @@
 
 float SVGTextContentElement::getRotationOfChar(unsigned charnum, ExceptionState& es)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
 
     if (charnum > getNumberOfChars()) {
         es.throwDOMException(IndexSizeError);
@@ -179,7 +179,7 @@
 
 int SVGTextContentElement::getCharNumAtPosition(const SVGPoint& point)
 {
-    document()->updateLayoutIgnorePendingStylesheets();
+    document().updateLayoutIgnorePendingStylesheets();
     return SVGTextQuery(renderer()).characterNumberAtPosition(point);
 }
 
@@ -194,12 +194,7 @@
     if (nchars > numberOfChars - charnum)
         nchars = numberOfChars - charnum;
 
-    ASSERT(document());
-    ASSERT(document()->frame());
-
-    FrameSelection* selection = document()->frame()->selection();
-    if (!selection)
-        return;
+    ASSERT(document().frame());
 
     // Find selection start
     VisiblePosition start(firstPositionInNode(const_cast<SVGTextContentElement*>(this)));
@@ -211,7 +206,7 @@
     for (unsigned i = 0; i < nchars; ++i)
         end = end.next();
 
-    selection->setSelection(VisibleSelection(start, end));
+    document().frame()->selection().setSelection(VisibleSelection(start, end));
 }
 
 bool SVGTextContentElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/Source/core/svg/SVGTextContentElement.h b/Source/core/svg/SVGTextContentElement.h
index 3cccd0e..255330e 100644
--- a/Source/core/svg/SVGTextContentElement.h
+++ b/Source/core/svg/SVGTextContentElement.h
@@ -95,7 +95,7 @@
     static const SVGPropertyInfo* textLengthPropertyInfo();
 
 protected:
-    SVGTextContentElement(const QualifiedName&, Document*);
+    SVGTextContentElement(const QualifiedName&, Document&);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
 
diff --git a/Source/core/svg/SVGTextElement.cpp b/Source/core/svg/SVGTextElement.cpp
index fef8f16..d7ed0d6 100644
--- a/Source/core/svg/SVGTextElement.cpp
+++ b/Source/core/svg/SVGTextElement.cpp
@@ -23,21 +23,20 @@
 #include "core/svg/SVGTextElement.h"
 
 #include "SVGNames.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/rendering/svg/RenderSVGResource.h"
 #include "core/rendering/svg/RenderSVGText.h"
 #include "core/svg/SVGElementInstance.h"
 
 namespace WebCore {
 
-inline SVGTextElement::SVGTextElement(const QualifiedName& tagName, Document* doc)
+inline SVGTextElement::SVGTextElement(const QualifiedName& tagName, Document& doc)
     : SVGTextPositioningElement(tagName, doc)
 {
     ASSERT(hasTagName(SVGNames::textTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGTextElement> SVGTextElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGTextElement> SVGTextElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGTextElement(tagName, document));
 }
@@ -72,16 +71,15 @@
     return new RenderSVGText(this);
 }
 
-bool SVGTextElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGTextElement::childShouldCreateRenderer(const Node& child) const
 {
-    if (childContext.node()->isTextNode()
-        || childContext.node()->hasTagName(SVGNames::aTag)
+    if (child.isTextNode()
+        || child.hasTagName(SVGNames::aTag)
 #if ENABLE(SVG_FONTS)
-        || childContext.node()->hasTagName(SVGNames::altGlyphTag)
+        || child.hasTagName(SVGNames::altGlyphTag)
 #endif
-        || childContext.node()->hasTagName(SVGNames::textPathTag)
-        || childContext.node()->hasTagName(SVGNames::trefTag)
-        || childContext.node()->hasTagName(SVGNames::tspanTag))
+        || child.hasTagName(SVGNames::textPathTag)
+        || child.hasTagName(SVGNames::tspanTag))
         return true;
 
     return false;
diff --git a/Source/core/svg/SVGTextElement.h b/Source/core/svg/SVGTextElement.h
index 95be00e..55b63e6 100644
--- a/Source/core/svg/SVGTextElement.h
+++ b/Source/core/svg/SVGTextElement.h
@@ -21,25 +21,32 @@
 #ifndef SVGTextElement_h
 #define SVGTextElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGTextPositioningElement.h"
 
 namespace WebCore {
 
 class SVGTextElement FINAL : public SVGTextPositioningElement {
 public:
-    static PassRefPtr<SVGTextElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGTextElement> create(const QualifiedName&, Document&);
 
     virtual AffineTransform animatedLocalTransform() const;
 
 private:
-    SVGTextElement(const QualifiedName&, Document*);
+    SVGTextElement(const QualifiedName&, Document&);
 
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
 
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
+    virtual bool childShouldCreateRenderer(const Node& child) const;
 };
 
+inline SVGTextElement* toSVGTextElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::textTag));
+    return static_cast<SVGTextElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGTextPathElement.cpp b/Source/core/svg/SVGTextPathElement.cpp
index dbba619..eb21c90 100644
--- a/Source/core/svg/SVGTextPathElement.cpp
+++ b/Source/core/svg/SVGTextPathElement.cpp
@@ -24,7 +24,6 @@
 
 #include "SVGNames.h"
 #include "XLinkNames.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/rendering/svg/RenderSVGResource.h"
 #include "core/rendering/svg/RenderSVGTextPath.h"
 #include "core/svg/SVGElementInstance.h"
@@ -45,7 +44,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextContentElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGTextPathElement::SVGTextPathElement(const QualifiedName& tagName, Document* document)
+inline SVGTextPathElement::SVGTextPathElement(const QualifiedName& tagName, Document& document)
     : SVGTextContentElement(tagName, document)
     , m_startOffset(LengthModeOther)
     , m_method(SVGTextPathMethodAlign)
@@ -56,7 +55,7 @@
     registerAnimatedPropertiesForSVGTextPathElement();
 }
 
-PassRefPtr<SVGTextPathElement> SVGTextPathElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGTextPathElement> SVGTextPathElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGTextPathElement(tagName, document));
 }
@@ -68,8 +67,7 @@
 
 void SVGTextPathElement::clearResourceReferences()
 {
-    ASSERT(document());
-    document()->accessSVGExtensions()->removeAllTargetReferencesForElement(this);
+    document().accessSVGExtensions()->removeAllTargetReferencesForElement(this);
 }
 
 bool SVGTextPathElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -133,23 +131,22 @@
     return new RenderSVGTextPath(this);
 }
 
-bool SVGTextPathElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
+bool SVGTextPathElement::childShouldCreateRenderer(const Node& child) const
 {
-    if (childContext.node()->isTextNode()
-        || childContext.node()->hasTagName(SVGNames::aTag)
-        || childContext.node()->hasTagName(SVGNames::trefTag)
-        || childContext.node()->hasTagName(SVGNames::tspanTag))
+    if (child.isTextNode()
+        || child.hasTagName(SVGNames::aTag)
+        || child.hasTagName(SVGNames::tspanTag))
         return true;
 
     return false;
 }
 
-bool SVGTextPathElement::rendererIsNeeded(const NodeRenderingContext& context)
+bool SVGTextPathElement::rendererIsNeeded(const RenderStyle& style)
 {
     if (parentNode()
         && (parentNode()->hasTagName(SVGNames::aTag)
             || parentNode()->hasTagName(SVGNames::textTag)))
-        return Element::rendererIsNeeded(context);
+        return Element::rendererIsNeeded(style);
 
     return false;
 }
@@ -164,17 +161,17 @@
     Element* target = SVGURIReference::targetElementFromIRIString(hrefCurrentValue(), document(), &id);
     if (!target) {
         // Do not register as pending if we are already pending this resource.
-        if (document()->accessSVGExtensions()->isElementPendingResource(this, id))
+        if (document().accessSVGExtensions()->isElementPendingResource(this, id))
             return;
 
         if (!id.isEmpty()) {
-            document()->accessSVGExtensions()->addPendingResource(id, this);
+            document().accessSVGExtensions()->addPendingResource(id, this);
             ASSERT(hasPendingResources());
         }
     } else if (target->hasTagName(SVGNames::pathTag)) {
         // Register us with the target in the dependencies map. Any change of hrefElement
         // that leads to relayout/repainting now informs us, so we can react to it.
-        document()->accessSVGExtensions()->addElementReferencingTarget(this, toSVGElement(target));
+        document().accessSVGExtensions()->addElementReferencingTarget(this, toSVGElement(target));
     }
 }
 
diff --git a/Source/core/svg/SVGTextPathElement.h b/Source/core/svg/SVGTextPathElement.h
index 0ad3f96..1ea5d11 100644
--- a/Source/core/svg/SVGTextPathElement.h
+++ b/Source/core/svg/SVGTextPathElement.h
@@ -109,10 +109,10 @@
         TEXTPATH_SPACINGTYPE_EXACT = SVGTextPathSpacingExact
     };
 
-    static PassRefPtr<SVGTextPathElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGTextPathElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGTextPathElement(const QualifiedName&, Document*);
+    SVGTextPathElement(const QualifiedName&, Document&);
 
     virtual ~SVGTextPathElement();
 
@@ -127,8 +127,8 @@
     virtual void svgAttributeChanged(const QualifiedName&);
 
     virtual RenderObject* createRenderer(RenderStyle*);
-    virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
-    virtual bool rendererIsNeeded(const NodeRenderingContext&);
+    virtual bool childShouldCreateRenderer(const Node& child) const;
+    virtual bool rendererIsNeeded(const RenderStyle&);
 
     virtual bool selfHasRelativeLengths() const;
 
diff --git a/Source/core/svg/SVGTextPositioningElement.cpp b/Source/core/svg/SVGTextPositioningElement.cpp
index b8c8f8a..664ba23 100644
--- a/Source/core/svg/SVGTextPositioningElement.cpp
+++ b/Source/core/svg/SVGTextPositioningElement.cpp
@@ -47,7 +47,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextContentElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGTextPositioningElement::SVGTextPositioningElement(const QualifiedName& tagName, Document* document)
+SVGTextPositioningElement::SVGTextPositioningElement(const QualifiedName& tagName, Document& document)
     : SVGTextContentElement(tagName, document)
 {
     ScriptWrappable::init(this);
@@ -161,11 +161,10 @@
     ASSERT(node->isSVGElement());
 
     if (!node->hasTagName(SVGNames::textTag)
-        && !node->hasTagName(SVGNames::tspanTag)
 #if ENABLE(SVG_FONTS)
         && !node->hasTagName(SVGNames::altGlyphTag)
 #endif
-        && !node->hasTagName(SVGNames::trefTag))
+        && !node->hasTagName(SVGNames::tspanTag))
         return 0;
 
     return static_cast<SVGTextPositioningElement*>(node);
diff --git a/Source/core/svg/SVGTextPositioningElement.h b/Source/core/svg/SVGTextPositioningElement.h
index 1421814..665315c 100644
--- a/Source/core/svg/SVGTextPositioningElement.h
+++ b/Source/core/svg/SVGTextPositioningElement.h
@@ -32,7 +32,7 @@
     static SVGTextPositioningElement* elementFromRenderer(RenderObject*);
 
 protected:
-    SVGTextPositioningElement(const QualifiedName&, Document*);
+    SVGTextPositioningElement(const QualifiedName&, Document&);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/Source/core/svg/SVGTitleElement.cpp b/Source/core/svg/SVGTitleElement.cpp
index 6f8c585..7e6a1ce 100644
--- a/Source/core/svg/SVGTitleElement.cpp
+++ b/Source/core/svg/SVGTitleElement.cpp
@@ -26,14 +26,14 @@
 
 namespace WebCore {
 
-inline SVGTitleElement::SVGTitleElement(const QualifiedName& tagName, Document* document)
+inline SVGTitleElement::SVGTitleElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::titleTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGTitleElement> SVGTitleElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGTitleElement> SVGTitleElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGTitleElement(tagName, document));
 }
@@ -44,7 +44,7 @@
     if (!rootParent->inDocument())
         return InsertionDone;
     if (firstChild())
-        document()->setTitleElement(textContent(), this);
+        document().setTitleElement(textContent(), this);
     return InsertionDone;
 }
 
@@ -52,14 +52,14 @@
 {
     SVGElement::removedFrom(rootParent);
     if (rootParent->inDocument())
-        document()->removeTitle(this);
+        document().removeTitle(this);
 }
 
 void SVGTitleElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
     SVGElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
     if (inDocument())
-        document()->setTitleElement(textContent(), this);
+        document().setTitleElement(textContent(), this);
 }
 
 }
diff --git a/Source/core/svg/SVGTitleElement.h b/Source/core/svg/SVGTitleElement.h
index ab513b6..e5ac03b 100644
--- a/Source/core/svg/SVGTitleElement.h
+++ b/Source/core/svg/SVGTitleElement.h
@@ -27,16 +27,16 @@
 
 class SVGTitleElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGTitleElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGTitleElement> create(const QualifiedName&, Document&);
 
 private:
-    SVGTitleElement(const QualifiedName&, Document*);
+    SVGTitleElement(const QualifiedName&, Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGURIReference.cpp b/Source/core/svg/SVGURIReference.cpp
index 270e261..4152c15 100644
--- a/Source/core/svg/SVGURIReference.cpp
+++ b/Source/core/svg/SVGURIReference.cpp
@@ -43,23 +43,21 @@
     return attrName.matches(XLinkNames::hrefAttr);
 }
 
-String SVGURIReference::fragmentIdentifierFromIRIString(const String& url, Document* document)
+String SVGURIReference::fragmentIdentifierFromIRIString(const String& url, const Document& document)
 {
-    ASSERT(document);
     size_t start = url.find('#');
     if (start == notFound)
         return emptyString();
 
-    KURL base = start ? KURL(document->baseURI(), url.substring(0, start)) : document->baseURI();
-    if (equalIgnoringFragmentIdentifier(base, document->url()))
+    KURL base = start ? KURL(document.baseURI(), url.substring(0, start)) : document.baseURI();
+    if (equalIgnoringFragmentIdentifier(base, document.url()))
         return url.substring(start + 1);
 
     return emptyString();
 }
 
-static inline KURL urlFromIRIStringWithFragmentIdentifier(const String& url, Document* document, String& fragmentIdentifier)
+static inline KURL urlFromIRIStringWithFragmentIdentifier(const String& url, const Document& document, String& fragmentIdentifier)
 {
-    ASSERT(document);
     size_t startOfFragmentIdentifier = url.find('#');
     if (startOfFragmentIdentifier == notFound)
         return KURL();
@@ -67,14 +65,14 @@
     // Exclude the '#' character when determining the fragmentIdentifier.
     fragmentIdentifier = url.substring(startOfFragmentIdentifier + 1);
     if (startOfFragmentIdentifier) {
-        KURL base(document->baseURI(), url.substring(0, startOfFragmentIdentifier));
+        KURL base(document.baseURI(), url.substring(0, startOfFragmentIdentifier));
         return KURL(base, url.substring(startOfFragmentIdentifier));
     }
 
-    return KURL(document->baseURI(), url.substring(startOfFragmentIdentifier));
+    return KURL(document.baseURI(), url.substring(startOfFragmentIdentifier));
 }
 
-Element* SVGURIReference::targetElementFromIRIString(const String& iri, Document* document, String* fragmentIdentifier, Document* externalDocument)
+Element* SVGURIReference::targetElementFromIRIString(const String& iri, const Document& document, String* fragmentIdentifier, Document* externalDocument)
 {
     // If there's no fragment identifier contained within the IRI string, we can't lookup an element.
     String id;
@@ -98,7 +96,7 @@
     if (isExternalURIReference(iri, document))
         return 0;
 
-    return document->getElementById(id);
+    return document.getElementById(id);
 }
 
 void SVGURIReference::addSupportedAttributes(HashSet<QualifiedName>& supportedAttributes)
diff --git a/Source/core/svg/SVGURIReference.h b/Source/core/svg/SVGURIReference.h
index de25107..e6901e6 100644
--- a/Source/core/svg/SVGURIReference.h
+++ b/Source/core/svg/SVGURIReference.h
@@ -36,19 +36,18 @@
     bool isKnownAttribute(const QualifiedName&);
     void addSupportedAttributes(HashSet<QualifiedName>&);
 
-    static String fragmentIdentifierFromIRIString(const String&, Document*);
-    static Element* targetElementFromIRIString(const String&, Document*, String* = 0, Document* = 0);
+    static String fragmentIdentifierFromIRIString(const String&, const Document&);
+    static Element* targetElementFromIRIString(const String&, const Document&, String* = 0, Document* = 0);
 
-    static inline bool isExternalURIReference(const String& uri, Document* document)
+    static inline bool isExternalURIReference(const String& uri, const Document& document)
     {
         // Fragment-only URIs are always internal
         if (uri.startsWith('#'))
             return false;
 
         // If the URI matches our documents URL, we're dealing with a local reference.
-        ASSERT(document);
-        KURL url = document->completeURL(uri);
-        return !equalIgnoringFragmentIdentifier(url, document->url());
+        KURL url = document.completeURL(uri);
+        return !equalIgnoringFragmentIdentifier(url, document.url());
     }
 
 protected:
diff --git a/Source/core/svg/SVGUnknownElement.cpp b/Source/core/svg/SVGUnknownElement.cpp
index ecc0d2f..3136a70 100644
--- a/Source/core/svg/SVGUnknownElement.cpp
+++ b/Source/core/svg/SVGUnknownElement.cpp
@@ -33,7 +33,7 @@
 
 namespace WebCore {
 
-SVGUnknownElement::SVGUnknownElement(const QualifiedName& tagName, Document* document)
+SVGUnknownElement::SVGUnknownElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
 }
diff --git a/Source/core/svg/SVGUnknownElement.h b/Source/core/svg/SVGUnknownElement.h
index fe8d7e4..93dd832 100644
--- a/Source/core/svg/SVGUnknownElement.h
+++ b/Source/core/svg/SVGUnknownElement.h
@@ -43,15 +43,15 @@
 // false to make sure we don't attempt to render such elements.
 class SVGUnknownElement : public SVGElement {
 public:
-    static PassRefPtr<SVGUnknownElement> create(const QualifiedName& tagName, Document* document)
+    static PassRefPtr<SVGUnknownElement> create(const QualifiedName& tagName, Document& document)
     {
         return adoptRef(new SVGUnknownElement(tagName, document));
     }
 
 private:
-    SVGUnknownElement(const QualifiedName&, Document*);
+    SVGUnknownElement(const QualifiedName&, Document&);
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGUseElement.cpp b/Source/core/svg/SVGUseElement.cpp
index 590eddd..58910f3 100644
--- a/Source/core/svg/SVGUseElement.cpp
+++ b/Source/core/svg/SVGUseElement.cpp
@@ -71,7 +71,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document* document, bool wasInsertedByParser)
+inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
     : SVGGraphicsElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
@@ -88,7 +88,7 @@
     registerAnimatedPropertiesForSVGUseElement();
 }
 
-PassRefPtr<SVGUseElement> SVGUseElement::create(const QualifiedName& tagName, Document* document, bool wasInsertedByParser)
+PassRefPtr<SVGUseElement> SVGUseElement::create(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
 {
     // Always build a #shadow-root for SVGUseElement.
     RefPtr<SVGUseElement> use = adoptRef(new SVGUseElement(tagName, document, wasInsertedByParser));
@@ -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().updateLayoutIgnorePendingStylesheets();
 
     return m_targetElementInstance.get();
 }
@@ -172,8 +172,8 @@
     SVGGraphicsElement::insertedInto(rootParent);
     if (!rootParent->inDocument())
         return InsertionDone;
-    ASSERT(!m_targetElementInstance || !isWellFormedDocument(document()));
-    ASSERT(!hasPendingResources() || !isWellFormedDocument(document()));
+    ASSERT(!m_targetElementInstance || !isWellFormedDocument(&document()));
+    ASSERT(!hasPendingResources() || !isWellFormedDocument(&document()));
     if (!m_wasInsertedByParser)
         buildPendingResource();
     SVGExternalResourcesRequired::insertedIntoDocument(this);
@@ -190,7 +190,7 @@
 Document* SVGUseElement::referencedDocument() const
 {
     if (!isExternalURIReference(hrefCurrentValue(), document()))
-        return document();
+        return &document();
     return externalDocument();
 }
 
@@ -232,10 +232,10 @@
     if (SVGURIReference::isKnownAttribute(attrName)) {
         bool isExternalReference = isExternalURIReference(hrefCurrentValue(), document());
         if (isExternalReference) {
-            KURL url = document()->completeURL(hrefCurrentValue());
+            KURL url = document().completeURL(hrefCurrentValue());
             if (url.hasFragmentIdentifier()) {
                 FetchRequest request(ResourceRequest(url.string()), localName());
-                setDocumentResource(document()->fetcher()->fetchSVGDocument(request));
+                setDocumentResource(document().fetcher()->fetchSVGDocument(request));
             }
         } else {
             setDocumentResource(0);
@@ -266,7 +266,7 @@
     SVGGraphicsElement::attach(context);
 }
 
-void SVGUseElement::willRecalcStyle(StyleChange)
+void SVGUseElement::willRecalcStyle(StyleRecalcChange)
 {
     if (!m_wasInsertedByParser && m_needsShadowTreeRecreation && renderer() && needsStyleRecalc())
         buildPendingResource();
@@ -361,7 +361,6 @@
         allowedElementTags.add(SVGNames::textTag);
         allowedElementTags.add(SVGNames::textPathTag);
         allowedElementTags.add(SVGNames::titleTag);
-        allowedElementTags.add(SVGNames::trefTag);
         allowedElementTags.add(SVGNames::tspanTag);
         allowedElementTags.add(SVGNames::useTag);
     }
@@ -394,8 +393,7 @@
 
     m_needsShadowTreeRecreation = false;
 
-    ASSERT(document());
-    document()->accessSVGExtensions()->removeAllTargetReferencesForElement(this);
+    document().accessSVGExtensions()->removeAllTargetReferencesForElement(this);
 }
 
 void SVGUseElement::buildPendingResource()
@@ -553,10 +551,10 @@
         return;
 
     if (n->isSVGElement() && toSVGElement(n)->isSVGGraphicsElement()) {
-        if (!isDirectReference(n))
+        if (!isDirectReference(n)) {
             // Spec: Indirect references are an error (14.3.5)
-            document()->accessSVGExtensions()->reportError("Not allowed to use indirect reference in <clip-path>");
-        else {
+            document().accessSVGExtensions()->reportError("Not allowed to use indirect reference in <clip-path>");
+        } else {
             toSVGGraphicsElement(n)->toClipPath(path);
             // FIXME: Avoid manual resolution of x/y here. Its potentially harmful.
             SVGLengthContext lengthContext(this);
@@ -595,8 +593,7 @@
         // We only need to track first degree <use> dependencies. Indirect references are handled
         // as the invalidation bubbles up the dependency chain.
         if (!foundUse) {
-            ASSERT(document());
-            document()->accessSVGExtensions()->addElementReferencingTarget(this, target);
+            document().accessSVGExtensions()->addElementReferencingTarget(this, target);
             foundUse = true;
         }
     } else if (isDisallowedElement(target)) {
@@ -642,7 +639,8 @@
 
 bool SVGUseElement::hasCycleUseReferencing(SVGUseElement* use, SVGElementInstance* targetInstance, SVGElement*& newTarget)
 {
-    Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefCurrentValue(), referencedDocument());
+    ASSERT(referencedDocument());
+    Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefCurrentValue(), *referencedDocument());
     newTarget = 0;
     if (targetElement && targetElement->isSVGElement())
         newTarget = toSVGElement(targetElement);
@@ -659,7 +657,7 @@
     while (instance) {
         SVGElement* element = instance->correspondingElement();
 
-        if (element->hasID() && element->getIdAttribute() == targetId && element->document() == newTarget->document())
+        if (element->hasID() && element->getIdAttribute() == targetId && &element->document() == &newTarget->document())
             return true;
 
         instance = instance->parentNode();
@@ -714,14 +712,15 @@
         SVGUseElement* use = toSVGUseElement(element);
         ASSERT(!use->resourceIsStillLoading());
 
-        Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefCurrentValue(), referencedDocument());
+        ASSERT(referencedDocument());
+        Element* targetElement = SVGURIReference::targetElementFromIRIString(use->hrefCurrentValue(), *referencedDocument());
         SVGElement* target = 0;
         if (targetElement && targetElement->isSVGElement())
             target = toSVGElement(targetElement);
 
         // Don't ASSERT(target) here, it may be "pending", too.
         // Setup sub-shadow tree root node
-        RefPtr<SVGGElement> cloneParent = SVGGElement::create(SVGNames::gTag, referencedDocument());
+        RefPtr<SVGGElement> cloneParent = SVGGElement::create(SVGNames::gTag, *referencedDocument());
         use->cloneChildNodes(cloneParent.get());
 
         // Spec: In the generated content, the 'use' will be replaced by 'g', where all attributes from the
@@ -768,7 +767,8 @@
         // height are provided on the 'use' element, then these attributes will be transferred to
         // the generated 'svg'. If attributes width and/or height are not specified, the generated
         // 'svg' element will use values of 100% for these attributes.
-        RefPtr<SVGSVGElement> svgElement = SVGSVGElement::create(SVGNames::svgTag, referencedDocument());
+        ASSERT(referencedDocument());
+        RefPtr<SVGSVGElement> svgElement = SVGSVGElement::create(SVGNames::svgTag, *referencedDocument());
 
         // Transfer all data (attributes, etc.) from <symbol> to the new <svg> element.
         svgElement->cloneDataFromElement(*toElement(element));
diff --git a/Source/core/svg/SVGUseElement.h b/Source/core/svg/SVGUseElement.h
index 8f55402..459cb2b 100644
--- a/Source/core/svg/SVGUseElement.h
+++ b/Source/core/svg/SVGUseElement.h
@@ -39,7 +39,7 @@
                             public SVGURIReference,
                             public DocumentResourceClient {
 public:
-    static PassRefPtr<SVGUseElement> create(const QualifiedName&, Document*, bool wasInsertedByParser);
+    static PassRefPtr<SVGUseElement> create(const QualifiedName&, Document&, bool wasInsertedByParser);
     virtual ~SVGUseElement();
 
     SVGElementInstance* instanceRoot();
@@ -51,7 +51,7 @@
     RenderObject* rendererClipChild() const;
 
 private:
-    SVGUseElement(const QualifiedName&, Document*, bool wasInsertedByParser);
+    SVGUseElement(const QualifiedName&, Document&, bool wasInsertedByParser);
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -65,7 +65,7 @@
     virtual void svgAttributeChanged(const QualifiedName&);
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual void willRecalcStyle(StyleChange) OVERRIDE;
+    virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
 
     virtual RenderObject* createRenderer(RenderStyle*);
     virtual void toClipPath(Path&);
diff --git a/Source/core/svg/SVGVKernElement.cpp b/Source/core/svg/SVGVKernElement.cpp
index d78c777..0908be7 100644
--- a/Source/core/svg/SVGVKernElement.cpp
+++ b/Source/core/svg/SVGVKernElement.cpp
@@ -28,14 +28,14 @@
 
 namespace WebCore {
 
-inline SVGVKernElement::SVGVKernElement(const QualifiedName& tagName, Document* document)
+inline SVGVKernElement::SVGVKernElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::vkernTag));
     ScriptWrappable::init(this);
 }
 
-PassRefPtr<SVGVKernElement> SVGVKernElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGVKernElement> SVGVKernElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGVKernElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGVKernElement.h b/Source/core/svg/SVGVKernElement.h
index 3a788b3..185b0de 100644
--- a/Source/core/svg/SVGVKernElement.h
+++ b/Source/core/svg/SVGVKernElement.h
@@ -21,6 +21,7 @@
 #define SVGVKernElement_h
 
 #if ENABLE(SVG_FONTS)
+#include "SVGNames.h"
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGFontElement.h"
 
@@ -28,19 +29,25 @@
 
 class SVGVKernElement FINAL : public SVGElement {
 public:
-    static PassRefPtr<SVGVKernElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGVKernElement> create(const QualifiedName&, Document&);
 
     void buildVerticalKerningPair(KerningPairVector&);
 
 private:
-    SVGVKernElement(const QualifiedName&, Document*);
+    SVGVKernElement(const QualifiedName&, Document&);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 };
 
+inline SVGVKernElement* toSVGVKernElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::vkernTag));
+    return static_cast<SVGVKernElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(SVG_FONTS)
diff --git a/Source/core/svg/SVGViewElement.cpp b/Source/core/svg/SVGViewElement.cpp
index 1f29d8c..89d7bc4 100644
--- a/Source/core/svg/SVGViewElement.cpp
+++ b/Source/core/svg/SVGViewElement.cpp
@@ -41,7 +41,7 @@
     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
-inline SVGViewElement::SVGViewElement(const QualifiedName& tagName, Document* document)
+inline SVGViewElement::SVGViewElement(const QualifiedName& tagName, Document& document)
     : SVGElement(tagName, document)
     , m_zoomAndPan(SVGZoomAndPanMagnify)
     , m_viewTarget(SVGNames::viewTargetAttr)
@@ -51,7 +51,7 @@
     registerAnimatedPropertiesForSVGViewElement();
 }
 
-PassRefPtr<SVGViewElement> SVGViewElement::create(const QualifiedName& tagName, Document* document)
+PassRefPtr<SVGViewElement> SVGViewElement::create(const QualifiedName& tagName, Document& document)
 {
     return adoptRef(new SVGViewElement(tagName, document));
 }
diff --git a/Source/core/svg/SVGViewElement.h b/Source/core/svg/SVGViewElement.h
index d2bf387..881bfaf 100644
--- a/Source/core/svg/SVGViewElement.h
+++ b/Source/core/svg/SVGViewElement.h
@@ -21,6 +21,7 @@
 #ifndef SVGViewElement_h
 #define SVGViewElement_h
 
+#include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedPreserveAspectRatio.h"
 #include "core/svg/SVGAnimatedRect.h"
@@ -37,7 +38,7 @@
                              public SVGFitToViewBox,
                              public SVGZoomAndPan {
 public:
-    static PassRefPtr<SVGViewElement> create(const QualifiedName&, Document*);
+    static PassRefPtr<SVGViewElement> create(const QualifiedName&, Document&);
 
     using SVGElement::ref;
     using SVGElement::deref;
@@ -47,13 +48,13 @@
     void setZoomAndPan(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
 
 private:
-    SVGViewElement(const QualifiedName&, Document*);
+    SVGViewElement(const QualifiedName&, Document&);
 
     // FIXME: svgAttributeChanged missing.
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGViewElement)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
@@ -65,6 +66,12 @@
     SVGStringList m_viewTarget;
 };
 
+inline SVGViewElement* toSVGViewElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::viewTag));
+    return static_cast<SVGViewElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/svg/SVGViewSpec.cpp b/Source/core/svg/SVGViewSpec.cpp
index 69fc7d3..7a188cc 100644
--- a/Source/core/svg/SVGViewSpec.cpp
+++ b/Source/core/svg/SVGViewSpec.cpp
@@ -142,7 +142,7 @@
 {
     if (!m_contextElement)
         return 0;
-    Element* element = m_contextElement->treeScope()->getElementById(m_viewTargetString);
+    Element* element = m_contextElement->treeScope().getElementById(m_viewTargetString);
     if (!element || !element->isSVGElement())
         return 0;
     return toSVGElement(element);
@@ -224,7 +224,7 @@
                     return false;
                 ptr++;
                 FloatRect viewBox;
-                if (!SVGFitToViewBox::parseViewBox(m_contextElement->document(), ptr, end, viewBox, false))
+                if (!SVGFitToViewBox::parseViewBox(&m_contextElement->document(), ptr, end, viewBox, false))
                     return false;
                 setViewBoxBaseValue(viewBox);
                 if (ptr >= end || *ptr != ')')
diff --git a/Source/core/svg/SVGZoomAndPan.h b/Source/core/svg/SVGZoomAndPan.h
index 32759f3..b1432eb 100644
--- a/Source/core/svg/SVGZoomAndPan.h
+++ b/Source/core/svg/SVGZoomAndPan.h
@@ -59,7 +59,6 @@
     static bool parseAttribute(SVGElementTarget* target, const QualifiedName& name, const AtomicString& value)
     {
         ASSERT(target);
-        ASSERT(target->document());
         if (name == SVGNames::zoomAndPanAttr) {
             SVGZoomAndPanType zoomAndPan = SVGZoomAndPanUnknown;
             if (!value.isEmpty()) {
diff --git a/Source/core/svg/animation/SMILTime.h b/Source/core/svg/animation/SMILTime.h
index 9ff88c9..e572de3 100644
--- a/Source/core/svg/animation/SMILTime.h
+++ b/Source/core/svg/animation/SMILTime.h
@@ -26,7 +26,7 @@
 #ifndef SMILTime_h
 #define SMILTime_h
 
-#include <algorithm>
+#include "wtf/Assertions.h"
 #include "wtf/MathExtras.h"
 
 namespace WebCore {
diff --git a/Source/core/svg/animation/SMILTimeContainer.cpp b/Source/core/svg/animation/SMILTimeContainer.cpp
index 5b6ccc9..174c99f 100644
--- a/Source/core/svg/animation/SMILTimeContainer.cpp
+++ b/Source/core/svg/animation/SMILTimeContainer.cpp
@@ -273,6 +273,15 @@
     GroupedAnimationsMap::iterator end = m_scheduledAnimations.end();
     for (GroupedAnimationsMap::iterator it = m_scheduledAnimations.begin(); it != end; ++it) {
         AnimationsVector* scheduled = it->value.get();
+        unsigned size = scheduled->size();
+        for (unsigned n = 0; n < size; n++) {
+            SVGSMILElement* animation = scheduled->at(n);
+            animation->connectConditions();
+        }
+    }
+
+    for (GroupedAnimationsMap::iterator it = m_scheduledAnimations.begin(); it != end; ++it) {
+        AnimationsVector* scheduled = it->value.get();
 
         // Sort according to priority. Elements with later begin time have higher priority.
         // In case of a tie, document order decides.
diff --git a/Source/core/svg/animation/SVGSMILElement.cpp b/Source/core/svg/animation/SVGSMILElement.cpp
index c229f95..91c3499 100644
--- a/Source/core/svg/animation/SVGSMILElement.cpp
+++ b/Source/core/svg/animation/SVGSMILElement.cpp
@@ -31,6 +31,7 @@
 #include "bindings/v8/ExceptionStatePlaceholder.h"
 #include "core/dom/Document.h"
 #include "core/dom/EventListener.h"
+#include "core/dom/EventSender.h"
 #include "core/platform/FloatConversion.h"
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGSVGElement.h"
@@ -44,6 +45,30 @@
 
 namespace WebCore {
 
+static SMILEventSender& smilEndEventSender()
+{
+    DEFINE_STATIC_LOCAL(SMILEventSender, sender, ("endEvent"));
+    return sender;
+}
+
+static SMILEventSender& smilBeginEventSender()
+{
+    DEFINE_STATIC_LOCAL(SMILEventSender, sender, ("beginEvent"));
+    return sender;
+}
+
+static SMILEventSender& smilRepeatEventSender()
+{
+    DEFINE_STATIC_LOCAL(SMILEventSender, sender, ("repeatEvent"));
+    return sender;
+}
+
+static SMILEventSender& smilRepeatNEventSender()
+{
+    DEFINE_STATIC_LOCAL(SMILEventSender, sender, ("repeatn"));
+    return sender;
+}
+
 // This is used for duration type time values that can't be negative.
 static const double invalidCachedTime = -1.;
 
@@ -96,17 +121,16 @@
     m_animation->handleConditionEvent(event, m_condition);
 }
 
-SVGSMILElement::Condition::Condition(Type type, BeginOrEnd beginOrEnd, const String& baseID, const String& name, SMILTime offset, int repeats)
+SVGSMILElement::Condition::Condition(Type type, BeginOrEnd beginOrEnd, const String& baseID, const String& name, SMILTime offset)
     : m_type(type)
     , m_beginOrEnd(beginOrEnd)
     , m_baseID(baseID)
     , m_name(name)
     , m_offset(offset)
-    , m_repeats(repeats)
 {
 }
 
-SVGSMILElement::SVGSMILElement(const QualifiedName& tagName, Document* doc)
+SVGSMILElement::SVGSMILElement(const QualifiedName& tagName, Document& doc)
     : SVGElement(tagName, doc)
     , m_attributeName(anyQName())
     , m_targetElement(0)
@@ -133,6 +157,10 @@
 SVGSMILElement::~SVGSMILElement()
 {
     clearResourceReferences();
+    smilEndEventSender().cancelEvent(this);
+    smilBeginEventSender().cancelEvent(this);
+    smilRepeatEventSender().cancelEvent(this);
+    smilRepeatNEventSender().cancelEvent(this);
     disconnectConditions();
     if (m_timeContainer && m_targetElement && hasValidAttributeName())
         m_timeContainer->unschedule(this, m_targetElement, m_attributeName);
@@ -140,8 +168,7 @@
 
 void SVGSMILElement::clearResourceReferences()
 {
-    ASSERT(document());
-    document()->accessSVGExtensions()->removeAllTargetReferencesForElement(this);
+    document().accessSVGExtensions()->removeAllTargetReferencesForElement(this);
 }
 
 void SVGSMILElement::buildPendingResource()
@@ -171,17 +198,17 @@
 
     if (!svgTarget) {
         // Do not register as pending if we are already pending this resource.
-        if (document()->accessSVGExtensions()->isElementPendingResource(this, id))
+        if (document().accessSVGExtensions()->isElementPendingResource(this, id))
             return;
 
         if (!id.isEmpty()) {
-            document()->accessSVGExtensions()->addPendingResource(id, this);
+            document().accessSVGExtensions()->addPendingResource(id, this);
             ASSERT(hasPendingResources());
         }
     } else {
         // Register us with the target in the dependencies map. Any change of hrefElement
         // that leads to relayout/repainting now informs us, so we can react to it.
-        document()->accessSVGExtensions()->addElementReferencingTarget(this, svgTarget);
+        document().accessSVGExtensions()->addElementReferencingTarget(this, svgTarget);
     }
 }
 
@@ -346,7 +373,6 @@
     String parseString = value.stripWhiteSpace();
 
     double sign = 1.;
-    bool ok;
     size_t pos = parseString.find('+');
     if (pos == notFound) {
         pos = parseString.find('-');
@@ -381,16 +407,7 @@
         return false;
 
     Condition::Type type;
-    int repeats = -1;
-    if (nameString.startsWith("repeat(") && nameString.endsWith(')')) {
-        // FIXME: For repeat events we just need to add the data carrying TimeEvent class and
-        // fire the events at appropiate times.
-        repeats = nameString.substring(7, nameString.length() - 8).toUIntStrict(&ok);
-        if (!ok)
-            return false;
-        nameString = "repeat";
-        type = Condition::EventBase;
-    } else if (nameString == "begin" || nameString == "end") {
+    if (nameString == "begin" || nameString == "end") {
         if (baseID.isEmpty())
             return false;
         type = Condition::Syncbase;
@@ -400,7 +417,7 @@
     } else
         type = Condition::EventBase;
 
-    m_conditions.append(Condition(type, beginOrEnd, baseID, nameString, offset, repeats));
+    m_conditions.append(Condition(type, beginOrEnd, baseID, nameString, offset));
 
     if (type == Condition::EventBase && beginOrEnd == End)
         m_hasEndEventConditions = true;
@@ -511,7 +528,7 @@
 
 inline Element* SVGSMILElement::eventBaseFor(const Condition& condition)
 {
-    return condition.m_baseID.isEmpty() ? targetElement() : treeScope()->getElementById(condition.m_baseID);
+    return condition.m_baseID.isEmpty() ? targetElement() : treeScope().getElementById(condition.m_baseID);
 }
 
 void SVGSMILElement::connectConditions()
@@ -531,7 +548,7 @@
             eventBase->addEventListener(condition.m_name, condition.m_eventListener, false);
         } else if (condition.m_type == Condition::Syncbase) {
             ASSERT(!condition.m_baseID.isEmpty());
-            condition.m_syncbase = treeScope()->getElementById(condition.m_baseID);
+            condition.m_syncbase = treeScope().getElementById(condition.m_baseID);
             if (!isSMILElement(condition.m_syncbase.get())) {
                 condition.m_syncbase = 0;
                 continue;
@@ -1051,9 +1068,6 @@
     ASSERT(m_timeContainer);
     ASSERT(m_isWaitingForFirstInterval || m_intervalBegin.isFinite());
 
-    if (!m_conditionsConnected)
-        connectConditions();
-
     if (!m_intervalBegin.isFinite()) {
         ASSERT(m_activeState == Inactive);
         m_nextProgressTime = SMILTime::unresolved();
@@ -1101,8 +1115,13 @@
         resetAnimatedType();
 
     if (animationIsContributing) {
-        if (oldActiveState == Inactive)
+        if (oldActiveState == Inactive) {
+            smilBeginEventSender().dispatchEventSoon(this);
             startedActiveInterval();
+        }
+
+        if (repeat && repeat != m_lastRepeat)
+            dispatchRepeatEvents(repeat);
 
         updateAnimation(percent, repeat, resultElement);
         m_lastPercent = percent;
@@ -1110,11 +1129,28 @@
     }
 
     if (oldActiveState == Active && m_activeState != Active) {
+        smilEndEventSender().dispatchEventSoon(this);
         endedActiveInterval();
         if (m_activeState != Frozen && this == resultElement)
             clearAnimatedType(m_targetElement);
     }
 
+    // Triggering all the pending events if the animation timeline is changed.
+    if (seekToTime) {
+        if (m_activeState == Inactive)
+            smilBeginEventSender().dispatchEventSoon(this);
+
+        if (repeat) {
+            for (unsigned repeatEventCount = 1; repeatEventCount < repeat; repeatEventCount++)
+                dispatchRepeatEvents(repeatEventCount);
+            if (m_activeState == Inactive)
+                dispatchRepeatEvents(repeat);
+        }
+
+        if (m_activeState == Inactive || m_activeState == Frozen)
+            smilEndEventSender().dispatchEventSoon(this);
+    }
+
     m_nextProgressTime = calculateNextProgressTime(elapsed);
     return animationIsContributing;
 }
@@ -1191,4 +1227,24 @@
     clearTimesWithDynamicOrigins(m_endTimes);
 }
 
+void SVGSMILElement::dispatchRepeatEvents(unsigned count)
+{
+    m_repeatEventCountList.append(count);
+    smilRepeatEventSender().dispatchEventSoon(this);
+    smilRepeatNEventSender().dispatchEventSoon(this);
+}
+
+void SVGSMILElement::dispatchPendingEvent(SMILEventSender* eventSender)
+{
+    ASSERT(eventSender == &smilEndEventSender() || eventSender == &smilBeginEventSender() || eventSender == &smilRepeatEventSender() || eventSender == &smilRepeatNEventSender());
+    const AtomicString& eventType = eventSender->eventType();
+    if (eventType == "repeatn") {
+        unsigned repeatEventCount = m_repeatEventCountList.first();
+        m_repeatEventCountList.remove(0);
+        dispatchEvent(Event::create(String("repeat(" + String::number(repeatEventCount) + ")")));
+    } else {
+        dispatchEvent(Event::create(eventType));
+    }
+}
+
 }
diff --git a/Source/core/svg/animation/SVGSMILElement.h b/Source/core/svg/animation/SVGSMILElement.h
index 5d8c403..b7213f5 100644
--- a/Source/core/svg/animation/SVGSMILElement.h
+++ b/Source/core/svg/animation/SVGSMILElement.h
@@ -34,11 +34,15 @@
 
 class ConditionEventListener;
 class SMILTimeContainer;
+class SVGSMILElement;
+
+template<typename T> class EventSender;
+typedef EventSender<SVGSMILElement> SMILEventSender;
 
 // This class implements SMIL interval timing model as needed for SVG animation.
 class SVGSMILElement : public SVGElement {
 public:
-    SVGSMILElement(const QualifiedName&, Document*);
+    SVGSMILElement(const QualifiedName&, Document&);
     virtual ~SVGSMILElement();
 
     static bool isSMILElement(Node*);
@@ -109,6 +113,11 @@
     virtual void clearAnimatedType(SVGElement* targetElement) = 0;
     virtual void applyResultsToTarget() = 0;
 
+    void connectConditions();
+
+    void dispatchPendingEvent(SMILEventSender*);
+    void dispatchRepeatEvents(unsigned);
+
 protected:
     void addBeginTime(SMILTime eventTime, SMILTime endTime, SMILTimeWithOrigin::Origin = SMILTimeWithOrigin::ParserOrigin);
     void addEndTime(SMILTime eventTime, SMILTime endTime, SMILTimeWithOrigin::Origin = SMILTimeWithOrigin::ParserOrigin);
@@ -127,7 +136,7 @@
     void endedActiveInterval();
     virtual void updateAnimation(float percent, unsigned repeat, SVGSMILElement* resultElement) = 0;
 
-    virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE { return false; }
+    virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
 
     enum BeginOrEnd {
         Begin,
@@ -153,13 +162,12 @@
             AccessKey
         };
 
-        Condition(Type, BeginOrEnd, const String& baseID, const String& name, SMILTime offset, int repeats = -1);
+        Condition(Type, BeginOrEnd, const String& baseID, const String& name, SMILTime offset);
         Type m_type;
         BeginOrEnd m_beginOrEnd;
         String m_baseID;
         String m_name;
         SMILTime m_offset;
-        int m_repeats;
         RefPtr<Element> m_syncbase;
         RefPtr<ConditionEventListener> m_eventListener;
     };
@@ -167,7 +175,6 @@
     void parseBeginOrEnd(const String&, BeginOrEnd beginOrEnd);
     Element* eventBaseFor(const Condition&);
 
-    void connectConditions();
     void disconnectConditions();
 
     // Event base timing
@@ -226,6 +233,8 @@
     RefPtr<SMILTimeContainer> m_timeContainer;
     unsigned m_documentOrderIndex;
 
+    Vector<unsigned> m_repeatEventCountList;
+
     mutable SMILTime m_cachedDur;
     mutable SMILTime m_cachedRepeatDur;
     mutable SMILTime m_cachedRepeatCount;
diff --git a/Source/core/svg/graphics/SVGImage.cpp b/Source/core/svg/graphics/SVGImage.cpp
index 8f234ac..e44c11b 100644
--- a/Source/core/svg/graphics/SVGImage.cpp
+++ b/Source/core/svg/graphics/SVGImage.cpp
@@ -33,6 +33,7 @@
 #include "core/dom/shadow/ComposedTreeWalker.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/page/Chrome.h"
+#include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Settings.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
@@ -42,6 +43,7 @@
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/svg/RenderSVGRoot.h"
 #include "core/svg/SVGDocument.h"
+#include "core/svg/SVGFEImageElement.h"
 #include "core/svg/SVGImageElement.h"
 #include "core/svg/SVGSVGElement.h"
 #include "core/svg/graphics/SVGImageChromeClient.h"
@@ -70,19 +72,22 @@
 {
     ASSERT(element);
 
-    Page* page = element->document()->page();
+    Page* page = element->document().page();
     if (!page)
         return false;
 
     return page->chrome().client().isSVGImageChromeClient();
 }
 
-bool SVGImage::hasSingleSecurityOrigin() const
+bool SVGImage::currentFrameHasSingleSecurityOrigin() const
 {
     if (!m_page)
         return true;
 
     Frame* frame = m_page->mainFrame();
+
+    RELEASE_ASSERT(frame->document()->loadEventFinished());
+
     SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
     if (!rootElement)
         return true;
@@ -93,13 +98,10 @@
     while (Node* node = walker.get()) {
         if (node->hasTagName(SVGNames::foreignObjectTag))
             return false;
-        // FIXME(crbug.com/249037): Images should be allowed but the
-        // implementation is difficult because images can have animations which
-        // cause them to dynamically change their single-origin state.
         if (node->hasTagName(SVGNames::imageTag))
-            return false;
+            return toSVGImageElement(node)->currentFrameHasSingleSecurityOrigin();
         if (node->hasTagName(SVGNames::feImageTag))
-            return false;
+            return toSVGFEImageElement(node)->currentFrameHasSingleSecurityOrigin();
         walker.next();
     }
 
@@ -167,11 +169,8 @@
     if (!m_page)
         return;
 
-    ImageObserver* observer = imageObserver();
-    ASSERT(observer);
-
-    // Temporarily reset image observer, we don't want to receive any changeInRect() calls due to this relayout.
-    setImageObserver(0);
+    // Temporarily disable the image observer to prevent changeInRect() calls due re-laying out the image.
+    ImageObserverDisabler imageObserverDisabler(this);
 
     IntSize roundedContainerSize = roundedIntSize(containerSize);
     setContainerSize(roundedContainerSize);
@@ -185,8 +184,6 @@
     scaledSrc.setSize(adjustedSrcSize);
 
     draw(context, dstRect, scaledSrc, compositeOp, blendMode);
-
-    setImageObserver(observer);
 }
 
 PassRefPtr<NativeImageSkia> SVGImage::nativeImageForCurrentFrame()
@@ -240,8 +237,6 @@
     if (!m_page)
         return;
 
-    FrameView* view = frameView();
-
     GraphicsContextStateSaver stateSaver(*context);
     context->setCompositeOperation(compositeOp, blendMode);
     context->clip(enclosingIntRect(dstRect));
@@ -258,6 +253,7 @@
     context->translate(destOffset.x(), destOffset.y());
     context->scale(scale);
 
+    FrameView* view = frameView();
     view->resize(containerSize());
 
     if (view->needsLayout())
diff --git a/Source/core/svg/graphics/SVGImage.h b/Source/core/svg/graphics/SVGImage.h
index 74ea091..b75dd70 100644
--- a/Source/core/svg/graphics/SVGImage.h
+++ b/Source/core/svg/graphics/SVGImage.h
@@ -49,12 +49,11 @@
     static bool isInSVGImage(const Element*);
 
     RenderBox* embeddedContentBox() const;
-    FrameView* frameView() const;
 
     virtual bool isSVGImage() const OVERRIDE { return true; }
     virtual IntSize size() const OVERRIDE { return m_intrinsicSize; }
 
-    virtual bool hasSingleSecurityOrigin() const OVERRIDE;
+    virtual bool currentFrameHasSingleSecurityOrigin() const OVERRIDE;
 
     virtual bool hasRelativeWidth() const OVERRIDE;
     virtual bool hasRelativeHeight() const OVERRIDE;
@@ -66,11 +65,15 @@
     virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() OVERRIDE;
 
 private:
+    friend class AccessibilityRenderObject;
     friend class SVGImageChromeClient;
     friend class SVGImageForContainer;
 
     virtual ~SVGImage();
 
+    // Returns the SVG image document's frame.
+    FrameView* frameView() const;
+
     virtual String filenameExtension() const OVERRIDE;
 
     virtual void setContainerSize(const IntSize&) OVERRIDE;
@@ -98,6 +101,33 @@
     OwnPtr<Page> m_page;
     IntSize m_intrinsicSize;
 };
+
+inline SVGImage* toSVGImage(Image* image)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!image || image->isSVGImage());
+    return static_cast<SVGImage*>(image);
+}
+
+class ImageObserverDisabler {
+    WTF_MAKE_NONCOPYABLE(ImageObserverDisabler);
+public:
+    ImageObserverDisabler(Image* image)
+        : m_image(image)
+    {
+        ASSERT(m_image->imageObserver());
+        m_observer = m_image->imageObserver();
+        m_image->setImageObserver(0);
+    }
+
+    ~ImageObserverDisabler()
+    {
+        m_image->setImageObserver(m_observer);
+    }
+private:
+    Image* m_image;
+    ImageObserver* m_observer;
+};
+
 }
 
 #endif // SVGImage_h
diff --git a/Source/core/svg/graphics/filters/SVGFEImage.cpp b/Source/core/svg/graphics/filters/SVGFEImage.cpp
index 0f2bf2c..f61a702 100644
--- a/Source/core/svg/graphics/filters/SVGFEImage.cpp
+++ b/Source/core/svg/graphics/filters/SVGFEImage.cpp
@@ -47,9 +47,9 @@
 {
 }
 
-FEImage::FEImage(Filter* filter, Document* document, const String& href, const SVGPreserveAspectRatio& preserveAspectRatio)
+FEImage::FEImage(Filter* filter, Document& document, const String& href, const SVGPreserveAspectRatio& preserveAspectRatio)
     : FilterEffect(filter)
-    , m_document(document)
+    , m_document(&document)
     , m_href(href)
     , m_preserveAspectRatio(preserveAspectRatio)
 {
@@ -60,7 +60,7 @@
     return adoptRef(new FEImage(filter, image, preserveAspectRatio));
 }
 
-PassRefPtr<FEImage> FEImage::createWithIRIReference(Filter* filter, Document* document, const String& href, const SVGPreserveAspectRatio& preserveAspectRatio)
+PassRefPtr<FEImage> FEImage::createWithIRIReference(Filter* filter, Document& document, const String& href, const SVGPreserveAspectRatio& preserveAspectRatio)
 {
     return adoptRef(new FEImage(filter, document, href, preserveAspectRatio));
 }
@@ -86,7 +86,7 @@
 {
     if (!m_document)
         return 0;
-    Element* hrefElement = SVGURIReference::targetElementFromIRIString(m_href, m_document);
+    Element* hrefElement = SVGURIReference::targetElementFromIRIString(m_href, *m_document);
     if (!hrefElement || !hrefElement->isSVGElement())
         return 0;
     return hrefElement->renderer();
diff --git a/Source/core/svg/graphics/filters/SVGFEImage.h b/Source/core/svg/graphics/filters/SVGFEImage.h
index 1566b7a..3f75541 100644
--- a/Source/core/svg/graphics/filters/SVGFEImage.h
+++ b/Source/core/svg/graphics/filters/SVGFEImage.h
@@ -36,7 +36,7 @@
 class FEImage : public FilterEffect {
 public:
     static PassRefPtr<FEImage> createWithImage(Filter*, PassRefPtr<Image>, const SVGPreserveAspectRatio&);
-    static PassRefPtr<FEImage> createWithIRIReference(Filter*, Document*, const String&, const SVGPreserveAspectRatio&);
+    static PassRefPtr<FEImage> createWithIRIReference(Filter*, Document&, const String&, const SVGPreserveAspectRatio&);
 
     virtual void determineAbsolutePaintRect();
 
@@ -48,7 +48,7 @@
 private:
     virtual ~FEImage() { }
     FEImage(Filter*, PassRefPtr<Image>, const SVGPreserveAspectRatio&);
-    FEImage(Filter*, Document*, const String&, const SVGPreserveAspectRatio&);
+    FEImage(Filter*, Document&, const String&, const SVGPreserveAspectRatio&);
     RenderObject* referencedRenderer() const;
 
     virtual void applySoftware() OVERRIDE;
diff --git a/Source/core/svg/svgtags.in b/Source/core/svg/svgtags.in
index efa5f50..094ccaf 100644
--- a/Source/core/svg/svgtags.in
+++ b/Source/core/svg/svgtags.in
@@ -89,7 +89,6 @@
 text
 textPath
 title
-tref interfaceName=SVGTRefElement
 tspan interfaceName=SVGTSpanElement
 use constructorNeedsCreatedByParser
 view
diff --git a/Source/core/testing/InspectorFrontendClientLocal.h b/Source/core/testing/InspectorFrontendClientLocal.h
index f18fb0e..a97b8d8 100644
--- a/Source/core/testing/InspectorFrontendClientLocal.h
+++ b/Source/core/testing/InspectorFrontendClientLocal.h
@@ -52,30 +52,11 @@
 
     virtual void windowObjectCleared();
 
-    virtual void moveWindowBy(float x, float y) { }
-
-    virtual void requestSetDockSide(DockSide) { }
-    virtual void changeAttachedWindowHeight(unsigned) { }
-    virtual void openInNewTab(const String&) { }
-    virtual void save(const String&, const String&, bool) { }
-    virtual void append(const String&, const String&) { }
-
-    virtual void bringToFront() OVERRIDE { }
-    virtual void closeWindow() OVERRIDE { }
-
-    virtual void attachWindow(DockSide) { }
-    virtual void detachWindow() { }
-
     virtual void inspectedURLChanged(const String&) OVERRIDE { }
 
     virtual void sendMessageToBackend(const String& message);
 
-    virtual void requestFileSystems() { }
-    virtual void addFileSystem() { }
-    virtual void removeFileSystem(const String&) { }
-    virtual void indexPath(int requestId, const String& fileSystemPath) { }
-    virtual void stopIndexing(int requestId) { }
-    virtual void searchInPath(int requestId, const String& fileSystemPath, const String& query) { }
+    virtual void sendMessageToEmbedder(const String&) OVERRIDE { }
 
     virtual bool isUnderTest() { return true; }
 
diff --git a/Source/core/testing/InternalSettings.cpp b/Source/core/testing/InternalSettings.cpp
index 745e2fa..dc78943 100644
--- a/Source/core/testing/InternalSettings.cpp
+++ b/Source/core/testing/InternalSettings.cpp
@@ -58,7 +58,6 @@
 
 InternalSettings::Backup::Backup(Settings* settings)
     : m_originalCSSExclusionsEnabled(RuntimeEnabledFeatures::cssExclusionsEnabled())
-    , m_originalCSSShapesEnabled(RuntimeEnabledFeatures::cssShapesEnabled())
     , m_originalAuthorShadowDOMForAnyElementEnabled(RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
     , m_originalExperimentalWebSocketEnabled(settings->experimentalWebSocketEnabled())
     , m_originalStyleScoped(RuntimeEnabledFeatures::styleScopedEnabled())
@@ -74,13 +73,13 @@
     , m_shouldDisplayCaptions(settings->shouldDisplayCaptions())
     , m_shouldDisplayTextDescriptions(settings->shouldDisplayTextDescriptions())
     , m_defaultVideoPosterURL(settings->defaultVideoPosterURL())
+    , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->isCompositorDrivenAcceleratedScrollingEnabled())
 {
 }
 
 void InternalSettings::Backup::restoreTo(Settings* settings)
 {
     RuntimeEnabledFeatures::setCSSExclusionsEnabled(m_originalCSSExclusionsEnabled);
-    RuntimeEnabledFeatures::setCSSShapesEnabled(m_originalCSSShapesEnabled);
     RuntimeEnabledFeatures::setAuthorShadowDOMForAnyElementEnabled(m_originalAuthorShadowDOMForAnyElementEnabled);
     settings->setExperimentalWebSocketEnabled(m_originalExperimentalWebSocketEnabled);
     RuntimeEnabledFeatures::setStyleScopedEnabled(m_originalStyleScoped);
@@ -96,6 +95,7 @@
     settings->setShouldDisplayCaptions(m_shouldDisplayCaptions);
     settings->setShouldDisplayTextDescriptions(m_shouldDisplayTextDescriptions);
     settings->setDefaultVideoPosterURL(m_defaultVideoPosterURL);
+    settings->setCompositorDrivenAcceleratedScrollingEnabled(m_originalCompositorDrivenAcceleratedScrollEnabled);
 }
 
 // We can't use RefCountedSupplement because that would try to make InternalSettings RefCounted
diff --git a/Source/core/testing/InternalSettings.h b/Source/core/testing/InternalSettings.h
index 290566a..f364686 100644
--- a/Source/core/testing/InternalSettings.h
+++ b/Source/core/testing/InternalSettings.h
@@ -50,7 +50,6 @@
         void restoreTo(Settings*);
 
         bool m_originalCSSExclusionsEnabled;
-        bool m_originalCSSShapesEnabled;
         bool m_originalAuthorShadowDOMForAnyElementEnabled;
         bool m_originalExperimentalWebSocketEnabled;
         bool m_originalStyleScoped;
@@ -60,13 +59,13 @@
         float m_originalTextAutosizingFontScaleFactor;
         String m_originalMediaTypeOverride;
         bool m_originalMockScrollbarsEnabled;
-        bool m_originalUsesOverlayScrollbars;
         bool m_langAttributeAwareFormControlUIEnabled;
         bool m_imagesEnabled;
         bool m_shouldDisplaySubtitles;
         bool m_shouldDisplayCaptions;
         bool m_shouldDisplayTextDescriptions;
         String m_defaultVideoPosterURL;
+        bool m_originalCompositorDrivenAcceleratedScrollEnabled;
     };
 
     static PassRefPtr<InternalSettings> create(Page* page)
@@ -96,7 +95,6 @@
     void setTextAutosizingFontScaleFactor(float fontScaleFactor, ExceptionState&);
     void setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState&);
     void setTouchEventEmulationEnabled(bool, ExceptionState&);
-    void setUsesOverlayScrollbars(bool, ExceptionState&);
     void setViewportEnabled(bool, ExceptionState&);
 
     // FIXME: This is a temporary flag and should be removed once accelerated
diff --git a/Source/core/testing/Internals.cpp b/Source/core/testing/Internals.cpp
index 39b409f..ad961fa 100644
--- a/Source/core/testing/Internals.cpp
+++ b/Source/core/testing/Internals.cpp
@@ -54,12 +54,12 @@
 #include "core/dom/Element.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/FullscreenElementStack.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/PseudoElement.h"
 #include "core/dom/Range.h"
 #include "core/dom/StaticNodeList.h"
 #include "core/dom/TreeScope.h"
 #include "core/dom/ViewportArguments.h"
+#include "core/dom/WheelController.h"
 #include "core/dom/shadow/ComposedTreeWalker.h"
 #include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/SelectRuleFeatureSet.h"
@@ -195,7 +195,7 @@
     page->setPagination(Pagination());
     TextRun::setAllowsRoundingHacks(false);
     WebCore::overrideUserPreferredLanguages(Vector<String>());
-    WebCore::Settings::setUsesOverlayScrollbars(false);
+    WebCore::RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(false);
     delete s_pagePopupDriver;
     s_pagePopupDriver = 0;
     page->chrome().client().resetPagePopupDriver();
@@ -299,7 +299,7 @@
         return 0;
     }
 
-    return HTMLContentElement::create(document);
+    return HTMLContentElement::create(*document);
 }
 
 bool Internals::isValidContentSelect(Element* insertionPoint, ExceptionState& es)
@@ -319,7 +319,7 @@
         return 0;
     }
 
-    return node->treeScope()->rootNode();
+    return node->treeScope().rootNode();
 }
 
 Node* Internals::parentTreeScope(Node* node, ExceptionState& es)
@@ -328,7 +328,7 @@
         es.throwDOMException(InvalidAccessError);
         return 0;
     }
-    const TreeScope* parentTreeScope = node->treeScope()->parentTreeScope();
+    const TreeScope* parentTreeScope = node->treeScope().parentTreeScope();
     return parentTreeScope ? parentTreeScope->rootNode() : 0;
 }
 
@@ -403,7 +403,7 @@
         es.throwDOMException(InvalidAccessError);
         return 0;
     }
-    return treeScope1->comparePosition(treeScope2);
+    return treeScope1->comparePosition(*treeScope2);
 }
 
 unsigned Internals::numberOfActiveAnimations() const
@@ -717,7 +717,7 @@
 {
     if (!element->hasTagName(inputTag))
         return;
-    toHTMLInputElement(element)->selectColorInColorChooser(StyleColor(colorValue).color());
+    toHTMLInputElement(element)->selectColorInColorChooser(Color(colorValue));
 }
 
 Vector<String> Internals::formControlStateOfPreviousHistoryItem(ExceptionState& es)
@@ -797,12 +797,12 @@
 PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionState& es)
 {
     Document* document = contextDocument();
-    if (!document || !document->frame() || !document->frame()->selection()) {
+    if (!document || !document->frame()) {
         es.throwDOMException(InvalidAccessError);
         return ClientRect::create();
     }
 
-    return ClientRect::create(document->frame()->selection()->absoluteCaretBounds());
+    return ClientRect::create(document->frame()->selection().absoluteCaretBounds());
 }
 
 PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionState& es)
@@ -812,7 +812,7 @@
         return ClientRect::create();
     }
 
-    element->document()->updateLayoutIgnorePendingStylesheets();
+    element->document().updateLayoutIgnorePendingStylesheets();
     RenderObject* renderer = element->renderer();
     if (!renderer)
         return ClientRect::create();
@@ -844,7 +844,7 @@
         return 0;
     }
 
-    return node->document()->markers()->markersFor(node, markerTypes).size();
+    return node->document().markers()->markersFor(node, markerTypes).size();
 }
 
 unsigned Internals::activeMarkerCountForNode(Node* node, ExceptionState& es)
@@ -856,7 +856,7 @@
 
     // Only TextMatch markers can be active.
     DocumentMarker::MarkerType markerType = DocumentMarker::TextMatch;
-    Vector<DocumentMarker*> markers = node->document()->markers()->markersFor(node, markerType);
+    Vector<DocumentMarker*> markers = node->document().markers()->markersFor(node, markerType);
 
     unsigned activeMarkerCount = 0;
     for (Vector<DocumentMarker*>::iterator iter = markers.begin(); iter != markers.end(); ++iter) {
@@ -880,7 +880,7 @@
         return 0;
     }
 
-    Vector<DocumentMarker*> markers = node->document()->markers()->markersFor(node, markerTypes);
+    Vector<DocumentMarker*> markers = node->document().markers()->markersFor(node, markerTypes);
     if (markers.size() <= index)
         return 0;
     return markers[index];
@@ -904,8 +904,8 @@
 
 void Internals::addTextMatchMarker(const Range* range, bool isActive)
 {
-    range->ownerDocument()->updateLayoutIgnorePendingStylesheets();
-    range->ownerDocument()->markers()->addTextMatchMarker(range, isActive);
+    range->ownerDocument().updateLayoutIgnorePendingStylesheets();
+    range->ownerDocument().markers()->addTextMatchMarker(range, isActive);
 }
 
 void Internals::setMarkersActive(Node* node, unsigned startOffset, unsigned endOffset, bool active, ExceptionState& es)
@@ -915,7 +915,7 @@
         return;
     }
 
-    node->document()->markers()->setMarkersActive(node, startOffset, endOffset, active);
+    node->document().markers()->setMarkersActive(node, startOffset, endOffset, active);
 }
 
 void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionState& es)
@@ -978,7 +978,7 @@
     document->page()->mainFrame()->view()->setFrameRect(IntRect(IntPoint::zero(), initialViewportSize));
 
     ViewportArguments arguments = page->viewportArguments();
-    PageScaleConstraints constraints = arguments.resolve(initialViewportSize, 980 /* defaultLayoutWidthForNonMobilePages */);
+    PageScaleConstraints constraints = arguments.resolve(initialViewportSize);
 
     constraints.fitToContentsWidth(constraints.layoutSize.width(), availableWidth);
 
@@ -1090,11 +1090,11 @@
 
 void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionState& es)
 {
-    if (!element || !element->document() || !element->document()->view()) {
+    if (!element || !element->document().view()) {
         es.throwDOMException(InvalidAccessError);
         return;
     }
-    FrameView* frameView = element->document()->view();
+    FrameView* frameView = element->document().view();
     frameView->scrollElementToRect(element, IntRect(x, y, w, h));
 }
 
@@ -1117,7 +1117,7 @@
     }
 
     // TextIterator depends on Layout information, make sure layout it up to date.
-    scope->document()->updateLayoutIgnorePendingStylesheets();
+    scope->document().updateLayoutIgnorePendingStylesheets();
 
     return TextIterator::rangeFromLocationAndLength(scope, rangeLocation, rangeLength);
 }
@@ -1130,7 +1130,7 @@
     }
 
     // TextIterator depends on Layout information, make sure layout it up to date.
-    scope->document()->updateLayoutIgnorePendingStylesheets();
+    scope->document().updateLayoutIgnorePendingStylesheets();
 
     size_t location = 0;
     size_t unusedLength = 0;
@@ -1146,7 +1146,7 @@
     }
 
     // TextIterator depends on Layout information, make sure layout it up to date.
-    scope->document()->updateLayoutIgnorePendingStylesheets();
+    scope->document().updateLayoutIgnorePendingStylesheets();
 
     size_t unusedLocation = 0;
     size_t length = 0;
@@ -1307,7 +1307,7 @@
         return 0;
     }
 
-    return document->wheelEventHandlerCount();
+    return WheelController::from(document)->wheelEventHandlerCount();
 }
 
 unsigned Internals::touchEventHandlerCount(Document* document, ExceptionState& es)
@@ -1544,11 +1544,17 @@
 
 unsigned Internals::numberOfLiveNodes() const
 {
+    if (StyleResolver* resolver = contextDocument()->styleResolverIfExists())
+        resolver->clearStyleSharingList();
+
     return InspectorCounters::counterValue(InspectorCounters::NodeCounter);
 }
 
 unsigned Internals::numberOfLiveDocuments() const
 {
+    if (StyleResolver* resolver = contextDocument()->styleResolverIfExists())
+        resolver->clearStyleSharingList();
+
     return InspectorCounters::counterValue(InspectorCounters::DocumentCounter);
 }
 
@@ -1676,7 +1682,7 @@
         return 0;
     }
 
-    element->document()->updateLayout();
+    element->document().updateLayout();
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
@@ -1712,7 +1718,7 @@
         return 0;
     }
 
-    element1->document()->updateLayout();
+    element1->document().updateLayout();
 
     RenderObject* renderer1 = element1->renderer();
     RenderObject* renderer2 = element2->renderer();
@@ -1748,7 +1754,7 @@
         return String();
     }
 
-    element->document()->updateLayout();
+    element->document().updateLayout();
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
@@ -1774,7 +1780,7 @@
         return;
     }
 
-    element->document()->updateLayout();
+    element->document().updateLayout();
 
     RenderObject* renderer = element->renderer();
     if (!renderer || !renderer->isBox()) {
@@ -1841,6 +1847,11 @@
         return;
     }
 
+    if (StyleResolver* resolver = contextDocument()->styleResolverIfExists())
+        resolver->clearStyleSharingList();
+    if (StyleResolver* resolver = document->styleResolverIfExists())
+        resolver->clearStyleSharingList();
+
     ResourceFetcher* fetcher = document->fetcher();
     if (!fetcher)
         return;
@@ -1859,7 +1870,10 @@
 
 void Internals::insertAuthorCSS(Document* document, const String& css) const
 {
-    RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(document);
+    if (!document)
+        return;
+
+    RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(*document);
     parsedSheet->setIsUserStyleSheet(false);
     parsedSheet->parseString(css);
     document->styleSheetCollections()->addAuthorSheet(parsedSheet);
@@ -1867,7 +1881,10 @@
 
 void Internals::insertUserCSS(Document* document, const String& css) const
 {
-    RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(document);
+    if (!document)
+        return;
+
+    RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(*document);
     parsedSheet->setIsUserStyleSheet(true);
     parsedSheet->parseString(css);
     document->styleSheetCollections()->addUserSheet(parsedSheet);
@@ -2134,9 +2151,9 @@
     return SerializedScriptValue::createFromWire(value);
 }
 
-void Internals::setUsesOverlayScrollbars(bool enabled)
+void Internals::setOverlayScrollbarsEnabled(bool enabled)
 {
-    WebCore::Settings::setUsesOverlayScrollbars(enabled);
+    RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);
 }
 
 void Internals::forceReload(bool endToEnd)
@@ -2147,12 +2164,12 @@
 PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionState& es)
 {
     Document* document = contextDocument();
-    if (!document || !document->frame() || !document->frame()->selection()) {
+    if (!document || !document->frame()) {
         es.throwDOMException(InvalidAccessError);
         return 0;
     }
 
-    return ClientRect::create(document->frame()->selection()->bounds());
+    return ClientRect::create(document->frame()->selection().bounds());
 }
 
 String Internals::markerTextForListItem(Element* element, ExceptionState& es)
diff --git a/Source/core/testing/Internals.h b/Source/core/testing/Internals.h
index 5a7d162..817c1fc 100644
--- a/Source/core/testing/Internals.h
+++ b/Source/core/testing/Internals.h
@@ -278,7 +278,7 @@
     PassRefPtr<ArrayBuffer> serializeObject(PassRefPtr<SerializedScriptValue>) const;
     PassRefPtr<SerializedScriptValue> deserializeBuffer(PassRefPtr<ArrayBuffer>) const;
 
-    void setUsesOverlayScrollbars(bool enabled);
+    void setOverlayScrollbarsEnabled(bool);
 
     String getCurrentCursorInfo(Document*, ExceptionState&);
 
diff --git a/Source/core/testing/Internals.idl b/Source/core/testing/Internals.idl
index a7c648d..6e5f1a2 100644
--- a/Source/core/testing/Internals.idl
+++ b/Source/core/testing/Internals.idl
@@ -248,7 +248,7 @@
     SerializedScriptValue deserializeBuffer(ArrayBuffer buffer);
     ArrayBuffer serializeObject(SerializedScriptValue obj);
 
-    void setUsesOverlayScrollbars(boolean enabled);
+    void setOverlayScrollbarsEnabled(boolean enabled);
 
     void forceReload(boolean endToEnd);
 
diff --git a/Source/core/testing/MockPagePopupDriver.cpp b/Source/core/testing/MockPagePopupDriver.cpp
index 966897b..5ca92ce 100644
--- a/Source/core/testing/MockPagePopupDriver.cpp
+++ b/Source/core/testing/MockPagePopupDriver.cpp
@@ -61,7 +61,8 @@
     , m_closeTimer(this, &MockPagePopup::close)
 {
     Document* document = mainFrame->document();
-    m_iframe = HTMLIFrameElement::create(HTMLNames::iframeTag, document);
+    ASSERT(document);
+    m_iframe = HTMLIFrameElement::create(HTMLNames::iframeTag, *document);
     m_iframe->setIdAttribute("mock-page-popup");
     m_iframe->setInlineStyleProperty(CSSPropertyBorderWidth, 0.0, CSSPrimitiveValue::CSS_PX);
     m_iframe->setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
diff --git a/Source/core/testing/v8/WebCoreTestSupport.cpp b/Source/core/testing/v8/WebCoreTestSupport.cpp
index e48d100..e18e369 100644
--- a/Source/core/testing/v8/WebCoreTestSupport.cpp
+++ b/Source/core/testing/v8/WebCoreTestSupport.cpp
@@ -42,8 +42,7 @@
 void injectInternalsObject(v8::Local<v8::Context> context)
 {
     v8::Context::Scope contextScope(context);
-    v8::HandleScope scope;
-
+    v8::HandleScope scope(context->GetIsolate());
     ScriptExecutionContext* scriptContext = getScriptExecutionContext();
     if (scriptContext->isDocument())
         context->Global()->Set(v8::String::New(Internals::internalsId), toV8(Internals::create(toDocument(scriptContext)), v8::Handle<v8::Object>(), context->GetIsolate()));
@@ -56,7 +55,7 @@
         return;
 
     v8::Context::Scope contextScope(context);
-    v8::HandleScope scope;
+    v8::HandleScope scope(context->GetIsolate());
 
     ScriptExecutionContext* scriptContext = getScriptExecutionContext();
     Page* page = toDocument(scriptContext)->frame()->page();
diff --git a/Source/core/tests/LayoutUnit.cpp b/Source/core/tests/LayoutUnit.cpp
index e675ca8..0953f93 100644
--- a/Source/core/tests/LayoutUnit.cpp
+++ b/Source/core/tests/LayoutUnit.cpp
@@ -29,9 +29,10 @@
  */
 
 #include "config.h"
+#include "core/platform/LayoutUnit.h"
 
 #include <gtest/gtest.h>
-#include "core/platform/LayoutUnit.h"
+#include <limits.h>
 
 using namespace WebCore;
 
diff --git a/Source/core/webcore_arm_neon.target.darwin-arm.mk b/Source/core/webcore_arm_neon.target.darwin-arm.mk
index 8e4a7f7..270a8d5 100644
--- a/Source/core/webcore_arm_neon.target.darwin-arm.mk
+++ b/Source/core/webcore_arm_neon.target.darwin-arm.mk
@@ -33,7 +33,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -52,7 +54,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_arm_neon.target.linux-arm.mk b/Source/core/webcore_arm_neon.target.linux-arm.mk
index 8e4a7f7..270a8d5 100644
--- a/Source/core/webcore_arm_neon.target.linux-arm.mk
+++ b/Source/core/webcore_arm_neon.target.linux-arm.mk
@@ -33,7 +33,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -52,7 +54,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_derived.target.darwin-arm.mk b/Source/core/webcore_derived.target.darwin-arm.mk
index 83aa859..1626ee5 100644
--- a/Source/core/webcore_derived.target.darwin-arm.mk
+++ b/Source/core/webcore_derived.target.darwin-arm.mk
@@ -311,6 +311,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
@@ -384,6 +386,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -396,6 +399,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -413,12 +417,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -550,6 +552,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -562,6 +565,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -579,12 +583,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -695,7 +697,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -714,7 +718,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_derived.target.darwin-mips.mk b/Source/core/webcore_derived.target.darwin-mips.mk
index e4e6961..d7b8411 100644
--- a/Source/core/webcore_derived.target.darwin-mips.mk
+++ b/Source/core/webcore_derived.target.darwin-mips.mk
@@ -311,6 +311,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
@@ -384,6 +386,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -396,6 +399,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -413,12 +417,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -550,6 +552,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -562,6 +565,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -579,12 +583,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -693,7 +695,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -710,7 +714,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_derived.target.darwin-x86.mk b/Source/core/webcore_derived.target.darwin-x86.mk
index bc828f6..eca73ea 100644
--- a/Source/core/webcore_derived.target.darwin-x86.mk
+++ b/Source/core/webcore_derived.target.darwin-x86.mk
@@ -311,6 +311,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
@@ -386,6 +388,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -398,6 +401,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -415,12 +419,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -555,6 +557,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -567,6 +570,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -584,12 +588,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -697,7 +699,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -714,7 +718,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_derived.target.linux-arm.mk b/Source/core/webcore_derived.target.linux-arm.mk
index 83aa859..1626ee5 100644
--- a/Source/core/webcore_derived.target.linux-arm.mk
+++ b/Source/core/webcore_derived.target.linux-arm.mk
@@ -311,6 +311,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
@@ -384,6 +386,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -396,6 +399,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -413,12 +417,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -550,6 +552,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -562,6 +565,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -579,12 +583,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -695,7 +697,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -714,7 +718,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_derived.target.linux-mips.mk b/Source/core/webcore_derived.target.linux-mips.mk
index e4e6961..d7b8411 100644
--- a/Source/core/webcore_derived.target.linux-mips.mk
+++ b/Source/core/webcore_derived.target.linux-mips.mk
@@ -311,6 +311,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
@@ -384,6 +386,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -396,6 +399,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -413,12 +417,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -550,6 +552,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -562,6 +565,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -579,12 +583,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -693,7 +695,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -710,7 +714,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_derived.target.linux-x86.mk b/Source/core/webcore_derived.target.linux-x86.mk
index bc828f6..eca73ea 100644
--- a/Source/core/webcore_derived.target.linux-x86.mk
+++ b/Source/core/webcore_derived.target.linux-x86.mk
@@ -311,6 +311,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8InspectorFrontendHostCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8JavaScriptCallFrameCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8LocationCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIInputCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8MIDIOutputCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageChannelCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8MessagePortCustom.cpp \
@@ -386,6 +388,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -398,6 +401,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -415,12 +419,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -555,6 +557,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -567,6 +570,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -584,12 +588,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -697,7 +699,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -714,7 +718,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_dom.target.darwin-arm.mk b/Source/core/webcore_dom.target.darwin-arm.mk
index 31789c6..007c570 100644
--- a/Source/core/webcore_dom.target.darwin-arm.mk
+++ b/Source/core/webcore_dom.target.darwin-arm.mk
@@ -63,6 +63,7 @@
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
+	third_party/WebKit/Source/core/dom/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
@@ -137,6 +138,7 @@
 	third_party/WebKit/Source/core/dom/PositionIterator.cpp \
 	third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp \
 	third_party/WebKit/Source/core/dom/ProgressEvent.cpp \
+	third_party/WebKit/Source/core/dom/PostAttachCallbacks.cpp \
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
@@ -149,6 +151,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
@@ -178,6 +181,7 @@
 	third_party/WebKit/Source/core/dom/ViewportArguments.cpp \
 	third_party/WebKit/Source/core/dom/VisitedLinkState.cpp \
 	third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp \
+	third_party/WebKit/Source/core/dom/WheelController.cpp \
 	third_party/WebKit/Source/core/dom/WheelEvent.cpp \
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
@@ -227,6 +231,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -239,6 +244,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -256,12 +262,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -384,6 +388,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -396,6 +401,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -413,12 +419,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -520,7 +524,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -539,7 +545,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_dom.target.darwin-mips.mk b/Source/core/webcore_dom.target.darwin-mips.mk
index 5035ea7..87cb87b 100644
--- a/Source/core/webcore_dom.target.darwin-mips.mk
+++ b/Source/core/webcore_dom.target.darwin-mips.mk
@@ -63,6 +63,7 @@
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
+	third_party/WebKit/Source/core/dom/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
@@ -137,6 +138,7 @@
 	third_party/WebKit/Source/core/dom/PositionIterator.cpp \
 	third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp \
 	third_party/WebKit/Source/core/dom/ProgressEvent.cpp \
+	third_party/WebKit/Source/core/dom/PostAttachCallbacks.cpp \
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
@@ -149,6 +151,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
@@ -178,6 +181,7 @@
 	third_party/WebKit/Source/core/dom/ViewportArguments.cpp \
 	third_party/WebKit/Source/core/dom/VisitedLinkState.cpp \
 	third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp \
+	third_party/WebKit/Source/core/dom/WheelController.cpp \
 	third_party/WebKit/Source/core/dom/WheelEvent.cpp \
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
@@ -227,6 +231,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -239,6 +244,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -256,12 +262,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -384,6 +388,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -396,6 +401,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -413,12 +419,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -518,7 +522,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -535,7 +541,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_dom.target.darwin-x86.mk b/Source/core/webcore_dom.target.darwin-x86.mk
index 2e87aab..fb7e8df 100644
--- a/Source/core/webcore_dom.target.darwin-x86.mk
+++ b/Source/core/webcore_dom.target.darwin-x86.mk
@@ -63,6 +63,7 @@
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
+	third_party/WebKit/Source/core/dom/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
@@ -137,6 +138,7 @@
 	third_party/WebKit/Source/core/dom/PositionIterator.cpp \
 	third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp \
 	third_party/WebKit/Source/core/dom/ProgressEvent.cpp \
+	third_party/WebKit/Source/core/dom/PostAttachCallbacks.cpp \
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
@@ -149,6 +151,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
@@ -178,6 +181,7 @@
 	third_party/WebKit/Source/core/dom/ViewportArguments.cpp \
 	third_party/WebKit/Source/core/dom/VisitedLinkState.cpp \
 	third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp \
+	third_party/WebKit/Source/core/dom/WheelController.cpp \
 	third_party/WebKit/Source/core/dom/WheelEvent.cpp \
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
@@ -229,6 +233,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -241,6 +246,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -258,12 +264,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -389,6 +393,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -401,6 +406,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -418,12 +424,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -522,7 +526,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -539,7 +545,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_dom.target.linux-arm.mk b/Source/core/webcore_dom.target.linux-arm.mk
index 31789c6..007c570 100644
--- a/Source/core/webcore_dom.target.linux-arm.mk
+++ b/Source/core/webcore_dom.target.linux-arm.mk
@@ -63,6 +63,7 @@
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
+	third_party/WebKit/Source/core/dom/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
@@ -137,6 +138,7 @@
 	third_party/WebKit/Source/core/dom/PositionIterator.cpp \
 	third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp \
 	third_party/WebKit/Source/core/dom/ProgressEvent.cpp \
+	third_party/WebKit/Source/core/dom/PostAttachCallbacks.cpp \
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
@@ -149,6 +151,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
@@ -178,6 +181,7 @@
 	third_party/WebKit/Source/core/dom/ViewportArguments.cpp \
 	third_party/WebKit/Source/core/dom/VisitedLinkState.cpp \
 	third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp \
+	third_party/WebKit/Source/core/dom/WheelController.cpp \
 	third_party/WebKit/Source/core/dom/WheelEvent.cpp \
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
@@ -227,6 +231,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -239,6 +244,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -256,12 +262,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -384,6 +388,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -396,6 +401,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -413,12 +419,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -520,7 +524,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -539,7 +545,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_dom.target.linux-mips.mk b/Source/core/webcore_dom.target.linux-mips.mk
index 5035ea7..87cb87b 100644
--- a/Source/core/webcore_dom.target.linux-mips.mk
+++ b/Source/core/webcore_dom.target.linux-mips.mk
@@ -63,6 +63,7 @@
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
+	third_party/WebKit/Source/core/dom/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
@@ -137,6 +138,7 @@
 	third_party/WebKit/Source/core/dom/PositionIterator.cpp \
 	third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp \
 	third_party/WebKit/Source/core/dom/ProgressEvent.cpp \
+	third_party/WebKit/Source/core/dom/PostAttachCallbacks.cpp \
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
@@ -149,6 +151,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
@@ -178,6 +181,7 @@
 	third_party/WebKit/Source/core/dom/ViewportArguments.cpp \
 	third_party/WebKit/Source/core/dom/VisitedLinkState.cpp \
 	third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp \
+	third_party/WebKit/Source/core/dom/WheelController.cpp \
 	third_party/WebKit/Source/core/dom/WheelEvent.cpp \
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
@@ -227,6 +231,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -239,6 +244,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -256,12 +262,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -384,6 +388,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -396,6 +401,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -413,12 +419,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -518,7 +522,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -535,7 +541,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_dom.target.linux-x86.mk b/Source/core/webcore_dom.target.linux-x86.mk
index 2e87aab..fb7e8df 100644
--- a/Source/core/webcore_dom.target.linux-x86.mk
+++ b/Source/core/webcore_dom.target.linux-x86.mk
@@ -63,6 +63,7 @@
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringMap.cpp \
+	third_party/WebKit/Source/core/dom/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/dom/DataTransferItem.cpp \
 	third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp \
 	third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp \
@@ -137,6 +138,7 @@
 	third_party/WebKit/Source/core/dom/PositionIterator.cpp \
 	third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp \
 	third_party/WebKit/Source/core/dom/ProgressEvent.cpp \
+	third_party/WebKit/Source/core/dom/PostAttachCallbacks.cpp \
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
@@ -149,6 +151,7 @@
 	third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp \
 	third_party/WebKit/Source/core/dom/SecurityContext.cpp \
 	third_party/WebKit/Source/core/dom/SelectorQuery.cpp \
+	third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp \
 	third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp \
 	third_party/WebKit/Source/core/dom/SpaceSplitString.cpp \
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
@@ -178,6 +181,7 @@
 	third_party/WebKit/Source/core/dom/ViewportArguments.cpp \
 	third_party/WebKit/Source/core/dom/VisitedLinkState.cpp \
 	third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp \
+	third_party/WebKit/Source/core/dom/WheelController.cpp \
 	third_party/WebKit/Source/core/dom/WheelEvent.cpp \
 	third_party/WebKit/Source/core/dom/WindowEventContext.cpp \
 	third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp \
@@ -229,6 +233,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -241,6 +246,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -258,12 +264,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -389,6 +393,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -401,6 +406,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -418,12 +424,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -522,7 +526,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -539,7 +545,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_html.target.darwin-arm.mk b/Source/core/webcore_html.target.darwin-arm.mk
index 90420d6..d73b1c0 100644
--- a/Source/core/webcore_html.target.darwin-arm.mk
+++ b/Source/core/webcore_html.target.darwin-arm.mk
@@ -36,8 +36,6 @@
 	third_party/WebKit/Source/core/html/ClassList.cpp \
 	third_party/WebKit/Source/core/html/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/DOMFormData.cpp \
-	third_party/WebKit/Source/core/html/DOMSettableTokenList.cpp \
-	third_party/WebKit/Source/core/html/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/html/DOMURL.cpp \
 	third_party/WebKit/Source/core/html/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/DateTimeFieldsState.cpp \
@@ -328,6 +326,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -340,6 +339,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -357,12 +357,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -485,6 +483,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -497,6 +496,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -514,12 +514,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -621,7 +619,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -640,7 +640,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_html.target.darwin-mips.mk b/Source/core/webcore_html.target.darwin-mips.mk
index e75dfa6..34afd9e 100644
--- a/Source/core/webcore_html.target.darwin-mips.mk
+++ b/Source/core/webcore_html.target.darwin-mips.mk
@@ -36,8 +36,6 @@
 	third_party/WebKit/Source/core/html/ClassList.cpp \
 	third_party/WebKit/Source/core/html/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/DOMFormData.cpp \
-	third_party/WebKit/Source/core/html/DOMSettableTokenList.cpp \
-	third_party/WebKit/Source/core/html/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/html/DOMURL.cpp \
 	third_party/WebKit/Source/core/html/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/DateTimeFieldsState.cpp \
@@ -328,6 +326,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -340,6 +339,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -357,12 +357,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -485,6 +483,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -497,6 +496,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -514,12 +514,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -619,7 +617,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -636,7 +636,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_html.target.darwin-x86.mk b/Source/core/webcore_html.target.darwin-x86.mk
index 077fac0..8a9c36a 100644
--- a/Source/core/webcore_html.target.darwin-x86.mk
+++ b/Source/core/webcore_html.target.darwin-x86.mk
@@ -36,8 +36,6 @@
 	third_party/WebKit/Source/core/html/ClassList.cpp \
 	third_party/WebKit/Source/core/html/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/DOMFormData.cpp \
-	third_party/WebKit/Source/core/html/DOMSettableTokenList.cpp \
-	third_party/WebKit/Source/core/html/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/html/DOMURL.cpp \
 	third_party/WebKit/Source/core/html/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/DateTimeFieldsState.cpp \
@@ -330,6 +328,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -342,6 +341,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -359,12 +359,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -490,6 +488,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -502,6 +501,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -519,12 +519,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -623,7 +621,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -640,7 +640,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_html.target.linux-arm.mk b/Source/core/webcore_html.target.linux-arm.mk
index 90420d6..d73b1c0 100644
--- a/Source/core/webcore_html.target.linux-arm.mk
+++ b/Source/core/webcore_html.target.linux-arm.mk
@@ -36,8 +36,6 @@
 	third_party/WebKit/Source/core/html/ClassList.cpp \
 	third_party/WebKit/Source/core/html/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/DOMFormData.cpp \
-	third_party/WebKit/Source/core/html/DOMSettableTokenList.cpp \
-	third_party/WebKit/Source/core/html/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/html/DOMURL.cpp \
 	third_party/WebKit/Source/core/html/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/DateTimeFieldsState.cpp \
@@ -328,6 +326,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -340,6 +339,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -357,12 +357,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -485,6 +483,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -497,6 +496,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -514,12 +514,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -621,7 +619,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -640,7 +640,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_html.target.linux-mips.mk b/Source/core/webcore_html.target.linux-mips.mk
index e75dfa6..34afd9e 100644
--- a/Source/core/webcore_html.target.linux-mips.mk
+++ b/Source/core/webcore_html.target.linux-mips.mk
@@ -36,8 +36,6 @@
 	third_party/WebKit/Source/core/html/ClassList.cpp \
 	third_party/WebKit/Source/core/html/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/DOMFormData.cpp \
-	third_party/WebKit/Source/core/html/DOMSettableTokenList.cpp \
-	third_party/WebKit/Source/core/html/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/html/DOMURL.cpp \
 	third_party/WebKit/Source/core/html/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/DateTimeFieldsState.cpp \
@@ -328,6 +326,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -340,6 +339,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -357,12 +357,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -485,6 +483,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -497,6 +496,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -514,12 +514,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -619,7 +617,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -636,7 +636,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_html.target.linux-x86.mk b/Source/core/webcore_html.target.linux-x86.mk
index 077fac0..8a9c36a 100644
--- a/Source/core/webcore_html.target.linux-x86.mk
+++ b/Source/core/webcore_html.target.linux-x86.mk
@@ -36,8 +36,6 @@
 	third_party/WebKit/Source/core/html/ClassList.cpp \
 	third_party/WebKit/Source/core/html/ColorInputType.cpp \
 	third_party/WebKit/Source/core/html/DOMFormData.cpp \
-	third_party/WebKit/Source/core/html/DOMSettableTokenList.cpp \
-	third_party/WebKit/Source/core/html/DOMTokenList.cpp \
 	third_party/WebKit/Source/core/html/DOMURL.cpp \
 	third_party/WebKit/Source/core/html/DateInputType.cpp \
 	third_party/WebKit/Source/core/html/DateTimeFieldsState.cpp \
@@ -330,6 +328,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -342,6 +341,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -359,12 +359,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -490,6 +488,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -502,6 +501,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -519,12 +519,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -623,7 +621,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -640,7 +640,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform.target.darwin-arm.mk b/Source/core/webcore_platform.target.darwin-arm.mk
index 705d67b..59c7030 100644
--- a/Source/core/webcore_platform.target.darwin-arm.mk
+++ b/Source/core/webcore_platform.target.darwin-arm.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/LinkHash.cpp \
+	third_party/WebKit/Source/core/platform/LocalizedStrings.cpp \
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
@@ -77,6 +78,7 @@
 	third_party/WebKit/Source/core/platform/Widget.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
+	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioBus.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp \
@@ -128,7 +130,6 @@
 	third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
 	third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
@@ -168,7 +169,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsLayerTransform.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
@@ -374,6 +374,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -386,6 +387,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -403,12 +405,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -532,6 +532,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -544,6 +545,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -561,12 +563,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -669,7 +669,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -688,7 +690,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform.target.darwin-mips.mk b/Source/core/webcore_platform.target.darwin-mips.mk
index 5d07448..b1f6956 100644
--- a/Source/core/webcore_platform.target.darwin-mips.mk
+++ b/Source/core/webcore_platform.target.darwin-mips.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/LinkHash.cpp \
+	third_party/WebKit/Source/core/platform/LocalizedStrings.cpp \
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
@@ -77,6 +78,7 @@
 	third_party/WebKit/Source/core/platform/Widget.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
+	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioBus.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp \
@@ -128,7 +130,6 @@
 	third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
 	third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
@@ -168,7 +169,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsLayerTransform.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
@@ -374,6 +374,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -386,6 +387,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -403,12 +405,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -532,6 +532,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -544,6 +545,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -561,12 +563,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -667,7 +667,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -684,7 +686,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform.target.darwin-x86.mk b/Source/core/webcore_platform.target.darwin-x86.mk
index 964d627..e73a70c 100644
--- a/Source/core/webcore_platform.target.darwin-x86.mk
+++ b/Source/core/webcore_platform.target.darwin-x86.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/LinkHash.cpp \
+	third_party/WebKit/Source/core/platform/LocalizedStrings.cpp \
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
@@ -77,6 +78,7 @@
 	third_party/WebKit/Source/core/platform/Widget.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
+	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioBus.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp \
@@ -128,7 +130,6 @@
 	third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
 	third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
@@ -168,7 +169,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsLayerTransform.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
@@ -376,6 +376,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -388,6 +389,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -405,12 +407,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -537,6 +537,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -549,6 +550,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -566,12 +568,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -671,7 +671,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -688,7 +690,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform.target.linux-arm.mk b/Source/core/webcore_platform.target.linux-arm.mk
index 705d67b..59c7030 100644
--- a/Source/core/webcore_platform.target.linux-arm.mk
+++ b/Source/core/webcore_platform.target.linux-arm.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/LinkHash.cpp \
+	third_party/WebKit/Source/core/platform/LocalizedStrings.cpp \
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
@@ -77,6 +78,7 @@
 	third_party/WebKit/Source/core/platform/Widget.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
+	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioBus.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp \
@@ -128,7 +130,6 @@
 	third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
 	third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
@@ -168,7 +169,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsLayerTransform.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
@@ -374,6 +374,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -386,6 +387,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -403,12 +405,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -532,6 +532,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -544,6 +545,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -561,12 +563,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -669,7 +669,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -688,7 +690,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform.target.linux-mips.mk b/Source/core/webcore_platform.target.linux-mips.mk
index 5d07448..b1f6956 100644
--- a/Source/core/webcore_platform.target.linux-mips.mk
+++ b/Source/core/webcore_platform.target.linux-mips.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/LinkHash.cpp \
+	third_party/WebKit/Source/core/platform/LocalizedStrings.cpp \
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
@@ -77,6 +78,7 @@
 	third_party/WebKit/Source/core/platform/Widget.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
+	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioBus.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp \
@@ -128,7 +130,6 @@
 	third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
 	third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
@@ -168,7 +169,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsLayerTransform.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
@@ -374,6 +374,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -386,6 +387,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -403,12 +405,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -532,6 +532,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -544,6 +545,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -561,12 +563,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -667,7 +667,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -684,7 +686,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform.target.linux-x86.mk b/Source/core/webcore_platform.target.linux-x86.mk
index 964d627..e73a70c 100644
--- a/Source/core/webcore_platform.target.linux-x86.mk
+++ b/Source/core/webcore_platform.target.linux-x86.mk
@@ -47,6 +47,7 @@
 	third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/platform/LifecycleObserver.cpp \
 	third_party/WebKit/Source/core/platform/LinkHash.cpp \
+	third_party/WebKit/Source/core/platform/LocalizedStrings.cpp \
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
@@ -77,6 +78,7 @@
 	third_party/WebKit/Source/core/platform/Widget.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp \
 	third_party/WebKit/Source/core/platform/animation/CSSAnimationDataList.cpp \
+	third_party/WebKit/Source/core/platform/animation/KeyframeValueList.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioBus.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp \
 	third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp \
@@ -128,7 +130,6 @@
 	third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp \
 	third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/LocalizedStringsChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp \
@@ -168,7 +169,6 @@
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp \
-	third_party/WebKit/Source/core/platform/graphics/GraphicsLayerTransform.cpp \
 	third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp \
 	third_party/WebKit/Source/core/platform/graphics/Image.cpp \
 	third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp \
@@ -376,6 +376,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -388,6 +389,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -405,12 +407,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -537,6 +537,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -549,6 +550,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -566,12 +568,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -671,7 +671,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -688,7 +690,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform_geometry.target.darwin-arm.mk b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
index 1aa861f..d0a30ba 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
@@ -75,6 +75,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -87,6 +88,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -104,12 +106,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -232,6 +232,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -244,6 +245,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -261,12 +263,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -368,7 +368,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -387,7 +389,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform_geometry.target.darwin-mips.mk b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
index d5c67d6..08b02f6 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
@@ -75,6 +75,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -87,6 +88,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -104,12 +106,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -232,6 +232,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -244,6 +245,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -261,12 +263,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -366,7 +366,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -383,7 +385,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform_geometry.target.darwin-x86.mk b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
index 91dcd7b..0a81c51 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
@@ -77,6 +77,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -89,6 +90,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -106,12 +108,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -237,6 +237,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -249,6 +250,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -266,12 +268,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -370,7 +370,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -387,7 +389,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform_geometry.target.linux-arm.mk b/Source/core/webcore_platform_geometry.target.linux-arm.mk
index 1aa861f..d0a30ba 100644
--- a/Source/core/webcore_platform_geometry.target.linux-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-arm.mk
@@ -75,6 +75,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -87,6 +88,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -104,12 +106,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -232,6 +232,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -244,6 +245,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -261,12 +263,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -368,7 +368,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -387,7 +389,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform_geometry.target.linux-mips.mk b/Source/core/webcore_platform_geometry.target.linux-mips.mk
index d5c67d6..08b02f6 100644
--- a/Source/core/webcore_platform_geometry.target.linux-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-mips.mk
@@ -75,6 +75,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -87,6 +88,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -104,12 +106,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -232,6 +232,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -244,6 +245,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -261,12 +263,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -366,7 +366,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -383,7 +385,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_platform_geometry.target.linux-x86.mk b/Source/core/webcore_platform_geometry.target.linux-x86.mk
index 91dcd7b..0a81c51 100644
--- a/Source/core/webcore_platform_geometry.target.linux-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-x86.mk
@@ -77,6 +77,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -89,6 +90,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -106,12 +108,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -237,6 +237,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -249,6 +250,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -266,12 +268,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -370,7 +370,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -387,7 +389,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_remaining.target.darwin-arm.mk b/Source/core/webcore_remaining.target.darwin-arm.mk
index cb9b174..241625c 100644
--- a/Source/core/webcore_remaining.target.darwin-arm.mk
+++ b/Source/core/webcore_remaining.target.darwin-arm.mk
@@ -58,6 +58,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
@@ -160,7 +161,6 @@
 	third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp \
 	third_party/WebKit/Source/core/css/SelectorFilter.cpp \
 	third_party/WebKit/Source/core/css/ShadowValue.cpp \
-	third_party/WebKit/Source/core/css/StyleColor.cpp \
 	third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp \
 	third_party/WebKit/Source/core/css/StyleMedia.cpp \
 	third_party/WebKit/Source/core/css/StylePropertySerializer.cpp \
@@ -244,19 +244,23 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
+	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
@@ -335,9 +339,7 @@
 	third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp \
-	third_party/WebKit/Source/core/loader/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/loader/CookieJar.cpp \
-	third_party/WebKit/Source/core/loader/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoader.cpp \
@@ -346,6 +348,7 @@
 	third_party/WebKit/Source/core/loader/EmptyClients.cpp \
 	third_party/WebKit/Source/core/loader/FormState.cpp \
 	third_party/WebKit/Source/core/loader/FormSubmission.cpp \
+	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
@@ -361,7 +364,6 @@
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
@@ -553,6 +555,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -565,6 +568,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -582,12 +586,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -711,6 +713,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -723,6 +726,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -740,12 +744,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -847,7 +849,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -866,7 +870,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_remaining.target.darwin-mips.mk b/Source/core/webcore_remaining.target.darwin-mips.mk
index 77f5a62..f9b5735 100644
--- a/Source/core/webcore_remaining.target.darwin-mips.mk
+++ b/Source/core/webcore_remaining.target.darwin-mips.mk
@@ -58,6 +58,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
@@ -160,7 +161,6 @@
 	third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp \
 	third_party/WebKit/Source/core/css/SelectorFilter.cpp \
 	third_party/WebKit/Source/core/css/ShadowValue.cpp \
-	third_party/WebKit/Source/core/css/StyleColor.cpp \
 	third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp \
 	third_party/WebKit/Source/core/css/StyleMedia.cpp \
 	third_party/WebKit/Source/core/css/StylePropertySerializer.cpp \
@@ -244,19 +244,23 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
+	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
@@ -335,9 +339,7 @@
 	third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp \
-	third_party/WebKit/Source/core/loader/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/loader/CookieJar.cpp \
-	third_party/WebKit/Source/core/loader/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoader.cpp \
@@ -346,6 +348,7 @@
 	third_party/WebKit/Source/core/loader/EmptyClients.cpp \
 	third_party/WebKit/Source/core/loader/FormState.cpp \
 	third_party/WebKit/Source/core/loader/FormSubmission.cpp \
+	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
@@ -361,7 +364,6 @@
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
@@ -553,6 +555,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -565,6 +568,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -582,12 +586,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -711,6 +713,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -723,6 +726,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -740,12 +744,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -845,7 +847,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -862,7 +866,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_remaining.target.darwin-x86.mk b/Source/core/webcore_remaining.target.darwin-x86.mk
index 406441a..d14442f 100644
--- a/Source/core/webcore_remaining.target.darwin-x86.mk
+++ b/Source/core/webcore_remaining.target.darwin-x86.mk
@@ -58,6 +58,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
@@ -160,7 +161,6 @@
 	third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp \
 	third_party/WebKit/Source/core/css/SelectorFilter.cpp \
 	third_party/WebKit/Source/core/css/ShadowValue.cpp \
-	third_party/WebKit/Source/core/css/StyleColor.cpp \
 	third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp \
 	third_party/WebKit/Source/core/css/StyleMedia.cpp \
 	third_party/WebKit/Source/core/css/StylePropertySerializer.cpp \
@@ -244,19 +244,23 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
+	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
@@ -335,9 +339,7 @@
 	third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp \
-	third_party/WebKit/Source/core/loader/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/loader/CookieJar.cpp \
-	third_party/WebKit/Source/core/loader/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoader.cpp \
@@ -346,6 +348,7 @@
 	third_party/WebKit/Source/core/loader/EmptyClients.cpp \
 	third_party/WebKit/Source/core/loader/FormState.cpp \
 	third_party/WebKit/Source/core/loader/FormSubmission.cpp \
+	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
@@ -361,7 +364,6 @@
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
@@ -555,6 +557,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -567,6 +570,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -584,12 +588,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -716,6 +718,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -728,6 +731,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -745,12 +749,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -849,7 +851,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -866,7 +870,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_remaining.target.linux-arm.mk b/Source/core/webcore_remaining.target.linux-arm.mk
index cb9b174..241625c 100644
--- a/Source/core/webcore_remaining.target.linux-arm.mk
+++ b/Source/core/webcore_remaining.target.linux-arm.mk
@@ -58,6 +58,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
@@ -160,7 +161,6 @@
 	third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp \
 	third_party/WebKit/Source/core/css/SelectorFilter.cpp \
 	third_party/WebKit/Source/core/css/ShadowValue.cpp \
-	third_party/WebKit/Source/core/css/StyleColor.cpp \
 	third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp \
 	third_party/WebKit/Source/core/css/StyleMedia.cpp \
 	third_party/WebKit/Source/core/css/StylePropertySerializer.cpp \
@@ -244,19 +244,23 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
+	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
@@ -335,9 +339,7 @@
 	third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp \
-	third_party/WebKit/Source/core/loader/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/loader/CookieJar.cpp \
-	third_party/WebKit/Source/core/loader/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoader.cpp \
@@ -346,6 +348,7 @@
 	third_party/WebKit/Source/core/loader/EmptyClients.cpp \
 	third_party/WebKit/Source/core/loader/FormState.cpp \
 	third_party/WebKit/Source/core/loader/FormSubmission.cpp \
+	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
@@ -361,7 +364,6 @@
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
@@ -553,6 +555,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -565,6 +568,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -582,12 +586,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -711,6 +713,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -723,6 +726,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -740,12 +744,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -847,7 +849,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -866,7 +870,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_remaining.target.linux-mips.mk b/Source/core/webcore_remaining.target.linux-mips.mk
index 77f5a62..f9b5735 100644
--- a/Source/core/webcore_remaining.target.linux-mips.mk
+++ b/Source/core/webcore_remaining.target.linux-mips.mk
@@ -58,6 +58,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
@@ -160,7 +161,6 @@
 	third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp \
 	third_party/WebKit/Source/core/css/SelectorFilter.cpp \
 	third_party/WebKit/Source/core/css/ShadowValue.cpp \
-	third_party/WebKit/Source/core/css/StyleColor.cpp \
 	third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp \
 	third_party/WebKit/Source/core/css/StyleMedia.cpp \
 	third_party/WebKit/Source/core/css/StylePropertySerializer.cpp \
@@ -244,19 +244,23 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
+	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
@@ -335,9 +339,7 @@
 	third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp \
-	third_party/WebKit/Source/core/loader/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/loader/CookieJar.cpp \
-	third_party/WebKit/Source/core/loader/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoader.cpp \
@@ -346,6 +348,7 @@
 	third_party/WebKit/Source/core/loader/EmptyClients.cpp \
 	third_party/WebKit/Source/core/loader/FormState.cpp \
 	third_party/WebKit/Source/core/loader/FormSubmission.cpp \
+	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
@@ -361,7 +364,6 @@
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
@@ -553,6 +555,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -565,6 +568,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -582,12 +586,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -711,6 +713,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -723,6 +726,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -740,12 +744,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -845,7 +847,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -862,7 +866,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_remaining.target.linux-x86.mk b/Source/core/webcore_remaining.target.linux-x86.mk
index 406441a..d14442f 100644
--- a/Source/core/webcore_remaining.target.linux-x86.mk
+++ b/Source/core/webcore_remaining.target.linux-x86.mk
@@ -58,6 +58,7 @@
 	third_party/WebKit/Source/core/animation/AnimatableNumber.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableTransform.cpp \
 	third_party/WebKit/Source/core/animation/AnimatableValue.cpp \
+	third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp \
 	third_party/WebKit/Source/core/animation/Animation.cpp \
 	third_party/WebKit/Source/core/animation/DocumentTimeline.cpp \
 	third_party/WebKit/Source/core/animation/InertAnimation.cpp \
@@ -160,7 +161,6 @@
 	third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp \
 	third_party/WebKit/Source/core/css/SelectorFilter.cpp \
 	third_party/WebKit/Source/core/css/ShadowValue.cpp \
-	third_party/WebKit/Source/core/css/StyleColor.cpp \
 	third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp \
 	third_party/WebKit/Source/core/css/StyleMedia.cpp \
 	third_party/WebKit/Source/core/css/StylePropertySerializer.cpp \
@@ -244,19 +244,23 @@
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
+	third_party/WebKit/Source/core/fetch/CachedMetadata.cpp \
+	third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/DocumentResource.cpp \
+	third_party/WebKit/Source/core/fetch/FetchContext.cpp \
+	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/FontResource.cpp \
 	third_party/WebKit/Source/core/fetch/ImageResource.cpp \
 	third_party/WebKit/Source/core/fetch/RawResource.cpp \
 	third_party/WebKit/Source/core/fetch/Resource.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp \
-	third_party/WebKit/Source/core/fetch/ResourceLoadNotifier.cpp \
 	third_party/WebKit/Source/core/fetch/ResourceLoader.cpp \
+	third_party/WebKit/Source/core/fetch/ResourceLoaderSet.cpp \
 	third_party/WebKit/Source/core/fetch/ResourcePtr.cpp \
-	third_party/WebKit/Source/core/fetch/FetchRequest.cpp \
 	third_party/WebKit/Source/core/fetch/ScriptResource.cpp \
 	third_party/WebKit/Source/core/fetch/ShaderResource.cpp \
+	third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/fetch/TextTrackResource.cpp \
 	third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp \
 	third_party/WebKit/Source/core/fetch/MemoryCache.cpp \
@@ -335,9 +339,7 @@
 	third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp \
 	third_party/WebKit/Source/core/inspector/WorkerRuntimeAgent.cpp \
-	third_party/WebKit/Source/core/loader/CachedMetadata.cpp \
 	third_party/WebKit/Source/core/loader/CookieJar.cpp \
-	third_party/WebKit/Source/core/loader/CrossOriginAccessControl.cpp \
 	third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp \
 	third_party/WebKit/Source/core/loader/DocumentLoader.cpp \
@@ -346,6 +348,7 @@
 	third_party/WebKit/Source/core/loader/EmptyClients.cpp \
 	third_party/WebKit/Source/core/loader/FormState.cpp \
 	third_party/WebKit/Source/core/loader/FormSubmission.cpp \
+	third_party/WebKit/Source/core/loader/FrameFetchContext.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoader.cpp \
 	third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp \
 	third_party/WebKit/Source/core/loader/HistoryController.cpp \
@@ -361,7 +364,6 @@
 	third_party/WebKit/Source/core/loader/PrerendererClient.cpp \
 	third_party/WebKit/Source/core/loader/ProgressTracker.cpp \
 	third_party/WebKit/Source/core/loader/SinkDocument.cpp \
-	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
@@ -555,6 +557,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -567,6 +570,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -584,12 +588,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -716,6 +718,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -728,6 +731,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -745,12 +749,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -849,7 +851,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -866,7 +870,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_rendering.target.darwin-arm.mk b/Source/core/webcore_rendering.target.darwin-arm.mk
index e87a726..419df09 100644
--- a/Source/core/webcore_rendering.target.darwin-arm.mk
+++ b/Source/core/webcore_rendering.target.darwin-arm.mk
@@ -42,12 +42,14 @@
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	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/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlock.cpp \
+	third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp \
@@ -135,6 +137,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/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -145,7 +148,6 @@
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
@@ -217,6 +219,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -229,6 +232,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -246,12 +250,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -374,6 +376,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -386,6 +389,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -403,12 +407,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -510,7 +512,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -529,7 +533,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_rendering.target.darwin-mips.mk b/Source/core/webcore_rendering.target.darwin-mips.mk
index 27336d3..7a0920e 100644
--- a/Source/core/webcore_rendering.target.darwin-mips.mk
+++ b/Source/core/webcore_rendering.target.darwin-mips.mk
@@ -42,12 +42,14 @@
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	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/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlock.cpp \
+	third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp \
@@ -135,6 +137,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/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -145,7 +148,6 @@
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
@@ -217,6 +219,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -229,6 +232,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -246,12 +250,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -374,6 +376,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -386,6 +389,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -403,12 +407,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -508,7 +510,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -525,7 +529,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_rendering.target.darwin-x86.mk b/Source/core/webcore_rendering.target.darwin-x86.mk
index 2afffaf..1cdbfa8 100644
--- a/Source/core/webcore_rendering.target.darwin-x86.mk
+++ b/Source/core/webcore_rendering.target.darwin-x86.mk
@@ -42,12 +42,14 @@
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	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/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlock.cpp \
+	third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp \
@@ -135,6 +137,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/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -145,7 +148,6 @@
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
@@ -220,6 +222,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -232,6 +235,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -249,12 +253,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -381,6 +383,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -393,6 +396,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -410,12 +414,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -514,7 +516,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -531,7 +535,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_rendering.target.linux-arm.mk b/Source/core/webcore_rendering.target.linux-arm.mk
index e87a726..419df09 100644
--- a/Source/core/webcore_rendering.target.linux-arm.mk
+++ b/Source/core/webcore_rendering.target.linux-arm.mk
@@ -42,12 +42,14 @@
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	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/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlock.cpp \
+	third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp \
@@ -135,6 +137,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/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -145,7 +148,6 @@
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
@@ -217,6 +219,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -229,6 +232,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -246,12 +250,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -374,6 +376,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -386,6 +389,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -403,12 +407,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -510,7 +512,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -529,7 +533,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_rendering.target.linux-mips.mk b/Source/core/webcore_rendering.target.linux-mips.mk
index 27336d3..7a0920e 100644
--- a/Source/core/webcore_rendering.target.linux-mips.mk
+++ b/Source/core/webcore_rendering.target.linux-mips.mk
@@ -42,12 +42,14 @@
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	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/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlock.cpp \
+	third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp \
@@ -135,6 +137,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/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -145,7 +148,6 @@
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
@@ -217,6 +219,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -229,6 +232,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -246,12 +250,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -374,6 +376,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -386,6 +389,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -403,12 +407,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -508,7 +510,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -525,7 +529,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_rendering.target.linux-x86.mk b/Source/core/webcore_rendering.target.linux-x86.mk
index 2afffaf..1cdbfa8 100644
--- a/Source/core/webcore_rendering.target.linux-x86.mk
+++ b/Source/core/webcore_rendering.target.linux-x86.mk
@@ -42,12 +42,14 @@
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
 	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/Pagination.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBR.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlock.cpp \
+	third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBox.cpp \
 	third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp \
@@ -135,6 +137,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/RenderingNodeProxy.cpp \
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp \
@@ -145,7 +148,6 @@
 	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
 	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
@@ -220,6 +222,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -232,6 +235,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -249,12 +253,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -381,6 +383,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -393,6 +396,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -410,12 +414,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -514,7 +516,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -531,7 +535,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_svg.target.darwin-arm.mk b/Source/core/webcore_svg.target.darwin-arm.mk
index 31bd1e0..222458d 100644
--- a/Source/core/webcore_svg.target.darwin-arm.mk
+++ b/Source/core/webcore_svg.target.darwin-arm.mk
@@ -212,7 +212,6 @@
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTests.cpp \
 	third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp \
@@ -284,6 +283,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -296,6 +296,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -313,12 +314,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -441,6 +440,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -453,6 +453,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -470,12 +471,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -577,7 +576,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -596,7 +597,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_svg.target.darwin-mips.mk b/Source/core/webcore_svg.target.darwin-mips.mk
index 9e8e28e..4818894 100644
--- a/Source/core/webcore_svg.target.darwin-mips.mk
+++ b/Source/core/webcore_svg.target.darwin-mips.mk
@@ -212,7 +212,6 @@
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTests.cpp \
 	third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp \
@@ -284,6 +283,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -296,6 +296,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -313,12 +314,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -441,6 +440,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -453,6 +453,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -470,12 +471,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -575,7 +574,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -592,7 +593,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_svg.target.darwin-x86.mk b/Source/core/webcore_svg.target.darwin-x86.mk
index 0b57271..70e5f01 100644
--- a/Source/core/webcore_svg.target.darwin-x86.mk
+++ b/Source/core/webcore_svg.target.darwin-x86.mk
@@ -212,7 +212,6 @@
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTests.cpp \
 	third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp \
@@ -286,6 +285,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -298,6 +298,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -315,12 +316,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -446,6 +445,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -458,6 +458,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -475,12 +476,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -579,7 +578,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -596,7 +597,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_svg.target.linux-arm.mk b/Source/core/webcore_svg.target.linux-arm.mk
index 31bd1e0..222458d 100644
--- a/Source/core/webcore_svg.target.linux-arm.mk
+++ b/Source/core/webcore_svg.target.linux-arm.mk
@@ -212,7 +212,6 @@
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTests.cpp \
 	third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp \
@@ -284,6 +283,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -296,6 +296,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -313,12 +314,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -441,6 +440,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -453,6 +453,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -470,12 +471,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -577,7 +576,9 @@
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
 	-Wl,--icf=safe \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -596,7 +597,9 @@
 	-Wl,--icf=safe \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_svg.target.linux-mips.mk b/Source/core/webcore_svg.target.linux-mips.mk
index 9e8e28e..4818894 100644
--- a/Source/core/webcore_svg.target.linux-mips.mk
+++ b/Source/core/webcore_svg.target.linux-mips.mk
@@ -212,7 +212,6 @@
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTests.cpp \
 	third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp \
@@ -284,6 +283,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -296,6 +296,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -313,12 +314,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -441,6 +440,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -453,6 +453,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -470,12 +471,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -575,7 +574,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -592,7 +593,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/webcore_svg.target.linux-x86.mk b/Source/core/webcore_svg.target.linux-x86.mk
index 0b57271..70e5f01 100644
--- a/Source/core/webcore_svg.target.linux-x86.mk
+++ b/Source/core/webcore_svg.target.linux-x86.mk
@@ -212,7 +212,6 @@
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTests.cpp \
 	third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp \
@@ -286,6 +285,7 @@
 
 MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -298,6 +298,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -315,12 +316,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -446,6 +445,7 @@
 
 MY_DEFS_Release := \
 	'-DANGLE_DX11' \
+	'-DWTF_VECTOR_INITIAL_SIZE=16' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
 	'-DDISCARDABLE_MEMORY_ALWAYS_SUPPORTED_NATIVELY' \
@@ -458,6 +458,7 @@
 	'-DENABLE_GPU=1' \
 	'-DUSE_OPENSSL=1' \
 	'-DENABLE_EGLIMAGE=1' \
+	'-DCLD_VERSION=1' \
 	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
 	'-DWEBKIT_IMPLEMENTATION=1' \
 	'-DINSIDE_WEBKIT' \
@@ -475,12 +476,10 @@
 	'-DENABLE_INPUT_SPEECH=0' \
 	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
 	'-DENABLE_MEDIA_CAPTURE=1' \
-	'-DENABLE_NOTIFICATIONS=0' \
 	'-DENABLE_ORIENTATION_EVENTS=1' \
 	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
 	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
-	'-DWTF_USE_HARFBUZZ=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_ENABLE_INST_COUNT=0' \
 	'-DSK_SUPPORT_GPU=1' \
@@ -579,7 +578,9 @@
 	-nostdlib \
 	-Wl,--no-undefined \
 	-Wl,--exclude-libs=ALL \
+	-Wl,--fatal-warnings \
 	-Wl,--gc-sections \
+	-Wl,--warn-shared-textrel \
 	-Wl,-O1 \
 	-Wl,--as-needed
 
@@ -596,7 +597,9 @@
 	-Wl,--exclude-libs=ALL \
 	-Wl,-O1 \
 	-Wl,--as-needed \
-	-Wl,--gc-sections
+	-Wl,--gc-sections \
+	-Wl,--fatal-warnings \
+	-Wl,--warn-shared-textrel
 
 
 LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
diff --git a/Source/core/workers/Worker.cpp b/Source/core/workers/Worker.cpp
index 9719951..fd19c81 100644
--- a/Source/core/workers/Worker.cpp
+++ b/Source/core/workers/Worker.cpp
@@ -35,9 +35,7 @@
 #include "core/dom/MessageEvent.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/FrameLoader.h"
 #include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
 #include "core/page/UseCounter.h"
 #include "core/workers/WorkerGlobalScopeProxy.h"
 #include "core/workers/WorkerScriptLoader.h"
diff --git a/Source/core/workers/WorkerMessagingProxy.cpp b/Source/core/workers/WorkerMessagingProxy.cpp
index 9794ea6..950ee3d 100644
--- a/Source/core/workers/WorkerMessagingProxy.cpp
+++ b/Source/core/workers/WorkerMessagingProxy.cpp
@@ -138,7 +138,7 @@
         // We don't bother checking the askedToTerminate() flag here, because exceptions should *always* be reported even if the thread is terminated.
         // This is intentionally different than the behavior in MessageWorkerTask, because terminated workers no longer deliver messages (section 4.6 of the WebWorker spec), but they do report exceptions.
 
-        RefPtr<ErrorEvent> event = ErrorEvent::create(m_errorMessage, m_sourceURL, m_lineNumber, m_columnNumber);
+        RefPtr<ErrorEvent> event = ErrorEvent::create(m_errorMessage, m_sourceURL, m_lineNumber, m_columnNumber, 0);
         bool errorHandled = !workerObject->dispatchEvent(event);
         if (!errorHandled)
             context->reportException(event, 0, NotSharableCrossOrigin);
diff --git a/Source/core/workers/WorkerScriptLoader.cpp b/Source/core/workers/WorkerScriptLoader.cpp
index 7f6290e..7e0e930 100644
--- a/Source/core/workers/WorkerScriptLoader.cpp
+++ b/Source/core/workers/WorkerScriptLoader.cpp
@@ -29,7 +29,7 @@
 #include "core/workers/WorkerScriptLoader.h"
 
 #include "core/dom/ScriptExecutionContext.h"
-#include "core/loader/TextResourceDecoder.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/loader/WorkerThreadableLoader.h"
 #include "core/platform/network/ResourceResponse.h"
 #include "core/workers/WorkerGlobalScope.h"
diff --git a/Source/core/workers/WorkerThread.cpp b/Source/core/workers/WorkerThread.cpp
index 801693c..eed8047 100644
--- a/Source/core/workers/WorkerThread.cpp
+++ b/Source/core/workers/WorkerThread.cpp
@@ -69,9 +69,7 @@
     , m_workerLoaderProxy(workerLoaderProxy)
     , m_workerReportingProxy(workerReportingProxy)
     , m_startupData(startupData)
-#if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
     , m_notificationClient(0)
-#endif
 {
     MutexLocker lock(threadSetMutex());
     workerThreads().add(this);
diff --git a/Source/core/workers/WorkerThread.h b/Source/core/workers/WorkerThread.h
index 3b212bb..c019d80 100644
--- a/Source/core/workers/WorkerThread.h
+++ b/Source/core/workers/WorkerThread.h
@@ -62,10 +62,8 @@
         static unsigned workerThreadCount();
         static void releaseFastMallocFreeMemoryInAllThreads();
 
-#if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
         NotificationClient* getNotificationClient() { return m_notificationClient; }
         void setNotificationClient(NotificationClient* client) { m_notificationClient = client; }
-#endif
 
     protected:
         WorkerThread(WorkerLoaderProxy&, WorkerReportingProxy&, PassOwnPtr<WorkerThreadStartupData>);
@@ -94,9 +92,7 @@
 
         OwnPtr<WorkerThreadStartupData> m_startupData;
 
-#if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
         NotificationClient* m_notificationClient;
-#endif
     };
 
 } // namespace WebCore
diff --git a/Source/core/xml/DOMParser.cpp b/Source/core/xml/DOMParser.cpp
index b923b46..25c1cb6 100644
--- a/Source/core/xml/DOMParser.cpp
+++ b/Source/core/xml/DOMParser.cpp
@@ -20,14 +20,13 @@
 #include "core/xml/DOMParser.h"
 
 #include "core/dom/DOMImplementation.h"
-#include "core/dom/Document.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
 PassRefPtr<Document> DOMParser::parseFromString(const String& str, const String& contentType)
 {
-    if (!DOMImplementation::isXMLMIMEType(contentType))
+    if (!DOMImplementation::isXMLMIMEType(contentType) && contentType != "text/html")
         return 0;
 
     RefPtr<Document> doc = DOMImplementation::createDocument(contentType, 0, KURL(), false);
diff --git a/Source/core/xml/XMLHttpRequest.cpp b/Source/core/xml/XMLHttpRequest.cpp
index 645c48a..4b041d4 100644
--- a/Source/core/xml/XMLHttpRequest.cpp
+++ b/Source/core/xml/XMLHttpRequest.cpp
@@ -24,6 +24,7 @@
 #include "core/xml/XMLHttpRequest.h"
 
 #include "FetchInitiatorTypeNames.h"
+#include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ExceptionMessages.h"
 #include "bindings/v8/ExceptionState.h"
 #include "core/dom/ContextFeatures.h"
@@ -33,13 +34,14 @@
 #include "core/dom/EventNames.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/editing/markup.h"
+#include "core/fetch/CrossOriginAccessControl.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/fileapi/Blob.h"
 #include "core/fileapi/File.h"
+#include "core/fileapi/Stream.h"
 #include "core/html/DOMFormData.h"
 #include "core/html/HTMLDocument.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/CrossOriginAccessControl.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/loader/ThreadableLoader.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/Settings.h"
@@ -253,10 +255,11 @@
             || scriptExecutionContext()->isWorkerGlobalScope()) {
             m_responseDocument = 0;
         } else {
+            DocumentInit init = DocumentInit::fromContext(document()->contextDocument(), m_url);
             if (isHTML)
-                m_responseDocument = HTMLDocument::create(DocumentInit(m_url));
+                m_responseDocument = HTMLDocument::create(init);
             else
-                m_responseDocument = Document::create(DocumentInit(m_url));
+                m_responseDocument = Document::create(init);
             // FIXME: Set Last-Modified.
             m_responseDocument->setContent(m_responseText.flattenToString());
             m_responseDocument->setSecurityOrigin(securityOrigin());
@@ -310,14 +313,28 @@
     if (m_error || m_state != DONE)
         return 0;
 
-    if (!m_responseArrayBuffer.get() && m_binaryResponseBuilder.get() && m_binaryResponseBuilder->size() > 0) {
-        m_responseArrayBuffer = m_binaryResponseBuilder->getAsArrayBuffer();
-        m_binaryResponseBuilder.clear();
+    if (!m_responseArrayBuffer.get()) {
+        if (m_binaryResponseBuilder.get() && m_binaryResponseBuilder->size() > 0) {
+            m_responseArrayBuffer = m_binaryResponseBuilder->getAsArrayBuffer();
+            m_binaryResponseBuilder.clear();
+        } else {
+            m_responseArrayBuffer = ArrayBuffer::create(static_cast<void*>(0), 0);
+        }
     }
 
     return m_responseArrayBuffer.get();
 }
 
+Stream* XMLHttpRequest::responseStream()
+{
+    ASSERT(m_responseTypeCode == ResponseTypeStream);
+
+    if (m_error || (m_state != LOADING && m_state != DONE))
+        return 0;
+
+    return m_responseStream.get();
+}
+
 void XMLHttpRequest::setTimeout(unsigned long timeout, ExceptionState& es)
 {
     // FIXME: Need to trigger or update the timeout Timer here, if needed. http://webkit.org/b/98156
@@ -345,20 +362,26 @@
         return;
     }
 
-    if (responseType == "")
+    if (responseType == "") {
         m_responseTypeCode = ResponseTypeDefault;
-    else if (responseType == "text")
+    } else if (responseType == "text") {
         m_responseTypeCode = ResponseTypeText;
-    else if (responseType == "json")
+    } else if (responseType == "json") {
         m_responseTypeCode = ResponseTypeJSON;
-    else if (responseType == "document")
+    } else if (responseType == "document") {
         m_responseTypeCode = ResponseTypeDocument;
-    else if (responseType == "blob")
+    } else if (responseType == "blob") {
         m_responseTypeCode = ResponseTypeBlob;
-    else if (responseType == "arraybuffer")
+    } else if (responseType == "arraybuffer") {
         m_responseTypeCode = ResponseTypeArrayBuffer;
-    else
+    } else if (responseType == "stream") {
+        if (RuntimeEnabledFeatures::streamEnabled())
+            m_responseTypeCode = ResponseTypeStream;
+        else
+            return;
+    } else {
         ASSERT_NOT_REACHED();
+    }
 }
 
 String XMLHttpRequest::responseType()
@@ -376,6 +399,8 @@
         return "blob";
     case ResponseTypeArrayBuffer:
         return "arraybuffer";
+    case ResponseTypeStream:
+        return "stream";
     }
     return "";
 }
@@ -748,6 +773,7 @@
     options.securityOrigin = securityOrigin();
     options.initiator = FetchInitiatorTypeNames::xmlhttprequest;
     options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(scriptExecutionContext()) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective;
+    options.mixedContentBlockingTreatment = TreatAsActiveContent;
     options.timeoutMilliseconds = m_timeoutMilliseconds;
 
     m_exceptionCode = 0;
@@ -825,15 +851,19 @@
 
     InspectorInstrumentation::didFailXHRLoading(scriptExecutionContext(), this);
 
-    if (m_loader) {
-        m_loader->cancel();
-        m_loader = 0;
+    if (m_responseStream && m_state != DONE)
+        m_responseStream->abort();
 
-        if (async == DropProtectionAsync)
-            dropProtectionSoon();
-        else
-            dropProtection();
-    }
+    if (!m_loader)
+        return;
+
+    m_loader->cancel();
+    m_loader = 0;
+
+    if (async == DropProtectionAsync)
+        dropProtectionSoon();
+    else
+        dropProtection();
 }
 
 void XMLHttpRequest::clearResponse()
@@ -849,6 +879,7 @@
     m_createdDocument = false;
     m_responseDocument = 0;
     m_responseBlob = 0;
+    m_responseStream = 0;
     m_binaryResponseBuilder.clear();
     m_responseArrayBuffer.clear();
 }
@@ -1096,6 +1127,9 @@
     if (m_decoder)
         m_responseText = m_responseText.concatenateWith(m_decoder->flush());
 
+    if (m_responseStream)
+        m_responseStream->finalize();
+
     InspectorInstrumentation::didFinishXHRLoading(scriptExecutionContext(), this, identifier, m_responseText, m_url, m_lastSendURL, m_lastSendLineNumber);
 
     // Prevent dropProtection releasing the last reference, and retain |this| until the end of this method.
@@ -1172,13 +1206,17 @@
     if (len == -1)
         len = strlen(data);
 
-    if (useDecoder)
+    if (useDecoder) {
         m_responseText = m_responseText.concatenateWith(m_decoder->decode(data, len));
-    else if (m_responseTypeCode == ResponseTypeArrayBuffer || m_responseTypeCode == ResponseTypeBlob) {
+    } else if (m_responseTypeCode == ResponseTypeArrayBuffer || m_responseTypeCode == ResponseTypeBlob) {
         // Buffer binary data.
         if (!m_binaryResponseBuilder)
             m_binaryResponseBuilder = SharedBuffer::create();
         m_binaryResponseBuilder->append(data, len);
+    } else if (m_responseTypeCode == ResponseTypeStream) {
+        if (!m_responseStream)
+            m_responseStream = Stream::create(responseMIMEType());
+        m_responseStream->addData(data, len);
     }
 
     if (!m_error) {
diff --git a/Source/core/xml/XMLHttpRequest.h b/Source/core/xml/XMLHttpRequest.h
index 3ffc6c2..ad3546d 100644
--- a/Source/core/xml/XMLHttpRequest.h
+++ b/Source/core/xml/XMLHttpRequest.h
@@ -46,6 +46,7 @@
 class ResourceRequest;
 class SecurityOrigin;
 class SharedBuffer;
+class Stream;
 class TextResourceDecoder;
 class ThreadableLoader;
 
@@ -72,7 +73,8 @@
         ResponseTypeJSON,
         ResponseTypeDocument,
         ResponseTypeBlob,
-        ResponseTypeArrayBuffer
+        ResponseTypeArrayBuffer,
+        ResponseTypeStream
     };
 
     enum DropProtection {
@@ -116,6 +118,7 @@
     ScriptString responseJSONSource();
     Document* responseXML(ExceptionState&);
     Blob* responseBlob();
+    Stream* responseStream();
     unsigned long timeout() const { return m_timeoutMilliseconds; }
     void setTimeout(unsigned long timeout, ExceptionState&);
 
@@ -196,6 +199,7 @@
     bool m_includeCredentials;
     unsigned long m_timeoutMilliseconds;
     RefPtr<Blob> m_responseBlob;
+    RefPtr<Stream> m_responseStream;
 
     RefPtr<ThreadableLoader> m_loader;
     State m_state;
diff --git a/Source/core/xml/XMLHttpRequest.idl b/Source/core/xml/XMLHttpRequest.idl
index ecee6f5..069129d 100644
--- a/Source/core/xml/XMLHttpRequest.idl
+++ b/Source/core/xml/XMLHttpRequest.idl
@@ -32,7 +32,8 @@
     "blob",
     "document",
     "json",
-    "text"
+    "text",
+    "stream"
 };
 
 [
diff --git a/Source/core/xml/XMLSerializer.cpp b/Source/core/xml/XMLSerializer.cpp
index 3b05636..eb17e92 100644
--- a/Source/core/xml/XMLSerializer.cpp
+++ b/Source/core/xml/XMLSerializer.cpp
@@ -1,6 +1,7 @@
 /*
  *  Copyright (C) 2003, 2006 Apple Inc. All rights reserved.
  *  Copyright (C) 2006 Samuel Weinig (sam@webkit.org)
+ *  Copyright (C) 2013 Samsung Electronics. All rights reserved.
  *
  *  This library is free software; you can redistribute it and/or
  *  modify it under the terms of the GNU Lesser General Public
@@ -30,16 +31,8 @@
 
 String XMLSerializer::serializeToString(Node* node, ExceptionState& es)
 {
-    if (!node)
-        return String();
-
-    if (!node->document()) {
-        // Due to the fact that DocumentType nodes are created by the DOMImplementation
-        // and not the Document, it is possible for it to not have a Document associated
-        // with it.  It should be the only type of node where this is possible.
-        ASSERT(node->nodeType() == Node::DOCUMENT_TYPE_NODE);
-
-        es.throwDOMException(InvalidAccessError);
+    if (!node) {
+        es.throwDOMException(TypeError, "Invalid node value.");
         return String();
     }
 
diff --git a/Source/core/xml/XMLViewer.js b/Source/core/xml/XMLViewer.js
index 049779b..25a39ef 100644
--- a/Source/core/xml/XMLViewer.js
+++ b/Source/core/xml/XMLViewer.js
@@ -30,6 +30,8 @@
 
 // Script entry point.
 
+var tree;
+
 function prepareWebKitXMLViewer(noStyleMessage)
 {
     var html = createHTMLElement('html');
@@ -60,10 +62,9 @@
     headerSpan.textContent = noStyleMessage;
     header.appendChild(createHTMLElement('br'));
 
-    var tree = createHTMLElement('div');
+    tree = createHTMLElement('div');
     body.appendChild(tree);
     tree.classList.add('pretty-print');
-    tree.id = 'tree';
     window.onload = sourceXMLLoaded;
 }
 
@@ -72,10 +73,9 @@
     var sourceXML = document.getElementById('webkit-xml-viewer-source-xml');
     if (!sourceXML)
         return; // Stop if some XML tree extension is already processing this document
-    var root = document.getElementById('tree');
 
     for (var child = sourceXML.firstChild; child; child = child.nextSibling)
-        nodeParentPairs.push({parentElement: root, node: child});
+        nodeParentPairs.push({parentElement: tree, node: child});
 
     for (var i = 0; i < nodeParentPairs.length; i++)
         processNode(nodeParentPairs[i].parentElement, nodeParentPairs[i].node);
diff --git a/Source/core/xml/XPathExpression.cpp b/Source/core/xml/XPathExpression.cpp
index 0850a92..920f6c9 100644
--- a/Source/core/xml/XPathExpression.cpp
+++ b/Source/core/xml/XPathExpression.cpp
@@ -69,7 +69,7 @@
     evaluationContext.size = 1;
     evaluationContext.position = 1;
     evaluationContext.hadTypeConversionError = false;
-    RefPtr<XPathResult> result = XPathResult::create(contextNode->document(), m_topExpression->evaluate());
+    RefPtr<XPathResult> result = XPathResult::create(&contextNode->document(), m_topExpression->evaluate());
     evaluationContext.node = 0; // Do not hold a reference to the context node, as this may prevent the whole document from being destroyed in time.
 
     if (evaluationContext.hadTypeConversionError) {
diff --git a/Source/core/xml/XPathFunctions.cpp b/Source/core/xml/XPathFunctions.cpp
index 0af3a8b..94ddadd 100644
--- a/Source/core/xml/XPathFunctions.cpp
+++ b/Source/core/xml/XPathFunctions.cpp
@@ -330,7 +330,7 @@
         idList.append(str);
     }
 
-    TreeScope* contextScope = evaluationContext().node->treeScope();
+    TreeScope& contextScope = evaluationContext().node->treeScope();
     NodeSet result;
     HashSet<Node*> resultSet;
 
@@ -349,7 +349,7 @@
 
         // If there are several nodes with the same id, id() should return the first one.
         // In WebKit, getElementById behaves so, too, although its behavior in this case is formally undefined.
-        Node* node = contextScope->getElementById(idList.substring(startPos, endPos - startPos));
+        Node* node = contextScope.getElementById(idList.substring(startPos, endPos - startPos));
         if (node && resultSet.add(node).isNewEntry)
             result.append(node);
 
@@ -366,7 +366,7 @@
     // The local part of an XPath expanded-name matches DOM local name for most node types, except for namespace nodes and processing instruction nodes.
     ASSERT(node->nodeType() != Node::XPATH_NAMESPACE_NODE); // Not supported yet.
     if (node->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
-        return static_cast<ProcessingInstruction*>(node)->target();
+        return toProcessingInstruction(node)->target();
     return node->localName().string();
 }
 
diff --git a/Source/core/xml/XPathNodeSet.cpp b/Source/core/xml/XPathNodeSet.cpp
index 1f64ad0..c621994 100644
--- a/Source/core/xml/XPathNodeSet.cpp
+++ b/Source/core/xml/XPathNodeSet.cpp
@@ -182,7 +182,7 @@
     if (node->isAttributeNode())
         node = toAttr(node)->ownerElement();
     if (node->inDocument())
-        node = node->document();
+        node = &node->document();
     else {
         while (Node* parent = node->parentNode())
             node = parent;
diff --git a/Source/core/xml/XPathStep.cpp b/Source/core/xml/XPathStep.cpp
index dee7834..618a421 100644
--- a/Source/core/xml/XPathStep.cpp
+++ b/Source/core/xml/XPathStep.cpp
@@ -192,7 +192,7 @@
             if (name == starAtom)
                 return namespaceURI.isEmpty() || namespaceURI == node->namespaceURI();
 
-            if (node->document()->isHTMLDocument()) {
+            if (node->document().isHTMLDocument()) {
                 if (node->isHTMLElement()) {
                     // Paths without namespaces should match HTML elements in HTML documents despite those having an XHTML namespace. Names are compared case-insensitively.
                     return equalIgnoringCase(toElement(node)->localName(), name) && (namespaceURI.isNull() || namespaceURI == node->namespaceURI());
diff --git a/Source/core/xml/XSLStyleSheetLibxslt.cpp b/Source/core/xml/XSLStyleSheetLibxslt.cpp
index 15e8a66..b7b8326 100644
--- a/Source/core/xml/XSLStyleSheetLibxslt.cpp
+++ b/Source/core/xml/XSLStyleSheetLibxslt.cpp
@@ -254,7 +254,7 @@
     for (XSLStyleSheet* styleSheet = this; styleSheet; styleSheet = styleSheet->parentStyleSheet()) {
         Node* node = styleSheet->ownerNode();
         if (node)
-            return node->document();
+            return &node->document();
     }
     return 0;
 }
diff --git a/Source/core/xml/XSLTProcessor.cpp b/Source/core/xml/XSLTProcessor.cpp
index 2c4f547..083736a 100644
--- a/Source/core/xml/XSLTProcessor.cpp
+++ b/Source/core/xml/XSLTProcessor.cpp
@@ -60,7 +60,7 @@
 PassRefPtr<Document> XSLTProcessor::createDocumentFromSource(const String& sourceString,
     const String& sourceEncoding, const String& sourceMIMEType, Node* sourceNode, Frame* frame)
 {
-    RefPtr<Document> ownerDocument = sourceNode->document();
+    RefPtr<Document> ownerDocument = &sourceNode->document();
     bool sourceIsDocument = (sourceNode == ownerDocument.get());
     String documentSource = sourceString;
 
@@ -121,7 +121,7 @@
 
     if (!transformToString(sourceNode, resultMIMEType, resultString, resultEncoding))
         return 0;
-    return createFragmentForTransformToFragment(resultString, resultMIMEType, outputDoc);
+    return createFragmentForTransformToFragment(resultString, resultMIMEType, *outputDoc);
 }
 
 void XSLTProcessor::setParameter(const String& /*namespaceURI*/, const String& localName, const String& value)
diff --git a/Source/core/xml/XSLTProcessorLibxslt.cpp b/Source/core/xml/XSLTProcessorLibxslt.cpp
index 74fcf53..4ab991f 100644
--- a/Source/core/xml/XSLTProcessorLibxslt.cpp
+++ b/Source/core/xml/XSLTProcessorLibxslt.cpp
@@ -104,7 +104,7 @@
 
         bool requestAllowed = globalResourceFetcher->frame() && globalResourceFetcher->document()->securityOrigin()->canRequest(url);
         if (requestAllowed) {
-            globalResourceFetcher->frame()->loader()->loadResourceSynchronously(url, AllowStoredCredentials, error, response, data);
+            globalResourceFetcher->fetchSynchronously(url, AllowStoredCredentials, error, response, data);
             requestAllowed = globalResourceFetcher->document()->securityOrigin()->canRequest(response.url());
         }
         if (!requestAllowed) {
@@ -226,8 +226,8 @@
 {
     if (!cachedStylesheet && stylesheetRootNode) {
         cachedStylesheet = XSLStyleSheet::createForXSLTProcessor(stylesheetRootNode->parentNode() ? stylesheetRootNode->parentNode() : stylesheetRootNode,
-            stylesheetRootNode->document()->url().string(),
-            stylesheetRootNode->document()->url()); // FIXME: Should we use baseURL here?
+            stylesheetRootNode->document().url().string(),
+            stylesheetRootNode->document().url()); // FIXME: Should we use baseURL here?
 
         // According to Mozilla documentation, the node must be a Document node, an xsl:stylesheet or xsl:transform element.
         // But we just use text content regardless of node type.
@@ -242,7 +242,7 @@
 
 static inline xmlDocPtr xmlDocPtrFromNode(Node* sourceNode, bool& shouldDelete)
 {
-    RefPtr<Document> ownerDocument = sourceNode->document();
+    RefPtr<Document> ownerDocument = &sourceNode->document();
     bool sourceIsDocument = (sourceNode == ownerDocument.get());
 
     xmlDocPtr sourceDoc = 0;
@@ -277,7 +277,7 @@
 
 bool XSLTProcessor::transformToString(Node* sourceNode, String& mimeType, String& resultString, String& resultEncoding)
 {
-    RefPtr<Document> ownerDocument = sourceNode->document();
+    RefPtr<Document> ownerDocument = &sourceNode->document();
 
     setXSLTLoadCallBack(docLoaderFunc, this, ownerDocument->fetcher());
     xsltStylesheetPtr sheet = xsltStylesheetPointer(m_stylesheet, m_stylesheetRootNode.get());
diff --git a/Source/core/xml/parser/XMLDocumentParser.cpp b/Source/core/xml/parser/XMLDocumentParser.cpp
index fafc5dd..26f839d 100644
--- a/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -42,12 +42,12 @@
 #include "core/dom/TransformSource.h"
 #include "core/fetch/ResourceFetcher.h"
 #include "core/fetch/ScriptResource.h"
+#include "core/fetch/TextResourceDecoder.h"
 #include "core/html/HTMLHtmlElement.h"
 #include "core/html/HTMLTemplateElement.h"
 #include "core/html/parser/HTMLEntityParser.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/ImageLoader.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/page/Frame.h"
 #include "core/page/UseCounter.h"
 #include "core/platform/network/ResourceError.h"
@@ -373,7 +373,7 @@
     ASSERT(m_bufferedText.size() == 0);
     ASSERT(!m_leafTextNode);
     m_leafTextNode = Text::create(m_currentNode->document(), "");
-    m_currentNode->parserAppendChild(m_leafTextNode.get(), DeprecatedAttachNow);
+    m_currentNode->parserAppendChild(m_leafTextNode.get());
 }
 
 void XMLDocumentParser::exitText()
@@ -384,7 +384,7 @@
     if (!m_leafTextNode)
         return;
 
-    m_leafTextNode->appendData(toString(m_bufferedText.data(), m_bufferedText.size()), DeprecatedAttachNow);
+    m_leafTextNode->appendData(toString(m_bufferedText.data(), m_bufferedText.size()));
     m_bufferedText.clear();
     m_leafTextNode = 0;
 }
@@ -499,7 +499,7 @@
     // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-xhtml-syntax.html#xml-fragment-parsing-algorithm
     // For now we have a hack for script/style innerHTML support:
     if (contextElement && (contextElement->hasLocalName(HTMLNames::scriptTag) || contextElement->hasLocalName(HTMLNames::styleTag))) {
-        fragment->parserAppendChild(fragment->document()->createTextNode(chunk));
+        fragment->parserAppendChild(fragment->document().createTextNode(chunk));
         return true;
     }
 
@@ -648,7 +648,7 @@
         // FIXME: We should restore the original global error handler as well.
 
         if (fetcher->frame())
-            fetcher->frame()->loader()->loadResourceSynchronously(url, AllowStoredCredentials, error, response, data);
+            fetcher->fetchSynchronously(url, AllowStoredCredentials, error, response, data);
     }
 
     // We have to check the URL again after the load to catch redirects.
@@ -778,7 +778,7 @@
 }
 
 XMLDocumentParser::XMLDocumentParser(DocumentFragment* fragment, Element* parentElement, ParserContentPolicy parserContentPolicy)
-    : ScriptableDocumentParser(fragment->document(), parserContentPolicy)
+    : ScriptableDocumentParser(&fragment->document(), parserContentPolicy)
     , m_view(0)
     , m_context(0)
     , m_currentNode(fragment)
@@ -791,7 +791,7 @@
     , m_parserPaused(false)
     , m_requestingScript(false)
     , m_finishCalled(false)
-    , m_xmlErrors(fragment->document())
+    , m_xmlErrors(&fragment->document())
     , m_pendingScript(0)
     , m_scriptStartPosition(TextPosition::belowRangePosition())
     , m_parsingFragment(true)
@@ -957,7 +957,7 @@
     m_sawFirstElement = true;
 
     QualifiedName qName(prefix, localName, adjustedURI);
-    RefPtr<Element> newElement = m_currentNode->document()->createElement(qName, true);
+    RefPtr<Element> newElement = m_currentNode->document().createElement(qName, true);
     if (!newElement) {
         stopParsing();
         return;
@@ -985,7 +985,7 @@
     if (scriptLoader)
         m_scriptStartPosition = textPosition();
 
-    m_currentNode->parserAppendChild(newElement.get(), DeprecatedAttachNow);
+    m_currentNode->parserAppendChild(newElement.get());
 
     const ContainerNode* currentNode = m_currentNode;
     if (newElement->hasTagName(HTMLNames::templateTag))
@@ -1133,13 +1133,13 @@
 
     // ### handle exceptions
     TrackExceptionState es;
-    RefPtr<ProcessingInstruction> pi = m_currentNode->document()->createProcessingInstruction(target, data, es);
+    RefPtr<ProcessingInstruction> pi = m_currentNode->document().createProcessingInstruction(target, data, es);
     if (es.hadException())
         return;
 
     pi->setCreatedByParser(true);
 
-    m_currentNode->parserAppendChild(pi.get(), DeprecatedAttachNow);
+    m_currentNode->parserAppendChild(pi.get());
 
     pi->finishParsingChildren();
 
@@ -1163,7 +1163,7 @@
     exitText();
 
     RefPtr<CDATASection> newNode = CDATASection::create(m_currentNode->document(), text);
-    m_currentNode->parserAppendChild(newNode.get(), DeprecatedAttachNow);
+    m_currentNode->parserAppendChild(newNode.get());
 }
 
 void XMLDocumentParser::comment(const String& text)
@@ -1179,7 +1179,7 @@
     exitText();
 
     RefPtr<Comment> newNode = Comment::create(m_currentNode->document(), text);
-    m_currentNode->parserAppendChild(newNode.get(), DeprecatedAttachNow);
+    m_currentNode->parserAppendChild(newNode.get());
 }
 
 enum StandaloneInfo {
@@ -1222,7 +1222,7 @@
     }
 
     if (document())
-        document()->parserAppendChild(DocumentType::create(document(), name, externalID, systemID), DeprecatedAttachNow);
+        document()->parserAppendChild(DocumentType::create(document(), name, externalID, systemID));
 }
 
 static inline XMLDocumentParser* getParser(void* closure)