Skip to content

Commit 86eca47

Browse files
committed
[clang] Improve getFileIDLocal binary search. (llvm#146510)
Avoid reading the `LocalSLocEntryTable` twice per loop iteration. NFC. https://llvm-compile-time-tracker.com/compare.php?from=0b6ddb02efdcbdac9426e8d857499ea0580303cd&to=1aa335ccfb07ba96177b89b1933aa6b980fa14f6&stat=instructions:u
1 parent 960aaa4 commit 86eca47

File tree

1 file changed

+16
-25
lines changed

1 file changed

+16
-25
lines changed

clang/lib/Basic/SourceManager.cpp

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -812,6 +812,8 @@ FileID SourceManager::getFileIDSlow(SourceLocation::UIntTy SLocOffset) const {
812812
/// loaded one.
813813
FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
814814
assert(SLocOffset < NextLocalOffset && "Bad function choice");
815+
assert(SLocOffset >= LocalSLocEntryTable[0].getOffset() &&
816+
"Invalid SLocOffset");
815817

816818
// After the first and second level caches, I see two common sorts of
817819
// behavior: 1) a lot of searched FileID's are "near" the cached file
@@ -855,35 +857,24 @@ FileID SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
855857
break;
856858
}
857859

858-
NumProbes = 0;
859-
while (true) {
860-
unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
861-
SourceLocation::UIntTy MidOffset =
862-
getLocalSLocEntry(MiddleIndex).getOffset();
863-
864-
++NumProbes;
865-
866-
// If the offset of the midpoint is too large, chop the high side of the
867-
// range to the midpoint.
868-
if (MidOffset > SLocOffset) {
869-
GreaterIndex = MiddleIndex;
870-
continue;
871-
}
860+
while (LessIndex < GreaterIndex) {
861+
++NumBinaryProbes;
872862

873-
// If the middle index contains the value, succeed and return.
874-
if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
875-
SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
876-
FileID Res = FileID::get(MiddleIndex);
863+
unsigned MiddleIndex = LessIndex + (GreaterIndex - LessIndex) / 2;
877864

878-
// Remember it. We have good locality across FileID lookups.
879-
LastFileIDLookup = Res;
880-
NumBinaryProbes += NumProbes;
881-
return Res;
882-
}
865+
SourceLocation::UIntTy MidOffset =
866+
LocalSLocEntryTable[MiddleIndex].getOffset();
883867

884-
// Otherwise, move the low-side up to the middle index.
885-
LessIndex = MiddleIndex;
868+
if (MidOffset <= SLocOffset)
869+
LessIndex = MiddleIndex + 1;
870+
else
871+
GreaterIndex = MiddleIndex;
886872
}
873+
874+
// At this point, LessIndex is the index of the *first element greater than*
875+
// SLocOffset. The element we are actually looking for is the one immediately
876+
// before it.
877+
return LastFileIDLookup = FileID::get(LessIndex - 1);
887878
}
888879

889880
/// Return the FileID for a SourceLocation with a high offset.

0 commit comments

Comments
 (0)