QtBase  v6.3.1
hb-repacker.hh
Go to the documentation of this file.
1 /*
2  * Copyright © 2020 Google, Inc.
3  *
4  * This is part of HarfBuzz, a text shaping library.
5  *
6  * Permission is hereby granted, without written agreement and without
7  * license or royalty fees, to use, copy, modify, and distribute this
8  * software and its documentation for any purpose, provided that the
9  * above copyright notice and the following two paragraphs appear in
10  * all copies of this software.
11  *
12  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16  * DAMAGE.
17  *
18  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20  * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
21  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23  *
24  * Google Author(s): Garret Rieger
25  */
26 
27 #ifndef HB_REPACKER_HH
28 #define HB_REPACKER_HH
29 
30 #include "hb-open-type.hh"
31 #include "hb-map.hh"
32 #include "hb-priority-queue.hh"
33 #include "hb-serialize.hh"
34 #include "hb-vector.hh"
35 
36 /*
37  * For a detailed writeup on the overflow resolution algorithm see:
38  * docs/repacker.md
39  */
40 struct graph_t
41 {
42  struct vertex_t
43  {
45  int64_t distance = 0 ;
46  int64_t space = 0 ;
48  unsigned start = 0;
49  unsigned end = 0;
50  unsigned priority = 0;
51 
52  bool is_shared () const
53  {
54  return parents.length > 1;
55  }
56 
57  unsigned incoming_edges () const
58  {
59  return parents.length;
60  }
61 
62  void remove_parent (unsigned parent_index)
63  {
64  for (unsigned i = 0; i < parents.length; i++)
65  {
66  if (parents[i] != parent_index) continue;
67  parents.remove (i);
68  break;
69  }
70  }
71 
72  void remap_parents (const hb_vector_t<unsigned>& id_map)
73  {
74  for (unsigned i = 0; i < parents.length; i++)
75  parents[i] = id_map[parents[i]];
76  }
77 
78  void remap_parent (unsigned old_index, unsigned new_index)
79  {
80  for (unsigned i = 0; i < parents.length; i++)
81  {
82  if (parents[i] == old_index)
83  parents[i] = new_index;
84  }
85  }
86 
87  bool is_leaf () const
88  {
89  return !obj.real_links.length && !obj.virtual_links.length;
90  }
91 
93  {
94  if (has_max_priority ()) return false;
95  priority++;
96  return true;
97  }
98 
99  bool has_max_priority () const {
100  return priority >= 3;
101  }
102 
103  int64_t modified_distance (unsigned order) const
104  {
105  // TODO(garretrieger): once priority is high enough, should try
106  // setting distance = 0 which will force to sort immediately after
107  // it's parent where possible.
108 
109  int64_t modified_distance =
110  hb_min (hb_max(distance + distance_modifier (), 0), 0x7FFFFFFFFFF);
111  if (has_max_priority ()) {
112  modified_distance = 0;
113  }
114  return (modified_distance << 18) | (0x003FFFF & order);
115  }
116 
117  int64_t distance_modifier () const
118  {
119  if (!priority) return 0;
120  int64_t table_size = obj.tail - obj.head;
121 
122  if (priority == 1)
123  return -table_size / 2;
124 
125  return -table_size;
126  }
127  };
128 
130  {
131  unsigned parent;
132  unsigned child;
133  };
134 
135  /*
136  * A topological sorting of an object graph. Ordered
137  * in reverse serialization order (first object in the
138  * serialization is at the end of the list). This matches
139  * the 'packed' object stack used internally in the
140  * serializer
141  */
142  template<typename T>
143  graph_t (const T& objects)
144  : parents_invalid (true),
145  distance_invalid (true),
146  positions_invalid (true),
147  successful (true)
148  {
149  num_roots_for_space_.push (1);
150  bool removed_nil = false;
151  for (unsigned i = 0; i < objects.length; i++)
152  {
153  // TODO(grieger): check all links point to valid objects.
154 
155  // If this graph came from a serialization buffer object 0 is the
156  // nil object. We don't need it for our purposes here so drop it.
157  if (i == 0 && !objects[i])
158  {
159  removed_nil = true;
160  continue;
161  }
162 
163  vertex_t* v = vertices_.push ();
164  if (check_success (!vertices_.in_error ()))
165  v->obj = *objects[i];
166  if (!removed_nil) continue;
167  // Fix indices to account for removed nil object.
168  for (auto& l : v->obj.all_links_writer ()) {
169  l.objidx--;
170  }
171  }
172  }
173 
175  {
176  vertices_.fini ();
177  }
178 
179  bool in_error () const
180  {
181  return !successful ||
182  vertices_.in_error () ||
183  num_roots_for_space_.in_error ();
184  }
185 
186  const vertex_t& root () const
187  {
188  return vertices_[root_idx ()];
189  }
190 
191  unsigned root_idx () const
192  {
193  // Object graphs are in reverse order, the first object is at the end
194  // of the vector. Since the graph is topologically sorted it's safe to
195  // assume the first object has no incoming edges.
196  return vertices_.length - 1;
197  }
198 
200  {
201  return vertices_[i].obj;
202  }
203 
204  /*
205  * serialize graph into the provided serialization buffer.
206  */
208  {
210  size_t size = serialized_length ();
211  if (!buffer.alloc (size)) {
212  DEBUG_MSG (SUBSET_REPACK, nullptr, "Unable to allocate output buffer.");
213  return nullptr;
214  }
215  hb_serialize_context_t c((void *) buffer, size);
216 
217  c.start_serialize<void> ();
218  for (unsigned i = 0; i < vertices_.length; i++) {
219  c.push ();
220 
221  size_t size = vertices_[i].obj.tail - vertices_[i].obj.head;
222  char* start = c.allocate_size <char> (size);
223  if (!start) {
224  DEBUG_MSG (SUBSET_REPACK, nullptr, "Buffer out of space.");
225  return nullptr;
226  }
227 
228  memcpy (start, vertices_[i].obj.head, size);
229 
230  // Only real links needs to be serialized.
231  for (const auto& link : vertices_[i].obj.real_links)
232  serialize_link (link, start, &c);
233 
234  // All duplications are already encoded in the graph, so don't
235  // enable sharing during packing.
236  c.pop_pack (false);
237  }
238  c.end_serialize ();
239 
240  if (c.in_error ()) {
241  DEBUG_MSG (SUBSET_REPACK, nullptr, "Error during serialization. Err flag: %d",
242  c.errors);
243  return nullptr;
244  }
245 
246  return c.copy_blob ();
247  }
248 
249  /*
250  * Generates a new topological sorting of graph using Kahn's
251  * algorithm: https://en.wikipedia.org/wiki/Topological_sorting#Algorithms
252  */
253  void sort_kahn ()
254  {
255  positions_invalid = true;
256 
257  if (vertices_.length <= 1) {
258  // Graph of 1 or less doesn't need sorting.
259  return;
260  }
261 
263  hb_vector_t<vertex_t> sorted_graph;
264  if (unlikely (!check_success (sorted_graph.resize (vertices_.length)))) return;
265  hb_vector_t<unsigned> id_map;
266  if (unlikely (!check_success (id_map.resize (vertices_.length)))) return;
267 
268  hb_vector_t<unsigned> removed_edges;
269  if (unlikely (!check_success (removed_edges.resize (vertices_.length)))) return;
270  update_parents ();
271 
272  queue.push (root_idx ());
273  int new_id = vertices_.length - 1;
274 
275  while (!queue.in_error () && queue.length)
276  {
277  unsigned next_id = queue[0];
278  queue.remove (0);
279 
280  vertex_t& next = vertices_[next_id];
281  sorted_graph[new_id] = next;
282  id_map[next_id] = new_id--;
283 
284  for (const auto& link : next.obj.all_links ()) {
285  removed_edges[link.objidx]++;
286  if (!(vertices_[link.objidx].incoming_edges () - removed_edges[link.objidx]))
287  queue.push (link.objidx);
288  }
289  }
290 
291  check_success (!queue.in_error ());
292  check_success (!sorted_graph.in_error ());
293  if (!check_success (new_id == -1))
295 
296  remap_all_obj_indices (id_map, &sorted_graph);
297 
298  hb_swap (vertices_, sorted_graph);
299  sorted_graph.fini ();
300  }
301 
302  /*
303  * Generates a new topological sorting of graph ordered by the shortest
304  * distance to each node.
305  */
307  {
308  positions_invalid = true;
309 
310  if (vertices_.length <= 1) {
311  // Graph of 1 or less doesn't need sorting.
312  return;
313  }
314 
315  update_distances ();
316 
318  hb_vector_t<vertex_t> sorted_graph;
319  if (unlikely (!check_success (sorted_graph.resize (vertices_.length)))) return;
320  hb_vector_t<unsigned> id_map;
321  if (unlikely (!check_success (id_map.resize (vertices_.length)))) return;
322 
323  hb_vector_t<unsigned> removed_edges;
324  if (unlikely (!check_success (removed_edges.resize (vertices_.length)))) return;
325  update_parents ();
326 
327  queue.insert (root ().modified_distance (0), root_idx ());
328  int new_id = root_idx ();
329  unsigned order = 1;
330  while (!queue.in_error () && !queue.is_empty ())
331  {
332  unsigned next_id = queue.pop_minimum().second;
333 
334  vertex_t& next = vertices_[next_id];
335  sorted_graph[new_id] = next;
336  id_map[next_id] = new_id--;
337 
338  for (const auto& link : next.obj.all_links ()) {
339  removed_edges[link.objidx]++;
340  if (!(vertices_[link.objidx].incoming_edges () - removed_edges[link.objidx]))
341  // Add the order that the links were encountered to the priority.
342  // This ensures that ties between priorities objects are broken in a consistent
343  // way. More specifically this is set up so that if a set of objects have the same
344  // distance they'll be added to the topological order in the order that they are
345  // referenced from the parent object.
346  queue.insert (vertices_[link.objidx].modified_distance (order++),
347  link.objidx);
348  }
349  }
350 
351  check_success (!queue.in_error ());
352  check_success (!sorted_graph.in_error ());
353  if (!check_success (new_id == -1))
355 
356  remap_all_obj_indices (id_map, &sorted_graph);
357 
358  hb_swap (vertices_, sorted_graph);
359  sorted_graph.fini ();
360  }
361 
362  /*
363  * Assign unique space numbers to each connected subgraph of 32 bit offset(s).
364  */
366  {
367  unsigned root_index = root_idx ();
368  hb_set_t visited;
369  hb_set_t roots;
370  for (unsigned i = 0; i <= root_index; i++)
371  {
372  // Only real links can form 32 bit spaces
373  for (auto& l : vertices_[i].obj.real_links)
374  {
375  if (l.width == 4 && !l.is_signed)
376  {
377  roots.add (l.objidx);
378  find_subgraph (l.objidx, visited);
379  }
380  }
381  }
382 
383  // Mark everything not in the subgraphs of 32 bit roots as visited.
384  // This prevents 32 bit subgraphs from being connected via nodes not in the 32 bit subgraphs.
385  visited.invert ();
386 
387  if (!roots) return false;
388 
389  while (roots)
390  {
391  unsigned next = HB_SET_VALUE_INVALID;
392  if (unlikely (!check_success (!roots.in_error ()))) break;
393  if (!roots.next (&next)) break;
394 
395  hb_set_t connected_roots;
396  find_connected_nodes (next, roots, visited, connected_roots);
397  if (unlikely (!check_success (!connected_roots.in_error ()))) break;
398 
399  isolate_subgraph (connected_roots);
400  if (unlikely (!check_success (!connected_roots.in_error ()))) break;
401 
402  unsigned next_space = this->next_space ();
403  num_roots_for_space_.push (0);
404  for (unsigned root : connected_roots)
405  {
406  DEBUG_MSG (SUBSET_REPACK, nullptr, "Subgraph %u gets space %u", root, next_space);
407  vertices_[root].space = next_space;
408  num_roots_for_space_[next_space] = num_roots_for_space_[next_space] + 1;
409  distance_invalid = true;
410  positions_invalid = true;
411  }
412 
413  // TODO(grieger): special case for GSUB/GPOS use extension promotions to move 16 bit space
414  // into the 32 bit space as needed, instead of using isolation.
415  }
416 
417 
418 
419  return true;
420  }
421 
422  /*
423  * Isolates the subgraph of nodes reachable from root. Any links to nodes in the subgraph
424  * that originate from outside of the subgraph will be removed by duplicating the linked to
425  * object.
426  *
427  * Indices stored in roots will be updated if any of the roots are duplicated to new indices.
428  */
430  {
431  update_parents ();
433 
434  // incoming edges to root_idx should be all 32 bit in length so we don't need to de-dup these
435  // set the subgraph incoming edge count to match all of root_idx's incoming edges
436  hb_set_t parents;
437  for (unsigned root_idx : roots)
438  {
439  subgraph.set (root_idx, wide_parents (root_idx, parents));
440  find_subgraph (root_idx, subgraph);
441  }
442 
443  unsigned original_root_idx = root_idx ();
445  bool made_changes = false;
446  for (auto entry : subgraph.iter ())
447  {
448  const auto& node = vertices_[entry.first];
449  unsigned subgraph_incoming_edges = entry.second;
450 
451  if (subgraph_incoming_edges < node.incoming_edges ())
452  {
453  // Only de-dup objects with incoming links from outside the subgraph.
454  made_changes = true;
455  duplicate_subgraph (entry.first, index_map);
456  }
457  }
458 
459  if (!made_changes)
460  return false;
461 
462  if (original_root_idx != root_idx ()
463  && parents.has (original_root_idx))
464  {
465  // If the root idx has changed since parents was determined, update root idx in parents
466  parents.add (root_idx ());
467  parents.del (original_root_idx);
468  }
469 
470  auto new_subgraph =
471  + subgraph.keys ()
472  | hb_map([&] (unsigned node_idx) {
473  if (index_map.has (node_idx)) return index_map[node_idx];
474  return node_idx;
475  })
476  ;
477 
478  remap_obj_indices (index_map, new_subgraph);
479  remap_obj_indices (index_map, parents.iter (), true);
480 
481  // Update roots set with new indices as needed.
482  unsigned next = HB_SET_VALUE_INVALID;
483  while (roots.next (&next))
484  {
485  if (index_map.has (next))
486  {
487  roots.del (next);
488  roots.add (index_map[next]);
489  }
490  }
491 
492  return true;
493  }
494 
495  void find_subgraph (unsigned node_idx, hb_hashmap_t<unsigned, unsigned>& subgraph)
496  {
497  for (const auto& link : vertices_[node_idx].obj.all_links ())
498  {
499  if (subgraph.has (link.objidx))
500  {
501  subgraph.set (link.objidx, subgraph[link.objidx] + 1);
502  continue;
503  }
504  subgraph.set (link.objidx, 1);
505  find_subgraph (link.objidx, subgraph);
506  }
507  }
508 
509  void find_subgraph (unsigned node_idx, hb_set_t& subgraph)
510  {
511  if (subgraph.has (node_idx)) return;
512  subgraph.add (node_idx);
513  for (const auto& link : vertices_[node_idx].obj.all_links ())
514  find_subgraph (link.objidx, subgraph);
515  }
516 
517  /*
518  * duplicates all nodes in the subgraph reachable from node_idx. Does not re-assign
519  * links. index_map is updated with mappings from old id to new id. If a duplication has already
520  * been performed for a given index, then it will be skipped.
521  */
522  void duplicate_subgraph (unsigned node_idx, hb_hashmap_t<unsigned, unsigned>& index_map)
523  {
524  if (index_map.has (node_idx))
525  return;
526 
527  index_map.set (node_idx, duplicate (node_idx));
528  for (const auto& l : object (node_idx).all_links ()) {
529  duplicate_subgraph (l.objidx, index_map);
530  }
531  }
532 
533  /*
534  * Creates a copy of node_idx and returns it's new index.
535  */
536  unsigned duplicate (unsigned node_idx)
537  {
538  positions_invalid = true;
539  distance_invalid = true;
540 
541  auto* clone = vertices_.push ();
542  auto& child = vertices_[node_idx];
543  if (vertices_.in_error ()) {
544  return -1;
545  }
546 
547  clone->obj.head = child.obj.head;
548  clone->obj.tail = child.obj.tail;
549  clone->distance = child.distance;
550  clone->space = child.space;
551  clone->parents.reset ();
552 
553  unsigned clone_idx = vertices_.length - 2;
554  for (const auto& l : child.obj.real_links)
555  {
556  clone->obj.real_links.push (l);
557  vertices_[l.objidx].parents.push (clone_idx);
558  }
559  for (const auto& l : child.obj.virtual_links)
560  {
561  clone->obj.virtual_links.push (l);
562  vertices_[l.objidx].parents.push (clone_idx);
563  }
564 
565  check_success (!clone->obj.real_links.in_error ());
566  check_success (!clone->obj.virtual_links.in_error ());
567 
568  // The last object is the root of the graph, so swap back the root to the end.
569  // The root's obj idx does change, however since it's root nothing else refers to it.
570  // all other obj idx's will be unaffected.
571  vertex_t root = vertices_[vertices_.length - 2];
572  vertices_[clone_idx] = *clone;
573  vertices_[vertices_.length - 1] = root;
574 
575  // Since the root moved, update the parents arrays of all children on the root.
576  for (const auto& l : root.obj.all_links ())
577  vertices_[l.objidx].remap_parent (root_idx () - 1, root_idx ());
578 
579  return clone_idx;
580  }
581 
582  /*
583  * Creates a copy of child and re-assigns the link from
584  * parent to the clone. The copy is a shallow copy, objects
585  * linked from child are not duplicated.
586  */
587  bool duplicate (unsigned parent_idx, unsigned child_idx)
588  {
589  update_parents ();
590 
591  unsigned links_to_child = 0;
592  for (const auto& l : vertices_[parent_idx].obj.all_links ())
593  {
594  if (l.objidx == child_idx) links_to_child++;
595  }
596 
597  if (vertices_[child_idx].incoming_edges () <= links_to_child)
598  {
599  // Can't duplicate this node, doing so would orphan the original one as all remaining links
600  // to child are from parent.
601  DEBUG_MSG (SUBSET_REPACK, nullptr, " Not duplicating %d => %d",
602  parent_idx, child_idx);
603  return false;
604  }
605 
606  DEBUG_MSG (SUBSET_REPACK, nullptr, " Duplicating %d => %d",
607  parent_idx, child_idx);
608 
609  unsigned clone_idx = duplicate (child_idx);
610  if (clone_idx == (unsigned) -1) return false;
611  // duplicate shifts the root node idx, so if parent_idx was root update it.
612  if (parent_idx == clone_idx) parent_idx++;
613 
614  auto& parent = vertices_[parent_idx];
615  for (auto& l : parent.obj.all_links_writer ())
616  {
617  if (l.objidx != child_idx)
618  continue;
619 
620  reassign_link (l, parent_idx, clone_idx);
621  }
622 
623  return true;
624  }
625 
626  /*
627  * Raises the sorting priority of all children.
628  */
629  bool raise_childrens_priority (unsigned parent_idx)
630  {
631  DEBUG_MSG (SUBSET_REPACK, nullptr, " Raising priority of all children of %d",
632  parent_idx);
633  // This operation doesn't change ordering until a sort is run, so no need
634  // to invalidate positions. It does not change graph structure so no need
635  // to update distances or edge counts.
636  auto& parent = vertices_[parent_idx].obj;
637  bool made_change = false;
638  for (auto& l : parent.all_links_writer ())
639  made_change |= vertices_[l.objidx].raise_priority ();
640  return made_change;
641  }
642 
643  /*
644  * Will any offsets overflow on graph when it's serialized?
645  */
646  bool will_overflow (hb_vector_t<overflow_record_t>* overflows = nullptr)
647  {
648  if (overflows) overflows->resize (0);
649  update_positions ();
650 
651  for (int parent_idx = vertices_.length - 1; parent_idx >= 0; parent_idx--)
652  {
653  // Don't need to check virtual links for overflow
654  for (const auto& link : vertices_[parent_idx].obj.real_links)
655  {
656  int64_t offset = compute_offset (parent_idx, link);
657  if (is_valid_offset (offset, link))
658  continue;
659 
660  if (!overflows) return true;
661 
663  r.parent = parent_idx;
664  r.child = link.objidx;
665  overflows->push (r);
666  }
667  }
668 
669  if (!overflows) return false;
670  return overflows->length;
671  }
672 
674  {
675  if (!DEBUG_ENABLED(SUBSET_REPACK)) return;
676 
677  DEBUG_MSG (SUBSET_REPACK, nullptr, "Graph is not fully connected.");
678  parents_invalid = true;
679  update_parents();
680 
681  for (unsigned i = 0; i < root_idx (); i++)
682  {
683  const auto& v = vertices_[i];
684  if (!v.parents)
685  DEBUG_MSG (SUBSET_REPACK, nullptr, "Node %u is orphaned.", i);
686  }
687  }
688 
690  {
691  if (!DEBUG_ENABLED(SUBSET_REPACK)) return;
692 
693  update_parents ();
694  int limit = 10;
695  for (const auto& o : overflows)
696  {
697  if (!limit--) break;
698  const auto& parent = vertices_[o.parent];
699  const auto& child = vertices_[o.child];
700  DEBUG_MSG (SUBSET_REPACK, nullptr,
701  " overflow from "
702  "%4d (%4d in, %4d out, space %2d) => "
703  "%4d (%4d in, %4d out, space %2d)",
704  o.parent,
705  parent.incoming_edges (),
706  parent.obj.real_links.length + parent.obj.virtual_links.length,
707  space_for (o.parent),
708  o.child,
709  child.incoming_edges (),
710  child.obj.real_links.length + child.obj.virtual_links.length,
711  space_for (o.child));
712  }
713  if (overflows.length > 10) {
714  DEBUG_MSG (SUBSET_REPACK, nullptr, " ... plus %d more overflows.", overflows.length - 10);
715  }
716  }
717 
718  unsigned num_roots_for_space (unsigned space) const
719  {
720  return num_roots_for_space_[space];
721  }
722 
723  unsigned next_space () const
724  {
725  return num_roots_for_space_.length;
726  }
727 
729  {
730  num_roots_for_space_.push (0);
731  unsigned new_space = num_roots_for_space_.length - 1;
732 
733  for (unsigned index : indices) {
734  auto& node = vertices_[index];
735  num_roots_for_space_[node.space] = num_roots_for_space_[node.space] - 1;
736  num_roots_for_space_[new_space] = num_roots_for_space_[new_space] + 1;
737  node.space = new_space;
738  distance_invalid = true;
739  positions_invalid = true;
740  }
741  }
742 
743  unsigned space_for (unsigned index, unsigned* root = nullptr) const
744  {
745  const auto& node = vertices_[index];
746  if (node.space)
747  {
748  if (root != nullptr)
749  *root = index;
750  return node.space;
751  }
752 
753  if (!node.parents)
754  {
755  if (root)
756  *root = index;
757  return 0;
758  }
759 
760  return space_for (node.parents[0], root);
761  }
762 
763  void err_other_error () { this->successful = false; }
764 
765  private:
766 
767  size_t serialized_length () const {
768  size_t total_size = 0;
769  for (unsigned i = 0; i < vertices_.length; i++) {
770  size_t size = vertices_[i].obj.tail - vertices_[i].obj.head;
771  total_size += size;
772  }
773  return total_size;
774  }
775 
776  /*
777  * Returns the numbers of incoming edges that are 32bits wide.
778  */
779  unsigned wide_parents (unsigned node_idx, hb_set_t& parents) const
780  {
781  unsigned count = 0;
782  hb_set_t visited;
783  for (unsigned p : vertices_[node_idx].parents)
784  {
785  if (visited.has (p)) continue;
786  visited.add (p);
787 
788  // Only real links can be wide
789  for (const auto& l : vertices_[p].obj.real_links)
790  {
791  if (l.objidx == node_idx && l.width == 4 && !l.is_signed)
792  {
793  count++;
794  parents.add (p);
795  }
796  }
797  }
798  return count;
799  }
800 
801  bool check_success (bool success)
802  { return this->successful && (success || (err_other_error (), false)); }
803 
804  /*
805  * Creates a map from objid to # of incoming edges.
806  */
807  void update_parents ()
808  {
809  if (!parents_invalid) return;
810 
811  for (unsigned i = 0; i < vertices_.length; i++)
812  vertices_[i].parents.reset ();
813 
814  for (unsigned p = 0; p < vertices_.length; p++)
815  {
816  for (auto& l : vertices_[p].obj.all_links ())
817  {
818  vertices_[l.objidx].parents.push (p);
819  }
820  }
821 
822  parents_invalid = false;
823  }
824 
825  /*
826  * compute the serialized start and end positions for each vertex.
827  */
828  void update_positions ()
829  {
830  if (!positions_invalid) return;
831 
832  unsigned current_pos = 0;
833  for (int i = root_idx (); i >= 0; i--)
834  {
835  auto& v = vertices_[i];
836  v.start = current_pos;
837  current_pos += v.obj.tail - v.obj.head;
838  v.end = current_pos;
839  }
840 
841  positions_invalid = false;
842  }
843 
844  /*
845  * Finds the distance to each object in the graph
846  * from the initial node.
847  */
848  void update_distances ()
849  {
850  if (!distance_invalid) return;
851 
852  // Uses Dijkstra's algorithm to find all of the shortest distances.
853  // https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
854  //
855  // Implementation Note:
856  // Since our priority queue doesn't support fast priority decreases
857  // we instead just add new entries into the queue when a priority changes.
858  // Redundant ones are filtered out later on by the visited set.
859  // According to https://www3.cs.stonybrook.edu/~rezaul/papers/TR-07-54.pdf
860  // for practical performance this is faster then using a more advanced queue
861  // (such as a fibonacci queue) with a fast decrease priority.
862  for (unsigned i = 0; i < vertices_.length; i++)
863  {
864  if (i == vertices_.length - 1)
865  vertices_[i].distance = 0;
866  else
867  vertices_[i].distance = hb_int_max (int64_t);
868  }
869 
871  queue.insert (0, vertices_.length - 1);
872 
873  hb_vector_t<bool> visited;
874  visited.resize (vertices_.length);
875 
876  while (!queue.in_error () && !queue.is_empty ())
877  {
878  unsigned next_idx = queue.pop_minimum ().second;
879  if (visited[next_idx]) continue;
880  const auto& next = vertices_[next_idx];
881  int64_t next_distance = vertices_[next_idx].distance;
882  visited[next_idx] = true;
883 
884  for (const auto& link : next.obj.all_links ())
885  {
886  if (visited[link.objidx]) continue;
887 
888  const auto& child = vertices_[link.objidx].obj;
889  unsigned link_width = link.width ? link.width : 4; // treat virtual offsets as 32 bits wide
890  int64_t child_weight = (child.tail - child.head) +
891  ((int64_t) 1 << (link_width * 8)) * (vertices_[link.objidx].space + 1);
892  int64_t child_distance = next_distance + child_weight;
893 
894  if (child_distance < vertices_[link.objidx].distance)
895  {
896  vertices_[link.objidx].distance = child_distance;
897  queue.insert (child_distance, link.objidx);
898  }
899  }
900  }
901 
902  check_success (!queue.in_error ());
903  if (!check_success (queue.is_empty ()))
904  {
906  return;
907  }
908 
909  distance_invalid = false;
910  }
911 
912  int64_t compute_offset (
913  unsigned parent_idx,
915  {
916  const auto& parent = vertices_[parent_idx];
917  const auto& child = vertices_[link.objidx];
918  int64_t offset = 0;
919  switch ((hb_serialize_context_t::whence_t) link.whence) {
920  case hb_serialize_context_t::whence_t::Head:
921  offset = child.start - parent.start; break;
922  case hb_serialize_context_t::whence_t::Tail:
923  offset = child.start - parent.end; break;
924  case hb_serialize_context_t::whence_t::Absolute:
925  offset = child.start; break;
926  }
927 
928  assert (offset >= link.bias);
929  offset -= link.bias;
930  return offset;
931  }
932 
933  bool is_valid_offset (int64_t offset,
935  {
936  if (unlikely (!link.width))
937  // Virtual links can't overflow.
938  return link.is_signed || offset >= 0;
939 
940  if (link.is_signed)
941  {
942  if (link.width == 4)
943  return offset >= -((int64_t) 1 << 31) && offset < ((int64_t) 1 << 31);
944  else
945  return offset >= -(1 << 15) && offset < (1 << 15);
946  }
947  else
948  {
949  if (link.width == 4)
950  return offset >= 0 && offset < ((int64_t) 1 << 32);
951  else if (link.width == 3)
952  return offset >= 0 && offset < ((int32_t) 1 << 24);
953  else
954  return offset >= 0 && offset < (1 << 16);
955  }
956  }
957 
958  /*
959  * Updates a link in the graph to point to a different object. Corrects the
960  * parents vector on the previous and new child nodes.
961  */
962  void reassign_link (hb_serialize_context_t::object_t::link_t& link,
963  unsigned parent_idx,
964  unsigned new_idx)
965  {
966  unsigned old_idx = link.objidx;
967  link.objidx = new_idx;
968  vertices_[old_idx].remove_parent (parent_idx);
969  vertices_[new_idx].parents.push (parent_idx);
970  }
971 
972  /*
973  * Updates all objidx's in all links using the provided mapping. Corrects incoming edge counts.
974  */
975  template<typename Iterator, hb_requires (hb_is_iterator (Iterator))>
976  void remap_obj_indices (const hb_hashmap_t<unsigned, unsigned>& id_map,
977  Iterator subgraph,
978  bool only_wide = false)
979  {
980  if (!id_map) return;
981  for (unsigned i : subgraph)
982  {
983  for (auto& link : vertices_[i].obj.all_links_writer ())
984  {
985  if (!id_map.has (link.objidx)) continue;
986  if (only_wide && !(link.width == 4 && !link.is_signed)) continue;
987 
988  reassign_link (link, i, id_map[link.objidx]);
989  }
990  }
991  }
992 
993  /*
994  * Updates all objidx's in all links using the provided mapping.
995  */
996  void remap_all_obj_indices (const hb_vector_t<unsigned>& id_map,
997  hb_vector_t<vertex_t>* sorted_graph) const
998  {
999  for (unsigned i = 0; i < sorted_graph->length; i++)
1000  {
1001  (*sorted_graph)[i].remap_parents (id_map);
1002  for (auto& link : (*sorted_graph)[i].obj.all_links_writer ())
1003  {
1004  link.objidx = id_map[link.objidx];
1005  }
1006  }
1007  }
1008 
1009  template <typename O> void
1010  serialize_link_of_type (const hb_serialize_context_t::object_t::link_t& link,
1011  char* head,
1012  hb_serialize_context_t* c) const
1013  {
1014  OT::Offset<O>* offset = reinterpret_cast<OT::Offset<O>*> (head + link.position);
1015  *offset = 0;
1016  c->add_link (*offset,
1017  // serializer has an extra nil object at the start of the
1018  // object array. So all id's are +1 of what our id's are.
1019  link.objidx + 1,
1021  link.bias);
1022  }
1023 
1024  void serialize_link (const hb_serialize_context_t::object_t::link_t& link,
1025  char* head,
1026  hb_serialize_context_t* c) const
1027  {
1028  switch (link.width)
1029  {
1030  case 0:
1031  // Virtual links aren't serialized.
1032  return;
1033  case 4:
1034  if (link.is_signed)
1035  {
1036  serialize_link_of_type<OT::HBINT32> (link, head, c);
1037  } else {
1038  serialize_link_of_type<OT::HBUINT32> (link, head, c);
1039  }
1040  return;
1041  case 2:
1042  if (link.is_signed)
1043  {
1044  serialize_link_of_type<OT::HBINT16> (link, head, c);
1045  } else {
1046  serialize_link_of_type<OT::HBUINT16> (link, head, c);
1047  }
1048  return;
1049  case 3:
1050  serialize_link_of_type<OT::HBUINT24> (link, head, c);
1051  return;
1052  default:
1053  // Unexpected link width.
1054  assert (0);
1055  }
1056  }
1057 
1058  /*
1059  * Finds all nodes in targets that are reachable from start_idx, nodes in visited will be skipped.
1060  * For this search the graph is treated as being undirected.
1061  *
1062  * Connected targets will be added to connected and removed from targets. All visited nodes
1063  * will be added to visited.
1064  */
1065  void find_connected_nodes (unsigned start_idx,
1066  hb_set_t& targets,
1067  hb_set_t& visited,
1068  hb_set_t& connected)
1069  {
1070  if (unlikely (!check_success (!visited.in_error ()))) return;
1071  if (visited.has (start_idx)) return;
1072  visited.add (start_idx);
1073 
1074  if (targets.has (start_idx))
1075  {
1076  targets.del (start_idx);
1077  connected.add (start_idx);
1078  }
1079 
1080  const auto& v = vertices_[start_idx];
1081 
1082  // Graph is treated as undirected so search children and parents of start_idx
1083  for (const auto& l : v.obj.all_links ())
1084  find_connected_nodes (l.objidx, targets, visited, connected);
1085 
1086  for (unsigned p : v.parents)
1087  find_connected_nodes (p, targets, visited, connected);
1088  }
1089 
1090  public:
1091  // TODO(garretrieger): make private, will need to move most of offset overflow code into graph.
1093  private:
1094  bool parents_invalid;
1095  bool distance_invalid;
1096  bool positions_invalid;
1097  bool successful;
1098  hb_vector_t<unsigned> num_roots_for_space_;
1099 };
1100 
1101 static inline
1102 bool _try_isolating_subgraphs (const hb_vector_t<graph_t::overflow_record_t>& overflows,
1103  graph_t& sorted_graph)
1104 {
1105  unsigned space = 0;
1106  hb_set_t roots_to_isolate;
1107 
1108  for (int i = overflows.length - 1; i >= 0; i--)
1109  {
1110  const graph_t::overflow_record_t& r = overflows[i];
1111 
1112  unsigned root;
1113  unsigned overflow_space = sorted_graph.space_for (r.parent, &root);
1114  if (!overflow_space) continue;
1115  if (sorted_graph.num_roots_for_space (overflow_space) <= 1) continue;
1116 
1117  if (!space) {
1118  space = overflow_space;
1119  }
1120 
1121  if (space == overflow_space)
1122  roots_to_isolate.add(root);
1123  }
1124 
1125  if (!roots_to_isolate) return false;
1126 
1127  unsigned maximum_to_move = hb_max ((sorted_graph.num_roots_for_space (space) / 2u), 1u);
1128  if (roots_to_isolate.get_population () > maximum_to_move) {
1129  // Only move at most half of the roots in a space at a time.
1130  unsigned extra = roots_to_isolate.get_population () - maximum_to_move;
1131  while (extra--) {
1132  unsigned root = HB_SET_VALUE_INVALID;
1133  roots_to_isolate.previous (&root);
1134  roots_to_isolate.del (root);
1135  }
1136  }
1137 
1138  DEBUG_MSG (SUBSET_REPACK, nullptr,
1139  "Overflow in space %d (%d roots). Moving %d roots to space %d.",
1140  space,
1141  sorted_graph.num_roots_for_space (space),
1142  roots_to_isolate.get_population (),
1143  sorted_graph.next_space ());
1144 
1145  sorted_graph.isolate_subgraph (roots_to_isolate);
1146  sorted_graph.move_to_new_space (roots_to_isolate);
1147 
1148  return true;
1149 }
1150 
1151 static inline
1152 bool _process_overflows (const hb_vector_t<graph_t::overflow_record_t>& overflows,
1153  hb_set_t& priority_bumped_parents,
1154  graph_t& sorted_graph)
1155 {
1156  bool resolution_attempted = false;
1157 
1158  // Try resolving the furthest overflows first.
1159  for (int i = overflows.length - 1; i >= 0; i--)
1160  {
1161  const graph_t::overflow_record_t& r = overflows[i];
1162  const auto& child = sorted_graph.vertices_[r.child];
1163  if (child.is_shared ())
1164  {
1165  // The child object is shared, we may be able to eliminate the overflow
1166  // by duplicating it.
1167  if (!sorted_graph.duplicate (r.parent, r.child)) continue;
1168  return true;
1169  }
1170 
1171  if (child.is_leaf () && !priority_bumped_parents.has (r.parent))
1172  {
1173  // This object is too far from it's parent, attempt to move it closer.
1174  //
1175  // TODO(garretrieger): initially limiting this to leaf's since they can be
1176  // moved closer with fewer consequences. However, this can
1177  // likely can be used for non-leafs as well.
1178  // TODO(garretrieger): also try lowering priority of the parent. Make it
1179  // get placed further up in the ordering, closer to it's children.
1180  // this is probably preferable if the total size of the parent object
1181  // is < then the total size of the children (and the parent can be moved).
1182  // Since in that case moving the parent will cause a smaller increase in
1183  // the length of other offsets.
1184  if (sorted_graph.raise_childrens_priority (r.parent)) {
1185  priority_bumped_parents.add (r.parent);
1186  resolution_attempted = true;
1187  }
1188  continue;
1189  }
1190 
1191  // TODO(garretrieger): add additional offset resolution strategies
1192  // - Promotion to extension lookups.
1193  // - Table splitting.
1194  }
1195 
1196  return resolution_attempted;
1197 }
1198 
1199 /*
1200  * Attempts to modify the topological sorting of the provided object graph to
1201  * eliminate offset overflows in the links between objects of the graph. If a
1202  * non-overflowing ordering is found the updated graph is serialized it into the
1203  * provided serialization context.
1204  *
1205  * If necessary the structure of the graph may be modified in ways that do not
1206  * affect the functionality of the graph. For example shared objects may be
1207  * duplicated.
1208  *
1209  * For a detailed writeup describing how the algorithm operates see:
1210  * docs/repacker.md
1211  */
1212 template<typename T>
1213 inline hb_blob_t*
1216  unsigned max_rounds = 20) {
1217  // Kahn sort is ~twice as fast as shortest distance sort and works for many fonts
1218  // so try it first to save time.
1219  graph_t sorted_graph (packed);
1220  sorted_graph.sort_kahn ();
1221  if (!sorted_graph.will_overflow ())
1222  {
1223  return sorted_graph.serialize ();
1224  }
1225 
1226  sorted_graph.sort_shortest_distance ();
1227 
1228  if ((table_tag == HB_OT_TAG_GPOS
1229  || table_tag == HB_OT_TAG_GSUB)
1230  && sorted_graph.will_overflow ())
1231  {
1232  DEBUG_MSG (SUBSET_REPACK, nullptr, "Assigning spaces to 32 bit subgraphs.");
1233  if (sorted_graph.assign_32bit_spaces ())
1234  sorted_graph.sort_shortest_distance ();
1235  }
1236 
1237  unsigned round = 0;
1239  // TODO(garretrieger): select a good limit for max rounds.
1240  while (!sorted_graph.in_error ()
1241  && sorted_graph.will_overflow (&overflows)
1242  && round++ < max_rounds) {
1243  DEBUG_MSG (SUBSET_REPACK, nullptr, "=== Overflow resolution round %d ===", round);
1244  sorted_graph.print_overflows (overflows);
1245 
1246  hb_set_t priority_bumped_parents;
1247 
1248  if (!_try_isolating_subgraphs (overflows, sorted_graph))
1249  {
1250  if (!_process_overflows (overflows, priority_bumped_parents, sorted_graph))
1251  {
1252  DEBUG_MSG (SUBSET_REPACK, nullptr, "No resolution available :(");
1253  break;
1254  }
1255  }
1256 
1257  sorted_graph.sort_shortest_distance ();
1258  }
1259 
1260  if (sorted_graph.in_error ())
1261  {
1262  DEBUG_MSG (SUBSET_REPACK, nullptr, "Sorted graph in error state.");
1263  return nullptr;
1264  }
1265 
1266  if (sorted_graph.will_overflow ())
1267  {
1268  DEBUG_MSG (SUBSET_REPACK, nullptr, "Offset overflow resolution failed.");
1269  return nullptr;
1270  }
1271 
1272  return sorted_graph.serialize ();
1273 }
1274 
1275 #endif /* HB_REPACKER_HH */
small capitals from c petite p scientific i
[1]
Definition: afcover.h:80
QQueue< int > queue
[0]
#define true
Definition: ftrandom.c:51
#define DEBUG_MSG(WHAT, OBJ,...)
#define DEBUG_ENABLED(WHAT)
Definition: hb-debug.hh:94
auto it hb_map(hb_second)) template< typename Type > inline hb_array_t< Type > operator()(hb_array_t< Type > array
#define hb_int_max(T)
Definition: hb-meta.hh:189
HB_EXTERN hb_tag_t table_tag
hb_blob_t * hb_resolve_overflows(const T &packed, hb_tag_t table_tag, unsigned max_rounds=20)
#define unlikely(expr)
Definition: hb.hh:251
short next
Definition: keywords.cpp:454
QPainterPath node()
Definition: paths.cpp:574
#define assert
Definition: qcborcommon_p.h:63
GLsizei const GLfloat * v
[13]
GLboolean r
[2]
GLenum GLuint GLintptr GLsizeiptr size
[1]
GLuint index
[2]
GLuint GLuint end
GLenum GLenum GLsizei count
GLsizei GLsizei GLfloat distance
GLenum GLuint buffer
GLuint start
GLenum GLuint GLintptr offset
GLsizei GLenum const void * indices
GLhandleARB obj
[2]
Definition: qopenglext.h:4164
const GLubyte * c
Definition: qopenglext.h:12701
GLuint entry
Definition: qopenglext.h:11002
GLint limit
Definition: qopenglext.h:9975
GLfloat GLfloat p
[1]
Definition: qopenglext.h:12698
GLfixed GLfixed GLint GLint order
Definition: qopenglext.h:5206
GLuint GLenum GLsizei GLsizei GLint GLint GLboolean packed
Definition: qopenglext.h:9781
uint32_t hb_tag_t
Definition: hb-common.h:157
#define HB_OT_TAG_GPOS
Definition: hb-ot-layout.h:64
#define HB_OT_TAG_GSUB
Definition: hb-ot-layout.h:58
#define HB_SET_VALUE_INVALID
Definition: hb-set.h:46
QLayoutItem * child
[0]
Definition: main.cpp:38
int64_t modified_distance(unsigned order) const
Definition: hb-repacker.hh:103
bool has_max_priority() const
Definition: hb-repacker.hh:99
int64_t distance_modifier() const
Definition: hb-repacker.hh:117
void remap_parents(const hb_vector_t< unsigned > &id_map)
Definition: hb-repacker.hh:72
void remove_parent(unsigned parent_index)
Definition: hb-repacker.hh:62
bool is_shared() const
Definition: hb-repacker.hh:52
bool is_leaf() const
Definition: hb-repacker.hh:87
hb_vector_t< unsigned > parents
Definition: hb-repacker.hh:47
hb_serialize_context_t::object_t obj
Definition: hb-repacker.hh:44
void remap_parent(unsigned old_index, unsigned new_index)
Definition: hb-repacker.hh:78
unsigned incoming_edges() const
Definition: hb-repacker.hh:57
void print_orphaned_nodes()
Definition: hb-repacker.hh:673
bool will_overflow(hb_vector_t< overflow_record_t > *overflows=nullptr)
Definition: hb-repacker.hh:646
graph_t(const T &objects)
Definition: hb-repacker.hh:143
unsigned num_roots_for_space(unsigned space) const
Definition: hb-repacker.hh:718
void move_to_new_space(const hb_set_t &indices)
Definition: hb-repacker.hh:728
void duplicate_subgraph(unsigned node_idx, hb_hashmap_t< unsigned, unsigned > &index_map)
Definition: hb-repacker.hh:522
void sort_shortest_distance()
Definition: hb-repacker.hh:306
unsigned space_for(unsigned index, unsigned *root=nullptr) const
Definition: hb-repacker.hh:743
unsigned next_space() const
Definition: hb-repacker.hh:723
void find_subgraph(unsigned node_idx, hb_hashmap_t< unsigned, unsigned > &subgraph)
Definition: hb-repacker.hh:495
const vertex_t & root() const
Definition: hb-repacker.hh:186
hb_blob_t * serialize() const
Definition: hb-repacker.hh:207
bool isolate_subgraph(hb_set_t &roots)
Definition: hb-repacker.hh:429
unsigned duplicate(unsigned node_idx)
Definition: hb-repacker.hh:536
bool duplicate(unsigned parent_idx, unsigned child_idx)
Definition: hb-repacker.hh:587
bool raise_childrens_priority(unsigned parent_idx)
Definition: hb-repacker.hh:629
unsigned root_idx() const
Definition: hb-repacker.hh:191
bool assign_32bit_spaces()
Definition: hb-repacker.hh:365
void sort_kahn()
Definition: hb-repacker.hh:253
void print_overflows(const hb_vector_t< overflow_record_t > &overflows)
Definition: hb-repacker.hh:689
const hb_serialize_context_t::object_t & object(unsigned i) const
Definition: hb-repacker.hh:199
void err_other_error()
Definition: hb-repacker.hh:763
bool in_error() const
Definition: hb-repacker.hh:179
void find_subgraph(unsigned node_idx, hb_set_t &subgraph)
Definition: hb-repacker.hh:509
hb_vector_t< vertex_t > vertices_
auto iter() const HB_AUTO_RETURN(+hb_array(items
bool set(K key, const V &value)
Definition: hb-map.hh:199
bool has(K k, V *vp=nullptr) const
Definition: hb-map.hh:214
auto all_links() const HB_AUTO_RETURN((hb_concat(this -> real_links, this->virtual_links)))
bool previous(hb_codepoint_t *codepoint) const
Definition: hb-set.hh:137
bool next(hb_codepoint_t *codepoint) const
Definition: hb-set.hh:136
iter_t iter() const
Definition: hb-set.hh:155
void invert()
Definition: hb-set.hh:82
bool has(hb_codepoint_t k) const
Definition: hb-set.hh:111
unsigned int get_population() const
Definition: hb-set.hh:145
bool in_error() const
Definition: hb-set.hh:78
void del(hb_codepoint_t g)
Definition: hb-set.hh:102
void add(hb_codepoint_t g)
Definition: hb-set.hh:85
void fini()
Definition: hb-vector.hh:86
Type * push()
Definition: hb-vector.hh:183
bool in_error() const
Definition: hb-vector.hh:203
unsigned int length
Definition: hb-vector.hh:76
bool resize(int size_)
Definition: hb-vector.hh:326
void remove(unsigned int i)
Definition: hb-vector.hh:350
IUIAutomationTreeWalker __RPC__deref_out_opt IUIAutomationElement ** parent