Skip to content

Conversation

mysterymath
Copy link
Contributor

A new InstCombine transform uses this attribute to rewrite calls to a modular version of the implementation along with llvm.reloc.none relocations against aspects of the implementation needed by the call.

This change only adds support for the 'float' aspect, but it also builds the structure needed for others.

See issue #146159

@mysterymath
Copy link
Contributor Author

mysterymath commented Jul 8, 2025

Sending this out as a draft to obtain some early feedback about the direction of the implemenation of the Modular Printf RFC.

Prev PR: #147427
Next PR: #147431

@llvmbot
Copy link
Member

llvmbot commented Jul 8, 2025

@llvm/pr-subscribers-llvm-ir

Author: Daniel Thornburgh (mysterymath)

Changes

A new InstCombine transform uses this attribute to rewrite calls to a modular version of the implementation along with llvm.reloc.none relocations against aspects of the implementation needed by the call.

This change only adds support for the 'float' aspect, but it also builds the structure needed for others.

See issue #146159


Full diff: https://github.com/llvm/llvm-project/pull/147429.diff

2 Files Affected:

  • (modified) llvm/docs/LangRef.rst (+17)
  • (modified) llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp (+62)
diff --git a/llvm/docs/LangRef.rst b/llvm/docs/LangRef.rst
index 187182e5357e7..6694863874241 100644
--- a/llvm/docs/LangRef.rst
+++ b/llvm/docs/LangRef.rst
@@ -2620,6 +2620,23 @@ For example:
     This attribute indicates that outlining passes should not modify the
     function.
 
+``"modular_format"="<string_idx>,<first_idx_to_check>,<modular_impl_fn>,<impl_name>,<aspects...>"``
+    This attribute indicates that the implementation is modular on a particular
+    format string argument . When the argument for a given call is constant, the
+    compiler may redirect the call to a modular implementation function
+    instead.
+
+    The compiler also emits relocations to report various aspects of the format
+    string and arguments that were present. The compiler reports an aspect by
+    issing a relocation for the symbol `<impl_name>_<aspect>``. This arranges
+    for code and data needed to support the aspect of the implementation to be
+    brought into the link to satisfy weak references in the modular
+    implemenation function.
+
+    The following aspects are currently supported:
+
+    - ``float``: The call has a floating point argument
+
 Call Site Attributes
 ----------------------
 
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index b6ed1dc4331d2..579e5769796c6 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -19,6 +19,7 @@
 #include "llvm/ADT/SmallBitVector.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/Analysis/AliasAnalysis.h"
 #include "llvm/Analysis/AssumeBundleQueries.h"
 #include "llvm/Analysis/AssumptionCache.h"
@@ -3915,6 +3916,63 @@ Instruction *InstCombinerImpl::visitCallBrInst(CallBrInst &CBI) {
   return visitCallBase(CBI);
 }
 
+static Value *optimizeModularFormat(CallInst *CI, IRBuilderBase &B) {
+  if (!CI->hasFnAttr("modular-format"))
+    return nullptr;
+
+  SmallVector<StringRef> Args(
+      llvm::split(CI->getFnAttr("modular-format").getValueAsString(), ','));
+  // TODO: Examine the format argument in Args[0].
+  // TODO: Error handling
+  unsigned FirstArgIdx;
+  if (!llvm::to_integer(Args[1], FirstArgIdx))
+    return nullptr;
+  if (FirstArgIdx == 0)
+    return nullptr;
+  --FirstArgIdx;
+  StringRef FnName = Args[2];
+  StringRef ImplName = Args[3];
+  DenseSet<StringRef> Aspects(llvm::from_range,
+                              ArrayRef<StringRef>(Args).drop_front(4));
+  Module *M = CI->getModule();
+  Function *Callee = CI->getCalledFunction();
+  FunctionCallee ModularFn =
+      M->getOrInsertFunction(FnName, Callee->getFunctionType(),
+                             Callee->getAttributes().removeFnAttribute(
+                                 M->getContext(), "modular-format"));
+  CallInst *New = cast<CallInst>(CI->clone());
+  New->setCalledFunction(ModularFn);
+  New->removeFnAttr("modular-format");
+  B.Insert(New);
+
+  const auto ReferenceAspect = [&](StringRef Aspect) {
+    SmallString<20> Name = ImplName;
+    Name += '_';
+    Name += Aspect;
+    Constant *Sym =
+        M->getOrInsertGlobal(Name, Type::getInt8Ty(M->getContext()));
+    Function *RelocNoneFn =
+        Intrinsic::getOrInsertDeclaration(M, Intrinsic::reloc_none);
+    B.CreateCall(RelocNoneFn, {Sym});
+  };
+
+  if (Aspects.contains("float")) {
+    Aspects.erase("float");
+    if (llvm::any_of(
+            llvm::make_range(std::next(CI->arg_begin(), FirstArgIdx),
+                             CI->arg_end()),
+            [](Value *V) { return V->getType()->isFloatingPointTy(); }))
+      ReferenceAspect("float");
+  }
+
+  SmallVector<StringRef> UnknownAspects(Aspects.begin(), Aspects.end());
+  llvm::sort(UnknownAspects);
+  for (StringRef Request : UnknownAspects)
+    ReferenceAspect(Request);
+
+  return New;
+}
+
 Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
   if (!CI->getCalledFunction()) return nullptr;
 
@@ -3936,6 +3994,10 @@ Instruction *InstCombinerImpl::tryOptimizeCall(CallInst *CI) {
     ++NumSimplified;
     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
   }
+  if (Value *With = optimizeModularFormat(CI, Builder)) {
+    ++NumSimplified;
+    return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
+  }
 
   return nullptr;
 }

@mysterymath mysterymath force-pushed the users/mysterymath/modular-printf/ir branch from 3ba5f13 to 813226e Compare July 8, 2025 22:00
@mysterymath mysterymath force-pushed the users/mysterymath/modular-printf/ir branch from 271a63f to c2e511c Compare July 21, 2025 22:24
Copy link

github-actions bot commented Jul 21, 2025

✅ With the latest revision this PR passed the C/C++ code formatter.

@mysterymath mysterymath force-pushed the users/mysterymath/modular-printf/ir branch 3 times, most recently from 36ef26c to 326fcc3 Compare July 29, 2025 21:31
@mysterymath mysterymath force-pushed the users/mysterymath/modular-printf/reloc.none branch from c89242c to 657f659 Compare July 29, 2025 22:11
@mysterymath mysterymath force-pushed the users/mysterymath/modular-printf/ir branch from 326fcc3 to 4c26a6c Compare July 29, 2025 22:11
@mysterymath mysterymath force-pushed the users/mysterymath/modular-printf/ir branch from 4c26a6c to 9265309 Compare August 21, 2025 22:16
@mysterymath mysterymath force-pushed the users/mysterymath/modular-printf/reloc.none branch from 657f659 to 341dd6a Compare August 21, 2025 22:16
A new InstCombine transform uses this attribute to rewrite calls to a
modular version of the implementation along with llvm.reloc.none
relocations against aspects of the implementation needed by the call.

This change only adds support for the 'float' aspect, but it also builds
the structure needed for others.

See issue #146159
This avoids avoid modifying Module in ISel
@mysterymath mysterymath force-pushed the users/mysterymath/modular-printf/ir branch from 9265309 to 2ed9e3d Compare August 26, 2025 18:18
@mysterymath mysterymath force-pushed the users/mysterymath/modular-printf/reloc.none branch from 341dd6a to b76a6c3 Compare August 26, 2025 18:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants