96ff5ad0f529734fcea7b12f01e542f798ea8a76
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9RegInfo.cpp
1 //===-- SparcRegInfo.cpp - Sparc Target Register Information --------------===//
2 //
3 // This file contains implementation of Sparc specific helper methods
4 // used for register allocation.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "SparcInternals.h"
9 #include "SparcRegClassInfo.h"
10 #include "llvm/Target/Sparc.h"
11 #include "llvm/CodeGen/MachineCodeForMethod.h"
12 #include "llvm/CodeGen/PhyRegAlloc.h"
13 #include "llvm/CodeGen/InstrSelection.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/CodeGen/MachineInstrAnnot.h"
16 #include "llvm/CodeGen/RegAllocCommon.h"
17 #include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Function.h"
21 #include "llvm/DerivedTypes.h"
22 #include <iostream>
23 #include <values.h>
24 using std::cerr;
25 using std::vector;
26
27 UltraSparcRegInfo::UltraSparcRegInfo(const UltraSparc &tgt)
28   : MachineRegInfo(tgt), UltraSparcInfo(&tgt), NumOfIntArgRegs(6), 
29     NumOfFloatArgRegs(32), InvalidRegNum(1000) {
30    
31   MachineRegClassArr.push_back(new SparcIntRegClass(IntRegClassID));
32   MachineRegClassArr.push_back(new SparcFloatRegClass(FloatRegClassID));
33   MachineRegClassArr.push_back(new SparcIntCCRegClass(IntCCRegClassID));
34   MachineRegClassArr.push_back(new SparcFloatCCRegClass(FloatCCRegClassID));
35
36   assert(SparcFloatRegOrder::StartOfNonVolatileRegs == 32 && 
37          "32 Float regs are used for float arg passing");
38 }
39
40
41 // getZeroRegNum - returns the register that contains always zero.
42 // this is the unified register number
43 //
44 int UltraSparcRegInfo::getZeroRegNum() const {
45   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
46                                 SparcIntRegOrder::g0);
47 }
48
49 // getCallAddressReg - returns the reg used for pushing the address when a
50 // method is called. This can be used for other purposes between calls
51 //
52 unsigned UltraSparcRegInfo::getCallAddressReg() const {
53   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
54                                 SparcIntRegOrder::o7);
55 }
56
57 // Returns the register containing the return address.
58 // It should be made sure that this  register contains the return 
59 // value when a return instruction is reached.
60 //
61 unsigned UltraSparcRegInfo::getReturnAddressReg() const {
62   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
63                                 SparcIntRegOrder::i7);
64 }
65
66 // given the unified register number, this gives the name
67 // for generating assembly code or debugging.
68 //
69 const std::string UltraSparcRegInfo::getUnifiedRegName(int reg) const {
70   if( reg < 32 ) 
71     return SparcIntRegOrder::getRegName(reg);
72   else if ( reg < (64 + 32) )
73     return SparcFloatRegOrder::getRegName( reg  - 32);                  
74   else if( reg < (64+32+4) )
75     return SparcFloatCCRegOrder::getRegName( reg -32 - 64);
76   else if( reg < (64+32+4+2) )    // two names: %xcc and %ccr
77     return SparcIntCCRegOrder::getRegName( reg -32 - 64 - 4);             
78   else if (reg== InvalidRegNum)       //****** TODO: Remove */
79     return "<*NoReg*>";
80   else 
81     assert(0 && "Invalid register number");
82   return "";
83 }
84
85 // Get unified reg number for frame pointer
86 unsigned UltraSparcRegInfo::getFramePointer() const {
87   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
88                                 SparcIntRegOrder::i6);
89 }
90
91 // Get unified reg number for stack pointer
92 unsigned UltraSparcRegInfo::getStackPointer() const {
93   return this->getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
94                                 SparcIntRegOrder::o6);
95 }
96
97
98 //---------------------------------------------------------------------------
99 // Finds whether a call is an indirect call
100 //---------------------------------------------------------------------------
101
102 inline bool
103 isVarArgsFunction(const Type *funcType) {
104   return cast<FunctionType>(cast<PointerType>(funcType)
105                             ->getElementType())->isVarArg();
106 }
107
108 inline bool
109 isVarArgsCall(const MachineInstr *CallMI) {
110   Value* callee = CallMI->getOperand(0).getVRegValue();
111   // const Type* funcType = isa<Function>(callee)? callee->getType()
112   //   : cast<PointerType>(callee->getType())->getElementType();
113   const Type* funcType = callee->getType();
114   return isVarArgsFunction(funcType);
115 }
116
117
118 // Get the register number for the specified integer arg#,
119 // assuming there are argNum total args, intArgNum int args,
120 // and fpArgNum FP args preceding (and not including) this one.
121 // Use INT regs for FP args if this is a varargs call.
122 // 
123 // Return value:
124 //      InvalidRegNum,  if there is no int register available for the arg. 
125 //      regNum,         otherwise (this is NOT the unified reg. num).
126 // 
127 inline int
128 UltraSparcRegInfo::regNumForIntArg(bool inCallee, bool isVarArgsCall,
129                                    unsigned argNo,
130                                    unsigned intArgNo, unsigned fpArgNo,
131                                    unsigned& regClassId) const
132 {
133   regClassId = IntRegClassID;
134   if (argNo >= NumOfIntArgRegs)
135     return InvalidRegNum;
136   else
137     return argNo + (inCallee? SparcIntRegOrder::i0 : SparcIntRegOrder::o0);
138 }
139
140 // Get the register number for the specified FP arg#,
141 // assuming there are argNum total args, intArgNum int args,
142 // and fpArgNum FP args preceding (and not including) this one.
143 // Use INT regs for FP args if this is a varargs call.
144 // 
145 // Return value:
146 //      InvalidRegNum,  if there is no int register available for the arg. 
147 //      regNum,         otherwise (this is NOT the unified reg. num).
148 // 
149 inline int
150 UltraSparcRegInfo::regNumForFPArg(unsigned regType,
151                                   bool inCallee, bool isVarArgsCall,
152                                   unsigned argNo,
153                                   unsigned intArgNo, unsigned fpArgNo,
154                                   unsigned& regClassId) const
155 {
156   if (isVarArgsCall)
157     return regNumForIntArg(inCallee, isVarArgsCall, argNo, intArgNo, fpArgNo,
158                            regClassId);
159   else
160     {
161       regClassId = FloatRegClassID;
162       if (regType == FPSingleRegType)
163         return (argNo*2+1 >= NumOfFloatArgRegs)?
164           InvalidRegNum : SparcFloatRegOrder::f0 + (argNo * 2 + 1);
165       else if (regType == FPDoubleRegType)
166         return (argNo*2 >= NumOfFloatArgRegs)?
167           InvalidRegNum : SparcFloatRegOrder::f0 + (argNo * 2);
168       else
169         assert(0 && "Illegal FP register type");
170     }
171 }
172
173
174 //---------------------------------------------------------------------------
175 // Finds the return address of a call sparc specific call instruction
176 //---------------------------------------------------------------------------
177
178 // The following 4  methods are used to find the RegType (see enum above)
179 // of a LiveRange, a Value, and for a given register unified reg number.
180 //
181 int UltraSparcRegInfo::getRegType(unsigned regClassID,
182                                   const Type* type) const {
183   switch (regClassID) {
184   case IntRegClassID: return IntRegType; 
185   case FloatRegClassID: {
186     if (type == Type::FloatTy) 
187       return FPSingleRegType;
188     else if (type == Type::DoubleTy)
189       return FPDoubleRegType;
190     assert(0 && "Unknown type in FloatRegClass");
191   }
192   case IntCCRegClassID:   return IntCCRegType; 
193   case FloatCCRegClassID: return FloatCCRegType; 
194   default: assert( 0 && "Unknown reg class ID"); return 0;
195   }
196 }
197
198 int UltraSparcRegInfo::getRegType(const LiveRange *LR) const {
199   return getRegType(LR->getRegClass()->getID(), LR->getType());
200 }
201
202 int UltraSparcRegInfo::getRegType(const Value *Val) const {
203   return getRegType(getRegClassIDOfValue(Val), Val->getType());
204 }
205
206 int UltraSparcRegInfo::getRegType(int reg) const {
207   if (reg < 32) 
208     return IntRegType;
209   else if (reg < (32 + 32))
210     return FPSingleRegType;
211   else if (reg < (64 + 32))
212     return FPDoubleRegType;
213   else if (reg < (64+32+4))
214     return FloatCCRegType;
215   else if (reg < (64+32+4+2))  
216     return IntCCRegType;             
217   else 
218     assert(0 && "Invalid register number in getRegType");
219   return 0;
220 }
221
222
223 //---------------------------------------------------------------------------
224 // Suggests a register for the ret address in the RET machine instruction.
225 // We always suggest %i7 by convention.
226 //---------------------------------------------------------------------------
227 void UltraSparcRegInfo::suggestReg4RetAddr(const MachineInstr *RetMI, 
228                                            LiveRangeInfo& LRI) const {
229
230   assert( (RetMI->getNumOperands() >= 2)
231           && "JMPL/RETURN must have 3 and 2 operands respectively");
232   
233   MachineOperand & MO  = ( MachineOperand &) RetMI->getOperand(0);
234
235   // return address is always mapped to i7
236   //
237   MO.setRegForValue( getUnifiedRegNum( IntRegClassID, SparcIntRegOrder::i7) );
238   
239   // Possible Optimization: 
240   // Instead of setting the color, we can suggest one. In that case,
241   // we have to test later whether it received the suggested color.
242   // In that case, a LR has to be created at the start of method.
243   // It has to be done as follows (remove the setRegVal above):
244
245   // const Value *RetAddrVal = MO.getVRegValue();
246   // assert( RetAddrVal && "LR for ret address must be created at start");
247   // LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);  
248   // RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID, 
249   // SparcIntRegOrdr::i7) );
250 }
251
252
253 //---------------------------------------------------------------------------
254 // Suggests a register for the ret address in the JMPL/CALL machine instr.
255 // Sparc ABI dictates that %o7 be used for this purpose.
256 //---------------------------------------------------------------------------
257 void UltraSparcRegInfo::suggestReg4CallAddr(const MachineInstr * CallMI,
258                                             LiveRangeInfo& LRI,
259                                          std::vector<RegClass *> RCList) const {
260   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
261   const Value *RetAddrVal = argDesc->getReturnAddrReg();
262   assert(RetAddrVal && "Return address value is required");
263   
264   // create a new LR for the return address and color it
265   LiveRange * RetAddrLR = new LiveRange();  
266   RetAddrLR->insert( RetAddrVal );
267   unsigned RegClassID = getRegClassIDOfValue( RetAddrVal );
268   RetAddrLR->setRegClass( RCList[RegClassID] );
269   RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID,SparcIntRegOrder::o7));
270   LRI.addLRToMap( RetAddrVal, RetAddrLR);
271   
272 }
273
274
275
276
277 //---------------------------------------------------------------------------
278 //  This method will suggest colors to incoming args to a method. 
279 //  According to the Sparc ABI, the first 6 incoming args are in 
280 //  %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
281 //  If the arg is passed on stack due to the lack of regs, NOTHING will be
282 //  done - it will be colored (or spilled) as a normal live range.
283 //---------------------------------------------------------------------------
284 void UltraSparcRegInfo::suggestRegs4MethodArgs(const Function *Meth, 
285                                                LiveRangeInfo& LRI) const 
286 {
287   // check if this is a varArgs function. needed for choosing regs.
288   bool isVarArgs = isVarArgsFunction(Meth->getType());
289   
290   // for each argument.  count INT and FP arguments separately.
291   unsigned argNo=0, intArgNo=0, fpArgNo=0;
292   for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
293       I != E; ++I, ++argNo) {
294     // get the LR of arg
295     LiveRange *LR = LRI.getLiveRangeForValue(I);
296     assert(LR && "No live range found for method arg");
297     
298     unsigned regType = getRegType(LR);
299     unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg (unused)
300     
301     int regNum = (regType == IntRegType)
302       ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
303                         argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
304       : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
305                        argNo, intArgNo, fpArgNo++, regClassIDOfArgReg); 
306     
307     if(regNum != InvalidRegNum)
308       LR->setSuggestedColor(regNum);
309   }
310 }
311
312
313 //---------------------------------------------------------------------------
314 // This method is called after graph coloring to move incoming args to
315 // the correct hardware registers if they did not receive the correct
316 // (suggested) color through graph coloring.
317 //---------------------------------------------------------------------------
318 void UltraSparcRegInfo::colorMethodArgs(const Function *Meth, 
319                                         LiveRangeInfo &LRI,
320                                         AddedInstrns *FirstAI) const {
321
322   // check if this is a varArgs function. needed for choosing regs.
323   bool isVarArgs = isVarArgsFunction(Meth->getType());
324   MachineInstr *AdMI;
325
326   // for each argument
327   // for each argument.  count INT and FP arguments separately.
328   unsigned argNo=0, intArgNo=0, fpArgNo=0;
329   for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
330       I != E; ++I, ++argNo) {
331     // get the LR of arg
332     LiveRange *LR = LRI.getLiveRangeForValue(I);
333     assert( LR && "No live range found for method arg");
334
335     unsigned regType = getRegType( LR );
336     unsigned RegClassID = (LR->getRegClass())->getID();
337     
338     // Find whether this argument is coming in a register (if not, on stack)
339     // Also find the correct register the argument must use (UniArgReg)
340     //
341     bool isArgInReg = false;
342     unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
343     unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg
344     
345     int regNum = (regType == IntRegType)
346       ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
347                         argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
348       : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
349                        argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
350     
351     if(regNum != InvalidRegNum) {
352       isArgInReg = true;
353       UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
354     }
355     
356     if( LR->hasColor() ) {              // if this arg received a register
357
358       unsigned UniLRReg = getUnifiedRegNum(  RegClassID, LR->getColor() );
359
360       // if LR received the correct color, nothing to do
361       //
362       if( UniLRReg == UniArgReg )
363         continue;
364
365       // We are here because the LR did not receive the suggested 
366       // but LR received another register.
367       // Now we have to copy the %i reg (or stack pos of arg) 
368       // to the register the LR was colored with.
369       
370       // if the arg is coming in UniArgReg register, it MUST go into
371       // the UniLRReg register
372       //
373       if( isArgInReg ) {
374         if( regClassIDOfArgReg != RegClassID ) {
375           assert(0 && "This could should work but it is not tested yet");
376           
377           // It is a variable argument call: the float reg must go in a %o reg.
378           // We have to move an int reg to a float reg via memory.
379           // 
380           assert(isVarArgs &&
381                  RegClassID == FloatRegClassID && 
382                  regClassIDOfArgReg == IntRegClassID &&
383                  "This should only be an Int register for an FP argument");
384           
385           int TmpOff = MachineCodeForMethod::get(Meth).pushTempValue(target,  
386                                                 getSpilledRegSize(regType));
387           cpReg2MemMI(UniArgReg, getFramePointer(), TmpOff, IntRegType,
388                       FirstAI->InstrnsBefore);
389           
390           cpMem2RegMI(getFramePointer(), TmpOff, UniLRReg, regType,
391                       FirstAI->InstrnsBefore);
392         }
393         else {  
394           cpReg2RegMI(UniArgReg, UniLRReg, regType, FirstAI->InstrnsBefore);
395         }
396       }
397       else {
398
399         // Now the arg is coming on stack. Since the LR recieved a register,
400         // we just have to load the arg on stack into that register
401         //
402         const MachineFrameInfo& frameInfo = target.getFrameInfo();
403         int offsetFromFP =
404           frameInfo.getIncomingArgOffset(MachineCodeForMethod::get(Meth),
405                                          argNo);
406         
407         cpMem2RegMI(getFramePointer(), offsetFromFP, UniLRReg, regType,
408                     FirstAI->InstrnsBefore);
409       }
410       
411     } // if LR received a color
412
413     else {                             
414
415       // Now, the LR did not receive a color. But it has a stack offset for
416       // spilling.
417       // So, if the arg is coming in UniArgReg register,  we can just move
418       // that on to the stack pos of LR
419
420       if( isArgInReg ) {
421         
422         if( regClassIDOfArgReg != RegClassID ) {
423           assert(0 &&
424                  "FP arguments to a varargs function should be explicitly "
425                  "copied to/from int registers by instruction selection!");
426           
427           // It must be a float arg for a variable argument call, which
428           // must come in a %o reg.  Move the int reg to the stack.
429           // 
430           assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
431                  "This should only be an Int register for an FP argument");
432           
433           cpReg2MemMI(UniArgReg, getFramePointer(), LR->getSpillOffFromFP(),
434                       IntRegType, FirstAI->InstrnsBefore);
435         }
436         else {
437            cpReg2MemMI(UniArgReg, getFramePointer(), LR->getSpillOffFromFP(),
438                        regType, FirstAI->InstrnsBefore);
439         }
440       }
441
442       else {
443
444         // Now the arg is coming on stack. Since the LR did NOT 
445         // recieved a register as well, it is allocated a stack position. We
446         // can simply change the stack position of the LR. We can do this,
447         // since this method is called before any other method that makes
448         // uses of the stack pos of the LR (e.g., updateMachineInstr)
449
450         const MachineFrameInfo& frameInfo = target.getFrameInfo();
451         int offsetFromFP =
452           frameInfo.getIncomingArgOffset(MachineCodeForMethod::get(Meth),
453                                          argNo);
454         
455         LR->modifySpillOffFromFP( offsetFromFP );
456       }
457
458     }
459
460   }  // for each incoming argument
461
462 }
463
464
465
466 //---------------------------------------------------------------------------
467 // This method is called before graph coloring to suggest colors to the
468 // outgoing call args and the return value of the call.
469 //---------------------------------------------------------------------------
470 void UltraSparcRegInfo::suggestRegs4CallArgs(const MachineInstr *CallMI, 
471                                              LiveRangeInfo& LRI,
472                                          std::vector<RegClass *> RCList) const {
473   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
474
475   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
476   
477   suggestReg4CallAddr(CallMI, LRI, RCList);
478
479   // First color the return value of the call instruction. The return value
480   // will be in %o0 if the value is an integer type, or in %f0 if the 
481   // value is a float type.
482
483   // the return value cannot have a LR in machine instruction since it is
484   // only defined by the call instruction
485
486   // if type is not void,  create a new live range and set its 
487   // register class and add to LRI
488
489   const Value *RetVal = argDesc->getReturnValue();
490
491   if (RetVal) {
492     assert ((!LRI.getLiveRangeForValue(RetVal)) && 
493             "LR for ret Value of call already definded!");
494
495     // create a new LR for the return value
496     LiveRange *RetValLR = new LiveRange();  
497     RetValLR->insert(RetVal);
498     unsigned RegClassID = getRegClassIDOfValue(RetVal);
499     RetValLR->setRegClass(RCList[RegClassID]);
500     LRI.addLRToMap(RetVal, RetValLR);
501     
502     // now suggest a register depending on the register class of ret arg
503
504     if( RegClassID == IntRegClassID ) 
505       RetValLR->setSuggestedColor(SparcIntRegOrder::o0);
506     else if (RegClassID == FloatRegClassID ) 
507       RetValLR->setSuggestedColor(SparcFloatRegOrder::f0 );
508     else assert( 0 && "Unknown reg class for return value of call\n");
509   }
510
511   
512   // Now suggest colors for arguments (operands) of the call instruction.
513   // Colors are suggested only if the arg number is smaller than the
514   // the number of registers allocated for argument passing.
515   // Now, go thru call args - implicit operands of the call MI
516
517   unsigned NumOfCallArgs = argDesc->getNumArgs();
518   
519   for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
520        i < NumOfCallArgs; ++i, ++argNo) {    
521
522     const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
523     
524     // get the LR of call operand (parameter)
525     LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
526     
527     // not possible to have a null LR since all args (even consts)  
528     // must be defined before
529     if (!LR) {          
530       cerr << " ERROR: In call instr, no LR for arg: " << RAV(CallArg) << "\n";
531       assert(0 && "NO LR for call arg");  
532     }
533     
534     unsigned regType = getRegType( LR );
535     unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg (unused)
536     
537     // Choose a register for this arg depending on whether it is
538     // an INT or FP value.  Here we ignore whether or not it is a
539     // varargs calls, because FP arguments will be explicitly copied
540     // to an integer Value and handled under (argCopy != NULL) below.
541     int regNum = (regType == IntRegType)
542       ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
543                         argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
544       : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
545                        argNo, intArgNo, fpArgNo++, regClassIDOfArgReg); 
546     
547     // If a register could be allocated, use it.
548     // If not, do NOTHING as this will be colored as a normal value.
549     if(regNum != InvalidRegNum)
550       LR->setSuggestedColor(regNum);
551     
552     // Repeat for the second copy of the argument, which would be
553     // an FP argument being passed to a function with no prototype
554     const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
555     if (argCopy != NULL)
556       {
557         assert(regType != IntRegType && argCopy->getType()->isIntegral()
558                && "Must be passing copy of FP argument in int register");
559         int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
560                                          argNo, intArgNo, fpArgNo-1,
561                                          regClassIDOfArgReg);
562         assert(copyRegNum != InvalidRegNum); 
563         LiveRange *const copyLR = LRI.getLiveRangeForValue(argCopy); 
564         copyLR->setSuggestedColor(copyRegNum);
565       }
566     
567   } // for all call arguments
568
569 }
570
571
572 //---------------------------------------------------------------------------
573 // Helper method for UltraSparcRegInfo::colorCallArgs().
574 //---------------------------------------------------------------------------
575     
576 void
577 UltraSparcRegInfo::InitializeOutgoingArg(const MachineInstr* CallMI,
578                              AddedInstrns *CallAI,
579                              PhyRegAlloc &PRA, LiveRange* LR,
580                              unsigned regType, unsigned RegClassID,
581                              int UniArgRegOrNone, unsigned int argNo,
582                              std::vector<MachineInstr *>& AddedInstrnsBefore)
583   const
584 {
585   MachineInstr *AdMI;
586   bool isArgInReg = false;
587   unsigned UniArgReg = MAXINT;          // unused unless initialized below
588   if (UniArgRegOrNone != InvalidRegNum)
589     {
590       isArgInReg = true;
591       UniArgReg = (unsigned) UniArgRegOrNone;
592     }
593   
594   if (LR->hasColor()) {
595     unsigned UniLRReg = getUnifiedRegNum(RegClassID, LR->getColor());
596     
597     // if LR received the correct color, nothing to do
598     if( isArgInReg && UniArgReg == UniLRReg )
599       return;
600     
601     // The LR is allocated to a register UniLRReg and must be copied
602     // to UniArgReg or to the stack slot.
603     // 
604     if( isArgInReg ) {
605       // Copy UniLRReg to UniArgReg
606       cpReg2RegMI(UniLRReg, UniArgReg, regType, AddedInstrnsBefore);
607     }
608     else {
609       // Copy UniLRReg to the stack to pass the arg on stack.
610       const MachineFrameInfo& frameInfo = target.getFrameInfo();
611       int argOffset = frameInfo.getOutgoingArgOffset(PRA.mcInfo, argNo);
612       cpReg2MemMI(UniLRReg, getStackPointer(), argOffset, regType,
613                   CallAI->InstrnsBefore);
614     }
615
616   } else {                          // LR is not colored (i.e., spilled)      
617     
618     if( isArgInReg ) {
619       // Insert a load instruction to load the LR to UniArgReg
620       cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(),
621                   UniArgReg, regType, AddedInstrnsBefore);
622                                         // Now add the instruction
623     }
624       
625     else {
626       // Now, we have to pass the arg on stack. Since LR  also did NOT
627       // receive a register we have to move an argument in memory to 
628       // outgoing parameter on stack.
629       // Use TReg to load and store the value.
630       // Use TmpOff to save TReg, since that may have a live value.
631       // 
632       int TReg = PRA.getUniRegNotUsedByThisInst( LR->getRegClass(), CallMI );
633       int TmpOff = PRA.mcInfo.pushTempValue(target,  
634                                             getSpilledRegSize(getRegType(LR)));
635       const MachineFrameInfo& frameInfo = target.getFrameInfo();
636       int argOffset = frameInfo.getOutgoingArgOffset(PRA.mcInfo, argNo);
637       
638       MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
639         
640       // Sequence:
641       // (1) Save TReg on stack    
642       // (2) Load LR value into TReg from stack pos of LR
643       // (3) Store Treg on outgoing Arg pos on stack
644       // (4) Load the old value of TReg from stack to TReg (restore it)
645       // 
646       // OPTIMIZE THIS:
647       // When reverse pointers in MahineInstr are introduced: 
648       // Call PRA.getUnusedRegAtMI(....) to get an unused reg. Step 1 is
649       // needed only if this fails. Currently, we cannot call the
650       // above method since we cannot find LVSetBefore without the BB 
651       // 
652       // NOTE: We directly add to CallAI->InstrnsBefore instead of adding to
653       // AddedInstrnsBefore since these instructions must not be reordered.
654       cpReg2MemMI(TReg, getFramePointer(), TmpOff, regType,
655                   CallAI->InstrnsBefore);
656       cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(), TReg, regType,
657                   CallAI->InstrnsBefore); 
658       cpReg2MemMI(TReg, getStackPointer(), argOffset, regType,
659                   CallAI->InstrnsBefore);
660       cpMem2RegMI(getFramePointer(), TmpOff, TReg, regType,
661                   CallAI->InstrnsBefore); 
662     }
663   }
664 }
665
666 //---------------------------------------------------------------------------
667 // After graph coloring, we have call this method to see whehter the return
668 // value and the call args received the correct colors. If not, we have
669 // to instert copy instructions.
670 //---------------------------------------------------------------------------
671
672 void UltraSparcRegInfo::colorCallArgs(const MachineInstr *CallMI,
673                                       LiveRangeInfo &LRI,
674                                       AddedInstrns *CallAI,
675                                       PhyRegAlloc &PRA,
676                                       const BasicBlock *BB) const {
677
678   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
679
680   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
681   
682   // First color the return value of the call.
683   // If there is a LR for the return value, it means this
684   // method returns a value
685   
686   MachineInstr *AdMI;
687
688   const Value *RetVal = argDesc->getReturnValue();
689
690   if (RetVal) {
691     LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
692
693     if (!RetValLR) {
694       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
695       assert(RetValLR && "ERR:No LR for non-void return value");
696     }
697
698     unsigned RegClassID = (RetValLR->getRegClass())->getID();    
699     bool recvCorrectColor = false;
700
701     unsigned CorrectCol;                // correct color for ret value
702     if(RegClassID == IntRegClassID)
703       CorrectCol = SparcIntRegOrder::o0;
704     else if(RegClassID == FloatRegClassID)
705       CorrectCol = SparcFloatRegOrder::f0;
706     else {
707       assert( 0 && "Unknown RegClass");
708       return;
709     }
710
711     // if the LR received the correct color, NOTHING to do
712
713     if(  RetValLR->hasColor() )
714       if( RetValLR->getColor() == CorrectCol )
715         recvCorrectColor = true;
716
717
718     // if we didn't receive the correct color for some reason, 
719     // put copy instruction
720     
721     if( !recvCorrectColor ) {
722
723       unsigned regType = getRegType( RetValLR );
724
725       // the  reg that LR must be colored with 
726       unsigned UniRetReg = getUnifiedRegNum( RegClassID, CorrectCol);   
727       
728       if( RetValLR->hasColor() ) {
729         
730         unsigned 
731           UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
732         
733         // the return value is coming in UniRetReg but has to go into
734         // the UniRetLRReg
735
736         cpReg2RegMI(UniRetReg, UniRetLRReg, regType, CallAI->InstrnsAfter);
737
738       } // if LR has color
739       else {
740
741         // if the LR did NOT receive a color, we have to move the return
742         // value coming in UniRetReg to the stack pos of spilled LR
743         
744         cpReg2MemMI(UniRetReg, getFramePointer(),RetValLR->getSpillOffFromFP(),
745                     regType, CallAI->InstrnsAfter);
746       }
747
748     } // the LR didn't receive the suggested color  
749     
750   } // if there a return value
751   
752
753   //-------------------------------------------
754   // Now color all args of the call instruction
755   //-------------------------------------------
756
757   std::vector<MachineInstr *> AddedInstrnsBefore;
758   
759   unsigned NumOfCallArgs = argDesc->getNumArgs();
760   
761   for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
762       i < NumOfCallArgs; ++i, ++argNo) {    
763
764     const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
765     
766     // get the LR of call operand (parameter)
767     LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
768
769     unsigned RegClassID = getRegClassIDOfValue( CallArg);
770     unsigned regType = getRegType( RegClassID, CallArg->getType() );
771     
772     // Find whether this argument is coming in a register (if not, on stack)
773     // Also find the correct register the argument must use (UniArgReg)
774     //
775     bool isArgInReg = false;
776     unsigned UniArgReg = InvalidRegNum;   // reg that LR MUST be colored with
777     unsigned regClassIDOfArgReg = MAXINT; // reg class of chosen reg
778     
779     // Find the register that must be used for this arg, depending on
780     // whether it is an INT or FP value.  Here we ignore whether or not it
781     // is a varargs calls, because FP arguments will be explicitly copied
782     // to an integer Value and handled under (argCopy != NULL) below.
783     int regNum = (regType == IntRegType)
784       ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
785                         argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
786       : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
787                        argNo, intArgNo, fpArgNo++, regClassIDOfArgReg); 
788     
789     if(regNum != InvalidRegNum) {
790       isArgInReg = true;
791       UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
792       assert(regClassIDOfArgReg == RegClassID &&
793              "Moving values between reg classes must happen during selection");
794     }
795     
796     // not possible to have a null LR since all args (even consts)  
797     // must be defined before
798     if (!LR) {          
799       cerr << " ERROR: In call instr, no LR for arg:  " << RAV(CallArg) <<"\n";
800       assert(LR && "NO LR for call arg");  
801     }
802     
803     InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
804                           UniArgReg, argNo, AddedInstrnsBefore);
805     
806     // Repeat for the second copy of the argument, which would be
807     // an FP argument being passed to a function with no prototype.
808     const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
809     if (argCopy != NULL)
810       {
811         assert(regType != IntRegType && argCopy->getType()->isIntegral()
812                && "Must be passing copy of FP argument in int register");
813         
814         unsigned copyRegClassID = getRegClassIDOfValue(argCopy);
815         unsigned copyRegType = getRegType(copyRegClassID, argCopy->getType());
816         
817         int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
818                                          argNo, intArgNo, fpArgNo-1,
819                                          regClassIDOfArgReg);
820         assert(copyRegNum != InvalidRegNum); 
821         assert(regClassIDOfArgReg == copyRegClassID &&
822            "Moving values between reg classes must happen during selection");
823         
824         InitializeOutgoingArg(CallMI, CallAI, PRA,
825                               LRI.getLiveRangeForValue(argCopy), copyRegType,
826                               copyRegClassID, copyRegNum, argNo,
827                               AddedInstrnsBefore);
828       }
829   }  // for each parameter in call instruction
830
831   // If we added any instruction before the call instruction, verify
832   // that they are in the proper order and if not, reorder them
833   // 
834   if (!AddedInstrnsBefore.empty()) {
835
836     if (DEBUG_RA) {
837       cerr << "\nCalling reorder with instrns: \n";
838       for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
839         cerr  << *(AddedInstrnsBefore[i]);
840     }
841
842     std::vector<MachineInstr *> TmpVec;
843     OrderAddedInstrns(AddedInstrnsBefore, TmpVec, PRA);
844
845     if (DEBUG_RA) {
846       cerr << "\nAfter reordering instrns: \n";
847       for(unsigned i = 0; i < TmpVec.size(); i++)
848         cerr << *TmpVec[i];
849     }
850
851     // copy the results back from TmpVec to InstrnsBefore
852     for(unsigned i=0; i < TmpVec.size(); i++)
853       CallAI->InstrnsBefore.push_back( TmpVec[i] );
854   }
855   
856   // now insert caller saving code for this call instruction
857   //
858   insertCallerSavingCode(CallMI, BB, PRA);
859 }
860
861 //---------------------------------------------------------------------------
862 // This method is called for an LLVM return instruction to identify which
863 // values will be returned from this method and to suggest colors.
864 //---------------------------------------------------------------------------
865 void UltraSparcRegInfo::suggestReg4RetValue(const MachineInstr *RetMI, 
866                                             LiveRangeInfo &LRI) const {
867
868   assert( (UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode() ) );
869
870     suggestReg4RetAddr(RetMI, LRI);
871
872   // if there is an implicit ref, that has to be the ret value
873   if(  RetMI->getNumImplicitRefs() > 0 ) {
874
875     // The first implicit operand is the return value of a return instr
876     const Value *RetVal =  RetMI->getImplicitRef(0);
877
878     LiveRange *const LR = LRI.getLiveRangeForValue( RetVal ); 
879
880     if (!LR) {
881       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
882       assert(0 && "No LR for return value of non-void method");
883     }
884
885     unsigned RegClassID = (LR->getRegClass())->getID();
886       
887     if (RegClassID == IntRegClassID) 
888       LR->setSuggestedColor(SparcIntRegOrder::i0);
889     else if (RegClassID == FloatRegClassID) 
890       LR->setSuggestedColor(SparcFloatRegOrder::f0);
891   }
892 }
893
894
895
896 //---------------------------------------------------------------------------
897 // Colors the return value of a method to %i0 or %f0, if possible. If it is
898 // not possilbe to directly color the LR, insert a copy instruction to move
899 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we 
900 // have to put a load instruction.
901 //---------------------------------------------------------------------------
902 void UltraSparcRegInfo::colorRetValue(const MachineInstr *RetMI, 
903                                       LiveRangeInfo &LRI,
904                                       AddedInstrns *RetAI) const {
905
906   assert((UltraSparcInfo->getInstrInfo()).isReturn( RetMI->getOpCode()));
907
908   // if there is an implicit ref, that has to be the ret value
909   if(RetMI->getNumImplicitRefs() > 0) {
910
911     // The first implicit operand is the return value of a return instr
912     const Value *RetVal =  RetMI->getImplicitRef(0);
913
914     LiveRange *LR = LRI.getLiveRangeForValue(RetVal); 
915
916     if (!LR) {
917       cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
918       // assert( LR && "No LR for return value of non-void method");
919       return;
920     }
921
922     unsigned RegClassID =  getRegClassIDOfValue(RetVal);
923     unsigned regType = getRegType( RetVal );
924
925     unsigned CorrectCol;
926     if(RegClassID == IntRegClassID)
927       CorrectCol = SparcIntRegOrder::i0;
928     else if(RegClassID == FloatRegClassID)
929       CorrectCol = SparcFloatRegOrder::f0;
930     else {
931       assert (0 && "Unknown RegClass");
932       return;
933     }
934
935     // if the LR received the correct color, NOTHING to do
936
937     if (LR->hasColor() && LR->getColor() == CorrectCol)
938       return;
939
940     unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
941
942     if (LR->hasColor()) {
943
944       // We are here because the LR was allocted a regiter
945       // It may be the suggested register or not
946
947       // copy the LR of retun value to i0 or f0
948
949       unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
950
951       // the LR received  UniLRReg but must be colored with UniRetReg
952       // to pass as the return value
953       cpReg2RegMI(UniLRReg, UniRetReg, regType, RetAI->InstrnsBefore);
954     }
955     else {                              // if the LR is spilled
956       cpMem2RegMI(getFramePointer(), LR->getSpillOffFromFP(),
957                   UniRetReg, regType, RetAI->InstrnsBefore);
958       cerr << "\nCopied the return value from stack\n";
959     }
960   
961   } // if there is a return value
962
963 }
964
965
966 //---------------------------------------------------------------------------
967 // Copy from a register to register. Register number must be the unified
968 // register number
969 //---------------------------------------------------------------------------
970
971 void
972 UltraSparcRegInfo::cpReg2RegMI(unsigned SrcReg,
973                                unsigned DestReg,
974                                int RegType,
975                                vector<MachineInstr*>& mvec) const {
976   assert( ((int)SrcReg != InvalidRegNum) && ((int)DestReg != InvalidRegNum) &&
977           "Invalid Register");
978   
979   MachineInstr * MI = NULL;
980   
981   switch( RegType ) {
982     
983   case IntCCRegType:
984   case FloatCCRegType: 
985     assert(0 && "This code was bogus and needs to be fixed!");
986     break;
987     
988   case IntRegType:
989     MI = new MachineInstr(ADD, 3);
990     MI->SetMachineOperandReg(0, SrcReg, false);
991     MI->SetMachineOperandReg(1, this->getZeroRegNum(), false);
992     MI->SetMachineOperandReg(2, DestReg, true);
993     break;
994     
995   case FPSingleRegType:
996     MI = new MachineInstr(FMOVS, 2);
997     MI->SetMachineOperandReg(0, SrcReg, false);
998     MI->SetMachineOperandReg(1, DestReg, true);
999     break;
1000
1001   case FPDoubleRegType:
1002     MI = new MachineInstr(FMOVD, 2);
1003     MI->SetMachineOperandReg(0, SrcReg, false);    
1004     MI->SetMachineOperandReg(1, DestReg, true);
1005     break;
1006
1007   default:
1008     assert(0 && "Unknown RegType");
1009   }
1010   
1011   if (MI)
1012     mvec.push_back(MI);
1013 }
1014
1015 //---------------------------------------------------------------------------
1016 // Copy from a register to memory (i.e., Store). Register number must 
1017 // be the unified register number
1018 //---------------------------------------------------------------------------
1019
1020
1021 void
1022 UltraSparcRegInfo::cpReg2MemMI(unsigned SrcReg, 
1023                                unsigned DestPtrReg,
1024                                int Offset, int RegType,
1025                                vector<MachineInstr*>& mvec) const {
1026   MachineInstr * MI = NULL;
1027   switch( RegType ) {
1028   case IntRegType:
1029   case FloatCCRegType: 
1030     MI = new MachineInstr(STX, 3);
1031     MI->SetMachineOperandReg(0, SrcReg, false);
1032     MI->SetMachineOperandReg(1, DestPtrReg, false);
1033     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1034                                (int64_t) Offset);
1035     break;
1036
1037   case FPSingleRegType:
1038     MI = new MachineInstr(ST, 3);
1039     MI->SetMachineOperandReg(0, SrcReg, false);
1040     MI->SetMachineOperandReg(1, DestPtrReg, false);
1041     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1042                                (int64_t) Offset);
1043     break;
1044
1045   case FPDoubleRegType:
1046     MI = new MachineInstr(STD, 3);
1047     MI->SetMachineOperandReg(0, SrcReg, false);
1048     MI->SetMachineOperandReg(1, DestPtrReg, false);
1049     MI->SetMachineOperandConst(2, MachineOperand:: MO_SignExtendedImmed, 
1050                                (int64_t) Offset);
1051     break;
1052
1053   case IntCCRegType:
1054     assert( 0 && "Cannot directly store %ccr to memory");
1055     
1056   default:
1057     assert(0 && "Unknown RegType in cpReg2MemMI");
1058   }
1059
1060   if (MI)
1061     mvec.push_back(MI);
1062 }
1063
1064
1065 //---------------------------------------------------------------------------
1066 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1067 // register number
1068 //---------------------------------------------------------------------------
1069
1070
1071 void
1072 UltraSparcRegInfo::cpMem2RegMI(unsigned SrcPtrReg,      
1073                                int Offset,
1074                                unsigned DestReg,
1075                                int RegType,
1076                                vector<MachineInstr*>& mvec) const {
1077   MachineInstr * MI = NULL;
1078   switch (RegType) {
1079   case IntRegType:
1080   case FloatCCRegType: 
1081     MI = new MachineInstr(LDX, 3);
1082     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1083     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1084                                (int64_t) Offset);
1085     MI->SetMachineOperandReg(2, DestReg, true);
1086     break;
1087
1088   case FPSingleRegType:
1089     MI = new MachineInstr(LD, 3);
1090     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1091     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1092                                (int64_t) Offset);
1093     MI->SetMachineOperandReg(2, DestReg, true);
1094
1095     break;
1096
1097   case FPDoubleRegType:
1098     MI = new MachineInstr(LDD, 3);
1099     MI->SetMachineOperandReg(0, SrcPtrReg, false);
1100     MI->SetMachineOperandConst(1, MachineOperand:: MO_SignExtendedImmed, 
1101                                (int64_t) Offset);
1102     MI->SetMachineOperandReg(2, DestReg, true);
1103     break;
1104
1105   case IntCCRegType:
1106     assert( 0 && "Cannot directly load into %ccr from memory");
1107
1108   default:
1109     assert(0 && "Unknown RegType in cpMem2RegMI");
1110   }
1111
1112   if (MI)
1113     mvec.push_back(MI);
1114 }
1115
1116
1117 //---------------------------------------------------------------------------
1118 // Generate a copy instruction to copy a value to another. Temporarily
1119 // used by PhiElimination code.
1120 //---------------------------------------------------------------------------
1121
1122
1123 void
1124 UltraSparcRegInfo::cpValue2Value(Value *Src,
1125                                  Value *Dest,
1126                                  vector<MachineInstr*>& mvec) const {
1127   int RegType = getRegType( Src );
1128
1129   assert( (RegType==getRegType(Src))  && "Src & Dest are diff types");
1130
1131   MachineInstr * MI = NULL;
1132
1133   switch( RegType ) {
1134   case IntRegType:
1135     MI = new MachineInstr(ADD, 3);
1136     MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1137     MI->SetMachineOperandReg(1, this->getZeroRegNum(), false);
1138     MI->SetMachineOperandVal(2, MachineOperand:: MO_VirtualRegister, Dest, true);
1139     break;
1140
1141   case FPSingleRegType:
1142     MI = new MachineInstr(FMOVS, 2);
1143     MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1144     MI->SetMachineOperandVal(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1145     break;
1146
1147
1148   case FPDoubleRegType:
1149     MI = new MachineInstr(FMOVD, 2);
1150     MI->SetMachineOperandVal(0, MachineOperand:: MO_VirtualRegister, Src, false);
1151     MI->SetMachineOperandVal(1, MachineOperand:: MO_VirtualRegister, Dest, true);
1152     break;
1153
1154   default:
1155     assert(0 && "Unknow RegType in CpValu2Value");
1156   }
1157
1158   if (MI)
1159     mvec.push_back(MI);
1160 }
1161
1162
1163
1164
1165
1166
1167 //----------------------------------------------------------------------------
1168 // This method inserts caller saving/restoring instructons before/after
1169 // a call machine instruction. The caller saving/restoring instructions are
1170 // inserted like:
1171 //
1172 //    ** caller saving instructions
1173 //    other instructions inserted for the call by ColorCallArg
1174 //    CALL instruction
1175 //    other instructions inserted for the call ColorCallArg
1176 //    ** caller restoring instructions
1177 //
1178 //----------------------------------------------------------------------------
1179
1180
1181 void UltraSparcRegInfo::insertCallerSavingCode(const MachineInstr *CallMI, 
1182                                                const BasicBlock *BB,
1183                                                PhyRegAlloc &PRA) const {
1184
1185   assert ( (UltraSparcInfo->getInstrInfo()).isCall(CallMI->getOpCode()) );
1186   
1187   // has set to record which registers were saved/restored
1188   //
1189   std::hash_set<unsigned> PushedRegSet;
1190
1191   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
1192   
1193   // Now find the LR of the return value of the call
1194   // The last *implicit operand* is the return value of a call
1195   // Insert it to to he PushedRegSet since we must not save that register
1196   // and restore it after the call.
1197   // We do this because, we look at the LV set *after* the instruction
1198   // to determine, which LRs must be saved across calls. The return value
1199   // of the call is live in this set - but we must not save/restore it.
1200
1201   const Value *RetVal = argDesc->getReturnValue();
1202
1203   if (RetVal) {
1204     LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( RetVal );
1205     assert(RetValLR && "No LR for RetValue of call");
1206
1207     if (RetValLR->hasColor())
1208       PushedRegSet.insert(
1209          getUnifiedRegNum((RetValLR->getRegClass())->getID(), 
1210                                       RetValLR->getColor() ) );
1211   }
1212
1213
1214   const ValueSet &LVSetAft =  PRA.LVI->getLiveVarSetAfterMInst(CallMI, BB);
1215   ValueSet::const_iterator LIt = LVSetAft.begin();
1216
1217   // for each live var in live variable set after machine inst
1218   for( ; LIt != LVSetAft.end(); ++LIt) {
1219
1220    //  get the live range corresponding to live var
1221     LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );    
1222
1223     // LR can be null if it is a const since a const 
1224     // doesn't have a dominating def - see Assumptions above
1225     if( LR )   {  
1226       
1227       if( LR->hasColor() ) {
1228
1229         unsigned RCID = (LR->getRegClass())->getID();
1230         unsigned Color = LR->getColor();
1231
1232         if ( isRegVolatile(RCID, Color) ) {
1233
1234           // if the value is in both LV sets (i.e., live before and after 
1235           // the call machine instruction)
1236
1237           unsigned Reg = getUnifiedRegNum(RCID, Color);
1238           
1239           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1240             
1241             // if we haven't already pushed that register
1242
1243             unsigned RegType = getRegType( LR );
1244
1245             // Now get two instructions - to push on stack and pop from stack
1246             // and add them to InstrnsBefore and InstrnsAfter of the
1247             // call instruction
1248
1249
1250             int StackOff =  PRA.mcInfo.pushTempValue(target,  
1251                                                getSpilledRegSize(RegType));
1252
1253             
1254             MachineInstr *AdIBefCC=NULL, *AdIAftCC=NULL, *AdICpCC;
1255             MachineInstr *AdIBef=NULL, *AdIAft=NULL;
1256
1257             //---- Insert code for pushing the reg on stack ----------
1258                   
1259             if( RegType == IntCCRegType ) {
1260
1261               // Handle IntCCRegType specially since we cannot directly 
1262               // push %ccr on to the stack
1263
1264               const ValueSet &LVSetBef = 
1265                 PRA.LVI->getLiveVarSetBeforeMInst(CallMI, BB);
1266
1267               // get a free INTEGER register
1268               int FreeIntReg = 
1269                 PRA.getUsableUniRegAtMI(PRA.getRegClassByID(IntRegClassID) /*LR->getRegClass()*/,
1270                                         IntRegType, CallMI, &LVSetBef, AdIBefCC, AdIAftCC);
1271               
1272               // insert the instructions in reverse order since we are
1273               // adding them to the front of InstrnsBefore
1274               AddedInstrns& addedI = PRA.AddedInstrMap[CallMI];
1275               if(AdIAftCC)
1276                 addedI.InstrnsBefore.insert(addedI.InstrnsBefore.begin(),
1277                                             AdIAftCC);
1278               
1279               AdICpCC = cpCCR2IntMI(FreeIntReg);
1280               addedI.InstrnsBefore.insert(addedI.InstrnsBefore.begin(),
1281                                           AdICpCC);
1282               
1283               if(AdIBefCC)
1284                 addedI.InstrnsBefore.insert(addedI.InstrnsBefore.begin(),
1285                                             AdIBefCC);
1286               
1287               if(DEBUG_RA) {
1288                 cerr << "\n!! Inserted caller saving (push) inst for %ccr:";
1289                 if(AdIBefCC) cerr << "\t" <<  *(AdIBefCC);
1290                 cerr  << "\t" << *AdICpCC;
1291                 if(AdIAftCC) cerr  << "\t" << *(AdIAftCC);
1292               }
1293
1294             } else  {  
1295               // for any other register type, just add the push inst
1296               cpReg2MemMI(Reg, getFramePointer(), StackOff, RegType,
1297                           PRA.AddedInstrMap[CallMI].InstrnsBefore);
1298             }
1299
1300
1301             //---- Insert code for popping the reg from the stack ----------
1302
1303             if (RegType == IntCCRegType) {
1304
1305               // Handle IntCCRegType specially since we cannot directly 
1306               // pop %ccr on from the stack
1307               
1308               // get a free INT register
1309               int FreeIntReg = 
1310                 PRA.getUsableUniRegAtMI(PRA.getRegClassByID(IntRegClassID) /* LR->getRegClass()*/,
1311                                         IntRegType, CallMI, &LVSetAft, AdIBefCC, AdIAftCC);
1312               
1313               if(AdIBefCC)
1314                 PRA.AddedInstrMap[CallMI].InstrnsAfter.push_back(AdIBefCC);
1315
1316               AdICpCC = cpInt2CCRMI(FreeIntReg);
1317               PRA.AddedInstrMap[CallMI].InstrnsAfter.push_back(AdICpCC);
1318             
1319               if(AdIAftCC)
1320                 PRA.AddedInstrMap[CallMI].InstrnsAfter.push_back(AdIAftCC);
1321
1322               if(DEBUG_RA) {
1323
1324                 cerr << "\n!! Inserted caller saving (pop) inst for %ccr:";
1325                 if(AdIBefCC) cerr << "\t" <<  *(AdIBefCC);
1326                 cerr  << "\t" << *AdICpCC;
1327                 if(AdIAftCC) cerr  << "\t" << *(AdIAftCC);
1328               }
1329
1330             } else {
1331               // for any other register type, just add the pop inst
1332               cpMem2RegMI(getFramePointer(), StackOff, Reg, RegType,
1333                           PRA.AddedInstrMap[CallMI].InstrnsAfter);
1334             }
1335             
1336             PushedRegSet.insert(Reg);
1337
1338             if(DEBUG_RA) {
1339               cerr << "\nFor call inst:" << *CallMI;
1340               cerr << " -inserted caller saving instrs:\n\t ";
1341               if( RegType == IntCCRegType ) {
1342                 if(AdIBefCC) cerr << *AdIBefCC << "\t";
1343                 if(AdIAftCC) cerr << *AdIAftCC;
1344               }
1345               else {
1346                 if(AdIBef) cerr << *AdIBef << "\t";
1347                 if(AdIAft) cerr << *AdIAft;
1348               }
1349             }       
1350           } // if not already pushed
1351
1352         } // if LR has a volatile color
1353         
1354       } // if LR has color
1355
1356     } // if there is a LR for Var
1357     
1358   } // for each value in the LV set after instruction
1359   
1360 }
1361
1362 //---------------------------------------------------------------------------
1363 // Copies %ccr into an integer register. IntReg is the UNIFIED register
1364 // number.
1365 //---------------------------------------------------------------------------
1366
1367 MachineInstr * UltraSparcRegInfo::cpCCR2IntMI(unsigned IntReg) const {
1368   MachineInstr * MI = new MachineInstr(RDCCR, 2);
1369   MI->SetMachineOperandReg(0, this->getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
1370                                                      SparcIntCCRegOrder::ccr),
1371                            false, true);
1372   MI->SetMachineOperandReg(1, IntReg, true);
1373   return MI;
1374 }
1375
1376 //---------------------------------------------------------------------------
1377 // Copies an integer register into  %ccr. IntReg is the UNIFIED register
1378 // number.
1379 //---------------------------------------------------------------------------
1380
1381 MachineInstr *UltraSparcRegInfo::cpInt2CCRMI(unsigned IntReg) const {
1382   MachineInstr *MI = new MachineInstr(WRCCR, 3);
1383   MI->SetMachineOperandReg(0, IntReg, false);
1384   MI->SetMachineOperandReg(1, this->getZeroRegNum(), false);
1385   MI->SetMachineOperandReg(2, this->getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID, SparcIntCCRegOrder::ccr),
1386                            true, true);
1387   return MI;
1388 }
1389
1390
1391
1392
1393 //---------------------------------------------------------------------------
1394 // Print the register assigned to a LR
1395 //---------------------------------------------------------------------------
1396
1397 void UltraSparcRegInfo::printReg(const LiveRange *LR) {
1398   unsigned RegClassID = (LR->getRegClass())->getID();
1399   cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1400
1401   if (!LR->hasColor()) {
1402     cerr << " - could not find a color\n";
1403     return;
1404   }
1405   
1406   // if a color is found
1407
1408   cerr << " colored with color "<< LR->getColor();
1409
1410   if (RegClassID == IntRegClassID) {
1411     cerr<< " [" << SparcIntRegOrder::getRegName(LR->getColor()) << "]\n";
1412
1413   } else if (RegClassID == FloatRegClassID) {
1414     cerr << "[" << SparcFloatRegOrder::getRegName(LR->getColor());
1415     if( LR->getType() == Type::DoubleTy)
1416       cerr << "+" << SparcFloatRegOrder::getRegName(LR->getColor()+1);
1417     cerr << "]\n";
1418   }
1419 }
1420
1421 //---------------------------------------------------------------------------
1422 // This method examines instructions inserted by RegAlloc code before a
1423 // machine instruction to detect invalid orders that destroy values before
1424 // they are used. If it detects such conditions, it reorders the instructions.
1425 //
1426 // The unordered instructions come in the UnordVec. These instructions are
1427 // instructions inserted by RegAlloc. All such instruction MUST have 
1428 // their USES BEFORE THE DEFS after reordering.
1429 // 
1430 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1431 // this method is called.
1432 // 
1433 // This method uses two vectors for efficiency in accessing
1434 // 
1435 // Since instructions are inserted in RegAlloc, this assumes that the 
1436 // first operand is the source reg and the last operand is the dest reg.
1437 // 
1438 // All the uses are before THE def to a register
1439 //---------------------------------------------------------------------------
1440
1441 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr*> &UnordVec,
1442                                           std::vector<MachineInstr*> &OrdVec,
1443                                           PhyRegAlloc &PRA) const{
1444
1445   /*
1446     Problem: We can have instructions inserted by RegAlloc like
1447     1. add %ox %g0 %oy
1448     2. add %oy %g0 %oz, where z!=x or z==x
1449
1450     This is wrong since %oy used by 2 is overwritten by 1
1451   
1452     Solution:
1453     We re-order the instructions so that the uses are before the defs
1454
1455     Algorithm:
1456     
1457     do
1458       for each instruction 'DefInst' in the UnOrdVec
1459          for each instruction 'UseInst' that follows the DefInst
1460            if the reg defined by DefInst is used by UseInst
1461              mark DefInst as not movable in this iteration
1462          If DefInst is not marked as not-movable, move DefInst to OrdVec
1463     while all instructions in DefInst are moved to OrdVec
1464     
1465     For moving, we call the move2OrdVec(). It checks whether there is a def
1466     in it for the uses in the instruction to be added to OrdVec. If there
1467     are no preceding defs, it just appends the instruction. If there is a
1468     preceding def, it puts two instructions to save the reg on stack before
1469     the load and puts a restore at use.
1470
1471   */
1472
1473   bool CouldMoveAll;
1474   bool DebugPrint = false;
1475
1476   do {
1477     CouldMoveAll = true;
1478     std::vector<MachineInstr *>::iterator DefIt = UnordVec.begin();
1479
1480     for( ; DefIt !=  UnordVec.end(); ++DefIt ) {
1481
1482       // for each instruction in the UnordVec do ...
1483
1484       MachineInstr *DefInst = *DefIt;
1485
1486       if( DefInst == NULL) continue;
1487
1488       //cerr << "\nInst in UnordVec = " <<  *DefInst;
1489       
1490       // last operand is the def (unless for a store which has no def reg)
1491       MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1492       
1493       if( DefOp.opIsDef() &&  
1494           DefOp.getOperandType() ==  MachineOperand::MO_MachineRegister) {
1495         
1496         // If the operand in DefInst is a def ...
1497         
1498         bool DefEqUse = false;
1499         
1500         std::vector<MachineInstr *>::iterator UseIt = DefIt;
1501         UseIt++;
1502         
1503         for( ; UseIt !=  UnordVec.end(); ++UseIt ) {
1504
1505           MachineInstr *UseInst = *UseIt;
1506           if( UseInst == NULL) continue;
1507           
1508           // for each inst (UseInst) that is below the DefInst do ...
1509           MachineOperand& UseOp = UseInst->getOperand(0);
1510           
1511           if( ! UseOp.opIsDef() &&  
1512               UseOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1513             
1514             // if use is a register ...
1515             
1516             if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1517               
1518               // if Def and this use are the same, it means that this use
1519               // is destroyed by a def before it is used
1520               
1521               // cerr << "\nCouldn't move " << *DefInst;
1522
1523               DefEqUse = true;
1524               CouldMoveAll = false;     
1525               DebugPrint = true;
1526               break;
1527             } // if two registers are equal
1528             
1529           } // if use is a register
1530           
1531         }// for all use instructions
1532         
1533         if( ! DefEqUse ) {
1534           
1535           // after examining all the instructions that follow the DefInst
1536           // if there are no dependencies, we can move it to the OrdVec
1537
1538           // cerr << "Moved to Ord: " << *DefInst;
1539
1540           moveInst2OrdVec(OrdVec, DefInst, PRA);
1541
1542           //OrdVec.push_back(DefInst);
1543
1544           // mark the pos of DefInst with NULL to indicate that it is
1545           // empty
1546           *DefIt = NULL;
1547         }
1548     
1549       } // if Def is a machine register
1550       
1551     } // for all instructions in the UnordVec
1552     
1553
1554   } while(!CouldMoveAll);
1555
1556   if (DebugPrint && DEBUG_RA) {
1557     cerr << "\nAdded instructions were reordered to:\n";
1558     for(unsigned int i=0; i < OrdVec.size(); i++)
1559       cerr << *(OrdVec[i]);
1560   }
1561 }
1562
1563
1564
1565
1566
1567 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
1568                                         MachineInstr *UnordInst,
1569                                         PhyRegAlloc &PRA) const {
1570   MachineOperand& UseOp = UnordInst->getOperand(0);
1571
1572   if( ! UseOp.opIsDef() &&  
1573       UseOp.getOperandType() ==  MachineOperand::MO_MachineRegister) {
1574
1575     // for the use of UnordInst, see whether there is a defining instr
1576     // before in the OrdVec
1577     bool DefEqUse = false;
1578
1579     std::vector<MachineInstr *>::iterator OrdIt = OrdVec.begin();
1580   
1581     for( ; OrdIt !=  OrdVec.end(); ++OrdIt ) {
1582
1583       MachineInstr *OrdInst = *OrdIt ;
1584
1585       MachineOperand& DefOp = 
1586         OrdInst->getOperand(OrdInst->getNumOperands()-1);
1587
1588       if( DefOp.opIsDef() &&  
1589           DefOp.getOperandType() == MachineOperand::MO_MachineRegister) {
1590
1591         //cerr << "\nDefining Ord Inst: " <<  *OrdInst;
1592           
1593         if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1594
1595           // we are here because there is a preceding def in the OrdVec 
1596           // for the use in this intr we are going to insert. This
1597           // happened because the original code was like:
1598           // 1. add %ox %g0 %oy
1599           // 2. add %oy %g0 %ox
1600           // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1601           // Now we are processing %ox of 1.
1602           // We have to 
1603               
1604           const int UReg = DefOp.getMachineRegNum();
1605           const int RegType = getRegType(UReg);
1606           MachineInstr *AdIBef, *AdIAft;
1607               
1608           const int StackOff =  PRA.mcInfo.pushTempValue(target,
1609                                          getSpilledRegSize(RegType));
1610           
1611           // Save the UReg (%ox) on stack before it's destroyed
1612           vector<MachineInstr*> mvec;
1613           cpReg2MemMI(UReg, getFramePointer(), StackOff, RegType, mvec);
1614           for (vector<MachineInstr*>::iterator MI=mvec.begin(); MI != mvec.end(); ++MI) {
1615             OrdIt = OrdVec.insert(OrdIt, *MI);
1616             ++OrdIt; // OrdIt must still point to current instr we processed
1617           }
1618           
1619           // Load directly into DReg (%oy)
1620           MachineOperand&  DOp=
1621             (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1622           assert(DOp.opIsDef() && "Last operand is not the def");
1623           const int DReg = DOp.getMachineRegNum();
1624           
1625           cpMem2RegMI(getFramePointer(), StackOff, DReg, RegType, OrdVec);
1626             
1627           cerr << "\nFixed CIRCULAR references by reordering";
1628
1629           if( DEBUG_RA ) {
1630             cerr << "\nBefore CIRCULAR Reordering:\n";
1631             cerr << *UnordInst;
1632             cerr << *OrdInst;
1633           
1634             cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1635             for(unsigned i=0; i < OrdVec.size(); i++)
1636               cerr << *(OrdVec[i]);
1637           }
1638           
1639           // Do not copy the UseInst to OrdVec
1640           DefEqUse = true;
1641           break;  
1642           
1643         }// if two registers are equal
1644
1645       } // if Def is a register
1646
1647     } // for each instr in OrdVec
1648
1649     if(!DefEqUse) {  
1650
1651       // We didn't find a def in the OrdVec, so just append this inst
1652       OrdVec.push_back( UnordInst );  
1653       //cerr << "Reordered Inst (Moved Dn): " <<  *UnordInst;
1654     }
1655     
1656   }// if the operand in UnordInst is a use
1657 }