Add code to support stack spill/temp offsets that don't fit in the
[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/CodeGen/MachineFunction.h"
11 #include "llvm/CodeGen/MachineFunctionInfo.h"
12 #include "llvm/CodeGen/InstrSelection.h"
13 #include "llvm/CodeGen/MachineInstrBuilder.h"
14 #include "llvm/CodeGen/MachineCodeForInstruction.h"
15 #include "llvm/CodeGen/MachineInstrAnnot.h"
16 #include "llvm/CodeGen/LiveRangeInfo.h"
17 #include "llvm/iTerminators.h"
18 #include "llvm/iOther.h"
19 #include "llvm/Function.h"
20 #include "llvm/DerivedTypes.h"
21
22 enum {
23   BadRegClass = ~0
24 };
25
26 UltraSparcRegInfo::UltraSparcRegInfo(const UltraSparc &tgt)
27   : TargetRegInfo(tgt), NumOfIntArgRegs(6), NumOfFloatArgRegs(32)
28 {
29   MachineRegClassArr.push_back(new SparcIntRegClass(IntRegClassID));
30   MachineRegClassArr.push_back(new SparcFloatRegClass(FloatRegClassID));
31   MachineRegClassArr.push_back(new SparcIntCCRegClass(IntCCRegClassID));
32   MachineRegClassArr.push_back(new SparcFloatCCRegClass(FloatCCRegClassID));
33   MachineRegClassArr.push_back(new SparcSpecialRegClass(SpecialRegClassID));
34   
35   assert(SparcFloatRegClass::StartOfNonVolatileRegs == 32 && 
36          "32 Float regs are used for float arg passing");
37 }
38
39
40 // getZeroRegNum - returns the register that contains always zero.
41 // this is the unified register number
42 //
43 int UltraSparcRegInfo::getZeroRegNum() const {
44   return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
45                           SparcIntRegClass::g0);
46 }
47
48 // getCallAddressReg - returns the reg used for pushing the address when a
49 // method is called. This can be used for other purposes between calls
50 //
51 unsigned UltraSparcRegInfo::getCallAddressReg() const {
52   return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
53                           SparcIntRegClass::o7);
54 }
55
56 // Returns the register containing the return address.
57 // It should be made sure that this  register contains the return 
58 // value when a return instruction is reached.
59 //
60 unsigned UltraSparcRegInfo::getReturnAddressReg() const {
61   return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
62                           SparcIntRegClass::i7);
63 }
64
65 // Register get name implementations...
66
67 // Int register names in same order as enum in class SparcIntRegClass
68 static const char * const IntRegNames[] = {
69   "o0", "o1", "o2", "o3", "o4", "o5",       "o7",
70   "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
71   "i0", "i1", "i2", "i3", "i4", "i5",  
72   "i6", "i7",
73   "g0", "g1", "g2", "g3", "g4", "g5",  "g6", "g7", 
74   "o6"
75 }; 
76
77 const char * const SparcIntRegClass::getRegName(unsigned reg) const {
78   assert(reg < NumOfAllRegs);
79   return IntRegNames[reg];
80 }
81
82 static const char * const FloatRegNames[] = {    
83   "f0",  "f1",  "f2",  "f3",  "f4",  "f5",  "f6",  "f7",  "f8",  "f9", 
84   "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19",
85   "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29",
86   "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39",
87   "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49",
88   "f50", "f51", "f52", "f53", "f54", "f55", "f56", "f57", "f58", "f59",
89   "f60", "f61", "f62", "f63"
90 };
91
92 const char * const SparcFloatRegClass::getRegName(unsigned reg) const {
93   assert (reg < NumOfAllRegs);
94   return FloatRegNames[reg];
95 }
96
97
98 static const char * const IntCCRegNames[] = {    
99   "xcc",  "icc",  "ccr"
100 };
101
102 const char * const SparcIntCCRegClass::getRegName(unsigned reg) const {
103   assert(reg < 3);
104   return IntCCRegNames[reg];
105 }
106
107 static const char * const FloatCCRegNames[] = {    
108   "fcc0", "fcc1",  "fcc2",  "fcc3"
109 };
110
111 const char * const SparcFloatCCRegClass::getRegName(unsigned reg) const {
112   assert (reg < 5);
113   return FloatCCRegNames[reg];
114 }
115
116 static const char * const SpecialRegNames[] = {    
117   "fsr"
118 };
119
120 const char * const SparcSpecialRegClass::getRegName(unsigned reg) const {
121   assert (reg < 1);
122   return SpecialRegNames[reg];
123 }
124
125 // Get unified reg number for frame pointer
126 unsigned UltraSparcRegInfo::getFramePointer() const {
127   return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
128                           SparcIntRegClass::i6);
129 }
130
131 // Get unified reg number for stack pointer
132 unsigned UltraSparcRegInfo::getStackPointer() const {
133   return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
134                           SparcIntRegClass::o6);
135 }
136
137
138 //---------------------------------------------------------------------------
139 // Finds whether a call is an indirect call
140 //---------------------------------------------------------------------------
141
142 inline bool
143 isVarArgsFunction(const Type *funcType) {
144   return cast<FunctionType>(cast<PointerType>(funcType)
145                             ->getElementType())->isVarArg();
146 }
147
148 inline bool
149 isVarArgsCall(const MachineInstr *CallMI) {
150   Value* callee = CallMI->getOperand(0).getVRegValue();
151   // const Type* funcType = isa<Function>(callee)? callee->getType()
152   //   : cast<PointerType>(callee->getType())->getElementType();
153   const Type* funcType = callee->getType();
154   return isVarArgsFunction(funcType);
155 }
156
157
158 // Get the register number for the specified argument #argNo,
159 // 
160 // Return value:
161 //      getInvalidRegNum(),  if there is no int register available for the arg. 
162 //      regNum,              otherwise (this is NOT the unified reg. num).
163 //                           regClassId is set to the register class ID.
164 // 
165 int
166 UltraSparcRegInfo::regNumForIntArg(bool inCallee, bool isVarArgsCall,
167                                    unsigned argNo, unsigned& regClassId) const
168 {
169   regClassId = IntRegClassID;
170   if (argNo >= NumOfIntArgRegs)
171     return getInvalidRegNum();
172   else
173     return argNo + (inCallee? SparcIntRegClass::i0 : SparcIntRegClass::o0);
174 }
175
176 // Get the register number for the specified FP argument #argNo,
177 // Use INT regs for FP args if this is a varargs call.
178 // 
179 // Return value:
180 //      getInvalidRegNum(),  if there is no int register available for the arg. 
181 //      regNum,              otherwise (this is NOT the unified reg. num).
182 //                           regClassId is set to the register class ID.
183 // 
184 int
185 UltraSparcRegInfo::regNumForFPArg(unsigned regType,
186                                   bool inCallee, bool isVarArgsCall,
187                                   unsigned argNo, unsigned& regClassId) const
188 {
189   if (isVarArgsCall)
190     return regNumForIntArg(inCallee, isVarArgsCall, argNo, regClassId);
191   else
192     {
193       regClassId = FloatRegClassID;
194       if (regType == FPSingleRegType)
195         return (argNo*2+1 >= NumOfFloatArgRegs)?
196           getInvalidRegNum() : SparcFloatRegClass::f0 + (argNo * 2 + 1);
197       else if (regType == FPDoubleRegType)
198         return (argNo*2 >= NumOfFloatArgRegs)?
199           getInvalidRegNum() : SparcFloatRegClass::f0 + (argNo * 2);
200       else
201         assert(0 && "Illegal FP register type");
202         return 0;
203     }
204 }
205
206
207 //---------------------------------------------------------------------------
208 // Finds the return address of a call sparc specific call instruction
209 //---------------------------------------------------------------------------
210
211 // The following 4  methods are used to find the RegType (SparcInternals.h)
212 // of a LiveRange, a Value, and for a given register unified reg number.
213 //
214 int UltraSparcRegInfo::getRegTypeForClassAndType(unsigned regClassID,
215                                                  const Type* type) const
216 {
217   switch (regClassID) {
218   case IntRegClassID:                   return IntRegType; 
219   case FloatRegClassID:
220     if (type == Type::FloatTy)          return FPSingleRegType;
221     else if (type == Type::DoubleTy)    return FPDoubleRegType;
222     assert(0 && "Unknown type in FloatRegClass"); return 0;
223   case IntCCRegClassID:                 return IntCCRegType; 
224   case FloatCCRegClassID:               return FloatCCRegType; 
225   case SpecialRegClassID:               return SpecialRegType; 
226   default: assert( 0 && "Unknown reg class ID"); return 0;
227   }
228 }
229
230 int UltraSparcRegInfo::getRegTypeForDataType(const Type* type) const
231 {
232   return getRegTypeForClassAndType(getRegClassIDOfType(type), type);
233 }
234
235 int UltraSparcRegInfo::getRegTypeForLR(const LiveRange *LR) const
236 {
237   return getRegTypeForClassAndType(LR->getRegClassID(), LR->getType());
238 }
239
240 int UltraSparcRegInfo::getRegType(int unifiedRegNum) const
241 {
242   if (unifiedRegNum < 32) 
243     return IntRegType;
244   else if (unifiedRegNum < (32 + 32))
245     return FPSingleRegType;
246   else if (unifiedRegNum < (64 + 32))
247     return FPDoubleRegType;
248   else if (unifiedRegNum < (64+32+4))
249     return FloatCCRegType;
250   else if (unifiedRegNum < (64+32+4+2))  
251     return IntCCRegType;             
252   else 
253     assert(0 && "Invalid unified register number in getRegType");
254   return 0;
255 }
256
257
258 // To find the register class used for a specified Type
259 //
260 unsigned UltraSparcRegInfo::getRegClassIDOfType(const Type *type,
261                                                 bool isCCReg) const {
262   Type::PrimitiveID ty = type->getPrimitiveID();
263   unsigned res;
264     
265   // FIXME: Comparing types like this isn't very safe...
266   if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
267       (ty == Type::FunctionTyID) ||  (ty == Type::PointerTyID) )
268     res = IntRegClassID;             // sparc int reg (ty=0: void)
269   else if (ty <= Type::DoubleTyID)
270     res = FloatRegClassID;           // sparc float reg class
271   else { 
272     //std::cerr << "TypeID: " << ty << "\n";
273     assert(0 && "Cannot resolve register class for type");
274     return 0;
275   }
276   
277   if (isCCReg)
278     return res + 2;      // corresponding condition code register 
279   else 
280     return res;
281 }
282
283 unsigned UltraSparcRegInfo::getRegClassIDOfRegType(int regType) const {
284   switch(regType) {
285   case IntRegType:      return IntRegClassID;
286   case FPSingleRegType:
287   case FPDoubleRegType: return FloatRegClassID;
288   case IntCCRegType:    return IntCCRegClassID;
289   case FloatCCRegType:  return FloatCCRegClassID;
290   default:
291     assert(0 && "Invalid register type in getRegClassIDOfRegType");
292     return 0;
293   }
294 }
295
296 //---------------------------------------------------------------------------
297 // Suggests a register for the ret address in the RET machine instruction.
298 // We always suggest %i7 by convention.
299 //---------------------------------------------------------------------------
300 void UltraSparcRegInfo::suggestReg4RetAddr(MachineInstr *RetMI, 
301                                            LiveRangeInfo& LRI) const {
302
303   assert(target.getInstrInfo().isReturn(RetMI->getOpCode()));
304   
305   // return address is always mapped to i7 so set it immediately
306   RetMI->SetRegForOperand(0, getUnifiedRegNum(IntRegClassID,
307                                               SparcIntRegClass::i7));
308   
309   // Possible Optimization: 
310   // Instead of setting the color, we can suggest one. In that case,
311   // we have to test later whether it received the suggested color.
312   // In that case, a LR has to be created at the start of method.
313   // It has to be done as follows (remove the setRegVal above):
314
315   // MachineOperand & MO  = RetMI->getOperand(0);
316   // const Value *RetAddrVal = MO.getVRegValue();
317   // assert( RetAddrVal && "LR for ret address must be created at start");
318   // LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);  
319   // RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID, 
320   //                              SparcIntRegOrdr::i7) );
321 }
322
323
324 //---------------------------------------------------------------------------
325 // Suggests a register for the ret address in the JMPL/CALL machine instr.
326 // Sparc ABI dictates that %o7 be used for this purpose.
327 //---------------------------------------------------------------------------
328 void
329 UltraSparcRegInfo::suggestReg4CallAddr(MachineInstr * CallMI,
330                                        LiveRangeInfo& LRI) const
331 {
332   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
333   const Value *RetAddrVal = argDesc->getReturnAddrReg();
334   assert(RetAddrVal && "INTERNAL ERROR: Return address value is required");
335
336   // A LR must already exist for the return address.
337   LiveRange *RetAddrLR = LRI.getLiveRangeForValue(RetAddrVal);
338   assert(RetAddrLR && "INTERNAL ERROR: No LR for return address of call!");
339
340   unsigned RegClassID = RetAddrLR->getRegClassID();
341   RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID, SparcIntRegClass::o7));
342 }
343
344
345
346 //---------------------------------------------------------------------------
347 //  This method will suggest colors to incoming args to a method. 
348 //  According to the Sparc ABI, the first 6 incoming args are in 
349 //  %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
350 //  If the arg is passed on stack due to the lack of regs, NOTHING will be
351 //  done - it will be colored (or spilled) as a normal live range.
352 //---------------------------------------------------------------------------
353 void UltraSparcRegInfo::suggestRegs4MethodArgs(const Function *Meth, 
354                                                LiveRangeInfo& LRI) const 
355 {
356   // Check if this is a varArgs function. needed for choosing regs.
357   bool isVarArgs = isVarArgsFunction(Meth->getType());
358   
359   // Count the arguments, *ignoring* whether they are int or FP args.
360   // Use this common arg numbering to pick the right int or fp register.
361   unsigned argNo=0;
362   for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
363       I != E; ++I, ++argNo) {
364     LiveRange *LR = LRI.getLiveRangeForValue(I);
365     assert(LR && "No live range found for method arg");
366     
367     unsigned regType = getRegTypeForLR(LR);
368     unsigned regClassIDOfArgReg = BadRegClass; // for chosen reg (unused)
369     
370     int regNum = (regType == IntRegType)
371       ? regNumForIntArg(/*inCallee*/ true, isVarArgs, argNo, regClassIDOfArgReg)
372       : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs, argNo,
373                        regClassIDOfArgReg); 
374     
375     if (regNum != getInvalidRegNum())
376       LR->setSuggestedColor(regNum);
377   }
378 }
379
380
381 //---------------------------------------------------------------------------
382 // This method is called after graph coloring to move incoming args to
383 // the correct hardware registers if they did not receive the correct
384 // (suggested) color through graph coloring.
385 //---------------------------------------------------------------------------
386 void UltraSparcRegInfo::colorMethodArgs(const Function *Meth, 
387                             LiveRangeInfo &LRI,
388                             std::vector<MachineInstr*>& InstrnsBefore,
389                             std::vector<MachineInstr*>& InstrnsAfter) const {
390
391   // check if this is a varArgs function. needed for choosing regs.
392   bool isVarArgs = isVarArgsFunction(Meth->getType());
393   MachineInstr *AdMI;
394
395   // for each argument
396   // for each argument.  count INT and FP arguments separately.
397   unsigned argNo=0, intArgNo=0, fpArgNo=0;
398   for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
399       I != E; ++I, ++argNo) {
400     // get the LR of arg
401     LiveRange *LR = LRI.getLiveRangeForValue(I);
402     assert( LR && "No live range found for method arg");
403
404     unsigned regType = getRegTypeForLR(LR);
405     unsigned RegClassID = LR->getRegClassID();
406     
407     // Find whether this argument is coming in a register (if not, on stack)
408     // Also find the correct register the argument must use (UniArgReg)
409     //
410     bool isArgInReg = false;
411     unsigned UniArgReg = getInvalidRegNum(); // reg that LR MUST be colored with
412     unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
413     
414     int regNum = (regType == IntRegType)
415       ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
416                         argNo, regClassIDOfArgReg)
417       : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
418                        argNo, regClassIDOfArgReg);
419     
420     if(regNum != getInvalidRegNum()) {
421       isArgInReg = true;
422       UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
423     }
424     
425     if( ! LR->isMarkedForSpill() ) {    // if this arg received a register
426
427       unsigned UniLRReg = getUnifiedRegNum(  RegClassID, LR->getColor() );
428
429       // if LR received the correct color, nothing to do
430       //
431       if( UniLRReg == UniArgReg )
432         continue;
433
434       // We are here because the LR did not receive the suggested 
435       // but LR received another register.
436       // Now we have to copy the %i reg (or stack pos of arg) 
437       // to the register the LR was colored with.
438       
439       // if the arg is coming in UniArgReg register, it MUST go into
440       // the UniLRReg register
441       //
442       if( isArgInReg ) {
443         if( regClassIDOfArgReg != RegClassID ) {
444           assert(0 && "This could should work but it is not tested yet");
445           
446           // It is a variable argument call: the float reg must go in a %o reg.
447           // We have to move an int reg to a float reg via memory.
448           // 
449           assert(isVarArgs &&
450                  RegClassID == FloatRegClassID && 
451                  regClassIDOfArgReg == IntRegClassID &&
452                  "This should only be an Int register for an FP argument");
453           
454           int TmpOff = MachineFunction::get(Meth).getInfo()->pushTempValue(
455                                                 getSpilledRegSize(regType));
456           cpReg2MemMI(InstrnsBefore,
457                       UniArgReg, getFramePointer(), TmpOff, IntRegType);
458           
459           cpMem2RegMI(InstrnsBefore,
460                       getFramePointer(), TmpOff, UniLRReg, regType);
461         }
462         else {  
463           cpReg2RegMI(InstrnsBefore, UniArgReg, UniLRReg, regType);
464         }
465       }
466       else {
467
468         // Now the arg is coming on stack. Since the LR recieved a register,
469         // we just have to load the arg on stack into that register
470         //
471         const TargetFrameInfo& frameInfo = target.getFrameInfo();
472         int offsetFromFP =
473           frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
474                                          argNo);
475
476         // float arguments on stack are right justified so adjust the offset!
477         // int arguments are also right justified but they are always loaded as
478         // a full double-word so the offset does not need to be adjusted.
479         if (regType == FPSingleRegType) {
480           unsigned argSize = target.getTargetData().getTypeSize(LR->getType());
481           unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
482           assert(argSize <= slotSize && "Insufficient slot size!");
483           offsetFromFP += slotSize - argSize;
484         }
485
486         cpMem2RegMI(InstrnsBefore,
487                     getFramePointer(), offsetFromFP, UniLRReg, regType);
488       }
489       
490     } // if LR received a color
491
492     else {                             
493
494       // Now, the LR did not receive a color. But it has a stack offset for
495       // spilling.
496       // So, if the arg is coming in UniArgReg register,  we can just move
497       // that on to the stack pos of LR
498
499       if( isArgInReg ) {
500         
501         if( regClassIDOfArgReg != RegClassID ) {
502           assert(0 &&
503                  "FP arguments to a varargs function should be explicitly "
504                  "copied to/from int registers by instruction selection!");
505           
506           // It must be a float arg for a variable argument call, which
507           // must come in a %o reg.  Move the int reg to the stack.
508           // 
509           assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
510                  "This should only be an Int register for an FP argument");
511           
512           cpReg2MemMI(InstrnsBefore, UniArgReg,
513                       getFramePointer(), LR->getSpillOffFromFP(), IntRegType);
514         }
515         else {
516            cpReg2MemMI(InstrnsBefore, UniArgReg,
517                        getFramePointer(), LR->getSpillOffFromFP(), regType);
518         }
519       }
520
521       else {
522
523         // Now the arg is coming on stack. Since the LR did NOT 
524         // recieved a register as well, it is allocated a stack position. We
525         // can simply change the stack position of the LR. We can do this,
526         // since this method is called before any other method that makes
527         // uses of the stack pos of the LR (e.g., updateMachineInstr)
528         // 
529         const TargetFrameInfo& frameInfo = target.getFrameInfo();
530         int offsetFromFP =
531           frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
532                                          argNo);
533
534         // FP arguments on stack are right justified so adjust offset!
535         // int arguments are also right justified but they are always loaded as
536         // a full double-word so the offset does not need to be adjusted.
537         if (regType == FPSingleRegType) {
538           unsigned argSize = target.getTargetData().getTypeSize(LR->getType());
539           unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
540           assert(argSize <= slotSize && "Insufficient slot size!");
541           offsetFromFP += slotSize - argSize;
542         }
543         
544         LR->modifySpillOffFromFP( offsetFromFP );
545       }
546
547     }
548
549   }  // for each incoming argument
550
551 }
552
553
554
555 //---------------------------------------------------------------------------
556 // This method is called before graph coloring to suggest colors to the
557 // outgoing call args and the return value of the call.
558 //---------------------------------------------------------------------------
559 void UltraSparcRegInfo::suggestRegs4CallArgs(MachineInstr *CallMI, 
560                                              LiveRangeInfo& LRI) const {
561   assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
562
563   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI); 
564   
565   suggestReg4CallAddr(CallMI, LRI);
566
567   // First color the return value of the call instruction, if any.
568   // The return value will be in %o0 if the value is an integer type,
569   // or in %f0 if the value is a float type.
570   // 
571   if (const Value *RetVal = argDesc->getReturnValue()) {
572     LiveRange *RetValLR = LRI.getLiveRangeForValue(RetVal);
573     assert(RetValLR && "No LR for return Value of call!");
574
575     unsigned RegClassID = RetValLR->getRegClassID();
576
577     // now suggest a register depending on the register class of ret arg
578     if( RegClassID == IntRegClassID ) 
579       RetValLR->setSuggestedColor(SparcIntRegClass::o0);
580     else if (RegClassID == FloatRegClassID ) 
581       RetValLR->setSuggestedColor(SparcFloatRegClass::f0 );
582     else assert( 0 && "Unknown reg class for return value of call\n");
583   }
584
585   // Now suggest colors for arguments (operands) of the call instruction.
586   // Colors are suggested only if the arg number is smaller than the
587   // the number of registers allocated for argument passing.
588   // Now, go thru call args - implicit operands of the call MI
589
590   unsigned NumOfCallArgs = argDesc->getNumArgs();
591   
592   for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
593        i < NumOfCallArgs; ++i, ++argNo) {    
594
595     const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
596     
597     // get the LR of call operand (parameter)
598     LiveRange *const LR = LRI.getLiveRangeForValue(CallArg); 
599     if (!LR)
600       continue;                    // no live ranges for constants and labels
601
602     unsigned regType = getRegTypeForLR(LR);
603     unsigned regClassIDOfArgReg = BadRegClass; // chosen reg class (unused)
604
605     // Choose a register for this arg depending on whether it is
606     // an INT or FP value.  Here we ignore whether or not it is a
607     // varargs calls, because FP arguments will be explicitly copied
608     // to an integer Value and handled under (argCopy != NULL) below.
609     int regNum = (regType == IntRegType)
610       ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
611                         argNo, regClassIDOfArgReg)
612       : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
613                        argNo, regClassIDOfArgReg); 
614     
615     // If a register could be allocated, use it.
616     // If not, do NOTHING as this will be colored as a normal value.
617     if(regNum != getInvalidRegNum())
618       LR->setSuggestedColor(regNum);
619   } // for all call arguments
620 }
621
622
623 //---------------------------------------------------------------------------
624 // this method is called for an LLVM return instruction to identify which
625 // values will be returned from this method and to suggest colors.
626 //---------------------------------------------------------------------------
627 void UltraSparcRegInfo::suggestReg4RetValue(MachineInstr *RetMI, 
628                                             LiveRangeInfo& LRI) const {
629
630   assert( (target.getInstrInfo()).isReturn( RetMI->getOpCode() ) );
631
632   suggestReg4RetAddr(RetMI, LRI);
633
634   // To find the return value (if any), we can get the LLVM return instr.
635   // from the return address register, which is the first operand
636   Value* tmpI = RetMI->getOperand(0).getVRegValue();
637   ReturnInst* retI=cast<ReturnInst>(cast<TmpInstruction>(tmpI)->getOperand(0));
638   if (const Value *RetVal = retI->getReturnValue())
639     if (LiveRange *const LR = LRI.getLiveRangeForValue(RetVal))
640       LR->setSuggestedColor(LR->getRegClassID() == IntRegClassID
641                             ? (unsigned) SparcIntRegClass::i0
642                             : (unsigned) SparcFloatRegClass::f0);
643 }
644
645 //---------------------------------------------------------------------------
646 // Check if a specified register type needs a scratch register to be
647 // copied to/from memory.  If it does, the reg. type that must be used
648 // for scratch registers is returned in scratchRegType.
649 //
650 // Only the int CC register needs such a scratch register.
651 // The FP CC registers can (and must) be copied directly to/from memory.
652 //---------------------------------------------------------------------------
653
654 bool
655 UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
656                                           int& scratchRegType) const
657 {
658   if (RegType == IntCCRegType)
659     {
660       scratchRegType = IntRegType;
661       return true;
662     }
663   return false;
664 }
665
666 //---------------------------------------------------------------------------
667 // Copy from a register to register. Register number must be the unified
668 // register number.
669 //---------------------------------------------------------------------------
670
671 void
672 UltraSparcRegInfo::cpReg2RegMI(std::vector<MachineInstr*>& mvec,
673                                unsigned SrcReg,
674                                unsigned DestReg,
675                                int RegType) const {
676   assert( ((int)SrcReg != getInvalidRegNum()) && 
677           ((int)DestReg != getInvalidRegNum()) &&
678           "Invalid Register");
679   
680   MachineInstr * MI = NULL;
681   
682   switch( RegType ) {
683     
684   case IntCCRegType:
685     if (getRegType(DestReg) == IntRegType) {
686       // copy intCC reg to int reg
687       MI = (BuildMI(V9::RDCCR, 2)
688             .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
689                                       SparcIntCCRegClass::ccr))
690             .addMReg(DestReg,MOTy::Def));
691     } else {
692       // copy int reg to intCC reg
693       assert(getRegType(SrcReg) == IntRegType
694              && "Can only copy CC reg to/from integer reg");
695       MI = (BuildMI(V9::WRCCRr, 3)
696             .addMReg(SrcReg)
697             .addMReg(SparcIntRegClass::g0)
698             .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
699                                       SparcIntCCRegClass::ccr), MOTy::Def));
700     }
701     break;
702     
703   case FloatCCRegType: 
704     assert(0 && "Cannot copy FPCC register to any other register");
705     break;
706     
707   case IntRegType:
708     MI = BuildMI(V9::ADDr, 3).addMReg(SrcReg).addMReg(getZeroRegNum())
709       .addMReg(DestReg, MOTy::Def);
710     break;
711     
712   case FPSingleRegType:
713     MI = BuildMI(V9::FMOVS, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
714     break;
715
716   case FPDoubleRegType:
717     MI = BuildMI(V9::FMOVD, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
718     break;
719
720   default:
721     assert(0 && "Unknown RegType");
722     break;
723   }
724   
725   if (MI)
726     mvec.push_back(MI);
727 }
728
729 //---------------------------------------------------------------------------
730 // Copy from a register to memory (i.e., Store). Register number must 
731 // be the unified register number
732 //---------------------------------------------------------------------------
733
734
735 void
736 UltraSparcRegInfo::cpReg2MemMI(std::vector<MachineInstr*>& mvec,
737                                unsigned SrcReg, 
738                                unsigned PtrReg,
739                                int Offset, int RegType,
740                                int scratchReg) const {
741   MachineInstr * MI = NULL;
742   int OffReg = -1;
743
744   // If the Offset will not fit in the signed-immediate field, find an
745   // unused register to hold the offset value.  This takes advantage of
746   // the fact that all the opcodes used below have the same size immed. field.
747   // Use the register allocator, PRA, to find an unused reg. at this MI.
748   // 
749   if (RegType != IntCCRegType)          // does not use offset below
750     if (! target.getInstrInfo().constantFitsInImmedField(V9::LDXi, Offset)) {
751 #ifdef CAN_FIND_FREE_REGISTER_TRANSPARENTLY
752       RegClass* RC = PRA.getRegClassByID(this->getRegClassIDOfRegType(RegType));
753       OffReg = PRA.getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
754 #else
755       // Default to using register g2 for holding large offsets
756       OffReg = getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
757                                 SparcIntRegClass::g4);
758 #endif
759       assert(OffReg >= 0 && "FIXME: cpReg2MemMI cannot find an unused reg.");
760       mvec.push_back(BuildMI(V9::SETSW, 2).addZImm(Offset).addReg(OffReg));
761     }
762
763   switch (RegType) {
764   case IntRegType:
765     if (target.getInstrInfo().constantFitsInImmedField(V9::STXi, Offset))
766       MI = BuildMI(V9::STXi,3).addMReg(SrcReg).addMReg(PtrReg).addSImm(Offset);
767     else
768       MI = BuildMI(V9::STXr,3).addMReg(SrcReg).addMReg(PtrReg).addMReg(OffReg);
769     break;
770
771   case FPSingleRegType:
772     if (target.getInstrInfo().constantFitsInImmedField(V9::STFi, Offset))
773       MI = BuildMI(V9::STFi, 3).addMReg(SrcReg).addMReg(PtrReg).addSImm(Offset);
774     else
775       MI = BuildMI(V9::STFr, 3).addMReg(SrcReg).addMReg(PtrReg).addMReg(OffReg);
776     break;
777
778   case FPDoubleRegType:
779     if (target.getInstrInfo().constantFitsInImmedField(V9::STDFi, Offset))
780       MI = BuildMI(V9::STDFi,3).addMReg(SrcReg).addMReg(PtrReg).addSImm(Offset);
781     else
782       MI = BuildMI(V9::STDFr,3).addMReg(SrcReg).addMReg(PtrReg).addSImm(OffReg);
783     break;
784
785   case IntCCRegType:
786     assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
787     assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
788     MI = (BuildMI(V9::RDCCR, 2)
789           .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
790                                     SparcIntCCRegClass::ccr))
791           .addMReg(scratchReg, MOTy::Def));
792     mvec.push_back(MI);
793     
794     cpReg2MemMI(mvec, scratchReg, PtrReg, Offset, IntRegType);
795     return;
796
797   case FloatCCRegType: {
798     unsigned fsrReg =  getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
799                                            SparcSpecialRegClass::fsr);
800     if (target.getInstrInfo().constantFitsInImmedField(V9::STXFSRi, Offset))
801       MI=BuildMI(V9::STXFSRi,3).addMReg(fsrReg).addMReg(PtrReg).addSImm(Offset);
802     else
803       MI=BuildMI(V9::STXFSRr,3).addMReg(fsrReg).addMReg(PtrReg).addMReg(OffReg);
804     break;
805   }
806   default:
807     assert(0 && "Unknown RegType in cpReg2MemMI");
808   }
809   mvec.push_back(MI);
810 }
811
812
813 //---------------------------------------------------------------------------
814 // Copy from memory to a reg (i.e., Load) Register number must be the unified
815 // register number
816 //---------------------------------------------------------------------------
817
818
819 void
820 UltraSparcRegInfo::cpMem2RegMI(std::vector<MachineInstr*>& mvec,
821                                unsigned PtrReg, 
822                                int Offset,
823                                unsigned DestReg,
824                                int RegType,
825                                int scratchReg) const {
826   MachineInstr * MI = NULL;
827   int OffReg = -1;
828
829   // If the Offset will not fit in the signed-immediate field, find an
830   // unused register to hold the offset value.  This takes advantage of
831   // the fact that all the opcodes used below have the same size immed. field.
832   // Use the register allocator, PRA, to find an unused reg. at this MI.
833   // 
834   if (RegType != IntCCRegType)          // does not use offset below
835     if (! target.getInstrInfo().constantFitsInImmedField(V9::LDXi, Offset)) {
836 #ifdef CAN_FIND_FREE_REGISTER_TRANSPARENTLY
837       RegClass* RC = PRA.getRegClassByID(this->getRegClassIDOfRegType(RegType));
838       OffReg = PRA.getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
839 #else
840       // Default to using register g2 for holding large offsets
841       OffReg = getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
842                                 SparcIntRegClass::g4);
843 #endif
844       assert(OffReg >= 0 && "FIXME: cpReg2MemMI cannot find an unused reg.");
845       mvec.push_back(BuildMI(V9::SETSW, 2).addZImm(Offset).addReg(OffReg));
846     }
847
848   switch (RegType) {
849   case IntRegType:
850     if (target.getInstrInfo().constantFitsInImmedField(V9::LDXi, Offset))
851       MI = BuildMI(V9::LDXi, 3).addMReg(PtrReg).addSImm(Offset).addMReg(DestReg,
852                                                                     MOTy::Def);
853     else
854       MI = BuildMI(V9::LDXr, 3).addMReg(PtrReg).addMReg(OffReg).addMReg(DestReg,
855                                                                     MOTy::Def);
856     break;
857
858   case FPSingleRegType:
859     if (target.getInstrInfo().constantFitsInImmedField(V9::LDFi, Offset))
860       MI = BuildMI(V9::LDFi, 3).addMReg(PtrReg).addSImm(Offset).addMReg(DestReg,
861                                                                     MOTy::Def);
862     else
863       MI = BuildMI(V9::LDFr, 3).addMReg(PtrReg).addMReg(OffReg).addMReg(DestReg,
864                                                                     MOTy::Def);
865     break;
866
867   case FPDoubleRegType:
868     if (target.getInstrInfo().constantFitsInImmedField(V9::LDDFi, Offset))
869       MI= BuildMI(V9::LDDFi, 3).addMReg(PtrReg).addSImm(Offset).addMReg(DestReg,
870                                                                     MOTy::Def);
871     else
872       MI= BuildMI(V9::LDDFr, 3).addMReg(PtrReg).addMReg(OffReg).addMReg(DestReg,
873                                                                     MOTy::Def);
874     break;
875
876   case IntCCRegType:
877     assert(scratchReg >= 0 && "Need scratch reg to load %ccr from memory");
878     assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
879     cpMem2RegMI(mvec, PtrReg, Offset, scratchReg, IntRegType);
880     MI = (BuildMI(V9::WRCCRr, 3)
881           .addMReg(scratchReg)
882           .addMReg(SparcIntRegClass::g0)
883           .addMReg(getUnifiedRegNum(UltraSparcRegInfo::IntCCRegClassID,
884                                     SparcIntCCRegClass::ccr), MOTy::Def));
885     break;
886     
887   case FloatCCRegType: {
888     unsigned fsrRegNum =  getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
889                                            SparcSpecialRegClass::fsr);
890     if (target.getInstrInfo().constantFitsInImmedField(V9::LDXFSRi, Offset))
891       MI = BuildMI(V9::LDXFSRi, 3).addMReg(PtrReg).addSImm(Offset)
892         .addMReg(fsrRegNum, MOTy::UseAndDef);
893     else
894       MI = BuildMI(V9::LDXFSRr, 3).addMReg(PtrReg).addMReg(OffReg)
895         .addMReg(fsrRegNum, MOTy::UseAndDef);
896     break;
897   }
898   default:
899     assert(0 && "Unknown RegType in cpMem2RegMI");
900   }
901   mvec.push_back(MI);
902 }
903
904
905 //---------------------------------------------------------------------------
906 // Generate a copy instruction to copy a value to another. Temporarily
907 // used by PhiElimination code.
908 //---------------------------------------------------------------------------
909
910
911 void
912 UltraSparcRegInfo::cpValue2Value(Value *Src, Value *Dest,
913                                  std::vector<MachineInstr*>& mvec) const {
914   int RegType = getRegTypeForDataType(Src->getType());
915   MachineInstr * MI = NULL;
916
917   switch( RegType ) {
918   case IntRegType:
919     MI = BuildMI(V9::ADDr, 3).addReg(Src).addMReg(getZeroRegNum())
920       .addRegDef(Dest);
921     break;
922   case FPSingleRegType:
923     MI = BuildMI(V9::FMOVS, 2).addReg(Src).addRegDef(Dest);
924     break;
925   case FPDoubleRegType:
926     MI = BuildMI(V9::FMOVD, 2).addReg(Src).addRegDef(Dest);
927     break;
928   default:
929     assert(0 && "Unknow RegType in CpValu2Value");
930   }
931
932   mvec.push_back(MI);
933 }
934
935
936
937 //---------------------------------------------------------------------------
938 // Print the register assigned to a LR
939 //---------------------------------------------------------------------------
940
941 void UltraSparcRegInfo::printReg(const LiveRange *LR) const {
942   unsigned RegClassID = LR->getRegClassID();
943   std::cerr << " *Node " << (LR->getUserIGNode())->getIndex();
944
945   if (!LR->hasColor()) {
946     std::cerr << " - could not find a color\n";
947     return;
948   }
949   
950   // if a color is found
951
952   std::cerr << " colored with color "<< LR->getColor();
953
954   unsigned uRegName = getUnifiedRegNum(RegClassID, LR->getColor());
955   
956   std::cerr << "[";
957   std::cerr<< getUnifiedRegName(uRegName);
958   if (RegClassID == FloatRegClassID && LR->getType() == Type::DoubleTy)
959     std::cerr << "+" << getUnifiedRegName(uRegName+1);
960   std::cerr << "]\n";
961 }