[clang] [llvm] Reimplement constrained 'trunc' using operand bundles (PR #118253)

Kevin P. Neal via llvm-commits llvm-commits at lists.llvm.org
Wed Jan 8 12:33:25 PST 2025


================
@@ -86,6 +86,43 @@ IRBuilderBase::createCallHelper(Function *Callee, ArrayRef<Value *> Ops,
   return CI;
 }
 
+CallInst *IRBuilderBase::CreateCall(FunctionType *FTy, Value *Callee,
+                                    ArrayRef<Value *> Args,
+                                    ArrayRef<OperandBundleDef> OpBundles,
+                                    const Twine &Name, MDNode *FPMathTag) {
+  ArrayRef<OperandBundleDef> ActualBundlesRef = OpBundles;
+  SmallVector<OperandBundleDef, 2> ActualBundles;
+
+  if (IsFPConstrained) {
+    if (const auto *Func = dyn_cast<Function>(Callee)) {
+      if (Intrinsic::ID ID = Func->getIntrinsicID()) {
+        if (IntrinsicInst::canAccessFPEnvironment(ID)) {
+          bool NeedRound = true, NeedExcept = true;
+          for (const auto &Item : OpBundles) {
+            if (NeedRound && Item.getTag() == "fpe.round")
+              NeedRound = false;
+            else if (NeedExcept && Item.getTag() == "fpe.except")
+              NeedExcept = false;
+            ActualBundles.push_back(Item);
----------------
kpneal wrote:

I think #1 is a better choice despite the downsides. Having more opportunities to optimize when lowering if we know the current rounding mode seems like a good choice. It does simplify the implementation in places as you said.

Having the rounding mode bundle specify the FP environment is a change from the constrained intrinsics, and this point is a little fine, so I do think we'll need to clearly state this in the LangRef at some point.

I am a little worried that we're creating a footgun and someone may write code that relies on the rounding mode bundle when handling trunc, floor, or one of the other math intrinsics/library calls. Then again, if code is trying to evaluate an expression then a switch is going to be needed with entries that would be expected to have rounding modes hardcoded into them. So I'm not worried enough to change my view that #1 is preferred.

Having the rounding mode bundle specify the FP environment also means we don't need any Verifier checks for improperly present or specified rounding bundles. That's a minor win.

One last point: this is another example of how having the rounding mode specified is useful. Since we've defined the constrained intrinsics to require the rounding mode be correct, and an incorrect rounding mode is undefined behavior, we can rely on the specified rounding mode being correct. The constant folding that we're doing currently checks the rounding mode in the cases I remember. We should carry over in the LangRef the verbiage about incorrect rounding mode metadata being UB.

https://github.com/llvm/llvm-project/pull/118253


More information about the llvm-commits mailing list