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] );
945 //Insert machine instructions before and after call into the
946 //call instructions map --- Anand
947 const CallInst *callInst = argDesc->getCallInst();
948 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(callInst);
949 mvec.insert(mvec.begin(), CallAI->InstrnsBefore.begin(),
950 CallAI->InstrnsBefore.end());
951 mvec.insert(mvec.end(), CallAI->InstrnsAfter.begin(),
952 CallAI->InstrnsAfter.end());
955 //---------------------------------------------------------------------------
956 // this method is called for an LLVM return instruction to identify which
957 // values will be returned from this method and to suggest colors.
958 //---------------------------------------------------------------------------
959 void UltraSparcRegInfo::suggestReg4RetValue(MachineInstr *RetMI,
960 LiveRangeInfo &LRI) const {
962 assert( (target.getInstrInfo()).isReturn( RetMI->getOpCode() ) );
964 suggestReg4RetAddr(RetMI, LRI);
966 // To find the return value (if any), we can get the LLVM return instr.
967 // from the return address register, which is the first operand
968 Value* tmpI = RetMI->getOperand(0).getVRegValue();
969 ReturnInst* retI=cast<ReturnInst>(cast<TmpInstruction>(tmpI)->getOperand(0));
970 if (const Value *RetVal = retI->getReturnValue())
971 if (LiveRange *const LR = LRI.getLiveRangeForValue(RetVal))
972 LR->setSuggestedColor(LR->getRegClassID() == IntRegClassID
973 ? (unsigned) SparcIntRegClass::i0
974 : (unsigned) SparcFloatRegClass::f0);
979 //---------------------------------------------------------------------------
980 // Colors the return value of a method to %i0 or %f0, if possible. If it is
981 // not possilbe to directly color the LR, insert a copy instruction to move
982 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we
983 // have to put a load instruction.
984 //---------------------------------------------------------------------------
985 void UltraSparcRegInfo::colorRetValue(MachineInstr *RetMI,
987 AddedInstrns *RetAI) const {
989 assert((target.getInstrInfo()).isReturn( RetMI->getOpCode()));
991 // To find the return value (if any), we can get the LLVM return instr.
992 // from the return address register, which is the first operand
993 Value* tmpI = RetMI->getOperand(0).getVRegValue();
994 ReturnInst* retI=cast<ReturnInst>(cast<TmpInstruction>(tmpI)->getOperand(0));
995 if (const Value *RetVal = retI->getReturnValue()) {
997 unsigned RegClassID = getRegClassIDOfType(RetVal->getType());
998 unsigned regType = getRegType(RetVal->getType());
999 unsigned CorrectCol = (RegClassID == IntRegClassID
1000 ? (unsigned) SparcIntRegClass::i0
1001 : (unsigned) SparcFloatRegClass::f0);
1003 // convert to unified number
1004 unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
1006 // Mark the register as used by this instruction
1007 RetMI->insertUsedReg(UniRetReg);
1009 #ifdef CANNOT_PRECOPY_CALLARGS
1010 LiveRange *LR = LRI.getLiveRangeForValue(RetVal);
1011 assert(LR && "No LR for return value of non-void method?");
1013 if (LR->hasColor()) {
1014 // if the LR received the correct color, NOTHING to do
1015 if (LR->getColor() == CorrectCol)
1018 // We are here because the LR was allocated a register
1019 // It may be the suggested register or not
1021 // copy the LR of retun value to i0 or f0
1023 unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
1025 // the LR received UniLRReg but must be colored with UniRetReg
1026 // to pass as the return value
1027 cpReg2RegMI(RetAI->InstrnsBefore, UniLRReg, UniRetReg, regType);
1029 else { // if the LR is spilled
1030 cpMem2RegMI(RetAI->InstrnsBefore, getFramePointer(),
1031 LR->getSpillOffFromFP(), UniRetReg, regType);
1032 //std::cerr << "\nCopied the return value from stack\n";
1036 } // if there is a return value
1040 //---------------------------------------------------------------------------
1041 // Check if a specified register type needs a scratch register to be
1042 // copied to/from memory. If it does, the reg. type that must be used
1043 // for scratch registers is returned in scratchRegType.
1045 // Only the int CC register needs such a scratch register.
1046 // The FP CC registers can (and must) be copied directly to/from memory.
1047 //---------------------------------------------------------------------------
1050 UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
1051 int& scratchRegType) const
1053 if (RegType == IntCCRegType)
1055 scratchRegType = IntRegType;
1061 //---------------------------------------------------------------------------
1062 // Copy from a register to register. Register number must be the unified
1064 //---------------------------------------------------------------------------
1067 UltraSparcRegInfo::cpReg2RegMI(std::vector<MachineInstr*>& mvec,
1070 int RegType) const {
1071 assert( ((int)SrcReg != getInvalidRegNum()) &&
1072 ((int)DestReg != getInvalidRegNum()) &&
1073 "Invalid Register");
1075 MachineInstr * MI = NULL;
1080 if (getRegType(DestReg) == IntRegType) {
1081 // copy intCC reg to int reg
1082 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1083 MI = BuildMI(V9::RDCCR, 2).addMReg(SrcReg+1).addMReg(DestReg,MOTy::Def);
1085 // copy int reg to intCC reg
1086 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1087 assert(getRegType(SrcReg) == IntRegType
1088 && "Can only copy CC reg to/from integer reg");
1089 MI = BuildMI(V9::WRCCRr, 3).addMReg(SrcReg)
1090 .addMReg(SparcIntRegClass::g0).addMReg(DestReg+1, MOTy::Def);
1094 case FloatCCRegType:
1095 assert(0 && "Cannot copy FPCC register to any other register");
1099 MI = BuildMI(V9::ADDr, 3).addMReg(SrcReg).addMReg(getZeroRegNum())
1100 .addMReg(DestReg, MOTy::Def);
1103 case FPSingleRegType:
1104 MI = BuildMI(V9::FMOVS, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
1107 case FPDoubleRegType:
1108 MI = BuildMI(V9::FMOVD, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
1112 assert(0 && "Unknown RegType");
1120 //---------------------------------------------------------------------------
1121 // Copy from a register to memory (i.e., Store). Register number must
1122 // be the unified register number
1123 //---------------------------------------------------------------------------
1127 UltraSparcRegInfo::cpReg2MemMI(std::vector<MachineInstr*>& mvec,
1129 unsigned DestPtrReg,
1130 int Offset, int RegType,
1131 int scratchReg) const {
1132 MachineInstr * MI = NULL;
1135 assert(target.getInstrInfo().constantFitsInImmedField(V9::STXi, Offset));
1136 MI = BuildMI(V9::STXi,3).addMReg(SrcReg).addMReg(DestPtrReg)
1140 case FPSingleRegType:
1141 assert(target.getInstrInfo().constantFitsInImmedField(V9::STFi, Offset));
1142 MI = BuildMI(V9::STFi, 3).addMReg(SrcReg).addMReg(DestPtrReg)
1146 case FPDoubleRegType:
1147 assert(target.getInstrInfo().constantFitsInImmedField(V9::STDFi, Offset));
1148 MI = BuildMI(V9::STDFi,3).addMReg(SrcReg).addMReg(DestPtrReg)
1153 assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
1154 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1156 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1157 MI = BuildMI(V9::RDCCR, 2).addMReg(SrcReg+1).addMReg(scratchReg, MOTy::Def);
1160 cpReg2MemMI(mvec, scratchReg, DestPtrReg, Offset, IntRegType);
1163 case FloatCCRegType: {
1164 assert(target.getInstrInfo().constantFitsInImmedField(V9::STXFSRi, Offset));
1165 unsigned fsrRegNum = getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
1166 SparcSpecialRegClass::fsr);
1167 MI = BuildMI(V9::STXFSRi, 3)
1168 .addMReg(fsrRegNum).addMReg(DestPtrReg).addSImm(Offset);
1172 assert(0 && "Unknown RegType in cpReg2MemMI");
1178 //---------------------------------------------------------------------------
1179 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1181 //---------------------------------------------------------------------------
1185 UltraSparcRegInfo::cpMem2RegMI(std::vector<MachineInstr*>& mvec,
1190 int scratchReg) const {
1191 MachineInstr * MI = NULL;
1194 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDXi, Offset));
1195 MI = BuildMI(V9::LDXi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1196 .addMReg(DestReg, MOTy::Def);
1199 case FPSingleRegType:
1200 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDFi, Offset));
1201 MI = BuildMI(V9::LDFi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1202 .addMReg(DestReg, MOTy::Def);
1205 case FPDoubleRegType:
1206 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDDFi, Offset));
1207 MI = BuildMI(V9::LDDFi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1208 .addMReg(DestReg, MOTy::Def);
1212 assert(scratchReg >= 0 && "Need scratch reg to load %ccr from memory");
1213 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1214 cpMem2RegMI(mvec, SrcPtrReg, Offset, scratchReg, IntRegType);
1216 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1217 MI = BuildMI(V9::WRCCRr, 3).addMReg(scratchReg)
1218 .addMReg(SparcIntRegClass::g0).addMReg(DestReg+1,MOTy::Def);
1221 case FloatCCRegType: {
1222 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDXFSRi, Offset));
1223 unsigned fsrRegNum = getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
1224 SparcSpecialRegClass::fsr);
1225 MI = BuildMI(V9::LDXFSRi, 3).addMReg(SrcPtrReg).addSImm(Offset)
1226 .addMReg(fsrRegNum, MOTy::UseAndDef);
1230 assert(0 && "Unknown RegType in cpMem2RegMI");
1236 //---------------------------------------------------------------------------
1237 // Generate a copy instruction to copy a value to another. Temporarily
1238 // used by PhiElimination code.
1239 //---------------------------------------------------------------------------
1243 UltraSparcRegInfo::cpValue2Value(Value *Src, Value *Dest,
1244 std::vector<MachineInstr*>& mvec) const {
1245 int RegType = getRegType(Src->getType());
1246 MachineInstr * MI = NULL;
1250 MI = BuildMI(V9::ADDr, 3).addReg(Src).addMReg(getZeroRegNum())
1253 case FPSingleRegType:
1254 MI = BuildMI(V9::FMOVS, 2).addReg(Src).addRegDef(Dest);
1256 case FPDoubleRegType:
1257 MI = BuildMI(V9::FMOVD, 2).addReg(Src).addRegDef(Dest);
1260 assert(0 && "Unknow RegType in CpValu2Value");
1271 //----------------------------------------------------------------------------
1272 // This method inserts caller saving/restoring instructons before/after
1273 // a call machine instruction. The caller saving/restoring instructions are
1276 // ** caller saving instructions
1277 // other instructions inserted for the call by ColorCallArg
1279 // other instructions inserted for the call ColorCallArg
1280 // ** caller restoring instructions
1282 //----------------------------------------------------------------------------
1286 UltraSparcRegInfo::insertCallerSavingCode
1287 (std::vector<MachineInstr*> &instrnsBefore,
1288 std::vector<MachineInstr*> &instrnsAfter,
1289 MachineInstr *CallMI,
1290 const BasicBlock *BB,
1291 PhyRegAlloc &PRA) const
1293 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
1295 // has set to record which registers were saved/restored
1297 hash_set<unsigned> PushedRegSet;
1299 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
1301 // Now check if the call has a return value (using argDesc) and if so,
1302 // find the LR of the TmpInstruction representing the return value register.
1303 // (using the last or second-last *implicit operand* of the call MI).
1304 // Insert it to to the PushedRegSet since we must not save that register
1305 // and restore it after the call.
1306 // We do this because, we look at the LV set *after* the instruction
1307 // to determine, which LRs must be saved across calls. The return value
1308 // of the call is live in this set - but we must not save/restore it.
1310 if (const Value *origRetVal = argDesc->getReturnValue()) {
1311 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
1312 (argDesc->getIndirectFuncPtr()? 1 : 2));
1313 const TmpInstruction* tmpRetVal =
1314 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
1315 assert(tmpRetVal->getOperand(0) == origRetVal &&
1316 tmpRetVal->getType() == origRetVal->getType() &&
1317 "Wrong implicit ref?");
1318 LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( tmpRetVal );
1319 assert(RetValLR && "No LR for RetValue of call");
1321 if (RetValLR->hasColor())
1322 PushedRegSet.insert(getUnifiedRegNum(RetValLR->getRegClassID(),
1323 RetValLR->getColor()));
1326 const ValueSet &LVSetAft = PRA.LVI->getLiveVarSetAfterMInst(CallMI, BB);
1327 ValueSet::const_iterator LIt = LVSetAft.begin();
1329 // for each live var in live variable set after machine inst
1330 for( ; LIt != LVSetAft.end(); ++LIt) {
1332 // get the live range corresponding to live var
1333 LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );
1335 // LR can be null if it is a const since a const
1336 // doesn't have a dominating def - see Assumptions above
1339 if( LR->hasColor() ) {
1341 unsigned RCID = LR->getRegClassID();
1342 unsigned Color = LR->getColor();
1344 if ( isRegVolatile(RCID, Color) ) {
1346 // if the value is in both LV sets (i.e., live before and after
1347 // the call machine instruction)
1349 unsigned Reg = getUnifiedRegNum(RCID, Color);
1351 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1353 // if we haven't already pushed that register
1355 unsigned RegType = getRegType(LR);
1357 // Now get two instructions - to push on stack and pop from stack
1358 // and add them to InstrnsBefore and InstrnsAfter of the
1362 PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1364 std::vector<MachineInstr*> AdIBef, AdIAft;
1366 //---- Insert code for pushing the reg on stack ----------
1368 // We may need a scratch register to copy the saved value
1369 // to/from memory. This may itself have to insert code to
1370 // free up a scratch register. Any such code should go before
1371 // the save code. The scratch register, if any, is by default
1372 // temporary and not "used" by the instruction unless the
1373 // copy code itself decides to keep the value in the scratch reg.
1374 int scratchRegType = -1;
1375 int scratchReg = -1;
1376 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1377 { // Find a register not live in the LVSet before CallMI
1378 const ValueSet &LVSetBef =
1379 PRA.LVI->getLiveVarSetBeforeMInst(CallMI, BB);
1380 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetBef,
1381 CallMI, AdIBef, AdIAft);
1382 assert(scratchReg != getInvalidRegNum());
1385 if (AdIBef.size() > 0)
1386 instrnsBefore.insert(instrnsBefore.end(),
1387 AdIBef.begin(), AdIBef.end());
1389 cpReg2MemMI(instrnsBefore, Reg,getFramePointer(),StackOff,RegType,
1392 if (AdIAft.size() > 0)
1393 instrnsBefore.insert(instrnsBefore.end(),
1394 AdIAft.begin(), AdIAft.end());
1396 //---- Insert code for popping the reg from the stack ----------
1398 // We may need a scratch register to copy the saved value
1399 // from memory. This may itself have to insert code to
1400 // free up a scratch register. Any such code should go
1401 // after the save code. As above, scratch is not marked "used".
1403 scratchRegType = -1;
1405 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1406 { // Find a register not live in the LVSet after CallMI
1407 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetAft,
1408 CallMI, AdIBef, AdIAft);
1409 assert(scratchReg != getInvalidRegNum());
1412 if (AdIBef.size() > 0)
1413 instrnsAfter.insert(instrnsAfter.end(),
1414 AdIBef.begin(), AdIBef.end());
1416 cpMem2RegMI(instrnsAfter, getFramePointer(), StackOff,Reg,RegType,
1419 if (AdIAft.size() > 0)
1420 instrnsAfter.insert(instrnsAfter.end(),
1421 AdIAft.begin(), AdIAft.end());
1423 PushedRegSet.insert(Reg);
1426 std::cerr << "\nFor call inst:" << *CallMI;
1427 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
1428 for_each(instrnsBefore.begin(), instrnsBefore.end(),
1429 std::mem_fun(&MachineInstr::dump));
1430 std::cerr << " -and After:\n\t ";
1431 for_each(instrnsAfter.begin(), instrnsAfter.end(),
1432 std::mem_fun(&MachineInstr::dump));
1434 } // if not already pushed
1436 } // if LR has a volatile color
1438 } // if LR has color
1440 } // if there is a LR for Var
1442 } // for each value in the LV set after instruction
1446 //---------------------------------------------------------------------------
1447 // Print the register assigned to a LR
1448 //---------------------------------------------------------------------------
1450 void UltraSparcRegInfo::printReg(const LiveRange *LR) const {
1451 unsigned RegClassID = LR->getRegClassID();
1452 std::cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1454 if (!LR->hasColor()) {
1455 std::cerr << " - could not find a color\n";
1459 // if a color is found
1461 std::cerr << " colored with color "<< LR->getColor();
1463 unsigned uRegName = getUnifiedRegNum(RegClassID, LR->getColor());
1466 std::cerr<< getUnifiedRegName(uRegName);
1467 if (RegClassID == FloatRegClassID && LR->getType() == Type::DoubleTy)
1468 std::cerr << "+" << getUnifiedRegName(uRegName+1);
1472 //---------------------------------------------------------------------------
1473 // This method examines instructions inserted by RegAlloc code before a
1474 // machine instruction to detect invalid orders that destroy values before
1475 // they are used. If it detects such conditions, it reorders the instructions.
1477 // The unordered instructions come in the UnordVec. These instructions are
1478 // instructions inserted by RegAlloc. All such instruction MUST have
1479 // their USES BEFORE THE DEFS after reordering.
1481 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1482 // this method is called.
1484 // This method uses two vectors for efficiency in accessing
1486 // Since instructions are inserted in RegAlloc, this assumes that the
1487 // first operand is the source reg and the last operand is the dest reg.
1488 // It also does not consider operands that are both use and def.
1490 // All the uses are before THE def to a register
1491 //---------------------------------------------------------------------------
1493 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr*> &UnordVec,
1494 std::vector<MachineInstr*> &OrdVec,
1495 PhyRegAlloc &PRA) const{
1498 Problem: We can have instructions inserted by RegAlloc like
1500 2. add %oy %g0 %oz, where z!=x or z==x
1502 This is wrong since %oy used by 2 is overwritten by 1
1505 We re-order the instructions so that the uses are before the defs
1510 for each instruction 'DefInst' in the UnOrdVec
1511 for each instruction 'UseInst' that follows the DefInst
1512 if the reg defined by DefInst is used by UseInst
1513 mark DefInst as not movable in this iteration
1514 If DefInst is not marked as not-movable, move DefInst to OrdVec
1515 while all instructions in DefInst are moved to OrdVec
1517 For moving, we call the move2OrdVec(). It checks whether there is a def
1518 in it for the uses in the instruction to be added to OrdVec. If there
1519 are no preceding defs, it just appends the instruction. If there is a
1520 preceding def, it puts two instructions to save the reg on stack before
1521 the load and puts a restore at use.
1526 bool DebugPrint = false;
1529 CouldMoveAll = true;
1530 std::vector<MachineInstr*>::iterator DefIt = UnordVec.begin();
1532 for( ; DefIt != UnordVec.end(); ++DefIt ) {
1534 // for each instruction in the UnordVec do ...
1536 MachineInstr *DefInst = *DefIt;
1538 if( DefInst == NULL) continue;
1540 //std::cerr << "\nInst in UnordVec = " << *DefInst;
1542 // last operand is the def (unless for a store which has no def reg)
1543 MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1545 if ((DefOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1546 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1548 // If the operand in DefInst is a def ...
1549 bool DefEqUse = false;
1551 std::vector<MachineInstr*>::iterator UseIt = DefIt;
1554 for( ; UseIt != UnordVec.end(); ++UseIt ) {
1556 MachineInstr *UseInst = *UseIt;
1557 if( UseInst == NULL) continue;
1559 // for each inst (UseInst) that is below the DefInst do ...
1560 MachineOperand& UseOp = UseInst->getOperand(0);
1562 if (!UseOp.opIsDefOnly() &&
1563 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1565 // if use is a register ...
1567 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1569 // if Def and this use are the same, it means that this use
1570 // is destroyed by a def before it is used
1572 // std::cerr << "\nCouldn't move " << *DefInst;
1575 CouldMoveAll = false;
1578 } // if two registers are equal
1580 } // if use is a register
1582 }// for all use instructions
1586 // after examining all the instructions that follow the DefInst
1587 // if there are no dependencies, we can move it to the OrdVec
1589 // std::cerr << "Moved to Ord: " << *DefInst;
1591 moveInst2OrdVec(OrdVec, DefInst, PRA);
1593 //OrdVec.push_back(DefInst);
1595 // mark the pos of DefInst with NULL to indicate that it is
1600 } // if Def is a machine register
1602 } // for all instructions in the UnordVec
1605 } while(!CouldMoveAll);
1607 if (DebugPrint && DEBUG_RA) {
1608 std::cerr << "\nAdded instructions were reordered to:\n";
1609 for(unsigned i=0; i < OrdVec.size(); i++)
1610 std::cerr << *OrdVec[i];
1618 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr*> &OrdVec,
1619 MachineInstr *UnordInst,
1620 PhyRegAlloc &PRA) const {
1621 MachineOperand& UseOp = UnordInst->getOperand(0);
1623 if (!UseOp.opIsDefOnly() &&
1624 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1626 // for the use of UnordInst, see whether there is a defining instr
1627 // before in the OrdVec
1628 bool DefEqUse = false;
1630 std::vector<MachineInstr*>::iterator OrdIt = OrdVec.begin();
1632 for( ; OrdIt != OrdVec.end(); ++OrdIt ) {
1634 MachineInstr *OrdInst = *OrdIt ;
1636 MachineOperand& DefOp =
1637 OrdInst->getOperand(OrdInst->getNumOperands()-1);
1639 if( (DefOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1640 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1642 //std::cerr << "\nDefining Ord Inst: " << *OrdInst;
1644 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1646 // we are here because there is a preceding def in the OrdVec
1647 // for the use in this intr we are going to insert. This
1648 // happened because the original code was like:
1649 // 1. add %ox %g0 %oy
1650 // 2. add %oy %g0 %ox
1651 // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1652 // Now we are processing %ox of 1.
1655 int UReg = DefOp.getMachineRegNum();
1656 int RegType = getRegType(UReg);
1657 MachineInstr *AdIBef, *AdIAft;
1660 PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1662 // Save the UReg (%ox) on stack before it's destroyed
1663 std::vector<MachineInstr*> mvec;
1664 cpReg2MemMI(mvec, UReg, getFramePointer(), StackOff, RegType);
1665 for (std::vector<MachineInstr*>::iterator MI=mvec.begin();
1666 MI != mvec.end(); ++MI)
1667 OrdIt = 1+OrdVec.insert(OrdIt, *MI);
1669 // Load directly into DReg (%oy)
1670 MachineOperand& DOp=
1671 (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1672 assert((DOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1673 "Last operand is not the def");
1674 const int DReg = DOp.getMachineRegNum();
1676 cpMem2RegMI(OrdVec, getFramePointer(), StackOff, DReg, RegType);
1679 std::cerr << "\nFixed CIRCULAR references by reordering:";
1680 std::cerr << "\nBefore CIRCULAR Reordering:\n";
1681 std::cerr << *UnordInst;
1682 std::cerr << *OrdInst;
1684 std::cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1685 for(unsigned i=0; i < OrdVec.size(); i++)
1686 std::cerr << *(OrdVec[i]);
1689 // Do not copy the UseInst to OrdVec
1693 }// if two registers are equal
1695 } // if Def is a register
1697 } // for each instr in OrdVec
1701 // We didn't find a def in the OrdVec, so just append this inst
1702 OrdVec.push_back( UnordInst );
1703 //std::cerr << "Reordered Inst (Moved Dn): " << *UnordInst;
1706 }// if the operand in UnordInst is a use