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