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