================
@@ -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,
----------------
yxsamliu wrote:

What should happen on older targets? `nanosleep` needs `sm_70` and PTX 6.3 or 
newer. Could we add a codegen test for that boundary?

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