Skip unmodified flags in FlagSaver without allocating.

FlagImpl::SaveState() now returns nullptr for a flag that is still in its
initial state, rather than allocating a FlagState for it.  Such a flag
registers itself the first time it is modified, and FlagSaver restores the
flags that registered during its lifetime.  FlagSaver reserves space for the
registrations, so the first modification of a flag still does not allocate.
PiperOrigin-RevId: 1017933082
diff --git a/absl/flags/CMakeLists.txt b/absl/flags/CMakeLists.txt
index 57dcc50..a4f9b11 100644
--- a/absl/flags/CMakeLists.txt
+++ b/absl/flags/CMakeLists.txt
@@ -200,6 +200,7 @@
     absl::flags_commandlineflag_internal
     absl::flags_config
     absl::flags_marshalling
+    absl::flags_reflection
     absl::flat_hash_map
     absl::meta
     absl::no_destructor
diff --git a/absl/flags/commandlineflag_test.cc b/absl/flags/commandlineflag_test.cc
index 35ce567..76cf367 100644
--- a/absl/flags/commandlineflag_test.cc
+++ b/absl/flags/commandlineflag_test.cc
@@ -40,6 +40,10 @@
 ABSL_FLAG(int, int_flag2, 201, "");
 ABSL_FLAG(std::string, string_flag2, "dflt", "");
 
+// These are only modified under a FlagSaver.
+ABSL_FLAG(int, int_flag3, 301, "");
+ABSL_FLAG(std::string, string_flag3, "dflt", "");
+
 using CustomIntAlias = int;
 using CustomStringListAlias = std::vector<std::string>;
 
@@ -313,4 +317,30 @@
 #endif
 }
 
+// Checks that FlagSaver restores flags that were unmodified when it was
+// created and whose default value has been changed since.
+TEST_F(CommandLineFlagTest, TestFlagSaverRestoresChangedDefault) {
+  absl::CommandLineFlag* int_flag = absl::FindCommandLineFlag("int_flag3");
+  absl::CommandLineFlag* string_flag =
+      absl::FindCommandLineFlag("string_flag3");
+  ASSERT_NE(int_flag, nullptr);
+  ASSERT_NE(string_flag, nullptr);
+
+  {
+    absl::FlagSaver saver;
+    std::string err;
+    EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom(
+        *int_flag, "302", flags::SET_FLAGS_DEFAULT, flags::kProgrammaticChange,
+        err));
+    EXPECT_TRUE(flags::PrivateHandleAccessor::ParseFrom(
+        *string_flag, "changed", flags::SET_FLAGS_DEFAULT,
+        flags::kProgrammaticChange, err));
+    EXPECT_EQ(absl::GetFlag(FLAGS_int_flag3), 302);
+    EXPECT_EQ(absl::GetFlag(FLAGS_string_flag3), "changed");
+  }
+
+  EXPECT_EQ(absl::GetFlag(FLAGS_int_flag3), 301);
+  EXPECT_EQ(absl::GetFlag(FLAGS_string_flag3), "dflt");
+}
+
 }  // namespace
diff --git a/absl/flags/internal/flag.cc b/absl/flags/internal/flag.cc
index 4c70b7b..ca1c357 100644
--- a/absl/flags/internal/flag.cc
+++ b/absl/flags/internal/flag.cc
@@ -41,8 +41,10 @@
 #include "absl/base/optimization.h"
 #include "absl/base/thread_annotations.h"
 #include "absl/container/flat_hash_map.h"
+#include "absl/flags/commandlineflag.h"
 #include "absl/flags/config.h"
 #include "absl/flags/internal/commandlineflag.h"
+#include "absl/flags/internal/registry.h"
 #include "absl/flags/usage_config.h"
 #include "absl/memory/memory.h"
 #include "absl/strings/str_cat.h"
@@ -237,6 +239,12 @@
  private:
   friend class FlagImpl;
 
+  // Restores a flag that was unmodified when SaveState() returned nullptr.
+  static void RestoreInitialState(CommandLineFlag& flag) {
+    FlagImpl& flag_impl = static_cast<FlagImpl&>(flag);
+    FlagState(flag_impl, flag_impl.default_value_).Restore();
+  }
+
   // Restores the flag to the saved state.
   void Restore() && override {
     if (!std::move(flag_impl_).RestoreState(*this)) return;
@@ -438,6 +446,7 @@
 }
 
 void FlagImpl::StoreValue(const void* src, ValueSource source) {
+  const bool first_modification = CanSkipInitOnSave();
   switch (ValueStorageKind()) {
     case FlagValueStorageKind::kValueAndInitBit:
     case FlagValueStorageKind::kOneWordAtomic: {
@@ -475,6 +484,10 @@
       break;
   }
   RecordMutation();
+  if (first_modification) {
+    flags_internal::RegisterFirstFlagModification(
+        *this, &FlagState::RestoreInitialState);
+  }
   InvokeCallback();
 }
 
@@ -609,7 +622,8 @@
 
 std::unique_ptr<FlagStateInterface> FlagImpl::SaveState() {
   if (ABSL_PREDICT_TRUE(CanSkipInitOnSave())) {
-    return std::make_unique<FlagState>(*this, default_value_);
+    // FlagSaver restores the flag with FlagState::RestoreInitialState().
+    return nullptr;
   }
 
   absl::MutexLock l(DataGuard());
@@ -870,8 +884,13 @@
       if (s.DefaultKind() == FlagDefaultKind::kDynamicValue) {
         tentative_value.reset(old_value);
       } else {
+        const bool first_modification = CanSkipInitOnSave();
         s.default_kind = static_cast<uint8_t>(FlagDefaultKind::kDynamicValue);
         mu_state_.store(s, std::memory_order_relaxed);
+        if (first_modification) {
+          flags_internal::RegisterFirstFlagModification(
+              *this, &FlagState::RestoreInitialState);
+        }
       }
 
       if (!was_modified) {
diff --git a/absl/flags/internal/registry.h b/absl/flags/internal/registry.h
index a1f4a82..d39ccc7 100644
--- a/absl/flags/internal/registry.h
+++ b/absl/flags/internal/registry.h
@@ -43,6 +43,15 @@
 void FinalizeRegistry();
 
 //-----------------------------------------------------------------------------
+
+// A flag may return nullptr from SaveState() while it is unmodified.  Such a
+// flag calls this when it is first modified, after SaveState() has stopped
+// returning nullptr.  A FlagSaver that has not saved the flag's state then
+// restores the flag by calling `restore_initial_state(flag)`.
+void RegisterFirstFlagModification(
+    CommandLineFlag& flag, void (*restore_initial_state)(CommandLineFlag&));
+
+//-----------------------------------------------------------------------------
 // Retired registrations:
 //
 // Retired flag registrations are treated specially. A 'retired' flag is
diff --git a/absl/flags/reflection.cc b/absl/flags/reflection.cc
index 13f210c..2380e12 100644
--- a/absl/flags/reflection.cc
+++ b/absl/flags/reflection.cc
@@ -19,6 +19,7 @@
 
 #include <algorithm>
 #include <atomic>
+#include <cstddef>
 #include <cstdlib>
 #include <functional>
 #include <memory>
@@ -205,6 +206,36 @@
   return true;
 }
 
+namespace {
+
+struct FirstFlagModifications {
+  struct Entry {
+    CommandLineFlag* flag;
+    void (*restore_initial_state)(CommandLineFlag&);
+  };
+
+  absl::Mutex mu;
+  // False until the first FlagSaver.  A flag modified before then has a state
+  // to save, so it does not need an entry.
+  bool enabled ABSL_GUARDED_BY(mu) = false;
+  std::vector<Entry> entries ABSL_GUARDED_BY(mu);
+};
+
+FirstFlagModifications& GetFirstFlagModifications() {
+  static absl::NoDestructor<FirstFlagModifications> modifications;
+  return *modifications;
+}
+
+}  // namespace
+
+void RegisterFirstFlagModification(
+    CommandLineFlag& flag, void (*restore_initial_state)(CommandLineFlag&)) {
+  FirstFlagModifications& modifications = GetFirstFlagModifications();
+  absl::MutexLock l(modifications.mu);
+  if (!modifications.enabled) return;
+  modifications.entries.push_back({&flag, restore_initial_state});
+}
+
 void FinalizeRegistry() {
   auto& registry = FlagRegistry::GlobalRegistry();
   FlagRegistryLock frl(registry);
@@ -319,24 +350,63 @@
   // It's an error to call this more than once.
   void SaveFromRegistry() {
     assert(backup_registry_.empty());  // call only once!
+    FirstFlagModifications& modifications = GetFirstFlagModifications();
+    {
+      // This has to precede the calls to SaveState(), so that the entry of a
+      // flag that returns nullptr from it is at or after `first_modification_`.
+      absl::MutexLock l(modifications.mu);
+      modifications.enabled = true;
+      first_modification_ = modifications.entries.size();
+    }
+    size_t num_flags = 0;
     flags_internal::ForEachFlag([&](CommandLineFlag& flag) {
+      ++num_flags;
       if (auto flag_state =
               flags_internal::PrivateHandleAccessor::SaveState(flag)) {
-        backup_registry_.emplace_back(std::move(flag_state));
+        backup_registry_.push_back({&flag, std::move(flag_state)});
       }
     });
+    // Each flag has at most one entry.  Reserving them here keeps the first
+    // modification of a flag from allocating.
+    absl::MutexLock l(modifications.mu);
+    modifications.entries.reserve(num_flags);
   }
 
   // Restores the saved flag states into the flag registry.
   void RestoreToRegistry() && {
-    for (const auto& flag_state : backup_registry_) {
-      std::move(*flag_state).Restore();
+    // Flags that returned nullptr from SaveState() and were modified since.
+    std::vector<FirstFlagModifications::Entry> modified;
+    {
+      FirstFlagModifications& modifications = GetFirstFlagModifications();
+      absl::MutexLock l(modifications.mu);
+      modified.assign(modifications.entries.begin() +
+                          static_cast<ptrdiff_t>(first_modification_),
+                      modifications.entries.end());
+    }
+    for (const auto& entry : modified) {
+      if (std::any_of(backup_registry_.begin(), backup_registry_.end(),
+                      [&](const SavedFlag& saved) {
+                        return saved.flag == entry.flag;
+                      })) {
+        continue;
+      }
+      entry.restore_initial_state(*entry.flag);
+    }
+    for (auto& saved : backup_registry_) {
+      std::move(*saved.state).Restore();
     }
   }
 
  private:
-  std::vector<std::unique_ptr<flags_internal::FlagStateInterface>>
-      backup_registry_;
+  struct SavedFlag {
+    CommandLineFlag* flag;
+    std::unique_ptr<flags_internal::FlagStateInterface> state;
+  };
+
+  std::vector<SavedFlag> backup_registry_;
+  // Index of the first entry of FirstFlagModifications added after
+  // SaveFromRegistry().
+  size_t first_modification_ = 0;
 };
 
 }  // namespace flags_internal