Skip to content

Commit

Permalink
[clang][ubsan] Switch UBSAN optimization to `llvm.allow.{runtime,ubsa…
Browse files Browse the repository at this point in the history
…n}.check()` (#84858)

Intrinsic introduced with #84850. Intrinsics improves performance
by 3% comparing to removing traps (on
"test-suite/MultiSource/Benchmarks" with PGO+ThinLTO).

The pass will be renamed with #84853.

RFC:
https://discourse.llvm.org/t/rfc-add-llvm-experimental-hot-intrinsic-or-llvm-hot/77641
  • Loading branch information
vitalybuka committed Apr 5, 2024
1 parent cfadf3f commit a9d9387
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 72 deletions.
37 changes: 0 additions & 37 deletions clang/test/CodeGen/remote-traps.c

This file was deleted.

27 changes: 17 additions & 10 deletions llvm/lib/Transforms/Instrumentation/RemoveTrapsPass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
Expand All @@ -35,9 +36,11 @@ STATISTIC(NumChecksRemoved, "Number of removed checks");

static bool removeUbsanTraps(Function &F, const BlockFrequencyInfo &BFI,
const ProfileSummaryInfo *PSI) {
SmallVector<IntrinsicInst *, 16> Remove;
SmallVector<std::pair<IntrinsicInst *, bool>, 16> ReplaceWithValue;
std::unique_ptr<RandomNumberGenerator> Rng;

// TODO:
// https://github.com/llvm/llvm-project/pull/84858#discussion_r1520603139
auto ShouldRemove = [&](bool IsHot) {
if (!RandomRate.getNumOccurrences())
return IsHot;
Expand All @@ -54,21 +57,23 @@ static bool removeUbsanTraps(Function &F, const BlockFrequencyInfo &BFI,
continue;
auto ID = II->getIntrinsicID();
switch (ID) {
case Intrinsic::ubsantrap: {
case Intrinsic::allow_ubsan_check:
case Intrinsic::allow_runtime_check: {
++NumChecksTotal;

bool IsHot = false;
if (PSI) {
uint64_t Count = 0;
for (const auto *PR : predecessors(&BB))
Count += BFI.getBlockProfileCount(PR).value_or(0);
uint64_t Count = BFI.getBlockProfileCount(&BB).value_or(0);
IsHot = PSI->isHotCountNthPercentile(HotPercentileCutoff, Count);
}

if (ShouldRemove(IsHot)) {
Remove.push_back(II);
bool ToRemove = ShouldRemove(IsHot);
ReplaceWithValue.push_back({
II,
ToRemove,
});
if (ToRemove)
++NumChecksRemoved;
}
break;
}
default:
Expand All @@ -77,10 +82,12 @@ static bool removeUbsanTraps(Function &F, const BlockFrequencyInfo &BFI,
}
}

for (IntrinsicInst *I : Remove)
for (auto [I, V] : ReplaceWithValue) {
I->replaceAllUsesWith(ConstantInt::getBool(I->getType(), !V));
I->eraseFromParent();
}

return !Remove.empty();
return !ReplaceWithValue.empty();
}

PreservedAnalyses RemoveTrapsPass::run(Function &F,
Expand Down

0 comments on commit a9d9387

Please sign in to comment.