1 //===-- FunctionLiveVarInfo.cpp - Live Variable Analysis for a Function ---===//
3 // This is the interface to function level live variable information that is
4 // provided by live variable analysis.
6 //===----------------------------------------------------------------------===//
8 #include "llvm/CodeGen/FunctionLiveVarInfo.h"
9 #include "llvm/CodeGen/MachineInstr.h"
10 #include "llvm/CodeGen/MachineFunction.h"
11 #include "llvm/Target/TargetMachine.h"
12 #include "llvm/Target/TargetInstrInfo.h"
13 #include "llvm/Support/CFG.h"
14 #include "Support/PostOrderIterator.h"
15 #include "Support/SetOperations.h"
16 #include "Support/CommandLine.h"
17 #include "BBLiveVar.h"
19 static RegisterAnalysis<FunctionLiveVarInfo>
20 X("livevar", "Live Variable Analysis");
22 LiveVarDebugLevel_t DEBUG_LV;
24 static cl::opt<LiveVarDebugLevel_t, true>
25 DEBUG_LV_opt("dlivevar", cl::Hidden, cl::location(DEBUG_LV),
26 cl::desc("enable live-variable debugging information"),
28 clEnumValN(LV_DEBUG_None , "n", "disable debug output"),
29 clEnumValN(LV_DEBUG_Normal , "y", "enable debug output"),
30 clEnumValN(LV_DEBUG_Instr, "i", "print live-var sets before/after "
31 "every machine instrn"),
32 clEnumValN(LV_DEBUG_Verbose, "v", "print def, use sets for every instrn also"),
37 //-----------------------------------------------------------------------------
39 //-----------------------------------------------------------------------------
41 // gets OutSet of a BB
42 const ValueSet &FunctionLiveVarInfo::getOutSetOfBB(const BasicBlock *BB) const {
43 return BBLiveVar::GetFromBB(*BB)->getOutSet();
45 ValueSet &FunctionLiveVarInfo::getOutSetOfBB(const BasicBlock *BB) {
46 return BBLiveVar::GetFromBB(*BB)->getOutSet();
50 const ValueSet &FunctionLiveVarInfo::getInSetOfBB(const BasicBlock *BB) const {
51 return BBLiveVar::GetFromBB(*BB)->getInSet();
53 ValueSet &FunctionLiveVarInfo::getInSetOfBB(const BasicBlock *BB) {
54 return BBLiveVar::GetFromBB(*BB)->getInSet();
58 //-----------------------------------------------------------------------------
59 // Performs live var analysis for a function
60 //-----------------------------------------------------------------------------
62 bool FunctionLiveVarInfo::runOnFunction(Function &F) {
64 if (DEBUG_LV) std::cerr << "Analysing live variables ...\n";
66 // create and initialize all the BBLiveVars of the CFG
70 while (doSingleBackwardPass(M, iter++))
71 ; // Iterate until we are done.
73 if (DEBUG_LV) std::cerr << "Live Variable Analysis complete!\n";
78 //-----------------------------------------------------------------------------
79 // constructs BBLiveVars and init Def and In sets
80 //-----------------------------------------------------------------------------
82 void FunctionLiveVarInfo::constructBBs(const Function *F) {
83 unsigned POId = 0; // Reverse Depth-first Order ID
84 std::map<const BasicBlock*, unsigned> PONumbering;
86 for (po_iterator<const Function*> BBI = po_begin(M), BBE = po_end(M);
88 PONumbering[*BBI] = POId++;
90 MachineFunction &MF = MachineFunction::get(F);
91 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
92 const BasicBlock &BB = *I->getBasicBlock(); // get the current BB
93 if (DEBUG_LV) std::cerr << " For BB " << RAV(BB) << ":\n";
96 std::map<const BasicBlock*, unsigned>::iterator POI = PONumbering.find(&BB);
97 if (POI != PONumbering.end()) {
98 // create a new BBLiveVar
99 LVBB = BBLiveVar::CreateOnBB(BB, *I, POId);
101 // The PO iterator does not discover unreachable blocks, but the random
102 // iterator later may access these blocks. We must make sure to
103 // initialize unreachable blocks as well. However, LV info is not correct
104 // for those blocks (they are not analyzed)
106 LVBB = BBLiveVar::CreateOnBB(BB, *I, ++POId);
110 LVBB->printAllSets();
115 //-----------------------------------------------------------------------------
116 // do one backward pass over the CFG (for iterative analysis)
117 //-----------------------------------------------------------------------------
119 bool FunctionLiveVarInfo::doSingleBackwardPass(const Function *M,
121 if (DEBUG_LV) std::cerr << "\n After Backward Pass " << iter << "...\n";
123 bool NeedAnotherIteration = false;
124 for (po_iterator<const Function*> BBI = po_begin(M), BBE = po_end(M);
126 BBLiveVar *LVBB = BBLiveVar::GetFromBB(**BBI);
127 assert(LVBB && "BasicBlock information not set for block!");
129 if (DEBUG_LV) std::cerr << " For BB " << (*BBI)->getName() << ":\n";
131 // InSets are initialized to "GenSet". Recompute only if OutSet changed.
132 if(LVBB->isOutSetChanged())
133 LVBB->applyTransferFunc(); // apply the Tran Func to calc InSet
135 // OutSets are initialized to EMPTY. Recompute on first iter or if InSet
137 if (iter == 0 || LVBB->isInSetChanged()) // to calc Outsets of preds
138 NeedAnotherIteration |= LVBB->applyFlowFunc();
140 if (DEBUG_LV) LVBB->printInOutSets();
143 // true if we need to reiterate over the CFG
144 return NeedAnotherIteration;
148 void FunctionLiveVarInfo::releaseMemory() {
149 // First remove all BBLiveVar annotations created in constructBBs().
151 for (Function::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
152 BBLiveVar::RemoveFromBB(*I);
155 // Then delete all objects of type ValueSet created in calcLiveVarSetsForBB
156 // and entered into MInst2LVSetBI and MInst2LVSetAI (these are caches
157 // to return ValueSet's before/after a machine instruction quickly).
158 // We do not need to free up ValueSets in MInst2LVSetAI because it holds
159 // pointers to the same sets as in MInst2LVSetBI (for all instructions
160 // except the last one in a BB) or in BBLiveVar (for the last instruction).
162 for (hash_map<const MachineInstr*, ValueSet*>::iterator
163 MI = MInst2LVSetBI.begin(),
164 ME = MInst2LVSetBI.end(); MI != ME; ++MI)
165 delete MI->second; // delete all ValueSets in MInst2LVSetBI
167 MInst2LVSetBI.clear();
168 MInst2LVSetAI.clear();
174 //-----------------------------------------------------------------------------
175 // Following functions will give the LiveVar info for any machine instr in
176 // a function. It should be called after a call to analyze().
178 // Thsese functions calucluates live var info for all the machine instrs in a
179 // BB when LVInfo for one inst is requested. Hence, this function is useful
180 // when live var info is required for many (or all) instructions in a basic
181 // block. Also, the arguments to this function does not require specific
183 //-----------------------------------------------------------------------------
185 //-----------------------------------------------------------------------------
186 // Gives live variable information before a machine instruction
187 //-----------------------------------------------------------------------------
190 FunctionLiveVarInfo::getLiveVarSetBeforeMInst(const MachineInstr *MI,
191 const BasicBlock *BB) {
192 ValueSet* &LVSet = MInst2LVSetBI[MI]; // ref. to map entry
193 if (LVSet == NULL && BB != NULL) { // if not found and BB provided
194 calcLiveVarSetsForBB(BB); // calc LVSet for all instrs in BB
195 assert(LVSet != NULL);
201 //-----------------------------------------------------------------------------
202 // Gives live variable information after a machine instruction
203 //-----------------------------------------------------------------------------
206 FunctionLiveVarInfo::getLiveVarSetAfterMInst(const MachineInstr *MI,
207 const BasicBlock *BB) {
209 ValueSet* &LVSet = MInst2LVSetAI[MI]; // ref. to map entry
210 if (LVSet == NULL && BB != NULL) { // if not found and BB provided
211 calcLiveVarSetsForBB(BB); // calc LVSet for all instrs in BB
212 assert(LVSet != NULL);
217 // This function applies a machine instr to a live var set (accepts OutSet) and
218 // makes necessary changes to it (produces InSet). Note that two for loops are
219 // used to first kill all defs and then to add all uses. This is because there
220 // can be instructions like Val = Val + 1 since we allow multipe defs to a
221 // machine instruction operand.
223 static void applyTranferFuncForMInst(ValueSet &LVS, const MachineInstr *MInst) {
224 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
225 OpE = MInst->end(); OpI != OpE; ++OpI) {
226 if (OpI.isDefOnly() || OpI.isDefAndUse()) // kill if this operand is a def
227 LVS.erase(*OpI); // this definition kills any uses
230 // do for implicit operands as well
231 for (unsigned i=0; i < MInst->getNumImplicitRefs(); ++i) {
232 if (MInst->getImplicitOp(i).opIsDefOnly() ||
233 MInst->getImplicitOp(i).opIsDefAndUse())
234 LVS.erase(MInst->getImplicitRef(i));
237 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
238 OpE = MInst->end(); OpI != OpE; ++OpI) {
239 if (!isa<BasicBlock>(*OpI)) // don't process labels
240 // add only if this operand is a use
241 if (!OpI.isDefOnly() || OpI.isDefAndUse() )
242 LVS.insert(*OpI); // An operand is a use - so add to use set
245 // do for implicit operands as well
246 for (unsigned i = 0, e = MInst->getNumImplicitRefs(); i != e; ++i)
247 if (MInst->getImplicitOp(i).opIsUse() ||
248 MInst->getImplicitOp(i).opIsDefAndUse())
249 LVS.insert(MInst->getImplicitRef(i));
252 //-----------------------------------------------------------------------------
253 // This method calculates the live variable information for all the
254 // instructions in a basic block and enter the newly constructed live
255 // variable sets into a the caches (MInst2LVSetAI, MInst2LVSetBI)
256 //-----------------------------------------------------------------------------
258 void FunctionLiveVarInfo::calcLiveVarSetsForBB(const BasicBlock *BB) {
259 BBLiveVar *BBLV = BBLiveVar::GetFromBB(*BB);
260 assert(BBLV && "BBLiveVar annotation doesn't exist?");
261 const MachineBasicBlock &MIVec = BBLV->getMachineBasicBlock();
262 const MachineFunction &MF = MachineFunction::get(M);
263 const TargetMachine &TM = MF.getTarget();
265 if (DEBUG_LV >= LV_DEBUG_Instr)
266 std::cerr << "\n======For BB " << BB->getName()
267 << ": Live var sets for instructions======\n";
269 ValueSet *SetAI = &getOutSetOfBB(BB); // init SetAI with OutSet
270 ValueSet CurSet(*SetAI); // CurSet now contains OutSet
272 // iterate over all the machine instructions in BB
273 for (MachineBasicBlock::const_reverse_iterator MII = MIVec.rbegin(),
274 MIE = MIVec.rend(); MII != MIE; ++MII) {
275 // MI is cur machine inst
276 const MachineInstr *MI = *MII;
278 MInst2LVSetAI[MI] = SetAI; // record in After Inst map
280 applyTranferFuncForMInst(CurSet, MI); // apply the transfer Func
281 ValueSet *NewSet = new ValueSet(CurSet); // create a new set with a copy
282 // of the set after T/F
283 MInst2LVSetBI[MI] = NewSet; // record in Before Inst map
285 // If the current machine instruction has delay slots, mark values
286 // used by this instruction as live before and after each delay slot
287 // instruction (After(MI) is the same as Before(MI+1) except for last MI).
288 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(MI->getOpCode())) {
289 MachineBasicBlock::const_iterator fwdMII = MII.base(); // ptr to *next* MI
290 for (unsigned i = 0; i < DS; ++i, ++fwdMII) {
291 assert(fwdMII != MIVec.end() && "Missing instruction in delay slot?");
292 MachineInstr* DelaySlotMI = *fwdMII;
293 if (! TM.getInstrInfo().isNop(DelaySlotMI->getOpCode())) {
294 set_union(*MInst2LVSetBI[DelaySlotMI], *NewSet);
296 set_union(*MInst2LVSetAI[DelaySlotMI], *NewSet);
301 if (DEBUG_LV >= LV_DEBUG_Instr) {
302 std::cerr << "\nLive var sets before/after instruction " << *MI;
303 std::cerr << " Before: "; printSet(*NewSet); std::cerr << "\n";
304 std::cerr << " After : "; printSet(*SetAI); std::cerr << "\n";
307 // SetAI will be used in the next iteration