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