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