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