Bug type: crash
Component: DeadArgumentElimination
Bug location: llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp: DeadArgumentEliminationPass::isLive
DeadArgumentEliminationPass::markLive
DeadArgumentEliminationPass::markValue
DeadArgumentEliminationPass::propagateVirtMustcallLiveness
DeadArgumentEliminationPass::removeDeadArgumentsFromCallers
DeadArgumentEliminationPass::removeDeadStuffFromFunction
DeadArgumentEliminationPass::run
DeadArgumentEliminationPass::surveyFunction
isMustTailCalleeAnalyzable
Issue title: DeadArgumentElimination creates invalid code with musttail calls returning structs
Labels: ipo
crash-on-valid
Reported by: ostannard

The DeadArgumentElimination pass creates code which fails the IR verifier when run on this input:

```test.ll
%struct.S = type { i32 }

define internal %struct.S @F38()  {
  ret %struct.S { i32 0 }
}

define %struct.S @F36() {
  %3 = musttail call %struct.S @F38()
  ret %struct.S %3
}
```

```
$ /work/llvm/build/bin/opt test.ll -passes=deadargelim -S
cannot guarantee tail call due to mismatched return types
  %1 = musttail call i32 @F38()
LLVM ERROR: Broken module found, compilation aborted!
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace.
Stack dump:
0.      Program arguments: /work/llvm/build/bin/opt test.ll -passes=deadargelim -S
1.      Running pass "verify" on module "test.ll"
 #0 0x000055c16a99ca37 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/work/llvm/build/bin/opt+0x4133a37)
 #1 0x000055c16a99a57e llvm::sys::RunSignalHandlers() (/work/llvm/build/bin/opt+0x413157e)
 #2 0x000055c16a99d27a SignalHandler(int) Signals.cpp:0:0
 #3 0x00007f38e3a42520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #4 0x00007f38e3a969fc __pthread_kill_implementation ./nptl/pthread_kill.c:44:76
 #5 0x00007f38e3a969fc __pthread_kill_internal ./nptl/pthread_kill.c:78:10
 #6 0x00007f38e3a969fc pthread_kill ./nptl/pthread_kill.c:89:10
 #7 0x00007f38e3a42476 gsignal ./signal/../sysdeps/posix/raise.c:27:6
 #8 0x00007f38e3a287f3 abort ./stdlib/abort.c:81:7
 #9 0x000055c16a9857a3 llvm::report_fatal_error(llvm::Twine const&, bool) (/work/llvm/build/bin/opt+0x411c7a3)
#10 0x000055c16a9855f6 (/work/llvm/build/bin/opt+0x411c5f6)
#11 0x000055c16afe2d4a (/work/llvm/build/bin/opt+0x4779d4a)
#12 0x000055c16bd1b53d llvm::detail::PassModel<llvm::Module, llvm::VerifierPass, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) NewPMDriver.cpp:0:0
#13 0x000055c16abad88a llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/work/llvm/build/bin/opt+0x434488a)
#14 0x000055c16bd146eb llvm::runPassPipeline(llvm::StringRef, llvm::Module&, llvm::TargetMachine*, llvm::TargetLibraryInfoImpl*, llvm::ToolOutputFile*, llvm::ToolOutputFile*, llvm::ToolOutputFile*, llvm::StringRef, llvm::ArrayRef<llvm::PassPlugin>, llvm::ArrayRef<std::function<void (llvm::PassBuilder&)>>, llvm::opt_tool::OutputKind, llvm::opt_tool::VerifierKind, bool, bool, bool, bool, bool, bool, bool) (/work/llvm/build/bin/opt+0x54ab6eb)
#15 0x000055c16a964609 optMain (/work/llvm/build/bin/opt+0x40fb609)
#16 0x00007f38e3a29d90 __libc_start_call_main ./csu/../sysdeps/nptl/libc_start_call_main.h:58:16
#17 0x00007f38e3a29e40 call_init ./csu/../csu/libc-start.c:128:20
#18 0x00007f38e3a29e40 __libc_start_main ./csu/../csu/libc-start.c:379:5
#19 0x000055c16a95e0a5 _start (/work/llvm/build/bin/opt+0x40f50a5)
fish: Job 1, '/work/llvm/build/bin/opt test.l…' terminated by signal SIGABRT (Abort)
```

Found using a fuzzer while testing #102896.

Comments: author: ostannard
body: Related case with a different assertion message:
```test2.ll
%struct.S = type { double }

define internal %struct.S @F38() {
  ret %struct.S { double 0.0 }
}

define internal %struct.S @F36() {
  %1 = alloca %struct.S, align 8
  %3 = musttail call %struct.S @F38()
  ret %struct.S %3
}

define double @foo() {
  %3 = call %struct.S @F36()
  %5 = extractvalue %struct.S %3, 0
  ret double %5
}
```

```
$ /work/llvm/build/bin/opt test2.ll -passes=deadargelim -S -print-after-all
; *** IR Dump After DeadArgumentEliminationPass on [module] ***
; ModuleID = 'test2.ll'
source_filename = "test2.ll"

%struct.S = type { double }

define internal double @F38() {
  %oldret = extractvalue %struct.S zeroinitializer, 0
  ret double %oldret
}

define internal double @F36() {
  %1 = alloca %struct.S, align 8
  %2 = musttail call double @F38()
  %oldret = insertvalue %struct.S poison, double %2, 0
  %oldret1 = extractvalue %struct.S %oldret, 0
  ret double %oldret1
}

define double @foo() {
  %1 = call double @F36()
  %oldret = insertvalue %struct.S poison, double %1, 0
  %2 = extractvalue %struct.S %oldret, 0
  ret double %2
}
musttail call must precede a ret with an optional bitcast
  %2 = musttail call double @F38()
LLVM ERROR: Broken module found, compilation aborted!
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace.
Stack dump:
0.      Program arguments: /work/llvm/build/bin/opt test2.ll -passes=deadargelim -S -print-after-all
1.      Running pass "verify" on module "test2.ll"
 #0 0x000055c5f980ca37 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) (/work/llvm/build/bin/opt+0x4133a37)
 #1 0x000055c5f980a57e llvm::sys::RunSignalHandlers() (/work/llvm/build/bin/opt+0x413157e)
 #2 0x000055c5f980d27a SignalHandler(int) Signals.cpp:0:0
 #3 0x00007faf4da42520 (/lib/x86_64-linux-gnu/libc.so.6+0x42520)
 #4 0x00007faf4da969fc __pthread_kill_implementation ./nptl/pthread_kill.c:44:76
 #5 0x00007faf4da969fc __pthread_kill_internal ./nptl/pthread_kill.c:78:10
 #6 0x00007faf4da969fc pthread_kill ./nptl/pthread_kill.c:89:10
 #7 0x00007faf4da42476 gsignal ./signal/../sysdeps/posix/raise.c:27:6
 #8 0x00007faf4da287f3 abort ./stdlib/abort.c:81:7
 #9 0x000055c5f97f57a3 llvm::report_fatal_error(llvm::Twine const&, bool) (/work/llvm/build/bin/opt+0x411c7a3)
#10 0x000055c5f97f55f6 (/work/llvm/build/bin/opt+0x411c5f6)
#11 0x000055c5f9e52d4a (/work/llvm/build/bin/opt+0x4779d4a)
#12 0x000055c5fab8b53d llvm::detail::PassModel<llvm::Module, llvm::VerifierPass, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) NewPMDriver.cpp:0:0
#13 0x000055c5f9a1d88a llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) (/work/llvm/build/bin/opt+0x434488a)
#14 0x000055c5fab846eb llvm::runPassPipeline(llvm::StringRef, llvm::Module&, llvm::TargetMachine*, llvm::TargetLibraryInfoImpl*, llvm::ToolOutputFile*, llvm::ToolOutputFile*, llvm::ToolOutputFile*, llvm::StringRef, llvm::ArrayRef<llvm::PassPlugin>, llvm::ArrayRef<std::function<void (llvm::PassBuilder&)>>, llvm::opt_tool::OutputKind, llvm::opt_tool::VerifierKind, bool, bool, bool, bool, bool, bool, bool) (/work/llvm/build/bin/opt+0x54ab6eb)
#15 0x000055c5f97d4609 optMain (/work/llvm/build/bin/opt+0x40fb609)
#16 0x00007faf4da29d90 __libc_start_call_main ./csu/../sysdeps/nptl/libc_start_call_main.h:58:16
#17 0x00007faf4da29e40 call_init ./csu/../csu/libc-start.c:128:20
#18 0x00007faf4da29e40 __libc_start_main ./csu/../csu/libc-start.c:379:5
#19 0x000055c5f97ce0a5 _start (/work/llvm/build/bin/opt+0x40f50a5)
fish: Job 1, '/work/llvm/build/bin/opt test2.…' terminated by signal SIGABRT (Abort)
```
author: ParkHanbum
body: we have the test for second case at musttail-invalid.ll
```declare i32 @not_tail_pos_callee()
define i32 @not_tail_pos() {
; CHECK: musttail call must precede a ret with an optional bitcast
  %v = musttail call i32 @not_tail_pos_callee()
  %w = add i32 %v, 1
  ret i32 %w
}
```

but first case is not. maybe we need to add this into testcase.

first case 
```void Verifier::verifyMustTailCall(CallInst &CI) {
  Check(!CI.isInlineAsm(), "cannot use musttail call with inline asm", &CI);

  Function *F = CI.getParent()->getParent();
  FunctionType *CallerTy = F->getFunctionType();
  FunctionType *CalleeTy = CI.getFunctionType();
  Check(CallerTy->isVarArg() == CalleeTy->isVarArg(),
        "cannot guarantee tail call due to mismatched varargs", &CI);
  Check(isTypeCongruent(CallerTy->getReturnType(), CalleeTy->getReturnType()),
        "cannot guarantee tail call due to mismatched return types", F, CallerTy->getReturnType(), &CI, CalleeTy->getReturnType());
```

CallInst:  %1 = musttail call i32 @F38()
Return type of Caller :  %struct.S = type { i32 }
Return type of Callee:  i32

This is weird. 
I couldn't understand why `%struct.S = type { i32 }` is changed to `i32` at `%3 = musttail call %struct.S @F38()`

but after change it to `i32` then it works.
```
%struct.S = type { i32 }

define internal %struct.S @F38()  {
  ret %struct.S { i32 0 }
}

define i32 @F36() {
  %3 = musttail call i32 @F38()
  ret i32 %3
}
```
```
% bin/opt --passes=deadargelim  test.ll -S       
; ModuleID = 'test.ll'
source_filename = "test.ll"

%struct.S = type { i32 }

define internal %struct.S @F38() {
  ret %struct.S zeroinitializer
}

define i32 @F36() {
  %1 = musttail call i32 @F38()
  ret i32 %1
}

```

is this normal?
author: ParkHanbum
body: I found why it causes, maybe.
```
source_filename = "test.ll"

%struct.S = type { i32 }

define internal i32 @F38() {
  %oldret = extractvalue %struct.S zeroinitializer, 0
  ret i32 %oldret
}

define %struct.S @F36() {
  %1 = musttail call i32 @F38()
  %oldret = insertvalue %struct.S poison, i32 %1, 0
  ret %struct.S %oldret
}

```


author: ParkHanbum
body: we create new return type in here
```
// Look at each of the original return values individually.
    for (unsigned Ri = 0; Ri != RetCount; ++Ri) {
      RetOrArg Ret = createRet(F, Ri);
      if (LiveValues.erase(Ret)) {
        RetTypes.push_back(getRetComponentType(F, Ri));
        NewRetIdxs[Ri] = RetTypes.size() - 1;
      } else {
        ++NumRetValsEliminated;
        LLVM_DEBUG(
            dbgs() << "DeadArgumentEliminationPass - Removing return value "
                   << Ri << " from " << F->getName() << "\n");
      }
    
```

I tested disabling the code that creates the new return type to see if it would make a quick improvement
```
NRetTy = RetTy;
```

it seems to work
```
; ModuleID = 'test.ll'
source_filename = "test.ll"

%struct.S = type { i32 }

define internal %struct.S @F38() {
  ret %struct.S zeroinitializer
}

define %struct.S @F36() {
  %1 = musttail call %struct.S @F38()
  ret %struct.S %1
}

```

If this is a defect,
1. do not change return type if it conflict with caller's return type when CB was musttail call.
2. if caller's return type is conflict with new return type then change all of uses type.

we can fix it by choosing one of above. IMO
how do you think?

please let me know this issue need to fix or not~

@dtcxzyw Can you please review this issue?

author: dtcxzyw
body: cc @nikic @efriedma-quic 
author: efriedma-quic
body: I'm not sure why we're trying to run DAE on functions where we can't change the signature; why doesn't the current check for musttail callers handle this?
author: ParkHanbum
body: @efriedma-quic Don't think it needs to be fix?

author: efriedma-quic
body: Not sure what you're saying.  I'm asking about the structure of the existing code.  There are already checks for musttail calls in DeadArgumentElimination, which at first glance should exclude transforming cases like this.  Can those checks be extended to also exclude this case?

Fix patch:
commit 5978bb2936d9a71d8e6891c640a36be760b569d3
Author: u4f3 <ricoafoat@gmail.com>
Date:   Thu Apr 10 22:08:09 2025 +0800

    [DeadArgElim] fix verifier failure when changing musttail's function signature (#127366)
    
    This commit is for #107569 and #126817.
    
    Stop changing musttail's caller and callee's function signature when
    calling convention is not swifttailcc nor tailcc. Verifier makes sure
    musttail's caller and callee shares exactly the same signature, see
    commit 9ff2eb1 and #54964.
    
    Otherwise just make sure the return type is the same and then process
    musttail like usual calls.
    
    close #107569, #126817

diff --git a/llvm/include/llvm/Transforms/IPO/DeadArgumentElimination.h b/llvm/include/llvm/Transforms/IPO/DeadArgumentElimination.h
index 63e1ad043d49..efa9c4bdc496 100644
--- a/llvm/include/llvm/Transforms/IPO/DeadArgumentElimination.h
+++ b/llvm/include/llvm/Transforms/IPO/DeadArgumentElimination.h
@@ -106,13 +106,16 @@ public:
   UseMap Uses;
 
   using LiveSet = std::set<RetOrArg>;
-  using LiveFuncSet = std::set<const Function *>;
+  using FuncSet = std::set<const Function *>;
 
   /// This set contains all values that have been determined to be live.
   LiveSet LiveValues;
 
-  /// This set contains all values that are cannot be changed in any way.
-  LiveFuncSet LiveFunctions;
+  /// This set contains all functions that cannot be changed in any way.
+  FuncSet FrozenFunctions;
+
+  /// This set contains all functions that cannot change return type;
+  FuncSet FrozenRetTyFunctions;
 
   using UseVector = SmallVector<RetOrArg, 5>;
 
@@ -131,12 +134,13 @@ private:
   void markValue(const RetOrArg &RA, Liveness L,
                  const UseVector &MaybeLiveUses);
   void markLive(const RetOrArg &RA);
-  void markLive(const Function &F);
+  void markFrozen(const Function &F);
+  void markRetTyFrozen(const Function &F);
+  bool markFnOrRetTyFrozenOnMusttail(const Function &F);
   void propagateLiveness(const RetOrArg &RA);
   bool removeDeadStuffFromFunction(Function *F);
   bool deleteDeadVarargs(Function &F);
   bool removeDeadArgumentsFromCallers(Function &F);
-  void propagateVirtMustcallLiveness(const Module &M);
 };
 
 } // end namespace llvm
diff --git a/llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp b/llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
index ed93b4491c50..2e2687a5ff6e 100644
--- a/llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
+++ b/llvm/lib/Transforms/IPO/DeadArgumentElimination.cpp
@@ -87,11 +87,6 @@ public:
   virtual bool shouldHackArguments() const { return false; }
 };
 
-bool isMustTailCalleeAnalyzable(const CallBase &CB) {
-  assert(CB.isMustTailCall());
-  return CB.getCalledFunction() && !CB.getCalledFunction()->isDeclaration();
-}
-
 } // end anonymous namespace
 
 char DAE::ID = 0;
@@ -280,7 +275,7 @@ bool DeadArgumentEliminationPass::removeDeadArgumentsFromCallers(Function &F) {
   // they are fully alive (e.g., called indirectly) and except for the fragile
   // (variadic) ones. In these cases, we may still be able to improve their
   // statically known call sites.
-  if ((F.hasLocalLinkage() && !LiveFunctions.count(&F)) &&
+  if ((F.hasLocalLinkage() && !FrozenFunctions.count(&F)) &&
       !F.getFunctionType()->isVarArg())
     return false;
 
@@ -496,7 +491,7 @@ void DeadArgumentEliminationPass::surveyFunction(const Function &F) {
   // particular register and memory layout.
   if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
       F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) {
-    markLive(F);
+    markFrozen(F);
     return;
   }
 
@@ -504,7 +499,7 @@ void DeadArgumentEliminationPass::surveyFunction(const Function &F) {
   // otherwise rely on the frame layout in a way that this analysis will not
   // see.
   if (F.hasFnAttribute(Attribute::Naked)) {
-    markLive(F);
+    markFrozen(F);
     return;
   }
 
@@ -522,29 +517,17 @@ void DeadArgumentEliminationPass::surveyFunction(const Function &F) {
   // MaybeLive. Initialized to a list of RetCount empty lists.
   RetUses MaybeLiveRetUses(RetCount);
 
-  bool HasMustTailCalls = false;
   for (const BasicBlock &BB : F) {
-    // If we have any returns of `musttail` results - the signature can't
-    // change
-    if (const auto *TC = BB.getTerminatingMustTailCall()) {
-      HasMustTailCalls = true;
-      // In addition, if the called function is not locally defined (or unknown,
-      // if this is an indirect call), we can't change the callsite and thus
-      // can't change this function's signature either.
-      if (!isMustTailCalleeAnalyzable(*TC)) {
-        markLive(F);
+    if (BB.getTerminatingMustTailCall()) {
+      LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName()
+                        << " has musttail calls\n");
+      if (markFnOrRetTyFrozenOnMusttail(F))
         return;
-      }
     }
   }
 
-  if (HasMustTailCalls) {
-    LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName()
-                      << " has musttail calls\n");
-  }
-
   if (!F.hasLocalLinkage() && (!ShouldHackArguments || F.isIntrinsic())) {
-    markLive(F);
+    markFrozen(F);
     return;
   }
 
@@ -555,8 +538,6 @@ void DeadArgumentEliminationPass::surveyFunction(const Function &F) {
   // of them turn out to be live.
   unsigned NumLiveRetVals = 0;
 
-  bool HasMustTailCallers = false;
-
   // Loop all uses of the function.
   for (const Use &U : F.uses()) {
     // If the function is PASSED IN as an argument, its address has been
@@ -564,14 +545,16 @@ void DeadArgumentEliminationPass::surveyFunction(const Function &F) {
     const auto *CB = dyn_cast<CallBase>(U.getUser());
     if (!CB || !CB->isCallee(&U) ||
         CB->getFunctionType() != F.getFunctionType()) {
-      markLive(F);
+      markFrozen(F);
       return;
     }
 
-    // The number of arguments for `musttail` call must match the number of
-    // arguments of the caller
-    if (CB->isMustTailCall())
-      HasMustTailCallers = true;
+    if (CB->isMustTailCall()) {
+      LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName()
+                        << " has musttail callers\n");
+      if (markFnOrRetTyFrozenOnMusttail(F))
+        return;
+    }
 
     // If we end up here, we are looking at a direct call to our function.
 
@@ -610,11 +593,6 @@ void DeadArgumentEliminationPass::surveyFunction(const Function &F) {
     }
   }
 
-  if (HasMustTailCallers) {
-    LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName()
-                      << " has musttail callers\n");
-  }
-
   // Now we've inspected all callers, record the liveness of our return values.
   for (unsigned Ri = 0; Ri != RetCount; ++Ri)
     markValue(createRet(&F, Ri), RetValLiveness[Ri], MaybeLiveRetUses[Ri]);
@@ -628,19 +606,12 @@ void DeadArgumentEliminationPass::surveyFunction(const Function &F) {
   for (Function::const_arg_iterator AI = F.arg_begin(), E = F.arg_end();
        AI != E; ++AI, ++ArgI) {
     Liveness Result;
-    if (F.getFunctionType()->isVarArg() || HasMustTailCallers ||
-        HasMustTailCalls) {
+    if (F.getFunctionType()->isVarArg()) {
       // Variadic functions will already have a va_arg function expanded inside
       // them, making them potentially very sensitive to ABI changes resulting
       // from removing arguments entirely, so don't. For example AArch64 handles
       // register and stack HFAs very differently, and this is reflected in the
       // IR which has already been generated.
-      //
-      // `musttail` calls to this function restrict argument removal attempts.
-      // The signature of the caller must match the signature of the function.
-      //
-      // `musttail` calls in this function prevents us from changing its
-      // signature
       Result = Live;
     } else {
       // See what the effect of this use is (recording any uses that cause
@@ -680,14 +651,30 @@ void DeadArgumentEliminationPass::markValue(const RetOrArg &RA, Liveness L,
   }
 }
 
+/// Return true if we freeze the whole function.
+/// If the calling convention is not swifttailcc or tailcc, the caller and
+/// callee of musttail must have exactly the same signature. Otherwise we
+/// only needs to guarantee they have the same return type.
+bool DeadArgumentEliminationPass::markFnOrRetTyFrozenOnMusttail(
+    const Function &F) {
+  if (F.getCallingConv() != CallingConv::SwiftTail ||
+      F.getCallingConv() != CallingConv::Tail) {
+    markFrozen(F);
+    return true;
+  } else {
+    markRetTyFrozen(F);
+    return false;
+  }
+}
+
 /// Mark the given Function as alive, meaning that it cannot be changed in any
 /// way. Additionally, mark any values that are used as this function's
 /// parameters or by its return values (according to Uses) live as well.
-void DeadArgumentEliminationPass::markLive(const Function &F) {
-  LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Intrinsically live fn: "
+void DeadArgumentEliminationPass::markFrozen(const Function &F) {
+  LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - frozen fn: "
                     << F.getName() << "\n");
-  // Mark the function as live.
-  LiveFunctions.insert(&F);
+  // Mark the function as frozen.
+  FrozenFunctions.insert(&F);
   // Mark all arguments as live.
   for (unsigned ArgI = 0, E = F.arg_size(); ArgI != E; ++ArgI)
     propagateLiveness(createArg(&F, ArgI));
@@ -696,6 +683,12 @@ void DeadArgumentEliminationPass::markLive(const Function &F) {
     propagateLiveness(createRet(&F, Ri));
 }
 
+void DeadArgumentEliminationPass::markRetTyFrozen(const Function &F) {
+  LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - frozen return type fn: "
+                    << F.getName() << "\n");
+  FrozenRetTyFunctions.insert(&F);
+}
+
 /// Mark the given return value or argument as live. Additionally, mark any
 /// values that are used by this value (according to Uses) live as well.
 void DeadArgumentEliminationPass::markLive(const RetOrArg &RA) {
@@ -710,7 +703,7 @@ void DeadArgumentEliminationPass::markLive(const RetOrArg &RA) {
 }
 
 bool DeadArgumentEliminationPass::isLive(const RetOrArg &RA) {
-  return LiveFunctions.count(RA.F) || LiveValues.count(RA);
+  return FrozenFunctions.count(RA.F) || LiveValues.count(RA);
 }
 
 /// Given that RA is a live value, propagate it's liveness to any other values
@@ -734,8 +727,8 @@ void DeadArgumentEliminationPass::propagateLiveness(const RetOrArg &RA) {
 /// Transform the function and all the callees of the function to not have these
 /// arguments and return values.
 bool DeadArgumentEliminationPass::removeDeadStuffFromFunction(Function *F) {
-  // Don't modify fully live functions
-  if (LiveFunctions.count(F))
+  // Don't modify frozen functions
+  if (FrozenFunctions.count(F))
     return false;
 
   // Start by computing a new prototype for the function, which is the same as
@@ -807,7 +800,8 @@ bool DeadArgumentEliminationPass::removeDeadStuffFromFunction(Function *F) {
   // performance win, so the second option can just be used always for now.
   //
   // This should be revisited if 'returned' is ever applied more liberally.
-  if (RetTy->isVoidTy() || HasLiveReturnedArg) {
+  if (RetTy->isVoidTy() || HasLiveReturnedArg ||
+      FrozenRetTyFunctions.count(F)) {
     NRetTy = RetTy;
   } else {
     // Look at each of the original return values individually.
@@ -1109,26 +1103,6 @@ bool DeadArgumentEliminationPass::removeDeadStuffFromFunction(Function *F) {
   return true;
 }
 
-void DeadArgumentEliminationPass::propagateVirtMustcallLiveness(
-    const Module &M) {
-  // If a function was marked "live", and it has musttail callers, they in turn
-  // can't change either.
-  LiveFuncSet NewLiveFuncs(LiveFunctions);
-  while (!NewLiveFuncs.empty()) {
-    LiveFuncSet Temp;
-    for (const auto *F : NewLiveFuncs)
-      for (const auto *U : F->users())
-        if (const auto *CB = dyn_cast<CallBase>(U))
-          if (CB->isMustTailCall())
-            if (!LiveFunctions.count(CB->getParent()->getParent()))
-              Temp.insert(CB->getParent()->getParent());
-    NewLiveFuncs.clear();
-    NewLiveFuncs.insert(Temp.begin(), Temp.end());
-    for (const auto *F : Temp)
-      markLive(*F);
-  }
-}
-
 PreservedAnalyses DeadArgumentEliminationPass::run(Module &M,
                                                    ModuleAnalysisManager &) {
   bool Changed = false;
@@ -1149,8 +1123,6 @@ PreservedAnalyses DeadArgumentEliminationPass::run(Module &M,
   for (auto &F : M)
     surveyFunction(F);
 
-  propagateVirtMustcallLiveness(M);
-
   // Now, remove all dead arguments and return values from each function in
   // turn.  We use make_early_inc_range here because functions will probably get
   // removed (i.e. replaced by new ones).


Regression tests:
file: llvm/test/Transforms/DeadArgElim/musttail-caller.ll
commands: opt -passes=deadargelim -S < %s
tests: test_name: test
test_body: define hidden void @test(i32 %a, i32 %b) {
  musttail call void @foo(i32 %a, i32 0)
  ret void
}

declare hidden void @foo(i32, i32)

test_name: foo
test_body: define hidden void @foo(i32 %a, i32 %b) {
  ret void
}

file: llvm/test/Transforms/DeadArgElim/musttail-verifier.ll
commands: opt -passes=deadargelim -S < %s
tests: test_name: <module>
test_body: ; Testcases comes from PR126817 and PR107569
; See PR54964 and langref for more information about how llvm deal with musttail currently

define i64 @A() {
;
entry:
  %v2660 = musttail call i64 @B()
  ret i64 %v2660
}

define internal i64 @B() {
;
entry:
  ret i64 0
}

define internal i64 @C() {
;
entry:
  %v30543 = musttail call i64 @B()
  ret i64 %v30543
}

%struct.S = type { double }

define internal %struct.S @F38() {
;
  ret %struct.S { double 0.0 }
}

define internal %struct.S @F36() {
;
  %1 = alloca %struct.S, align 8
  %3 = musttail call %struct.S @F38()
  ret %struct.S %3
}

define double @foo() {
;
  %3 = call %struct.S @F36()
  %5 = extractvalue %struct.S %3, 0
  ret double %5
}