[subzero] Fix integer overflows during alloca coalescing

Bug: chromium:1427865,chromium:1431761,chromium:1464038,chromium:1464680
Change-Id: Ie09a9ba3709d867544ca045b066b437e2d60da51
Reviewed-on: https://swiftshader-review.googlesource.com/c/SwiftShader/+/71928
Kokoro-Result: kokoro <noreply+kokoro@google.com>
Reviewed-by: Shahbaz Youssefi <syoussefi@google.com>
Presubmit-Ready: Shahbaz Youssefi <syoussefi@google.com>
Reviewed-by: Ben Clayton <bclayton@google.com>
Tested-by: Shahbaz Youssefi <syoussefi@google.com>
Commit-Queue: Shahbaz Youssefi <syoussefi@google.com>
diff --git a/third_party/subzero/src/IceCfg.cpp b/third_party/subzero/src/IceCfg.cpp
index 570987f..43cf090 100644
--- a/third_party/subzero/src/IceCfg.cpp
+++ b/third_party/subzero/src/IceCfg.cpp
@@ -837,7 +837,16 @@
     uint32_t Alignment = std::max(Alloca->getAlignInBytes(), 1u);
     auto *ConstSize =
         llvm::dyn_cast<ConstantInteger32>(Alloca->getSizeInBytes());
-    uint32_t Size = Utils::applyAlignment(ConstSize->getValue(), Alignment);
+    const uint32_t Size =
+        Utils::applyAlignment(ConstSize->getValue(), Alignment);
+
+    // Ensure that the Size does not exceed StackSizeLimit which can lead to
+    // undefined behavior below.
+    if (Size > StackSizeLimit) {
+      llvm::report_fatal_error("Local variable exceeds stack size limit");
+      return; // NOTREACHED
+    }
+
     if (BaseVariableType == BVT_FramePointer) {
       // Addressing is relative to the frame pointer.  Subtract the offset after
       // adding the size of the alloca, because it grows downwards from the
@@ -855,6 +864,14 @@
               : 0;
       Offsets.push_back(CurrentOffset + OutArgsOffsetOrZero);
     }
+
+    // Ensure that the addition below does not overflow or exceed
+    // StackSizeLimit as this leads to undefined behavior.
+    if (CurrentOffset + Size > StackSizeLimit) {
+      llvm::report_fatal_error("Local variable exceeds stack size limit");
+      return; // NOTREACHED
+    }
+
     // Update the running offset of the fused alloca region.
     CurrentOffset += Size;
   }