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