https://github.com/Harald-R created 
https://github.com/llvm/llvm-project/pull/206484

Applies the fixes suggested by the `bugprone-container-bounds-check-overflow` 
check over the `llvm`, `clang`, `clang-extra-tools` and `mlir` subprojects.

A couple of the fixes also now raised build warnings for comparison of integers 
of different signs. This is for existing code which mixed signed and unsigned 
elements for the addition. With the check's fix applied, the signed elements 
are now part of the comparsion, which results in the build warnings. The second 
commit in the PR adapt the code to avoid the warnings.

>From cda8752bf1939465d351b4968cf5d6870db1f7b9 Mon Sep 17 00:00:00 2001
From: Harald-R <[email protected]>
Date: Mon, 29 Jun 2026 15:54:31 +0300
Subject: [PATCH 1/2] Fix all matches from
 bugprone-container-bounds-check-overflow

---
 clang-tools-extra/clang-doc/BitcodeReader.cpp |  2 +-
 .../clang-tidy/bugprone/BranchCloneCheck.cpp  |  2 +-
 .../objc/PropertyDeclarationCheck.cpp         |  3 +-
 .../utils/FormatStringConverter.cpp           |  3 +-
 clang-tools-extra/clangd/ProjectModules.cpp   |  6 ++--
 .../clangd/SystemIncludeExtractor.cpp         | 14 ++++-----
 .../clangd/unittests/tweaks/TweakTesting.cpp  |  3 +-
 .../PrintFunctionNames/PrintFunctionNames.cpp |  2 +-
 clang/lib/AST/ByteCode/Interp.cpp             |  3 +-
 clang/lib/AST/ExprConstant.cpp                |  8 +++--
 .../FlowSensitive/DataflowAnalysisContext.cpp |  2 +-
 .../FlowSensitive/WatchedLiteralsSolver.cpp   |  2 +-
 clang/lib/Driver/OffloadBundler.cpp           | 12 ++++----
 clang/lib/Driver/ToolChains/AIX.cpp           |  2 +-
 clang/lib/Driver/ToolChains/Clang.cpp         |  2 +-
 clang/lib/Format/BreakableToken.cpp           |  6 ++--
 clang/lib/Format/DefinitionBlockSeparator.cpp |  7 +++--
 clang/lib/Format/Format.cpp                   |  4 +--
 clang/lib/Format/MacroExpander.cpp            |  2 +-
 .../lib/Format/NamespaceEndCommentsFixer.cpp  |  4 +--
 clang/lib/Format/SortJavaScriptImports.cpp    |  2 +-
 clang/lib/Lex/PPCaching.cpp                   |  4 ++-
 clang/lib/Tooling/ArgumentsAdjusters.cpp      |  2 +-
 clang/unittests/AST/RandstructTest.cpp        |  2 +-
 .../TableGen/ClangDiagnosticsEmitter.cpp      |  2 +-
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp     | 13 ++++----
 llvm/lib/CAS/OnDiskDataAllocator.cpp          |  3 +-
 llvm/lib/CAS/OnDiskGraphDB.cpp                | 11 ++++---
 llvm/lib/CAS/OnDiskTrieRawHashMap.cpp         | 12 ++++----
 .../GlobalISel/LegacyLegalizerInfo.cpp        |  3 +-
 .../CodeGen/GlobalISel/LegalizerHelper.cpp    |  4 ++-
 llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp |  6 ++--
 llvm/lib/DebugInfo/DWARF/DWARFContext.cpp     |  2 +-
 llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp        |  6 ++--
 llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp    |  3 +-
 llvm/lib/DebugInfo/GSYM/GsymReader.cpp        |  9 +++---
 llvm/lib/DebugInfo/GSYM/GsymReaderV2.cpp      |  2 +-
 llvm/lib/ExecutionEngine/JITLink/COFF.cpp     |  6 ++--
 .../JITLink/MachOLinkGraphBuilder.cpp         |  3 +-
 llvm/lib/MC/MCAsmStreamer.cpp                 |  3 +-
 llvm/lib/MC/XCOFFObjectWriter.cpp             |  2 +-
 llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp           |  4 +--
 llvm/lib/Object/COFFObjectFile.cpp            |  5 ++--
 llvm/lib/Object/DXContainer.cpp               |  2 +-
 llvm/lib/Object/MachOObjectFile.cpp           |  3 +-
 llvm/lib/Object/Minidump.cpp                  |  7 +++--
 .../Coverage/CoverageMappingReader.cpp        |  2 +-
 llvm/lib/Support/CommandLine.cpp              |  2 +-
 llvm/lib/Support/RewriteBuffer.cpp            |  3 +-
 llvm/lib/Support/Unicode.cpp                  |  2 +-
 .../AMDGPU/R600ControlFlowFinalizer.cpp       |  4 +--
 llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp   |  2 +-
 .../X86/Disassembler/X86Disassembler.cpp      |  2 +-
 .../X86/MCTargetDesc/X86MCTargetDesc.cpp      |  6 ++--
 llvm/lib/Transforms/IPO/InstrumentorUtils.cpp | 30 ++++++++++++-------
 .../IPO/MemProfContextDisambiguation.cpp      |  3 +-
 .../InstCombine/InstCombineCalls.cpp          |  3 +-
 .../InstCombine/InstructionCombining.cpp      |  2 +-
 .../lib/Transforms/Scalar/LoopPassManager.cpp |  2 +-
 llvm/lib/Transforms/Scalar/SROA.cpp           |  2 +-
 .../Transforms/Vectorize/SLPVectorizer.cpp    | 11 +++----
 .../Passes/SeedCollection.cpp                 |  2 +-
 llvm/tools/llvm-cas-fuzzer/cas-fuzzer.cpp     | 14 +++++----
 llvm/tools/llvm-objdump/COFFDump.cpp          |  3 +-
 llvm/tools/llvm-objdump/MachODump.cpp         |  4 +--
 llvm/tools/llvm-objdump/llvm-objdump.cpp      | 14 ++++-----
 llvm/tools/llvm-profgen/ProfiledBinary.cpp    |  5 ++--
 llvm/tools/llvm-rc/ResourceFileWriter.cpp     |  3 +-
 llvm/tools/llvm-readobj/ARMWinEHPrinter.cpp   |  2 +-
 llvm/unittests/Support/AddressRangeTest.cpp   |  9 ++++--
 .../TableGen/Common/CodeGenRegisters.cpp      |  3 +-
 llvm/utils/TableGen/SubtargetEmitter.cpp      |  6 ++--
 mlir/lib/AsmParser/Parser.cpp                 |  2 +-
 mlir/lib/AsmParser/Token.cpp                  |  6 ++--
 mlir/lib/Bytecode/Reader/BytecodeReader.cpp   |  3 +-
 mlir/lib/Dialect/Affine/Analysis/Utils.cpp    |  3 +-
 mlir/lib/Dialect/Affine/IR/AffineOps.cpp      |  3 +-
 .../Transforms/SimplifyAffineWithBounds.cpp   |  3 +-
 .../LLVMIR/IR/BasicPtxBuilderInterface.cpp    |  2 +-
 .../Linalg/Transforms/ElementwiseOpFusion.cpp |  5 ++--
 .../OpenACC/Utils/OpenACCUtilsTiling.cpp      |  2 +-
 mlir/lib/Dialect/SPIRV/IR/ImageOps.cpp        |  6 ++--
 .../Transforms/SPIRVWebGPUTransforms.cpp      |  2 +-
 mlir/lib/Dialect/Shard/IR/ShardOps.cpp        |  3 +-
 mlir/lib/IR/Remarks.cpp                       |  2 +-
 mlir/lib/Tools/PDLL/Parser/Lexer.cpp          |  6 ++--
 .../tools/mlir-tblgen/AttrOrTypeFormatGen.cpp |  4 +--
 .../Dialect/SPIRV/SerializationTest.cpp       |  7 +++--
 88 files changed, 242 insertions(+), 168 deletions(-)

diff --git a/clang-tools-extra/clang-doc/BitcodeReader.cpp 
b/clang-tools-extra/clang-doc/BitcodeReader.cpp
index 3299dedfbc3e4..458c57ef6b518 100644
--- a/clang-tools-extra/clang-doc/BitcodeReader.cpp
+++ b/clang-tools-extra/clang-doc/BitcodeReader.cpp
@@ -43,7 +43,7 @@ static llvm::Error decodeRecord(const Record &R, SymbolID 
&Field,
   if (R[0] != BitCodeConstants::USRHashSize)
     return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                    "incorrect USR size");
-  if (R.size() < R[0] + 1)
+  if (R.size() < R[0] || R.size() - R[0] < 1)
     return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                    "record too short for SymbolID");
 
diff --git a/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
index 588f9bfe076df..389c40dd350d4 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp
@@ -328,7 +328,7 @@ void BranchCloneCheck::check(const MatchFinder::MatchResult 
&Result) {
     const size_t N = Branches.size();
     llvm::BitVector KnownAsClone(N);
 
-    for (size_t I = 0; I + 1 < N; I++) {
+    for (size_t I = 0; (I < N && 1 < N - I); I++) {
       // We have already seen Branches[i] as a clone of an earlier branch.
       if (KnownAsClone[I])
         continue;
diff --git a/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp 
b/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp
index 0080a389ce9cb..9e0a6a4b161aa 100644
--- a/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp
+++ b/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp
@@ -86,7 +86,8 @@ static bool hasCategoryPropertyPrefix(StringRef PropertyName) 
{
 
 static bool prefixedPropertyNameValid(StringRef PropertyName) {
   const size_t Start = PropertyName.find_first_of('_');
-  assert(Start != StringRef::npos && Start + 1 < PropertyName.size());
+  assert(Start != StringRef::npos &&
+         (Start < PropertyName.size() && 1 < PropertyName.size() - Start));
   auto Prefix = PropertyName.substr(0, Start);
   if (Prefix.lower() != Prefix)
     return false;
diff --git a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp 
b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
index 98709e924a7a1..236a084d43575 100644
--- a/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
+++ b/clang-tools-extra/clang-tidy/utils/FormatStringConverter.cpp
@@ -623,7 +623,8 @@ bool FormatStringConverter::HandlePrintfSpecifier(const 
PrintfSpecifier &FS,
                                                   unsigned SpecifierLen,
                                                   const TargetInfo &Target) {
   const size_t StartSpecifierPos = StartSpecifier - PrintfFormatString.data();
-  assert(StartSpecifierPos + SpecifierLen <= PrintfFormatString.size());
+  assert((StartSpecifierPos <= PrintfFormatString.size() &&
+          SpecifierLen <= PrintfFormatString.size() - StartSpecifierPos));
 
   // Everything before the specifier needs copying verbatim
   assert(StartSpecifierPos >= PrintfFormatStringPos);
diff --git a/clang-tools-extra/clangd/ProjectModules.cpp 
b/clang-tools-extra/clangd/ProjectModules.cpp
index 33cbc715e9659..f833be69fc5bf 100644
--- a/clang-tools-extra/clangd/ProjectModules.cpp
+++ b/clang-tools-extra/clangd/ProjectModules.cpp
@@ -81,12 +81,14 @@ parseCompileCommandInfo(tooling::CompileCommand Cmd, const 
ThreadsafeFS &TFS) {
       Result.OutputModuleFile = normalizePath(Arg, Cmd.Directory);
       continue;
     }
-    if (Arg == "-fmodule-output" && I + 1 < Cmd.CommandLine.size()) {
+    if (Arg == "-fmodule-output" &&
+        (I < Cmd.CommandLine.size() && 1 < Cmd.CommandLine.size() - I)) {
       Result.OutputModuleFile =
           normalizePath(Cmd.CommandLine[++I], Cmd.Directory);
       continue;
     }
-    if (SawPrecompile && Arg == "-o" && I + 1 < Cmd.CommandLine.size()) {
+    if (SawPrecompile && Arg == "-o" &&
+        (I < Cmd.CommandLine.size() && 1 < Cmd.CommandLine.size() - I)) {
       Result.OutputModuleFile =
           normalizePath(Cmd.CommandLine[++I], Cmd.Directory);
       continue;
diff --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index 22237863ff041..ba4a24cde76fd 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -114,7 +114,7 @@ struct DriverArgs {
 
       // Look for Language related flags.
       if (Arg.consume_front("-x")) {
-        if (Arg.empty() && I + 1 < E)
+        if (Arg.empty() && (I < E && 1 < E - I))
           Lang = Cmd.CommandLine[I + 1];
         else
           Lang = Arg.str();
@@ -128,22 +128,22 @@ struct DriverArgs {
       else if (Arg.consume_front("--sysroot")) {
         if (Arg.consume_front("="))
           Sysroot = Arg.str();
-        else if (Arg.empty() && I + 1 < E)
+        else if (Arg.empty() && (I < E && 1 < E - I))
           Sysroot = Cmd.CommandLine[I + 1];
       } else if (Arg.consume_front("-isysroot")) {
-        if (Arg.empty() && I + 1 < E)
+        if (Arg.empty() && (I < E && 1 < E - I))
           ISysroot = Cmd.CommandLine[I + 1];
         else
           ISysroot = Arg.str();
       } else if (Arg.consume_front("--target=")) {
         Target = Arg.str();
       } else if (Arg.consume_front("-target")) {
-        if (Arg.empty() && I + 1 < E)
+        if (Arg.empty() && (I < E && 1 < E - I))
           Target = Cmd.CommandLine[I + 1];
       } else if (Arg.consume_front("--stdlib")) {
         if (Arg.consume_front("="))
           Stdlib = Arg.str();
-        else if (Arg.empty() && I + 1 < E)
+        else if (Arg.empty() && (I < E && 1 < E - I))
           Stdlib = Cmd.CommandLine[I + 1];
       } else if (Arg.consume_front("-stdlib=")) {
         Stdlib = Arg.str();
@@ -155,7 +155,7 @@ struct DriverArgs {
         Specs.push_back(Arg.str());
       } else if (Arg.starts_with("--specs=")) {
         Specs.push_back(Arg.str());
-      } else if (Arg == "--specs" && I + 1 < E) {
+      } else if (Arg == "--specs" && (I < E && 1 < E - I)) {
         Specs.push_back(Arg.str());
         Specs.push_back(Cmd.CommandLine[I + 1]);
       }
@@ -462,7 +462,7 @@ std::string convertGlobToRegex(llvm::StringRef Glob) {
   RegStream << '^';
   for (size_t I = 0, E = Glob.size(); I < E; ++I) {
     if (Glob[I] == '*') {
-      if (I + 1 < E && Glob[I + 1] == '*') {
+      if ((I < E && 1 < E - I) && Glob[I + 1] == '*') {
         // Double star, accept any sequence.
         RegStream << ".*";
         // Also skip the second star.
diff --git a/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp
index c26fc21d7a01c..6205508582bef 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/TweakTesting.cpp
@@ -44,7 +44,8 @@ llvm::StringRef unwrap(Context Ctx, llvm::StringRef Outer) {
   // Unwrap only if the code matches the expected wrapping.
   // Don't allow the begin/end wrapping to overlap!
   if (Outer.starts_with(Wrapping.first) && Outer.ends_with(Wrapping.second) &&
-      Outer.size() >= Wrapping.first.size() + Wrapping.second.size())
+      (Outer.size() >= Wrapping.first.size() &&
+       Outer.size() - Wrapping.first.size() >= Wrapping.second.size()))
     return Outer.drop_front(Wrapping.first.size())
         .drop_back(Wrapping.second.size());
   return Outer;
diff --git a/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp 
b/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp
index b2b785b87c25c..7587d84caaf8f 100644
--- a/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp
+++ b/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp
@@ -97,7 +97,7 @@ class PrintFunctionNamesAction : public PluginASTAction {
         D.Report(DiagID) << args[i];
         return false;
       } else if (args[i] == "-parse-template") {
-        if (i + 1 >= e) {
+        if (i >= e || 1 >= e - i) {
           D.Report(D.getCustomDiagID(DiagnosticsEngine::Error,
                                      "missing -parse-template argument"));
           return false;
diff --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 2f09c19178f09..42e1b1c6cc67b 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -2810,7 +2810,8 @@ bool arePotentiallyOverlappingStringLiterals(const 
Pointer &LHS,
   // manually. If the longer string doesn't have a null terminator where the
   // shorter string ends, they aren't potentially overlapping.
   for (unsigned NullByte : llvm::seq(ShorterCharWidth)) {
-    if (Shorter.size() + NullByte >= Longer.size())
+    if (Shorter.size() >= Longer.size() ||
+        NullByte >= Longer.size() - Shorter.size())
       break;
     if (Longer[Shorter.size() + NullByte])
       return false;
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 1d359339b9104..5fdcc36d99c9e 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2094,7 +2094,8 @@ static bool ArePotentiallyOverlappingStringLiterals(const 
EvalInfo &Info,
   // manually. If the longer string doesn't have a null terminator where the
   // shorter string ends, they aren't potentially overlapping.
   for (int NullByte : llvm::seq(ShorterCharWidth)) {
-    if (Shorter.size() + NullByte >= Longer.size())
+    if (Shorter.size() >= Longer.size() ||
+        NullByte >= Longer.size() - Shorter.size())
       break;
     if (Longer[Shorter.size() + NullByte])
       return false;
@@ -5305,8 +5306,9 @@ static const ValueDecl 
*HandleMemberPointerAccess(EvalInfo &Info,
     // C++23 [expr.mptr.oper]p4:
     //   If the result of E1 is an object [...] whose most derived object does
     //   not contain the member to which E2 refers, the behavior is undefined.
-    if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
-        LV.Designator.Entries.size()) {
+    if (LV.Designator.MostDerivedPathLength > LV.Designator.Entries.size() ||
+        MemPtr.Path.size() > LV.Designator.Entries.size() -
+                                 LV.Designator.MostDerivedPathLength) {
       Info.FFDiag(RHS);
       return nullptr;
     }
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
index bad91eff61769..29c28c1a451d2 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
@@ -347,7 +347,7 @@ static void printAtomList(const llvm::SmallVector<Atom> 
&Atoms,
   OS << "(";
   for (size_t i = 0; i < Atoms.size(); ++i) {
     OS << Atoms[i];
-    if (i + 1 < Atoms.size())
+    if (i < Atoms.size() && 1 < Atoms.size() - i)
       OS << ", ";
   }
   OS << ")\n";
diff --git a/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp 
b/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
index 98109faff222a..b9b71668f795f 100644
--- a/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
+++ b/clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
@@ -206,7 +206,7 @@ class WatchedLiteralsSolverImpl {
 
         // Remove the variable that was just assigned from the set of active
         // variables.
-        if (I + 1 < ActiveVars.size()) {
+        if (I < ActiveVars.size() && 1 < ActiveVars.size() - I) {
           // Replace the variable that was just assigned with the last active
           // variable for efficient removal.
           ActiveVars[I] = ActiveVars.back();
diff --git a/clang/lib/Driver/OffloadBundler.cpp 
b/clang/lib/Driver/OffloadBundler.cpp
index 70b5668c35a30..7b5d1fe6bd237 100644
--- a/clang/lib/Driver/OffloadBundler.cpp
+++ b/clang/lib/Driver/OffloadBundler.cpp
@@ -382,7 +382,7 @@ class BinaryFileHandler final : public FileHandler {
       return Error::success();
 
     // Read number of bundles.
-    if (ReadChars + 8 > FC.size())
+    if (ReadChars > FC.size() || 8 > FC.size() - ReadChars)
       return Error::success();
 
     uint64_t NumberOfBundles = Read8byteIntegerFromBuffer(FC, ReadChars);
@@ -392,35 +392,35 @@ class BinaryFileHandler final : public FileHandler {
     for (uint64_t i = 0; i < NumberOfBundles; ++i) {
 
       // Read offset.
-      if (ReadChars + 8 > FC.size())
+      if (ReadChars > FC.size() || 8 > FC.size() - ReadChars)
         return Error::success();
 
       uint64_t Offset = Read8byteIntegerFromBuffer(FC, ReadChars);
       ReadChars += 8;
 
       // Read size.
-      if (ReadChars + 8 > FC.size())
+      if (ReadChars > FC.size() || 8 > FC.size() - ReadChars)
         return Error::success();
 
       uint64_t Size = Read8byteIntegerFromBuffer(FC, ReadChars);
       ReadChars += 8;
 
       // Read triple size.
-      if (ReadChars + 8 > FC.size())
+      if (ReadChars > FC.size() || 8 > FC.size() - ReadChars)
         return Error::success();
 
       uint64_t TripleSize = Read8byteIntegerFromBuffer(FC, ReadChars);
       ReadChars += 8;
 
       // Read triple.
-      if (ReadChars + TripleSize > FC.size())
+      if (ReadChars > FC.size() || TripleSize > FC.size() - ReadChars)
         return Error::success();
 
       StringRef Triple(&FC.data()[ReadChars], TripleSize);
       ReadChars += TripleSize;
 
       // Check if the offset and size make sense.
-      if (!Offset || Offset + Size > FC.size())
+      if (!Offset || (Offset > FC.size() || Size > FC.size() - Offset))
         return Error::success();
 
       BundlesInfo[Triple] = BinaryBundleInfo(Size, Offset);
diff --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index 586bc08067eff..a4e1b459a3f31 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -95,7 +95,7 @@ static bool hasExportListLinkerOpts(const ArgStringList 
&CmdArgs) {
       return true;
 
     // If we split -b option, check the next opt.
-    if (ArgString == "-b" && i + 1 < Size) {
+    if (ArgString == "-b" && (i < Size && 1 < Size - i)) {
       ++i;
       llvm::StringRef ArgNextString(CmdArgs[i]);
       if (ArgNextString.starts_with("E:") ||
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index a3a3954bc464e..256ca68ec7960 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -8725,7 +8725,7 @@ ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
 }
 
 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
-  bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
+  bool HaveDash = ((I < EH.size() && 1 < EH.size() - I) && EH[I + 1] == '-');
   I += HaveDash;
   return !HaveDash;
 }
diff --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index 9571a64797a2d..a576e45e5fc47 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -82,7 +82,8 @@ getCommentSplit(StringRef Text, unsigned ContentStartColumn,
   if (Style.isJavaScript()) {
     StringRef::size_type SpaceOffset =
         Text.find_first_of(Blanks, MaxSplitBytes);
-    if (SpaceOffset != StringRef::npos && SpaceOffset + 1 < Text.size() &&
+    if (SpaceOffset != StringRef::npos &&
+        (SpaceOffset < Text.size() && 1 < Text.size() - SpaceOffset) &&
         Text[SpaceOffset + 1] == '{') {
       MaxSplitBytes = SpaceOffset + 1;
     }
@@ -115,7 +116,8 @@ getCommentSplit(StringRef Text, unsigned ContentStartColumn,
     }
 
     // Avoid ever breaking before a @tag or a { in JavaScript.
-    if (Style.isJavaScript() && SpaceOffset + 1 < Text.size() &&
+    if (Style.isJavaScript() &&
+        (SpaceOffset < Text.size() && 1 < Text.size() - SpaceOffset) &&
         (Text[SpaceOffset + 1] == '{' || Text[SpaceOffset + 1] == '@')) {
       SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
       continue;
diff --git a/clang/lib/Format/DefinitionBlockSeparator.cpp 
b/clang/lib/Format/DefinitionBlockSeparator.cpp
index 6b52b1fc0deff..a1d059c4da75f 100644
--- a/clang/lib/Format/DefinitionBlockSeparator.cpp
+++ b/clang/lib/Format/DefinitionBlockSeparator.cpp
@@ -152,7 +152,9 @@ void DefinitionBlockSeparator::separateBlocks(
         return false;
 
       const auto *NextLine =
-          OperateIndex + 1 < Lines.size() ? Lines[OperateIndex + 1] : nullptr;
+          (OperateIndex < Lines.size() && 1 < Lines.size() - OperateIndex)
+              ? Lines[OperateIndex + 1]
+              : nullptr;
 
       if (const auto *Tok = OperateLine->First;
           Tok->is(tok::comment) && !isClangFormatOn(Tok->TokenText)) {
@@ -248,7 +250,8 @@ void DefinitionBlockSeparator::separateBlocks(
       // definition.
       if (!TargetToken->closesScope() && !IsPPConditional(OpeningLineIndex)) {
         // Check whether current line may precede a definition line.
-        while (OpeningLineIndex + 1 < Lines.size() &&
+        while ((OpeningLineIndex < Lines.size() &&
+                1 < Lines.size() - OpeningLineIndex) &&
                MayPrecedeDefinition(/*Direction=*/0)) {
           ++OpeningLineIndex;
         }
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index ecfe5d2ce60d0..6761711c84555 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2917,7 +2917,7 @@ class JavaScriptRequoter : public TokenAnalyzer {
         for (size_t i = 1; i < Input.size() - 1; i++) {
           switch (Input[i]) {
           case '\\':
-            if (!Escaped && i + 1 < Input.size() &&
+            if (!Escaped && (i < Input.size() && 1 < Input.size() - i) &&
                 ((IsSingle && Input[i + 1] == '"') ||
                  (!IsSingle && Input[i + 1] == '\''))) {
               // Remove this \, it's escaping a " or ' that no longer needs
@@ -4371,7 +4371,7 @@ reformat(const FormatStyle &Style, StringRef Code,
     if (NewCode) {
       Fixes = Fixes.merge(PassFixes.first);
       Penalty += PassFixes.second;
-      if (I + 1 < E) {
+      if (I < E && 1 < E - I) {
         CurrentCode = std::move(*NewCode);
         Env = Environment::make(
             *CurrentCode, FileName,
diff --git a/clang/lib/Format/MacroExpander.cpp 
b/clang/lib/Format/MacroExpander.cpp
index 445e17358844d..1bc343406b42d 100644
--- a/clang/lib/Format/MacroExpander.cpp
+++ b/clang/lib/Format/MacroExpander.cpp
@@ -103,7 +103,7 @@ class MacroExpander::DefinitionParser {
   }
 
   void nextToken() {
-    if (Pos + 1 < Tokens.size())
+    if (Pos < Tokens.size() && 1 < Tokens.size() - Pos)
       ++Pos;
     Current = Tokens[Pos];
     Current->Finalized = true;
diff --git a/clang/lib/Format/NamespaceEndCommentsFixer.cpp 
b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
index 95ccfac5e6e61..3387fa29dc548 100644
--- a/clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -325,7 +325,7 @@ std::pair<tooling::Replacements, unsigned> 
NamespaceEndCommentsFixer::analyze(
     if (Style.CompactNamespaces) {
       if (CompactedNamespacesCount == 0)
         NamespaceTokenText = NamespaceTok->TokenText;
-      if ((I + 1 < E) &&
+      if ((I < E && 1 < E - I) &&
           NamespaceTokenText ==
               getNamespaceTokenText(AnnotatedLines[I + 1], AnnotatedLines) &&
           StartLineIndex - CompactedNamespacesCount - 1 ==
@@ -350,7 +350,7 @@ std::pair<tooling::Replacements, unsigned> 
NamespaceEndCommentsFixer::analyze(
     const FormatToken *EndCommentNextTok = EndCommentPrevTok->Next;
     if (EndCommentNextTok && EndCommentNextTok->is(tok::comment))
       EndCommentNextTok = EndCommentNextTok->Next;
-    if (!EndCommentNextTok && I + 1 < E)
+    if (!EndCommentNextTok && (I < E && 1 < E - I))
       EndCommentNextTok = AnnotatedLines[I + 1]->First;
     bool AddNewline = EndCommentNextTok &&
                       EndCommentNextTok->NewlinesBefore == 0 &&
diff --git a/clang/lib/Format/SortJavaScriptImports.cpp 
b/clang/lib/Format/SortJavaScriptImports.cpp
index a403a4fed664c..30ba84038930e 100644
--- a/clang/lib/Format/SortJavaScriptImports.cpp
+++ b/clang/lib/Format/SortJavaScriptImports.cpp
@@ -162,7 +162,7 @@ class JavaScriptImportSorter : public TokenAnalyzer {
     for (unsigned I = 0, E = References.size(); I != E; ++I) {
       JsModuleReference Reference = References[I];
       appendReference(ReferencesText, Reference);
-      if (I + 1 < E) {
+      if (I < E && 1 < E - I) {
         // Insert breaks between imports and exports.
         ReferencesText += "\n";
         // Separate imports groups with two line breaks, but keep all exports
diff --git a/clang/lib/Lex/PPCaching.cpp b/clang/lib/Lex/PPCaching.cpp
index 3f0ebd8455685..fffc0f59e6c14 100644
--- a/clang/lib/Lex/PPCaching.cpp
+++ b/clang/lib/Lex/PPCaching.cpp
@@ -131,7 +131,9 @@ void Preprocessor::EnterCachingLexModeUnchecked() {
 
 
 const Token &Preprocessor::PeekAhead(unsigned N) {
-  assert(CachedLexPos + N > CachedTokens.size() && "Confused caching.");
+  assert((CachedLexPos > CachedTokens.size() ||
+          N > CachedTokens.size() - CachedLexPos) &&
+         "Confused caching.");
   ExitCachingLexMode();
   for (size_t C = CachedLexPos + N - CachedTokens.size(); C > 0; --C) {
     CachedTokens.push_back(Token());
diff --git a/clang/lib/Tooling/ArgumentsAdjusters.cpp 
b/clang/lib/Tooling/ArgumentsAdjusters.cpp
index 999fa790124cb..e27567ea90c89 100644
--- a/clang/lib/Tooling/ArgumentsAdjusters.cpp
+++ b/clang/lib/Tooling/ArgumentsAdjusters.cpp
@@ -157,7 +157,7 @@ ArgumentsAdjuster getStripPluginsAdjuster() {
       // plugin arguments are in the form:
       // -Xclang {-load, -plugin, -plugin-arg-<plugin-name>, -add-plugin}
       // -Xclang <arbitrary-argument>
-      if (I + 4 < E && Args[I] == "-Xclang" &&
+      if ((I < E && 4 < E - I) && Args[I] == "-Xclang" &&
           (Args[I + 1] == "-load" || Args[I + 1] == "-plugin" ||
            llvm::StringRef(Args[I + 1]).starts_with("-plugin-arg-") ||
            Args[I + 1] == "-add-plugin") &&
diff --git a/clang/unittests/AST/RandstructTest.cpp 
b/clang/unittests/AST/RandstructTest.cpp
index a90665b2c0631..d68ccd3eefca9 100644
--- a/clang/unittests/AST/RandstructTest.cpp
+++ b/clang/unittests/AST/RandstructTest.cpp
@@ -64,7 +64,7 @@ static bool isSubsequence(const field_names &Seq, const 
field_names &Subseq) {
   for (unsigned I = 0; I < SeqLen; ++I)
     if (Seq[I] == Subseq[0]) {
       IsSubseq = true;
-      for (unsigned J = 0; J + I < SeqLen && J < SubLen; ++J) {
+      for (unsigned J = 0; (J < SeqLen && I < SeqLen - J) && J < SubLen; ++J) {
         if (Seq[J + I] != Subseq[J]) {
           IsSubseq = false;
           break;
diff --git a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp 
b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
index ba10be060c20a..526819264c35f 100644
--- a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
+++ b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
@@ -849,7 +849,7 @@ struct DiagTextDocPrinter : 
DiagTextVisitor<DiagTextDocPrinter> {
       const char *Separator = (Lines.size() > 1 || HasMultipleLines) ? "|" : 
"";
       HasMultipleLines = Lines.size() > 1;
 
-      if (Start + Lines.size() > RST.size())
+      if (Start > RST.size() || Lines.size() > RST.size() - Start)
         RST.resize(Start + Lines.size(), EmptyLinePrefix);
 
       padToSameLength(Lines.begin(), Lines.end());
diff --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp 
b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
index f6366061c9b52..d937ee2900203 100644
--- a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -483,7 +483,7 @@ BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> 
Record) {
   if (!UseStrtab)
     return {"", Record};
   // Invalid reference. Let the caller complain about the record being empty.
-  if (Record[0] + Record[1] > Strtab.size())
+  if (Record[0] > Strtab.size() || Record[1] > Strtab.size() - Record[0])
     return {"", {}};
   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
 }
@@ -2540,7 +2540,7 @@ Error BitcodeReader::parseAttributeGroupBlock() {
             return error("Not a constant range list attribute");
 
           SmallVector<ConstantRange, 2> Val;
-          if (i + 2 > e)
+          if (i > e || 2 > e - i)
             return error("Too few records for constant range list");
           unsigned RangeSize = Record[i++];
           unsigned BitWidth = Record[i++];
@@ -4447,7 +4447,8 @@ Error 
BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
   // Check whether we have enough values to read a partition name. Also make
   // sure Strtab has enough values.
   if (Record.size() > 18 && Strtab.data() &&
-      Record[17] + Record[18] <= Strtab.size()) {
+      (Record[17] <= Strtab.size() &&
+       Record[18] <= Strtab.size() - Record[17])) {
     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
   }
 
@@ -4549,7 +4550,8 @@ Error BitcodeReader::parseGlobalIndirectSymbolRecord(
   // Check whether we have enough values to read a partition name.
   if (OpNum + 1 < Record.size()) {
     // Check Strtab has enough values for the partition.
-    if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
+    if (Record[OpNum] > Strtab.size() ||
+        Record[OpNum + 1] > Strtab.size() - Record[OpNum])
       return error("Malformed partition, too large.");
     NewGA->setPartition(
         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
@@ -8584,7 +8586,8 @@ llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
     // We may be consuming bitcode from a client that leaves garbage at the end
     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
     // the end that there cannot possibly be another module, stop looking.
-    if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
+    if ((BCBegin >= Stream.getBitcodeBytes().size() ||
+         8 >= Stream.getBitcodeBytes().size() - BCBegin))
       return F;
 
     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
diff --git a/llvm/lib/CAS/OnDiskDataAllocator.cpp 
b/llvm/lib/CAS/OnDiskDataAllocator.cpp
index 5f646ac74a2e6..561c4d443b80a 100644
--- a/llvm/lib/CAS/OnDiskDataAllocator.cpp
+++ b/llvm/lib/CAS/OnDiskDataAllocator.cpp
@@ -181,7 +181,8 @@ Expected<ArrayRef<char>> 
OnDiskDataAllocator::get(FileOffset Offset,
                                                   size_t Size) const {
   assert(Offset);
   assert(Impl);
-  if (Offset.get() + Size >= Impl->File.getAlloc().size())
+  if (Offset.get() >= Impl->File.getAlloc().size() ||
+      Size >= Impl->File.getAlloc().size() - Offset.get())
     return createStringError(make_error_code(std::errc::protocol_error),
                              "requested size too large in allocator");
   return ArrayRef<char>{Impl->File.getRegion().data() + Offset.get(), Size};
diff --git a/llvm/lib/CAS/OnDiskGraphDB.cpp b/llvm/lib/CAS/OnDiskGraphDB.cpp
index c38dd9151bc08..cab359ef6a19a 100644
--- a/llvm/lib/CAS/OnDiskGraphDB.cpp
+++ b/llvm/lib/CAS/OnDiskGraphDB.cpp
@@ -652,7 +652,8 @@ DataRecordHandle::getFromDataPool(const OnDiskDataAllocator 
&Pool,
     return HeaderData.takeError();
 
   auto Record = DataRecordHandle::get(HeaderData->data());
-  if (Record.getTotalSize() + Offset.get() > Pool.size())
+  if (Record.getTotalSize() > Pool.size() ||
+      Offset.get() > Pool.size() - Record.getTotalSize())
     return createStringError(
         make_error_code(std::errc::illegal_byte_sequence),
         "data record span passed the end of the data pool");
@@ -959,8 +960,9 @@ Error OnDiskGraphDB::validate(bool Deep, HashingFuncT 
Hasher) const {
     case TrieRecord::StorageKind::DataPool: {
       // Check offset is a postive value, and large enough to hold the
       // header for the data record.
-      if (D.Offset.get() <= 0 ||
-          D.Offset.get() + sizeof(DataRecordHandle::Header) >= DataPool.size())
+      if (D.Offset.get() <= 0 || (D.Offset.get() >= DataPool.size() ||
+                                  sizeof(DataRecordHandle::Header) >=
+                                      DataPool.size() - D.Offset.get()))
         return formatError("datapool record out of bound");
 
       // DataRecord start needs to be aligned.
@@ -1897,7 +1899,8 @@ Error OnDiskGraphDB::importFullTree(ObjectID PrimaryID,
 
       // The bottom of \p PrimaryNodesStack contains the primary ID for the
       // current node plus the list of imported referenced IDs.
-      assert(PrimaryNodesStack.size() >= Cur.RefsCount + 1);
+      assert((PrimaryNodesStack.size() >= Cur.RefsCount &&
+              PrimaryNodesStack.size() - Cur.RefsCount >= 1));
       ObjectID PrimaryID = *(PrimaryNodesStack.end() - Cur.RefsCount - 1);
       auto PrimaryRefs = ArrayRef(PrimaryNodesStack)
                              .slice(PrimaryNodesStack.size() - Cur.RefsCount);
diff --git a/llvm/lib/CAS/OnDiskTrieRawHashMap.cpp 
b/llvm/lib/CAS/OnDiskTrieRawHashMap.cpp
index edb19d7e7c737..1f9fc886cee7e 100644
--- a/llvm/lib/CAS/OnDiskTrieRawHashMap.cpp
+++ b/llvm/lib/CAS/OnDiskTrieRawHashMap.cpp
@@ -478,8 +478,9 @@ OnDiskTrieRawHashMap::recoverFromFileOffset(FileOffset 
Offset) const {
   //
   // Note: There's no potential overflow when using \c uint64_t because Offset
   // is in valid offset range and the record size is in \c [0,UINT32_MAX].
-  if (!validOffset(Offset) ||
-      Offset.get() + Impl->Trie.getRecordSize() > Impl->File.getAlloc().size())
+  if (!validOffset(Offset) || (Offset.get() > Impl->File.getAlloc().size() ||
+                               Impl->Trie.getRecordSize() >
+                                   Impl->File.getAlloc().size() - 
Offset.get()))
     return createStringError(make_error_code(std::errc::protocol_error),
                              "file offset too large: 0x" +
                                  utohexstr(Offset.get(), /*LowerCase=*/true));
@@ -1124,7 +1125,8 @@ Error TrieVisitor::validateSubTrie(SubtrieHandle Node, 
bool IsRoot) {
 
 Error TrieVisitor::validateSubtrieHeader(uint64_t Offset, bool IsRoot) {
   uint64_t RegionSize = Trie.getRegion().size();
-  if (Offset + sizeof(SubtrieHandle::Header) > RegionSize)
+  if (Offset > RegionSize ||
+      sizeof(SubtrieHandle::Header) > RegionSize - Offset)
     return createInvalidTrieError(Offset, "subtrie header out of bound");
 
   auto *H = reinterpret_cast<const SubtrieHandle::Header *>(
@@ -1135,8 +1137,8 @@ Error TrieVisitor::validateSubtrieHeader(uint64_t Offset, 
bool IsRoot) {
   if (!IsRoot && H->NumBits > Trie.getNumSubtrieBits())
     return createInvalidTrieError(Offset, "subtrie has corrupt NumBits");
 
-  if (Offset + static_cast<uint64_t>(SubtrieHandle::getSize(H->NumBits)) >
-      RegionSize)
+  if (Offset > RegionSize || static_cast<uint64_t>(SubtrieHandle::getSize(
+                                 H->NumBits)) > RegionSize - Offset)
     return createInvalidTrieError(Offset, "subtrie node spans out of bound");
 
   return Error::success();
diff --git a/llvm/lib/CodeGen/GlobalISel/LegacyLegalizerInfo.cpp 
b/llvm/lib/CodeGen/GlobalISel/LegacyLegalizerInfo.cpp
index 05923e5fc97cc..f77b9c36bba53 100644
--- a/llvm/lib/CodeGen/GlobalISel/LegacyLegalizerInfo.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/LegacyLegalizerInfo.cpp
@@ -218,7 +218,8 @@ 
LegacyLegalizerInfo::increaseToLargerTypesAndDecreaseToLargest(
   for (size_t i = 0; i < v.size(); ++i) {
     result.push_back(v[i]);
     LargestSizeSoFar = v[i].first;
-    if (i + 1 < v.size() && v[i + 1].first != v[i].first + 1) {
+    if ((i < v.size() && 1 < v.size() - i) &&
+        v[i + 1].first != v[i].first + 1) {
       result.push_back({LargestSizeSoFar + 1, IncreaseAction});
       LargestSizeSoFar = v[i].first + 1;
     }
diff --git a/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp 
b/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
index edc8a0714eb4b..ec98fb16941e2 100644
--- a/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/LegalizerHelper.cpp
@@ -7127,7 +7127,9 @@ void 
LegalizerHelper::multiplyRegisters(SmallVectorImpl<Register> &DstRegs,
     // Collect low parts of muls for DstIdx. Visit the diagonal starting with
     // the low Src1 part, so multiply-add selectors can use it as the first
     // accumulated cross product.
-    unsigned LowStart = DstIdx + 1 < SrcParts ? 0 : DstIdx - SrcParts + 1;
+    unsigned LowStart = (DstIdx < SrcParts && 1 < SrcParts - DstIdx)
+                            ? 0
+                            : DstIdx - SrcParts + 1;
     unsigned LowEnd = std::min(DstIdx, SrcParts - 1);
     for (unsigned RevI = LowEnd + 1; RevI != LowStart; --RevI) {
       unsigned i = RevI - 1;
diff --git a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp 
b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
index 1b9a62211deaf..f0e7dca6ae242 100644
--- a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
@@ -23167,13 +23167,13 @@ 
DAGCombiner::getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
   while (true) {
     // Find a store past the width of the first store.
     size_t StartIdx = 0;
-    while ((StartIdx + 1 < StoreNodes.size()) &&
+    while ((StartIdx < StoreNodes.size() && 1 < StoreNodes.size() - StartIdx) 
&&
            StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
-              StoreNodes[StartIdx + 1].OffsetFromBase)
+               StoreNodes[StartIdx + 1].OffsetFromBase)
       ++StartIdx;
 
     // Bail if we don't have enough candidates to merge.
-    if (StartIdx + 1 >= StoreNodes.size())
+    if (StartIdx >= StoreNodes.size() || 1 >= StoreNodes.size() - StartIdx)
       return 0;
 
     // Trim stores that overlapped with the first store.
diff --git a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp 
b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
index 70ce257a5804a..1d6ddda3ae27f 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFContext.cpp
@@ -1890,7 +1890,7 @@ 
DWARFContext::getInliningInfoForAddress(object::SectionedAddress Address,
         Frame.Discriminator = CallDiscriminator;
       }
       // Get call file/line/column of a current DIE.
-      if (i + 1 < n) {
+      if (i < n && 1 < n - i) {
         FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
                                    CallDiscriminator);
       }
diff --git a/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp 
b/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
index 029048b5e67b3..b930848029fda 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
@@ -234,7 +234,8 @@ DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {
   }
 
   uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize();
-  if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
+  if (AddrOffsetSection->Data.size() < Offset ||
+      AddrOffsetSection->Data.size() - Offset < getAddressByteSize())
     return std::nullopt;
   DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
                         IsLittleEndian, getAddressByteSize());
@@ -250,7 +251,8 @@ Expected<uint64_t> 
DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {
         inconvertibleErrorCode());
   unsigned ItemSize = getDwarfStringOffsetsByteSize();
   uint64_t Offset = getStringOffsetsBase() + Index * ItemSize;
-  if (StringOffsetSection.Data.size() < Offset + ItemSize)
+  if (StringOffsetSection.Data.size() < Offset ||
+      StringOffsetSection.Data.size() - Offset < ItemSize)
     return make_error<StringError>("DW_FORM_strx uses index " + Twine(Index) +
                                        ", which is too large",
                                    inconvertibleErrorCode());
diff --git a/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp 
b/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp
index 17d1bfb3f575c..605654df53adf 100644
--- a/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp
+++ b/llvm/lib/DebugInfo/DWARF/DWARFVerifier.cpp
@@ -2264,7 +2264,8 @@ bool DWARFVerifier::verifyDebugStrOffsets(
       std::tie(Length, Format) = DA.getInitialLength(C);
       if (!C)
         break;
-      if (C.tell() + Length > DA.getData().size()) {
+      if ((C.tell() > DA.getData().size() ||
+           Length > DA.getData().size() - C.tell())) {
         ErrorCategory.Report(
             "Section contribution length exceeds available space", [&]() {
               error() << formatv(
diff --git a/llvm/lib/DebugInfo/GSYM/GsymReader.cpp 
b/llvm/lib/DebugInfo/GSYM/GsymReader.cpp
index 92efd66566445..dc525a8800ba0 100644
--- a/llvm/lib/DebugInfo/GSYM/GsymReader.cpp
+++ b/llvm/lib/DebugInfo/GSYM/GsymReader.cpp
@@ -173,7 +173,7 @@ llvm::Error GsymReader::parseGlobalDataEntries(uint64_t 
Offset) {
   const StringRef Buf = MemBuffer->getBuffer();
   const uint64_t BufSize = Buf.size();
   GsymDataExtractor Data(Buf, isLittleEndian());
-  while (Offset + sizeof(GlobalData) <= BufSize) {
+  while (Offset <= BufSize && sizeof(GlobalData) <= BufSize - Offset) {
     auto GDOrErr = GlobalData::decode(Data, Offset);
     if (!GDOrErr)
       return GDOrErr.takeError();
@@ -187,7 +187,7 @@ llvm::Error GsymReader::parseGlobalDataEntries(uint64_t 
Offset) {
                                "GlobalData section type %u has zero size",
                                static_cast<uint32_t>(GD.Type));
 
-    if (GD.FileOffset + GD.FileSize > BufSize)
+    if (GD.FileOffset > BufSize || GD.FileSize > BufSize - GD.FileOffset)
       return createStringError(
           std::errc::invalid_argument,
           "GlobalData section type %u extends beyond "
@@ -268,7 +268,7 @@ llvm::Error GsymReader::setFileTableData(StringRef Bytes) {
   uint32_t NumFiles = Data.getU32(&Offset);
   uint64_t EntriesSize =
       static_cast<uint64_t>(NumFiles) * FileEntry::getEncodedSize(StrpSize);
-  if (Bytes.size() < Offset + EntriesSize)
+  if (Bytes.size() < Offset || Bytes.size() - Offset < EntriesSize)
     return createStringError(std::errc::invalid_argument,
                              "FileTable section too small for %u files",
                              NumFiles);
@@ -305,7 +305,8 @@ GsymReader::getOptionalGlobalDataBytes(GlobalInfoType Type) 
const {
   if (!GD)
     return std::nullopt;
   StringRef Buf = MemBuffer->getBuffer();
-  if (GD->FileSize == 0 || GD->FileOffset + GD->FileSize > Buf.size())
+  if (GD->FileSize == 0 || (GD->FileOffset > Buf.size() ||
+                            GD->FileSize > Buf.size() - GD->FileOffset))
     return std::nullopt;
   return Buf.substr(GD->FileOffset, GD->FileSize);
 }
diff --git a/llvm/lib/DebugInfo/GSYM/GsymReaderV2.cpp 
b/llvm/lib/DebugInfo/GSYM/GsymReaderV2.cpp
index 1a8dfcb5f4038..92caccea8312b 100644
--- a/llvm/lib/DebugInfo/GSYM/GsymReaderV2.cpp
+++ b/llvm/lib/DebugInfo/GSYM/GsymReaderV2.cpp
@@ -44,7 +44,7 @@ void GsymReaderV2::dump(raw_ostream &OS) {
   const uint64_t BufSize = Buf.size();
   GsymDataExtractor Data(Buf, isLittleEndian());
   uint64_t Offset = HeaderV2::getEncodedSize();
-  while (Offset + sizeof(GlobalData) <= BufSize) {
+  while (Offset <= BufSize && sizeof(GlobalData) <= BufSize - Offset) {
     auto GDOrErr = GlobalData::decode(Data, Offset);
     assert(GDOrErr && "GlobalData::decode() should not fail");
     const GlobalData &GD = *GDOrErr;
diff --git a/llvm/lib/ExecutionEngine/JITLink/COFF.cpp 
b/llvm/lib/ExecutionEngine/JITLink/COFF.cpp
index 7e9bd0fe3092e..0ef53529ba13b 100644
--- a/llvm/lib/ExecutionEngine/JITLink/COFF.cpp
+++ b/llvm/lib/ExecutionEngine/JITLink/COFF.cpp
@@ -56,7 +56,8 @@ createLinkGraphFromCOFFObject(MemoryBufferRef ObjectBuffer,
   bool IsPE = false;
 
   // Check if this is a PE/COFF file.
-  if (Data.size() >= sizeof(object::dos_header) + sizeof(COFF::PEMagic)) {
+  if (Data.size() >= sizeof(object::dos_header) &&
+      Data.size() - sizeof(object::dos_header) >= sizeof(COFF::PEMagic)) {
     const auto *DH =
         reinterpret_cast<const object::dos_header *>(Data.data() + CurPtr);
     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
@@ -70,7 +71,8 @@ createLinkGraphFromCOFFObject(MemoryBufferRef ObjectBuffer,
       IsPE = true;
     }
   }
-  if (Data.size() < CurPtr + sizeof(object::coff_file_header))
+  if (Data.size() < CurPtr ||
+      Data.size() - CurPtr < sizeof(object::coff_file_header))
     return make_error<JITLinkError>("Truncated COFF buffer");
 
   const object::coff_file_header *COFFHeader =
diff --git a/llvm/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.cpp 
b/llvm/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.cpp
index 8562ebeaad745..d49334a271280 100644
--- a/llvm/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.cpp
+++ b/llvm/lib/ExecutionEngine/JITLink/MachOLinkGraphBuilder.cpp
@@ -162,7 +162,8 @@ Error MachOLinkGraphBuilder::createNormalizedSections() {
 
     // Get the section data if any.
     if (!isZeroFillSection(NSec)) {
-      if (DataOffset + NSec.Size > Obj.getData().size())
+      if ((DataOffset > Obj.getData().size() ||
+           NSec.Size > Obj.getData().size() - DataOffset))
         return make_error<JITLinkError>(
             "Section data extends past end of file");
 
diff --git a/llvm/lib/MC/MCAsmStreamer.cpp b/llvm/lib/MC/MCAsmStreamer.cpp
index a518daa997945..98f7f570fec7a 100644
--- a/llvm/lib/MC/MCAsmStreamer.cpp
+++ b/llvm/lib/MC/MCAsmStreamer.cpp
@@ -1074,7 +1074,8 @@ void MCAsmStreamer::emitXCOFFCInfoSym(StringRef Name, 
StringRef Metadata) {
   };
 
   size_t Index = 0;
-  for (; Index + WordSize <= MetadataSize; Index += WordSize)
+  for (; (Index <= MetadataSize && WordSize <= MetadataSize - Index);
+       Index += WordSize)
     PrintWord(reinterpret_cast<const uint8_t *>(Metadata.data()) + Index);
 
   // If there is padding, then we have at least one byte of payload left
diff --git a/llvm/lib/MC/XCOFFObjectWriter.cpp 
b/llvm/lib/MC/XCOFFObjectWriter.cpp
index d9f47d6f4ba25..96ab0e169547e 100644
--- a/llvm/lib/MC/XCOFFObjectWriter.cpp
+++ b/llvm/lib/MC/XCOFFObjectWriter.cpp
@@ -1691,7 +1691,7 @@ void XCOFFWriter::writeSectionForCInfoSymSectionEntry(
 
   // Write out the payload one word at a time.
   size_t Index = 0;
-  while (Index + WordSize <= Metadata.size()) {
+  while (Index <= Metadata.size() && WordSize <= Metadata.size() - Index) {
     uint32_t NextWord =
         llvm::support::endian::read32be(Metadata.data() + Index);
     W.write<uint32_t>(NextWord);
diff --git a/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp 
b/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp
index edb6ae0a5b108..5cebcbb5d9feb 100644
--- a/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp
+++ b/llvm/lib/ObjCopy/ELF/ELFObjcopy.cpp
@@ -633,10 +633,10 @@ RemoveNoteDetail::findNotesToRemove(ArrayRef<uint8_t> 
Data, size_t Align,
   using Elf_Note = typename ELFT::Note;
   std::vector<DeletedRange> ToRemove;
   uint64_t CurPos = 0;
-  while (CurPos + sizeof(Elf_Nhdr) <= Data.size()) {
+  while (CurPos <= Data.size() && sizeof(Elf_Nhdr) <= Data.size() - CurPos) {
     auto Nhdr = reinterpret_cast<const Elf_Nhdr *>(Data.data() + CurPos);
     size_t FullSize = Nhdr->getSize(Align);
-    if (CurPos + FullSize > Data.size())
+    if (CurPos > Data.size() || FullSize > Data.size() - CurPos)
       break;
     Elf_Note Note(*Nhdr);
     bool ShouldRemove =
diff --git a/llvm/lib/Object/COFFObjectFile.cpp 
b/llvm/lib/Object/COFFObjectFile.cpp
index 14a2343811a38..304abdb4bf7ac 100644
--- a/llvm/lib/Object/COFFObjectFile.cpp
+++ b/llvm/lib/Object/COFFObjectFile.cpp
@@ -550,7 +550,8 @@ Error COFFObjectFile::getDebugPDBInfo(const debug_directory 
*DebugDir,
           getRvaAndSizeAsBytes(DebugDir->AddressOfRawData, 
DebugDir->SizeOfData,
                                InfoBytes, "PDB info"))
     return E;
-  if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
+  if (InfoBytes.size() < sizeof(*PDBInfo) ||
+      InfoBytes.size() - sizeof(*PDBInfo) < 1)
     return createStringError(object_error::parse_failed, "PDB info too small");
   PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
   InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
@@ -2374,7 +2375,7 @@ ResourceSectionRef::getContents(const 
coff_resource_data_entry &Entry) {
     ArrayRef<uint8_t> Contents;
     if (Error E = Obj->getSectionContents(*Section, Contents))
       return E;
-    if (Offset + Entry.DataSize > Contents.size())
+    if (Offset > Contents.size() || Entry.DataSize > Contents.size() - Offset)
       return createStringError(object_error::parse_failed,
                                "data outside of section");
     // Return a reference to the data inside the section.
diff --git a/llvm/lib/Object/DXContainer.cpp b/llvm/lib/Object/DXContainer.cpp
index e7641077b5029..33273995490f3 100644
--- a/llvm/lib/Object/DXContainer.cpp
+++ b/llvm/lib/Object/DXContainer.cpp
@@ -178,7 +178,7 @@ Error DirectX::Signature::initialize(StringRef Part) {
     return Err;
   size_t Size = sizeof(dxbc::ProgramSignatureElement) * SigHeader.ParamCount;
 
-  if (Part.size() < Size + SigHeader.FirstParamOffset)
+  if (Part.size() < Size || Part.size() - Size < SigHeader.FirstParamOffset)
     return parseFailed("Signature parameters extend beyond the part boundary");
 
   Parameters.Data = Part.substr(SigHeader.FirstParamOffset, Size);
diff --git a/llvm/lib/Object/MachOObjectFile.cpp 
b/llvm/lib/Object/MachOObjectFile.cpp
index 3342c99e245ca..daabfd1cfc4d4 100644
--- a/llvm/lib/Object/MachOObjectFile.cpp
+++ b/llvm/lib/Object/MachOObjectFile.cpp
@@ -3469,7 +3469,8 @@ void MachOChainedFixupEntry::moveNext() {
   PointerValue = 0;
   SymbolName = {};
 
-  if (SegmentOffset + sizeof(RawValue) > SegmentData.size()) {
+  if (SegmentOffset > SegmentData.size() ||
+      sizeof(RawValue) > SegmentData.size() - SegmentOffset) {
     *E = malformedError("fixup in segment " + Twine(SegmentIndex) +
                         " at offset " + Twine(SegmentOffset) +
                         " extends past segment's end");
diff --git a/llvm/lib/Object/Minidump.cpp b/llvm/lib/Object/Minidump.cpp
index 1c69687dc47f3..7c94c30f703db 100644
--- a/llvm/lib/Object/Minidump.cpp
+++ b/llvm/lib/Object/Minidump.cpp
@@ -82,7 +82,7 @@ Expected<ArrayRef<uint8_t>> 
MinidumpFile::getDataSlice(ArrayRef<uint8_t> Data,
                                                        uint64_t Size) {
   // Check for overflow.
   if (Offset + Size < Offset || Offset + Size < Size ||
-      Offset + Size > Data.size())
+      (Offset > Data.size() || Size > Data.size() - Offset))
     return createEOFError();
   return Data.slice(Offset, Size);
 }
@@ -166,8 +166,9 @@ MinidumpFile::getMemory64List(Error &Err) const {
     return make_range(end, end);
   }
 
-  if (!Descriptors->empty() &&
-      ListHeader->BaseRVA + Descriptors->front().DataSize > getData().size()) {
+  if (!Descriptors->empty() && (ListHeader->BaseRVA > getData().size() ||
+                                Descriptors->front().DataSize >
+                                    getData().size() - ListHeader->BaseRVA)) {
     Err = createError("Memory64List header RVA out of range");
     return make_range(end, end);
   }
diff --git a/llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp 
b/llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp
index e89efe09d49e8..064193e98d889 100644
--- a/llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp
+++ b/llvm/lib/ProfileData/Coverage/CoverageMappingReader.cpp
@@ -530,7 +530,7 @@ StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, 
size_t Size) const {
   if (Pointer < Address)
     return StringRef();
   auto Offset = Pointer - Address;
-  if (Offset + Size > Data.size())
+  if (Offset > Data.size() || Size > Data.size() - Offset)
     return StringRef();
   return Data.substr(Pointer - Address, Size);
 }
diff --git a/llvm/lib/Support/CommandLine.cpp b/llvm/lib/Support/CommandLine.cpp
index a9102fe30efe3..373bdd4abfe9a 100644
--- a/llvm/lib/Support/CommandLine.cpp
+++ b/llvm/lib/Support/CommandLine.cpp
@@ -868,7 +868,7 @@ void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver 
&Saver,
     char C = Src[I];
 
     // Backslash escapes the next character.
-    if (I + 1 < E && C == '\\') {
+    if ((I < E && 1 < E - I) && C == '\\') {
       ++I; // Skip the escape.
       Token.push_back(Src[I]);
       continue;
diff --git a/llvm/lib/Support/RewriteBuffer.cpp 
b/llvm/lib/Support/RewriteBuffer.cpp
index cc6ba7e97b1a7..6a9e7da3453b0 100644
--- a/llvm/lib/Support/RewriteBuffer.cpp
+++ b/llvm/lib/Support/RewriteBuffer.cpp
@@ -33,7 +33,8 @@ void RewriteBuffer::RemoveText(unsigned OrigOffset, unsigned 
Size,
     return;
 
   unsigned RealOffset = getMappedOffset(OrigOffset, true);
-  assert(RealOffset + Size <= Buffer.size() && "Invalid location");
+  assert((RealOffset <= Buffer.size() && Size <= Buffer.size() - RealOffset) &&
+         "Invalid location");
 
   // Remove the dead characters.
   Buffer.erase(RealOffset, Size);
diff --git a/llvm/lib/Support/Unicode.cpp b/llvm/lib/Support/Unicode.cpp
index cbf772b41f972..474e00fefb1ed 100644
--- a/llvm/lib/Support/Unicode.cpp
+++ b/llvm/lib/Support/Unicode.cpp
@@ -522,7 +522,7 @@ int columnWidthUTF8(StringRef Text) {
       continue;
     }
 
-    if (Length <= 0 || i + Length > Text.size())
+    if (Length <= 0 || (i > Text.size() || Length > Text.size() - i))
       return ErrorInvalidUTF8;
     UTF32 buf[1];
     const UTF8 *Start = reinterpret_cast<const UTF8 *>(Text.data() + i);
diff --git a/llvm/lib/Target/AMDGPU/R600ControlFlowFinalizer.cpp 
b/llvm/lib/Target/AMDGPU/R600ControlFlowFinalizer.cpp
index 248d734268ccf..b3a544c372ebc 100644
--- a/llvm/lib/Target/AMDGPU/R600ControlFlowFinalizer.cpp
+++ b/llvm/lib/Target/AMDGPU/R600ControlFlowFinalizer.cpp
@@ -365,7 +365,7 @@ class R600ControlFlowFinalizer : public MachineFunctionPass 
{
     MachineBasicBlock *MBB = InsertPos->getParent();
     for (unsigned i = 0, e = Literals.size(); i < e; i+=2) {
       unsigned LiteralPair0 = Literals[i];
-      unsigned LiteralPair1 = (i + 1 < e)?Literals[i + 1]:0;
+      unsigned LiteralPair1 = (i < e && 1 < e - i) ? Literals[i + 1] : 0;
       InsertPos = BuildMI(MBB, InsertPos->getDebugLoc(),
           TII->get(R600::LITERALS))
           .addImm(LiteralPair0)
@@ -416,7 +416,7 @@ class R600ControlFlowFinalizer : public MachineFunctionPass 
{
             MILit.addGlobalAddress(Literals[i]->getGlobal(),
                                    Literals[i]->getOffset());
         }
-        if (i + 1 < e) {
+        if (i < e && 1 < e - i) {
           if (Literals[i + 1]->isImm()) {
             MILit.addImm(Literals[i + 1]->getImm());
           } else {
diff --git a/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp 
b/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
index 1c5caf124c17e..76a168935c3d8 100644
--- a/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
+++ b/llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp
@@ -1906,7 +1906,7 @@ static SDValue buildTreeReduction(
     // Build the next level by partially reducing all elements.
     SmallVector<SDValue> ReducedLevel;
     unsigned I = 0, E = Level.size();
-    for (; I + NumInputs <= E; I += NumInputs) {
+    for (; (I <= E && NumInputs <= E - I); I += NumInputs) {
       // Reduce elements in groups of [NumInputs], as much as possible.
       ReducedLevel.push_back(DAG.getNode(
           Op, DL, EltTy, ArrayRef<SDValue>(Level).slice(I, NumInputs), Flags));
diff --git a/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp 
b/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp
index 7d2b5eb900133..f30c1f5a4d261 100644
--- a/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp
+++ b/llvm/lib/Target/X86/Disassembler/X86Disassembler.cpp
@@ -199,7 +199,7 @@ static bool peek(struct InternalInstruction *insn, uint8_t 
&byte) {
 template <typename T> static bool consume(InternalInstruction *insn, T &ptr) {
   auto r = insn->bytes;
   uint64_t offset = insn->readerCursor - insn->startLocation;
-  if (offset + sizeof(T) > r.size())
+  if (offset > r.size() || sizeof(T) > r.size() - offset)
     return true;
   ptr = support::endian::read<T>(&r[offset], llvm::endianness::little);
   insn->readerCursor += sizeof(T);
diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp 
b/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp
index 29ec0cb989977..d86214dbefcae 100644
--- a/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp
+++ b/llvm/lib/Target/X86/MCTargetDesc/X86MCTargetDesc.cpp
@@ -663,7 +663,8 @@ static std::vector<std::pair<uint64_t, uint64_t>>
 findX86PltEntries(uint64_t PltSectionVA, ArrayRef<uint8_t> PltContents) {
   // Do a lightweight parsing of PLT entries.
   std::vector<std::pair<uint64_t, uint64_t>> Result;
-  for (uint64_t Byte = 0, End = PltContents.size(); Byte + 6 < End; ) {
+  for (uint64_t Byte = 0, End = PltContents.size();
+       (Byte < End && 6 < End - Byte);) {
     // Recognize a jmp.
     if (PltContents[Byte] == 0xff && PltContents[Byte + 1] == 0xa3) {
       // The jmp instruction at the beginning of each PLT entry jumps to the
@@ -690,7 +691,8 @@ static std::vector<std::pair<uint64_t, uint64_t>>
 findX86_64PltEntries(uint64_t PltSectionVA, ArrayRef<uint8_t> PltContents) {
   // Do a lightweight parsing of PLT entries.
   std::vector<std::pair<uint64_t, uint64_t>> Result;
-  for (uint64_t Byte = 0, End = PltContents.size(); Byte + 6 < End; ) {
+  for (uint64_t Byte = 0, End = PltContents.size();
+       (Byte < End && 6 < End - Byte);) {
     // Recognize a jmp.
     if (PltContents[Byte] == 0xff && PltContents[Byte + 1] == 0x25) {
       // The jmp instruction at the beginning of each PLT entry jumps to the
diff --git a/llvm/lib/Transforms/IPO/InstrumentorUtils.cpp 
b/llvm/lib/Transforms/IPO/InstrumentorUtils.cpp
index 7030002824761..109bcc3cfade3 100644
--- a/llvm/lib/Transforms/IPO/InstrumentorUtils.cpp
+++ b/llvm/lib/Transforms/IPO/InstrumentorUtils.cpp
@@ -69,7 +69,8 @@ class FilterEvaluator {
     Expected<bool> Result = parseAndExpr();
     while (Result) {
       skipWhitespace();
-      if (Pos + 1 < Expr.size() && Expr[Pos] == '|' && Expr[Pos + 1] == '|') {
+      if ((Pos < Expr.size() && 1 < Expr.size() - Pos) && Expr[Pos] == '|' &&
+          Expr[Pos + 1] == '|') {
         Pos += 2;
         Expected<bool> NextResult = parseAndExpr();
         if (!NextResult)
@@ -86,7 +87,8 @@ class FilterEvaluator {
     Expected<bool> Result = parsePrimary();
     while (Result) {
       skipWhitespace();
-      if (Pos + 1 < Expr.size() && Expr[Pos] == '&' && Expr[Pos + 1] == '&') {
+      if ((Pos < Expr.size() && 1 < Expr.size() - Pos) && Expr[Pos] == '&' &&
+          Expr[Pos + 1] == '&') {
         Pos += 2;
         Expected<bool> NextResult = parsePrimary();
         if (!NextResult)
@@ -222,18 +224,22 @@ class FilterEvaluator {
       // Parse operator.
       enum OpKind { EQ, NE, LT, GT, LE, GE } Op;
       if (Pos < Expr.size()) {
-        if (Expr[Pos] == '=' && Pos + 1 < Expr.size() && Expr[Pos + 1] == '=') 
{
+        if (Expr[Pos] == '=' && (Pos < Expr.size() && 1 < Expr.size() - Pos) &&
+            Expr[Pos + 1] == '=') {
           Op = EQ;
           Pos += 2;
-        } else if (Expr[Pos] == '!' && Pos + 1 < Expr.size() &&
+        } else if (Expr[Pos] == '!' &&
+                   (Pos < Expr.size() && 1 < Expr.size() - Pos) &&
                    Expr[Pos + 1] == '=') {
           Op = NE;
           Pos += 2;
-        } else if (Expr[Pos] == '<' && Pos + 1 < Expr.size() &&
+        } else if (Expr[Pos] == '<' &&
+                   (Pos < Expr.size() && 1 < Expr.size() - Pos) &&
                    Expr[Pos + 1] == '=') {
           Op = LE;
           Pos += 2;
-        } else if (Expr[Pos] == '>' && Pos + 1 < Expr.size() &&
+        } else if (Expr[Pos] == '>' &&
+                   (Pos < Expr.size() && 1 < Expr.size() - Pos) &&
                    Expr[Pos + 1] == '=') {
           Op = GE;
           Pos += 2;
@@ -305,10 +311,12 @@ class FilterEvaluator {
       // Parse operator (only == and != for strings).
       enum OpKind { EQ, NE } Op;
       if (Pos < Expr.size()) {
-        if (Expr[Pos] == '=' && Pos + 1 < Expr.size() && Expr[Pos + 1] == '=') 
{
+        if (Expr[Pos] == '=' && (Pos < Expr.size() && 1 < Expr.size() - Pos) &&
+            Expr[Pos + 1] == '=') {
           Op = EQ;
           Pos += 2;
-        } else if (Expr[Pos] == '!' && Pos + 1 < Expr.size() &&
+        } else if (Expr[Pos] == '!' &&
+                   (Pos < Expr.size() && 1 < Expr.size() - Pos) &&
                    Expr[Pos + 1] == '=') {
           Op = NE;
           Pos += 2;
@@ -347,10 +355,12 @@ class FilterEvaluator {
       // Parse operator (only == and != for pointers).
       enum OpKind { EQ, NE } Op;
       if (Pos < Expr.size()) {
-        if (Expr[Pos] == '=' && Pos + 1 < Expr.size() && Expr[Pos + 1] == '=') 
{
+        if (Expr[Pos] == '=' && (Pos < Expr.size() && 1 < Expr.size() - Pos) &&
+            Expr[Pos + 1] == '=') {
           Op = EQ;
           Pos += 2;
-        } else if (Expr[Pos] == '!' && Pos + 1 < Expr.size() &&
+        } else if (Expr[Pos] == '!' &&
+                   (Pos < Expr.size() && 1 < Expr.size() - Pos) &&
                    Expr[Pos + 1] == '=') {
           Op = NE;
           Pos += 2;
diff --git a/llvm/lib/Transforms/IPO/MemProfContextDisambiguation.cpp 
b/llvm/lib/Transforms/IPO/MemProfContextDisambiguation.cpp
index bbcaa530e8e5b..fe0ef58641e17 100644
--- a/llvm/lib/Transforms/IPO/MemProfContextDisambiguation.cpp
+++ b/llvm/lib/Transforms/IPO/MemProfContextDisambiguation.cpp
@@ -5358,7 +5358,8 @@ bool CallsiteContextGraph<DerivedCCG, FuncTy, 
CallTy>::assignFunctions() {
       // skip it. Need to add one for the original copy.
       // Use >= in case there were clones that were skipped due to having empty
       // context ids
-      if (Node->Clones.size() + 1 >= FuncCloneInfos.size())
+      if (Node->Clones.size() >= FuncCloneInfos.size() ||
+          1 >= FuncCloneInfos.size() - Node->Clones.size())
         continue;
       // First collect all function clones we cloned this callsite node for.
       // They may not be sequential due to empty clones e.g.
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp 
b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index 0c2d11fab4f43..82fdfee0207a0 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -4509,7 +4509,8 @@ static Bitset<256> parseFormatStringSpecifiers(StringRef 
FormatStr) {
       continue;
 
     // Check for escaped '%'.
-    if (I + 1 < FormatStr.size() && FormatStr[I + 1] == '%') {
+    if ((I < FormatStr.size() && 1 < FormatStr.size() - I) &&
+        FormatStr[I + 1] == '%') {
       ++I; // Skip the second '%'.
       continue;
     }
diff --git a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp 
b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
index 6d901e835a1bd..48a40c336c7e9 100644
--- a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
@@ -5078,7 +5078,7 @@ Instruction 
*InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) {
   // advantageous because shorter filters are more likely to match, speeding up
   // unwinding, but mostly because it increases the effectiveness of the other
   // filter optimizations below.
-  for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
+  for (unsigned i = 0, e = NewClauses.size(); (i < e && 1 < e - i);) {
     unsigned j;
     // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
     for (j = i; j != e; ++j)
diff --git a/llvm/lib/Transforms/Scalar/LoopPassManager.cpp 
b/llvm/lib/Transforms/Scalar/LoopPassManager.cpp
index d827e649d0842..016d1dc6ad154 100644
--- a/llvm/lib/Transforms/Scalar/LoopPassManager.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopPassManager.cpp
@@ -53,7 +53,7 @@ void PassManager<Loop, LoopAnalysisManager, 
LoopStandardAnalysisResults &,
       auto *P = LoopPasses[IdxLP++].get();
       P->printPipeline(OS, MapClassName2PassName);
     }
-    if (Idx + 1 < Size)
+    if (Idx < Size && 1 < Size - Idx)
       OS << ',';
   }
 }
diff --git a/llvm/lib/Transforms/Scalar/SROA.cpp 
b/llvm/lib/Transforms/Scalar/SROA.cpp
index 14a1b093ea49a..1b067708bee47 100644
--- a/llvm/lib/Transforms/Scalar/SROA.cpp
+++ b/llvm/lib/Transforms/Scalar/SROA.cpp
@@ -3005,7 +3005,7 @@ class AllocaSliceRewriter : public 
InstVisitor<AllocaSliceRewriter, bool> {
       LLVM_DEBUG(dbgs() << "  Rewrite stores into shufflevectors:\n");
       while (Vals.size() > 1) {
         SmallVector<Value *, 8> Next;
-        for (unsigned I = 0, E = Vals.size(); I + 1 < E; I += 2) {
+        for (unsigned I = 0, E = Vals.size(); (I < E && 1 < E - I); I += 2) {
           Value *M =
               mergeTwoVectors(Vals[I], Vals[I + 1], DL, AllocatedEltTy, B);
           LLVM_DEBUG(dbgs() << "    shufflevector: " << *M << "\n");
diff --git a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp 
b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
index d1fb8e2beea50..a7396afe6f135 100644
--- a/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
+++ b/llvm/lib/Transforms/Vectorize/SLPVectorizer.cpp
@@ -8397,7 +8397,7 @@ BoUpSLP::getReorderingData(const TreeEntry &TE, bool 
TopToBottom,
         UsedVals.set(Val);
         for (unsigned K = 0; K < NumParts; ++K) {
           unsigned Idx = Val + Sz * K;
-          if (Idx < VF && I + K < VF)
+          if (Idx < VF && (I < VF && K < VF - I))
             ResOrder[Idx] = I + K;
         }
       }
@@ -13672,7 +13672,7 @@ bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL,
   }
   if (MaxIdx - MinIdx + 1 > E)
     return false;
-  if (MaxIdx + 1 <= E)
+  if (MaxIdx <= E && 1 <= E - MaxIdx)
     MinIdx = 0;
 
   // Check that all of the indices extract from the correct offset.
@@ -15114,7 +15114,7 @@ void BoUpSLP::transformNodes() {
                *TTI, VL.front()->getType(), VL.size() - 1);
            VF >= MinVF; VF = getFloorFullVectorNumberOfElements(
                             *TTI, VL.front()->getType(), VF - 1)) {
-        if (StartIdx + VF > End)
+        if (StartIdx > End || VF > End - StartIdx)
           continue;
         SmallVector<std::pair<unsigned, unsigned>> Slices;
         bool AllStrided = true;
@@ -28590,7 +28590,8 @@ bool 
SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
   InstructionCost MinCost = SLPCostThreshold.getValue();
 
   unsigned NextInst = 0, MaxInst = VL.size();
-  for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
+  for (unsigned VF = MaxVF;
+       (NextInst < MaxInst && 1 < MaxInst - NextInst) && VF >= MinVF;
        VF = getFloorFullVectorNumberOfElements(*TTI, I0->getType(), VF - 1)) {
     // No actual vectorization should happen, if number of parts is the same as
     // provided vectorization factor (i.e. the scalar type is used for vector
@@ -29666,7 +29667,7 @@ class HorizontalReduction {
       bool ShuffledExtracts = false;
       // Try to handle shuffled extractelements.
       if (S && S.getOpcode() == Instruction::ExtractElement &&
-          !S.isAltShuffle() && I + 1 < E) {
+          !S.isAltShuffle() && (I < E && 1 < E - I)) {
         SmallVector<Value *> CommonCandidates(Candidates);
         for (Value *RV : ReducedVals[I + 1]) {
           Value *RdxVal = TrackedVals.at(RV);
diff --git 
a/llvm/lib/Transforms/Vectorize/SandboxVectorizer/Passes/SeedCollection.cpp 
b/llvm/lib/Transforms/Vectorize/SandboxVectorizer/Passes/SeedCollection.cpp
index 48b6af9e4a203..2f3699529497f 100644
--- a/llvm/lib/Transforms/Vectorize/SandboxVectorizer/Passes/SeedCollection.cpp
+++ b/llvm/lib/Transforms/Vectorize/SandboxVectorizer/Passes/SeedCollection.cpp
@@ -86,7 +86,7 @@ bool SeedCollection::runOnFunction(Function &F, const 
Analyses &A) {
           // the slice. This could be quite expensive, so we enforce a limit.
           for (unsigned Offset = Seeds.getFirstUnusedElementIdx(),
                         OE = Seeds.size();
-               Offset + 1 < OE; Offset += 1) {
+               (Offset < OE && 1 < OE - Offset); Offset += 1) {
             // Seeds are getting used as we vectorize, so skip them.
             if (Seeds.isUsed(Offset))
               continue;
diff --git a/llvm/tools/llvm-cas-fuzzer/cas-fuzzer.cpp 
b/llvm/tools/llvm-cas-fuzzer/cas-fuzzer.cpp
index 1508a1d57559a..9acd751c5f35b 100644
--- a/llvm/tools/llvm-cas-fuzzer/cas-fuzzer.cpp
+++ b/llvm/tools/llvm-cas-fuzzer/cas-fuzzer.cpp
@@ -33,14 +33,14 @@ namespace {
 
 /// Read a little-endian uint32 from Data, or 0 if not enough bytes.
 static uint32_t readU32(ArrayRef<uint8_t> Data, size_t Offset) {
-  if (Offset + sizeof(uint32_t) > Data.size())
+  if (Offset > Data.size() || sizeof(uint32_t) > Data.size() - Offset)
     return 0;
   return support::endian::read32le(Data.data() + Offset);
 }
 
 /// Read a little-endian uint16 from Data, or 0 if not enough bytes.
 static uint16_t readU16(ArrayRef<uint8_t> Data, size_t Offset) {
-  if (Offset + sizeof(uint16_t) > Data.size())
+  if (Offset > Data.size() || sizeof(uint16_t) > Data.size() - Offset)
     return 0;
   return support::endian::read16le(Data.data() + Offset);
 }
@@ -157,7 +157,7 @@ static void applyByteMutations(StringRef Path, 
ArrayRef<uint8_t> Data) {
     return;
 
   // Parse as 7-byte chunks: [offset(4)][op(1)][value(1)][unused(1)]
-  for (size_t I = 0; I + 6 <= Data.size(); I += 7) {
+  for (size_t I = 0; (I <= Data.size() && 6 <= Data.size() - I); I += 7) {
     uint32_t Offset = readU32(Data, I) % Buf.size();
     uint8_t Op = Data[I + 4] % 3;
     uint8_t Value = Data[I + 5];
@@ -223,8 +223,10 @@ static void corruptStandaloneFiles(StringRef SubDir, 
ArrayRef<uint8_t> Data) {
 
   for (size_t I = 0; I < Data.size() && !StandaloneFiles.empty(); I += 3) {
     size_t FileIdx = Data[I] % StandaloneFiles.size();
-    uint8_t Action = (I + 1 < Data.size()) ? Data[I + 1] % 4 : 0;
-    uint8_t Param = (I + 2 < Data.size()) ? Data[I + 2] : 128;
+    uint8_t Action =
+        (I < Data.size() && 1 < Data.size() - I) ? Data[I + 1] % 4 : 0;
+    uint8_t Param =
+        (I < Data.size() && 2 < Data.size() - I) ? Data[I + 2] : 128;
 
     StringRef FilePath = StandaloneFiles[FileIdx];
     switch (Action) {
@@ -235,7 +237,7 @@ static void corruptStandaloneFiles(StringRef SubDir, 
ArrayRef<uint8_t> Data) {
       truncateFile(FilePath, Param);
       break;
     case 2: // Corrupt bytes
-      if (I + 3 < Data.size())
+      if (I < Data.size() && 3 < Data.size() - I)
         applyByteMutations(
             FilePath, Data.slice(I + 3, std::min(Data.size() - I - 3,
                                                  static_cast<size_t>(21))));
diff --git a/llvm/tools/llvm-objdump/COFFDump.cpp 
b/llvm/tools/llvm-objdump/COFFDump.cpp
index 581943390a0a3..421ef6f6459c1 100644
--- a/llvm/tools/llvm-objdump/COFFDump.cpp
+++ b/llvm/tools/llvm-objdump/COFFDump.cpp
@@ -910,7 +910,8 @@ static void printWin64EHUnwindInfoV3(ArrayRef<uint8_t> 
Data) {
       outs() << format("    Handler: 0x%X\n", HandlerRVA);
     }
   } else if (Info.Flags & UNW_ChainInfo) {
-    if (Info.PayloadSize + sizeof(RuntimeFunction) <= Data.size()) {
+    if (Info.PayloadSize <= Data.size() &&
+        sizeof(RuntimeFunction) <= Data.size() - Info.PayloadSize) {
       const auto *Chained =
           reinterpret_cast<const RuntimeFunction *>(&Data[Info.PayloadSize]);
       outs() << "    Chained:\n"
diff --git a/llvm/tools/llvm-objdump/MachODump.cpp 
b/llvm/tools/llvm-objdump/MachODump.cpp
index 8b5a56b0db095..a1efc26c280f0 100644
--- a/llvm/tools/llvm-objdump/MachODump.cpp
+++ b/llvm/tools/llvm-objdump/MachODump.cpp
@@ -7879,7 +7879,7 @@ namespace {
 
 template <typename T>
 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
-  if (Offset + sizeof(T) > Contents.size()) {
+  if (Offset > Contents.size() || sizeof(T) > Contents.size() - Offset) {
     outs() << "warning: attempt to read past end of buffer\n";
     return T();
   }
@@ -8318,7 +8318,7 @@ static void printMachOUnwindInfoSection(const 
MachOObjectFile *Obj,
            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
 
     Pos = IndexEntries[i].SecondLevelPageStart;
-    if (Pos + sizeof(uint32_t) > Contents.size()) {
+    if (Pos > Contents.size() || sizeof(uint32_t) > Contents.size() - Pos) {
       outs() << "warning: invalid offset for second level page: " << Pos << 
'\n';
       continue;
     }
diff --git a/llvm/tools/llvm-objdump/llvm-objdump.cpp 
b/llvm/tools/llvm-objdump/llvm-objdump.cpp
index daebae588cfff..de65c69560627 100644
--- a/llvm/tools/llvm-objdump/llvm-objdump.cpp
+++ b/llvm/tools/llvm-objdump/llvm-objdump.cpp
@@ -990,14 +990,14 @@ class ARMPrettyPrinter : public PrettyPrinter {
     if (ShowRawInsn) {
       size_t Pos = 0, End = Bytes.size();
       if (STI.checkFeatures("+thumb-mode")) {
-        for (; Pos + 2 <= End; Pos += 2)
+        for (; (Pos <= End && 2 <= End - Pos); Pos += 2)
           OS << ' '
              << format_hex_no_prefix(
                     llvm::support::endian::read<uint16_t>(
                         Bytes.data() + Pos, InstructionEndianness),
                     4);
       } else {
-        for (; Pos + 4 <= End; Pos += 4)
+        for (; (Pos <= End && 4 <= End - Pos); Pos += 4)
           OS << ' '
              << format_hex_no_prefix(
                     llvm::support::endian::read<uint32_t>(
@@ -1044,7 +1044,7 @@ class AArch64PrettyPrinter : public PrettyPrinter {
       OS << format("%8" PRIx64 ":", Address.Address);
     if (ShowRawInsn) {
       size_t Pos = 0, End = Bytes.size();
-      for (; Pos + 4 <= End; Pos += 4)
+      for (; (Pos <= End && 4 <= End - Pos); Pos += 4)
         OS << ' '
            << format_hex_no_prefix(
                   llvm::support::endian::read<uint32_t>(
@@ -1085,7 +1085,7 @@ class RISCVPrettyPrinter : public PrettyPrinter {
       size_t Pos = 0, End = Bytes.size();
       if (End % 4 == 0) {
         // 32-bit and 64-bit instructions.
-        for (; Pos + 4 <= End; Pos += 4)
+        for (; (Pos <= End && 4 <= End - Pos); Pos += 4)
           OS << ' '
              << format_hex_no_prefix(
                     llvm::support::endian::read<uint32_t>(
@@ -1093,7 +1093,7 @@ class RISCVPrettyPrinter : public PrettyPrinter {
                     8);
       } else if (End % 2 == 0) {
         // 16-bit and 48-bits instructions.
-        for (; Pos + 2 <= End; Pos += 2)
+        for (; (Pos <= End && 2 <= End - Pos); Pos += 2)
           OS << ' '
              << format_hex_no_prefix(
                     llvm::support::endian::read<uint16_t>(
@@ -3102,7 +3102,7 @@ void objdump::printSectionContents(const ObjectFile *Obj) 
{
       for (std::size_t I = 0; I < 16; ++I) {
         if (I != 0 && I % 4 == 0)
           outs() << ' ';
-        if (Addr + I < End)
+        if (Addr < End && I < End - Addr)
           outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
                  << hexdigit(Contents[Addr + I] & 0xF, true);
         else
@@ -3110,7 +3110,7 @@ void objdump::printSectionContents(const ObjectFile *Obj) 
{
       }
       // Print ascii.
       outs() << "  ";
-      for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
+      for (std::size_t I = 0; I < 16 && (Addr < End && I < End - Addr); ++I) {
         if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
           outs() << Contents[Addr + I];
         else
diff --git a/llvm/tools/llvm-profgen/ProfiledBinary.cpp 
b/llvm/tools/llvm-profgen/ProfiledBinary.cpp
index 08fd6917c9f3a..9051fa54bb908 100644
--- a/llvm/tools/llvm-profgen/ProfiledBinary.cpp
+++ b/llvm/tools/llvm-profgen/ProfiledBinary.cpp
@@ -588,8 +588,9 @@ bool ProfiledBinary::dissassembleSymbol(std::size_t SI, 
ArrayRef<uint8_t> Bytes,
   uint64_t SectionAddress = Section.getAddress();
   uint64_t SectSize = Section.getSize();
   uint64_t StartAddress = Symbols[SI].Addr;
-  uint64_t NextStartAddress =
-      (SI + 1 < SE) ? Symbols[SI + 1].Addr : SectionAddress + SectSize;
+  uint64_t NextStartAddress = (SI < SE && 1 < SE - SI)
+                                  ? Symbols[SI + 1].Addr
+                                  : SectionAddress + SectSize;
   FuncRange *FRange = findFuncRange(StartAddress);
   setIsFuncEntry(FRange, 
FunctionSamples::getCanonicalFnName(Symbols[SI].Name));
   StringRef SymbolName =
diff --git a/llvm/tools/llvm-rc/ResourceFileWriter.cpp 
b/llvm/tools/llvm-rc/ResourceFileWriter.cpp
index 2c35c5ad365dc..a8e96a9924a0d 100644
--- a/llvm/tools/llvm-rc/ResourceFileWriter.cpp
+++ b/llvm/tools/llvm-rc/ResourceFileWriter.cpp
@@ -346,7 +346,8 @@ static Error processString(StringRef Str, 
NullHandlingMethod NullHandler,
     break;
 
   case NullHandlingMethod::CutAtDoubleNull:
-    for (size_t Pos = 0; Pos + 1 < Result.size(); ++Pos)
+    for (size_t Pos = 0; (Pos < Result.size() && 1 < Result.size() - Pos);
+         ++Pos)
       if (Result[Pos] == '\0' && Result[Pos + 1] == '\0')
         Result.resize(Pos);
     if (Result.size() > 0 && Result.back() == '\0')
diff --git a/llvm/tools/llvm-readobj/ARMWinEHPrinter.cpp 
b/llvm/tools/llvm-readobj/ARMWinEHPrinter.cpp
index 32e3d059f44d3..fbe98ecc1566f 100644
--- a/llvm/tools/llvm-readobj/ARMWinEHPrinter.cpp
+++ b/llvm/tools/llvm-readobj/ARMWinEHPrinter.cpp
@@ -1064,7 +1064,7 @@ void Decoder::decodeOpcodes(ArrayRef<uint8_t> Opcodes, 
unsigned Offset,
       }
 
       if ((Opcodes[OI] & DecodeRing[DI].Mask) == DecodeRing[DI].Value) {
-        if (OI + DecodeRing[DI].Length > OE) {
+        if (OI > OE || DecodeRing[DI].Length > OE - OI) {
           SW.startLine() << format("Opcode 0x%02x goes past the unwind data\n",
                                     Opcodes[OI]);
           OI += DecodeRing[DI].Length;
diff --git a/llvm/unittests/Support/AddressRangeTest.cpp 
b/llvm/unittests/Support/AddressRangeTest.cpp
index 76e7e5e78d964..371469fbcf905 100644
--- a/llvm/unittests/Support/AddressRangeTest.cpp
+++ b/llvm/unittests/Support/AddressRangeTest.cpp
@@ -162,7 +162,8 @@ TEST(AddressRangeTest, TestRangesRandom) {
   }
 
   // Check ranges.
-  for (size_t Idx = 0; Idx + 1 < Ranges.size(); Idx++) {
+  for (size_t Idx = 0; (Idx < Ranges.size() && 1 < Ranges.size() - Idx);
+       Idx++) {
     // Check that ranges are not intersected.
     EXPECT_FALSE(Ranges[Idx].intersects(Ranges[Idx + 1]));
 
@@ -402,7 +403,8 @@ TEST(AddressRangeTest, TestRangesMapRandom) {
   }
 
   // Check ranges.
-  for (size_t Idx = 0; Idx + 1 < Ranges.size(); Idx++) {
+  for (size_t Idx = 0; (Idx < Ranges.size() && 1 < Ranges.size() - Idx);
+       Idx++) {
     // Check that ranges are not intersected.
     EXPECT_FALSE(Ranges[Idx].Range.intersects(Ranges[Idx + 1].Range));
 
@@ -420,7 +422,8 @@ TEST(AddressRangeTest, TestRangesMapRandom) {
   }
 
   // Check ranges.
-  for (size_t Idx = 0; Idx + 1 < Ranges.size(); Idx++) {
+  for (size_t Idx = 0; (Idx < Ranges.size() && 1 < Ranges.size() - Idx);
+       Idx++) {
     // Check that ranges are not intersected.
     EXPECT_FALSE(Ranges[Idx].Range.intersects(Ranges[Idx + 1].Range));
 
diff --git a/llvm/utils/TableGen/Common/CodeGenRegisters.cpp 
b/llvm/utils/TableGen/Common/CodeGenRegisters.cpp
index eb6f07d761029..e0558cad112e1 100644
--- a/llvm/utils/TableGen/Common/CodeGenRegisters.cpp
+++ b/llvm/utils/TableGen/Common/CodeGenRegisters.cpp
@@ -2099,7 +2099,8 @@ void CodeGenRegBank::pruneUnitSets() {
       unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
       const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
       if (isRegUnitSubSet(SubSet.Units, SuperSet.Units) &&
-          (SubSet.Units.size() + 3 > SuperSet.Units.size()) &&
+          (SubSet.Units.size() > SuperSet.Units.size() ||
+           3 > SuperSet.Units.size() - SubSet.Units.size()) &&
           UnitWeight == RegUnits[SuperSet.Units[0]].Weight &&
           UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
         LLVM_DEBUG({
diff --git a/llvm/utils/TableGen/SubtargetEmitter.cpp 
b/llvm/utils/TableGen/SubtargetEmitter.cpp
index a915ce0daec2d..a475146bf8fc8 100644
--- a/llvm/utils/TableGen/SubtargetEmitter.cpp
+++ b/llvm/utils/TableGen/SubtargetEmitter.cpp
@@ -1348,7 +1348,7 @@ void 
SubtargetEmitter::emitSchedClassTables(SchedClassTables &SchedTables,
     OS << "  {" << format("%2d", WPREntry.ProcResourceIdx) << ", "
        << format("%2d", WPREntry.ReleaseAtCycle) << ",  "
        << format("%2d", WPREntry.AcquireAtCycle) << "}";
-    if (WPRIdx + 1 < WPREnd)
+    if (WPRIdx < WPREnd && 1 < WPREnd - WPRIdx)
       OS << ',';
     OS << " // #" << WPRIdx << '\n';
   }
@@ -1364,7 +1364,7 @@ void 
SubtargetEmitter::emitSchedClassTables(SchedClassTables &SchedTables,
     MCWriteLatencyEntry &WLEntry = SchedTables.WriteLatencies[WLIdx];
     OS << "  {" << format("%2d", WLEntry.Cycles) << ", "
        << format("%2d", WLEntry.WriteResourceID) << "}";
-    if (WLIdx + 1 < WLEnd)
+    if (WLIdx < WLEnd && 1 < WLEnd - WLIdx)
       OS << ',';
     OS << " // #" << WLIdx << " " << SchedTables.WriterNames[WLIdx] << '\n';
   }
@@ -1381,7 +1381,7 @@ void 
SubtargetEmitter::emitSchedClassTables(SchedClassTables &SchedTables,
     OS << "  {" << RAEntry.UseIdx << ", "
        << format("%2d", RAEntry.WriteResourceID) << ", "
        << format("%2d", RAEntry.Cycles) << "}";
-    if (RAIdx + 1 < RAEnd)
+    if (RAIdx < RAEnd && 1 < RAEnd - RAIdx)
       OS << ',';
     OS << " // #" << RAIdx << '\n';
   }
diff --git a/mlir/lib/AsmParser/Parser.cpp b/mlir/lib/AsmParser/Parser.cpp
index 952d7e460c6e2..8c810042067cb 100644
--- a/mlir/lib/AsmParser/Parser.cpp
+++ b/mlir/lib/AsmParser/Parser.cpp
@@ -229,7 +229,7 @@ static size_t findCommentStart(StringRef line) {
     } else {
       if (c == '"') {
         inString = true;
-      } else if (c == '/' && i + 1 < e && line[i + 1] == '/') {
+      } else if (c == '/' && (i < e && 1 < e - i) && line[i + 1] == '/') {
         return i;
       }
     }
diff --git a/mlir/lib/AsmParser/Token.cpp b/mlir/lib/AsmParser/Token.cpp
index 5bf25bac6a5c6..90920d2ce4c1d 100644
--- a/mlir/lib/AsmParser/Token.cpp
+++ b/mlir/lib/AsmParser/Token.cpp
@@ -103,7 +103,8 @@ std::string Token::getStringValue() const {
       continue;
     }
 
-    assert(i + 1 <= e && "invalid string should be caught by lexer");
+    assert((i <= e && 1 <= e - i) &&
+           "invalid string should be caught by lexer");
     auto c1 = bytes[i++];
     switch (c1) {
     case '"':
@@ -120,7 +121,8 @@ std::string Token::getStringValue() const {
       break;
     }
 
-    assert(i + 1 <= e && "invalid string should be caught by lexer");
+    assert((i <= e && 1 <= e - i) &&
+           "invalid string should be caught by lexer");
     auto c2 = bytes[i++];
 
     assert(llvm::isHexDigit(c1) && llvm::isHexDigit(c2) && "invalid escape");
diff --git a/mlir/lib/Bytecode/Reader/BytecodeReader.cpp 
b/mlir/lib/Bytecode/Reader/BytecodeReader.cpp
index 96ead28d0aa40..265783f6be0f5 100644
--- a/mlir/lib/Bytecode/Reader/BytecodeReader.cpp
+++ b/mlir/lib/Bytecode/Reader/BytecodeReader.cpp
@@ -1339,7 +1339,8 @@ LogicalResult AttrTypeReader::initialize(
         return failure();
 
       // Verify that the offset is actually valid.
-      if (currentOffset + entrySize > sectionData.size()) {
+      if (currentOffset > sectionData.size() ||
+          entrySize > sectionData.size() - currentOffset) {
         return offsetReader.emitError(
             "Attribute or Type entry offset points past the end of section");
       }
diff --git a/mlir/lib/Dialect/Affine/Analysis/Utils.cpp 
b/mlir/lib/Dialect/Affine/Analysis/Utils.cpp
index cac305df8ba75..97b1ae412880c 100644
--- a/mlir/lib/Dialect/Affine/Analysis/Utils.cpp
+++ b/mlir/lib/Dialect/Affine/Analysis/Utils.cpp
@@ -2014,7 +2014,8 @@ AffineForOp mlir::affine::insertBackwardComputationSlice(
   // Sanity check.
   unsigned sliceSurroundingLoopsSize = sliceSurroundingLoops.size();
   (void)sliceSurroundingLoopsSize;
-  assert(dstLoopDepth + numSrcLoopIVs >= sliceSurroundingLoopsSize);
+  assert((dstLoopDepth >= sliceSurroundingLoopsSize ||
+          numSrcLoopIVs >= sliceSurroundingLoopsSize - dstLoopDepth));
   unsigned sliceLoopLimit = dstLoopDepth + numSrcLoopIVs;
   (void)sliceLoopLimit;
   assert(sliceLoopLimit >= sliceSurroundingLoopsSize);
diff --git a/mlir/lib/Dialect/Affine/IR/AffineOps.cpp 
b/mlir/lib/Dialect/Affine/IR/AffineOps.cpp
index f095500495f18..5fccb09816db8 100644
--- a/mlir/lib/Dialect/Affine/IR/AffineOps.cpp
+++ b/mlir/lib/Dialect/Affine/IR/AffineOps.cpp
@@ -5609,7 +5609,8 @@ struct CancelLinearizeOfDelinearizePortion final
 
       unsigned j = 1;
       unsigned numDelinOuts = delinearizeOp.getNumResults();
-      for (; j + linArgIdx < numLinArgs && j + delinArgIdx < numDelinOuts;
+      for (; (j < numLinArgs && linArgIdx < numLinArgs - j) &&
+             j + delinArgIdx < numDelinOuts;
            ++j) {
         if (multiIndex[linArgIdx + j] !=
             delinearizeOp.getResult(delinArgIdx + j))
diff --git a/mlir/lib/Dialect/Affine/Transforms/SimplifyAffineWithBounds.cpp 
b/mlir/lib/Dialect/Affine/Transforms/SimplifyAffineWithBounds.cpp
index f0c16a05a3070..b10ac3516724e 100644
--- a/mlir/lib/Dialect/Affine/Transforms/SimplifyAffineWithBounds.cpp
+++ b/mlir/lib/Dialect/Affine/Transforms/SimplifyAffineWithBounds.cpp
@@ -59,7 +59,8 @@ static std::optional<size_t> 
tryMatchProduct(ArrayRef<OpFoldResult> lhs,
   // Incrementally accumulate lhs product and check for equality.
   AffineExpr lhsExpr = getAffineConstantExpr(1, ctx);
   SmallVector<Value> lhsOperands;
-  for (size_t k = 1; k + lhsTailConsumed <= lhs.size(); ++k) {
+  for (size_t k = 1; (k <= lhs.size() && lhsTailConsumed <= lhs.size() - k);
+       ++k) {
     buildProductExpr(lhs[lhs.size() - lhsTailConsumed - k], lhsExpr,
                      lhsOperands, ctx);
     AffineMap lhsMap = AffineMap::get(0, lhsOperands.size(), lhsExpr, ctx);
diff --git a/mlir/lib/Dialect/LLVMIR/IR/BasicPtxBuilderInterface.cpp 
b/mlir/lib/Dialect/LLVMIR/IR/BasicPtxBuilderInterface.cpp
index 87206ba726765..cfcb8e8410d60 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/BasicPtxBuilderInterface.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/BasicPtxBuilderInterface.cpp
@@ -482,7 +482,7 @@ LLVM::InlineAsmOp PtxBuilder::build() {
   std::string mapped;
   mapped.reserve(ptxInstruction.size());
   for (size_t i = 0, e = ptxInstruction.size(); i < e; ++i) {
-    if (ptxInstruction[i] == '%' && i + 1 < e &&
+    if (ptxInstruction[i] == '%' && (i < e && 1 < e - i) &&
         llvm::isDigit(ptxInstruction[i + 1]))
       mapped.push_back('$');
     else
diff --git a/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp 
b/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp
index db46de75abd1a..7696e64519323 100644
--- a/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp
+++ b/mlir/lib/Dialect/Linalg/Transforms/ElementwiseOpFusion.cpp
@@ -1464,8 +1464,9 @@ getCollapsableIterationSpaceDims(GenericOp genericOp, 
OpOperand *fusableOperand,
           continue;
         // If sizes doesnt match, trivial not contiguous. This condition should
         // not be hit.
-        if (startDim.index() + foldedIterationSpaceDims.size() >
-            reductionDims.size())
+        if (startDim.index() > reductionDims.size() ||
+            foldedIterationSpaceDims.size() >
+                reductionDims.size() - startDim.index())
           break;
         // Check that the contiguity is maintained.
         isContiguous = true;
diff --git a/mlir/lib/Dialect/OpenACC/Utils/OpenACCUtilsTiling.cpp 
b/mlir/lib/Dialect/OpenACC/Utils/OpenACCUtilsTiling.cpp
index dddaebdee5ebc..7677674a1dd39 100644
--- a/mlir/lib/Dialect/OpenACC/Utils/OpenACCUtilsTiling.cpp
+++ b/mlir/lib/Dialect/OpenACC/Utils/OpenACCUtilsTiling.cpp
@@ -192,7 +192,7 @@ 
mlir::acc::tileACCLoops(llvm::SmallVector<mlir::acc::LoopOp> &tileLoops,
     llvm::SmallVector<mlir::Value, 3> currentLoopSteps;
     for (auto [j, step] : llvm::enumerate(tileLoop.getStep())) {
       origSteps.push_back(step);
-      if (i + j >= tileSizes.size()) {
+      if (i >= tileSizes.size() || j >= tileSizes.size() - i) {
         currentLoopSteps.push_back(step);
       } else {
         mlir::Value tileSize = resolveAndCastTileSize(
diff --git a/mlir/lib/Dialect/SPIRV/IR/ImageOps.cpp 
b/mlir/lib/Dialect/SPIRV/IR/ImageOps.cpp
index 43d94c86013b1..5430e7b33211f 100644
--- a/mlir/lib/Dialect/SPIRV/IR/ImageOps.cpp
+++ b/mlir/lib/Dialect/SPIRV/IR/ImageOps.cpp
@@ -51,7 +51,7 @@ static LogicalResult verifyImageOperands(Operation *imageOp,
       return imageOp->emitError(
           "Bias is only valid with implicit-lod instructions");
 
-    if (index + 1 > operands.size())
+    if (index > operands.size() || 1 > operands.size() - index)
       return imageOp->emitError("Bias operand requires 1 argument");
 
     if (!isCoreFloat(operands[index].getType()))
@@ -82,7 +82,7 @@ static LogicalResult verifyImageOperands(Operation *imageOp,
       return imageOp->emitError(
           "Lod is only valid with explicit-lod and fetch instructions");
 
-    if (index + 1 > operands.size())
+    if (index > operands.size() || 1 > operands.size() - index)
       return imageOp->emitError("Lod operand requires 1 argument");
 
     spirv::ImageType imageType;
@@ -124,7 +124,7 @@ static LogicalResult verifyImageOperands(Operation *imageOp,
       return imageOp->emitError(
           "Grad is only valid with explicit-lod instructions");
 
-    if (index + 2 > operands.size())
+    if (index > operands.size() || 2 > operands.size() - index)
       return imageOp->emitError(
           "Grad operand requires 2 arguments (scalars or vectors)");
 
diff --git a/mlir/lib/Dialect/SPIRV/Transforms/SPIRVWebGPUTransforms.cpp 
b/mlir/lib/Dialect/SPIRV/Transforms/SPIRVWebGPUTransforms.cpp
index f14632c7ff66c..348c03d822635 100644
--- a/mlir/lib/Dialect/SPIRV/Transforms/SPIRVWebGPUTransforms.cpp
+++ b/mlir/lib/Dialect/SPIRV/Transforms/SPIRVWebGPUTransforms.cpp
@@ -101,7 +101,7 @@ static Value lowerExtendedMultiplication(Operation *mulOp,
 
   for (auto [i, lhsDigit] : llvm::enumerate(lhsDigits)) {
     for (auto [j, rhsDigit] : llvm::enumerate(rhsDigits)) {
-      if (i + j >= resultDigits.size())
+      if (i >= resultDigits.size() || j >= resultDigits.size() - i)
         continue;
 
       if (lhsDigit == cst0 || rhsDigit == cst0)
diff --git a/mlir/lib/Dialect/Shard/IR/ShardOps.cpp 
b/mlir/lib/Dialect/Shard/IR/ShardOps.cpp
index ff790a0bf961d..6e2defaf49078 100644
--- a/mlir/lib/Dialect/Shard/IR/ShardOps.cpp
+++ b/mlir/lib/Dialect/Shard/IR/ShardOps.cpp
@@ -592,7 +592,8 @@ LogicalResult 
ShardingOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
           numShards += gridShape[i];
         }
         for (int64_t i = 0; i <= numShards; ++i) {
-          if (shardedDimsOffsets.size() <= pos + i) {
+          if (shardedDimsOffsets.size() <= pos ||
+              shardedDimsOffsets.size() - pos <= i) {
             return emitError() << "sharded dims offsets has wrong size.";
           }
           if (ShapedType::isStatic(shardedDimsOffsets[pos + i])) {
diff --git a/mlir/lib/IR/Remarks.cpp b/mlir/lib/IR/Remarks.cpp
index 273918171746d..1b9b9f7384fb0 100644
--- a/mlir/lib/IR/Remarks.cpp
+++ b/mlir/lib/IR/Remarks.cpp
@@ -61,7 +61,7 @@ static void printArgs(llvm::raw_ostream &os, 
llvm::ArrayRef<Remark::Arg> args) {
     else
       os << val;
 
-    if (i + 1 < sorted.size())
+    if (i < sorted.size() && 1 < sorted.size() - i)
       os << ", ";
   }
 }
diff --git a/mlir/lib/Tools/PDLL/Parser/Lexer.cpp 
b/mlir/lib/Tools/PDLL/Parser/Lexer.cpp
index cc111a095af5e..dc64f12d82645 100644
--- a/mlir/lib/Tools/PDLL/Parser/Lexer.cpp
+++ b/mlir/lib/Tools/PDLL/Parser/Lexer.cpp
@@ -40,7 +40,8 @@ std::string Token::getStringValue() const {
       continue;
     }
 
-    assert(i + 1 <= e && "invalid string should be caught by lexer");
+    assert((i <= e && 1 <= e - i) &&
+           "invalid string should be caught by lexer");
     auto c1 = bytes[i++];
     switch (c1) {
     case '"':
@@ -57,7 +58,8 @@ std::string Token::getStringValue() const {
       break;
     }
 
-    assert(i + 1 <= e && "invalid string should be caught by lexer");
+    assert((i <= e && 1 <= e - i) &&
+           "invalid string should be caught by lexer");
     auto c2 = bytes[i++];
 
     assert(llvm::isHexDigit(c1) && llvm::isHexDigit(c2) && "invalid escape");
diff --git a/mlir/tools/mlir-tblgen/AttrOrTypeFormatGen.cpp 
b/mlir/tools/mlir-tblgen/AttrOrTypeFormatGen.cpp
index d8778c6f59d28..cb6233253e80d 100644
--- a/mlir/tools/mlir-tblgen/AttrOrTypeFormatGen.cpp
+++ b/mlir/tools/mlir-tblgen/AttrOrTypeFormatGen.cpp
@@ -948,13 +948,13 @@ void DefFormat::genStructPrinter(StructDirective *el, 
FmtContext &ctx,
         os << tgfmt("$_printer << \"$0 = \";\n", &ctx, param->getName());
         auto *paramEl = dyn_cast<ParameterElement>(arg);
         if (paramEl && isUndelimitedArrayRefParam(paramEl) &&
-            elemIdx + 1 < elems.size())
+            (elemIdx < elems.size() && 1 < elems.size() - elemIdx))
           os << tgfmt("$_printer << \"[\";\n", &ctx);
       },
       [&](FormatElement *arg) {
         auto *paramEl = dyn_cast<ParameterElement>(arg);
         if (paramEl && isUndelimitedArrayRefParam(paramEl) &&
-            elemIdx + 1 < elems.size())
+            (elemIdx < elems.size() && 1 < elems.size() - elemIdx))
           os << tgfmt("$_printer << \"]\";\n", &ctx);
         ++elemIdx;
       });
diff --git a/mlir/unittests/Dialect/SPIRV/SerializationTest.cpp 
b/mlir/unittests/Dialect/SPIRV/SerializationTest.cpp
index b0413a8e994ba..bc40e7b90a0f9 100644
--- a/mlir/unittests/Dialect/SPIRV/SerializationTest.cpp
+++ b/mlir/unittests/Dialect/SPIRV/SerializationTest.cpp
@@ -250,7 +250,8 @@ bool hasOpcode(SmallVectorImpl<uint32_t> &binary, 
spirv::Opcode target) {
   size_t offset = spirv::kHeaderWordCount;
   while (offset < binary.size()) {
     uint32_t wordCount = binary[offset] >> 16;
-    if (!wordCount || offset + wordCount > binary.size())
+    if (!wordCount ||
+        (offset > binary.size() || wordCount > binary.size() - offset))
       return false;
     auto op = static_cast<spirv::Opcode>(binary[offset] & 0xffff);
     if (op == target)
@@ -268,7 +269,7 @@ bool hasLongCompositesCapabilityAndExtension(
   size_t binarySize = binary.size();
   while (offset < binarySize) {
     uint32_t wordCount = binary[offset] >> 16;
-    if (!wordCount || offset + wordCount > binarySize)
+    if (!wordCount || (offset > binarySize || wordCount > binarySize - offset))
       break;
     auto op = static_cast<spirv::Opcode>(binary[offset] & 0xffff);
     ArrayRef<uint32_t> operands(binary.data() + offset + 1, wordCount - 1);
@@ -516,7 +517,7 @@ unsigned countOpcode(SmallVectorImpl<uint32_t> &binary, 
spirv::Opcode target) {
   size_t binarySize = binary.size();
   while (offset < binarySize) {
     uint32_t wordCount = binary[offset] >> 16;
-    if (!wordCount || offset + wordCount > binarySize)
+    if (!wordCount || (offset > binarySize || wordCount > binarySize - offset))
       break;
     auto op = static_cast<spirv::Opcode>(binary[offset] & 0xffff);
     if (op == target)

>From 1d774784a45a2cb70c54c238fe2de9e980f21d0b Mon Sep 17 00:00:00 2001
From: Harald-R <[email protected]>
Date: Mon, 29 Jun 2026 14:26:00 +0300
Subject: [PATCH 2/2] Avoid warnings for comparison of integers of different
 signs

---
 clang/lib/AST/ExprConstant.cpp         | 2 +-
 llvm/tools/llvm-objdump/MachODump.cpp  | 6 ++++--
 mlir/lib/Dialect/Shard/IR/ShardOps.cpp | 2 +-
 3 files changed, 6 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5fdcc36d99c9e..dc2c08fd3b71b 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2093,7 +2093,7 @@ static bool ArePotentiallyOverlappingStringLiterals(const 
EvalInfo &Info,
   // The null terminator isn't included in the string data, so check for it
   // manually. If the longer string doesn't have a null terminator where the
   // shorter string ends, they aren't potentially overlapping.
-  for (int NullByte : llvm::seq(ShorterCharWidth)) {
+  for (size_t NullByte : llvm::seq(ShorterCharWidth)) {
     if (Shorter.size() >= Longer.size() ||
         NullByte >= Longer.size() - Shorter.size())
       break;
diff --git a/llvm/tools/llvm-objdump/MachODump.cpp 
b/llvm/tools/llvm-objdump/MachODump.cpp
index a1efc26c280f0..a6692d520b8eb 100644
--- a/llvm/tools/llvm-objdump/MachODump.cpp
+++ b/llvm/tools/llvm-objdump/MachODump.cpp
@@ -7879,7 +7879,8 @@ namespace {
 
 template <typename T>
 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
-  if (Offset > Contents.size() || sizeof(T) > Contents.size() - Offset) {
+  if (Offset > static_cast<ptrdiff_t>(Contents.size()) ||
+      sizeof(T) > Contents.size() - Offset) {
     outs() << "warning: attempt to read past end of buffer\n";
     return T();
   }
@@ -8318,7 +8319,8 @@ static void printMachOUnwindInfoSection(const 
MachOObjectFile *Obj,
            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
 
     Pos = IndexEntries[i].SecondLevelPageStart;
-    if (Pos > Contents.size() || sizeof(uint32_t) > Contents.size() - Pos) {
+    if (Pos > static_cast<ptrdiff_t>(Contents.size()) ||
+        sizeof(uint32_t) > Contents.size() - Pos) {
       outs() << "warning: invalid offset for second level page: " << Pos << 
'\n';
       continue;
     }
diff --git a/mlir/lib/Dialect/Shard/IR/ShardOps.cpp 
b/mlir/lib/Dialect/Shard/IR/ShardOps.cpp
index 6e2defaf49078..5953a40e92ad1 100644
--- a/mlir/lib/Dialect/Shard/IR/ShardOps.cpp
+++ b/mlir/lib/Dialect/Shard/IR/ShardOps.cpp
@@ -591,7 +591,7 @@ LogicalResult 
ShardingOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
         for (auto i : innerSplitAxes.asArrayRef()) {
           numShards += gridShape[i];
         }
-        for (int64_t i = 0; i <= numShards; ++i) {
+        for (size_t i = 0; i <= static_cast<size_t>(numShards); ++i) {
           if (shardedDimsOffsets.size() <= pos ||
               shardedDimsOffsets.size() - pos <= i) {
             return emitError() << "sharded dims offsets has wrong size.";

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to