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