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