43 #define DEBUG_TYPE "deadargelim"
45 STATISTIC(NumArgumentsEliminated,
"Number of unread args removed");
46 STATISTIC(NumRetValsEliminated ,
"Number of unused return values removed");
48 "Number of unread args replaced with undef");
63 bool runOnModule(
Module &M)
override {
72 virtual bool ShouldHackArguments()
const {
return false; }
78 INITIALIZE_PASS(DAE,
"deadargelim",
"Dead Argument Elimination",
false,
false)
84 struct DAH :
public DAE {
88 bool ShouldHackArguments()
const override {
return true; }
94 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
105 bool DeadArgumentEliminationPass::DeleteDeadVarargs(
Function &Fn) {
130 if (II->getIntrinsicID() == Intrinsic::vastart)
146 unsigned NumArgs = Params.size();
152 Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF);
158 std::vector<Value*>
Args;
166 Args.assign(
CS.arg_begin(),
CS.arg_begin() + NumArgs);
172 for (
unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo)
179 CS.getOperandBundlesAsDefs(OpBundles);
182 if (
InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
184 Args, OpBundles,
"", Call);
188 ->setTailCallKind(cast<CallInst>(Call)->getTailCallKind());
195 NewCS->setProfWeight(W);
202 NewCS->takeName(Call);
221 I->replaceAllUsesWith(&*I2);
234 Fn.eraseFromParent();
241 bool DeadArgumentEliminationPass::RemoveDeadArgumentsFromCallers(
Function &Fn) {
272 if (!Arg.hasSwiftErrorAttr() && Arg.use_empty() && !Arg.hasByValOrInAllocaAttr())
276 if (UnusedArgs.
empty())
279 bool Changed =
false;
283 if (!CS || !
CS.isCallee(&U))
287 for (
unsigned I = 0,
E = UnusedArgs.
size();
I !=
E; ++
I) {
288 unsigned ArgNo = UnusedArgs[
I];
290 Value *Arg =
CS.getArgument(ArgNo);
292 ++NumArgumentsReplacedWithUndef;
307 else if (
StructType *STy = dyn_cast<StructType>(RetTy))
308 return STy->getNumElements();
309 else if (
ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
310 return ATy->getNumElements();
322 if (
StructType *STy = dyn_cast<StructType>(RetTy))
323 return STy->getElementType(Idx);
324 else if (
ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
325 return ATy->getElementType();
334 DeadArgumentEliminationPass::MarkIfNotLive(RetOrArg
Use,
335 UseVector &MaybeLiveUses) {
342 MaybeLiveUses.push_back(Use);
355 DeadArgumentEliminationPass::SurveyUse(
const Use *U, UseVector &MaybeLiveUses,
356 unsigned RetValNum) {
357 const User *V = U->getUser();
358 if (
const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
363 const Function *
F = RI->getParent()->getParent();
364 if (RetValNum != -1U) {
367 return MarkIfNotLive(Use, MaybeLiveUses);
370 for (
unsigned i = 0; i <
NumRetVals(F); ++i) {
376 MarkIfNotLive(Use, MaybeLiveUses);
389 RetValNum = *IV->idx_begin();
395 for (
const Use &UU : IV->uses()) {
396 Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
409 if (
CS.isBundleOperand(U))
416 unsigned ArgNo =
CS.getArgumentNo(U);
423 ==
CS->getOperand(U->getOperandNo())
424 &&
"Argument is not where we expected it");
429 return MarkIfNotLive(Use, MaybeLiveUses);
443 DeadArgumentEliminationPass::SurveyUses(
const Value *V,
444 UseVector &MaybeLiveUses) {
448 for (
const Use &U : V->
uses()) {
449 Result = SurveyUse(&U, MaybeLiveUses);
464 void DeadArgumentEliminationPass::SurveyFunction(
const Function &F) {
483 RetVals RetValLiveness(RetCount,
MaybeLive);
489 RetUses MaybeLiveRetUses(RetCount);
492 if (
const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
493 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
505 DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Inspecting callers for fn: "
509 unsigned NumLiveRetVals = 0;
511 for (
const Use &U : F.
uses()) {
515 if (!CS || !
CS.isCallee(&U)) {
531 if (NumLiveRetVals == RetCount)
535 for (
const Use &U : TheCall->
uses()) {
539 unsigned Idx = *
Ext->idx_begin();
540 if (RetValLiveness[Idx] !=
Live) {
541 RetValLiveness[Idx] = SurveyUses(
Ext, MaybeLiveRetUses[Idx]);
542 if (RetValLiveness[Idx] ==
Live)
549 if (SurveyUse(&U, MaybeLiveAggregateUses) ==
Live) {
550 NumLiveRetVals = RetCount;
551 RetValLiveness.assign(RetCount,
Live);
554 for (
unsigned i = 0; i != RetCount; ++i) {
555 if (RetValLiveness[i] !=
Live)
556 MaybeLiveRetUses[i].append(MaybeLiveAggregateUses.begin(),
557 MaybeLiveAggregateUses.end());
565 for (
unsigned i = 0; i != RetCount; ++i)
566 MarkValue(
CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
568 DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Inspecting args for fn: "
587 Result = SurveyUses(&*AI, MaybeLiveArgUses);
591 MarkValue(
CreateArg(&F, i), Result, MaybeLiveArgUses);
593 MaybeLiveArgUses.clear();
601 void DeadArgumentEliminationPass::MarkValue(
const RetOrArg &RA, Liveness
L,
602 const UseVector &MaybeLiveUses) {
604 case Live: MarkLive(RA);
break;
609 for (
const auto &MaybeLiveUse : MaybeLiveUses)
610 Uses.insert(std::make_pair(MaybeLiveUse, RA));
620 void DeadArgumentEliminationPass::MarkLive(
const Function &F) {
621 DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Intrinsically live fn: "
626 for (
unsigned i = 0, e = F.
arg_size(); i != e; ++i)
629 for (
unsigned i = 0, e =
NumRetVals(&F); i != e; ++i)
636 void DeadArgumentEliminationPass::MarkLive(
const RetOrArg &RA) {
643 DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Marking "
644 << RA.getDescription() <<
" live\n");
645 PropagateLiveness(RA);
650 void DeadArgumentEliminationPass::PropagateLiveness(
const RetOrArg &RA) {
654 UseMap::iterator Begin =
Uses.lower_bound(RA);
655 UseMap::iterator
E =
Uses.end();
657 for (I = Begin; I != E && I->first == RA; ++
I)
662 Uses.erase(Begin, I);
669 bool DeadArgumentEliminationPass::RemoveDeadStuffFromFunction(
Function *F) {
677 std::vector<Type*> Params;
680 bool HasLiveReturnedArg =
false;
696 Params.push_back(I->getType());
701 ++NumArgumentsEliminated;
702 DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Removing argument " << i
703 <<
" (" << I->getName() <<
") from " << F->
getName()
710 Type *NRetTy =
nullptr;
715 std::vector<Type*> RetTypes;
736 if (RetTy->
isVoidTy() || HasLiveReturnedArg) {
740 for (
unsigned i = 0; i != RetCount; ++i) {
744 NewRetIdxs[i] = RetTypes.size() - 1;
746 ++NumRetValsEliminated;
747 DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Removing return value "
748 << i <<
" from " << F->
getName() <<
"\n");
751 if (RetTypes.size() > 1) {
753 if (
StructType *STy = dyn_cast<StructType>(RetTy)) {
756 NRetTy =
StructType::get(STy->getContext(), RetTypes, STy->isPacked());
758 assert(isa<ArrayType>(RetTy) &&
"unexpected multi-value return");
761 }
else if (RetTypes.size() == 1)
764 NRetTy = RetTypes.front();
765 else if (RetTypes.size() == 0)
770 assert(NRetTy &&
"No new return type found?");
783 "Return attributes no longer compatible?");
812 std::vector<Value*>
Args;
837 if (NRetTy != RetTy && Attrs.
hasAttribute(Attribute::Returned)) {
864 CS.getOperandBundlesAsDefs(OpBundles);
867 if (
InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
869 Args, OpBundles,
"", Call->getParent());
873 ->setTailCallKind(cast<CallInst>(Call)->getTailCallKind());
877 NewCS->setDebugLoc(Call->getDebugLoc());
879 if (Call->extractProfTotalWeight(W))
880 NewCS->setProfWeight(W);
885 if (!Call->use_empty()) {
886 if (New->
getType() == Call->getType()) {
893 if (!Call->getType()->isX86_MMXTy())
897 "Return type changed, but not into a void. The old return type"
898 " must have been a struct or an array!");
900 if (
InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
911 for (
unsigned i = 0; i != RetCount; ++i)
912 if (NewRetIdxs[i] != -1) {
914 if (RetTypes.size() > 1)
927 Call->replaceAllUsesWith(RetVal);
934 Call->eraseFromParent();
950 I->replaceAllUsesWith(&*I2);
956 if (!I->getType()->isX86_MMXTy())
964 if (
ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
967 if (NFTy->getReturnType()->isVoidTy()) {
976 Value *OldRet = RI->getOperand(0);
979 for (
unsigned i = 0; i != RetCount; ++i)
980 if (NewRetIdxs[i] != -1) {
983 if (RetTypes.size() > 1) {
999 BB.getInstList().erase(RI);
1013 bool Changed =
false;
1019 DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Deleting dead varargs\n");
1023 Changed |= DeleteDeadVarargs(F);
1030 DEBUG(
dbgs() <<
"DeadArgumentEliminationPass - Determining liveness\n");
1040 Changed |= RemoveDeadStuffFromFunction(F);
1046 Changed |= RemoveDeadArgumentsFromCallers(F);
AttributeSet getRetAttributes() const
The attributes for the ret value are returned.
Return a value (possibly void), from a function.
User::op_iterator arg_iterator
The type of iterator to use when looping over actual arguments at this call site. ...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
LinkageTypes getLinkage() const
iterator_range< use_iterator > uses()
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
This class represents an incoming formal argument to a Function.
Eliminate dead arguments (and return values) from functions.
bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
STATISTIC(NumFunctions,"Total number of functions")
A Module instance is used to store all the information related to an LLVM module. ...
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
This class represents a function call, abstracting a target machine's calling convention.
bool isIntrinsic() const
isIntrinsic - Returns true if the function's name starts with "llvm.".
bool hasExactDefinition() const
Return true if this global has an exact defintion.
RetOrArg CreateArg(const Function *F, unsigned Idx)
Convenience wrapper.
LiveSet LiveValues
This set contains all values that have been determined to be live.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
AttributeList getAttributes() const
Return the attribute list for this Function.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
AttributeSet getParamAttributes(unsigned ArgNo) const
The attributes for the argument or parameter at the given index are returned.
Class to represent struct types.
ModulePass * createDeadArgHackingPass()
DeadArgHacking pass - Same as DAE, but delete arguments of external functions as well.
A Use represents the edge between a Value definition and its users.
param_iterator param_end() const
bool isMustTailCall() const
LLVM_NODISCARD bool empty() const
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
Class to represent function types.
bool hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const
Equivalent to hasAttribute(ArgNo + FirstArgIndex, Kind).
Class to represent array types.
void setComdat(Comdat *C)
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
AttrBuilder & remove(const AttrBuilder &B)
Remove the attributes from the builder.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isArrayTy() const
True if this is an instance of ArrayType.
void takeName(Value *V)
Transfer the name from V to this value.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
Type * getReturnType() const
Returns the type of the ret val.
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
A set of analyses that are preserved following a run of a transformation pass.
static AttributeSet get(LLVMContext &C, const AttrBuilder &B)
static unsigned getAggregateOperandIndex()
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
FunctionType * getFunctionType() const
Returns the FunctionType for me.
const Comdat * getComdat() const
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
param_iterator param_begin() const
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
ModulePass * createDeadArgEliminationPass()
createDeadArgEliminationPass - This pass removes arguments from functions which are not used by the b...
void initializeDAEPass(PassRegistry &)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
static Type * getVoidTy(LLVMContext &C)
void splice(iterator where, iplist_impl &L2)
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
self_iterator getIterator()
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool areAllPreserved() const
Test whether all analyses are preserved (and none are abandoned).
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, Instruction *InsertBefore=nullptr)
const FunctionListType & getFunctionList() const
Get the Module's list of functions (constant).
bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
static unsigned NumRetVals(const Function *F)
Convenience function that returns the number of return values.
Iterator for intrusive lists based on ilist_node.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
InstrTy * getInstruction() const
bool isEmpty() const
Return true if there are no attributes.
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
AttrBuilder & removeAttribute(Attribute::AttrKind Val)
Remove an attribute from the builder.
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
static Type * getRetComponentType(const Function *F, unsigned Idx)
Returns the sub-type a function will return at a given Idx.
AttributeSet getFnAttributes() const
The function attributes are returned.
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
DISubprogram * getSubprogram() const
Get the attached subprogram.
UseMap Uses
This maps a return value or argument to any MaybeLive return values or arguments it uses...
LiveFuncSet LiveFunctions
This set contains all values that are cannot be changed in any way.
RetOrArg CreateRet(const Function *F, unsigned Idx)
Convenience wrapper.
bool isStructTy() const
True if this is an instance of StructType.
INITIALIZE_PASS(DAH,"deadarghaX0r","Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)", false, false) ModulePass *llvm
createDeadArgEliminationPass - This pass removes arguments from functions which are not used by the b...
PointerType * getType() const
Global values are always pointers.
iterator insert(iterator where, pointer New)
bool hasAddressTaken(const User **=nullptr) const
hasAddressTaken - returns true if there are any uses of this function other than direct calls or invo...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Establish a view to a call site for examination.
bool ShouldHackArguments
This allows this pass to do double-duty as the dead arg hacking pass (used only by bugpoint)...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
user_iterator_impl< User > user_iterator
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
bool hasLocalLinkage() const
SmallVector< RetOrArg, 5 > UseVector
Type * getReturnType() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Liveness
Liveness enum - During our initial pass over the program, we determine that things are either alive o...
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
AttrBuilder typeIncompatible(Type *Ty)
Which attributes cannot be applied to a type.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
bool hasAttrSomewhere(Attribute::AttrKind Kind, unsigned *Index=nullptr) const
Return true if the specified attribute is set for at least one parameter or for the return value...
A container for analyses that lazily runs them and caches their results.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
const BasicBlock * getParent() const
static AttributeList get(LLVMContext &C, ArrayRef< std::pair< unsigned, Attribute >> Attrs)
Create an AttributeList with the specified parameters in it.
iterator_range< arg_iterator > args()
A wrapper class for inspecting calls to intrinsic functions.
bool isVoidTy() const
Return true if this is 'void'.
This instruction inserts a struct field of array element value into an aggregate value.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)