46 #define DEBUG_TYPE "mergefunc"
70 STATISTIC(NumFunctionsMerged,
"Number of functions merged");
71 STATISTIC(NumThunksWritten,
"Number of thunks generated");
72 STATISTIC(NumAliasesWritten,
"Number of aliases generated");
73 STATISTIC(NumDoubleWeak,
"Number of new functions created");
96 for (
unsigned i = 0, e = FTy->
getNumParams(); i != e; ++i)
105 class ComparableFunction {
107 static const ComparableFunction EmptyKey;
108 static const ComparableFunction TombstoneKey;
115 unsigned getHash()
const {
return Hash; }
122 "Attempted to release function twice, or release empty/tombstone!");
127 explicit ComparableFunction(
unsigned Hash)
128 :
Func(NULL), Hash(Hash),
TD(NULL) {}
135 const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0);
136 const ComparableFunction ComparableFunction::TombstoneKey =
137 ComparableFunction(1);
146 return ComparableFunction::EmptyKey;
149 return ComparableFunction::TombstoneKey;
154 static bool isEqual(
const ComparableFunction &LHS,
155 const ComparableFunction &RHS);
165 class FunctionComparator {
169 : F1(F1), F2(F2), TD(TD) {}
193 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2));
197 bool isEquivalentType(
Type *Ty1,
Type *Ty2)
const;
212 bool FunctionComparator::isEquivalentType(
Type *Ty1,
Type *Ty2)
const {
218 if (isa<PointerType>(Ty1) && Ty2 ==
TD->getIntPtrType(Ty1))
221 if (isa<PointerType>(Ty2) && Ty1 ==
TD->getIntPtrType(Ty2))
258 if (STy1->
isPacked() != STy2->isPacked())
262 if (!isEquivalentType(STy1->
getElementType(i), STy2->getElementType(i)))
272 FTy1->
isVarArg() != FTy2->isVarArg())
275 if (!isEquivalentType(FTy1->
getReturnType(), FTy2->getReturnType()))
278 for (
unsigned i = 0, e = FTy1->
getNumParams(); i != e; ++i) {
279 if (!isEquivalentType(FTy1->
getParamType(i), FTy2->getParamType(i)))
297 bool FunctionComparator::isEquivalentOperation(
const Instruction *I1,
317 if (
const LoadInst *
LI = dyn_cast<LoadInst>(I1))
318 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
319 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() &&
320 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
321 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
322 if (
const StoreInst *SI = dyn_cast<StoreInst>(I1))
323 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
324 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() &&
325 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
326 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
327 if (
const CmpInst *CI = dyn_cast<CmpInst>(I1))
328 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
329 if (
const CallInst *CI = dyn_cast<CallInst>(I1))
330 return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
332 if (
const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
333 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
334 CI->getAttributes() == cast<InvokeInst>(I2)->
getAttributes();
336 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
338 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
339 if (
const FenceInst *FI = dyn_cast<FenceInst>(I1))
340 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
341 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
343 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
344 CXI->getOrdering() == cast<AtomicCmpXchgInst>(I2)->getOrdering() &&
345 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
347 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
348 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
349 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
350 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
356 bool FunctionComparator::isEquivalentGEP(
const GEPOperator *GEP1,
365 unsigned BitWidth =
TD ?
TD->getPointerSizeInBits(AS) : 1;
366 APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0);
369 return Offset1 == Offset2;
391 bool FunctionComparator::enumerate(
const Value *V1,
const Value *
V2) {
395 if (V1 == F1 && V2 == F2)
397 if (V1 == F2 && V2 == F1)
400 if (
const Constant *C1 = dyn_cast<Constant>(V1)) {
401 if (V1 == V2)
return true;
403 if (!C2)
return false;
406 isEquivalentType(C1->getType(), C2->
getType()))
414 if (isa<InlineAsm>(V1) || isa<InlineAsm>(
V2))
422 const Value *&map_elem = id_map[V1];
424 return map_elem ==
V2;
425 if (!seen_values.insert(V2).second)
437 if (!enumerate(F1I, F2I))
448 if (!isEquivalentGEP(GEP1, GEP2))
451 if (!isEquivalentOperation(F1I, F2I))
454 assert(F1I->getNumOperands() == F2I->getNumOperands());
455 for (
unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) {
456 Value *OpF1 = F1I->getOperand(i);
457 Value *OpF2 = F2I->getOperand(i);
459 if (!enumerate(OpF1, OpF2))
469 }
while (F1I != F1E && F2I != F2E);
471 return F1I == F1E && F2I == F2E;
475 bool FunctionComparator::compare() {
479 if (F1->getAttributes() != F2->getAttributes())
482 if (F1->hasGC() != F2->hasGC())
485 if (F1->hasGC() && F1->getGC() != F2->getGC())
488 if (F1->hasSection() != F2->hasSection())
491 if (F1->hasSection() && F1->getSection() != F2->getSection())
494 if (F1->isVarArg() != F2->isVarArg())
499 if (F1->getCallingConv() != F2->getCallingConv())
502 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType()))
505 assert(F1->arg_size() == F2->arg_size() &&
506 "Identically typed functions have different numbers of args!");
511 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) {
512 if (!enumerate(f1i, f2i))
526 VisitedBBs.
insert(F1BBs[0]);
527 while (!F1BBs.
empty()) {
531 if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB))
564 bool runOnModule(
Module &M);
571 std::vector<WeakVH> Deferred;
575 bool insert(ComparableFunction &NewF);
583 void removeUsers(
Value *V);
612 bool HasGlobalAliases;
618 INITIALIZE_PASS(MergeFunctions,
"mergefunc",
"Merge Functions",
false,
false)
621 return new MergeFunctions();
624 bool MergeFunctions::runOnModule(
Module &M) {
625 bool Changed =
false;
626 TD = getAnalysisIfAvailable<DataLayout>();
629 if (!
I->isDeclaration() && !
I->hasAvailableExternallyLinkage())
632 FnSet.resize(Deferred.size());
635 std::vector<WeakVH> Worklist;
636 Deferred.swap(Worklist);
639 DEBUG(
dbgs() <<
"size of worklist: " << Worklist.size() <<
'\n');
643 for (std::vector<WeakVH>::iterator
I = Worklist.begin(),
644 E = Worklist.end();
I != E; ++
I) {
649 ComparableFunction CF = ComparableFunction(F,
TD);
650 Changed |= insert(CF);
658 for (std::vector<WeakVH>::iterator I = Worklist.begin(),
659 E = Worklist.end(); I != E; ++
I) {
664 ComparableFunction CF = ComparableFunction(F,
TD);
665 Changed |= insert(CF);
668 DEBUG(
dbgs() <<
"size of FnSet: " << FnSet.size() <<
'\n');
669 }
while (!Deferred.empty());
677 const ComparableFunction &RHS) {
678 if (LHS.getFunc() == RHS.getFunc() &&
679 LHS.getHash() == RHS.getHash())
681 if (!LHS.getFunc() || !RHS.getFunc())
685 if (LHS.getTD() == ComparableFunction::LookupOnly ||
686 RHS.getTD() == ComparableFunction::LookupOnly)
689 assert(LHS.getTD() == RHS.getTD() &&
690 "Comparing functions for different targets");
692 return FunctionComparator(LHS.getTD(), LHS.getFunc(),
693 RHS.getFunc()).compare();
704 if (CS && CS.isCallee(TheIter)) {
705 remove(CS.getInstruction()->getParent()->getParent());
742 replaceDirectCallers(G, F);
766 CallInst *CI = Builder.CreateCall(F, Args);
770 Builder.CreateRetVoid();
797 DEBUG(
dbgs() <<
"writeAlias: " << GA->getName() <<
'\n');
806 if (HasGlobalAliases) {
825 replaceDirectCallers(G, F);
830 writeThunkOrAlias(F, G);
833 ++NumFunctionsMerged;
838 bool MergeFunctions::insert(ComparableFunction &NewF) {
839 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF);
841 DEBUG(
dbgs() <<
"Inserting as unique: " << NewF.getFunc()->getName() <<
'\n');
845 const ComparableFunction &OldF = *Result.first;
851 if (NewF.getFunc()->size() == 1) {
852 if (NewF.getFunc()->front().size() <= 2) {
853 DEBUG(
dbgs() << NewF.getFunc()->getName()
854 <<
" is to small to bother merging\n");
860 assert(!OldF.getFunc()->mayBeOverridden() ||
861 NewF.getFunc()->mayBeOverridden());
863 DEBUG(
dbgs() <<
" " << OldF.getFunc()->getName() <<
" == "
864 << NewF.getFunc()->getName() <<
'\n');
868 mergeTwoFunctions(OldF.getFunc(), DeleteF);
881 ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly);
882 if (FnSet.erase(CF)) {
883 DEBUG(
dbgs() <<
"Removed " << F->
getName() <<
" from set and deferred it.\n");
884 Deferred.push_back(F);
890 void MergeFunctions::removeUsers(
Value *V) {
891 std::vector<Value *> Worklist;
892 Worklist.push_back(V);
893 while (!Worklist.empty()) {
894 Value *V = Worklist.back();
899 Use &U = UI.getUse();
901 remove(I->getParent()->getParent());
902 }
else if (isa<GlobalValue>(U.
getUser())) {
907 Worklist.push_back(*CUI);
void push_back(const T &Elt)
LinkageTypes getLinkage() const
static Value * createCast(IRBuilder< false > &Builder, Value *V, Type *DestTy)
Value * getPointerOperand()
Abstract base class of comparison instructions.
static PassRegistry * getPassRegistry()
LLVMContext & getContext() const
VisibilityTypes getVisibility() const
int remove(const char *path);
The main container class for the LLVM Intermediate Representation.
unsigned getNumParams() const
static unsigned getHashValue(const ComparableFunction &CF)
2: 32-bit floating point type
unsigned getAlignment() const
ModulePass * createMergeFunctionsPass()
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
unsigned getNumOperands() const
STATISTIC(NumFunctionsMerged,"Number of functions merged")
Like Internal, but omit from symbol table.
bool hasAvailableExternallyLinkage() const
Type * getReturnType() const
4: 80-bit floating point type (X87)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
LoopInfoBase< BlockT, LoopT > * LI
CallingConv::ID getCallingConv() const
static ComparableFunction getEmptyKey()
StringRef getName() const
static unsigned profileFunction(const Function *F)
void setCallingConv(CallingConv::ID CC)
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
#define llvm_unreachable(msg)
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
bool canLosslesslyBitCastTo(Type *Ty) const
Determine if this type could be losslessly bitcast to Ty.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void AddInteger(signed I)
void copyAttributesFrom(const GlobalValue *Src)
ID
LLVM Calling Convention Representation.
bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const
Accumulate the constant address offset of this GEP if possible.
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
static Type::TypeID getTypeIDForHash(Type *Ty)
void replaceAllUsesWith(Value *V)
void initializeMergeFunctionsPass(PassRegistry &)
Type * getElementType() const
10: Arbitrary bit width integers
unsigned getNumSuccessors() const
Type * getParamType(unsigned i) const
Parameter type accessors.
LLVM Basic Block Representation.
BasicBlock * getSuccessor(unsigned idx) const
static bool mayBeOverridden(LinkageTypes Linkage)
Type * getElementType(unsigned N) const
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
LLVM Constant Representation.
uint64_t getNumElements() const
unsigned getValueID() const
Value * getPointerOperand()
6: 128-bit floating point type (two 64-bits, PowerPC)
Value * getOperand(unsigned i) const
static unsigned getHash(const void *V)
void setTailCall(bool isTC=true)
bool hasWeakLinkage() const
bool hasSameSubclassOptionalData(const Value *V) const
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
bool hasExternalLinkage() const
static Constant * getBitCast(Constant *C, Type *Ty)
15: SIMD 'packed' format, or other vector type
void setAlignment(unsigned Align)
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
void setLinkage(LinkageTypes LT)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
Class for arbitrary precision integers.
PointerType * getType() const
getType - Global values are always pointers.
bool isDeclaration() const
unsigned ComputeHash() const
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
FunctionType * getFunctionType() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=0, BasicBlock *InsertBefore=0)
Creates a new BasicBlock.
unsigned getPointerAddressSpace() const
virtual void eraseFromParent()
AttributeSet getAttributes(LLVMContext &C, ID id)
static ComparableFunction getTombstoneKey()
bool hasLocalLinkage() const
3: 64-bit floating point type
Type * getReturnType() const
LLVM Value Representation.
bool hasUnnamedAddr() const
unsigned getOpcode() const
getOpcode() returns a member of one of the enums like Instruction::Add.
unsigned getNumElements() const
Random access to the elements.
INITIALIZE_PASS(GlobalMerge,"global-merge","Global Merge", false, false) bool GlobalMerge const DataLayout * TD
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=0)
bool isVoidTy() const
isVoidTy - Return true if this is 'void'.
5: 128-bit floating point type (112-bit mantissa)