#define DEBUG_TYPE "globalopt"
#include "llvm/Transforms/IPO.h"
#include "llvm/CallingConv.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/STLExtras.h"
#include <algorithm>
using namespace llvm;
STATISTIC(NumMarked , "Number of globals marked constant");
STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
STATISTIC(NumDeleted , "Number of globals deleted");
STATISTIC(NumFnDeleted , "Number of functions deleted");
STATISTIC(NumGlobUses , "Number of global uses devirtualized");
STATISTIC(NumLocalized , "Number of globals localized");
STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
STATISTIC(NumNestRemoved , "Number of nest attributes removed");
STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
namespace {
struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetData>();
}
static char ID; GlobalOpt() : ModulePass(&ID) {}
bool runOnModule(Module &M);
private:
GlobalVariable *FindGlobalCtors(Module &M);
bool OptimizeFunctions(Module &M);
bool OptimizeGlobalVars(Module &M);
bool OptimizeGlobalAliases(Module &M);
bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
};
}
char GlobalOpt::ID = 0;
static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
namespace {
struct VISIBILITY_HIDDEN GlobalStatus {
bool isLoaded;
enum StoredType {
NotStored,
isInitializerStored,
isStoredOnce,
isStored
} StoredType;
Value *StoredOnceValue;
Function *AccessingFunction;
bool HasMultipleAccessingFunctions;
bool HasNonInstructionUser;
bool HasPHIUser;
GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
AccessingFunction(0), HasMultipleAccessingFunctions(false),
HasNonInstructionUser(false), HasPHIUser(false) {}
};
}
static bool ConstantIsDead(Constant *C) {
if (isa<GlobalValue>(C)) return false;
for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
if (Constant *CU = dyn_cast<Constant>(*UI)) {
if (!ConstantIsDead(CU)) return false;
} else
return false;
return true;
}
static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
SmallPtrSet<PHINode*, 16> &PHIUsers) {
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
GS.HasNonInstructionUser = true;
if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
} else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
if (!GS.HasMultipleAccessingFunctions) {
Function *F = I->getParent()->getParent();
if (GS.AccessingFunction == 0)
GS.AccessingFunction = F;
else if (GS.AccessingFunction != F)
GS.HasMultipleAccessingFunctions = true;
}
if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
GS.isLoaded = true;
if (LI->isVolatile()) return true; } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
if (SI->getOperand(0) == V) return true;
if (SI->isVolatile()) return true;
if (GS.StoredType != GlobalStatus::isStored) {
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
Value *StoredVal = SI->getOperand(0);
if (StoredVal == GV->getInitializer()) {
if (GS.StoredType < GlobalStatus::isInitializerStored)
GS.StoredType = GlobalStatus::isInitializerStored;
} else if (isa<LoadInst>(StoredVal) &&
cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
if (GS.StoredType < GlobalStatus::isInitializerStored)
GS.StoredType = GlobalStatus::isInitializerStored;
} else if (GS.StoredType < GlobalStatus::isStoredOnce) {
GS.StoredType = GlobalStatus::isStoredOnce;
GS.StoredOnceValue = StoredVal;
} else if (GS.StoredType == GlobalStatus::isStoredOnce &&
GS.StoredOnceValue == StoredVal) {
} else {
GS.StoredType = GlobalStatus::isStored;
}
} else {
GS.StoredType = GlobalStatus::isStored;
}
}
} else if (isa<GetElementPtrInst>(I)) {
if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
} else if (isa<SelectInst>(I)) {
if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
} else if (PHINode *PN = dyn_cast<PHINode>(I)) {
if (PHIUsers.insert(PN)) if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
GS.HasPHIUser = true;
} else if (isa<CmpInst>(I)) {
} else if (isa<MemTransferInst>(I)) {
if (I->getOperand(1) == V)
GS.StoredType = GlobalStatus::isStored;
if (I->getOperand(2) == V)
GS.isLoaded = true;
} else if (isa<MemSetInst>(I)) {
assert(I->getOperand(1) == V && "Memset only takes one pointer!");
GS.StoredType = GlobalStatus::isStored;
} else {
return true; }
} else if (Constant *C = dyn_cast<Constant>(*UI)) {
GS.HasNonInstructionUser = true;
if (!ConstantIsDead(C))
return true;
} else {
GS.HasNonInstructionUser = true;
return true;
}
return false;
}
static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
if (!CI) return 0;
unsigned IdxV = CI->getZExtValue();
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
} else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
} else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
} else if (isa<ConstantAggregateZero>(Agg)) {
if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
if (IdxV < STy->getNumElements())
return Constant::getNullValue(STy->getElementType(IdxV));
} else if (const SequentialType *STy =
dyn_cast<SequentialType>(Agg->getType())) {
return Constant::getNullValue(STy->getElementType());
}
} else if (isa<UndefValue>(Agg)) {
if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
if (IdxV < STy->getNumElements())
return UndefValue::get(STy->getElementType(IdxV));
} else if (const SequentialType *STy =
dyn_cast<SequentialType>(Agg->getType())) {
return UndefValue::get(STy->getElementType());
}
}
return 0;
}
static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
bool Changed = false;
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
User *U = *UI++;
if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
if (Init) {
LI->replaceAllUsesWith(Init);
LI->eraseFromParent();
Changed = true;
}
} else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
SI->eraseFromParent();
Changed = true;
} else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
if (CE->getOpcode() == Instruction::GetElementPtr) {
Constant *SubInit = 0;
if (Init)
SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
Changed |= CleanupConstantGlobalUsers(CE, SubInit);
} else if (CE->getOpcode() == Instruction::BitCast &&
isa<PointerType>(CE->getType())) {
Changed |= CleanupConstantGlobalUsers(CE, 0);
}
if (CE->use_empty()) {
CE->destroyConstant();
Changed = true;
}
} else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Constant *SubInit = 0;
if (!isa<ConstantExpr>(GEP->getOperand(0))) {
ConstantExpr *CE =
dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
}
Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
if (GEP->use_empty()) {
GEP->eraseFromParent();
Changed = true;
}
} else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { if (MI->getRawDest() == V) {
MI->eraseFromParent();
Changed = true;
}
} else if (Constant *C = dyn_cast<Constant>(U)) {
if (ConstantIsDead(C)) {
C->destroyConstant();
CleanupConstantGlobalUsers(V, Init);
return true;
}
}
}
return Changed;
}
static bool isSafeSROAElementUse(Value *V) {
if (Constant *C = dyn_cast<Constant>(V))
return ConstantIsDead(C);
Instruction *I = dyn_cast<Instruction>(V);
if (!I) return false;
if (isa<LoadInst>(I)) return true;
if (StoreInst *SI = dyn_cast<StoreInst>(I))
return SI->getOperand(0) != V;
GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
if (GEPI == 0) return false;
if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
!cast<Constant>(GEPI->getOperand(1))->isNullValue())
return false;
for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
I != E; ++I)
if (!isSafeSROAElementUse(*I))
return false;
return true;
}
static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
if (!isa<GetElementPtrInst>(U) &&
(!isa<ConstantExpr>(U) ||
cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
return false;
if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
!cast<Constant>(U->getOperand(1))->isNullValue() ||
!isa<ConstantInt>(U->getOperand(2)))
return false;
gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
++GEPI;
if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
uint64_t NumElements = AT->getNumElements();
ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
if (Idx->getZExtValue() >= NumElements)
return false;
for (++GEPI; GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
++GEPI) {
uint64_t NumElements;
if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
NumElements = SubArrayTy->getNumElements();
else
NumElements = cast<VectorType>(*GEPI)->getNumElements();
ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
return false;
}
}
for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
if (!isSafeSROAElementUse(*I))
return false;
return true;
}
static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
UI != E; ++UI) {
if (!IsUserOfGlobalSafeForSRA(*UI, GV))
return false;
}
return true;
}
static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
if (!GlobalUsersSafeToSRA(GV))
return 0;
assert(GV->hasLocalLinkage() && !GV->isConstant());
Constant *Init = GV->getInitializer();
const Type *Ty = Init->getType();
std::vector<GlobalVariable*> NewGlobals;
Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
unsigned StartAlignment = GV->getAlignment();
if (StartAlignment == 0)
StartAlignment = TD.getABITypeAlignment(GV->getType());
if (const StructType *STy = dyn_cast<StructType>(Ty)) {
NewGlobals.reserve(STy->getNumElements());
const StructLayout &Layout = *TD.getStructLayout(STy);
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Constant *In = getAggregateConstantElement(Init,
ConstantInt::get(Type::Int32Ty, i));
assert(In && "Couldn't get element of initializer?");
GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
GlobalVariable::InternalLinkage,
In, GV->getName()+"."+utostr(i),
(Module *)NULL,
GV->isThreadLocal(),
GV->getType()->getAddressSpace());
Globals.insert(GV, NGV);
NewGlobals.push_back(NGV);
uint64_t FieldOffset = Layout.getElementOffset(i);
unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
NGV->setAlignment(NewAlign);
}
} else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
unsigned NumElements = 0;
if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
NumElements = ATy->getNumElements();
else
NumElements = cast<VectorType>(STy)->getNumElements();
if (NumElements > 16 && GV->hasNUsesOrMore(16))
return 0; NewGlobals.reserve(NumElements);
uint64_t EltSize = TD.getTypePaddedSize(STy->getElementType());
unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
for (unsigned i = 0, e = NumElements; i != e; ++i) {
Constant *In = getAggregateConstantElement(Init,
ConstantInt::get(Type::Int32Ty, i));
assert(In && "Couldn't get element of initializer?");
GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
GlobalVariable::InternalLinkage,
In, GV->getName()+"."+utostr(i),
(Module *)NULL,
GV->isThreadLocal(),
GV->getType()->getAddressSpace());
Globals.insert(GV, NGV);
NewGlobals.push_back(NGV);
unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
if (NewAlign > EltAlign)
NGV->setAlignment(NewAlign);
}
}
if (NewGlobals.empty())
return 0;
DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
while (!GV->use_empty()) {
User *GEP = GV->use_back();
assert(((isa<ConstantExpr>(GEP) &&
cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
if (Val >= NewGlobals.size()) Val = 0;
Value *NewPtr = NewGlobals[Val];
if (GEP->getNumOperands() > 3) {
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
SmallVector<Constant*, 8> Idxs;
Idxs.push_back(NullInt);
for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
Idxs.push_back(CE->getOperand(i));
NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
&Idxs[0], Idxs.size());
} else {
GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
SmallVector<Value*, 8> Idxs;
Idxs.push_back(NullInt);
for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
Idxs.push_back(GEPI->getOperand(i));
NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
GEPI->getName()+"."+utostr(Val), GEPI);
}
}
GEP->replaceAllUsesWith(NewPtr);
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
GEPI->eraseFromParent();
else
cast<ConstantExpr>(GEP)->destroyConstant();
}
Globals.erase(GV);
++NumSRA;
unsigned FirstGlobal = 0;
for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
if (NewGlobals[i]->use_empty()) {
Globals.erase(NewGlobals[i]);
if (FirstGlobal == i) ++FirstGlobal;
}
return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
}
static bool AllUsesOfValueWillTrapIfNull(Value *V,
SmallPtrSet<PHINode*, 8> &PHIs) {
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
if (isa<LoadInst>(*UI)) {
} else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
if (SI->getOperand(0) == V) {
return false; }
} else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
if (CI->getOperand(0) != V) {
return false; }
} else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
if (II->getOperand(0) != V) {
return false; }
} else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
} else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
} else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
if (PHIs.insert(PN))
return AllUsesOfValueWillTrapIfNull(PN, PHIs);
} else if (isa<ICmpInst>(*UI) &&
isa<ConstantPointerNull>(UI->getOperand(1))) {
} else {
return false;
}
return true;
}
static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
SmallPtrSet<PHINode*, 8> PHIs;
if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
return false;
} else if (isa<StoreInst>(*UI)) {
} else {
return false;
}
return true;
}
static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
bool Changed = false;
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
Instruction *I = cast<Instruction>(*UI++);
if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
LI->setOperand(0, NewV);
Changed = true;
} else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
if (SI->getOperand(1) == V) {
SI->setOperand(1, NewV);
Changed = true;
}
} else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
if (I->getOperand(0) == V) {
I->setOperand(0, NewV);
Changed = true;
bool PassedAsArg = false;
for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
if (I->getOperand(i) == V) {
PassedAsArg = true;
I->setOperand(i, NewV);
}
if (PassedAsArg) {
UI = V->use_begin();
}
}
} else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Changed |= OptimizeAwayTrappingUsesOfValue(CI,
ConstantExpr::getCast(CI->getOpcode(),
NewV, CI->getType()));
if (CI->use_empty()) {
Changed = true;
CI->eraseFromParent();
}
} else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
SmallVector<Constant*, 8> Idxs;
Idxs.reserve(GEPI->getNumOperands()-1);
for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
i != e; ++i)
if (Constant *C = dyn_cast<Constant>(*i))
Idxs.push_back(C);
else
break;
if (Idxs.size() == GEPI->getNumOperands()-1)
Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
Idxs.size()));
if (GEPI->use_empty()) {
Changed = true;
GEPI->eraseFromParent();
}
}
}
return Changed;
}
static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
bool Changed = false;
bool AllNonStoreUsesGone = true;
for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
User *GlobalUser = *GUI++;
if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
if (LI->use_empty()) {
LI->eraseFromParent();
Changed = true;
} else {
AllNonStoreUsesGone = false;
}
} else if (isa<StoreInst>(GlobalUser)) {
assert(GlobalUser->getOperand(1) == GV &&
"Must be storing *to* the global");
} else {
AllNonStoreUsesGone = false;
assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
}
}
if (Changed) {
DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
++NumGlobUses;
}
if (AllNonStoreUsesGone) {
DOUT << " *** GLOBAL NOW DEAD!\n";
CleanupConstantGlobalUsers(GV, 0);
if (GV->use_empty()) {
GV->eraseFromParent();
++NumDeleted;
}
Changed = true;
}
return Changed;
}
static void ConstantPropUsersOf(Value *V) {
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
if (Instruction *I = dyn_cast<Instruction>(*UI++))
if (Constant *NewC = ConstantFoldInstruction(I)) {
I->replaceAllUsesWith(NewC);
while (UI != E && *UI == I)
++UI;
I->eraseFromParent();
}
}
static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
MallocInst *MI) {
DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
if (NElements->getZExtValue() != 1) {
Type *NewTy = ArrayType::get(MI->getAllocatedType(),
NElements->getZExtValue());
MallocInst *NewMI =
new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
MI->getAlignment(), MI->getName(), MI);
Value* Indices[2];
Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
NewMI->getName()+".el0", MI);
MI->replaceAllUsesWith(NewGEP);
MI->eraseFromParent();
MI = NewMI;
}
Constant *Init = UndefValue::get(MI->getAllocatedType());
GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
GlobalValue::InternalLinkage, Init,
GV->getName()+".body",
(Module *)NULL,
GV->isThreadLocal());
GV->getParent()->getGlobalList().insert(GV, NewGV);
MI->replaceAllUsesWith(NewGV);
Constant *RepValue = NewGV;
if (NewGV->getType() != GV->getType()->getElementType())
RepValue = ConstantExpr::getBitCast(RepValue,
GV->getType()->getElementType());
GlobalVariable *InitBool =
new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
ConstantInt::getFalse(), GV->getName()+".init",
(Module *)NULL, GV->isThreadLocal());
bool InitBoolUsed = false;
std::vector<StoreInst*> Stores;
while (!GV->use_empty())
if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
while (!LI->use_empty()) {
Use &LoadUse = LI->use_begin().getUse();
if (!isa<ICmpInst>(LoadUse.getUser()))
LoadUse = RepValue;
else {
ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
InitBoolUsed = true;
switch (CI->getPredicate()) {
default: assert(0 && "Unknown ICmp Predicate!");
case ICmpInst::ICMP_ULT:
case ICmpInst::ICMP_SLT:
LV = ConstantInt::getFalse(); break;
case ICmpInst::ICMP_ULE:
case ICmpInst::ICMP_SLE:
case ICmpInst::ICMP_EQ:
LV = BinaryOperator::CreateNot(LV, "notinit", CI);
break;
case ICmpInst::ICMP_NE:
case ICmpInst::ICMP_UGE:
case ICmpInst::ICMP_SGE:
case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_SGT:
break; }
CI->replaceAllUsesWith(LV);
CI->eraseFromParent();
}
}
LI->eraseFromParent();
} else {
StoreInst *SI = cast<StoreInst>(GV->use_back());
new StoreInst(ConstantInt::getTrue(), InitBool, SI);
SI->eraseFromParent();
}
if (!InitBoolUsed) {
while (!InitBool->use_empty()) cast<Instruction>(InitBool->use_back())->eraseFromParent();
delete InitBool;
} else
GV->getParent()->getGlobalList().insert(GV, InitBool);
GV->eraseFromParent();
MI->eraseFromParent();
ConstantPropUsersOf(NewGV);
if (RepValue != NewGV)
ConstantPropUsersOf(RepValue);
return NewGV;
}
static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
GlobalVariable *GV,
SmallPtrSet<PHINode*, 8> &PHIs) {
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Instruction *Inst = dyn_cast<Instruction>(*UI);
if (Inst == 0) return false;
if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
continue; }
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
return false; continue; }
if (isa<GetElementPtrInst>(Inst)) {
if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
return false;
continue;
}
if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
if (PHIs.insert(PN))
if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
return false;
continue;
}
if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
return false;
continue;
}
return false;
}
return true;
}
static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
GlobalVariable *GV) {
while (!Alloc->use_empty()) {
Instruction *U = cast<Instruction>(*Alloc->use_begin());
Instruction *InsertPt = U;
if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
if (SI->getOperand(1) == GV) {
SI->eraseFromParent();
continue;
}
} else if (PHINode *PN = dyn_cast<PHINode>(U)) {
InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
} else if (isa<BitCastInst>(U)) {
ReplaceUsesOfMallocWithGlobal(U, GV);
U->eraseFromParent();
continue;
} else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
if (SI->getOperand(1) == GV) {
ReplaceUsesOfMallocWithGlobal(GEPI, GV);
GEPI->eraseFromParent();
continue;
}
}
Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
U->replaceUsesOfWith(Alloc, NL);
}
}
static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
SmallPtrSet<PHINode*, 32> &LoadUsingPHIs) {
for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
Instruction *User = cast<Instruction>(*UI);
if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
return false;
continue;
}
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
if (GEPI->getNumOperands() < 3)
return false;
continue;
}
if (PHINode *PN = dyn_cast<PHINode>(User)) {
if (LoadUsingPHIs.insert(PN))
continue;
if (!LoadUsesSimpleEnoughForHeapSRA(PN, LoadUsingPHIs))
return false;
continue;
}
return false;
}
return true;
}
static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
MallocInst *MI) {
SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
++UI)
if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs))
return false;
for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
E = LoadUsingPHIs.end(); I != E; ++I) {
PHINode *PN = *I;
for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
Value *InVal = PN->getIncomingValue(op);
if (InVal == MI) continue;
if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
if (LoadUsingPHIs.count(InPN))
continue;
return false;
}
if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
if (LI->getOperand(0) == GV)
continue;
return false;
}
}
return true;
}
static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
if (FieldNo >= FieldVals.size())
FieldVals.resize(FieldNo+1);
if (Value *FieldVal = FieldVals[FieldNo])
return FieldVal;
Value *Result;
if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
InsertedScalarizedValues,
PHIsToRewrite),
LI->getName()+".f" + utostr(FieldNo), LI);
} else if (PHINode *PN = dyn_cast<PHINode>(V)) {
const StructType *ST =
cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
Result =PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
PN->getName()+".f"+utostr(FieldNo), PN);
PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
} else {
assert(0 && "Unknown usable value");
Result = 0;
}
return FieldVals[FieldNo] = Result;
}
static void RewriteHeapSROALoadUser(Instruction *LoadUser,
DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
InsertedScalarizedValues, PHIsToRewrite);
Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
Constant::getNullValue(NPtr->getType()),
SCI->getName(), SCI);
SCI->replaceAllUsesWith(New);
SCI->eraseFromParent();
return;
}
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
&& "Unexpected GEPI!");
unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
InsertedScalarizedValues, PHIsToRewrite);
SmallVector<Value*, 8> GEPIdx;
GEPIdx.push_back(GEPI->getOperand(1));
GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
Value *NGEPI = GetElementPtrInst::Create(NewPtr,
GEPIdx.begin(), GEPIdx.end(),
GEPI->getName(), GEPI);
GEPI->replaceAllUsesWith(NGEPI);
GEPI->eraseFromParent();
return;
}
PHINode *PN = cast<PHINode>(LoadUser);
bool Inserted;
DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
tie(InsertPos, Inserted) =
InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
if (!Inserted) return;
for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
Instruction *User = cast<Instruction>(*UI++);
RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
}
}
static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
UI != E; ) {
Instruction *User = cast<Instruction>(*UI++);
RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
}
if (Load->use_empty()) {
Load->eraseFromParent();
InsertedScalarizedValues.erase(Load);
}
}
static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
const StructType *STy = cast<StructType>(MI->getAllocatedType());
ReplaceUsesOfMallocWithGlobal(MI, GV);
std::vector<Value*> FieldGlobals;
std::vector<MallocInst*> FieldMallocs;
for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
const Type *FieldTy = STy->getElementType(FieldNo);
const Type *PFieldTy = PointerType::getUnqual(FieldTy);
GlobalVariable *NGV =
new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
Constant::getNullValue(PFieldTy),
GV->getName() + ".f" + utostr(FieldNo), GV,
GV->isThreadLocal());
FieldGlobals.push_back(NGV);
MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
MI->getName() + ".f" + utostr(FieldNo),MI);
FieldMallocs.push_back(NMI);
new StoreInst(NMI, NGV, MI);
}
Value *RunningOr = 0;
for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
Constant::getNullValue(FieldMallocs[i]->getType()),
"isnull", MI);
if (!RunningOr)
RunningOr = Cond; else
RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
}
BasicBlock *OrigBB = MI->getParent();
BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
OrigBB->getParent());
OrigBB->getTerminator()->eraseFromParent();
BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
Constant::getNullValue(GVVal->getType()),
"tmp", NullPtrBlock);
BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
new FreeInst(GVVal, FreeBlock);
new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
FreeBlock);
BranchInst::Create(NextBlock, FreeBlock);
NullPtrBlock = NextBlock;
}
BranchInst::Create(ContBB, NullPtrBlock);
MI->eraseFromParent();
DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
InsertedScalarizedValues[GV] = FieldGlobals;
std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
Instruction *User = cast<Instruction>(*UI++);
if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
continue;
}
StoreInst *SI = cast<StoreInst>(User);
assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
"Unexpected heap-sra user!");
for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
Constant *Null = Constant::getNullValue(PT->getElementType());
new StoreInst(Null, FieldGlobals[i], SI);
}
SI->eraseFromParent();
}
while (!PHIsToRewrite.empty()) {
PHINode *PN = PHIsToRewrite.back().first;
unsigned FieldNo = PHIsToRewrite.back().second;
PHIsToRewrite.pop_back();
PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *InVal = PN->getIncomingValue(i);
InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
PHIsToRewrite);
FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
}
}
for (DenseMap<Value*, std::vector<Value*> >::iterator
I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
I != E; ++I) {
if (PHINode *PN = dyn_cast<PHINode>(I->first))
PN->dropAllReferences();
else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
LI->dropAllReferences();
}
for (DenseMap<Value*, std::vector<Value*> >::iterator
I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
I != E; ++I) {
if (PHINode *PN = dyn_cast<PHINode>(I->first))
PN->eraseFromParent();
else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
LI->eraseFromParent();
}
GV->eraseFromParent();
++NumHeapSRA;
return cast<GlobalVariable>(FieldGlobals[0]);
}
static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
MallocInst *MI,
Module::global_iterator &GVI,
TargetData &TD) {
if (!MI->getAllocatedType()->isSized())
return false;
if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
return false;
{
SmallPtrSet<PHINode*, 8> PHIs;
if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
return false;
}
if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
if (NElements->getZExtValue()*
TD.getTypePaddedSize(MI->getAllocatedType()) < 2048) {
GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
return true;
}
}
const Type *AllocTy = MI->getAllocatedType();
if (!MI->isArrayAllocation())
if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
AllocTy = AT->getElementType();
if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
MallocInst *NewMI =
new MallocInst(AllocSTy,
ConstantInt::get(Type::Int32Ty, AT->getNumElements()),
"", MI);
NewMI->takeName(MI);
Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
MI->replaceAllUsesWith(Cast);
MI->eraseFromParent();
MI = NewMI;
}
GVI = PerformHeapAllocSRoA(GV, MI);
return true;
}
}
return false;
}
static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
Module::global_iterator &GVI,
TargetData &TD) {
StoredOnceVal = StoredOnceVal->stripPointerCasts();
if (isa<PointerType>(GV->getInitializer()->getType()) &&
GV->getInitializer()->isNullValue()) {
if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
if (GV->getInitializer()->getType() != SOVC->getType())
SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
return true;
} else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD))
return true;
}
}
return false;
}
static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
const Type *GVElType = GV->getType()->getElementType();
if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
isa<PointerType>(GVElType) || isa<VectorType>(GVElType))
return false;
for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
return false;
DOUT << " *** SHRINKING TO BOOL: " << *GV;
GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
GlobalValue::InternalLinkage, ConstantInt::getFalse(),
GV->getName()+".b",
(Module *)NULL,
GV->isThreadLocal());
GV->getParent()->getGlobalList().insert(GV, NewGV);
Constant *InitVal = GV->getInitializer();
assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
bool IsOneZero = false;
if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
IsOneZero = InitVal->isNullValue() && CI->isOne();
while (!GV->use_empty()) {
Instruction *UI = cast<Instruction>(GV->use_back());
if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
bool StoringOther = SI->getOperand(0) == OtherVal;
Value *StoreVal;
if (StoringOther || SI->getOperand(0) == InitVal)
StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
else {
Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
assert(LI->getOperand(0) == GV && "Not a copy!");
StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
} else {
assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
"This is not a form that we understand!");
StoreVal = StoredVal->getOperand(0);
assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
}
}
new StoreInst(StoreVal, NewGV, SI);
} else {
LoadInst *LI = cast<LoadInst>(UI);
LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
Value *NSI;
if (IsOneZero)
NSI = new ZExtInst(NLI, LI->getType(), "", LI);
else
NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
NSI->takeName(LI);
LI->replaceAllUsesWith(NSI);
}
UI->eraseFromParent();
}
GV->eraseFromParent();
return true;
}
bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
Module::global_iterator &GVI) {
SmallPtrSet<PHINode*, 16> PHIUsers;
GlobalStatus GS;
GV->removeDeadConstantUsers();
if (GV->use_empty()) {
DOUT << "GLOBAL DEAD: " << *GV;
GV->eraseFromParent();
++NumDeleted;
return true;
}
if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
#if 0
cerr << "Global: " << *GV;
cerr << " isLoaded = " << GS.isLoaded << "\n";
cerr << " StoredType = ";
switch (GS.StoredType) {
case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
case GlobalStatus::isStored: cerr << "stored\n"; break;
}
if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
<< "\n";
cerr << " HasMultipleAccessingFunctions = "
<< GS.HasMultipleAccessingFunctions << "\n";
cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
cerr << "\n";
#endif
if (!GS.HasMultipleAccessingFunctions &&
GS.AccessingFunction && !GS.HasNonInstructionUser &&
GV->getType()->getElementType()->isSingleValueType() &&
GS.AccessingFunction->getName() == "main" &&
GS.AccessingFunction->hasExternalLinkage()) {
DOUT << "LOCALIZING GLOBAL: " << *GV;
Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
const Type* ElemTy = GV->getType()->getElementType();
AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
if (!isa<UndefValue>(GV->getInitializer()))
new StoreInst(GV->getInitializer(), Alloca, FirstI);
GV->replaceAllUsesWith(Alloca);
GV->eraseFromParent();
++NumLocalized;
return true;
}
if (!GS.isLoaded) {
DOUT << "GLOBAL NEVER LOADED: " << *GV;
bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
if (GV->use_empty()) {
GV->eraseFromParent();
++NumDeleted;
Changed = true;
}
return Changed;
} else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
DOUT << "MARKING CONSTANT: " << *GV;
GV->setConstant(true);
CleanupConstantGlobalUsers(GV, GV->getInitializer());
if (GV->use_empty()) {
DOUT << " *** Marking constant allowed us to simplify "
<< "all users and delete global!\n";
GV->eraseFromParent();
++NumDeleted;
}
++NumMarked;
return true;
} else if (!GV->getInitializer()->getType()->isSingleValueType()) {
if (GlobalVariable *FirstNewGV = SRAGlobal(GV,
getAnalysis<TargetData>())) {
GVI = FirstNewGV; return true;
}
} else if (GS.StoredType == GlobalStatus::isStoredOnce) {
if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
if (isa<UndefValue>(GV->getInitializer())) {
GV->setInitializer(SOVConstant);
CleanupConstantGlobalUsers(GV, GV->getInitializer());
if (GV->use_empty()) {
DOUT << " *** Substituting initializer allowed us to "
<< "simplify all users and delete global!\n";
GV->eraseFromParent();
++NumDeleted;
} else {
GVI = GV;
}
++NumSubstitute;
return true;
}
if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
getAnalysis<TargetData>()))
return true;
if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
++NumShrunkToBool;
return true;
}
}
}
return false;
}
static bool OnlyCalledDirectly(Function *F) {
for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
Instruction *User = dyn_cast<Instruction>(*UI);
if (!User) return false;
if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
for (User::op_iterator i = User->op_begin() + 1, e = User->op_end();
i != e; ++i)
if (*i == F) return false;
}
return true;
}
static void ChangeCalleesToFastCall(Function *F) {
for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
CallSite User(cast<Instruction>(*UI));
User.setCallingConv(CallingConv::Fast);
}
}
static AttrListPtr StripNest(const AttrListPtr &Attrs) {
for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
continue;
return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
}
return Attrs;
}
static void RemoveNestAttribute(Function *F) {
F->setAttributes(StripNest(F->getAttributes()));
for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
CallSite User(cast<Instruction>(*UI));
User.setAttributes(StripNest(User.getAttributes()));
}
}
bool GlobalOpt::OptimizeFunctions(Module &M) {
bool Changed = false;
for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
Function *F = FI++;
if (!F->hasName() && !F->isDeclaration())
F->setLinkage(GlobalValue::InternalLinkage);
F->removeDeadConstantUsers();
if (F->use_empty() && (F->hasLocalLinkage() ||
F->hasLinkOnceLinkage())) {
M.getFunctionList().erase(F);
Changed = true;
++NumFnDeleted;
} else if (F->hasLocalLinkage()) {
if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
OnlyCalledDirectly(F)) {
F->setCallingConv(CallingConv::Fast);
ChangeCalleesToFastCall(F);
++NumFastCallFns;
Changed = true;
}
if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
OnlyCalledDirectly(F)) {
RemoveNestAttribute(F);
++NumNestRemoved;
Changed = true;
}
}
}
return Changed;
}
bool GlobalOpt::OptimizeGlobalVars(Module &M) {
bool Changed = false;
for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
GVI != E; ) {
GlobalVariable *GV = GVI++;
if (!GV->hasName() && !GV->isDeclaration())
GV->setLinkage(GlobalValue::InternalLinkage);
if (!GV->isConstant() && GV->hasLocalLinkage() &&
GV->hasInitializer())
Changed |= ProcessInternalGlobal(GV, GVI);
}
return Changed;
}
GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I)
if (I->getName() == "llvm.global_ctors") {
const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
if (!ATy) return 0;
const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
if (!STy || STy->getNumElements() != 2 ||
STy->getElementType(0) != Type::Int32Ty) return 0;
const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
if (!PFTy) return 0;
const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
FTy->getNumParams() != 0)
return 0;
if (!I->hasInitializer()) return 0;
ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
if (!CA) return 0;
for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
if (isa<ConstantPointerNull>(CS->getOperand(1)))
continue;
if (!isa<Function>(CS->getOperand(1)))
return 0;
ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
if (!CI || CI->getZExtValue() != 65535)
return 0;
} else {
return 0;
}
return I;
}
return 0;
}
static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
std::vector<Function*> Result;
Result.reserve(CA->getNumOperands());
for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
ConstantStruct *CS = cast<ConstantStruct>(*i);
Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
}
return Result;
}
static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
const std::vector<Function*> &Ctors) {
std::vector<Constant*> CSVals;
CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
CSVals.push_back(0);
std::vector<Constant*> CAList;
for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
if (Ctors[i]) {
CSVals[1] = Ctors[i];
} else {
const Type *FTy = FunctionType::get(Type::VoidTy,
std::vector<const Type*>(), false);
const PointerType *PFTy = PointerType::getUnqual(FTy);
CSVals[1] = Constant::getNullValue(PFTy);
CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
}
CAList.push_back(ConstantStruct::get(CSVals));
}
const Type *StructTy =
cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
CAList);
if (CA->getType() == GCL->getInitializer()->getType()) {
GCL->setInitializer(CA);
return GCL;
}
GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
GCL->getLinkage(), CA, "",
(Module *)NULL,
GCL->isThreadLocal());
GCL->getParent()->getGlobalList().insert(GCL, NGV);
NGV->takeName(GCL);
if (!GCL->use_empty()) {
Constant *V = NGV;
if (V->getType() != GCL->getType())
V = ConstantExpr::getBitCast(V, GCL->getType());
GCL->replaceAllUsesWith(V);
}
GCL->eraseFromParent();
if (Ctors.size())
return NGV;
else
return 0;
}
static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
Value *V) {
if (Constant *CV = dyn_cast<Constant>(V)) return CV;
Constant *R = ComputedValues[V];
assert(R && "Reference to an uncomputed value!");
return R;
}
static bool isSimpleEnoughPointerToCommit(Constant *C) {
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
return false; return !GV->isDeclaration(); }
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
if (CE->getOpcode() == Instruction::GetElementPtr &&
isa<GlobalVariable>(CE->getOperand(0))) {
GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
return false; return GV->hasInitializer() &&
ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
}
return false;
}
static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
ConstantExpr *Addr, unsigned OpNo) {
if (OpNo == Addr->getNumOperands()) {
assert(Val->getType() == Init->getType() && "Type mismatch!");
return Val;
}
if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
std::vector<Constant*> Elts;
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
Elts.push_back(cast<Constant>(*i));
} else if (isa<ConstantAggregateZero>(Init)) {
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
} else if (isa<UndefValue>(Init)) {
for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
Elts.push_back(UndefValue::get(STy->getElementType(i)));
} else {
assert(0 && "This code is out of sync with "
" ConstantFoldLoadThroughGEPConstantExpr");
}
ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
unsigned Idx = CU->getZExtValue();
assert(Idx < STy->getNumElements() && "Struct index out of range!");
Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
} else {
ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
const ArrayType *ATy = cast<ArrayType>(Init->getType());
std::vector<Constant*> Elts;
if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
Elts.push_back(cast<Constant>(*i));
} else if (isa<ConstantAggregateZero>(Init)) {
Constant *Elt = Constant::getNullValue(ATy->getElementType());
Elts.assign(ATy->getNumElements(), Elt);
} else if (isa<UndefValue>(Init)) {
Constant *Elt = UndefValue::get(ATy->getElementType());
Elts.assign(ATy->getNumElements(), Elt);
} else {
assert(0 && "This code is out of sync with "
" ConstantFoldLoadThroughGEPConstantExpr");
}
assert(CI->getZExtValue() < ATy->getNumElements());
Elts[CI->getZExtValue()] =
EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
return ConstantArray::get(ATy, Elts);
}
}
static void CommitValueTo(Constant *Val, Constant *Addr) {
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
assert(GV->hasInitializer());
GV->setInitializer(Val);
return;
}
ConstantExpr *CE = cast<ConstantExpr>(Addr);
GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
Constant *Init = GV->getInitializer();
Init = EvaluateStoreInto(Init, Val, CE, 2);
GV->setInitializer(Init);
}
static Constant *ComputeLoadResult(Constant *P,
const DenseMap<Constant*, Constant*> &Memory) {
DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
if (I != Memory.end()) return I->second;
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
if (GV->hasInitializer())
return GV->getInitializer();
return 0;
}
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
if (CE->getOpcode() == Instruction::GetElementPtr &&
isa<GlobalVariable>(CE->getOperand(0))) {
GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
if (GV->hasInitializer())
return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
}
return 0; }
static bool EvaluateFunction(Function *F, Constant *&RetVal,
const std::vector<Constant*> &ActualArgs,
std::vector<Function*> &CallStack,
DenseMap<Constant*, Constant*> &MutatedMemory,
std::vector<GlobalVariable*> &AllocaTmps) {
if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
return false;
CallStack.push_back(F);
DenseMap<Value*, Constant*> Values;
unsigned ArgNo = 0;
for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
++AI, ++ArgNo)
Values[AI] = ActualArgs[ArgNo];
SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
BasicBlock::iterator CurInst = F->begin()->begin();
while (1) {
Constant *InstResult = 0;
if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
if (SI->isVolatile()) return false; Constant *Ptr = getVal(Values, SI->getOperand(1));
if (!isSimpleEnoughPointerToCommit(Ptr))
return false;
Constant *Val = getVal(Values, SI->getOperand(0));
MutatedMemory[Ptr] = Val;
} else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
InstResult = ConstantExpr::get(BO->getOpcode(),
getVal(Values, BO->getOperand(0)),
getVal(Values, BO->getOperand(1)));
} else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
InstResult = ConstantExpr::getCompare(CI->getPredicate(),
getVal(Values, CI->getOperand(0)),
getVal(Values, CI->getOperand(1)));
} else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
InstResult = ConstantExpr::getCast(CI->getOpcode(),
getVal(Values, CI->getOperand(0)),
CI->getType());
} else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
getVal(Values, SI->getOperand(1)),
getVal(Values, SI->getOperand(2)));
} else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
Constant *P = getVal(Values, GEP->getOperand(0));
SmallVector<Constant*, 8> GEPOps;
for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
i != e; ++i)
GEPOps.push_back(getVal(Values, *i));
InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
} else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
if (LI->isVolatile()) return false; InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
MutatedMemory);
if (InstResult == 0) return false; } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
if (AI->isArrayAllocation()) return false; const Type *Ty = AI->getType()->getElementType();
AllocaTmps.push_back(new GlobalVariable(Ty, false,
GlobalValue::InternalLinkage,
UndefValue::get(Ty),
AI->getName()));
InstResult = AllocaTmps.back();
} else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
if (isa<DbgInfoIntrinsic>(CI)) {
++CurInst;
continue;
}
if (isa<InlineAsm>(CI->getOperand(0))) return false;
Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
if (!Callee) return false;
std::vector<Constant*> Formals;
for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
i != e; ++i)
Formals.push_back(getVal(Values, *i));
if (Callee->isDeclaration()) {
if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
Formals.size())) {
InstResult = C;
} else {
return false;
}
} else {
if (Callee->getFunctionType()->isVarArg())
return false;
Constant *RetVal;
if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
MutatedMemory, AllocaTmps))
return false;
InstResult = RetVal;
}
} else if (isa<TerminatorInst>(CurInst)) {
BasicBlock *NewBB = 0;
if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
if (BI->isUnconditional()) {
NewBB = BI->getSuccessor(0);
} else {
ConstantInt *Cond =
dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
if (!Cond) return false;
NewBB = BI->getSuccessor(!Cond->getZExtValue());
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
ConstantInt *Val =
dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
if (!Val) return false; NewBB = SI->getSuccessor(SI->findCaseValue(Val));
} else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
if (RI->getNumOperands())
RetVal = getVal(Values, RI->getOperand(0));
CallStack.pop_back(); return true; } else {
return false; }
if (!ExecutedBlocks.insert(NewBB))
return false;
BasicBlock *OldBB = CurInst->getParent();
CurInst = NewBB->begin();
PHINode *PN;
for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
continue;
} else {
return false;
}
if (!CurInst->use_empty())
Values[CurInst] = InstResult;
++CurInst;
}
}
static bool EvaluateStaticConstructor(Function *F) {
DenseMap<Constant*, Constant*> MutatedMemory;
std::vector<GlobalVariable*> AllocaTmps;
std::vector<Function*> CallStack;
Constant *RetValDummy;
bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
CallStack, MutatedMemory, AllocaTmps);
if (EvalSuccess) {
DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
<< F->getName() << "' to " << MutatedMemory.size()
<< " stores.\n";
for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
E = MutatedMemory.end(); I != E; ++I)
CommitValueTo(I->second, I->first);
}
while (!AllocaTmps.empty()) {
GlobalVariable *Tmp = AllocaTmps.back();
AllocaTmps.pop_back();
if (!Tmp->use_empty())
Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
delete Tmp;
}
return EvalSuccess;
}
bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
bool MadeChange = false;
if (Ctors.empty()) return false;
for (unsigned i = 0; i != Ctors.size(); ++i) {
Function *F = Ctors[i];
if (F == 0) {
if (i != Ctors.size()-1) {
Ctors.resize(i+1);
MadeChange = true;
}
break;
}
if (F->empty()) continue;
if (EvaluateStaticConstructor(F)) {
Ctors.erase(Ctors.begin()+i);
MadeChange = true;
--i;
++NumCtorsEvaluated;
continue;
}
}
if (!MadeChange) return false;
GCL = InstallGlobalCtors(GCL, Ctors);
return true;
}
bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
bool Changed = false;
for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
I != E;) {
Module::alias_iterator J = I++;
if (!J->hasName() && !J->isDeclaration())
J->setLinkage(GlobalValue::InternalLinkage);
if (J->mayBeOverridden())
continue;
Constant *Aliasee = J->getAliasee();
GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
Target->removeDeadConstantUsers();
bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
if (!J->use_empty()) {
J->replaceAllUsesWith(Aliasee);
++NumAliasesResolved;
Changed = true;
}
if (!Target->hasLocalLinkage())
continue;
if (J->hasLocalLinkage())
continue;
if (!hasOneUse)
continue;
Target->takeName(J);
Target->setLinkage(J->getLinkage());
Target->GlobalValue::copyAttributesFrom(J);
M.getAliasList().erase(J);
++NumAliasesRemoved;
Changed = true;
}
return Changed;
}
bool GlobalOpt::runOnModule(Module &M) {
bool Changed = false;
GlobalVariable *GlobalCtors = FindGlobalCtors(M);
bool LocalChange = true;
while (LocalChange) {
LocalChange = false;
LocalChange |= OptimizeFunctions(M);
if (GlobalCtors)
LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
LocalChange |= OptimizeGlobalVars(M);
LocalChange |= OptimizeGlobalAliases(M);
Changed |= LocalChange;
}
return Changed;
}