gecko-dev/servo/components/style/parallel.rs

209 lines
8.0 KiB
Rust
Raw Normal View History

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements parallel traversal over the DOM tree.
//!
//! This traversal is based on Rayon, and therefore its safety is largely
//! verified by the type system.
//!
//! The primary trickiness and fine print for the above relates to the
//! thread safety of the DOM nodes themselves. Accessing a DOM element
//! concurrently on multiple threads is actually mostly "safe", since all
//! the mutable state is protected by an AtomicRefCell, and so we'll
//! generally panic if something goes wrong. Still, we try to to enforce our
//! thread invariants at compile time whenever possible. As such, TNode and
//! TElement are not Send, so ordinary style system code cannot accidentally
//! share them with other threads. In the parallel traversal, we explicitly
//! invoke |unsafe { SendNode::new(n) }| to put nodes in containers that may
//! be sent to other threads. This occurs in only a handful of places and is
//! easy to grep for. At the time of this writing, there is no other unsafe
//! code in the parallel traversal.
use dom::{OpaqueNode, SendNode, TElement, TNode};
use rayon;
use scoped_tls::ScopedTLS;
servo: Merge #14592 - Remove the util crate (from asajeffrey:util-goodbye); r=mbrubeck <!-- Please describe your changes on the following line: --> This PR removes the `util` crate. * Replaced the `spawn_named` and `clamp` functions by appropriate uses of `std::thread::Builder::spawn`, `std::cmp::min` and `std::cmp::max`. * Moved `opts`, `prefs` and `resource_files` into a new `config` crate. * Moved `remutex` and `geometry` into their own crates. --- <!-- Thank you for contributing to Servo! Please replace each `[ ]` by `[X]` when the step is complete, and replace `__` with appropriate data: --> - [X] `./mach build -d` does not report any errors - [X] `./mach test-tidy` does not report any errors - [X] These changes do not require tests because they are refactorings <!-- Pull requests that do not address these steps are welcome, but they will require additional verification as part of the review process. --> Source-Repo: https://github.com/servo/servo Source-Revision: 4eb653817f87e5fb47de34356f558eb76ecbca9f --HG-- rename : servo/components/util/Cargo.toml => servo/components/config/Cargo.toml rename : servo/components/util/basedir.rs => servo/components/config/basedir.rs rename : servo/components/util/lib.rs => servo/components/config/lib.rs rename : servo/components/util/opts.rs => servo/components/config/opts.rs rename : servo/components/util/prefs.rs => servo/components/config/prefs.rs rename : servo/components/util/resource_files.rs => servo/components/config/resource_files.rs rename : servo/components/util/geometry.rs => servo/components/geometry/lib.rs rename : servo/components/util/remutex.rs => servo/components/remutex/lib.rs rename : servo/tests/unit/util/lib.rs => servo/tests/unit/servo_config/lib.rs rename : servo/tests/unit/util/opts.rs => servo/tests/unit/servo_config/opts.rs rename : servo/tests/unit/util/prefs.rs => servo/tests/unit/servo_config/prefs.rs rename : servo/tests/unit/util/remutex.rs => servo/tests/unit/servo_remutex/lib.rs
2016-12-15 00:48:42 +00:00
use servo_config::opts;
use std::sync::atomic::Ordering;
use traversal::{DomTraversal, PerLevelTraversalData, PreTraverseToken};
use traversal::{STYLE_SHARING_CACHE_HITS, STYLE_SHARING_CACHE_MISSES};
pub const CHUNK_SIZE: usize = 64;
#[allow(unsafe_code)]
pub fn traverse_dom<N, D>(traversal: &D,
root: N::ConcreteElement,
known_root_dom_depth: Option<usize>,
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
token: PreTraverseToken,
queue: &rayon::ThreadPool)
where N: TNode,
D: DomTraversal<N>
{
if opts::get().style_sharing_stats {
STYLE_SHARING_CACHE_HITS.store(0, Ordering::SeqCst);
STYLE_SHARING_CACHE_MISSES.store(0, Ordering::SeqCst);
}
// Handle Gecko's eager initial styling. We don't currently support it
// in conjunction with bottom-up traversal. If we did, we'd need to put
// it on the context to make it available to the bottom-up phase.
let (nodes, depth) = if token.traverse_unstyled_children_only() {
debug_assert!(!D::needs_postorder_traversal());
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
let mut children = vec![];
for kid in root.as_node().children() {
if kid.as_element().map_or(false, |el| el.get_data().is_none()) {
children.push(unsafe { SendNode::new(kid) });
}
}
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
(children, known_root_dom_depth.map(|x| x + 1))
} else {
(vec![unsafe { SendNode::new(root.as_node()) }], known_root_dom_depth)
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
};
let traversal_data = PerLevelTraversalData {
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
current_dom_depth: depth,
};
let tls = ScopedTLS::<D::ThreadLocalContext>::new(queue);
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
let root = root.as_node().opaque();
queue.install(|| {
rayon::scope(|scope| {
traverse_nodes(nodes, root, traversal_data, scope, traversal, &tls);
});
});
if opts::get().style_sharing_stats {
let hits = STYLE_SHARING_CACHE_HITS.load(Ordering::SeqCst);
let misses = STYLE_SHARING_CACHE_MISSES.load(Ordering::SeqCst);
println!("Style sharing stats:");
println!(" * Hits: {}", hits);
println!(" * Misses: {}", misses);
}
}
/// A parallel top-down DOM traversal.
#[inline(always)]
#[allow(unsafe_code)]
fn top_down_dom<'a, 'scope, N, D>(nodes: &'a [SendNode<N>],
root: OpaqueNode,
mut traversal_data: PerLevelTraversalData,
scope: &'a rayon::Scope<'scope>,
traversal: &'scope D,
tls: &'scope ScopedTLS<'scope, D::ThreadLocalContext>)
where N: TNode + 'scope,
D: DomTraversal<N>,
{
let mut discovered_child_nodes = vec![];
{
// Scope the borrow of the TLS so that the borrow is dropped before
// potentially traversing a child on this thread.
let mut tlc = tls.ensure(|| traversal.create_thread_local_context());
for n in nodes {
// Perform the appropriate traversal.
let node = **n;
let mut children_to_process = 0isize;
traversal.process_preorder(&mut traversal_data, &mut *tlc, node);
if let Some(el) = node.as_element() {
D::traverse_children(el, |kid| {
children_to_process += 1;
discovered_child_nodes.push(unsafe { SendNode::new(kid) })
});
}
// Reset the count of children if we need to do a bottom-up traversal
// after the top up.
if D::needs_postorder_traversal() {
if children_to_process == 0 {
// If there were no more children, start walking back up.
bottom_up_dom(traversal, &mut *tlc, root, node)
} else {
// Otherwise record the number of children to process when the
// time comes.
node.as_element().unwrap().store_children_to_process(children_to_process);
}
}
}
}
if let Some(ref mut depth) = traversal_data.current_dom_depth {
*depth += 1;
}
traverse_nodes(discovered_child_nodes, root, traversal_data, scope, traversal, tls);
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
}
fn traverse_nodes<'a, 'scope, N, D>(nodes: Vec<SendNode<N>>, root: OpaqueNode,
traversal_data: PerLevelTraversalData,
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
scope: &'a rayon::Scope<'scope>,
traversal: &'scope D,
tls: &'scope ScopedTLS<'scope, D::ThreadLocalContext>)
where N: TNode + 'scope,
D: DomTraversal<N>,
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
{
if nodes.is_empty() {
return;
}
// Optimization: traverse directly and avoid a heap-allocating spawn() call if
// we're only pushing one work unit.
if nodes.len() <= CHUNK_SIZE {
let nodes = nodes.into_boxed_slice();
top_down_dom(&nodes, root, traversal_data, scope, traversal, tls);
servo: Merge #14436 - Make restyle tracking more granular (from bholley:granular_restyle); r=emilio The primary idea of this patch is to ditch the rigid enum of Previous/Current styles, and replace it with a series of indicators for the various types of work that needs to be performed (expanding snapshots, rematching, recascading, and damage processing). This loses us a little bit of sanity checking (since the up-to-date-ness of our style is no longer baked into the type system), but gives us a lot more flexibility that we'll need going forward (especially when we separate matching from cascading). We also eliminate get_styling_mode in favor of a method on the traversal. This patch does a few other things as ridealongs: * Temporarily eliminates the handling for transfering ownership of styles to the frame. We'll need this again at some point, but for now it's causing too much complexity for a half-implemented feature. * Ditches TRestyleDamage, which is no longer necessary post-crate-merge, and is a constant source of compilation failures from either needing to be imported or being unnecessarily imported (which varies between gecko and servo). * Expands Snapshots for the traversal root, which was missing before. * Fixes up the skip_root stuff to avoid visiting the skipped root. * Unifies parallel traversal and avoids spawning for a single work item. * Adds an explicit pre_traverse step do any pre-processing and determine whether we need to traverse at all. Source-Repo: https://github.com/servo/servo Source-Revision: b9a8ccd775c3192e3810a1730b1d0bc2b5c9dfb6
2016-12-10 01:01:05 +00:00
return;
}
// General case.
for chunk in nodes.chunks(CHUNK_SIZE) {
let nodes = chunk.iter().cloned().collect::<Vec<_>>().into_boxed_slice();
let traversal_data = traversal_data.clone();
scope.spawn(move |scope| {
let nodes = nodes;
top_down_dom(&nodes, root, traversal_data, scope, traversal, tls)
})
}
}
/// Process current node and potentially traverse its ancestors.
///
/// If we are the last child that finished processing, recursively process
/// our parent. Else, stop. Also, stop at the root.
///
/// Thus, if we start with all the leaves of a tree, we end up traversing
/// the whole tree bottom-up because each parent will be processed exactly
/// once (by the last child that finishes processing).
///
/// The only communication between siblings is that they both
/// fetch-and-subtract the parent's children count.
fn bottom_up_dom<N, D>(traversal: &D,
thread_local: &mut D::ThreadLocalContext,
root: OpaqueNode,
mut node: N)
where N: TNode,
D: DomTraversal<N>
{
loop {
// Perform the appropriate operation.
traversal.process_postorder(thread_local, node);
if node.opaque() == root {
break;
}
let parent = match node.parent_element() {
None => unreachable!("How can this happen after the break above?"),
Some(parent) => parent,
};
let remaining = parent.did_process_child();
if remaining != 0 {
// Get out of here and find another node to work on.
break
}
// We were the last child of our parent. Construct flows for our parent.
node = parent.as_node();
}
}