Stack profiles: Reuse existing frame/module rows rather than adding one per sequence

R=fmayer@google.com

Change-Id: I64511978e0c5b648b0e8e6998d06bd283811e953
diff --git a/src/trace_processor/stack_profile_tracker.cc b/src/trace_processor/stack_profile_tracker.cc
index aa6b764..b006e77 100644
--- a/src/trace_processor/stack_profile_tracker.cc
+++ b/src/trace_processor/stack_profile_tracker.cc
@@ -82,12 +82,35 @@
       static_cast<int64_t>(mapping.load_bias),
       context_->storage->InternString(base::StringView(path))};
 
-  int64_t cur_row;
+  TraceStorage::StackProfileMappings* mappings =
+      context_->storage->mutable_stack_profile_mappings();
+  int64_t cur_row = -1;
   auto it = mapping_idx_.find(row);
   if (it != mapping_idx_.end()) {
     cur_row = it->second;
   } else {
-    cur_row = context_->storage->mutable_stack_profile_mappings()->Insert(row);
+    std::vector<int64_t> db_mappings =
+        mappings->FindMappingRow(row.name_id, row.build_id);
+    for (const int64_t preexisting_mapping : db_mappings) {
+      PERFETTO_DCHECK(preexisting_mapping >= 0);
+      size_t preexisting_row_id = static_cast<size_t>(preexisting_mapping);
+      TraceStorage::StackProfileMappings::Row preexisting_row{
+          mappings->build_ids()[preexisting_row_id],
+          mappings->exact_offsets()[preexisting_row_id],
+          mappings->start_offsets()[preexisting_row_id],
+          mappings->starts()[preexisting_row_id],
+          mappings->ends()[preexisting_row_id],
+          mappings->load_biases()[preexisting_row_id],
+          mappings->names()[preexisting_row_id]};
+
+      if (row == preexisting_row) {
+        cur_row = preexisting_mapping;
+      }
+    }
+    if (cur_row == -1) {
+      cur_row =
+          context_->storage->mutable_stack_profile_mappings()->Insert(row);
+    }
     mapping_idx_.emplace(row, cur_row);
   }
   mappings_.emplace(id, cur_row);
@@ -123,7 +146,11 @@
   if (it != frame_idx_.end()) {
     cur_row = it->second;
   } else {
-    cur_row = context_->storage->mutable_stack_profile_frames()->Insert(row);
+    cur_row = context_->storage->stack_profile_frames().FindFrameRow(
+        static_cast<size_t>(mapping_row), frame.rel_pc);
+    if (cur_row == -1) {
+      cur_row = context_->storage->mutable_stack_profile_frames()->Insert(row);
+    }
     frame_idx_.emplace(row, cur_row);
   }
   frames_.emplace(id, cur_row);