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