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