1 //===-- SparcRegInfo.cpp - Sparc Target Register Information --------------===//
3 // This file contains implementation of Sparc specific helper methods
4 // used for register allocation.
6 //===----------------------------------------------------------------------===//
8 #include "SparcInternals.h"
9 #include "SparcRegClassInfo.h"
10 #include "llvm/CodeGen/MachineFunction.h"
11 #include "llvm/CodeGen/MachineFunctionInfo.h"
12 #include "llvm/CodeGen/PhyRegAlloc.h"
13 #include "llvm/CodeGen/InstrSelection.h"
14 #include "llvm/CodeGen/MachineInstrBuilder.h"
15 #include "llvm/CodeGen/MachineCodeForInstruction.h"
16 #include "llvm/CodeGen/MachineInstrAnnot.h"
17 #include "llvm/CodeGen/FunctionLiveVarInfo.h" // FIXME: Remove
18 #include "../../CodeGen/RegAlloc/RegAllocCommon.h" // FIXME!
19 #include "llvm/iTerminators.h"
20 #include "llvm/iOther.h"
21 #include "llvm/Function.h"
22 #include "llvm/DerivedTypes.h"
28 UltraSparcRegInfo::UltraSparcRegInfo(const UltraSparc &tgt)
29 : TargetRegInfo(tgt), NumOfIntArgRegs(6), NumOfFloatArgRegs(32)
31 MachineRegClassArr.push_back(new SparcIntRegClass(IntRegClassID));
32 MachineRegClassArr.push_back(new SparcFloatRegClass(FloatRegClassID));
33 MachineRegClassArr.push_back(new SparcIntCCRegClass(IntCCRegClassID));
34 MachineRegClassArr.push_back(new SparcFloatCCRegClass(FloatCCRegClassID));
35 MachineRegClassArr.push_back(new SparcSpecialRegClass(SpecialRegClassID));
37 assert(SparcFloatRegClass::StartOfNonVolatileRegs == 32 &&
38 "32 Float regs are used for float arg passing");
42 // getZeroRegNum - returns the register that contains always zero.
43 // this is the unified register number
45 int UltraSparcRegInfo::getZeroRegNum() const {
46 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
47 SparcIntRegClass::g0);
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
53 unsigned UltraSparcRegInfo::getCallAddressReg() const {
54 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
55 SparcIntRegClass::o7);
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.
62 unsigned UltraSparcRegInfo::getReturnAddressReg() const {
63 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
64 SparcIntRegClass::i7);
67 // Register get name implementations...
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",
75 "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
79 const char * const SparcIntRegClass::getRegName(unsigned reg) const {
80 assert(reg < NumOfAllRegs);
81 return IntRegNames[reg];
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"
94 const char * const SparcFloatRegClass::getRegName(unsigned reg) const {
95 assert (reg < NumOfAllRegs);
96 return FloatRegNames[reg];
100 static const char * const IntCCRegNames[] = {
104 const char * const SparcIntCCRegClass::getRegName(unsigned reg) const {
106 return IntCCRegNames[reg];
109 static const char * const FloatCCRegNames[] = {
110 "fcc0", "fcc1", "fcc2", "fcc3"
113 const char * const SparcFloatCCRegClass::getRegName(unsigned reg) const {
115 return FloatCCRegNames[reg];
118 static const char * const SpecialRegNames[] = {
122 const char * const SparcSpecialRegClass::getRegName(unsigned reg) const {
124 return SpecialRegNames[reg];
127 // Get unified reg number for frame pointer
128 unsigned UltraSparcRegInfo::getFramePointer() const {
129 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
130 SparcIntRegClass::i6);
133 // Get unified reg number for stack pointer
134 unsigned UltraSparcRegInfo::getStackPointer() const {
135 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
136 SparcIntRegClass::o6);
140 //---------------------------------------------------------------------------
141 // Finds whether a call is an indirect call
142 //---------------------------------------------------------------------------
145 isVarArgsFunction(const Type *funcType) {
146 return cast<FunctionType>(cast<PointerType>(funcType)
147 ->getElementType())->isVarArg();
151 isVarArgsCall(const MachineInstr *CallMI) {
152 Value* callee = CallMI->getOperand(0).getVRegValue();
153 // const Type* funcType = isa<Function>(callee)? callee->getType()
154 // : cast<PointerType>(callee->getType())->getElementType();
155 const Type* funcType = callee->getType();
156 return isVarArgsFunction(funcType);
160 // Get the register number for the specified argument #argNo,
163 // getInvalidRegNum(), if there is no int register available for the arg.
164 // regNum, otherwise (this is NOT the unified reg. num).
165 // regClassId is set to the register class ID.
168 UltraSparcRegInfo::regNumForIntArg(bool inCallee, bool isVarArgsCall,
169 unsigned argNo, unsigned& regClassId) const
171 regClassId = IntRegClassID;
172 if (argNo >= NumOfIntArgRegs)
173 return getInvalidRegNum();
175 return argNo + (inCallee? SparcIntRegClass::i0 : SparcIntRegClass::o0);
178 // Get the register number for the specified FP argument #argNo,
179 // Use INT regs for FP args if this is a varargs call.
182 // getInvalidRegNum(), if there is no int register available for the arg.
183 // regNum, otherwise (this is NOT the unified reg. num).
184 // regClassId is set to the register class ID.
187 UltraSparcRegInfo::regNumForFPArg(unsigned regType,
188 bool inCallee, bool isVarArgsCall,
189 unsigned argNo, unsigned& regClassId) const
192 return regNumForIntArg(inCallee, isVarArgsCall, argNo, regClassId);
195 regClassId = FloatRegClassID;
196 if (regType == FPSingleRegType)
197 return (argNo*2+1 >= NumOfFloatArgRegs)?
198 getInvalidRegNum() : SparcFloatRegClass::f0 + (argNo * 2 + 1);
199 else if (regType == FPDoubleRegType)
200 return (argNo*2 >= NumOfFloatArgRegs)?
201 getInvalidRegNum() : SparcFloatRegClass::f0 + (argNo * 2);
203 assert(0 && "Illegal FP register type");
209 //---------------------------------------------------------------------------
210 // Finds the return address of a call sparc specific call instruction
211 //---------------------------------------------------------------------------
213 // The following 4 methods are used to find the RegType (SparcInternals.h)
214 // of a LiveRange, a Value, and for a given register unified reg number.
216 int UltraSparcRegInfo::getRegTypeForClassAndType(unsigned regClassID,
217 const Type* type) const
219 switch (regClassID) {
220 case IntRegClassID: return IntRegType;
221 case FloatRegClassID:
222 if (type == Type::FloatTy) return FPSingleRegType;
223 else if (type == Type::DoubleTy) return FPDoubleRegType;
224 assert(0 && "Unknown type in FloatRegClass"); return 0;
225 case IntCCRegClassID: return IntCCRegType;
226 case FloatCCRegClassID: return FloatCCRegType;
227 case SpecialRegClassID: return SpecialRegType;
228 default: assert( 0 && "Unknown reg class ID"); return 0;
232 int UltraSparcRegInfo::getRegType(const Type* type) const
234 return getRegTypeForClassAndType(getRegClassIDOfType(type), type);
237 int UltraSparcRegInfo::getRegType(const LiveRange *LR) const
239 return getRegTypeForClassAndType(LR->getRegClassID(), LR->getType());
242 int UltraSparcRegInfo::getRegType(int unifiedRegNum) const
244 if (unifiedRegNum < 32)
246 else if (unifiedRegNum < (32 + 32))
247 return FPSingleRegType;
248 else if (unifiedRegNum < (64 + 32))
249 return FPDoubleRegType;
250 else if (unifiedRegNum < (64+32+4))
251 return FloatCCRegType;
252 else if (unifiedRegNum < (64+32+4+2))
255 assert(0 && "Invalid unified register number in getRegType");
260 // To find the register class used for a specified Type
262 unsigned UltraSparcRegInfo::getRegClassIDOfType(const Type *type,
263 bool isCCReg) const {
264 Type::PrimitiveID ty = type->getPrimitiveID();
267 // FIXME: Comparing types like this isn't very safe...
268 if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
269 (ty == Type::FunctionTyID) || (ty == Type::PointerTyID) )
270 res = IntRegClassID; // sparc int reg (ty=0: void)
271 else if (ty <= Type::DoubleTyID)
272 res = FloatRegClassID; // sparc float reg class
274 //std::cerr << "TypeID: " << ty << "\n";
275 assert(0 && "Cannot resolve register class for type");
280 return res + 2; // corresponding condition code register
285 unsigned UltraSparcRegInfo::getRegClassIDOfRegType(int regType) const {
287 case IntRegType: return IntRegClassID;
288 case FPSingleRegType:
289 case FPDoubleRegType: return FloatRegClassID;
290 case IntCCRegType: return IntCCRegClassID;
291 case FloatCCRegType: return FloatCCRegClassID;
293 assert(0 && "Invalid register type in getRegClassIDOfRegType");
298 //---------------------------------------------------------------------------
299 // Suggests a register for the ret address in the RET machine instruction.
300 // We always suggest %i7 by convention.
301 //---------------------------------------------------------------------------
302 void UltraSparcRegInfo::suggestReg4RetAddr(MachineInstr *RetMI,
303 LiveRangeInfo& LRI) const {
305 assert(target.getInstrInfo().isReturn(RetMI->getOpCode()));
307 // return address is always mapped to i7 so set it immediately
308 RetMI->SetRegForOperand(0, getUnifiedRegNum(IntRegClassID,
309 SparcIntRegClass::i7));
311 // Possible Optimization:
312 // Instead of setting the color, we can suggest one. In that case,
313 // we have to test later whether it received the suggested color.
314 // In that case, a LR has to be created at the start of method.
315 // It has to be done as follows (remove the setRegVal above):
317 // MachineOperand & MO = RetMI->getOperand(0);
318 // const Value *RetAddrVal = MO.getVRegValue();
319 // assert( RetAddrVal && "LR for ret address must be created at start");
320 // LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);
321 // RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID,
322 // SparcIntRegOrdr::i7) );
326 //---------------------------------------------------------------------------
327 // Suggests a register for the ret address in the JMPL/CALL machine instr.
328 // Sparc ABI dictates that %o7 be used for this purpose.
329 //---------------------------------------------------------------------------
331 UltraSparcRegInfo::suggestReg4CallAddr(MachineInstr * CallMI,
332 LiveRangeInfo& LRI) const
334 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
335 const Value *RetAddrVal = argDesc->getReturnAddrReg();
336 assert(RetAddrVal && "INTERNAL ERROR: Return address value is required");
338 // A LR must already exist for the return address.
339 LiveRange *RetAddrLR = LRI.getLiveRangeForValue(RetAddrVal);
340 assert(RetAddrLR && "INTERNAL ERROR: No LR for return address of call!");
342 unsigned RegClassID = RetAddrLR->getRegClassID();
343 RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID, SparcIntRegClass::o7));
348 //---------------------------------------------------------------------------
349 // This method will suggest colors to incoming args to a method.
350 // According to the Sparc ABI, the first 6 incoming args are in
351 // %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
352 // If the arg is passed on stack due to the lack of regs, NOTHING will be
353 // done - it will be colored (or spilled) as a normal live range.
354 //---------------------------------------------------------------------------
355 void UltraSparcRegInfo::suggestRegs4MethodArgs(const Function *Meth,
356 LiveRangeInfo& LRI) const
358 // check if this is a varArgs function. needed for choosing regs.
359 bool isVarArgs = isVarArgsFunction(Meth->getType());
361 // for each argument. count INT and FP arguments separately.
362 unsigned argNo=0, intArgNo=0, fpArgNo=0;
363 for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
364 I != E; ++I, ++argNo) {
366 LiveRange *LR = LRI.getLiveRangeForValue(I);
367 assert(LR && "No live range found for method arg");
369 unsigned regType = getRegType(LR);
370 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg (unused)
372 int regNum = (regType == IntRegType)
373 ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
374 argNo, regClassIDOfArgReg)
375 : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
376 argNo, regClassIDOfArgReg);
378 if(regNum != getInvalidRegNum())
379 LR->setSuggestedColor(regNum);
384 //---------------------------------------------------------------------------
385 // This method is called after graph coloring to move incoming args to
386 // the correct hardware registers if they did not receive the correct
387 // (suggested) color through graph coloring.
388 //---------------------------------------------------------------------------
389 void UltraSparcRegInfo::colorMethodArgs(const Function *Meth,
391 AddedInstrns *FirstAI) const {
393 // check if this is a varArgs function. needed for choosing regs.
394 bool isVarArgs = isVarArgsFunction(Meth->getType());
398 // for each argument. count INT and FP arguments separately.
399 unsigned argNo=0, intArgNo=0, fpArgNo=0;
400 for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
401 I != E; ++I, ++argNo) {
403 LiveRange *LR = LRI.getLiveRangeForValue(I);
404 assert( LR && "No live range found for method arg");
406 unsigned regType = getRegType(LR);
407 unsigned RegClassID = LR->getRegClassID();
409 // Find whether this argument is coming in a register (if not, on stack)
410 // Also find the correct register the argument must use (UniArgReg)
412 bool isArgInReg = false;
413 unsigned UniArgReg = getInvalidRegNum(); // reg that LR MUST be colored with
414 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
416 int regNum = (regType == IntRegType)
417 ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
418 argNo, regClassIDOfArgReg)
419 : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
420 argNo, regClassIDOfArgReg);
422 if(regNum != getInvalidRegNum()) {
424 UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
427 if( LR->hasColor() ) { // if this arg received a register
429 unsigned UniLRReg = getUnifiedRegNum( RegClassID, LR->getColor() );
431 // if LR received the correct color, nothing to do
433 if( UniLRReg == UniArgReg )
436 // We are here because the LR did not receive the suggested
437 // but LR received another register.
438 // Now we have to copy the %i reg (or stack pos of arg)
439 // to the register the LR was colored with.
441 // if the arg is coming in UniArgReg register, it MUST go into
442 // the UniLRReg register
445 if( regClassIDOfArgReg != RegClassID ) {
446 assert(0 && "This could should work but it is not tested yet");
448 // It is a variable argument call: the float reg must go in a %o reg.
449 // We have to move an int reg to a float reg via memory.
452 RegClassID == FloatRegClassID &&
453 regClassIDOfArgReg == IntRegClassID &&
454 "This should only be an Int register for an FP argument");
456 int TmpOff = MachineFunction::get(Meth).getInfo()->pushTempValue(
457 getSpilledRegSize(regType));
458 cpReg2MemMI(FirstAI->InstrnsBefore,
459 UniArgReg, getFramePointer(), TmpOff, IntRegType);
461 cpMem2RegMI(FirstAI->InstrnsBefore,
462 getFramePointer(), TmpOff, UniLRReg, regType);
465 cpReg2RegMI(FirstAI->InstrnsBefore, UniArgReg, UniLRReg, regType);
470 // Now the arg is coming on stack. Since the LR recieved a register,
471 // we just have to load the arg on stack into that register
473 const TargetFrameInfo& frameInfo = target.getFrameInfo();
475 frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
478 // float arguments on stack are right justified so adjust the offset!
479 // int arguments are also right justified but they are always loaded as
480 // a full double-word so the offset does not need to be adjusted.
481 if (regType == FPSingleRegType) {
482 unsigned argSize = target.getTargetData().getTypeSize(LR->getType());
483 unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
484 assert(argSize <= slotSize && "Insufficient slot size!");
485 offsetFromFP += slotSize - argSize;
488 cpMem2RegMI(FirstAI->InstrnsBefore,
489 getFramePointer(), offsetFromFP, UniLRReg, regType);
492 } // if LR received a color
496 // Now, the LR did not receive a color. But it has a stack offset for
498 // So, if the arg is coming in UniArgReg register, we can just move
499 // that on to the stack pos of LR
503 if( regClassIDOfArgReg != RegClassID ) {
505 "FP arguments to a varargs function should be explicitly "
506 "copied to/from int registers by instruction selection!");
508 // It must be a float arg for a variable argument call, which
509 // must come in a %o reg. Move the int reg to the stack.
511 assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
512 "This should only be an Int register for an FP argument");
514 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
515 getFramePointer(), LR->getSpillOffFromFP(), IntRegType);
518 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
519 getFramePointer(), LR->getSpillOffFromFP(), regType);
525 // Now the arg is coming on stack. Since the LR did NOT
526 // recieved a register as well, it is allocated a stack position. We
527 // can simply change the stack position of the LR. We can do this,
528 // since this method is called before any other method that makes
529 // uses of the stack pos of the LR (e.g., updateMachineInstr)
531 const TargetFrameInfo& frameInfo = target.getFrameInfo();
533 frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
536 // FP arguments on stack are right justified so adjust offset!
537 // int arguments are also right justified but they are always loaded as
538 // a full double-word so the offset does not need to be adjusted.
539 if (regType == FPSingleRegType) {
540 unsigned argSize = target.getTargetData().getTypeSize(LR->getType());
541 unsigned slotSize = frameInfo.getSizeOfEachArgOnStack();
542 assert(argSize <= slotSize && "Insufficient slot size!");
543 offsetFromFP += slotSize - argSize;
546 LR->modifySpillOffFromFP( offsetFromFP );
551 } // for each incoming argument
557 //---------------------------------------------------------------------------
558 // This method is called before graph coloring to suggest colors to the
559 // outgoing call args and the return value of the call.
560 //---------------------------------------------------------------------------
561 void UltraSparcRegInfo::suggestRegs4CallArgs(MachineInstr *CallMI,
562 LiveRangeInfo& LRI) const {
563 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
565 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
567 suggestReg4CallAddr(CallMI, LRI);
569 // First color the return value of the call instruction, if any.
570 // The return value will be in %o0 if the value is an integer type,
571 // or in %f0 if the value is a float type.
573 if (const Value *RetVal = argDesc->getReturnValue()) {
574 LiveRange *RetValLR = LRI.getLiveRangeForValue(RetVal);
575 assert(RetValLR && "No LR for return Value of call!");
577 unsigned RegClassID = RetValLR->getRegClassID();
579 // now suggest a register depending on the register class of ret arg
580 if( RegClassID == IntRegClassID )
581 RetValLR->setSuggestedColor(SparcIntRegClass::o0);
582 else if (RegClassID == FloatRegClassID )
583 RetValLR->setSuggestedColor(SparcFloatRegClass::f0 );
584 else assert( 0 && "Unknown reg class for return value of call\n");
587 // Now suggest colors for arguments (operands) of the call instruction.
588 // Colors are suggested only if the arg number is smaller than the
589 // the number of registers allocated for argument passing.
590 // Now, go thru call args - implicit operands of the call MI
592 unsigned NumOfCallArgs = argDesc->getNumArgs();
594 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
595 i < NumOfCallArgs; ++i, ++argNo) {
597 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
599 // get the LR of call operand (parameter)
600 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
602 continue; // no live ranges for constants and labels
604 unsigned regType = getRegType(LR);
605 unsigned regClassIDOfArgReg = BadRegClass; // chosen reg class (unused)
607 // Choose a register for this arg depending on whether it is
608 // an INT or FP value. Here we ignore whether or not it is a
609 // varargs calls, because FP arguments will be explicitly copied
610 // to an integer Value and handled under (argCopy != NULL) below.
611 int regNum = (regType == IntRegType)
612 ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
613 argNo, regClassIDOfArgReg)
614 : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
615 argNo, regClassIDOfArgReg);
617 // If a register could be allocated, use it.
618 // If not, do NOTHING as this will be colored as a normal value.
619 if(regNum != getInvalidRegNum())
620 LR->setSuggestedColor(regNum);
622 #ifdef CANNOT_PRECOPY_CALLARGS
623 // Repeat for the second copy of the argument, which would be
624 // an FP argument being passed to a function with no prototype
625 const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
628 assert(regType != IntRegType && argCopy->getType()->isInteger()
629 && "Must be passing copy of FP argument in int register");
630 int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
631 argNo, regClassIDOfArgReg);
632 assert(copyRegNum != getInvalidRegNum());
633 LiveRange *const copyLR = LRI.getLiveRangeForValue(argCopy);
634 copyLR->setSuggestedColor(copyRegNum);
638 } // for all call arguments
643 //---------------------------------------------------------------------------
644 // Helper method for UltraSparcRegInfo::colorCallArgs().
645 //---------------------------------------------------------------------------
648 UltraSparcRegInfo::InitializeOutgoingArg(MachineInstr* CallMI,
649 AddedInstrns *CallAI,
650 PhyRegAlloc &PRA, LiveRange* LR,
651 unsigned regType, unsigned RegClassID,
652 int UniArgRegOrNone, unsigned argNo,
653 std::vector<MachineInstr*> &AddedInstrnsBefore)
656 assert(0 && "Should never get here because we are now using precopying!");
659 bool isArgInReg = false;
660 unsigned UniArgReg = BadRegClass; // unused unless initialized below
661 if (UniArgRegOrNone != getInvalidRegNum())
664 UniArgReg = (unsigned) UniArgRegOrNone;
667 if (LR->hasColor()) {
668 unsigned UniLRReg = getUnifiedRegNum(RegClassID, LR->getColor());
670 // if LR received the correct color, nothing to do
671 if( isArgInReg && UniArgReg == UniLRReg )
674 // The LR is allocated to a register UniLRReg and must be copied
675 // to UniArgReg or to the stack slot.
678 // Copy UniLRReg to UniArgReg
679 cpReg2RegMI(AddedInstrnsBefore, UniLRReg, UniArgReg, regType);
682 // Copy UniLRReg to the stack to pass the arg on stack.
683 const TargetFrameInfo& frameInfo = target.getFrameInfo();
684 int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
685 cpReg2MemMI(CallAI->InstrnsBefore,
686 UniLRReg, getStackPointer(), argOffset, regType);
689 } else { // LR is not colored (i.e., spilled)
692 // Insert a load instruction to load the LR to UniArgReg
693 cpMem2RegMI(AddedInstrnsBefore, getFramePointer(),
694 LR->getSpillOffFromFP(), UniArgReg, regType);
695 // Now add the instruction
699 // Now, we have to pass the arg on stack. Since LR also did NOT
700 // receive a register we have to move an argument in memory to
701 // outgoing parameter on stack.
702 // Use TReg to load and store the value.
703 // Use TmpOff to save TReg, since that may have a live value.
705 int TReg = PRA.getUniRegNotUsedByThisInst(LR->getRegClass(), CallMI);
706 int TmpOff = PRA.MF.getInfo()->
707 pushTempValue(getSpilledRegSize(getRegType(LR)));
708 const TargetFrameInfo& frameInfo = target.getFrameInfo();
709 int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
711 MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
714 // (1) Save TReg on stack
715 // (2) Load LR value into TReg from stack pos of LR
716 // (3) Store Treg on outgoing Arg pos on stack
717 // (4) Load the old value of TReg from stack to TReg (restore it)
720 // When reverse pointers in MahineInstr are introduced:
721 // Call PRA.getUnusedRegAtMI(....) to get an unused reg. Step 1 is
722 // needed only if this fails. Currently, we cannot call the
723 // above method since we cannot find LVSetBefore without the BB
725 // NOTE: We directly add to CallAI->InstrnsBefore instead of adding to
726 // AddedInstrnsBefore since these instructions must not be reordered.
727 cpReg2MemMI(CallAI->InstrnsBefore,
728 TReg, getFramePointer(), TmpOff, regType);
729 cpMem2RegMI(CallAI->InstrnsBefore,
730 getFramePointer(), LR->getSpillOffFromFP(), TReg, regType);
731 cpReg2MemMI(CallAI->InstrnsBefore,
732 TReg, getStackPointer(), argOffset, regType);
733 cpMem2RegMI(CallAI->InstrnsBefore,
734 getFramePointer(), TmpOff, TReg, regType);
739 //---------------------------------------------------------------------------
740 // After graph coloring, we have call this method to see whehter the return
741 // value and the call args received the correct colors. If not, we have
742 // to instert copy instructions.
743 //---------------------------------------------------------------------------
745 void UltraSparcRegInfo::colorCallArgs(MachineInstr *CallMI,
747 AddedInstrns *CallAI,
749 const BasicBlock *BB) const {
751 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
753 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
755 // First color the return value of the call.
756 // If there is a LR for the return value, it means this
757 // method returns a value
761 const Value *RetVal = argDesc->getReturnValue();
764 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
765 assert(RetValLR && "ERROR: No LR for non-void return value");
767 // Mark the return value register as used by this instruction
768 unsigned RegClassID = RetValLR->getRegClassID();
769 unsigned CorrectCol = (RegClassID == IntRegClassID
770 ? (unsigned) SparcIntRegClass::o0
771 : (unsigned) SparcFloatRegClass::f0);
773 CallMI->insertUsedReg(getUnifiedRegNum(RegClassID, CorrectCol));
775 #ifdef CANNOT_PRECOPY_CALLARGS
776 // unified number for CorrectCol
777 unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
780 // if the LR received the correct color, NOTHING to do
781 bool recvCorrectColor = (RetValLR->hasColor()
782 ? RetValLR->getColor() == CorrectCol : false);
784 // if we didn't receive the correct color for some reason,
785 // put copy instruction
786 if( !recvCorrectColor ) {
788 unsigned regType = getRegType(RetValLR);
790 if( RetValLR->hasColor() ) {
792 unsigned UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
794 // the return value is coming in UniRetReg but has to go into
797 cpReg2RegMI(CallAI->InstrnsAfter, UniRetReg, UniRetLRReg, regType);
802 // if the LR did NOT receive a color, we have to move the return
803 // value coming in UniRetReg to the stack pos of spilled LR
805 cpReg2MemMI(CallAI->InstrnsAfter, UniRetReg,
806 getFramePointer(),RetValLR->getSpillOffFromFP(), regType);
808 } // the LR didn't receive the suggested color
811 } // if there a return value
814 //-------------------------------------------
815 // Now color all args of the call instruction
816 //-------------------------------------------
818 std::vector<MachineInstr*> AddedInstrnsBefore;
820 unsigned NumOfCallArgs = argDesc->getNumArgs();
822 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
823 i < NumOfCallArgs; ++i, ++argNo) {
825 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
826 unsigned regType = getRegType(CallArg->getType());
828 // Find whether this argument is coming in a register (if not, on stack)
829 // Also find the correct register the argument must use (UniArgReg)
831 bool isArgInReg = false;
832 int UniArgReg = getInvalidRegNum(); // reg that LR MUST be colored with
833 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
835 // Find the register that must be used for this arg, depending on
836 // whether it is an INT or FP value. Here we ignore whether or not it
837 // is a varargs calls, because FP arguments will be explicitly copied
838 // to an integer Value and handled under (argCopy != NULL) below.
840 int regNum = (regType == IntRegType)
841 ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
842 argNo, regClassIDOfArgReg)
843 : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
844 argNo, regClassIDOfArgReg);
846 if (regNum != getInvalidRegNum()) {
848 UniArgReg = getUnifiedRegNum(regClassIDOfArgReg, regNum);
849 CallMI->insertUsedReg(UniArgReg); // mark the reg as used
852 #ifdef CANNOT_PRECOPY_CALLARGS
854 // Get the LR of call operand (parameter). There must be one because
855 // all args (even constants) must be defined before.
856 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
857 assert(LR && "NO LR for call arg");
859 unsigned RegClassID = getRegClassIDOfType(CallArg->getType());
861 if (regNum != getInvalidRegNum()) {
862 assert(regClassIDOfArgReg == RegClassID &&
863 "Moving values between reg classes must happen during selection");
866 InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
867 UniArgReg, argNo, AddedInstrnsBefore);
870 // Repeat for the second copy of the argument, which would be
871 // an FP argument being passed to a function with no prototype.
872 // It may either be passed as a copy in an integer register
873 // (in argCopy), or on the stack (useStackSlot).
874 int argCopyReg = argDesc->getArgInfo(i).getArgCopy();
875 if (argCopyReg != TargetRegInfo::getInvalidRegNum())
877 CallMI->insertUsedReg(argCopyReg); // mark the reg as used
879 #ifdef CANNOT_PRECOPY_CALLARGS
880 assert(regType != IntRegType && argCopy->getType()->isInteger()
881 && "Must be passing copy of FP argument in int register");
883 unsigned copyRegClassID = getRegClassIDOfType(argCopy->getType());
884 unsigned copyRegType = getRegType(argCopy->getType());
886 int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
887 argNo, regClassIDOfArgReg);
888 assert(copyRegNum != getInvalidRegNum());
889 assert(regClassIDOfArgReg == copyRegClassID &&
890 "Moving values between reg classes must happen during selection");
892 InitializeOutgoingArg(CallMI, CallAI, PRA,
893 LRI.getLiveRangeForValue(argCopy), copyRegType,
894 copyRegClassID, copyRegNum, argNo,
899 #ifdef CANNOT_PRECOPY_CALLARGS
900 if (regNum != getInvalidRegNum() &&
901 argDesc->getArgInfo(i).usesStackSlot())
903 // Pass the argument via the stack in addition to regNum
904 assert(regType != IntRegType && "Passing an integer arg. twice?");
905 assert(!argCopy && "Passing FP arg in FP reg, INT reg, and stack?");
906 InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
907 getInvalidRegNum(), argNo, AddedInstrnsBefore);
910 } // for each parameter in call instruction
912 // If we added any instruction before the call instruction, verify
913 // that they are in the proper order and if not, reorder them
915 std::vector<MachineInstr*> ReorderedVec;
916 if (!AddedInstrnsBefore.empty()) {
919 std::cerr << "\nCalling reorder with instrns: \n";
920 for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
921 std::cerr << *(AddedInstrnsBefore[i]);
924 OrderAddedInstrns(AddedInstrnsBefore, ReorderedVec, PRA);
925 assert(ReorderedVec.size() >= AddedInstrnsBefore.size()
926 && "Dropped some instructions when reordering!");
929 std::cerr << "\nAfter reordering instrns: \n";
930 for(unsigned i = 0; i < ReorderedVec.size(); i++)
931 std::cerr << *ReorderedVec[i];
935 // Now insert caller saving code for this call instruction
937 insertCallerSavingCode(CallAI->InstrnsBefore, CallAI->InstrnsAfter,
940 // Then insert the final reordered code for the call arguments.
942 for(unsigned i=0; i < ReorderedVec.size(); i++)
943 CallAI->InstrnsBefore.push_back( ReorderedVec[i] );
946 // Temporary sanity checking code to detect whether the same machine
947 // instruction is ever inserted twice before/after a call.
948 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
950 std::set<const MachineInstr*> instrsSeen;
951 for (int i = 0, N = CallAI->InstrnsBefore.size(); i < N; ++i) {
952 assert(instrsSeen.find(CallAI->InstrnsBefore[i]) == instrsSeen.end() &&
953 "Duplicate machine instruction in InstrnsBefore!");
954 instrsSeen.insert(CallAI->InstrnsBefore[i]);
956 for (int i = 0, N = CallAI->InstrnsAfter.size(); i < N; ++i) {
957 assert(instrsSeen.find(CallAI->InstrnsAfter[i]) == instrsSeen.end() &&
958 "Duplicate machine instruction in InstrnsBefore/After!");
959 instrsSeen.insert(CallAI->InstrnsAfter[i]);
964 //---------------------------------------------------------------------------
965 // this method is called for an LLVM return instruction to identify which
966 // values will be returned from this method and to suggest colors.
967 //---------------------------------------------------------------------------
968 void UltraSparcRegInfo::suggestReg4RetValue(MachineInstr *RetMI,
969 LiveRangeInfo &LRI) const {
971 assert( (target.getInstrInfo()).isReturn( RetMI->getOpCode() ) );
973 suggestReg4RetAddr(RetMI, LRI);
975 // To find the return value (if any), we can get the LLVM return instr.
976 // from the return address register, which is the first operand
977 Value* tmpI = RetMI->getOperand(0).getVRegValue();
978 ReturnInst* retI=cast<ReturnInst>(cast<TmpInstruction>(tmpI)->getOperand(0));
979 if (const Value *RetVal = retI->getReturnValue())
980 if (LiveRange *const LR = LRI.getLiveRangeForValue(RetVal))
981 LR->setSuggestedColor(LR->getRegClassID() == IntRegClassID
982 ? (unsigned) SparcIntRegClass::i0
983 : (unsigned) SparcFloatRegClass::f0);
988 //---------------------------------------------------------------------------
989 // Colors the return value of a method to %i0 or %f0, if possible. If it is
990 // not possilbe to directly color the LR, insert a copy instruction to move
991 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we
992 // have to put a load instruction.
993 //---------------------------------------------------------------------------
994 void UltraSparcRegInfo::colorRetValue(MachineInstr *RetMI,
996 AddedInstrns *RetAI) const {
998 assert((target.getInstrInfo()).isReturn( RetMI->getOpCode()));
1000 // To find the return value (if any), we can get the LLVM return instr.
1001 // from the return address register, which is the first operand
1002 Value* tmpI = RetMI->getOperand(0).getVRegValue();
1003 ReturnInst* retI=cast<ReturnInst>(cast<TmpInstruction>(tmpI)->getOperand(0));
1004 if (const Value *RetVal = retI->getReturnValue()) {
1006 unsigned RegClassID = getRegClassIDOfType(RetVal->getType());
1007 unsigned regType = getRegType(RetVal->getType());
1008 unsigned CorrectCol = (RegClassID == IntRegClassID
1009 ? (unsigned) SparcIntRegClass::i0
1010 : (unsigned) SparcFloatRegClass::f0);
1012 // convert to unified number
1013 unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
1015 // Mark the register as used by this instruction
1016 RetMI->insertUsedReg(UniRetReg);
1018 #ifdef CANNOT_PRECOPY_CALLARGS
1019 LiveRange *LR = LRI.getLiveRangeForValue(RetVal);
1020 assert(LR && "No LR for return value of non-void method?");
1022 if (LR->hasColor()) {
1023 // if the LR received the correct color, NOTHING to do
1024 if (LR->getColor() == CorrectCol)
1027 // We are here because the LR was allocated a register
1028 // It may be the suggested register or not
1030 // copy the LR of retun value to i0 or f0
1032 unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
1034 // the LR received UniLRReg but must be colored with UniRetReg
1035 // to pass as the return value
1036 cpReg2RegMI(RetAI->InstrnsBefore, UniLRReg, UniRetReg, regType);
1038 else { // if the LR is spilled
1039 cpMem2RegMI(RetAI->InstrnsBefore, getFramePointer(),
1040 LR->getSpillOffFromFP(), UniRetReg, regType);
1041 //std::cerr << "\nCopied the return value from stack\n";
1045 } // if there is a return value
1049 //---------------------------------------------------------------------------
1050 // Check if a specified register type needs a scratch register to be
1051 // copied to/from memory. If it does, the reg. type that must be used
1052 // for scratch registers is returned in scratchRegType.
1054 // Only the int CC register needs such a scratch register.
1055 // The FP CC registers can (and must) be copied directly to/from memory.
1056 //---------------------------------------------------------------------------
1059 UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
1060 int& scratchRegType) const
1062 if (RegType == IntCCRegType)
1064 scratchRegType = IntRegType;
1070 //---------------------------------------------------------------------------
1071 // Copy from a register to register. Register number must be the unified
1073 //---------------------------------------------------------------------------
1076 UltraSparcRegInfo::cpReg2RegMI(std::vector<MachineInstr*>& mvec,
1079 int RegType) const {
1080 assert( ((int)SrcReg != getInvalidRegNum()) &&
1081 ((int)DestReg != getInvalidRegNum()) &&
1082 "Invalid Register");
1084 MachineInstr * MI = NULL;
1089 if (getRegType(DestReg) == IntRegType) {
1090 // copy intCC reg to int reg
1091 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1092 MI = BuildMI(V9::RDCCR, 2).addMReg(SrcReg+1).addMReg(DestReg,MOTy::Def);
1094 // copy int reg to intCC reg
1095 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1096 assert(getRegType(SrcReg) == IntRegType
1097 && "Can only copy CC reg to/from integer reg");
1098 MI = BuildMI(V9::WRCCRr, 3).addMReg(SrcReg)
1099 .addMReg(SparcIntRegClass::g0).addMReg(DestReg+1, MOTy::Def);
1103 case FloatCCRegType:
1104 assert(0 && "Cannot copy FPCC register to any other register");
1108 MI = BuildMI(V9::ADDr, 3).addMReg(SrcReg).addMReg(getZeroRegNum())
1109 .addMReg(DestReg, MOTy::Def);
1112 case FPSingleRegType:
1113 MI = BuildMI(V9::FMOVS, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
1116 case FPDoubleRegType:
1117 MI = BuildMI(V9::FMOVD, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
1121 assert(0 && "Unknown RegType");
1129 //---------------------------------------------------------------------------
1130 // Copy from a register to memory (i.e., Store). Register number must
1131 // be the unified register number
1132 //---------------------------------------------------------------------------
1136 UltraSparcRegInfo::cpReg2MemMI(std::vector<MachineInstr*>& mvec,
1138 unsigned DestPtrReg,
1139 int Offset, int RegType,
1140 int scratchReg) const {
1141 MachineInstr * MI = NULL;
1144 assert(target.getInstrInfo().constantFitsInImmedField(V9::STXi, Offset));
1145 MI = BuildMI(V9::STXi,3).addMReg(SrcReg).addMReg(DestPtrReg)
1149 case FPSingleRegType:
1150 assert(target.getInstrInfo().constantFitsInImmedField(V9::STFi, Offset));
1151 MI = BuildMI(V9::STFi, 3).addMReg(SrcReg).addMReg(DestPtrReg)
1155 case FPDoubleRegType:
1156 assert(target.getInstrInfo().constantFitsInImmedField(V9::STDFi, Offset));
1157 MI = BuildMI(V9::STDFi,3).addMReg(SrcReg).addMReg(DestPtrReg)
1162 assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
1163 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1165 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1166 MI = BuildMI(V9::RDCCR, 2).addMReg(SrcReg+1).addMReg(scratchReg, MOTy::Def);
1169 cpReg2MemMI(mvec, scratchReg, DestPtrReg, Offset, IntRegType);
1172 case FloatCCRegType: {
1173 assert(target.getInstrInfo().constantFitsInImmedField(V9::STXFSRi, Offset));
1174 unsigned fsrRegNum = getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
1175 SparcSpecialRegClass::fsr);
1176 MI = BuildMI(V9::STXFSRi, 3)
1177 .addMReg(fsrRegNum).addMReg(DestPtrReg).addSImm(Offset);
1181 assert(0 && "Unknown RegType in cpReg2MemMI");
1187 //---------------------------------------------------------------------------
1188 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1190 //---------------------------------------------------------------------------
1194 UltraSparcRegInfo::cpMem2RegMI(std::vector<MachineInstr*>& mvec,
1199 int scratchReg) const {
1200 MachineInstr * MI = NULL;
1203 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDXi, Offset));
1204 MI = BuildMI(V9::LDXi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1205 .addMReg(DestReg, MOTy::Def);
1208 case FPSingleRegType:
1209 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDFi, Offset));
1210 MI = BuildMI(V9::LDFi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1211 .addMReg(DestReg, MOTy::Def);
1214 case FPDoubleRegType:
1215 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDDFi, Offset));
1216 MI = BuildMI(V9::LDDFi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1217 .addMReg(DestReg, MOTy::Def);
1221 assert(scratchReg >= 0 && "Need scratch reg to load %ccr from memory");
1222 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1223 cpMem2RegMI(mvec, SrcPtrReg, Offset, scratchReg, IntRegType);
1225 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1226 MI = BuildMI(V9::WRCCRr, 3).addMReg(scratchReg)
1227 .addMReg(SparcIntRegClass::g0).addMReg(DestReg+1,MOTy::Def);
1230 case FloatCCRegType: {
1231 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDXFSRi, Offset));
1232 unsigned fsrRegNum = getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
1233 SparcSpecialRegClass::fsr);
1234 MI = BuildMI(V9::LDXFSRi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1235 .addMReg(fsrRegNum, MOTy::UseAndDef);
1239 assert(0 && "Unknown RegType in cpMem2RegMI");
1245 //---------------------------------------------------------------------------
1246 // Generate a copy instruction to copy a value to another. Temporarily
1247 // used by PhiElimination code.
1248 //---------------------------------------------------------------------------
1252 UltraSparcRegInfo::cpValue2Value(Value *Src, Value *Dest,
1253 std::vector<MachineInstr*>& mvec) const {
1254 int RegType = getRegType(Src->getType());
1255 MachineInstr * MI = NULL;
1259 MI = BuildMI(V9::ADDr, 3).addReg(Src).addMReg(getZeroRegNum())
1262 case FPSingleRegType:
1263 MI = BuildMI(V9::FMOVS, 2).addReg(Src).addRegDef(Dest);
1265 case FPDoubleRegType:
1266 MI = BuildMI(V9::FMOVD, 2).addReg(Src).addRegDef(Dest);
1269 assert(0 && "Unknow RegType in CpValu2Value");
1280 //----------------------------------------------------------------------------
1281 // This method inserts caller saving/restoring instructons before/after
1282 // a call machine instruction. The caller saving/restoring instructions are
1285 // ** caller saving instructions
1286 // other instructions inserted for the call by ColorCallArg
1288 // other instructions inserted for the call ColorCallArg
1289 // ** caller restoring instructions
1291 //----------------------------------------------------------------------------
1295 UltraSparcRegInfo::insertCallerSavingCode
1296 (std::vector<MachineInstr*> &instrnsBefore,
1297 std::vector<MachineInstr*> &instrnsAfter,
1298 MachineInstr *CallMI,
1299 const BasicBlock *BB,
1300 PhyRegAlloc &PRA) const
1302 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
1304 // has set to record which registers were saved/restored
1306 hash_set<unsigned> PushedRegSet;
1308 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
1310 // Now check if the call has a return value (using argDesc) and if so,
1311 // find the LR of the TmpInstruction representing the return value register.
1312 // (using the last or second-last *implicit operand* of the call MI).
1313 // Insert it to to the PushedRegSet since we must not save that register
1314 // and restore it after the call.
1315 // We do this because, we look at the LV set *after* the instruction
1316 // to determine, which LRs must be saved across calls. The return value
1317 // of the call is live in this set - but we must not save/restore it.
1319 if (const Value *origRetVal = argDesc->getReturnValue()) {
1320 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
1321 (argDesc->getIndirectFuncPtr()? 1 : 2));
1322 const TmpInstruction* tmpRetVal =
1323 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
1324 assert(tmpRetVal->getOperand(0) == origRetVal &&
1325 tmpRetVal->getType() == origRetVal->getType() &&
1326 "Wrong implicit ref?");
1327 LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( tmpRetVal );
1328 assert(RetValLR && "No LR for RetValue of call");
1330 if (RetValLR->hasColor())
1331 PushedRegSet.insert(getUnifiedRegNum(RetValLR->getRegClassID(),
1332 RetValLR->getColor()));
1335 const ValueSet &LVSetAft = PRA.LVI->getLiveVarSetAfterMInst(CallMI, BB);
1336 ValueSet::const_iterator LIt = LVSetAft.begin();
1338 // for each live var in live variable set after machine inst
1339 for( ; LIt != LVSetAft.end(); ++LIt) {
1341 // get the live range corresponding to live var
1342 LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );
1344 // LR can be null if it is a const since a const
1345 // doesn't have a dominating def - see Assumptions above
1348 if( LR->hasColor() ) {
1350 unsigned RCID = LR->getRegClassID();
1351 unsigned Color = LR->getColor();
1353 if ( isRegVolatile(RCID, Color) ) {
1355 // if the value is in both LV sets (i.e., live before and after
1356 // the call machine instruction)
1358 unsigned Reg = getUnifiedRegNum(RCID, Color);
1360 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1362 // if we haven't already pushed that register
1364 unsigned RegType = getRegType(LR);
1366 // Now get two instructions - to push on stack and pop from stack
1367 // and add them to InstrnsBefore and InstrnsAfter of the
1371 PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1373 //---- Insert code for pushing the reg on stack ----------
1375 std::vector<MachineInstr*> AdIBef, AdIAft;
1377 // We may need a scratch register to copy the saved value
1378 // to/from memory. This may itself have to insert code to
1379 // free up a scratch register. Any such code should go before
1380 // the save code. The scratch register, if any, is by default
1381 // temporary and not "used" by the instruction unless the
1382 // copy code itself decides to keep the value in the scratch reg.
1383 int scratchRegType = -1;
1384 int scratchReg = -1;
1385 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1386 { // Find a register not live in the LVSet before CallMI
1387 const ValueSet &LVSetBef =
1388 PRA.LVI->getLiveVarSetBeforeMInst(CallMI, BB);
1389 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetBef,
1390 CallMI, AdIBef, AdIAft);
1391 assert(scratchReg != getInvalidRegNum());
1394 if (AdIBef.size() > 0)
1395 instrnsBefore.insert(instrnsBefore.end(),
1396 AdIBef.begin(), AdIBef.end());
1398 cpReg2MemMI(instrnsBefore, Reg,getFramePointer(),StackOff,RegType,
1401 if (AdIAft.size() > 0)
1402 instrnsBefore.insert(instrnsBefore.end(),
1403 AdIAft.begin(), AdIAft.end());
1405 //---- Insert code for popping the reg from the stack ----------
1410 // We may need a scratch register to copy the saved value
1411 // from memory. This may itself have to insert code to
1412 // free up a scratch register. Any such code should go
1413 // after the save code. As above, scratch is not marked "used".
1415 scratchRegType = -1;
1417 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1418 { // Find a register not live in the LVSet after CallMI
1419 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetAft,
1420 CallMI, AdIBef, AdIAft);
1421 assert(scratchReg != getInvalidRegNum());
1424 if (AdIBef.size() > 0)
1425 instrnsAfter.insert(instrnsAfter.end(),
1426 AdIBef.begin(), AdIBef.end());
1428 cpMem2RegMI(instrnsAfter, getFramePointer(), StackOff,Reg,RegType,
1431 if (AdIAft.size() > 0)
1432 instrnsAfter.insert(instrnsAfter.end(),
1433 AdIAft.begin(), AdIAft.end());
1435 PushedRegSet.insert(Reg);
1438 std::cerr << "\nFor call inst:" << *CallMI;
1439 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
1440 for_each(instrnsBefore.begin(), instrnsBefore.end(),
1441 std::mem_fun(&MachineInstr::dump));
1442 std::cerr << " -and After:\n\t ";
1443 for_each(instrnsAfter.begin(), instrnsAfter.end(),
1444 std::mem_fun(&MachineInstr::dump));
1446 } // if not already pushed
1448 } // if LR has a volatile color
1450 } // if LR has color
1452 } // if there is a LR for Var
1454 } // for each value in the LV set after instruction
1458 //---------------------------------------------------------------------------
1459 // Print the register assigned to a LR
1460 //---------------------------------------------------------------------------
1462 void UltraSparcRegInfo::printReg(const LiveRange *LR) const {
1463 unsigned RegClassID = LR->getRegClassID();
1464 std::cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1466 if (!LR->hasColor()) {
1467 std::cerr << " - could not find a color\n";
1471 // if a color is found
1473 std::cerr << " colored with color "<< LR->getColor();
1475 unsigned uRegName = getUnifiedRegNum(RegClassID, LR->getColor());
1478 std::cerr<< getUnifiedRegName(uRegName);
1479 if (RegClassID == FloatRegClassID && LR->getType() == Type::DoubleTy)
1480 std::cerr << "+" << getUnifiedRegName(uRegName+1);
1484 //---------------------------------------------------------------------------
1485 // This method examines instructions inserted by RegAlloc code before a
1486 // machine instruction to detect invalid orders that destroy values before
1487 // they are used. If it detects such conditions, it reorders the instructions.
1489 // The unordered instructions come in the UnordVec. These instructions are
1490 // instructions inserted by RegAlloc. All such instruction MUST have
1491 // their USES BEFORE THE DEFS after reordering.
1493 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1494 // this method is called.
1496 // This method uses two vectors for efficiency in accessing
1498 // Since instructions are inserted in RegAlloc, this assumes that the
1499 // first operand is the source reg and the last operand is the dest reg.
1500 // It also does not consider operands that are both use and def.
1502 // All the uses are before THE def to a register
1503 //---------------------------------------------------------------------------
1505 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr*> &UnordVec,
1506 std::vector<MachineInstr*> &OrdVec,
1507 PhyRegAlloc &PRA) const{
1510 Problem: We can have instructions inserted by RegAlloc like
1512 2. add %oy %g0 %oz, where z!=x or z==x
1514 This is wrong since %oy used by 2 is overwritten by 1
1517 We re-order the instructions so that the uses are before the defs
1522 for each instruction 'DefInst' in the UnOrdVec
1523 for each instruction 'UseInst' that follows the DefInst
1524 if the reg defined by DefInst is used by UseInst
1525 mark DefInst as not movable in this iteration
1526 If DefInst is not marked as not-movable, move DefInst to OrdVec
1527 while all instructions in DefInst are moved to OrdVec
1529 For moving, we call the move2OrdVec(). It checks whether there is a def
1530 in it for the uses in the instruction to be added to OrdVec. If there
1531 are no preceding defs, it just appends the instruction. If there is a
1532 preceding def, it puts two instructions to save the reg on stack before
1533 the load and puts a restore at use.
1538 bool DebugPrint = false;
1541 CouldMoveAll = true;
1542 std::vector<MachineInstr*>::iterator DefIt = UnordVec.begin();
1544 for( ; DefIt != UnordVec.end(); ++DefIt ) {
1546 // for each instruction in the UnordVec do ...
1548 MachineInstr *DefInst = *DefIt;
1550 if( DefInst == NULL) continue;
1552 //std::cerr << "\nInst in UnordVec = " << *DefInst;
1554 // last operand is the def (unless for a store which has no def reg)
1555 MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1557 if ((DefOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1558 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1560 // If the operand in DefInst is a def ...
1561 bool DefEqUse = false;
1563 std::vector<MachineInstr*>::iterator UseIt = DefIt;
1566 for( ; UseIt != UnordVec.end(); ++UseIt ) {
1568 MachineInstr *UseInst = *UseIt;
1569 if( UseInst == NULL) continue;
1571 // for each inst (UseInst) that is below the DefInst do ...
1572 MachineOperand& UseOp = UseInst->getOperand(0);
1574 if (!UseOp.opIsDefOnly() &&
1575 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1577 // if use is a register ...
1579 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1581 // if Def and this use are the same, it means that this use
1582 // is destroyed by a def before it is used
1584 // std::cerr << "\nCouldn't move " << *DefInst;
1587 CouldMoveAll = false;
1590 } // if two registers are equal
1592 } // if use is a register
1594 }// for all use instructions
1598 // after examining all the instructions that follow the DefInst
1599 // if there are no dependencies, we can move it to the OrdVec
1601 // std::cerr << "Moved to Ord: " << *DefInst;
1603 moveInst2OrdVec(OrdVec, DefInst, PRA);
1605 //OrdVec.push_back(DefInst);
1607 // mark the pos of DefInst with NULL to indicate that it is
1612 } // if Def is a machine register
1614 } // for all instructions in the UnordVec
1617 } while(!CouldMoveAll);
1619 if (DebugPrint && DEBUG_RA) {
1620 std::cerr << "\nAdded instructions were reordered to:\n";
1621 for(unsigned i=0; i < OrdVec.size(); i++)
1622 std::cerr << *OrdVec[i];
1630 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr*> &OrdVec,
1631 MachineInstr *UnordInst,
1632 PhyRegAlloc &PRA) const {
1633 MachineOperand& UseOp = UnordInst->getOperand(0);
1635 if (!UseOp.opIsDefOnly() &&
1636 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1638 // for the use of UnordInst, see whether there is a defining instr
1639 // before in the OrdVec
1640 bool DefEqUse = false;
1642 std::vector<MachineInstr*>::iterator OrdIt = OrdVec.begin();
1644 for( ; OrdIt != OrdVec.end(); ++OrdIt ) {
1646 MachineInstr *OrdInst = *OrdIt ;
1648 MachineOperand& DefOp =
1649 OrdInst->getOperand(OrdInst->getNumOperands()-1);
1651 if( (DefOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1652 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1654 //std::cerr << "\nDefining Ord Inst: " << *OrdInst;
1656 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1658 // we are here because there is a preceding def in the OrdVec
1659 // for the use in this intr we are going to insert. This
1660 // happened because the original code was like:
1661 // 1. add %ox %g0 %oy
1662 // 2. add %oy %g0 %ox
1663 // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1664 // Now we are processing %ox of 1.
1667 int UReg = DefOp.getMachineRegNum();
1668 int RegType = getRegType(UReg);
1669 MachineInstr *AdIBef, *AdIAft;
1672 PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1674 // Save the UReg (%ox) on stack before it's destroyed
1675 std::vector<MachineInstr*> mvec;
1676 cpReg2MemMI(mvec, UReg, getFramePointer(), StackOff, RegType);
1677 for (std::vector<MachineInstr*>::iterator MI=mvec.begin();
1678 MI != mvec.end(); ++MI)
1679 OrdIt = 1+OrdVec.insert(OrdIt, *MI);
1681 // Load directly into DReg (%oy)
1682 MachineOperand& DOp=
1683 (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1684 assert((DOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1685 "Last operand is not the def");
1686 const int DReg = DOp.getMachineRegNum();
1688 cpMem2RegMI(OrdVec, getFramePointer(), StackOff, DReg, RegType);
1691 std::cerr << "\nFixed CIRCULAR references by reordering:";
1692 std::cerr << "\nBefore CIRCULAR Reordering:\n";
1693 std::cerr << *UnordInst;
1694 std::cerr << *OrdInst;
1696 std::cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1697 for(unsigned i=0; i < OrdVec.size(); i++)
1698 std::cerr << *(OrdVec[i]);
1701 // Do not copy the UseInst to OrdVec
1705 }// if two registers are equal
1707 } // if Def is a register
1709 } // for each instr in OrdVec
1713 // We didn't find a def in the OrdVec, so just append this inst
1714 OrdVec.push_back( UnordInst );
1715 //std::cerr << "Reordered Inst (Moved Dn): " << *UnordInst;
1718 }// if the operand in UnordInst is a use