32a86047c52ed8a0b47161f988ce306612382202
[oota-llvm.git] / lib / Target / SparcV9 / RegAlloc / PhyRegAlloc.cpp
1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
2 // 
3 //  Register allocation for LLVM.
4 // 
5 //===----------------------------------------------------------------------===//
6
7 #include "PhyRegAlloc.h"
8 #include "RegAllocCommon.h"
9 #include "RegClass.h"
10 #include "IGNode.h"
11 #include "llvm/CodeGen/MachineInstr.h"
12 #include "llvm/CodeGen/MachineInstrBuilder.h"
13 #include "llvm/CodeGen/MachineInstrAnnot.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineFunctionInfo.h"
16 #include "llvm/CodeGen/FunctionLiveVarInfo.h"
17 #include "llvm/CodeGen/InstrSelection.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Target/TargetInstrInfo.h"
20 #include "llvm/Function.h"
21 #include "llvm/Type.h"
22 #include "llvm/iOther.h"
23 #include "Support/STLExtras.h"
24 #include "Support/SetOperations.h"
25 #include "Support/CommandLine.h"
26 #include <cmath>
27
28 RegAllocDebugLevel_t DEBUG_RA;
29
30 static cl::opt<RegAllocDebugLevel_t, true>
31 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
32         cl::desc("enable register allocation debugging information"),
33         cl::values(
34   clEnumValN(RA_DEBUG_None   ,     "n", "disable debug output"),
35   clEnumValN(RA_DEBUG_Results,     "y", "debug output for allocation results"),
36   clEnumValN(RA_DEBUG_Coloring,    "c", "debug output for graph coloring step"),
37   clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
38   clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
39   clEnumValN(RA_DEBUG_Verbose,     "v", "extra debug output"),
40                    0));
41
42 static cl::opt<bool>
43 SaveRegAllocState("save-ra-state", cl::Hidden,
44                   cl::desc("write reg. allocator state into module"));
45
46 FunctionPass *getRegisterAllocator(TargetMachine &T) {
47   return new PhyRegAlloc (T);
48 }
49
50 void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
51   AU.addRequired<LoopInfo> ();
52   AU.addRequired<FunctionLiveVarInfo> ();
53 }
54
55
56
57 //----------------------------------------------------------------------------
58 // This method initially creates interference graphs (one in each reg class)
59 // and IGNodeList (one in each IG). The actual nodes will be pushed later. 
60 //----------------------------------------------------------------------------
61 void PhyRegAlloc::createIGNodeListsAndIGs() {
62   if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
63
64   // hash map iterator
65   LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();   
66
67   // hash map end
68   LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();   
69
70   for (; HMI != HMIEnd ; ++HMI ) {
71     if (HMI->first) { 
72       LiveRange *L = HMI->second;   // get the LiveRange
73       if (!L) { 
74         if (DEBUG_RA)
75           std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
76                << RAV(HMI->first) << "****\n";
77         continue;
78       }
79
80       // if the Value * is not null, and LR is not yet written to the IGNodeList
81       if (!(L->getUserIGNode())  ) {  
82         RegClass *const RC =           // RegClass of first value in the LR
83           RegClassList[ L->getRegClassID() ];
84         RC->addLRToIG(L);              // add this LR to an IG
85       }
86     }
87   }
88     
89   // init RegClassList
90   for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)  
91     RegClassList[rc]->createInterferenceGraph();
92
93   if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
94 }
95
96
97 //----------------------------------------------------------------------------
98 // This method will add all interferences at for a given instruction.
99 // Interference occurs only if the LR of Def (Inst or Arg) is of the same reg 
100 // class as that of live var. The live var passed to this function is the 
101 // LVset AFTER the instruction
102 //----------------------------------------------------------------------------
103
104 void PhyRegAlloc::addInterference(const Value *Def, 
105                                   const ValueSet *LVSet,
106                                   bool isCallInst) {
107   ValueSet::const_iterator LIt = LVSet->begin();
108
109   // get the live range of instruction
110   const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );   
111
112   IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
113   assert( IGNodeOfDef );
114
115   RegClass *const RCOfDef = LROfDef->getRegClass(); 
116
117   // for each live var in live variable set
118   for ( ; LIt != LVSet->end(); ++LIt) {
119
120     if (DEBUG_RA >= RA_DEBUG_Verbose)
121       std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
122
123     //  get the live range corresponding to live var
124     LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
125
126     // LROfVar can be null if it is a const since a const 
127     // doesn't have a dominating def - see Assumptions above
128     if (LROfVar)
129       if (LROfDef != LROfVar)                  // do not set interf for same LR
130         if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
131           RCOfDef->setInterference( LROfDef, LROfVar);  
132   }
133 }
134
135
136 //----------------------------------------------------------------------------
137 // For a call instruction, this method sets the CallInterference flag in 
138 // the LR of each variable live int the Live Variable Set live after the
139 // call instruction (except the return value of the call instruction - since
140 // the return value does not interfere with that call itself).
141 //----------------------------------------------------------------------------
142
143 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst, 
144                                        const ValueSet *LVSetAft) {
145   if (DEBUG_RA >= RA_DEBUG_Interference)
146     std::cerr << "\n For call inst: " << *MInst;
147
148   // for each live var in live variable set after machine inst
149   for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
150        LIt != LEnd; ++LIt) {
151
152     //  get the live range corresponding to live var
153     LiveRange *const LR = LRI->getLiveRangeForValue(*LIt ); 
154
155     // LR can be null if it is a const since a const 
156     // doesn't have a dominating def - see Assumptions above
157     if (LR ) {  
158       if (DEBUG_RA >= RA_DEBUG_Interference) {
159         std::cerr << "\n\tLR after Call: ";
160         printSet(*LR);
161       }
162       LR->setCallInterference();
163       if (DEBUG_RA >= RA_DEBUG_Interference) {
164         std::cerr << "\n  ++After adding call interference for LR: " ;
165         printSet(*LR);
166       }
167     }
168
169   }
170
171   // Now find the LR of the return value of the call
172   // We do this because, we look at the LV set *after* the instruction
173   // to determine, which LRs must be saved across calls. The return value
174   // of the call is live in this set - but it does not interfere with call
175   // (i.e., we can allocate a volatile register to the return value)
176   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
177   
178   if (const Value *RetVal = argDesc->getReturnValue()) {
179     LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
180     assert( RetValLR && "No LR for RetValue of call");
181     RetValLR->clearCallInterference();
182   }
183
184   // If the CALL is an indirect call, find the LR of the function pointer.
185   // That has a call interference because it conflicts with outgoing args.
186   if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
187     LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
188     assert( AddrValLR && "No LR for indirect addr val of call");
189     AddrValLR->setCallInterference();
190   }
191 }
192
193
194 //----------------------------------------------------------------------------
195 // This method will walk thru code and create interferences in the IG of
196 // each RegClass. Also, this method calculates the spill cost of each
197 // Live Range (it is done in this method to save another pass over the code).
198 //----------------------------------------------------------------------------
199
200 void PhyRegAlloc::buildInterferenceGraphs()
201 {
202   if (DEBUG_RA >= RA_DEBUG_Interference)
203     std::cerr << "Creating interference graphs ...\n";
204
205   unsigned BBLoopDepthCost;
206   for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
207        BBI != BBE; ++BBI) {
208     const MachineBasicBlock &MBB = *BBI;
209     const BasicBlock *BB = MBB.getBasicBlock();
210
211     // find the 10^(loop_depth) of this BB 
212     BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
213
214     // get the iterator for machine instructions
215     MachineBasicBlock::const_iterator MII = MBB.begin();
216
217     // iterate over all the machine instructions in BB
218     for ( ; MII != MBB.end(); ++MII) {
219       const MachineInstr *MInst = *MII;
220
221       // get the LV set after the instruction
222       const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
223       bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
224
225       if (isCallInst ) {
226         // set the isCallInterference flag of each live range which extends
227         // across this call instruction. This information is used by graph
228         // coloring algorithm to avoid allocating volatile colors to live ranges
229         // that span across calls (since they have to be saved/restored)
230         setCallInterferences(MInst, &LVSetAI);
231       }
232
233       // iterate over all MI operands to find defs
234       for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
235              OpE = MInst->end(); OpI != OpE; ++OpI) {
236         if (OpI.isDefOnly() || OpI.isDefAndUse()) // create a new LR since def
237           addInterference(*OpI, &LVSetAI, isCallInst);
238
239         // Calculate the spill cost of each live range
240         LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
241         if (LR) LR->addSpillCost(BBLoopDepthCost);
242       } 
243
244       // if there are multiple defs in this instruction e.g. in SETX
245       if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
246         addInterf4PseudoInstr(MInst);
247
248       // Also add interference for any implicit definitions in a machine
249       // instr (currently, only calls have this).
250       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
251       for (unsigned z=0; z < NumOfImpRefs; z++) 
252         if (MInst->getImplicitOp(z).opIsDefOnly() ||
253             MInst->getImplicitOp(z).opIsDefAndUse())
254           addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
255
256     } // for all machine instructions in BB
257   } // for all BBs in function
258
259   // add interferences for function arguments. Since there are no explicit 
260   // defs in the function for args, we have to add them manually
261   addInterferencesForArgs();          
262
263   if (DEBUG_RA >= RA_DEBUG_Interference)
264     std::cerr << "Interference graphs calculated!\n";
265 }
266
267
268 //--------------------------------------------------------------------------
269 // Pseudo-instructions may be expanded to multiple instructions by the
270 // assembler. Consequently, all the operands must get distinct registers.
271 // Therefore, we mark all operands of a pseudo-instruction as interfering
272 // with one another.
273 //--------------------------------------------------------------------------
274
275 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
276   bool setInterf = false;
277
278   // iterate over MI operands to find defs
279   for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
280          ItE = MInst->end(); It1 != ItE; ++It1) {
281     const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1); 
282     assert((LROfOp1 || !It1.isUseOnly())&&"No LR for Def in PSEUDO insruction");
283
284     MachineInstr::const_val_op_iterator It2 = It1;
285     for (++It2; It2 != ItE; ++It2) {
286       const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2); 
287
288       if (LROfOp2) {
289         RegClass *RCOfOp1 = LROfOp1->getRegClass(); 
290         RegClass *RCOfOp2 = LROfOp2->getRegClass(); 
291  
292         if (RCOfOp1 == RCOfOp2 ){ 
293           RCOfOp1->setInterference( LROfOp1, LROfOp2 );  
294           setInterf = true;
295         }
296       } // if Op2 has a LR
297     } // for all other defs in machine instr
298   } // for all operands in an instruction
299
300   if (!setInterf && MInst->getNumOperands() > 2) {
301     std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
302     std::cerr << *MInst;
303     assert(0 && "Interf not set for pseudo instr with > 2 operands" );
304   }
305
306
307
308 //----------------------------------------------------------------------------
309 // This method adds interferences for incoming arguments to a function.
310 //----------------------------------------------------------------------------
311
312 void PhyRegAlloc::addInterferencesForArgs() {
313   // get the InSet of root BB
314   const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());  
315
316   for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
317     // add interferences between args and LVars at start 
318     addInterference(AI, &InSet, false);
319     
320     if (DEBUG_RA >= RA_DEBUG_Interference)
321       std::cerr << " - %% adding interference for  argument " << RAV(AI) << "\n";
322   }
323 }
324
325
326 //----------------------------------------------------------------------------
327 // This method is called after register allocation is complete to set the
328 // allocated registers in the machine code. This code will add register numbers
329 // to MachineOperands that contain a Value. Also it calls target specific
330 // methods to produce caller saving instructions. At the end, it adds all
331 // additional instructions produced by the register allocator to the 
332 // instruction stream. 
333 //----------------------------------------------------------------------------
334
335 //-----------------------------
336 // Utility functions used below
337 //-----------------------------
338 inline void
339 InsertBefore(MachineInstr* newMI,
340              MachineBasicBlock& MBB,
341              MachineBasicBlock::iterator& MII)
342 {
343   MII = MBB.insert(MII, newMI);
344   ++MII;
345 }
346
347 inline void
348 InsertAfter(MachineInstr* newMI,
349             MachineBasicBlock& MBB,
350             MachineBasicBlock::iterator& MII)
351 {
352   ++MII;    // insert before the next instruction
353   MII = MBB.insert(MII, newMI);
354 }
355
356 inline void
357 DeleteInstruction(MachineBasicBlock& MBB,
358                   MachineBasicBlock::iterator& MII)
359 {
360   MII = MBB.erase(MII);
361 }
362
363 inline void
364 SubstituteInPlace(MachineInstr* newMI,
365                   MachineBasicBlock& MBB,
366                   MachineBasicBlock::iterator MII)
367 {
368   *MII = newMI;
369 }
370
371 inline void
372 PrependInstructions(std::vector<MachineInstr *> &IBef,
373                     MachineBasicBlock& MBB,
374                     MachineBasicBlock::iterator& MII,
375                     const std::string& msg)
376 {
377   if (!IBef.empty())
378     {
379       MachineInstr* OrigMI = *MII;
380       std::vector<MachineInstr *>::iterator AdIt; 
381       for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
382         {
383           if (DEBUG_RA) {
384             if (OrigMI) std::cerr << "For MInst:\n  " << *OrigMI;
385             std::cerr << msg << "PREPENDed instr:\n  " << **AdIt << "\n";
386           }
387           InsertBefore(*AdIt, MBB, MII);
388         }
389     }
390 }
391
392 inline void
393 AppendInstructions(std::vector<MachineInstr *> &IAft,
394                    MachineBasicBlock& MBB,
395                    MachineBasicBlock::iterator& MII,
396                    const std::string& msg)
397 {
398   if (!IAft.empty())
399     {
400       MachineInstr* OrigMI = *MII;
401       std::vector<MachineInstr *>::iterator AdIt; 
402       for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
403         {
404           if (DEBUG_RA) {
405             if (OrigMI) std::cerr << "For MInst:\n  " << *OrigMI;
406             std::cerr << msg << "APPENDed instr:\n  "  << **AdIt << "\n";
407           }
408           InsertAfter(*AdIt, MBB, MII);
409         }
410     }
411 }
412
413 bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
414 {
415   bool instrNeedsSpills = false;
416
417   // First, set the registers for operands in the machine instruction
418   // if a register was successfully allocated.  Do this first because we
419   // will need to know which registers are already used by this instr'n.
420   for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
421     {
422       MachineOperand& Op = MInst->getOperand(OpNum);
423       if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
424           Op.getType() ==  MachineOperand::MO_CCRegister)
425         {
426           const Value *const Val =  Op.getVRegValue();
427           if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
428             // Remember if any operand needs spilling
429             instrNeedsSpills |= LR->isMarkedForSpill();
430
431             // An operand may have a color whether or not it needs spilling
432             if (LR->hasColor())
433               MInst->SetRegForOperand(OpNum,
434                           MRI.getUnifiedRegNum(LR->getRegClassID(),
435                                                LR->getColor()));
436           }
437         }
438     } // for each operand
439
440   return instrNeedsSpills;
441 }
442
443 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
444                                     MachineBasicBlock &MBB)
445 {
446   MachineInstr* MInst = *MII;
447   unsigned Opcode = MInst->getOpCode();
448
449   // Reset tmp stack positions so they can be reused for each machine instr.
450   MF->getInfo()->popAllTempValues();  
451
452   // Mark the operands for which regs have been allocated.
453   bool instrNeedsSpills = markAllocatedRegs(*MII);
454
455 #ifndef NDEBUG
456   // Mark that the operands have been updated.  Later,
457   // setRelRegsUsedByThisInst() is called to find registers used by each
458   // MachineInst, and it should not be used for an instruction until
459   // this is done.  This flag just serves as a sanity check.
460   OperandsColoredMap[MInst] = true;
461 #endif
462
463   // Now insert caller-saving code before/after the call.
464   // Do this before inserting spill code since some registers must be
465   // used by save/restore and spill code should not use those registers.
466   if (TM.getInstrInfo().isCall(Opcode)) {
467     AddedInstrns &AI = AddedInstrMap[MInst];
468     insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
469                            MBB.getBasicBlock());
470   }
471
472   // Now insert spill code for remaining operands not allocated to
473   // registers.  This must be done even for call return instructions
474   // since those are not handled by the special code above.
475   if (instrNeedsSpills)
476     for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
477       {
478         MachineOperand& Op = MInst->getOperand(OpNum);
479         if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
480             Op.getType() ==  MachineOperand::MO_CCRegister)
481           {
482             const Value* Val = Op.getVRegValue();
483             if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
484               if (LR->isMarkedForSpill())
485                 insertCode4SpilledLR(LR, MII, MBB, OpNum);
486           }
487       } // for each operand
488 }
489
490 void PhyRegAlloc::updateMachineCode()
491 {
492   // Insert any instructions needed at method entry
493   MachineBasicBlock::iterator MII = MF->front().begin();
494   PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
495                       "At function entry: \n");
496   assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
497          "InstrsAfter should be unnecessary since we are just inserting at "
498          "the function entry point here.");
499   
500   for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
501        BBI != BBE; ++BBI) {
502
503     MachineBasicBlock &MBB = *BBI;
504
505     // Iterate over all machine instructions in BB and mark operands with
506     // their assigned registers or insert spill code, as appropriate. 
507     // Also, fix operands of call/return instructions.
508     for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
509       if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
510         updateInstruction(MII, MBB);
511
512     // Now, move code out of delay slots of branches and returns if needed.
513     // (Also, move "after" code from calls to the last delay slot instruction.)
514     // Moving code out of delay slots is needed in 2 situations:
515     // (1) If this is a branch and it needs instructions inserted after it,
516     //     move any existing instructions out of the delay slot so that the
517     //     instructions can go into the delay slot.  This only supports the
518     //     case that #instrsAfter <= #delay slots.
519     // 
520     // (2) If any instruction in the delay slot needs
521     //     instructions inserted, move it out of the delay slot and before the
522     //     branch because putting code before or after it would be VERY BAD!
523     // 
524     // If the annul bit of the branch is set, neither of these is legal!
525     // If so, we need to handle spill differently but annulling is not yet used.
526     for (MachineBasicBlock::iterator MII = MBB.begin();
527          MII != MBB.end(); ++MII)
528       if (unsigned delaySlots =
529           TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
530         { 
531           MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
532           
533           // Check the 2 conditions above:
534           // (1) Does a branch need instructions added after it?
535           // (2) O/w does delay slot instr. need instrns before or after?
536           bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
537                            TM.getInstrInfo().isReturn(MInst->getOpCode()));
538           bool cond1 = (isBranch &&
539                         AddedInstrMap.count(MInst) &&
540                         AddedInstrMap[MInst].InstrnsAfter.size() > 0);
541           bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
542                         (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
543                          AddedInstrMap[DelaySlotMI].InstrnsAfter.size()  > 0));
544
545           if (cond1 || cond2)
546             {
547               assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
548                      "FIXME: Moving an annulled delay slot instruction!"); 
549               assert(delaySlots==1 &&
550                      "InsertBefore does not yet handle >1 delay slots!");
551               InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
552
553               // In case (1), delete it and don't replace with anything!
554               // Otherwise (i.e., case (2) only) replace it with a NOP.
555               if (cond1) {
556                 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
557                 --MII;                         // reset MII for ++MII of loop
558               }
559               else
560                 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
561                                   MBB, MII+1);        // replace with NOP
562
563               if (DEBUG_RA) {
564                 std::cerr << "\nRegAlloc: Moved instr. with added code: "
565                      << *DelaySlotMI
566                      << "           out of delay slots of instr: " << *MInst;
567               }
568             }
569           else
570             // For non-branch instr with delay slots (probably a call), move
571             // InstrAfter to the instr. in the last delay slot.
572             move2DelayedInstr(*MII, *(MII+delaySlots));
573         }
574
575     // Finally iterate over all instructions in BB and insert before/after
576     for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
577       MachineInstr *MInst = *MII; 
578
579       // do not process Phis
580       if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
581         continue;
582
583       // if there are any added instructions...
584       if (AddedInstrMap.count(MInst)) {
585         AddedInstrns &CallAI = AddedInstrMap[MInst];
586
587 #ifndef NDEBUG
588         bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
589                          TM.getInstrInfo().isReturn(MInst->getOpCode()));
590         assert((!isBranch ||
591                 AddedInstrMap[MInst].InstrnsAfter.size() <=
592                 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
593                "Cannot put more than #delaySlots instrns after "
594                "branch or return! Need to handle temps differently.");
595 #endif
596
597 #ifndef NDEBUG
598         // Temporary sanity checking code to detect whether the same machine
599         // instruction is ever inserted twice before/after a call.
600         // I suspect this is happening but am not sure. --Vikram, 7/1/03.
601         std::set<const MachineInstr*> instrsSeen;
602         for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
603           assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
604                  "Duplicate machine instruction in InstrnsBefore!");
605           instrsSeen.insert(CallAI.InstrnsBefore[i]);
606         } 
607         for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
608           assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
609                  "Duplicate machine instruction in InstrnsBefore/After!");
610           instrsSeen.insert(CallAI.InstrnsAfter[i]);
611         } 
612 #endif
613
614         // Now add the instructions before/after this MI.
615         // We do this here to ensure that spill for an instruction is inserted
616         // as close as possible to an instruction (see above insertCode4Spill)
617         if (! CallAI.InstrnsBefore.empty())
618           PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
619         
620         if (! CallAI.InstrnsAfter.empty())
621           AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
622
623       } // if there are any added instructions
624     } // for each machine instruction
625   }
626 }
627
628
629 //----------------------------------------------------------------------------
630 // This method inserts spill code for AN operand whose LR was spilled.
631 // This method may be called several times for a single machine instruction
632 // if it contains many spilled operands. Each time it is called, it finds
633 // a register which is not live at that instruction and also which is not
634 // used by other spilled operands of the same instruction. Then it uses
635 // this register temporarily to accommodate the spilled value.
636 //----------------------------------------------------------------------------
637
638 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR, 
639                                        MachineBasicBlock::iterator& MII,
640                                        MachineBasicBlock &MBB,
641                                        const unsigned OpNum) {
642   MachineInstr *MInst = *MII;
643   const BasicBlock *BB = MBB.getBasicBlock();
644
645   assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
646          "Outgoing arg of a call must be handled elsewhere (func arg ok)");
647   assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
648          "Return value of a ret must be handled elsewhere");
649
650   MachineOperand& Op = MInst->getOperand(OpNum);
651   bool isDef =  Op.opIsDefOnly();
652   bool isDefAndUse = Op.opIsDefAndUse();
653   unsigned RegType = MRI.getRegTypeForLR(LR);
654   int SpillOff = LR->getSpillOffFromFP();
655   RegClass *RC = LR->getRegClass();
656
657   // Get the live-variable set to find registers free before this instr.
658   const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
659
660 #ifndef NDEBUG
661   // If this instr. is in the delay slot of a branch or return, we need to
662   // include all live variables before that branch or return -- we don't want to
663   // trample those!  Verify that the set is included in the LV set before MInst.
664   if (MII != MBB.begin()) {
665     MachineInstr *PredMI = *(MII-1);
666     if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
667       assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
668              .empty() && "Live-var set before branch should be included in "
669              "live-var set of each delay slot instruction!");
670   }
671 #endif
672
673   MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
674   
675   std::vector<MachineInstr*> MIBef, MIAft;
676   std::vector<MachineInstr*> AdIMid;
677   
678   // Choose a register to hold the spilled value, if one was not preallocated.
679   // This may insert code before and after MInst to free up the value.  If so,
680   // this code should be first/last in the spill sequence before/after MInst.
681   int TmpRegU=(LR->hasColor()
682                ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
683                : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
684   
685   // Set the operand first so that it this register does not get used
686   // as a scratch register for later calls to getUsableUniRegAtMI below
687   MInst->SetRegForOperand(OpNum, TmpRegU);
688   
689   // get the added instructions for this instruction
690   AddedInstrns &AI = AddedInstrMap[MInst];
691
692   // We may need a scratch register to copy the spilled value to/from memory.
693   // This may itself have to insert code to free up a scratch register.  
694   // Any such code should go before (after) the spill code for a load (store).
695   // The scratch reg is not marked as used because it is only used
696   // for the copy and not used across MInst.
697   int scratchRegType = -1;
698   int scratchReg = -1;
699   if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
700     {
701       scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
702                                        MInst, MIBef, MIAft);
703       assert(scratchReg != MRI.getInvalidRegNum());
704     }
705   
706   if (!isDef || isDefAndUse) {
707     // for a USE, we have to load the value of LR from stack to a TmpReg
708     // and use the TmpReg as one operand of instruction
709     
710     // actual loading instruction(s)
711     MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
712                     RegType, scratchReg);
713     
714     // the actual load should be after the instructions to free up TmpRegU
715     MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
716     AdIMid.clear();
717   }
718   
719   if (isDef || isDefAndUse) {   // if this is a Def
720     // for a DEF, we have to store the value produced by this instruction
721     // on the stack position allocated for this LR
722     
723     // actual storing instruction(s)
724     MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
725                     RegType, scratchReg);
726     
727     MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
728   }  // if !DEF
729   
730   // Finally, insert the entire spill code sequences before/after MInst
731   AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
732   AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
733   
734   if (DEBUG_RA) {
735     std::cerr << "\nFor Inst:\n  " << *MInst;
736     std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
737     std::cerr << "; added Instructions:";
738     for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
739     for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
740   }
741 }
742
743
744 //----------------------------------------------------------------------------
745 // This method inserts caller saving/restoring instructions before/after
746 // a call machine instruction. The caller saving/restoring instructions are
747 // inserted like:
748 //    ** caller saving instructions
749 //    other instructions inserted for the call by ColorCallArg
750 //    CALL instruction
751 //    other instructions inserted for the call ColorCallArg
752 //    ** caller restoring instructions
753 //----------------------------------------------------------------------------
754
755 void
756 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
757                                     std::vector<MachineInstr*> &instrnsAfter,
758                                     MachineInstr *CallMI, 
759                                     const BasicBlock *BB)
760 {
761   assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
762   
763   // hash set to record which registers were saved/restored
764   hash_set<unsigned> PushedRegSet;
765
766   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
767   
768   // if the call is to a instrumentation function, do not insert save and
769   // restore instructions the instrumentation function takes care of save
770   // restore for volatile regs.
771   //
772   // FIXME: this should be made general, not specific to the reoptimizer!
773   const Function *Callee = argDesc->getCallInst()->getCalledFunction();
774   bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
775
776   // Now check if the call has a return value (using argDesc) and if so,
777   // find the LR of the TmpInstruction representing the return value register.
778   // (using the last or second-last *implicit operand* of the call MI).
779   // Insert it to to the PushedRegSet since we must not save that register
780   // and restore it after the call.
781   // We do this because, we look at the LV set *after* the instruction
782   // to determine, which LRs must be saved across calls. The return value
783   // of the call is live in this set - but we must not save/restore it.
784   if (const Value *origRetVal = argDesc->getReturnValue()) {
785     unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
786                              (argDesc->getIndirectFuncPtr()? 1 : 2));
787     const TmpInstruction* tmpRetVal =
788       cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
789     assert(tmpRetVal->getOperand(0) == origRetVal &&
790            tmpRetVal->getType() == origRetVal->getType() &&
791            "Wrong implicit ref?");
792     LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
793     assert(RetValLR && "No LR for RetValue of call");
794
795     if (! RetValLR->isMarkedForSpill())
796       PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
797                                                RetValLR->getColor()));
798   }
799
800   const ValueSet &LVSetAft =  LVI->getLiveVarSetAfterMInst(CallMI, BB);
801   ValueSet::const_iterator LIt = LVSetAft.begin();
802
803   // for each live var in live variable set after machine inst
804   for( ; LIt != LVSetAft.end(); ++LIt) {
805     // get the live range corresponding to live var
806     LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
807
808     // LR can be null if it is a const since a const 
809     // doesn't have a dominating def - see Assumptions above
810     if( LR )   {  
811       if(! LR->isMarkedForSpill()) {
812         assert(LR->hasColor() && "LR is neither spilled nor colored?");
813         unsigned RCID = LR->getRegClassID();
814         unsigned Color = LR->getColor();
815
816         if (MRI.isRegVolatile(RCID, Color) ) {
817           // if this is a call to the first-level reoptimizer
818           // instrumentation entry point, and the register is not
819           // modified by call, don't save and restore it.
820           if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
821             continue;
822
823           // if the value is in both LV sets (i.e., live before and after 
824           // the call machine instruction)
825           unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
826           
827           // if we haven't already pushed this register...
828           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
829             unsigned RegType = MRI.getRegTypeForLR(LR);
830
831             // Now get two instructions - to push on stack and pop from stack
832             // and add them to InstrnsBefore and InstrnsAfter of the
833             // call instruction
834             int StackOff =
835               MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
836             
837             //---- Insert code for pushing the reg on stack ----------
838             
839             std::vector<MachineInstr*> AdIBef, AdIAft;
840             
841             // We may need a scratch register to copy the saved value
842             // to/from memory.  This may itself have to insert code to
843             // free up a scratch register.  Any such code should go before
844             // the save code.  The scratch register, if any, is by default
845             // temporary and not "used" by the instruction unless the
846             // copy code itself decides to keep the value in the scratch reg.
847             int scratchRegType = -1;
848             int scratchReg = -1;
849             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
850               { // Find a register not live in the LVSet before CallMI
851                 const ValueSet &LVSetBef =
852                   LVI->getLiveVarSetBeforeMInst(CallMI, BB);
853                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
854                                                  CallMI, AdIBef, AdIAft);
855                 assert(scratchReg != MRI.getInvalidRegNum());
856               }
857             
858             if (AdIBef.size() > 0)
859               instrnsBefore.insert(instrnsBefore.end(),
860                                    AdIBef.begin(), AdIBef.end());
861             
862             MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
863                             StackOff, RegType, scratchReg);
864             
865             if (AdIAft.size() > 0)
866               instrnsBefore.insert(instrnsBefore.end(),
867                                    AdIAft.begin(), AdIAft.end());
868             
869             //---- Insert code for popping the reg from the stack ----------
870             AdIBef.clear();
871             AdIAft.clear();
872             
873             // We may need a scratch register to copy the saved value
874             // from memory.  This may itself have to insert code to
875             // free up a scratch register.  Any such code should go
876             // after the save code.  As above, scratch is not marked "used".
877             scratchRegType = -1;
878             scratchReg = -1;
879             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
880               { // Find a register not live in the LVSet after CallMI
881                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
882                                                  CallMI, AdIBef, AdIAft);
883                 assert(scratchReg != MRI.getInvalidRegNum());
884               }
885             
886             if (AdIBef.size() > 0)
887               instrnsAfter.insert(instrnsAfter.end(),
888                                   AdIBef.begin(), AdIBef.end());
889             
890             MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
891                             Reg, RegType, scratchReg);
892             
893             if (AdIAft.size() > 0)
894               instrnsAfter.insert(instrnsAfter.end(),
895                                   AdIAft.begin(), AdIAft.end());
896             
897             PushedRegSet.insert(Reg);
898             
899             if(DEBUG_RA) {
900               std::cerr << "\nFor call inst:" << *CallMI;
901               std::cerr << " -inserted caller saving instrs: Before:\n\t ";
902               for_each(instrnsBefore.begin(), instrnsBefore.end(),
903                        std::mem_fun(&MachineInstr::dump));
904               std::cerr << " -and After:\n\t ";
905               for_each(instrnsAfter.begin(), instrnsAfter.end(),
906                        std::mem_fun(&MachineInstr::dump));
907             }       
908           } // if not already pushed
909         } // if LR has a volatile color
910       } // if LR has color
911     } // if there is a LR for Var
912   } // for each value in the LV set after instruction
913 }
914
915
916 //----------------------------------------------------------------------------
917 // We can use the following method to get a temporary register to be used
918 // BEFORE any given machine instruction. If there is a register available,
919 // this method will simply return that register and set MIBef = MIAft = NULL.
920 // Otherwise, it will return a register and MIAft and MIBef will contain
921 // two instructions used to free up this returned register.
922 // Returned register number is the UNIFIED register number
923 //----------------------------------------------------------------------------
924
925 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
926                                      const ValueSet *LVSetBef,
927                                      MachineInstr *MInst, 
928                                      std::vector<MachineInstr*>& MIBef,
929                                      std::vector<MachineInstr*>& MIAft) {
930   RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
931   
932   int RegU =  getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
933   
934   if (RegU == -1) {
935     // we couldn't find an unused register. Generate code to free up a reg by
936     // saving it on stack and restoring after the instruction
937     
938     int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
939     
940     RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
941     
942     // Check if we need a scratch register to copy this register to memory.
943     int scratchRegType = -1;
944     if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
945       {
946         int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
947                                              MInst, MIBef, MIAft);
948         assert(scratchReg != MRI.getInvalidRegNum());
949         
950         // We may as well hold the value in the scratch register instead
951         // of copying it to memory and back.  But we have to mark the
952         // register as used by this instruction, so it does not get used
953         // as a scratch reg. by another operand or anyone else.
954         ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
955         MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
956         MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
957       }
958     else
959       { // the register can be copied directly to/from memory so do it.
960         MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
961         MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
962       }
963   }
964   
965   return RegU;
966 }
967
968
969 //----------------------------------------------------------------------------
970 // This method is called to get a new unused register that can be used
971 // to accommodate a temporary value.  This method may be called several times
972 // for a single machine instruction.  Each time it is called, it finds a
973 // register which is not live at that instruction and also which is not used
974 // by other spilled operands of the same instruction.  Return register number
975 // is relative to the register class, NOT the unified number.
976 //----------------------------------------------------------------------------
977
978 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, 
979                                      const int RegType,
980                                      const MachineInstr *MInst,
981                                      const ValueSet* LVSetBef) {
982   RC->clearColorsUsed();     // Reset array
983
984   if (LVSetBef == NULL) {
985       LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
986       assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
987   }
988
989   ValueSet::const_iterator LIt = LVSetBef->begin();
990
991   // for each live var in live variable set after machine inst
992   for ( ; LIt != LVSetBef->end(); ++LIt) {
993     // Get the live range corresponding to live var, and its RegClass
994     LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );    
995
996     // LR can be null if it is a const since a const 
997     // doesn't have a dominating def - see Assumptions above
998     if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
999       RC->markColorsUsed(LRofLV->getColor(),
1000                          MRI.getRegTypeForLR(LRofLV), RegType);
1001   }
1002
1003   // It is possible that one operand of this MInst was already spilled
1004   // and it received some register temporarily. If that's the case,
1005   // it is recorded in machine operand. We must skip such registers.
1006   setRelRegsUsedByThisInst(RC, RegType, MInst);
1007
1008   int unusedReg = RC->getUnusedColor(RegType);   // find first unused color
1009   if (unusedReg >= 0)
1010     return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1011
1012   return -1;
1013 }
1014
1015
1016 //----------------------------------------------------------------------------
1017 // Get any other register in a register class, other than what is used
1018 // by operands of a machine instruction. Returns the unified reg number.
1019 //----------------------------------------------------------------------------
1020
1021 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC, 
1022                                             const int RegType,
1023                                             const MachineInstr *MInst) {
1024   RC->clearColorsUsed();
1025
1026   setRelRegsUsedByThisInst(RC, RegType, MInst);
1027
1028   // find the first unused color
1029   int unusedReg = RC->getUnusedColor(RegType);
1030   assert(unusedReg >= 0 &&
1031          "FATAL: No free register could be found in reg class!!");
1032
1033   return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1034 }
1035
1036
1037 //----------------------------------------------------------------------------
1038 // This method modifies the IsColorUsedArr of the register class passed to it.
1039 // It sets the bits corresponding to the registers used by this machine
1040 // instructions. Both explicit and implicit operands are set.
1041 //----------------------------------------------------------------------------
1042
1043 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1044                              const TargetRegInfo &TRI) {
1045   unsigned classId = 0;
1046   int classRegNum = TRI.getClassRegNum(RegNo, classId);
1047   if (RC->getID() == classId)
1048     RC->markColorsUsed(classRegNum, RegType, RegType);
1049 }
1050
1051 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1052                                            const MachineInstr *MI)
1053 {
1054   assert(OperandsColoredMap[MI] == true &&
1055          "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1056          "are marked for an instruction.");
1057
1058   // Add the registers already marked as used by the instruction.
1059   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1060     if (MI->getOperand(i).hasAllocatedReg())
1061       markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1062
1063   for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1064     if (MI->getImplicitOp(i).hasAllocatedReg())
1065       markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1066                        RegType,MRI);
1067
1068   // Add all of the scratch registers that are used to save values across the
1069   // instruction (e.g., for saving state register values).
1070   std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1071     IR = ScratchRegsUsed.equal_range(MI);
1072   for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1073     markRegisterUsed(I->second, RC, RegType, MRI);
1074
1075   // If there are implicit references, mark their allocated regs as well
1076   for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1077     if (const LiveRange*
1078         LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))    
1079       if (LRofImpRef->hasColor())
1080         // this implicit reference is in a LR that received a color
1081         RC->markColorsUsed(LRofImpRef->getColor(),
1082                            MRI.getRegTypeForLR(LRofImpRef), RegType);
1083 }
1084
1085
1086 //----------------------------------------------------------------------------
1087 // If there are delay slots for an instruction, the instructions
1088 // added after it must really go after the delayed instruction(s).
1089 // So, we move the InstrAfter of that instruction to the 
1090 // corresponding delayed instruction using the following method.
1091 //----------------------------------------------------------------------------
1092
1093 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1094                                     const MachineInstr *DelayedMI)
1095 {
1096   // "added after" instructions of the original instr
1097   std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1098
1099   if (DEBUG_RA && OrigAft.size() > 0) {
1100     std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1101     std::cerr << "         to last delay slot instrn: " << *DelayedMI;
1102   }
1103
1104   // "added after" instructions of the delayed instr
1105   std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1106
1107   // go thru all the "added after instructions" of the original instruction
1108   // and append them to the "added after instructions" of the delayed
1109   // instructions
1110   DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1111
1112   // empty the "added after instructions" of the original instruction
1113   OrigAft.clear();
1114 }
1115
1116
1117 void PhyRegAlloc::colorIncomingArgs()
1118 {
1119   MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
1120                       AddedInstrAtEntry.InstrnsAfter);
1121 }
1122
1123
1124 //----------------------------------------------------------------------------
1125 // This method determines whether the suggested color of each live range
1126 // is really usable, and then calls its setSuggestedColorUsable() method to
1127 // record the answer. A suggested color is NOT usable when the suggested color
1128 // is volatile AND when there are call interferences.
1129 //----------------------------------------------------------------------------
1130
1131 void PhyRegAlloc::markUnusableSugColors()
1132 {
1133   LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();   
1134   LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();   
1135
1136   for (; HMI != HMIEnd ; ++HMI ) {
1137     if (HMI->first) { 
1138       LiveRange *L = HMI->second;      // get the LiveRange
1139       if (L && L->hasSuggestedColor ())
1140         L->setSuggestedColorUsable
1141           (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1142              && L->isCallInterference ()));
1143     }
1144   } // for all LR's in hash map
1145 }
1146
1147
1148 //----------------------------------------------------------------------------
1149 // The following method will set the stack offsets of the live ranges that
1150 // are decided to be spilled. This must be called just after coloring the
1151 // LRs using the graph coloring algo. For each live range that is spilled,
1152 // this method allocate a new spill position on the stack.
1153 //----------------------------------------------------------------------------
1154
1155 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1156   if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1157
1158   LiveRangeMapType::const_iterator HMI    = LRI->getLiveRangeMap()->begin();   
1159   LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();   
1160
1161   for ( ; HMI != HMIEnd ; ++HMI) {
1162     if (HMI->first && HMI->second) {
1163       LiveRange *L = HMI->second;       // get the LiveRange
1164       if (L->isMarkedForSpill()) {      // NOTE: allocating size of long Type **
1165         int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
1166         L->setSpillOffFromFP(stackOffset);
1167         if (DEBUG_RA)
1168           std::cerr << "  LR# " << L->getUserIGNode()->getIndex()
1169                << ": stack-offset = " << stackOffset << "\n";
1170       }
1171     }
1172   } // for all LR's in hash map
1173 }
1174
1175
1176 //----------------------------------------------------------------------------
1177 // The entry point to Register Allocation
1178 //----------------------------------------------------------------------------
1179
1180 bool PhyRegAlloc::runOnFunction (Function &F) { 
1181   if (DEBUG_RA) 
1182     std::cerr << "\n********* Function "<< F.getName () << " ***********\n"; 
1183  
1184   Fn = &F; 
1185   MF = &MachineFunction::get (Fn); 
1186   LVI = &getAnalysis<FunctionLiveVarInfo> (); 
1187   LRI = new LiveRangeInfo (Fn, TM, RegClassList); 
1188   LoopDepthCalc = &getAnalysis<LoopInfo> (); 
1189  
1190   // Create each RegClass for the target machine and add it to the 
1191   // RegClassList.  This must be done before calling constructLiveRanges().
1192   for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)   
1193     RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (), 
1194                                           MRI.getMachineRegClass (rc))); 
1195      
1196   LRI->constructLiveRanges();            // create LR info
1197   if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1198     LRI->printLiveRanges();
1199   
1200   createIGNodeListsAndIGs();            // create IGNode list and IGs
1201
1202   buildInterferenceGraphs();            // build IGs in all reg classes
1203   
1204   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1205     // print all LRs in all reg classes
1206     for ( unsigned rc=0; rc < NumOfRegClasses  ; rc++)  
1207       RegClassList[rc]->printIGNodeList(); 
1208     
1209     // print IGs in all register classes
1210     for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1211       RegClassList[rc]->printIG();       
1212   }
1213
1214   LRI->coalesceLRs();                    // coalesce all live ranges
1215
1216   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1217     // print all LRs in all reg classes
1218     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1219       RegClassList[rc]->printIGNodeList();
1220     
1221     // print IGs in all register classes
1222     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1223       RegClassList[rc]->printIG();
1224   }
1225
1226   // mark un-usable suggested color before graph coloring algorithm.
1227   // When this is done, the graph coloring algo will not reserve
1228   // suggested color unnecessarily - they can be used by another LR
1229   markUnusableSugColors(); 
1230
1231   // color all register classes using the graph coloring algo
1232   for (unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1233     RegClassList[rc]->colorAllRegs();    
1234
1235   // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1236   // a position for such spilled LRs
1237   allocateStackSpace4SpilledLRs();
1238
1239   // Reset the temp. area on the stack before use by the first instruction.
1240   // This will also happen after updating each instruction.
1241   MF->getInfo()->popAllTempValues();
1242
1243   // color incoming args - if the correct color was not received
1244   // insert code to copy to the correct register
1245   colorIncomingArgs();
1246
1247   // Now update the machine code with register names and add any 
1248   // additional code inserted by the register allocator to the instruction
1249   // stream
1250   updateMachineCode(); 
1251
1252   if (DEBUG_RA) {
1253     std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
1254     MF->dump();
1255   }
1256  
1257   // Tear down temporary data structures 
1258   for (unsigned rc = 0; rc < NumOfRegClasses; ++rc) 
1259     delete RegClassList[rc]; 
1260   RegClassList.clear (); 
1261   AddedInstrMap.clear (); 
1262   OperandsColoredMap.clear (); 
1263   ScratchRegsUsed.clear (); 
1264   AddedInstrAtEntry.clear (); 
1265   delete LRI;
1266
1267   if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n"; 
1268   return false;     // Function was not modified
1269