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