trace_processor: eliminate kRefLookupUpidForUtid

It's caused a lot of grief for a long time and b/131297700 is the
last straw.

Get rid of it and instead do explicit resolution of upids at the
end of the trace.

While we're at it, also close sched slices at the end of trace
fixing a long standing bug in trace processor.

Bug: 131297700
Change-Id: Ib1758ae0e044e8aa366374d05efaa85a9509b420
diff --git a/src/trace_processor/trace_storage.h b/src/trace_processor/trace_storage.h
index 2a80cab..47366e1 100644
--- a/src/trace_processor/trace_storage.h
+++ b/src/trace_processor/trace_storage.h
@@ -74,7 +74,6 @@
   kRefIrq = 3,
   kRefSoftIrq = 4,
   kRefUpid = 5,
-  kRefUtidLookupUpid = 6,
   kRefMax
 };
 
@@ -340,6 +339,7 @@
   class CounterDefinitions {
    public:
     using Id = uint32_t;
+    static constexpr Id kInvalidId = std::numeric_limits<Id>::max();
 
     inline Id AddCounterDefinition(StringId name_id,
                                    int64_t ref,
@@ -389,12 +389,26 @@
       values_.emplace_back(value);
       arg_set_ids_.emplace_back(kInvalidArgSetId);
 
+      if (counter_id != CounterDefinitions::kInvalidId) {
+        if (counter_id >= rows_for_counter_id_.size()) {
+          rows_for_counter_id_.resize(counter_id + 1);
+        }
+        rows_for_counter_id_[counter_id].emplace_back(size() - 1);
+      }
+      return size() - 1;
+    }
+
+    void set_counter_id(uint32_t index, CounterDefinitions::Id counter_id) {
+      PERFETTO_DCHECK(counter_ids_[index] == CounterDefinitions::kInvalidId);
+
+      counter_ids_[index] = counter_id;
       if (counter_id >= rows_for_counter_id_.size()) {
         rows_for_counter_id_.resize(counter_id + 1);
       }
-      uint32_t row = size() - 1;
-      rows_for_counter_id_[counter_id].emplace_back(row);
-      return row;
+
+      auto* new_rows = &rows_for_counter_id_[counter_id];
+      new_rows->insert(
+          std::upper_bound(new_rows->begin(), new_rows->end(), index), index);
     }
 
     void set_arg_set_id(uint32_t row, ArgSetId id) { arg_set_ids_[row] = id; }
@@ -462,6 +476,8 @@
       return static_cast<uint32_t>(instant_count() - 1);
     }
 
+    void set_ref(uint32_t row, int64_t ref) { refs_[row] = ref; }
+
     void set_arg_set_id(uint32_t row, ArgSetId id) { arg_set_ids_[row] = id; }
 
     size_t instant_count() const { return timestamps_.size(); }