[llvm] [PGO][ICP] Prevent indirect call promotion to functions with incompatible target features (PR #192142)

Han Shen via llvm-commits llvm-commits at lists.llvm.org
Mon May 4 20:02:21 PDT 2026


https://github.com/shenhanc78 updated https://github.com/llvm/llvm-project/pull/192142

>From c69c4d8bbf502d819b66ee4530992b02380ce7b6 Mon Sep 17 00:00:00 2001
From: Han Shen <shenhan at google.com>
Date: Tue, 14 Apr 2026 14:15:41 -0700
Subject: [PATCH 1/3] [PGO][ICP] Prevent indirect call promotion to functions
 with incompatible target features

Profile-driven indirect call promotion was promoting indirect calls to functions requiring advanced CPU features (e.g. AVX512) even when the caller function did not support those features. When these promoted calls were subsequently inlined, it created invalid IR that caused the backend to crash during instruction selection.

This patch adds target feature compatibility checks to both SampleProfileLoader and IndirectCallPromotion passes to skip promotion if the callee requires features not present in the caller. It also adds a defense-in-depth check in InlineCost for profile-promoted calls.

Added a regression test.
---
 llvm/lib/Analysis/InlineCost.cpp              | 25 ++++++++++
 .../Instrumentation/IndirectCallPromotion.cpp |  6 +++
 .../Transforms/Utils/CallPromotionUtils.cpp   | 17 +++++++
 .../SampleProfile/icp_target_feature.ll       | 50 +++++++++++++++++++
 4 files changed, 98 insertions(+)
 create mode 100644 llvm/test/Transforms/SampleProfile/icp_target_feature.ll

diff --git a/llvm/lib/Analysis/InlineCost.cpp b/llvm/lib/Analysis/InlineCost.cpp
index d975a93e9b1fd..42cba92aec5bd 100644
--- a/llvm/lib/Analysis/InlineCost.cpp
+++ b/llvm/lib/Analysis/InlineCost.cpp
@@ -3273,6 +3273,31 @@ InlineCost llvm::getInlineCost(
     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE,
     function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
 
+  if (Call.getMetadata("prof_promoted")) {
+    auto CalleeFeatures =
+        Callee->getFnAttribute("target-features").getValueAsString();
+    auto CallerFeatures =
+        Call.getCaller()->getFnAttribute("target-features").getValueAsString();
+
+    SmallVector<StringRef, 8> CalleeFeats;
+    CalleeFeatures.split(CalleeFeats, ',');
+
+    for (auto Feat : CalleeFeats) {
+      if (Feat.starts_with("+")) {
+        if (!CallerFeatures.contains(Feat)) {
+          return llvm::InlineCost::getNever(
+              "missing target feature in caller for profile promoted call");
+        }
+      }
+    }
+
+    if (!functionsHaveCompatibleAttributes(Call.getCaller(), Callee, CalleeTTI,
+                                           GetTLI)) {
+      return llvm::InlineCost::getNever(
+          "conflicting attributes for profile promoted call");
+    }
+  }
+
   auto UserDecision =
       llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
 
diff --git a/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp b/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
index f3cdb3518ddcb..7761b34cb080f 100644
--- a/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
+++ b/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
@@ -666,10 +666,16 @@ CallBase &llvm::pgo::promoteIndirectCall(CallBase &CB, Function *DirectCallee,
                                          uint64_t Count, uint64_t TotalCount,
                                          bool AttachProfToDirectCall,
                                          OptimizationRemarkEmitter *ORE) {
+  bool WasProfilePromoted = CB.getMetadata(LLVMContext::MD_prof) != nullptr;
+
   CallBase &NewInst = promoteCallWithIfThenElse(
       CB, DirectCallee,
       createBranchWeights(CB.getContext(), Count, TotalCount - Count));
 
+  if (WasProfilePromoted) {
+    NewInst.setMetadata("prof_promoted", MDNode::get(CB.getContext(), {}));
+  }
+
   if (AttachProfToDirectCall)
     setFittedBranchWeights(NewInst, {Count},
                            /*IsExpected=*/false);
diff --git a/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp b/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
index f0f9add09bf82..5751e89b1ac1b 100644
--- a/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
+++ b/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
@@ -477,6 +477,23 @@ bool llvm::isLegalToPromote(const CallBase &CB, Function *Callee,
     }
   }
 
+  // Check target feature compatibility.
+  auto CalleeFeatures =
+      Callee->getFnAttribute("target-features").getValueAsString();
+  auto CallerFeatures =
+      CB.getCaller()->getFnAttribute("target-features").getValueAsString();
+  SmallVector<StringRef, 8> CalleeFeats;
+  CalleeFeatures.split(CalleeFeats, ',');
+  for (auto Feat : CalleeFeats) {
+    if (Feat.starts_with("+")) {
+      if (!CallerFeatures.contains(Feat)) {
+        if (FailureReason)
+          *FailureReason = "Incompatible target features";
+        return false;
+      }
+    }
+  }
+
   return true;
 }
 
diff --git a/llvm/test/Transforms/SampleProfile/icp_target_feature.ll b/llvm/test/Transforms/SampleProfile/icp_target_feature.ll
new file mode 100644
index 0000000000000..7746f74ade562
--- /dev/null
+++ b/llvm/test/Transforms/SampleProfile/icp_target_feature.ll
@@ -0,0 +1,50 @@
+; RUN: opt < %s -passes=sample-profile -sample-profile-file=%S/Inputs/norepeated-icp-2.prof -S | FileCheck %s
+
+target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-linux-gnu"
+
+ at p = dso_local global ptr null, align 8
+
+; Function Attrs: uwtable mustprogress
+define dso_local void @_Z3moov() #0 !dbg !7 {
+entry:
+  ret void
+}
+
+; Function Attrs: uwtable mustprogress
+define dso_local void @_Z3hoov() #1 !dbg !11 {
+entry:
+  store ptr @_Z3moov, ptr @p, align 8
+  ret void
+}
+
+; Function Attrs: uwtable mustprogress
+define dso_local void @_Z3goov() #1 !dbg !24 {
+entry:
+  %t0 = load ptr, ptr @p, align 8
+  ; CHECK: icmp eq ptr %t0, @_Z3hoov
+  ; CHECK-NOT: icmp eq ptr %t0, @_Z3moov
+  call void %t0(), !dbg !26, !prof !30
+  ret void
+}
+
+attributes #0 = { uwtable mustprogress "use-sample-profile" "target-features"="+avx512f" }
+attributes #1 = { uwtable mustprogress "use-sample-profile" }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, producer: "clang", isOptimized: true, runtimeVersion: 0, emissionKind: LineTablesOnly, enums: !2, splitDebugInlining: false, debugInfoForProfiling: true, nameTableKind: None)
+!1 = !DIFile(filename: "1.cc", directory: "")
+!2 = !{}
+!3 = !{i32 7, !"Dwarf Version", i32 4}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 4}
+!6 = !{!"clang"}
+!7 = distinct !DISubprogram(name: "moo", linkageName: "_Z3moov", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !2)
+!8 = !DISubroutineType(types: !2)
+!11 = distinct !DISubprogram(name: "hoo", linkageName: "_Z3hoov", scope: !1, file: !1, line: 9, type: !8, scopeLine: 9, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !2)
+!24 = distinct !DISubprogram(name: "goo", linkageName: "_Z3goov", scope: !1, file: !1, line: 15, type: !8, scopeLine: 15, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !2)
+!26 = !DILocation(line: 16, column: 3, scope: !24)
+!30 = !{!"VP", i32 0, i64 0, i64 1850239051784516332, i64 -1}

>From df2dd57d29b2a48dcf57e82e518d21c367692354 Mon Sep 17 00:00:00 2001
From: Han Shen <shenhan at google.com>
Date: Sun, 26 Apr 2026 10:26:25 -0700
Subject: [PATCH 2/3] fixup! [PGO][ICP] Prevent indirect call promotion to
 functions with incompatible target features

---
 llvm/lib/Analysis/InlineCost.cpp              | 25 -------------------
 .../Instrumentation/IndirectCallPromotion.cpp |  6 -----
 2 files changed, 31 deletions(-)

diff --git a/llvm/lib/Analysis/InlineCost.cpp b/llvm/lib/Analysis/InlineCost.cpp
index 42cba92aec5bd..d975a93e9b1fd 100644
--- a/llvm/lib/Analysis/InlineCost.cpp
+++ b/llvm/lib/Analysis/InlineCost.cpp
@@ -3273,31 +3273,6 @@ InlineCost llvm::getInlineCost(
     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE,
     function_ref<EphemeralValuesCache &(Function &)> GetEphValuesCache) {
 
-  if (Call.getMetadata("prof_promoted")) {
-    auto CalleeFeatures =
-        Callee->getFnAttribute("target-features").getValueAsString();
-    auto CallerFeatures =
-        Call.getCaller()->getFnAttribute("target-features").getValueAsString();
-
-    SmallVector<StringRef, 8> CalleeFeats;
-    CalleeFeatures.split(CalleeFeats, ',');
-
-    for (auto Feat : CalleeFeats) {
-      if (Feat.starts_with("+")) {
-        if (!CallerFeatures.contains(Feat)) {
-          return llvm::InlineCost::getNever(
-              "missing target feature in caller for profile promoted call");
-        }
-      }
-    }
-
-    if (!functionsHaveCompatibleAttributes(Call.getCaller(), Callee, CalleeTTI,
-                                           GetTLI)) {
-      return llvm::InlineCost::getNever(
-          "conflicting attributes for profile promoted call");
-    }
-  }
-
   auto UserDecision =
       llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
 
diff --git a/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp b/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
index 7761b34cb080f..f3cdb3518ddcb 100644
--- a/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
+++ b/llvm/lib/Transforms/Instrumentation/IndirectCallPromotion.cpp
@@ -666,16 +666,10 @@ CallBase &llvm::pgo::promoteIndirectCall(CallBase &CB, Function *DirectCallee,
                                          uint64_t Count, uint64_t TotalCount,
                                          bool AttachProfToDirectCall,
                                          OptimizationRemarkEmitter *ORE) {
-  bool WasProfilePromoted = CB.getMetadata(LLVMContext::MD_prof) != nullptr;
-
   CallBase &NewInst = promoteCallWithIfThenElse(
       CB, DirectCallee,
       createBranchWeights(CB.getContext(), Count, TotalCount - Count));
 
-  if (WasProfilePromoted) {
-    NewInst.setMetadata("prof_promoted", MDNode::get(CB.getContext(), {}));
-  }
-
   if (AttachProfToDirectCall)
     setFittedBranchWeights(NewInst, {Count},
                            /*IsExpected=*/false);

>From 4095e9d4bfd73ac07ca71a018999f10fa4ed28e2 Mon Sep 17 00:00:00 2001
From: Han Shen <shenhan at google.com>
Date: Mon, 4 May 2026 19:56:18 -0700
Subject: [PATCH 3/3] fixup! [PGO][ICP] Prevent indirect call promotion to
 functions with incompatible target features

---
 llvm/lib/Transforms/Utils/CallPromotionUtils.cpp  |  6 +++++-
 .../SampleProfile/icp_target_feature.ll           | 15 +++++++++++++--
 2 files changed, 18 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp b/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
index 5751e89b1ac1b..1bfeea3b711f9 100644
--- a/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
+++ b/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
@@ -477,7 +477,11 @@ bool llvm::isLegalToPromote(const CallBase &CB, Function *Callee,
     }
   }
 
-  // Check target feature compatibility.
+  // Check target feature compatibility. This is also needed to avoid incorrect
+  // inlining if the callee has the always_inline attribute. An always_inline
+  // function can be incorrectly inlined via two paths: either it is directly
+  // called and inlined, or it is indirectly called, promoted, and then inlined.
+  // The check here only prevents the latter case.
   auto CalleeFeatures =
       Callee->getFnAttribute("target-features").getValueAsString();
   auto CallerFeatures =
diff --git a/llvm/test/Transforms/SampleProfile/icp_target_feature.ll b/llvm/test/Transforms/SampleProfile/icp_target_feature.ll
index 7746f74ade562..1210a97e98b09 100644
--- a/llvm/test/Transforms/SampleProfile/icp_target_feature.ll
+++ b/llvm/test/Transforms/SampleProfile/icp_target_feature.ll
@@ -1,3 +1,11 @@
+; This test verifies that indirect call promotion (ICP) under sample profiling
+; correctly checks target feature compatibility. Specifically, a callee with
+; target features incompatible with the caller's features (e.g., "_Z3moov" requiring
+; "+avx512f" while caller "_Z3goov" does not support it) should not be promoted,
+; while a compatible callee (e.g., "_Z3hoov") should be promoted successfully.
+; Note that under Sample PGO, the promotion candidates (e.g., _Z3hoov and _Z3moov)
+; are retrieved directly from the sample profile file (Inputs/norepeated-icp-2.prof)
+; at the corresponding line offset (1) rather than using value profile !prof metadata.
 ; RUN: opt < %s -passes=sample-profile -sample-profile-file=%S/Inputs/norepeated-icp-2.prof -S | FileCheck %s
 
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
@@ -22,9 +30,13 @@ entry:
 define dso_local void @_Z3goov() #1 !dbg !24 {
 entry:
   %t0 = load ptr, ptr @p, align 8
+  ; Here, _Z3moov requires "+avx512f" (attributes #0) which the caller lacks (attributes #1).
+  ; Therefore, _Z3moov is not promoted.
+  ; CHECK-NOT: icmp eq ptr %t0, @_Z3moov
+  ; On the other hand, _Z3hoov has compatible target features and is promoted successfully.
   ; CHECK: icmp eq ptr %t0, @_Z3hoov
   ; CHECK-NOT: icmp eq ptr %t0, @_Z3moov
-  call void %t0(), !dbg !26, !prof !30
+  call void %t0(), !dbg !26
   ret void
 }
 
@@ -47,4 +59,3 @@ attributes #1 = { uwtable mustprogress "use-sample-profile" }
 !11 = distinct !DISubprogram(name: "hoo", linkageName: "_Z3hoov", scope: !1, file: !1, line: 9, type: !8, scopeLine: 9, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !2)
 !24 = distinct !DISubprogram(name: "goo", linkageName: "_Z3goov", scope: !1, file: !1, line: 15, type: !8, scopeLine: 15, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !2)
 !26 = !DILocation(line: 16, column: 3, scope: !24)
-!30 = !{!"VP", i32 0, i64 0, i64 1850239051784516332, i64 -1}



More information about the llvm-commits mailing list