llvmorg-github-actions[bot] wrote:

<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-compiler-rt-sanitizer

@llvm/pr-subscribers-llvm-transforms

Author: Joseph Huber (jhuber6)

<details>
<summary>Changes</summary>

Summary:
This adds a `-csan-minimal` flag. Accesses are checked with an inlined
value comparison, and the runtime is reduced to race reporting. The
result is the smallest instrumentation that still detects races, at
the cost of coverage.


---

Patch is 50.02 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/244727.diff


13 Files Affected:

- (modified) clang/docs/ConcurrencySanitizer.md (+3-1) 
- (added) clang/test/CodeGen/csan-minimal.c (+28) 
- (modified) compiler-rt/lib/csan/csan.cpp (+18) 
- (modified) compiler-rt/lib/csan/csan_gpu.cpp (+10) 
- (modified) llvm/include/llvm/Analysis/TargetLibraryInfo.td (+3) 
- (modified) llvm/lib/Analysis/TargetLibraryInfo.cpp (+8) 
- (modified) llvm/lib/Transforms/Instrumentation/ConcurrencySanitizer.cpp 
(+221-8) 
- (modified) llvm/lib/Transforms/Utils/BuildLibCalls.cpp (+8) 
- (added) llvm/test/Instrumentation/ConcurrencySanitizer/minimal.ll (+485) 
- (added) llvm/test/Instrumentation/ConcurrencySanitizer/minimal_target.ll 
(+82) 
- (modified) llvm/test/Transforms/InferFunctionAttrs/annotate.ll (+6) 
- (modified) llvm/test/Transforms/InferFunctionAttrs/no-proto.ll (+3) 
- (modified) llvm/unittests/Analysis/TargetLibraryInfoTest.cpp (+1) 


``````````diff
diff --git a/clang/docs/ConcurrencySanitizer.md 
b/clang/docs/ConcurrencySanitizer.md
index 5a9d2b1edabbcb..aa9ba6433c02a7 100644
--- a/clang/docs/ConcurrencySanitizer.md
+++ b/clang/docs/ConcurrencySanitizer.md
@@ -119,7 +119,9 @@ void check_access(volatile void *addr, u32 size, u32 type) {
 
 The probability of detecting a race and the overhead of the sanitizer is
 directly related to the probability of sampling and the length of the delay. 
The
-watchpoint table can be omitted to make a minimal detector with less coverage.
+minimal configuration, selected with `-mllvm -csan-minimal`, inlines the value
+comparison and reduces the runtime to race reporting. This trades race coverage
+for a smaller runtime.
 
 ## `__SANITIZE_CONCURRENCY__`
 
diff --git a/clang/test/CodeGen/csan-minimal.c 
b/clang/test/CodeGen/csan-minimal.c
new file mode 100644
index 00000000000000..143132fc1442c2
--- /dev/null
+++ b/clang/test/CodeGen/csan-minimal.c
@@ -0,0 +1,28 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 6
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -emit-llvm -fsanitize=concurrency 
-mllvm -csan-minimal -o - %s | FileCheck %s
+
+// CHECK-LABEL: define dso_local i32 @instrumented(
+// CHECK-SAME: ptr noundef [[A:%.*]]) #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  [[ENTRY:.*:]]
+// CHECK-NEXT:    [[A_ADDR:%.*]] = alloca ptr, align 8
+// CHECK-NEXT:    store ptr [[A]], ptr [[A_ADDR]], align 8
+// CHECK-NEXT:    [[TMP0:%.*]] = load ptr, ptr [[A_ADDR]], align 8
+// CHECK-NEXT:    [[CSAN_OLD:%.*]] = load volatile i32, ptr [[TMP0]], align 4, 
!nosanitize [[META2:![0-9]+]]
+// CHECK-NEXT:    [[TMP1:%.*]] = call i32 @usleep(i32 80)
+// CHECK-NEXT:    [[CSAN_NEW:%.*]] = load volatile i32, ptr [[TMP0]], align 4, 
!nosanitize [[META2]]
+// CHECK-NEXT:    [[CSAN_CHANGED:%.*]] = icmp ne i32 [[CSAN_OLD]], [[CSAN_NEW]]
+// CHECK-NEXT:    br i1 [[CSAN_CHANGED]], label %[[BB2:.*]], label %[[BB3:.*]]
+// CHECK:       [[BB2]]:
+// CHECK-NEXT:    call void @__csan_report_race(ptr [[TMP0]], i64 4, i32 0)
+// CHECK-NEXT:    br label %[[BB3]]
+// CHECK:       [[BB3]]:
+// CHECK-NEXT:    fence syncscope("singlethread") acq_rel
+// CHECK-NEXT:    [[TMP4:%.*]] = load i32, ptr [[TMP0]], align 4
+// CHECK-NEXT:    ret i32 [[TMP4]]
+//
+int instrumented(int *a) {
+  return *a;
+}
+//.
+// CHECK: [[META2]] = !{}
+//.
diff --git a/compiler-rt/lib/csan/csan.cpp b/compiler-rt/lib/csan/csan.cpp
index 0925b6beba3542..9290de14446ac1 100644
--- a/compiler-rt/lib/csan/csan.cpp
+++ b/compiler-rt/lib/csan/csan.cpp
@@ -233,6 +233,19 @@ NOINLINE static void SetupWatchpoint(const volatile void 
*Ptr, uptr Size,
   GetHostWatchpoints().Remove(WP);
 }
 
+static void ReportRace(const volatile void *Ptr, uptr Size, int Type, uptr PC,
+                       uptr BP) {
+  if (UNLIKELY(!Ptr || !Size))
+    return;
+  Initialize();
+  if (UNLIKELY(DisableCount))
+    return;
+  ScopedDisable Disable;
+  const AccessInfo AI = MakeAccessInfo(Ptr, Size, Type, PC, BP);
+  // Equal values suppress the value-change line; the caller already compared.
+  ReportUnknownOrigin(AI, 0, 0);
+}
+
 ALWAYS_INLINE static void CheckAccess(const volatile void *Ptr, uptr Size,
                                       int Type, uptr PC, uptr BP) {
   if (UNLIKELY(!Ptr || !Size))
@@ -325,6 +338,11 @@ INTERFACE void __csan_write_range(void *Addr, uptr Size, 
int Flags) {
   __csan::CheckAccess(Addr, Size, AccessFlags(Flags, true), pc, bp);
 }
 
+INTERFACE NOINLINE void __csan_report_race(void *Addr, uptr Size, int Type) {
+  GET_CALLER_PC_BP;
+  __csan::ReportRace(Addr, Size, Type, pc, bp);
+}
+
 // TODO: Handle thread reordering checks like KCSAN.
 INTERFACE void __csan_atomic_thread_fence(int) {}
 INTERFACE void __csan_atomic_signal_fence(int) {}
diff --git a/compiler-rt/lib/csan/csan_gpu.cpp 
b/compiler-rt/lib/csan/csan_gpu.cpp
index cd881dd3362a2a..690fe66d4a5bb9 100644
--- a/compiler-rt/lib/csan/csan_gpu.cpp
+++ b/compiler-rt/lib/csan/csan_gpu.cpp
@@ -452,5 +452,15 @@ INTERFACE void __csan_write_range(void *addr, uptr size, 
int flags) {
   check_access(addr, size, access_flags(flags, true), GET_CALLER_PC());
 }
 
+INTERFACE NOINLINE void __csan_report_race(void *addr, uptr size,
+                                           int access_type) {
+  const uptr pc = GET_CALLER_PC();
+  if (!addr || !size)
+    return;
+  const u32 report_size = size > ~u32(0) ? ~u32(0) : static_cast<u32>(size);
+  report(CSAN_RACE_UNKNOWN_ORIGIN, reinterpret_cast<uptr>(addr), report_size,
+         access_type, pc);
+}
+
 INTERFACE void __csan_atomic_thread_fence(int) {}
 INTERFACE void __csan_atomic_signal_fence(int) {}
diff --git a/llvm/include/llvm/Analysis/TargetLibraryInfo.td 
b/llvm/include/llvm/Analysis/TargetLibraryInfo.td
index beaa5d1a69a0a8..1f5788789f6a5f 100644
--- a/llvm/include/llvm/Analysis/TargetLibraryInfo.td
+++ b/llvm/include/llvm/Analysis/TargetLibraryInfo.td
@@ -1649,6 +1649,9 @@ def unlink : TargetLibCall<"unlink", Int, [Ptr]>;
 /// int unsetenv(const char *name);
 def unsetenv : TargetLibCall<"unsetenv", Int, [Ptr]>;
 
+/// int usleep(useconds_t useconds);
+def usleep : TargetLibCall<"usleep", Int, [Int]>;
+
 /// int utime(const char *path, const struct utimbuf *times);
 def utime : TargetLibCall<"utime", Int, [Ptr, Ptr]>;
 
diff --git a/llvm/lib/Analysis/TargetLibraryInfo.cpp 
b/llvm/lib/Analysis/TargetLibraryInfo.cpp
index 30c9ecc35700e7..a88cd34055ac8f 100644
--- a/llvm/lib/Analysis/TargetLibraryInfo.cpp
+++ b/llvm/lib/Analysis/TargetLibraryInfo.cpp
@@ -159,6 +159,9 @@ static void initializeLibCalls(TargetLibraryInfoImpl &TLI, 
const Triple &T,
   TLI.setUnavailable(LibFunc_fputs_unlocked);
   TLI.setUnavailable(LibFunc_fgets_unlocked);
 
+  // POSIX usleep. Enabled below for hosted libcs that provide it.
+  TLI.setUnavailable(LibFunc_usleep);
+
   // There is really no runtime library on AMDGPU.
   if (T.isAMDGPU()) {
     TLI.disableAllFunctions();
@@ -708,6 +711,11 @@ static void initializeLibCalls(TargetLibraryInfoImpl &TLI, 
const Triple &T,
     TLI.setAvailable(LibFunc_fgets_unlocked);
   }
 
+  if (T.isOSLinux() || T.isOSDarwin() || T.isOSFreeBSD() || T.isOSNetBSD() ||
+      T.isOSOpenBSD() || T.isOSDragonFly() || T.isOSSolaris() || T.isOSAIX() ||
+      T.isOSHaiku() || T.isWindowsCygwinEnvironment())
+    TLI.setAvailable(LibFunc_usleep);
+
   if (T.isPS()) {
     // PS4/PS5 do have memalign.
     TLI.setAvailable(LibFunc_memalign);
diff --git a/llvm/lib/Transforms/Instrumentation/ConcurrencySanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/ConcurrencySanitizer.cpp
index 995dc45c272543..f93def8aa4b737 100644
--- a/llvm/lib/Transforms/Instrumentation/ConcurrencySanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/ConcurrencySanitizer.cpp
@@ -26,6 +26,8 @@
 #include "llvm/IR/Instructions.h"
 #include "llvm/IR/IntrinsicInst.h"
 #include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/IntrinsicsAMDGPU.h"
+#include "llvm/IR/IntrinsicsNVPTX.h"
 #include "llvm/IR/Module.h"
 #include "llvm/ProfileData/InstrProf.h"
 #include "llvm/Support/AMDGPUAddrSpace.h"
@@ -33,6 +35,8 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/NVPTXAddrSpace.h"
 #include "llvm/TargetParser/Triple.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/BuildLibCalls.h"
 #include "llvm/Transforms/Utils/EscapeEnumerator.h"
 #include "llvm/Transforms/Utils/Instrumentation.h"
 #include "llvm/Transforms/Utils/Local.h"
@@ -65,6 +69,10 @@ static cl::opt<bool> ClDistinguishVolatile(
     "csan-distinguish-volatile", cl::init(false),
     cl::desc("Treat aligned volatile accesses up to 8 bytes as atomic"),
     cl::Hidden);
+static cl::opt<bool>
+    ClMinimal("csan-minimal", cl::init(false),
+              cl::desc("Inline value checks with a report-only runtime"),
+              cl::Hidden);
 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
 STATISTIC(NumOmittedReadsBeforeWrite,
@@ -104,7 +112,8 @@ enum class AccessFlags : unsigned {
   None = 0,
   Atomic = 1u << 0,
   Compound = 1u << 1,
-  LLVM_MARK_AS_BITMASK_ENUM(Compound),
+  Write = 1u << 2,
+  LLVM_MARK_AS_BITMASK_ENUM(Write),
 };
 
 static bool isAtomicMemoryAccess(const Instruction *I) {
@@ -202,6 +211,13 @@ struct ConcurrencySanitizer {
   bool insertAccessProbe(Instruction *I, Value *Addr, Type *AccessTy,
                          const DataLayout &DL, bool IsWrite, bool IsCompound,
                          bool IsAtomic);
+  bool insertTypedValueCheck(Instruction *I, Value *Addr, Type *AccessTy,
+                             const DataLayout &DL, bool IsWrite);
+  bool insertRangeValueCheck(Instruction *I, Value *Addr, Value *ByteSize,
+                             bool IsWrite);
+  bool emitValueCheck(Instruction *I, Value *Addr, Type *LoadTy,
+                      Value *ByteSize, Align Alignment, bool IsWrite);
+  void insertInlineDelay(Instruction *InsertBefore);
   bool shouldInstrumentAddress(Value *Addr) const;
   bool shouldInstrumentAccess(Instruction *I) const;
   void insertFuncEntryExit(Function &F);
@@ -211,6 +227,7 @@ struct ConcurrencySanitizer {
   }
 
   Module *Mod = nullptr;
+  const TargetLibraryInfo *LibInfo = nullptr;
   Type *IntptrTy = nullptr;
   IntegerType *FlagsTy = nullptr;
 
@@ -242,6 +259,8 @@ struct ConcurrencySanitizer {
   FunctionCallee CsanAtomicThreadFence;
   // void __csan_atomic_signal_fence(i32);
   FunctionCallee CsanAtomicSignalFence;
+  // void __csan_report_race(ptr, intptr, i32);
+  FunctionCallee CsanReportRace;
 };
 
 void insertModuleCtor(Module &M) {
@@ -279,6 +298,10 @@ void ConcurrencySanitizer::initialize(Module &M, const 
TargetLibraryInfo &TLI) {
   IRBuilder<> IRB(M);
   Type *VoidTy = IRB.getVoidTy();
   Type *PtrTy = IRB.getPtrTy();
+  AttributeList ReportAttrs = Attr.addFnAttribute(Ctx, Attribute::NoInline)
+                                  .addFnAttribute(Ctx, Attribute::Cold);
+  CsanReportRace = M.getOrInsertFunction("__csan_report_race", ReportAttrs,
+                                         VoidTy, PtrTy, IntptrTy, FlagsTy);
   CsanFuncEntry =
       M.getOrInsertFunction("__csan_func_entry", Attr, VoidTy, PtrTy);
   CsanFuncExit = M.getOrInsertFunction("__csan_func_exit", Attr, VoidTy);
@@ -330,6 +353,7 @@ bool ConcurrencySanitizer::sanitizeFunction(Function &F,
     return false;
 
   Mod = F.getParent();
+  LibInfo = &TLI;
   MemoryAccessLists Acc;
   collectMemoryAccesses(F, Acc);
 
@@ -337,13 +361,16 @@ bool ConcurrencySanitizer::sanitizeFunction(Function &F,
       F.hasFnAttribute("sanitize_concurrency_no_checking_at_run_time");
   const bool SanitizeFunction =
       F.hasFnAttribute(Attribute::SanitizeConcurrency) && !SuppressChecking;
+  const bool CheckAtomics = ClInstrumentAtomics && !ClMinimal;
   const bool MayInstrument =
       SanitizeFunction &&
       ((ClInstrumentMemoryAccesses && !Acc.LoadsAndStores.empty()) ||
-       (ClInstrumentAtomics && !Acc.AtomicAccesses.empty()) ||
+       (CheckAtomics && !Acc.AtomicAccesses.empty()) ||
        (ClInstrumentMemIntrinsics && !Acc.MemIntrinCalls.empty()));
-  const bool NeedsRuntimeIgnores = SuppressChecking && Acc.HasCalls;
-  const bool NeedsFuncEntryExit = ClInstrumentFuncEntryExit && Acc.HasCalls;
+  const bool NeedsRuntimeIgnores =
+      SuppressChecking && Acc.HasCalls && !ClMinimal;
+  const bool NeedsFuncEntryExit =
+      ClInstrumentFuncEntryExit && Acc.HasCalls && !ClMinimal;
   if (!MayInstrument && !NeedsRuntimeIgnores && !NeedsFuncEntryExit)
     return false;
 
@@ -355,7 +382,7 @@ bool ConcurrencySanitizer::sanitizeFunction(Function &F,
     for (Instruction *I : Acc.LoadsAndStores)
       Res |= instrumentLoadOrStore(I, DL);
 
-  if (ClInstrumentAtomics && SanitizeFunction)
+  if (CheckAtomics && SanitizeFunction)
     for (Instruction *I : Acc.AtomicAccesses)
       Res |= instrumentAtomic(I, DL);
 
@@ -368,7 +395,7 @@ bool ConcurrencySanitizer::sanitizeFunction(Function &F,
     Res = true;
   }
 
-  if ((Res || Acc.HasCalls) && ClInstrumentFuncEntryExit) {
+  if (!ClMinimal && (Res || Acc.HasCalls) && ClInstrumentFuncEntryExit) {
     insertFuncEntryExit(F);
     Res = true;
   }
@@ -442,9 +469,14 @@ bool 
ConcurrencySanitizer::instrumentLoadOrStore(Instruction *I,
                                                  const DataLayout &DL) {
   const bool IsWrite = isa<StoreInst>(I);
   Value *Addr = getLoadStorePointerOperand(I);
-  if (!insertAccessProbe(I, Addr, getLoadStoreType(I), DL, IsWrite,
-                         /*IsCompound=*/false, /*IsAtomic=*/false))
+  Type *AccessTy = getLoadStoreType(I);
+  if (ClMinimal) {
+    if (!insertTypedValueCheck(I, Addr, AccessTy, DL, IsWrite))
+      return false;
+  } else if (!insertAccessProbe(I, Addr, AccessTy, DL, IsWrite,
+                                /*IsCompound=*/false, /*IsAtomic=*/false)) {
     return false;
+  }
   if (IsWrite)
     ++NumInstrumentedWrites;
   else
@@ -521,6 +553,22 @@ bool 
ConcurrencySanitizer::instrumentMemIntrinsic(IntrinsicInst *II,
     TypeSize Size = DL.getTypeAllocSize(MSP->getValue()->getType());
     Len = IRB.CreateMul(Len, IRB.CreateTypeSize(IntptrTy, Size));
   }
+  if (ClMinimal) {
+    if (MI && MI->isAtomic())
+      return false;
+    bool Changed = false;
+    if (InstrumentRead &&
+        insertRangeValueCheck(II, Src, Len, /*IsWrite=*/false)) {
+      ++NumInstrumentedReads;
+      Changed = true;
+    }
+    if (InstrumentWrite &&
+        insertRangeValueCheck(II, Dst, Len, /*IsWrite=*/true)) {
+      ++NumInstrumentedWrites;
+      Changed = true;
+    }
+    return Changed;
+  }
   Constant *Flags =
       getFlags(MI && MI->isAtomic() ? AccessFlags::Atomic : AccessFlags::None);
   if (InstrumentRead) {
@@ -534,6 +582,171 @@ bool 
ConcurrencySanitizer::instrumentMemIntrinsic(IntrinsicInst *II,
   return true;
 }
 
+// Builds a loop that spins until a timed deadline is complete.
+static void insertDeadlineLoop(Instruction *InsertBefore, Value *End,
+                               Intrinsic::ID Clock, Intrinsic::ID Wait,
+                               Value *WaitArg) {
+  BasicBlock *Pre = InsertBefore->getParent();
+  BasicBlock *Check =
+      Pre->splitBasicBlock(InsertBefore->getIterator(), "csan.delay");
+  BasicBlock *Done =
+      Check->splitBasicBlock(InsertBefore->getIterator(), "csan.delay.done");
+  BasicBlock *Body = BasicBlock::Create(Pre->getContext(), "csan.delay.body",
+                                        Pre->getParent(), Done);
+
+  Instruction *ToDone = Check->getTerminator();
+  InstrumentationIRBuilder C(ToDone);
+  Value *Now = C.CreateIntrinsic(Clock, {});
+  C.CreateCondBr(C.CreateICmpULT(Now, End, "csan.delaying"), Body, Done);
+  ToDone->eraseFromParent();
+
+  IRBuilder<> B(Body);
+  InstrumentationIRBuilder::ensureDebugInfo(B, *Pre->getParent());
+  if (WaitArg)
+    B.CreateIntrinsic(Wait, {WaitArg});
+  else
+    B.CreateIntrinsic(Wait, {});
+  B.CreateBr(Check);
+}
+
+void ConcurrencySanitizer::insertInlineDelay(Instruction *InsertBefore) {
+  Module *M = InsertBefore->getModule();
+  InstrumentationIRBuilder IRB(InsertBefore);
+  if (M->getTargetTriple().isAMDGPU()) {
+    // 1000 ticks is 10us at the 100MHz rate the device sampler assumes.
+    // s_sleep(15) is the yield that sampler uses between polls.
+    constexpr uint64_t AmdgpuDelayTicks = 1000;
+    Value *End =
+        IRB.CreateAdd(IRB.CreateIntrinsic(Intrinsic::readsteadycounter, {}),
+                      IRB.getInt64(AmdgpuDelayTicks), "csan.delay.end");
+    IRB.CreateIntrinsic(Intrinsic::amdgcn_s_sleep, {IRB.getInt32(2)});
+    insertDeadlineLoop(InsertBefore, End, Intrinsic::readsteadycounter,
+                       Intrinsic::amdgcn_s_sleep, IRB.getInt32(15));
+    return;
+  }
+  if (M->getTargetTriple().isNVPTX()) {
+    // The operand is nanoseconds. 10us is the device sampler's upper delay.
+    constexpr unsigned NvptxDelayNs = 10000;
+    IRB.CreateIntrinsic(Intrinsic::nvvm_nanosleep,
+                        {IRB.getInt32(NvptxDelayNs)});
+    return;
+  }
+
+  // Default udelay of the host sampler.
+  constexpr unsigned HostDelayUs = 80;
+  FunctionCallee USleep;
+  if (isLibFuncEmittable(M, LibInfo, LibFunc_usleep)) {
+    USleep = getOrInsertLibFunc(M, *LibInfo, LibFunc_usleep, IRB.getInt32Ty(),
+                                IRB.getInt32Ty());
+    inferNonMandatoryLibFuncAttrs(M, LibInfo->getName(LibFunc_usleep),
+                                  *LibInfo);
+  } else {
+    USleep =
+        M->getOrInsertFunction("usleep", IRB.getInt32Ty(), IRB.getInt32Ty());
+  }
+  CallInst *CI = IRB.CreateCall(USleep, {IRB.getInt32(HostDelayUs)});
+  if (auto *F = dyn_cast<Function>(USleep.getCallee()))
+    CI->setCallingConv(F->getCallingConv());
+}
+
+// A memcpy has no value type. Read at most 8 bytes, or one byte when the
+// length is not a constant.
+static Type *rangeSampleTy(LLVMContext &Ctx, Value *ByteSize) {
+  uint64_t Bytes = 1;
+  if (auto *C = dyn_cast<ConstantInt>(ByteSize)) {
+    Bytes = C->getZExtValue();
+    if (Bytes > 8)
+      Bytes = 8;
+  }
+  return Type::getIntNTy(Ctx, Bytes * 8);
+}
+
+bool ConcurrencySanitizer::insertTypedValueCheck(Instruction *I, Value *Addr,
+                                                 Type *AccessTy,
+                                                 const DataLayout &DL,
+                                                 bool IsWrite) {
+  if (Addr->isSwiftError() || !AccessTy->isSized())
+    return false;
+  TypeSize StoreSize = DL.getTypeStoreSize(AccessTy);
+  if (StoreSize.isZero())
+    return false;
+
+  // icmp has no aggregate form. Load the stored bytes as an integer.
+  Type *LoadTy = AccessTy;
+  if (!AccessTy->isIntOrIntVectorTy() && !AccessTy->isPtrOrPtrVectorTy() &&
+      !AccessTy->isFPOrFPVectorTy()) {
+    TypeSize Bits = DL.getTypeStoreSizeInBits(AccessTy);
+    if (!Bits.isFixed())
+      return false;
+    LoadTy = Type::getIntNTy(AccessTy->getContext(), Bits.getFixedValue());
+  }
+
+  InstrumentationIRBuilder IRB(I);
+  Value *ByteSize = IRB.CreateTypeSize(IntptrTy, StoreSize);
+  return emitValueCheck(I, Addr, LoadTy, ByteSize, getLoadStoreAlignment(I),
+                        IsWrite);
+}
+
+bool ConcurrencySanitizer::insertRangeValueCheck(Instruction *I, Value *Addr,
+                                                 Value *ByteSize,
+                                                 bool IsWrite) {
+  if (auto *C = dyn_cast<ConstantInt>(ByteSize)) {
+    if (C->isZero())
+      return false;
+  } else {
+    // A dynamic length may be zero.
+    InstrumentationIRBuilder IRB(I);
+    I = SplitBlockAndInsertIfThen(IRB.CreateIsNotNull(ByteSize), I,
+                                  /*Unreachable=*/false);
+  }
+  return emitValueCheck(I, Addr, rangeSampleTy(I->getContext(), ByteSize),
+                        ByteSize, Align(1), IsWrite);
+}
+
+bool ConcurrencySanitizer::emitValueCheck(Instruction *I, Value *Addr,
+                                          Type *LoadTy, Value *ByteSize,
+                                          Align Alignment, bool IsWrite) {
+  const DataLayout &DL = I->getModule()->getDataLayout();
+  MDNode *NoSanitize = MDNode::get(I->getContext(), {});
+  InstrumentationIRBuilder IRB(I);
+  LoadInst *Old = IRB.CreateAlignedLoad(LoadTy, Addr, Alignment,
+                                        /*isVolatile=*/true, "csan.old");
+  Old->setMetadata(LLVMContext::MD_nosanitize, NoSanitize);
+
+  insertInlineDelay(I);
+
+  InstrumentationIRBuilder After(I);
+  LoadInst *New = After.CreateAlignedLoad(LoadTy, Addr, Alignment,
+                                          /*isVolatile=*/true, "csan.new");
+  New->setMetadata(LLVMContext::MD_nosanitize, NoSanitize);
+
+  // Compare the raw bits. A scalable vector has no fixed integer width.
+  TypeSize Bits = DL.getTypeSizeInBits(LoadTy);
+  Type *BitTy;
+  if (Bits.isScalable())
+    BitTy = LoadTy->isPtrOrPtrVectorTy()
+                ? DL.getIntPtrType(LoadTy)
+                : VectorType::getInteger(cast<VectorType>(LoadTy));
+  else
+    BitTy = After.getIntNTy(Bits.getFixedValue());
+  Value *Changed = After.CreateICmpNE(
+      After.CreateBitPreservingCastChain(DL, Old, BitTy),
+      After.CreateBitPreservingCastChain(DL, New, BitTy), "csan.changed");
+  if (BitTy->isVectorTy())
+    Changed = After.CreateOrReduce(Changed);
+
+  Instruction *ReportTerm =
+      SplitBlockAndInsertIfThen(Changed, I, /*Unreachable=*/false);
+  InstrumentationIRBuilder Report(Repo...
[truncated]

``````````

</details>


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

Reply via email to