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