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