Skip to content

Commit 87c92cd

Browse files
Martin Sebortru
authored andcommitted
[InstCombine] Correct strtol folding with nonnull endptr
Reflect in the pointer's offset the length of the leading part of the consumed string preceding the first converted digit. Reviewed By: efriedma Differential Revision: https://reviews.llvm.org/D130912 (cherry picked from commit bcef4d2)
1 parent b630baf commit 87c92cd

File tree

3 files changed

+147
-103
lines changed

3 files changed

+147
-103
lines changed

llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,12 @@ static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr,
8989
// Fail for an invalid base (required by POSIX).
9090
return nullptr;
9191

92+
// Current offset into the original string to reflect in EndPtr.
93+
size_t Offset = 0;
9294
// Strip leading whitespace.
93-
for (unsigned i = 0; i != Str.size(); ++i)
94-
if (!isSpace((unsigned char)Str[i])) {
95-
Str = Str.substr(i);
95+
for ( ; Offset != Str.size(); ++Offset)
96+
if (!isSpace((unsigned char)Str[Offset])) {
97+
Str = Str.substr(Offset);
9698
break;
9799
}
98100

@@ -108,6 +110,7 @@ static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr,
108110
if (Str.empty())
109111
// Fail for a sign with nothing after it.
110112
return nullptr;
113+
++Offset;
111114
}
112115

113116
// Set Max to the absolute value of the minimum (for signed), or
@@ -127,6 +130,7 @@ static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr,
127130
return nullptr;
128131

129132
Str = Str.drop_front(2);
133+
Offset += 2;
130134
Base = 16;
131135
}
132136
else if (Base == 0)
@@ -167,7 +171,7 @@ static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr,
167171

168172
if (EndPtr) {
169173
// Store the pointer to the end.
170-
Value *Off = B.getInt64(Str.size());
174+
Value *Off = B.getInt64(Offset + Str.size());
171175
Value *StrBeg = CI->getArgOperand(0);
172176
Value *StrEnd = B.CreateInBoundsGEP(B.getInt8Ty(), StrBeg, Off, "endptr");
173177
B.CreateStore(StrEnd, EndPtr);

0 commit comments

Comments
 (0)