78 #define DEBUG_TYPE "shrink-wrap"
82 STATISTIC(NumFunc,
"Number of functions");
83 STATISTIC(NumCandidates,
"Number of shrink-wrapping candidates");
85 "Number of shrink-wrapping candidates dropped because of frequency");
89 cl::desc(
"enable the shrink-wrapping pass"));
121 unsigned FrameSetupOpcode;
123 unsigned FrameDestroyOpcode;
128 mutable SetOfRegs CurrentCSRs;
137 const SetOfRegs &getCurrentCSRs(
RegScavenger *RS)
const {
138 if (CurrentCSRs.empty()) {
141 MachineFunc->getSubtarget().getFrameLowering();
147 CurrentCSRs.insert((
unsigned)
Reg);
161 RCI.runOnMachineFunction(MF);
162 MDT = &getAnalysis<MachineDominatorTree>();
163 MPDT = &getAnalysis<MachinePostDominatorTree>();
166 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
167 MLI = &getAnalysis<MachineLoopInfo>();
168 EntryFreq = MBFI->getEntryFreq();
181 bool ArePointsInteresting()
const {
return Save != Entry && Save && Restore; }
202 StringRef getPassName()
const override {
return "Shrink Wrapping analysis"; }
222 if (MI.getOpcode() == FrameSetupOpcode ||
223 MI.getOpcode() == FrameDestroyOpcode) {
224 DEBUG(
dbgs() <<
"Frame instruction: " << MI <<
'\n');
228 bool UseOrDefCSR =
false;
230 unsigned PhysReg = MO.getReg();
234 "Unallocated register?!");
235 UseOrDefCSR = RCI.getLastCalleeSavedAlias(PhysReg);
236 }
else if (MO.isRegMask()) {
238 for (
unsigned Reg : getCurrentCSRs(RS)) {
239 if (MO.clobbersPhysReg(
Reg)) {
245 if (UseOrDefCSR || MO.isFI()) {
246 DEBUG(
dbgs() <<
"Use or define CSR(" << UseOrDefCSR <<
") or FI("
247 << MO.isFI() <<
"): " << MI <<
'\n');
255 template <
typename ListOfBBs,
typename DominanceAnalysis>
257 DominanceAnalysis &Dom) {
260 IDom = Dom.findNearestCommonDominator(IDom, BB);
275 Save = MDT->findNearestCommonDominator(Save, &MBB);
278 DEBUG(
dbgs() <<
"Found a block that is not reachable from Entry\n");
284 else if (MPDT->getNode(&MBB))
289 Restore = MPDT->findNearestCommonDominator(Restore, &MBB);
295 if (Restore == &MBB) {
306 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
312 DEBUG(
dbgs() <<
"Restore point needs to be spanned on several blocks\n");
323 bool SaveDominatesRestore =
false;
324 bool RestorePostDominatesSave =
false;
325 while (Save && Restore &&
326 (!(SaveDominatesRestore = MDT->dominates(Save, Restore)) ||
327 !(RestorePostDominatesSave = MPDT->dominates(Restore, Save)) ||
345 MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
347 if (!SaveDominatesRestore) {
348 Save = MDT->findNearestCommonDominator(Save, Restore);
352 if (!RestorePostDominatesSave)
353 Restore = MPDT->findNearestCommonDominator(Restore, Save);
356 if (Save && Restore &&
357 (MLI->getLoopFor(Save) || MLI->getLoopFor(Restore))) {
358 if (MLI->getLoopDepth(Save) > MLI->getLoopDepth(Restore)) {
361 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
368 MLI->getLoopFor(Restore)->getExitingBlocks(ExitBlocks);
373 IPdom = FindIDom<>(*IPdom, LoopExitBB->
successors(), *MPDT);
380 if (IPdom && MLI->getLoopDepth(IPdom) < MLI->getLoopDepth(Restore))
414 if (!VisitedBB.test(SuccBB->getNumber()))
427 if (skipFunction(*MF.
getFunction()) || MF.
empty() || !isShrinkWrapEnabled(MF))
441 DEBUG(
dbgs() <<
"Irreducible CFGs are not supported yet\n");
446 std::unique_ptr<RegScavenger> RS(
454 DEBUG(
dbgs() <<
"EH Funclets are not supported yet.\n");
459 if (!useOrDefCSROrFI(
MI, RS.get()))
463 updateSaveRestorePoints(MBB, RS.get());
466 if (!ArePointsInteresting()) {
467 DEBUG(
dbgs() <<
"No Shrink wrap candidate found\n");
475 if (!ArePointsInteresting()) {
479 assert(!Save && !Restore &&
"We miss a shrink-wrap opportunity?!");
480 DEBUG(
dbgs() <<
"Nothing to shrink-wrap\n");
484 DEBUG(
dbgs() <<
"\n ** Results **\nFrequency of the Entry: " << EntryFreq
489 DEBUG(
dbgs() <<
"Shrink wrap candidates (#, Name, Freq):\nSave: "
490 << Save->getNumber() <<
' ' << Save->getName() <<
' '
491 << MBFI->getBlockFreq(Save).getFrequency() <<
"\nRestore: "
492 << Restore->getNumber() <<
' ' << Restore->getName() <<
' '
493 << MBFI->getBlockFreq(Restore).getFrequency() <<
'\n');
495 bool IsSaveCheap, TargetCanUseSaveAsPrologue =
false;
496 if (((IsSaveCheap = EntryFreq >= MBFI->getBlockFreq(Save).getFrequency()) &&
497 EntryFreq >= MBFI->getBlockFreq(Restore).getFrequency()) &&
501 DEBUG(
dbgs() <<
"New points are too expensive or invalid for the target\n");
503 if (!IsSaveCheap || !TargetCanUseSaveAsPrologue) {
504 Save = FindIDom<>(*Save, Save->predecessors(), *MDT);
510 Restore = FindIDom<>(*Restore, Restore->successors(), *MPDT);
515 updateSaveRestorePoints(*NewBB, RS.get());
516 }
while (Save && Restore);
518 if (!ArePointsInteresting()) {
519 ++NumCandidatesDropped;
523 DEBUG(
dbgs() <<
"Final shrink wrap candidates:\nSave: " << Save->getNumber()
524 <<
' ' << Save->getName() <<
"\nRestore: "
525 << Restore->getNumber() <<
' ' << Restore->getName() <<
'\n');
529 MFI.setRestorePoint(Restore);
Pass interface - Implemented by all 'passes'.
static bool isIrreducibleCFG(const MachineFunction &MF, const MachineLoopInfo &MLI)
Check if the CFG of MF is irreducible.
void setSavePoint(MachineBasicBlock *NewSave)
int find_first() const
find_first - Returns the index of the first set bit, -1 if none of the bits are set.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
int find_next(unsigned Prev) const
find_next - Returns the index of the next set bit following the "Prev" bit.
virtual bool canUseAsEpilogue(const MachineBasicBlock &MBB) const
Check whether or not the given MBB can be used as a epilogue for the target.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
LoopT * getParentLoop() const
const Function * getFunction() const
getFunction - Return the LLVM function that this machine code represents
static bool isProperBackedge(const MachineLoopInfo &MLI, const MachineBasicBlock *SrcBB, const MachineBasicBlock *DestBB)
Check whether the edge (SrcBB, DestBB) is a backedge according to MLI.
BlockT * getHeader() const
iterator_range< succ_iterator > successors()
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
unsigned getCallFrameDestroyOpcode() const
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
Reg
All possible values of the reg field in the ModR/M byte.
iterator_range< iterator > terminators()
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted...
virtual bool canUseAsPrologue(const MachineBasicBlock &MBB) const
Check whether or not the given MBB can be used as a prologue for the target.
const MachineBasicBlock & front() const
unsigned getCallFrameSetupOpcode() const
These methods return the opcode of the frame setup/destroy instructions if they exist (-1 otherwise)...
virtual bool requiresRegisterScavenging(const MachineFunction &MF) const
Returns true if the target requires (and can make use of) the register scavenger. ...
TargetInstrInfo - Interface to description of machine instruction set.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
Function Alias Analysis false
initializer< Ty > init(const Ty &Val)
This file declares the machine register scavenger class.
static cl::opt< cl::boolOrDefault > EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden, cl::desc("enable the shrink-wrapping pass"))
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Represent the analysis usage information of a pass.
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
void initializeShrinkWrapPass(PassRegistry &)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
static MachineBasicBlock * FindIDom(MachineBasicBlock &Block, ListOfBBs BBs, DominanceAnalysis &Dom)
Helper function to find the immediate (post) dominator.
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual const TargetFrameLowering * getFrameLowering() const
A SetVector that performs no allocations if smaller than a certain size.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Information about stack frame layout on the target.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
void setPreservesAll()
Set by analyses that do not transform their input at all.
llvm_unreachable("Unknown RegBank!")
Representation of each machine instruction.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Represents a single loop in the control flow graph.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
virtual bool enableShrinkWrapping(const MachineFunction &MF) const
Returns true if the target will correctly handle shrink wrapping.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
virtual const TargetInstrInfo * getInstrInfo() const
char & ShrinkWrapID
ShrinkWrap pass. Look for the best place to insert save and restore.
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
StringRef - Represent a constant reference to a string, i.e.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool usesWindowsCFI() const