D3D11: Trigger Flush in ReduceMemoryUsageImpl() to force res cleanup.

When we destroy a D3D11 resource, the D3D11 runtime actually defers
the real destruction. In order to force deleting the resource for good,
we need to call Flush.

This CL implements the ReduceMemoryUsageImpl() in DeviceD3D11 so that
when being idle:
- All pending resource deletions will be flushed.
- All driver's allocated resources will be trimmed.

Bug: chromium:402138745
Change-Id: I51544cf066302a9c51787ec141e0bc92b753fe8f
Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/241614
Reviewed-by: Corentin Wallez <cwallez@chromium.org>
Commit-Queue: Quyen Le <lehoangquyen@chromium.org>
diff --git a/src/dawn/native/d3d11/DeviceD3D11.cpp b/src/dawn/native/d3d11/DeviceD3D11.cpp
index 806cf78..32e111c 100644
--- a/src/dawn/native/d3d11/DeviceD3D11.cpp
+++ b/src/dawn/native/d3d11/DeviceD3D11.cpp
@@ -45,6 +45,7 @@
 #include "dawn/native/d3d11/BindGroupLayoutD3D11.h"
 #include "dawn/native/d3d11/BufferD3D11.h"
 #include "dawn/native/d3d11/CommandBufferD3D11.h"
+#include "dawn/native/d3d11/CommandRecordingContextD3D11.h"
 #include "dawn/native/d3d11/ComputePipelineD3D11.h"
 #include "dawn/native/d3d11/PhysicalDeviceD3D11.h"
 #include "dawn/native/d3d11/PipelineLayoutD3D11.h"
@@ -459,6 +460,23 @@
     // Nothing to do, the ComPtr will release the keyed mutex.
 }
 
+bool Device::ReduceMemoryUsageImpl() {
+    // D3D11 defers the deletion of resources until we call Flush().
+    // So trigger a Flush() here to force deleting any pending resources.
+    auto commandContext =
+        ToBackend(GetQueue())
+            ->GetScopedPendingCommandContext(ExecutionQueueBase::SubmitMode::Passive);
+    commandContext.Flush();
+
+    // Call Trim() to delete any internal resources created by the driver.
+    ComPtr<IDXGIDevice3> dxgiDevice3;
+    if (SUCCEEDED(mD3d11Device.As(&dxgiDevice3))) {
+        dxgiDevice3->Trim();
+    }
+
+    return false;
+}
+
 bool Device::MayRequireDuplicationOfIndirectParameters() const {
     return true;
 }
diff --git a/src/dawn/native/d3d11/DeviceD3D11.h b/src/dawn/native/d3d11/DeviceD3D11.h
index a0a91e2..a56d38e 100644
--- a/src/dawn/native/d3d11/DeviceD3D11.h
+++ b/src/dawn/native/d3d11/DeviceD3D11.h
@@ -84,6 +84,8 @@
 
     void DisposeKeyedMutex(ComPtr<IDXGIKeyedMutex> dxgiKeyedMutex) override;
 
+    bool ReduceMemoryUsageImpl() override;
+
     uint32_t GetUAVSlotCount() const;
 
     ResultOrError<TextureViewBase*> GetOrCreateCachedImplicitPixelLocalStorageAttachment(