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