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