84 #define DEBUG_TYPE "tailcallelim"
86 STATISTIC(NumEliminated,
"Number of tail calls removed");
87 STATISTIC(NumRetDuped,
"Number of return duplicated");
88 STATISTIC(NumAccumAdded,
"Number of accumulators introduced");
101 struct AllocaDerivedValueTracker {
105 void walk(
Value *Root) {
109 auto AddUsesToWorklist = [&](
Value *V) {
110 for (
auto &U : V->uses()) {
111 if (!Visited.
insert(&U).second)
117 AddUsesToWorklist(Root);
119 while (!Worklist.
empty()) {
125 case Instruction::Invoke: {
128 CS.isDataOperand(U) &&
CS.doesNotCapture(
CS.getDataOperandNo(U));
129 callUsesLocalStack(CS, IsNocapture);
143 if (U->getOperandNo() == 0)
144 EscapePoints.insert(I);
147 case Instruction::BitCast:
148 case Instruction::GetElementPtr:
149 case Instruction::PHI:
151 case Instruction::AddrSpaceCast:
154 EscapePoints.insert(I);
158 AddUsesToWorklist(I);
162 void callUsesLocalStack(
CallSite CS,
bool IsNocapture) {
183 AllCallsAreTailCalls =
true;
186 AllocaDerivedValueTracker Tracker;
188 if (Arg.hasByValAttr())
193 if (
AllocaInst *AI = dyn_cast<AllocaInst>(&I))
197 bool Modified =
false;
224 VisitType Escaped = UNESCAPED;
226 for (
auto &I : *BB) {
227 if (Tracker.EscapePoints.count(&I))
244 bool SafeToTail =
true;
246 if (isa<Constant>(Arg.getUser()))
248 if (
Argument *
A = dyn_cast<Argument>(Arg.getUser()))
249 if (!
A->hasByValAttr())
257 "marked this readnone call a tail call candidate");
264 if (!IsNoTail && Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI)) {
267 AllCallsAreTailCalls =
false;
272 auto &State = Visited[SuccBB];
273 if (State < Escaped) {
275 if (State == ESCAPED)
282 if (!WorklistEscaped.
empty()) {
287 while (!WorklistUnescaped.
empty()) {
289 if (Visited[NextBB] == UNESCAPED) {
298 for (
CallInst *CI : DeferredTails) {
299 if (Visited[CI->getParent()] != ESCAPED) {
304 "marked this call a tail call candidate");
308 AllCallsAreTailCalls =
false;
325 if (
LoadInst *
L = dyn_cast<LoadInst>(I)) {
335 L->getAlignment(),
DL,
L))
354 if (isa<Constant>(V))
return true;
358 if (
Argument *Arg = dyn_cast<Argument>(V)) {
376 if (
SwitchInst *
SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
377 if (
SI->getCondition() == V)
389 Value *ReturnedValue =
nullptr;
393 if (RI ==
nullptr || RI == IgnoreRI)
continue;
403 if (ReturnedValue && RetOp != ReturnedValue)
405 ReturnedValue = RetOp;
407 return ReturnedValue;
416 "Associative/commutative operations should have 2 args!");
434 while (isa<DbgInfoIntrinsic>(I))
440 bool CannotTailCallElimCallsMarkedTail,
445 if (&BB->
front() == TI)
457 if (BBI == BB->
begin())
464 if (CI->
isTailCall() && CannotTailCallElimCallsMarkedTail)
481 for (; I !=
E && FI != FE; ++
I, ++FI)
482 if (*I != &*FI)
break;
483 if (I ==
E && FI == FE)
492 bool &TailCallsAreMarkedTail,
505 Value *AccumulatorRecursionEliminationInitVal =
nullptr;
513 for (++BBI; &*BBI !=
Ret; ++BBI) {
521 if ((AccumulatorRecursionEliminationInitVal =
525 AccumulatorRecursionInstr = &*BBI;
537 AccumulatorRecursionEliminationInitVal ==
nullptr &&
547 if (!AccumulatorRecursionEliminationInitVal)
555 "transforming tail recursion to loop");
563 OldEntry->
setName(
"tailrecurse");
569 if (TailCallsAreMarkedTail)
572 NEBI = NewEntry->
begin(); OEBI !=
E; )
573 if (
AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
574 if (isa<ConstantInt>(AI->getArraySize()))
575 AI->moveBefore(&*NEBI);
585 I->
getName() +
".tr", InsertPos);
598 if (TailCallsAreMarkedTail && !CI->
isTailCall())
612 if (AccumulatorRecursionEliminationInitVal) {
613 Instruction *AccRecInstr = AccumulatorRecursionInstr;
617 AccumulatorRecursionEliminationInitVal->
getType(),
618 std::distance(PB, PE) + 1,
"accumulator.tr", &OldEntry->
front());
629 AccPN->
addIncoming(AccumulatorRecursionEliminationInitVal, P);
653 if (
ReturnInst *RI = dyn_cast<ReturnInst>(BBI.getTerminator()))
654 RI->setOperand(0, AccPN);
671 bool &TailCallsAreMarkedTail,
673 bool CannotTailCallElimCallsMarkedTail,
680 "Trying to fold non-trivial return block");
690 if (
BranchInst *BI = dyn_cast<BranchInst>(PTI))
691 if (BI->isUnconditional())
692 UncondBranchPreds.push_back(BI);
695 while (!UncondBranchPreds.empty()) {
696 BranchInst *BI = UncondBranchPreds.pop_back_val();
700 <<
"INTO UNCOND BRANCH PRED: " << *Pred);
721 bool &TailCallsAreMarkedTail,
723 bool CannotTailCallElimCallsMarkedTail,
739 bool MadeChange =
false;
740 bool AllCallsAreTailCalls =
false;
741 MadeChange |=
markTails(F, AllCallsAreTailCalls);
742 if (!AllCallsAreTailCalls)
751 bool TailCallsAreMarkedTail =
false;
757 bool CanTRETailMarkedCall =
canTRE(F);
770 ArgumentPHIs, !CanTRETailMarkedCall, TTI, AA);
773 TailCallsAreMarkedTail, ArgumentPHIs,
774 !CanTRETailMarkedCall, TTI, AA);
775 MadeChange |= Change;
784 for (
PHINode *PN : ArgumentPHIs) {
787 PN->replaceAllUsesWith(PNV);
788 PN->eraseFromParent();
808 bool runOnFunction(
Function &
F)
override {
813 F, &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
814 &getAnalysis<AAResultsWrapperPass>().getAAResults());
828 return new TailCallElim();
Legacy wrapper pass to provide the GlobalsAAResult object.
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. ...
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
static bool foldReturnAndProcessPred(BasicBlock *BB, ReturnInst *Ret, BasicBlock *&OldEntry, bool &TailCallsAreMarkedTail, SmallVectorImpl< PHINode * > &ArgumentPHIs, bool CannotTailCallElimCallsMarkedTail, const TargetTransformInfo *TTI, AliasAnalysis *AA)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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.
STATISTIC(NumFunctions,"Total number of functions")
iterator erase(iterator where)
This is the interface for a simple mod/ref and alias analysis over globals.
static bool markTails(Function &F, bool &AllCallsAreTailCalls)
unsigned getNumOperands() const
This class represents a function call, abstracting a target machine's calling convention.
static bool eliminateTailRecursion(Function &F, const TargetTransformInfo *TTI, AliasAnalysis *AA)
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Analysis pass providing the TargetTransformInfo.
bool onlyReadsMemory() const
Determine if the call does not access or only reads memory.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & front() const
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
An instruction for reading from memory.
bool isSafeToLoadUnconditionally(Value *V, unsigned Align, const DataLayout &DL, Instruction *ScanFrom=nullptr, const DominatorTree *DT=nullptr)
Return true if we know that executing a load from this value cannot trap.
The access modifies the value stored in memory.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
unsigned getNumArgOperands() const
Return the number of call arguments.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
void setName(const Twine &Name)
Change the name of the value.
LLVM_NODISCARD bool empty() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
static bool eliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret, BasicBlock *&OldEntry, bool &TailCallsAreMarkedTail, SmallVectorImpl< PHINode * > &ArgumentPHIs, AliasAnalysis *AA)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool isNoTailCall() const
void takeName(Value *V)
Transfer the name from V to this value.
bool hasOperandBundles() const
Return true if this User has any operand bundles.
Interval::succ_iterator succ_end(Interval *I)
void emitOptimizationRemark(LLVMContext &Ctx, const char *PassName, const Function &Fn, const DiagnosticLocation &Loc, const Twine &Msg)
Legacy interface to emit an optimization-applied message.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Conditional or Unconditional Branch instruction.
FunctionPass * createTailCallEliminationPass()
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI)
Return true if the specified value is the same when the return would exit as it was when the initial ...
A manager for alias analyses.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool isAssociative() const LLVM_READONLY
Return true if the instruction is associative:
Represent the analysis usage information of a pass.
const InstListType & getInstList() const
Return the underlying instruction list container.
Analysis pass providing a never-invalidated alias analysis result.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
bool doesNotAccessMemory() const
Determine if the call does not access memory.
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
bool isCommutative() const
Return true if the instruction is commutative:
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
void setTailCall(bool isTC=true)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static Instruction * firstNonDbg(BasicBlock::iterator I)
static Value * getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI)
Check to see if the function containing the specified tail call consistently returns the same runtime...
static CallInst * findTRECandidate(Instruction *TI, bool CannotTailCallElimCallsMarkedTail, const TargetTransformInfo *TTI)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
InstrTy * getInstruction() const
INITIALIZE_PASS_BEGIN(TailCallElim,"tailcallelim","Tail Call Elimination", false, false) INITIALIZE_PASS_END(TailCallElim
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_NODISCARD T pop_back_val()
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
const BasicBlock & getEntryBlock() const
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
void initializeTailCallElimPass(PassRegistry &)
ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
static bool canTRE(Function &F)
Scan the specified function for alloca instructions.
static bool canMoveAboveCall(Instruction *I, CallInst *CI, AliasAnalysis *AA)
Return true if it is safe to move the specified instruction from after the call to before the call...
static bool processReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry, bool &TailCallsAreMarkedTail, SmallVectorImpl< PHINode * > &ArgumentPHIs, bool CannotTailCallElimCallsMarkedTail, const TargetTransformInfo *TTI, AliasAnalysis *AA)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
bool hasOneUse() const
Return true if there is exactly one user of this value.
bool callsFunctionThatReturnsTwice() const
callsFunctionThatReturnsTwice - Return true if the function has a call to setjmp or other function th...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
void preserve()
Mark an analysis as preserved.
iterator_range< op_iterator > arg_operands()
Iteration adapter for range-for loops.
StringRef getValueAsString() const
Return the attribute's value as a string.
static Value * canTransformAccumulatorRecursion(Instruction *I, CallInst *CI)
If the specified instruction can be transformed using accumulator recursion elimination, return the constant which is the start of the accumulator value.
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
inst_range instructions(Function *F)
A container for analyses that lazily runs them and caches their results.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
const BasicBlock * getParent() const
iterator_range< arg_iterator > args()
an instruction to allocate memory on the stack
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.