Added LLVM project notice to the top of every C++ source file.
[oota-llvm.git] / lib / CodeGen / RegAlloc / LiveRangeInfo.cpp
1 //===-- LiveRangeInfo.cpp -------------------------------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 // 
10 //  Live range construction for coloring-based register allocation for LLVM.
11 // 
12 //===----------------------------------------------------------------------===//
13
14 #include "LiveRangeInfo.h"
15 #include "RegAllocCommon.h"
16 #include "RegClass.h"
17 #include "IGNode.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetRegInfo.h"
23 #include "llvm/Function.h"
24 #include "Support/SetOperations.h"
25
26 unsigned LiveRange::getRegClassID() const { return getRegClass()->getID(); }
27
28 LiveRangeInfo::LiveRangeInfo(const Function *F, const TargetMachine &tm,
29                              std::vector<RegClass *> &RCL)
30   : Meth(F), TM(tm), RegClassList(RCL), MRI(tm.getRegInfo()) { }
31
32
33 LiveRangeInfo::~LiveRangeInfo() {
34   for (LiveRangeMapType::iterator MI = LiveRangeMap.begin(); 
35        MI != LiveRangeMap.end(); ++MI) {  
36
37     if (MI->first && MI->second) {
38       LiveRange *LR = MI->second;
39
40       // we need to be careful in deleting LiveRanges in LiveRangeMap
41       // since two/more Values in the live range map can point to the same
42       // live range. We have to make the other entries NULL when we delete
43       // a live range.
44
45       for (LiveRange::iterator LI = LR->begin(); LI != LR->end(); ++LI)
46         LiveRangeMap[*LI] = 0;
47       
48       delete LR;
49     }
50   }
51 }
52
53
54 //---------------------------------------------------------------------------
55 // union two live ranges into one. The 2nd LR is deleted. Used for coalescing.
56 // Note: the caller must make sure that L1 and L2 are distinct and both
57 // LRs don't have suggested colors
58 //---------------------------------------------------------------------------
59
60 void LiveRangeInfo::unionAndUpdateLRs(LiveRange *L1, LiveRange *L2) {
61   assert(L1 != L2 && (!L1->hasSuggestedColor() || !L2->hasSuggestedColor()));
62   assert(! (L1->hasColor() && L2->hasColor()) ||
63          L1->getColor() == L2->getColor());
64
65   set_union(*L1, *L2);                   // add elements of L2 to L1
66
67   for(ValueSet::iterator L2It = L2->begin(); L2It != L2->end(); ++L2It) {
68     //assert(( L1->getTypeID() == L2->getTypeID()) && "Merge:Different types");
69
70     L1->insert(*L2It);                  // add the var in L2 to L1
71     LiveRangeMap[*L2It] = L1;           // now the elements in L2 should map 
72                                         //to L1    
73   }
74   
75   // set call interference for L1 from L2
76   if (L2->isCallInterference())
77     L1->setCallInterference();
78   
79   // add the spill costs
80   L1->addSpillCost(L2->getSpillCost());
81
82   // If L2 has a color, give L1 that color.  Note that L1 may have had the same
83   // color or none, but would not have a different color as asserted above.
84   if (L2->hasColor())
85     L1->setColor(L2->getColor());
86
87   // Similarly, if LROfUse(L2) has a suggested color, the new range
88   // must have the same color.
89   if (L2->hasSuggestedColor())
90     L1->setSuggestedColor(L2->getSuggestedColor());
91   
92   delete L2;                        // delete L2 as it is no longer needed
93 }
94
95
96 //---------------------------------------------------------------------------
97 // Method for creating a single live range for a definition.
98 // The definition must be represented by a virtual register (a Value).
99 // Note: this function does *not* check that no live range exists for def.
100 //---------------------------------------------------------------------------
101
102 LiveRange*
103 LiveRangeInfo::createNewLiveRange(const Value* Def, bool isCC /* = false*/)
104 {  
105   LiveRange* DefRange = new LiveRange();  // Create a new live range,
106   DefRange->insert(Def);                  // add Def to it,
107   LiveRangeMap[Def] = DefRange;           // and update the map.
108
109   // set the register class of the new live range
110   DefRange->setRegClass(RegClassList[MRI.getRegClassIDOfType(Def->getType(),
111                                                              isCC)]);
112
113   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
114     std::cerr << "  Creating a LR for def ";
115     if (isCC) std::cerr << " (CC Register!)";
116     std::cerr << " : " << RAV(Def) << "\n";
117   }
118   return DefRange;
119 }
120
121
122 LiveRange*
123 LiveRangeInfo::createOrAddToLiveRange(const Value* Def, bool isCC /* = false*/)
124 {  
125   LiveRange *DefRange = LiveRangeMap[Def];
126
127   // check if the LR is already there (because of multiple defs)
128   if (!DefRange) { 
129     DefRange = createNewLiveRange(Def, isCC);
130   } else {                          // live range already exists
131     DefRange->insert(Def);          // add the operand to the range
132     LiveRangeMap[Def] = DefRange;   // make operand point to merged set
133     if (DEBUG_RA >= RA_DEBUG_LiveRanges)
134       std::cerr << "   Added to existing LR for def: " << RAV(Def) << "\n";
135   }
136   return DefRange;
137 }
138
139
140 //---------------------------------------------------------------------------
141 // Method for constructing all live ranges in a function. It creates live 
142 // ranges for all values defined in the instruction stream. Also, it
143 // creates live ranges for all incoming arguments of the function.
144 //---------------------------------------------------------------------------
145 void LiveRangeInfo::constructLiveRanges() {  
146
147   if (DEBUG_RA >= RA_DEBUG_LiveRanges) 
148     std::cerr << "Constructing Live Ranges ...\n";
149
150   // first find the live ranges for all incoming args of the function since
151   // those LRs start from the start of the function
152   for (Function::const_aiterator AI = Meth->abegin(); AI != Meth->aend(); ++AI)
153     createNewLiveRange(AI, /*isCC*/ false);
154
155   // Now suggest hardware registers for these function args 
156   MRI.suggestRegs4MethodArgs(Meth, *this);
157
158   // Now create LRs for machine instructions.  A new LR will be created 
159   // only for defs in the machine instr since, we assume that all Values are
160   // defined before they are used. However, there can be multiple defs for
161   // the same Value in machine instructions.
162   // 
163   // Also, find CALL and RETURN instructions, which need extra work.
164   //
165   MachineFunction &MF = MachineFunction::get(Meth);
166   for (MachineFunction::iterator BBI = MF.begin(); BBI != MF.end(); ++BBI) {
167     MachineBasicBlock &MBB = *BBI;
168
169     // iterate over all the machine instructions in BB
170     for(MachineBasicBlock::iterator MInstIterator = MBB.begin();
171         MInstIterator != MBB.end(); ++MInstIterator) {  
172       MachineInstr *MInst = *MInstIterator; 
173
174       // If the machine instruction is a  call/return instruction, add it to
175       // CallRetInstrList for processing its args, ret value, and ret addr.
176       // 
177       if(TM.getInstrInfo().isReturn(MInst->getOpCode()) ||
178          TM.getInstrInfo().isCall(MInst->getOpCode()))
179         CallRetInstrList.push_back(MInst); 
180  
181       // iterate over explicit MI operands and create a new LR
182       // for each operand that is defined by the instruction
183       for (MachineInstr::val_op_iterator OpI = MInst->begin(),
184              OpE = MInst->end(); OpI != OpE; ++OpI)
185         if (OpI.isDefOnly() || OpI.isDefAndUse()) {     
186           const Value *Def = *OpI;
187           bool isCC = (OpI.getMachineOperand().getType()
188                        == MachineOperand::MO_CCRegister);
189           LiveRange* LR = createOrAddToLiveRange(Def, isCC);
190
191           // If the operand has a pre-assigned register,
192           // set it directly in the LiveRange
193           if (OpI.getMachineOperand().hasAllocatedReg()) {
194             unsigned getClassId;
195             LR->setColor(MRI.getClassRegNum(
196                                 OpI.getMachineOperand().getAllocatedRegNum(),
197                                 getClassId));
198           }
199         }
200
201       // iterate over implicit MI operands and create a new LR
202       // for each operand that is defined by the instruction
203       for (unsigned i = 0; i < MInst->getNumImplicitRefs(); ++i) 
204         if (MInst->getImplicitOp(i).opIsDefOnly() ||
205             MInst->getImplicitOp(i).opIsDefAndUse()) {     
206           const Value *Def = MInst->getImplicitRef(i);
207           LiveRange* LR = createOrAddToLiveRange(Def, /*isCC*/ false);
208
209           // If the implicit operand has a pre-assigned register,
210           // set it directly in the LiveRange
211           if (MInst->getImplicitOp(i).hasAllocatedReg()) {
212             unsigned getClassId;
213             LR->setColor(MRI.getClassRegNum(
214                                 MInst->getImplicitOp(i).getAllocatedRegNum(),
215                                 getClassId));
216           }
217         }
218
219     } // for all machine instructions in the BB
220
221   } // for all BBs in function
222
223   // Now we have to suggest clors for call and return arg live ranges.
224   // Also, if there are implicit defs (e.g., retun value of a call inst)
225   // they must be added to the live range list
226   // 
227   suggestRegs4CallRets();
228
229   if( DEBUG_RA >= RA_DEBUG_LiveRanges) 
230     std::cerr << "Initial Live Ranges constructed!\n";
231 }
232
233
234 //---------------------------------------------------------------------------
235 // If some live ranges must be colored with specific hardware registers
236 // (e.g., for outgoing call args), suggesting of colors for such live
237 // ranges is done using target specific function. Those functions are called
238 // from this function. The target specific methods must:
239 //    1) suggest colors for call and return args. 
240 //    2) create new LRs for implicit defs in machine instructions
241 //---------------------------------------------------------------------------
242 void LiveRangeInfo::suggestRegs4CallRets() {
243   std::vector<MachineInstr*>::iterator It = CallRetInstrList.begin();
244   for( ; It != CallRetInstrList.end(); ++It) {
245     MachineInstr *MInst = *It;
246     MachineOpCode OpCode = MInst->getOpCode();
247
248     if ((TM.getInstrInfo()).isReturn(OpCode))
249       MRI.suggestReg4RetValue(MInst, *this);
250     else if ((TM.getInstrInfo()).isCall(OpCode))
251       MRI.suggestRegs4CallArgs(MInst, *this);
252     else 
253       assert( 0 && "Non call/ret instr in CallRetInstrList" );
254   }
255 }
256
257
258 //--------------------------------------------------------------------------
259 // The following method coalesces live ranges when possible. This method
260 // must be called after the interference graph has been constructed.
261
262
263 /* Algorithm:
264    for each BB in function
265      for each machine instruction (inst)
266        for each definition (def) in inst
267          for each operand (op) of inst that is a use
268            if the def and op are of the same register type
269              if the def and op do not interfere //i.e., not simultaneously live
270                if (degree(LR of def) + degree(LR of op)) <= # avail regs
271                  if both LRs do not have suggested colors
272                     merge2IGNodes(def, op) // i.e., merge 2 LRs 
273
274 */
275 //---------------------------------------------------------------------------
276
277
278 // Checks if live range LR interferes with any node assigned or suggested to
279 // be assigned the specified color
280 // 
281 inline bool InterferesWithColor(const LiveRange& LR, unsigned color)
282 {
283   IGNode* lrNode = LR.getUserIGNode();
284   for (unsigned n=0, NN = lrNode->getNumOfNeighbors(); n < NN; n++) {
285     LiveRange *neighLR = lrNode->getAdjIGNode(n)->getParentLR();
286     if (neighLR->hasColor() && neighLR->getColor() == color)
287       return true;
288     if (neighLR->hasSuggestedColor() && neighLR->getSuggestedColor() == color)
289       return true;
290   }
291   return false;
292 }
293
294 // Cannot coalesce if any of the following is true:
295 // (1) Both LRs have suggested colors (should be "different suggested colors"?)
296 // (2) Both LR1 and LR2 have colors and the colors are different
297 //    (but if the colors are the same, it is definitely safe to coalesce)
298 // (3) LR1 has color and LR2 interferes with any LR that has the same color
299 // (4) LR2 has color and LR1 interferes with any LR that has the same color
300 // 
301 inline bool InterfsPreventCoalescing(const LiveRange& LROfDef,
302                                      const LiveRange& LROfUse)
303 {
304   // (4) if they have different suggested colors, cannot coalesce
305   if (LROfDef.hasSuggestedColor() && LROfUse.hasSuggestedColor())
306     return true;
307
308   // if neither has a color, nothing more to do.
309   if (! LROfDef.hasColor() && ! LROfUse.hasColor())
310     return false;
311
312   // (2, 3) if L1 has color...
313   if (LROfDef.hasColor()) {
314     if (LROfUse.hasColor())
315       return (LROfUse.getColor() != LROfDef.getColor());
316     return InterferesWithColor(LROfUse, LROfDef.getColor());
317   }
318
319   // (4) else only LROfUse has a color: check if that could interfere
320   return InterferesWithColor(LROfDef, LROfUse.getColor());
321 }
322
323
324 void LiveRangeInfo::coalesceLRs()  
325 {
326   if(DEBUG_RA >= RA_DEBUG_LiveRanges) 
327     std::cerr << "\nCoalescing LRs ...\n";
328
329   MachineFunction &MF = MachineFunction::get(Meth);
330   for (MachineFunction::iterator BBI = MF.begin(); BBI != MF.end(); ++BBI) {
331     MachineBasicBlock &MBB = *BBI;
332
333     // iterate over all the machine instructions in BB
334     for(MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII){
335       const MachineInstr *MI = *MII;
336
337       if( DEBUG_RA >= RA_DEBUG_LiveRanges) {
338         std::cerr << " *Iterating over machine instr ";
339         MI->dump();
340         std::cerr << "\n";
341       }
342
343       // iterate over  MI operands to find defs
344       for(MachineInstr::const_val_op_iterator DefI = MI->begin(),
345             DefE = MI->end(); DefI != DefE; ++DefI) {
346         if (DefI.isDefOnly() || DefI.isDefAndUse()) { // this operand is modified
347           LiveRange *LROfDef = getLiveRangeForValue( *DefI );
348           RegClass *RCOfDef = LROfDef->getRegClass();
349
350           MachineInstr::const_val_op_iterator UseI = MI->begin(),
351             UseE = MI->end();
352           for( ; UseI != UseE; ++UseI) { // for all uses
353             LiveRange *LROfUse = getLiveRangeForValue( *UseI );
354             if (!LROfUse) {             // if LR of use is not found
355               //don't warn about labels
356               if (!isa<BasicBlock>(*UseI) && DEBUG_RA >= RA_DEBUG_LiveRanges)
357                 std::cerr << " !! Warning: No LR for use " << RAV(*UseI)<< "\n";
358               continue;                 // ignore and continue
359             }
360
361             if (LROfUse == LROfDef)     // nothing to merge if they are same
362               continue;
363
364             if (MRI.getRegTypeForLR(LROfDef) ==
365                 MRI.getRegTypeForLR(LROfUse)) {
366               // If the two RegTypes are the same
367               if (!RCOfDef->getInterference(LROfDef, LROfUse) ) {
368
369                 unsigned CombinedDegree =
370                   LROfDef->getUserIGNode()->getNumOfNeighbors() + 
371                   LROfUse->getUserIGNode()->getNumOfNeighbors();
372
373                 if (CombinedDegree > RCOfDef->getNumOfAvailRegs()) {
374                   // get more precise estimate of combined degree
375                   CombinedDegree = LROfDef->getUserIGNode()->
376                     getCombinedDegree(LROfUse->getUserIGNode());
377                 }
378
379                 if (CombinedDegree <= RCOfDef->getNumOfAvailRegs()) {
380                   // if both LRs do not have different pre-assigned colors
381                   // and both LRs do not have suggested colors
382                   if (! InterfsPreventCoalescing(*LROfDef, *LROfUse)) {
383                     RCOfDef->mergeIGNodesOfLRs(LROfDef, LROfUse);
384                     unionAndUpdateLRs(LROfDef, LROfUse);
385                   }
386
387                 } // if combined degree is less than # of regs
388               } // if def and use do not interfere
389             }// if reg classes are the same
390           } // for all uses
391         } // if def
392       } // for all defs
393     } // for all machine instructions
394   } // for all BBs
395
396   if (DEBUG_RA >= RA_DEBUG_LiveRanges) 
397     std::cerr << "\nCoalescing Done!\n";
398 }
399
400 /*--------------------------- Debug code for printing ---------------*/
401
402
403 void LiveRangeInfo::printLiveRanges() {
404   LiveRangeMapType::iterator HMI = LiveRangeMap.begin();   // hash map iterator
405   std::cerr << "\nPrinting Live Ranges from Hash Map:\n";
406   for( ; HMI != LiveRangeMap.end(); ++HMI) {
407     if (HMI->first && HMI->second) {
408       std::cerr << " Value* " << RAV(HMI->first) << "\t: "; 
409       if (IGNode* igNode = HMI->second->getUserIGNode())
410         std::cerr << "LR# " << igNode->getIndex();
411       else
412         std::cerr << "LR# " << "<no-IGNode>";
413       std::cerr << "\t:Values = "; printSet(*HMI->second); std::cerr << "\n";
414     }
415   }
416 }