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