b1726d8beb310a9988790bfc8ca7551325545cf3
[platform/upstream/harfbuzz.git] / src / hb-repacker.hh
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
41 struct graph_t
42 {
43   struct vertex_t
44   {
45     hb_serialize_context_t::object_t obj;
46     int64_t distance = 0 ;
47     int64_t space = 0 ;
48     hb_vector_t<unsigned> parents;
49     unsigned start = 0;
50     unsigned end = 0;
51     unsigned priority = 0;
52
53     bool is_shared () const
54     {
55       return parents.length > 1;
56     }
57
58     unsigned incoming_edges () const
59     {
60       return parents.length;
61     }
62
63     void remove_parent (unsigned parent_index)
64     {
65       for (unsigned i = 0; i < parents.length; i++)
66       {
67         if (parents[i] != parent_index) continue;
68         parents.remove (i);
69         break;
70       }
71     }
72
73     void remap_parents (const hb_vector_t<unsigned>& id_map)
74     {
75       for (unsigned i = 0; i < parents.length; i++)
76         parents[i] = id_map[parents[i]];
77     }
78
79     void remap_parent (unsigned old_index, unsigned new_index)
80     {
81       for (unsigned i = 0; i < parents.length; i++)
82       {
83         if (parents[i] == old_index)
84           parents[i] = new_index;
85       }
86     }
87
88     bool is_leaf () const
89     {
90       return !obj.real_links.length && !obj.virtual_links.length;
91     }
92
93     bool raise_priority ()
94     {
95       if (has_max_priority ()) return false;
96       priority++;
97       return true;
98     }
99
100     bool has_max_priority () const {
101       return priority >= 3;
102     }
103
104     int64_t modified_distance (unsigned order) const
105     {
106       // TODO(garretrieger): once priority is high enough, should try
107       // setting distance = 0 which will force to sort immediately after
108       // it's parent where possible.
109
110       int64_t modified_distance =
111           hb_min (hb_max(distance + distance_modifier (), 0), 0x7FFFFFFFFFF);
112       if (has_max_priority ()) {
113         modified_distance = 0;
114       }
115       return (modified_distance << 18) | (0x003FFFF & order);
116     }
117
118     int64_t distance_modifier () const
119     {
120       if (!priority) return 0;
121       int64_t table_size = obj.tail - obj.head;
122
123       if (priority == 1)
124         return -table_size / 2;
125
126       return -table_size;
127     }
128   };
129
130   struct overflow_record_t
131   {
132     unsigned parent;
133     unsigned child;
134   };
135
136   /*
137    * A topological sorting of an object graph. Ordered
138    * in reverse serialization order (first object in the
139    * serialization is at the end of the list). This matches
140    * the 'packed' object stack used internally in the
141    * serializer
142    */
143   graph_t (const hb_vector_t<hb_serialize_context_t::object_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
174   ~graph_t ()
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
199   const hb_serialize_context_t::object_t& object(unsigned i) const
200   {
201     return vertices_[i].obj;
202   }
203
204   /*
205    * serialize graph into the provided serialization buffer.
206    */
207   hb_blob_t* serialize () const
208   {
209     hb_vector_t<char> buffer;
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
262     hb_vector_t<unsigned> queue;
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))
294       print_orphaned_nodes ();
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    */
306   void sort_shortest_distance ()
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
317     hb_priority_queue_t queue;
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))
354       print_orphaned_nodes ();
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    */
365   bool assign_32bit_spaces ()
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    */
429   bool isolate_subgraph (hb_set_t& roots)
430   {
431     update_parents ();
432     hb_hashmap_t<unsigned, unsigned> subgraph;
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 ();
444     hb_hashmap_t<unsigned, unsigned> index_map;
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
662         overflow_record_t r;
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
673   void print_orphaned_nodes ()
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
689   void print_overflows (const hb_vector_t<overflow_record_t>& overflows)
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
728   void move_to_new_space (const hb_set_t& indices)
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
870     hb_priority_queue_t queue;
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     {
905       print_orphaned_nodes ();
906       return;
907     }
908
909     distance_invalid = false;
910   }
911
912   int64_t compute_offset (
913       unsigned parent_idx,
914       const hb_serialize_context_t::object_t::link_t& link) const
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,
934                         const hb_serialize_context_t::object_t::link_t& link) const
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,
1020                  (hb_serialize_context_t::whence_t) link.whence,
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.
1092   hb_vector_t<vertex_t> vertices_;
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 bool _try_isolating_subgraphs (const hb_vector_t<graph_t::overflow_record_t>& overflows,
1102                                       graph_t& sorted_graph)
1103 {
1104   unsigned space = 0;
1105   hb_set_t roots_to_isolate;
1106
1107   for (int i = overflows.length - 1; i >= 0; i--)
1108   {
1109     const graph_t::overflow_record_t& r = overflows[i];
1110
1111     unsigned root;
1112     unsigned overflow_space = sorted_graph.space_for (r.parent, &root);
1113     if (!overflow_space) continue;
1114     if (sorted_graph.num_roots_for_space (overflow_space) <= 1) continue;
1115
1116     if (!space) {
1117       space = overflow_space;
1118     }
1119
1120     if (space == overflow_space)
1121       roots_to_isolate.add(root);
1122   }
1123
1124   if (!roots_to_isolate) return false;
1125
1126   unsigned maximum_to_move = hb_max ((sorted_graph.num_roots_for_space (space) / 2u), 1u);
1127   if (roots_to_isolate.get_population () > maximum_to_move) {
1128     // Only move at most half of the roots in a space at a time.
1129     unsigned extra = roots_to_isolate.get_population () - maximum_to_move;
1130     while (extra--) {
1131       unsigned root = HB_SET_VALUE_INVALID;
1132       roots_to_isolate.previous (&root);
1133       roots_to_isolate.del (root);
1134     }
1135   }
1136
1137   DEBUG_MSG (SUBSET_REPACK, nullptr,
1138              "Overflow in space %d (%d roots). Moving %d roots to space %d.",
1139              space,
1140              sorted_graph.num_roots_for_space (space),
1141              roots_to_isolate.get_population (),
1142              sorted_graph.next_space ());
1143
1144   sorted_graph.isolate_subgraph (roots_to_isolate);
1145   sorted_graph.move_to_new_space (roots_to_isolate);
1146
1147   return true;
1148 }
1149
1150 static bool _process_overflows (const hb_vector_t<graph_t::overflow_record_t>& overflows,
1151                                 hb_set_t& priority_bumped_parents,
1152                                 graph_t& sorted_graph)
1153 {
1154   bool resolution_attempted = false;
1155
1156   // Try resolving the furthest overflows first.
1157   for (int i = overflows.length - 1; i >= 0; i--)
1158   {
1159     const graph_t::overflow_record_t& r = overflows[i];
1160     const auto& child = sorted_graph.vertices_[r.child];
1161     if (child.is_shared ())
1162     {
1163       // The child object is shared, we may be able to eliminate the overflow
1164       // by duplicating it.
1165       if (!sorted_graph.duplicate (r.parent, r.child)) continue;
1166       return true;
1167     }
1168
1169     if (child.is_leaf () && !priority_bumped_parents.has (r.parent))
1170     {
1171       // This object is too far from it's parent, attempt to move it closer.
1172       //
1173       // TODO(garretrieger): initially limiting this to leaf's since they can be
1174       //                     moved closer with fewer consequences. However, this can
1175       //                     likely can be used for non-leafs as well.
1176       // TODO(garretrieger): also try lowering priority of the parent. Make it
1177       //                     get placed further up in the ordering, closer to it's children.
1178       //                     this is probably preferable if the total size of the parent object
1179       //                     is < then the total size of the children (and the parent can be moved).
1180       //                     Since in that case moving the parent will cause a smaller increase in
1181       //                     the length of other offsets.
1182       if (sorted_graph.raise_childrens_priority (r.parent)) {
1183         priority_bumped_parents.add (r.parent);
1184         resolution_attempted = true;
1185       }
1186       continue;
1187     }
1188
1189     // TODO(garretrieger): add additional offset resolution strategies
1190     // - Promotion to extension lookups.
1191     // - Table splitting.
1192   }
1193
1194   return resolution_attempted;
1195 }
1196
1197 /*
1198  * Attempts to modify the topological sorting of the provided object graph to
1199  * eliminate offset overflows in the links between objects of the graph. If a
1200  * non-overflowing ordering is found the updated graph is serialized it into the
1201  * provided serialization context.
1202  *
1203  * If necessary the structure of the graph may be modified in ways that do not
1204  * affect the functionality of the graph. For example shared objects may be
1205  * duplicated.
1206  *
1207  * For a detailed writeup describing how the algorithm operates see:
1208  * docs/repacker.md
1209  */
1210 inline hb_blob_t*
1211 hb_resolve_overflows (const hb_vector_t<hb_serialize_context_t::object_t *>& packed,
1212                       hb_tag_t table_tag,
1213                       unsigned max_rounds = 20) {
1214   // Kahn sort is ~twice as fast as shortest distance sort and works for many fonts
1215   // so try it first to save time.
1216   graph_t sorted_graph (packed);
1217   sorted_graph.sort_kahn ();
1218   if (!sorted_graph.will_overflow ())
1219   {
1220     return sorted_graph.serialize ();
1221   }
1222
1223   sorted_graph.sort_shortest_distance ();
1224
1225   if ((table_tag == HB_OT_TAG_GPOS
1226        ||  table_tag == HB_OT_TAG_GSUB)
1227       && sorted_graph.will_overflow ())
1228   {
1229     DEBUG_MSG (SUBSET_REPACK, nullptr, "Assigning spaces to 32 bit subgraphs.");
1230     if (sorted_graph.assign_32bit_spaces ())
1231       sorted_graph.sort_shortest_distance ();
1232   }
1233
1234   unsigned round = 0;
1235   hb_vector_t<graph_t::overflow_record_t> overflows;
1236   // TODO(garretrieger): select a good limit for max rounds.
1237   while (!sorted_graph.in_error ()
1238          && sorted_graph.will_overflow (&overflows)
1239          && round++ < max_rounds) {
1240     DEBUG_MSG (SUBSET_REPACK, nullptr, "=== Overflow resolution round %d ===", round);
1241     sorted_graph.print_overflows (overflows);
1242
1243     hb_set_t priority_bumped_parents;
1244
1245     if (!_try_isolating_subgraphs (overflows, sorted_graph))
1246     {
1247       if (!_process_overflows (overflows, priority_bumped_parents, sorted_graph))
1248       {
1249         DEBUG_MSG (SUBSET_REPACK, nullptr, "No resolution available :(");
1250         break;
1251       }
1252     }
1253
1254     sorted_graph.sort_shortest_distance ();
1255   }
1256
1257   if (sorted_graph.in_error ())
1258   {
1259     DEBUG_MSG (SUBSET_REPACK, nullptr, "Sorted graph in error state.");
1260     return nullptr;
1261   }
1262
1263   if (sorted_graph.will_overflow ())
1264   {
1265     DEBUG_MSG (SUBSET_REPACK, nullptr, "Offset overflow resolution failed.");
1266     return nullptr;
1267   }
1268
1269   return sorted_graph.serialize ();
1270 }
1271
1272 #endif /* HB_REPACKER_HH */