#define DEBUG_TYPE "machine-licm"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/PseudoSourceValue.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
STATISTIC(NumPostRAHoisted,
"Number of machine instructions hoisted out of loops post regalloc");
namespace {
class MachineLICM : public MachineFunctionPass {
bool PreRegAlloc;
const TargetMachine *TM;
const TargetInstrInfo *TII;
const TargetRegisterInfo *TRI;
const MachineFrameInfo *MFI;
MachineRegisterInfo *RegInfo;
AliasAnalysis *AA; MachineLoopInfo *MLI; MachineDominatorTree *DT;
bool Changed; bool FirstInLoop; MachineLoop *CurLoop; MachineBasicBlock *CurPreheader;
BitVector AllocatableSet;
DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
public:
static char ID; MachineLICM() :
MachineFunctionPass(&ID), PreRegAlloc(true) {}
explicit MachineLICM(bool PreRA) :
MachineFunctionPass(&ID), PreRegAlloc(PreRA) {}
virtual bool runOnMachineFunction(MachineFunction &MF);
const char *getPassName() const { return "Machine Instruction LICM"; }
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequired<MachineLoopInfo>();
AU.addRequired<MachineDominatorTree>();
AU.addRequired<AliasAnalysis>();
AU.addPreserved<MachineLoopInfo>();
AU.addPreserved<MachineDominatorTree>();
MachineFunctionPass::getAnalysisUsage(AU);
}
virtual void releaseMemory() {
CSEMap.clear();
}
private:
struct CandidateInfo {
MachineInstr *MI;
unsigned Def;
int FI;
CandidateInfo(MachineInstr *mi, unsigned def, int fi)
: MI(mi), Def(def), FI(fi) {}
};
void HoistRegionPostRA();
void HoistPostRA(MachineInstr *MI, unsigned Def);
void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
SmallSet<int, 32> &StoredFIs,
SmallVector<CandidateInfo, 32> &Candidates);
void AddToLiveIns(unsigned Reg);
bool IsLICMCandidate(MachineInstr &I);
bool IsLoopInvariantInst(MachineInstr &I);
bool IsProfitableToHoist(MachineInstr &MI);
void HoistRegion(MachineDomTreeNode *N);
bool isLoadFromConstantMemory(MachineInstr *MI);
MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
const MachineInstr *LookForDuplicate(const MachineInstr *MI,
std::vector<const MachineInstr*> &PrevMIs);
bool EliminateCSE(MachineInstr *MI,
DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
void Hoist(MachineInstr *MI);
void InitCSEMap(MachineBasicBlock *BB);
};
}
char MachineLICM::ID = 0;
static RegisterPass<MachineLICM>
X("machinelicm", "Machine Loop Invariant Code Motion");
FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
return new MachineLICM(PreRegAlloc);
}
static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
if (L->getLoopPreheader())
return false;
return true;
}
bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
if (PreRegAlloc)
DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
else
DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
Changed = FirstInLoop = false;
TM = &MF.getTarget();
TII = TM->getInstrInfo();
TRI = TM->getRegisterInfo();
MFI = MF.getFrameInfo();
RegInfo = &MF.getRegInfo();
AllocatableSet = TRI->getAllocatableSet(MF);
MLI = &getAnalysis<MachineLoopInfo>();
DT = &getAnalysis<MachineDominatorTree>();
AA = &getAnalysis<AliasAnalysis>();
for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I){
CurLoop = *I;
if (PreRegAlloc && !LoopIsOuterMostWithPreheader(CurLoop))
continue;
CurPreheader = CurLoop->getLoopPreheader();
if (!CurPreheader)
continue;
if (!PreRegAlloc)
HoistRegionPostRA();
else {
MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
FirstInLoop = true;
HoistRegion(N);
CSEMap.clear();
}
}
return Changed;
}
static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
oe = MI->memoperands_end(); o != oe; ++o) {
if (!(*o)->isStore() || !(*o)->getValue())
continue;
if (const FixedStackPseudoSourceValue *Value =
dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
if (Value->getFrameIndex() == FI)
return true;
}
}
return false;
}
void MachineLICM::ProcessMI(MachineInstr *MI,
unsigned *PhysRegDefs,
SmallSet<int, 32> &StoredFIs,
SmallVector<CandidateInfo, 32> &Candidates) {
bool RuledOut = false;
bool HasNonInvariantUse = false;
unsigned Def = 0;
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (MO.isFI()) {
int FI = MO.getIndex();
if (!StoredFIs.count(FI) &&
MFI->isSpillSlotObjectIndex(FI) &&
InstructionStoresToFI(MI, FI))
StoredFIs.insert(FI);
HasNonInvariantUse = true;
continue;
}
if (!MO.isReg())
continue;
unsigned Reg = MO.getReg();
if (!Reg)
continue;
assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
"Not expecting virtual register!");
if (!MO.isDef()) {
if (Reg && PhysRegDefs[Reg])
HasNonInvariantUse = true;
continue;
}
if (MO.isImplicit()) {
++PhysRegDefs[Reg];
for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
++PhysRegDefs[*AS];
if (!MO.isDead())
RuledOut = true;
continue;
}
if (Def)
RuledOut = true;
else
Def = Reg;
if (++PhysRegDefs[Reg] > 1)
RuledOut = true;
for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
if (++PhysRegDefs[*AS] > 1)
RuledOut = true;
}
if (Def && !RuledOut) {
int FI = INT_MIN;
if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
(TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
Candidates.push_back(CandidateInfo(MI, Def, FI));
}
}
void MachineLICM::HoistRegionPostRA() {
unsigned NumRegs = TRI->getNumRegs();
unsigned *PhysRegDefs = new unsigned[NumRegs];
std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
SmallVector<CandidateInfo, 32> Candidates;
SmallSet<int, 32> StoredFIs;
const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
MachineBasicBlock *BB = Blocks[i];
for (MachineBasicBlock::const_livein_iterator I = BB->livein_begin(),
E = BB->livein_end(); I != E; ++I) {
unsigned Reg = *I;
++PhysRegDefs[Reg];
for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
++PhysRegDefs[*AS];
}
for (MachineBasicBlock::iterator
MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
MachineInstr *MI = &*MII;
ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
}
}
for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
if (Candidates[i].FI != INT_MIN &&
StoredFIs.count(Candidates[i].FI))
continue;
if (PhysRegDefs[Candidates[i].Def] == 1) {
bool Safe = true;
MachineInstr *MI = Candidates[i].MI;
for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
const MachineOperand &MO = MI->getOperand(j);
if (!MO.isReg() || MO.isDef() || !MO.getReg())
continue;
if (PhysRegDefs[MO.getReg()]) {
Safe = false;
break;
}
}
if (Safe)
HoistPostRA(MI, Candidates[i].Def);
}
}
delete[] PhysRegDefs;
}
void MachineLICM::AddToLiveIns(unsigned Reg) {
const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
MachineBasicBlock *BB = Blocks[i];
if (!BB->isLiveIn(Reg))
BB->addLiveIn(Reg);
for (MachineBasicBlock::iterator
MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
MachineInstr *MI = &*MII;
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
MachineOperand &MO = MI->getOperand(i);
if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
MO.setIsKill(false);
}
}
}
}
void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
DEBUG({
dbgs() << "Hoisting " << *MI;
if (CurPreheader->getBasicBlock())
dbgs() << " to MachineBasicBlock "
<< CurPreheader->getName();
if (MI->getParent()->getBasicBlock())
dbgs() << " from MachineBasicBlock "
<< MI->getParent()->getName();
dbgs() << "\n";
});
MachineBasicBlock *MBB = MI->getParent();
CurPreheader->splice(CurPreheader->getFirstTerminator(), MBB, MI);
AddToLiveIns(Def);
++NumPostRAHoisted;
Changed = true;
}
void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
assert(N != 0 && "Null dominator tree node?");
MachineBasicBlock *BB = N->getBlock();
if (!CurLoop->contains(BB)) return;
for (MachineBasicBlock::iterator
MII = BB->begin(), E = BB->end(); MII != E; ) {
MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Hoist(&*MII);
MII = NextMII;
}
const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
for (unsigned I = 0, E = Children.size(); I != E; ++I)
HoistRegion(Children[I]);
}
bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
if (I.isImplicitDef())
return false;
const TargetInstrDesc &TID = I.getDesc();
if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
TID.hasUnmodeledSideEffects())
return false;
if (TID.mayLoad()) {
if (!I.isInvariantLoad(AA))
return false;
}
return true;
}
bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
if (!IsLICMCandidate(I))
return false;
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = I.getOperand(i);
if (!MO.isReg())
continue;
unsigned Reg = MO.getReg();
if (Reg == 0) continue;
if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
if (MO.isUse()) {
if (!RegInfo->def_empty(Reg))
return false;
if (AllocatableSet.test(Reg))
return false;
for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
unsigned AliasReg = *Alias;
if (!RegInfo->def_empty(AliasReg))
return false;
if (AllocatableSet.test(AliasReg))
return false;
}
continue;
} else if (!MO.isDead()) {
return false;
} else if (CurLoop->getHeader()->isLiveIn(Reg)) {
return false;
}
}
if (!MO.isUse())
continue;
assert(RegInfo->getVRegDef(Reg) &&
"Machine instr not mapped for this vreg?!");
if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
return false;
}
return true;
}
static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
UE = RegInfo->use_end(); UI != UE; ++UI) {
MachineInstr *UseMI = &*UI;
if (UseMI->isPHI())
return true;
}
return false;
}
bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
if (!MI->getDesc().mayLoad()) return false;
if (!MI->hasOneMemOperand()) return false;
MachineMemOperand *MMO = *MI->memoperands_begin();
if (MMO->isVolatile()) return false;
if (!MMO->getValue()) return false;
const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
if (PSV) {
MachineFunction &MF = *MI->getParent()->getParent();
return PSV->isConstant(MF.getFrameInfo());
} else {
return AA->pointsToConstantMemory(MMO->getValue());
}
}
bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
if (!TII->isTriviallyReMaterializable(&MI, AA)) {
if (!isLoadFromConstantMemory(&MI))
return false;
}
for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI.getOperand(i);
if (!MO.isReg() || !MO.isDef())
continue;
if (HasPHIUses(MO.getReg(), RegInfo))
return false;
}
return true;
}
MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
if (!isLoadFromConstantMemory(MI))
return 0;
unsigned LoadRegIndex;
unsigned NewOpc =
TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
true,
false,
&LoadRegIndex);
if (NewOpc == 0) return 0;
const TargetInstrDesc &TID = TII->get(NewOpc);
if (TID.getNumDefs() != 1) return 0;
const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
unsigned Reg = RegInfo->createVirtualRegister(RC);
MachineFunction &MF = *MI->getParent()->getParent();
SmallVector<MachineInstr *, 2> NewMIs;
bool Success =
TII->unfoldMemoryOperand(MF, MI, Reg,
true, false,
NewMIs);
(void)Success;
assert(Success &&
"unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
"succeeded!");
assert(NewMIs.size() == 2 &&
"Unfolded a load into multiple instructions!");
MachineBasicBlock *MBB = MI->getParent();
MBB->insert(MI, NewMIs[0]);
MBB->insert(MI, NewMIs[1]);
if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
NewMIs[0]->eraseFromParent();
NewMIs[1]->eraseFromParent();
return 0;
}
MI->eraseFromParent();
return NewMIs[0];
}
void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
const MachineInstr *MI = &*I;
if (TII->isTriviallyReMaterializable(MI, AA)) {
unsigned Opcode = MI->getOpcode();
DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
CI = CSEMap.find(Opcode);
if (CI != CSEMap.end())
CI->second.push_back(MI);
else {
std::vector<const MachineInstr*> CSEMIs;
CSEMIs.push_back(MI);
CSEMap.insert(std::make_pair(Opcode, CSEMIs));
}
}
}
}
const MachineInstr*
MachineLICM::LookForDuplicate(const MachineInstr *MI,
std::vector<const MachineInstr*> &PrevMIs) {
for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
const MachineInstr *PrevMI = PrevMIs[i];
if (TII->produceSameValue(MI, PrevMI))
return PrevMI;
}
return 0;
}
bool MachineLICM::EliminateCSE(MachineInstr *MI,
DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
if (CI == CSEMap.end())
return false;
if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
assert((!MO.isReg() || MO.getReg() == 0 ||
!TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
MO.getReg() == Dup->getOperand(i).getReg()) &&
"Instructions with different phys regs are not identical!");
if (MO.isReg() && MO.isDef() &&
!TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
}
MI->eraseFromParent();
++NumCSEed;
return true;
}
return false;
}
void MachineLICM::Hoist(MachineInstr *MI) {
if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
MI = ExtractHoistableLoad(MI);
if (!MI) return;
}
DEBUG({
dbgs() << "Hoisting " << *MI;
if (CurPreheader->getBasicBlock())
dbgs() << " to MachineBasicBlock "
<< CurPreheader->getName();
if (MI->getParent()->getBasicBlock())
dbgs() << " from MachineBasicBlock "
<< MI->getParent()->getName();
dbgs() << "\n";
});
if (FirstInLoop) {
InitCSEMap(CurPreheader);
FirstInLoop = false;
}
unsigned Opcode = MI->getOpcode();
DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
CI = CSEMap.find(Opcode);
if (!EliminateCSE(MI, CI)) {
CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
if (CI != CSEMap.end())
CI->second.push_back(MI);
else {
std::vector<const MachineInstr*> CSEMIs;
CSEMIs.push_back(MI);
CSEMap.insert(std::make_pair(Opcode, CSEMIs));
}
}
++NumHoisted;
Changed = true;
}