Fix TSAN error in SetLabel

Move the device guard higher, to the API layer only when
UseUserDefinedLabelsInBackend is enabled, to avoid lock inversion bugs.

Bug: 479457809
Change-Id: I1f8696b5c79a8c8ebbc517d692ec72ad8cc0c211
Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/299715
Reviewed-by: Corentin Wallez <cwallez@chromium.org>
Commit-Queue: Quyen Le <lehoangquyen@chromium.org>
diff --git a/src/dawn/native/ObjectBase.cpp b/src/dawn/native/ObjectBase.cpp
index fd1c174..096ccb6 100644
--- a/src/dawn/native/ObjectBase.cpp
+++ b/src/dawn/native/ObjectBase.cpp
@@ -27,12 +27,14 @@
 
 #include "dawn/native/ObjectBase.h"
 
+#include <optional>
 #include <utility>
 #include <vector>
 
 #include "absl/strings/str_format.h"
 #include "dawn/native/Adapter.h"
 #include "dawn/native/Device.h"
+#include "dawn/native/DeviceGuard.h"
 #include "dawn/native/ObjectLabel.h"
 #include "dawn/native/ObjectType_autogen.h"
 #include "dawn/native/Toggles.h"
@@ -173,6 +175,12 @@
 }
 
 void ApiObjectBase::APISetLabel(StringView label) {
+    // TODO(crbug.com/479457809): remove this once all backends' SetLabelImpl() implementations are
+    // thread safe. We only need the device guard to protect the backend's label.
+    std::optional<DeviceGuard> deviceGuard;
+    if (GetDevice()->IsToggleEnabled(Toggle::UseUserDefinedLabelsInBackend)) {
+        deviceGuard.emplace(GetDevice()->GetGuard());
+    }
     SetLabel(std::string(utils::NormalizeMessageString(label)));
 }
 
@@ -195,9 +203,6 @@
         return;
     }
 
-    // TODO(479457809): remove this once all backends' SetLabelImpl() implementations are thread
-    // safe
-    auto deviceGuard = GetDevice()->GetGuard();
     SetLabelImpl();
 }