[clang] [clang] Improve getFileIDLocal binary search. (PR #146510)
Erich Keane via cfe-commits
cfe-commits at lists.llvm.org
Tue Jul 1 08:27:31 PDT 2025
================
@@ -855,35 +857,24 @@ FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
break;
}
- NumProbes = 0;
- while (true) {
- unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
- SourceLocation::UIntTy MidOffset =
- getLocalSLocEntry(MiddleIndex).getOffset();
-
- ++NumProbes;
-
- // If the offset of the midpoint is too large, chop the high side of the
- // range to the midpoint.
- if (MidOffset > SLocOffset) {
- GreaterIndex = MiddleIndex;
- continue;
- }
+ while (LessIndex < GreaterIndex) {
+ ++NumBinaryProbes;
- // If the middle index contains the value, succeed and return.
- if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
- SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
- FileID Res = FileID::get(MiddleIndex);
+ unsigned MiddleIndex = LessIndex + (GreaterIndex - LessIndex) / 2;
- // Remember it. We have good locality across FileID lookups.
- LastFileIDLookup = Res;
- NumBinaryProbes += NumProbes;
- return Res;
- }
+ SourceLocation::UIntTy MidOffset =
+ LocalSLocEntryTable[MiddleIndex].getOffset();
- // Otherwise, move the low-side up to the middle index.
- LessIndex = MiddleIndex;
+ if (MidOffset <= SLocOffset)
----------------
erichkeane wrote:
Ah, hrmph.... I guess I see here. I guess that the 'we just managed to be searching for the very beginning of this file' is rare enough to not be worth a branch.
Though, is this safe (the +1/-1 dance)with 'GreaterIndex'? Despite its name, GreaterIndex is initialized to the 'size' (so not really an index... *sigh*). Though I guess the linear search ensures we've already checked the end....
I think I've convinced myself this is right enough. Thanks.
https://github.com/llvm/llvm-project/pull/146510
More information about the cfe-commits
mailing list