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