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/MachineInstrAnnot.h"
16 #include "llvm/CodeGen/FunctionLiveVarInfo.h" // FIXME: Remove
17 #include "../../CodeGen/RegAlloc/RegAllocCommon.h" // FIXME!
18 #include "llvm/iTerminators.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Function.h"
21 #include "llvm/DerivedTypes.h"
27 UltraSparcRegInfo::UltraSparcRegInfo(const UltraSparc &tgt)
28 : TargetRegInfo(tgt), NumOfIntArgRegs(6),
29 NumOfFloatArgRegs(32), InvalidRegNum(1000) {
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 integer arg#,
161 // assuming there are argNum total args, intArgNum int args,
162 // and fpArgNum FP args preceding (and not including) this one.
163 // Use INT regs for FP args if this is a varargs call.
166 // InvalidRegNum, if there is no int register available for the arg.
167 // regNum, otherwise (this is NOT the unified reg. num).
170 UltraSparcRegInfo::regNumForIntArg(bool inCallee, bool isVarArgsCall,
172 unsigned intArgNo, unsigned fpArgNo,
173 unsigned& regClassId) const
175 regClassId = IntRegClassID;
176 if (argNo >= NumOfIntArgRegs)
177 return InvalidRegNum;
179 return argNo + (inCallee? SparcIntRegClass::i0 : SparcIntRegClass::o0);
182 // Get the register number for the specified FP arg#,
183 // assuming there are argNum total args, intArgNum int args,
184 // and fpArgNum FP args preceding (and not including) this one.
185 // Use INT regs for FP args if this is a varargs call.
188 // InvalidRegNum, if there is no int register available for the arg.
189 // regNum, otherwise (this is NOT the unified reg. num).
192 UltraSparcRegInfo::regNumForFPArg(unsigned regType,
193 bool inCallee, bool isVarArgsCall,
195 unsigned intArgNo, unsigned fpArgNo,
196 unsigned& regClassId) const
199 return regNumForIntArg(inCallee, isVarArgsCall, argNo, intArgNo, fpArgNo,
203 regClassId = FloatRegClassID;
204 if (regType == FPSingleRegType)
205 return (argNo*2+1 >= NumOfFloatArgRegs)?
206 InvalidRegNum : SparcFloatRegClass::f0 + (argNo * 2 + 1);
207 else if (regType == FPDoubleRegType)
208 return (argNo*2 >= NumOfFloatArgRegs)?
209 InvalidRegNum : SparcFloatRegClass::f0 + (argNo * 2);
211 assert(0 && "Illegal FP register type");
217 //---------------------------------------------------------------------------
218 // Finds the return address of a call sparc specific call instruction
219 //---------------------------------------------------------------------------
221 // The following 4 methods are used to find the RegType (SparcInternals.h)
222 // of a LiveRange, a Value, and for a given register unified reg number.
224 int UltraSparcRegInfo::getRegTypeForClassAndType(unsigned regClassID,
225 const Type* type) const
227 switch (regClassID) {
228 case IntRegClassID: return IntRegType;
229 case FloatRegClassID:
230 if (type == Type::FloatTy) return FPSingleRegType;
231 else if (type == Type::DoubleTy) return FPDoubleRegType;
232 assert(0 && "Unknown type in FloatRegClass"); return 0;
233 case IntCCRegClassID: return IntCCRegType;
234 case FloatCCRegClassID: return FloatCCRegType;
235 case SpecialRegClassID: return SpecialRegType;
236 default: assert( 0 && "Unknown reg class ID"); return 0;
240 int UltraSparcRegInfo::getRegType(const Type* type) const
242 return getRegTypeForClassAndType(getRegClassIDOfType(type), type);
245 int UltraSparcRegInfo::getRegType(const LiveRange *LR) const
247 return getRegTypeForClassAndType(LR->getRegClassID(), LR->getType());
250 int UltraSparcRegInfo::getRegType(int unifiedRegNum) const
252 if (unifiedRegNum < 32)
254 else if (unifiedRegNum < (32 + 32))
255 return FPSingleRegType;
256 else if (unifiedRegNum < (64 + 32))
257 return FPDoubleRegType;
258 else if (unifiedRegNum < (64+32+4))
259 return FloatCCRegType;
260 else if (unifiedRegNum < (64+32+4+2))
263 assert(0 && "Invalid unified register number in getRegType");
268 // To find the register class used for a specified Type
270 unsigned UltraSparcRegInfo::getRegClassIDOfType(const Type *type,
271 bool isCCReg) const {
272 Type::PrimitiveID ty = type->getPrimitiveID();
275 // FIXME: Comparing types like this isn't very safe...
276 if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
277 (ty == Type::FunctionTyID) || (ty == Type::PointerTyID) )
278 res = IntRegClassID; // sparc int reg (ty=0: void)
279 else if (ty <= Type::DoubleTyID)
280 res = FloatRegClassID; // sparc float reg class
282 //std::cerr << "TypeID: " << ty << "\n";
283 assert(0 && "Cannot resolve register class for type");
288 return res + 2; // corresponding condition code register
293 unsigned UltraSparcRegInfo::getRegClassIDOfRegType(int regType) const {
295 case IntRegType: return IntRegClassID;
296 case FPSingleRegType:
297 case FPDoubleRegType: return FloatRegClassID;
298 case IntCCRegType: return IntCCRegClassID;
299 case FloatCCRegType: return FloatCCRegClassID;
301 assert(0 && "Invalid register type in getRegClassIDOfRegType");
306 //---------------------------------------------------------------------------
307 // Suggests a register for the ret address in the RET machine instruction.
308 // We always suggest %i7 by convention.
309 //---------------------------------------------------------------------------
310 void UltraSparcRegInfo::suggestReg4RetAddr(MachineInstr *RetMI,
311 LiveRangeInfo& LRI) const {
313 assert(target.getInstrInfo().isReturn(RetMI->getOpCode()));
315 // return address is always mapped to i7 so set it immediately
316 RetMI->SetRegForOperand(0, getUnifiedRegNum(IntRegClassID,
317 SparcIntRegClass::i7));
319 // Possible Optimization:
320 // Instead of setting the color, we can suggest one. In that case,
321 // we have to test later whether it received the suggested color.
322 // In that case, a LR has to be created at the start of method.
323 // It has to be done as follows (remove the setRegVal above):
325 // MachineOperand & MO = RetMI->getOperand(0);
326 // const Value *RetAddrVal = MO.getVRegValue();
327 // assert( RetAddrVal && "LR for ret address must be created at start");
328 // LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);
329 // RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID,
330 // SparcIntRegOrdr::i7) );
334 //---------------------------------------------------------------------------
335 // Suggests a register for the ret address in the JMPL/CALL machine instr.
336 // Sparc ABI dictates that %o7 be used for this purpose.
337 //---------------------------------------------------------------------------
339 UltraSparcRegInfo::suggestReg4CallAddr(MachineInstr * CallMI,
340 LiveRangeInfo& LRI) const
342 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
343 const Value *RetAddrVal = argDesc->getReturnAddrReg();
344 assert(RetAddrVal && "INTERNAL ERROR: Return address value is required");
346 // A LR must already exist for the return address.
347 LiveRange *RetAddrLR = LRI.getLiveRangeForValue(RetAddrVal);
348 assert(RetAddrLR && "INTERNAL ERROR: No LR for return address of call!");
350 unsigned RegClassID = RetAddrLR->getRegClassID();
351 RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID, SparcIntRegClass::o7));
356 //---------------------------------------------------------------------------
357 // This method will suggest colors to incoming args to a method.
358 // According to the Sparc ABI, the first 6 incoming args are in
359 // %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
360 // If the arg is passed on stack due to the lack of regs, NOTHING will be
361 // done - it will be colored (or spilled) as a normal live range.
362 //---------------------------------------------------------------------------
363 void UltraSparcRegInfo::suggestRegs4MethodArgs(const Function *Meth,
364 LiveRangeInfo& LRI) const
366 // check if this is a varArgs function. needed for choosing regs.
367 bool isVarArgs = isVarArgsFunction(Meth->getType());
369 // for each argument. count INT and FP arguments separately.
370 unsigned argNo=0, intArgNo=0, fpArgNo=0;
371 for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
372 I != E; ++I, ++argNo) {
374 LiveRange *LR = LRI.getLiveRangeForValue(I);
375 assert(LR && "No live range found for method arg");
377 unsigned regType = getRegType(LR);
378 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg (unused)
380 int regNum = (regType == IntRegType)
381 ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
382 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
383 : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
384 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
386 if(regNum != InvalidRegNum)
387 LR->setSuggestedColor(regNum);
392 //---------------------------------------------------------------------------
393 // This method is called after graph coloring to move incoming args to
394 // the correct hardware registers if they did not receive the correct
395 // (suggested) color through graph coloring.
396 //---------------------------------------------------------------------------
397 void UltraSparcRegInfo::colorMethodArgs(const Function *Meth,
399 AddedInstrns *FirstAI) const {
401 // check if this is a varArgs function. needed for choosing regs.
402 bool isVarArgs = isVarArgsFunction(Meth->getType());
406 // for each argument. count INT and FP arguments separately.
407 unsigned argNo=0, intArgNo=0, fpArgNo=0;
408 for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
409 I != E; ++I, ++argNo) {
411 LiveRange *LR = LRI.getLiveRangeForValue(I);
412 assert( LR && "No live range found for method arg");
414 unsigned regType = getRegType(LR);
415 unsigned RegClassID = LR->getRegClassID();
417 // Find whether this argument is coming in a register (if not, on stack)
418 // Also find the correct register the argument must use (UniArgReg)
420 bool isArgInReg = false;
421 unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
422 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
424 int regNum = (regType == IntRegType)
425 ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
426 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
427 : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
428 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
430 if(regNum != InvalidRegNum) {
432 UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
435 if( LR->hasColor() ) { // if this arg received a register
437 unsigned UniLRReg = getUnifiedRegNum( RegClassID, LR->getColor() );
439 // if LR received the correct color, nothing to do
441 if( UniLRReg == UniArgReg )
444 // We are here because the LR did not receive the suggested
445 // but LR received another register.
446 // Now we have to copy the %i reg (or stack pos of arg)
447 // to the register the LR was colored with.
449 // if the arg is coming in UniArgReg register, it MUST go into
450 // the UniLRReg register
453 if( regClassIDOfArgReg != RegClassID ) {
454 assert(0 && "This could should work but it is not tested yet");
456 // It is a variable argument call: the float reg must go in a %o reg.
457 // We have to move an int reg to a float reg via memory.
460 RegClassID == FloatRegClassID &&
461 regClassIDOfArgReg == IntRegClassID &&
462 "This should only be an Int register for an FP argument");
464 int TmpOff = MachineFunction::get(Meth).getInfo()->pushTempValue(
465 getSpilledRegSize(regType));
466 cpReg2MemMI(FirstAI->InstrnsBefore,
467 UniArgReg, getFramePointer(), TmpOff, IntRegType);
469 cpMem2RegMI(FirstAI->InstrnsBefore,
470 getFramePointer(), TmpOff, UniLRReg, regType);
473 cpReg2RegMI(FirstAI->InstrnsBefore, UniArgReg, UniLRReg, regType);
478 // Now the arg is coming on stack. Since the LR recieved a register,
479 // we just have to load the arg on stack into that register
481 const TargetFrameInfo& frameInfo = target.getFrameInfo();
483 frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
486 cpMem2RegMI(FirstAI->InstrnsBefore,
487 getFramePointer(), offsetFromFP, UniLRReg, regType);
490 } // if LR received a color
494 // Now, the LR did not receive a color. But it has a stack offset for
496 // So, if the arg is coming in UniArgReg register, we can just move
497 // that on to the stack pos of LR
501 if( regClassIDOfArgReg != RegClassID ) {
503 "FP arguments to a varargs function should be explicitly "
504 "copied to/from int registers by instruction selection!");
506 // It must be a float arg for a variable argument call, which
507 // must come in a %o reg. Move the int reg to the stack.
509 assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
510 "This should only be an Int register for an FP argument");
512 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
513 getFramePointer(), LR->getSpillOffFromFP(), IntRegType);
516 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
517 getFramePointer(), LR->getSpillOffFromFP(), regType);
523 // Now the arg is coming on stack. Since the LR did NOT
524 // recieved a register as well, it is allocated a stack position. We
525 // can simply change the stack position of the LR. We can do this,
526 // since this method is called before any other method that makes
527 // uses of the stack pos of the LR (e.g., updateMachineInstr)
529 const TargetFrameInfo& frameInfo = target.getFrameInfo();
531 frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
534 LR->modifySpillOffFromFP( offsetFromFP );
539 } // for each incoming argument
545 //---------------------------------------------------------------------------
546 // This method is called before graph coloring to suggest colors to the
547 // outgoing call args and the return value of the call.
548 //---------------------------------------------------------------------------
549 void UltraSparcRegInfo::suggestRegs4CallArgs(MachineInstr *CallMI,
550 LiveRangeInfo& LRI) const {
551 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
553 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
555 suggestReg4CallAddr(CallMI, LRI);
557 // First color the return value of the call instruction, if any.
558 // The return value will be in %o0 if the value is an integer type,
559 // or in %f0 if the value is a float type.
561 if (const Value *RetVal = argDesc->getReturnValue()) {
562 LiveRange *RetValLR = LRI.getLiveRangeForValue(RetVal);
563 assert(RetValLR && "No LR for return Value of call!");
565 unsigned RegClassID = RetValLR->getRegClassID();
567 // now suggest a register depending on the register class of ret arg
568 if( RegClassID == IntRegClassID )
569 RetValLR->setSuggestedColor(SparcIntRegClass::o0);
570 else if (RegClassID == FloatRegClassID )
571 RetValLR->setSuggestedColor(SparcFloatRegClass::f0 );
572 else assert( 0 && "Unknown reg class for return value of call\n");
575 // Now suggest colors for arguments (operands) of the call instruction.
576 // Colors are suggested only if the arg number is smaller than the
577 // the number of registers allocated for argument passing.
578 // Now, go thru call args - implicit operands of the call MI
580 unsigned NumOfCallArgs = argDesc->getNumArgs();
582 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
583 i < NumOfCallArgs; ++i, ++argNo) {
585 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
587 // get the LR of call operand (parameter)
588 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
589 assert (LR && "Must have a LR for all arguments since "
590 "all args (even consts) must be defined before");
592 unsigned regType = getRegType(LR);
593 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg (unused)
595 // Choose a register for this arg depending on whether it is
596 // an INT or FP value. Here we ignore whether or not it is a
597 // varargs calls, because FP arguments will be explicitly copied
598 // to an integer Value and handled under (argCopy != NULL) below.
599 int regNum = (regType == IntRegType)
600 ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
601 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
602 : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
603 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
605 // If a register could be allocated, use it.
606 // If not, do NOTHING as this will be colored as a normal value.
607 if(regNum != InvalidRegNum)
608 LR->setSuggestedColor(regNum);
610 // Repeat for the second copy of the argument, which would be
611 // an FP argument being passed to a function with no prototype
612 const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
615 assert(regType != IntRegType && argCopy->getType()->isInteger()
616 && "Must be passing copy of FP argument in int register");
617 int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
618 argNo, intArgNo, fpArgNo-1,
620 assert(copyRegNum != InvalidRegNum);
621 LiveRange *const copyLR = LRI.getLiveRangeForValue(argCopy);
622 copyLR->setSuggestedColor(copyRegNum);
625 } // for all call arguments
630 //---------------------------------------------------------------------------
631 // Helper method for UltraSparcRegInfo::colorCallArgs().
632 //---------------------------------------------------------------------------
635 UltraSparcRegInfo::InitializeOutgoingArg(MachineInstr* CallMI,
636 AddedInstrns *CallAI,
637 PhyRegAlloc &PRA, LiveRange* LR,
638 unsigned regType, unsigned RegClassID,
639 int UniArgRegOrNone, unsigned argNo,
640 std::vector<MachineInstr*> &AddedInstrnsBefore)
644 bool isArgInReg = false;
645 unsigned UniArgReg = BadRegClass; // unused unless initialized below
646 if (UniArgRegOrNone != InvalidRegNum)
649 UniArgReg = (unsigned) UniArgRegOrNone;
650 CallMI->insertUsedReg(UniArgReg); // mark the reg as used
653 if (LR->hasColor()) {
654 unsigned UniLRReg = getUnifiedRegNum(RegClassID, LR->getColor());
656 // if LR received the correct color, nothing to do
657 if( isArgInReg && UniArgReg == UniLRReg )
660 // The LR is allocated to a register UniLRReg and must be copied
661 // to UniArgReg or to the stack slot.
664 // Copy UniLRReg to UniArgReg
665 cpReg2RegMI(AddedInstrnsBefore, UniLRReg, UniArgReg, regType);
668 // Copy UniLRReg to the stack to pass the arg on stack.
669 const TargetFrameInfo& frameInfo = target.getFrameInfo();
670 int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
671 cpReg2MemMI(CallAI->InstrnsBefore,
672 UniLRReg, getStackPointer(), argOffset, regType);
675 } else { // LR is not colored (i.e., spilled)
678 // Insert a load instruction to load the LR to UniArgReg
679 cpMem2RegMI(AddedInstrnsBefore, getFramePointer(),
680 LR->getSpillOffFromFP(), UniArgReg, regType);
681 // Now add the instruction
685 // Now, we have to pass the arg on stack. Since LR also did NOT
686 // receive a register we have to move an argument in memory to
687 // outgoing parameter on stack.
688 // Use TReg to load and store the value.
689 // Use TmpOff to save TReg, since that may have a live value.
691 int TReg = PRA.getUniRegNotUsedByThisInst(LR->getRegClass(), CallMI);
692 int TmpOff = PRA.MF.getInfo()->
693 pushTempValue(getSpilledRegSize(getRegType(LR)));
694 const TargetFrameInfo& frameInfo = target.getFrameInfo();
695 int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
697 MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
700 // (1) Save TReg on stack
701 // (2) Load LR value into TReg from stack pos of LR
702 // (3) Store Treg on outgoing Arg pos on stack
703 // (4) Load the old value of TReg from stack to TReg (restore it)
706 // When reverse pointers in MahineInstr are introduced:
707 // Call PRA.getUnusedRegAtMI(....) to get an unused reg. Step 1 is
708 // needed only if this fails. Currently, we cannot call the
709 // above method since we cannot find LVSetBefore without the BB
711 // NOTE: We directly add to CallAI->InstrnsBefore instead of adding to
712 // AddedInstrnsBefore since these instructions must not be reordered.
713 cpReg2MemMI(CallAI->InstrnsBefore,
714 TReg, getFramePointer(), TmpOff, regType);
715 cpMem2RegMI(CallAI->InstrnsBefore,
716 getFramePointer(), LR->getSpillOffFromFP(), TReg, regType);
717 cpReg2MemMI(CallAI->InstrnsBefore,
718 TReg, getStackPointer(), argOffset, regType);
719 cpMem2RegMI(CallAI->InstrnsBefore,
720 getFramePointer(), TmpOff, TReg, regType);
725 //---------------------------------------------------------------------------
726 // After graph coloring, we have call this method to see whehter the return
727 // value and the call args received the correct colors. If not, we have
728 // to instert copy instructions.
729 //---------------------------------------------------------------------------
731 void UltraSparcRegInfo::colorCallArgs(MachineInstr *CallMI,
733 AddedInstrns *CallAI,
735 const BasicBlock *BB) const {
737 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
739 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
741 // First color the return value of the call.
742 // If there is a LR for the return value, it means this
743 // method returns a value
747 const Value *RetVal = argDesc->getReturnValue();
750 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
753 std::cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
754 assert(RetValLR && "ERR:No LR for non-void return value");
757 unsigned RegClassID = RetValLR->getRegClassID();
758 bool recvCorrectColor;
759 unsigned CorrectCol; // correct color for ret value
760 unsigned UniRetReg; // unified number for CorrectCol
762 if(RegClassID == IntRegClassID)
763 CorrectCol = SparcIntRegClass::o0;
764 else if(RegClassID == FloatRegClassID)
765 CorrectCol = SparcFloatRegClass::f0;
767 assert( 0 && "Unknown RegClass");
771 // convert to unified number
772 UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
774 // Mark the register as used by this instruction
775 CallMI->insertUsedReg(UniRetReg);
777 // if the LR received the correct color, NOTHING to do
778 recvCorrectColor = RetValLR->hasColor()? RetValLR->getColor() == CorrectCol
781 // if we didn't receive the correct color for some reason,
782 // put copy instruction
783 if( !recvCorrectColor ) {
785 unsigned regType = getRegType(RetValLR);
787 if( RetValLR->hasColor() ) {
789 unsigned UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
791 // the return value is coming in UniRetReg but has to go into
794 cpReg2RegMI(CallAI->InstrnsAfter, UniRetReg, UniRetLRReg, regType);
799 // if the LR did NOT receive a color, we have to move the return
800 // value coming in UniRetReg to the stack pos of spilled LR
802 cpReg2MemMI(CallAI->InstrnsAfter, UniRetReg,
803 getFramePointer(),RetValLR->getSpillOffFromFP(), regType);
806 } // the LR didn't receive the suggested color
808 } // if there a return value
811 //-------------------------------------------
812 // Now color all args of the call instruction
813 //-------------------------------------------
815 std::vector<MachineInstr*> AddedInstrnsBefore;
817 unsigned NumOfCallArgs = argDesc->getNumArgs();
819 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
820 i < NumOfCallArgs; ++i, ++argNo) {
822 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
824 // get the LR of call operand (parameter)
825 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
827 unsigned RegClassID = getRegClassIDOfType(CallArg->getType());
828 unsigned regType = getRegType(CallArg->getType());
830 // Find whether this argument is coming in a register (if not, on stack)
831 // Also find the correct register the argument must use (UniArgReg)
833 bool isArgInReg = false;
834 unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
835 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
837 // Find the register that must be used for this arg, depending on
838 // whether it is an INT or FP value. Here we ignore whether or not it
839 // is a varargs calls, because FP arguments will be explicitly copied
840 // to an integer Value and handled under (argCopy != NULL) below.
841 int regNum = (regType == IntRegType)
842 ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
843 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
844 : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
845 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
847 if(regNum != InvalidRegNum) {
849 UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
850 assert(regClassIDOfArgReg == RegClassID &&
851 "Moving values between reg classes must happen during selection");
854 // not possible to have a null LR since all args (even consts)
855 // must be defined before
857 std::cerr <<" ERROR: In call instr, no LR for arg: " <<RAV(CallArg)<<"\n";
858 assert(LR && "NO LR for call arg");
861 InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
862 UniArgReg, argNo, AddedInstrnsBefore);
864 // Repeat for the second copy of the argument, which would be
865 // an FP argument being passed to a function with no prototype.
866 // It may either be passed as a copy in an integer register
867 // (in argCopy), or on the stack (useStackSlot).
868 const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
871 assert(regType != IntRegType && argCopy->getType()->isInteger()
872 && "Must be passing copy of FP argument in int register");
874 unsigned copyRegClassID = getRegClassIDOfType(argCopy->getType());
875 unsigned copyRegType = getRegType(argCopy->getType());
877 int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
878 argNo, intArgNo, fpArgNo-1,
880 assert(copyRegNum != InvalidRegNum);
881 assert(regClassIDOfArgReg == copyRegClassID &&
882 "Moving values between reg classes must happen during selection");
884 InitializeOutgoingArg(CallMI, CallAI, PRA,
885 LRI.getLiveRangeForValue(argCopy), copyRegType,
886 copyRegClassID, copyRegNum, argNo,
890 if (regNum != InvalidRegNum &&
891 argDesc->getArgInfo(i).usesStackSlot())
893 // Pass the argument via the stack in addition to regNum
894 assert(regType != IntRegType && "Passing an integer arg. twice?");
895 assert(!argCopy && "Passing FP arg in FP reg, INT reg, and stack?");
896 InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
897 InvalidRegNum, argNo, AddedInstrnsBefore);
899 } // for each parameter in call instruction
901 // If we added any instruction before the call instruction, verify
902 // that they are in the proper order and if not, reorder them
904 std::vector<MachineInstr*> ReorderedVec;
905 if (!AddedInstrnsBefore.empty()) {
908 std::cerr << "\nCalling reorder with instrns: \n";
909 for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
910 std::cerr << *(AddedInstrnsBefore[i]);
913 OrderAddedInstrns(AddedInstrnsBefore, ReorderedVec, PRA);
914 assert(ReorderedVec.size() >= AddedInstrnsBefore.size()
915 && "Dropped some instructions when reordering!");
918 std::cerr << "\nAfter reordering instrns: \n";
919 for(unsigned i = 0; i < ReorderedVec.size(); i++)
920 std::cerr << *ReorderedVec[i];
924 // Now insert caller saving code for this call instruction
926 insertCallerSavingCode(CallAI->InstrnsBefore, CallAI->InstrnsAfter,
929 // Then insert the final reordered code for the call arguments.
931 for(unsigned i=0; i < ReorderedVec.size(); i++)
932 CallAI->InstrnsBefore.push_back( ReorderedVec[i] );
935 //---------------------------------------------------------------------------
936 // This method is called for an LLVM return instruction to identify which
937 // values will be returned from this method and to suggest colors.
938 //---------------------------------------------------------------------------
939 void UltraSparcRegInfo::suggestReg4RetValue(MachineInstr *RetMI,
940 LiveRangeInfo &LRI) const {
942 assert( (target.getInstrInfo()).isReturn( RetMI->getOpCode() ) );
944 suggestReg4RetAddr(RetMI, LRI);
946 // if there is an implicit ref, that has to be the ret value
947 if( RetMI->getNumImplicitRefs() > 0 ) {
949 // The first implicit operand is the return value of a return instr
950 const Value *RetVal = RetMI->getImplicitRef(0);
952 LiveRange *const LR = LRI.getLiveRangeForValue( RetVal );
955 std::cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
956 assert(0 && "No LR for return value of non-void method");
959 unsigned RegClassID = LR->getRegClassID();
960 if (RegClassID == IntRegClassID)
961 LR->setSuggestedColor(SparcIntRegClass::i0);
962 else if (RegClassID == FloatRegClassID)
963 LR->setSuggestedColor(SparcFloatRegClass::f0);
969 //---------------------------------------------------------------------------
970 // Colors the return value of a method to %i0 or %f0, if possible. If it is
971 // not possilbe to directly color the LR, insert a copy instruction to move
972 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we
973 // have to put a load instruction.
974 //---------------------------------------------------------------------------
975 void UltraSparcRegInfo::colorRetValue(MachineInstr *RetMI,
977 AddedInstrns *RetAI) const {
979 assert((target.getInstrInfo()).isReturn( RetMI->getOpCode()));
981 // if there is an implicit ref, that has to be the ret value
982 if(RetMI->getNumImplicitRefs() > 0) {
984 // The first implicit operand is the return value of a return instr
985 const Value *RetVal = RetMI->getImplicitRef(0);
987 LiveRange *LR = LRI.getLiveRangeForValue(RetVal);
990 std::cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
991 // assert( LR && "No LR for return value of non-void method");
995 unsigned RegClassID = getRegClassIDOfType(RetVal->getType());
996 unsigned regType = getRegType(RetVal->getType());
999 if(RegClassID == IntRegClassID)
1000 CorrectCol = SparcIntRegClass::i0;
1001 else if(RegClassID == FloatRegClassID)
1002 CorrectCol = SparcFloatRegClass::f0;
1004 assert (0 && "Unknown RegClass");
1008 // convert to unified number
1009 unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
1011 // Mark the register as used by this instruction
1012 RetMI->insertUsedReg(UniRetReg);
1014 // if the LR received the correct color, NOTHING to do
1016 if (LR->hasColor() && LR->getColor() == CorrectCol)
1019 if (LR->hasColor()) {
1021 // We are here because the LR was allocted a regiter
1022 // It may be the suggested register or not
1024 // copy the LR of retun value to i0 or f0
1026 unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
1028 // the LR received UniLRReg but must be colored with UniRetReg
1029 // to pass as the return value
1030 cpReg2RegMI(RetAI->InstrnsBefore, UniLRReg, UniRetReg, regType);
1032 else { // if the LR is spilled
1033 cpMem2RegMI(RetAI->InstrnsBefore, getFramePointer(),
1034 LR->getSpillOffFromFP(), UniRetReg, regType);
1035 //std::cerr << "\nCopied the return value from stack\n";
1038 } // if there is a return value
1042 //---------------------------------------------------------------------------
1043 // Check if a specified register type needs a scratch register to be
1044 // copied to/from memory. If it does, the reg. type that must be used
1045 // for scratch registers is returned in scratchRegType.
1047 // Only the int CC register needs such a scratch register.
1048 // The FP CC registers can (and must) be copied directly to/from memory.
1049 //---------------------------------------------------------------------------
1052 UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
1053 int& scratchRegType) const
1055 if (RegType == IntCCRegType)
1057 scratchRegType = IntRegType;
1063 //---------------------------------------------------------------------------
1064 // Copy from a register to register. Register number must be the unified
1066 //---------------------------------------------------------------------------
1069 UltraSparcRegInfo::cpReg2RegMI(std::vector<MachineInstr*>& mvec,
1072 int RegType) const {
1073 assert( ((int)SrcReg != InvalidRegNum) && ((int)DestReg != InvalidRegNum) &&
1074 "Invalid Register");
1076 MachineInstr * MI = NULL;
1081 if (getRegType(DestReg) == IntRegType) {
1082 // copy intCC reg to int reg
1083 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1084 MI = BuildMI(V9::RDCCR, 2).addMReg(SrcReg+1).addMReg(DestReg,MOTy::Def);
1086 // copy int reg to intCC reg
1087 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1088 assert(getRegType(SrcReg) == IntRegType
1089 && "Can only copy CC reg to/from integer reg");
1090 MI = BuildMI(V9::WRCCR, 2).addMReg(SrcReg).addMReg(DestReg+1, MOTy::Def);
1094 case FloatCCRegType:
1095 assert(0 && "Cannot copy FPCC register to any other register");
1099 MI = BuildMI(V9::ADD, 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::STX, Offset));
1136 MI = BuildMI(V9::STX,3).addMReg(SrcReg).addMReg(DestPtrReg).addSImm(Offset);
1139 case FPSingleRegType:
1140 assert(target.getInstrInfo().constantFitsInImmedField(V9::ST, Offset));
1141 MI = BuildMI(V9::ST, 3).addMReg(SrcReg).addMReg(DestPtrReg).addSImm(Offset);
1144 case FPDoubleRegType:
1145 assert(target.getInstrInfo().constantFitsInImmedField(V9::STD, Offset));
1146 MI = BuildMI(V9::STD,3).addMReg(SrcReg).addMReg(DestPtrReg).addSImm(Offset);
1150 assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
1151 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1153 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1154 MI = BuildMI(V9::RDCCR, 2).addMReg(SrcReg+1).addMReg(scratchReg, MOTy::Def);
1157 cpReg2MemMI(mvec, scratchReg, DestPtrReg, Offset, IntRegType);
1160 case FloatCCRegType: {
1161 assert(target.getInstrInfo().constantFitsInImmedField(V9::STXFSR, Offset));
1162 unsigned fsrRegNum = getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
1163 SparcSpecialRegClass::fsr);
1164 MI = BuildMI(V9::STXFSR, 3)
1165 .addMReg(fsrRegNum).addMReg(DestPtrReg).addSImm(Offset);
1169 assert(0 && "Unknown RegType in cpReg2MemMI");
1175 //---------------------------------------------------------------------------
1176 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1178 //---------------------------------------------------------------------------
1182 UltraSparcRegInfo::cpMem2RegMI(std::vector<MachineInstr*>& mvec,
1187 int scratchReg) const {
1188 MachineInstr * MI = NULL;
1191 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDX, Offset));
1192 MI = BuildMI(V9::LDX, 3).addMReg(SrcPtrReg).addSImm(Offset)
1193 .addMReg(DestReg, MOTy::Def);
1196 case FPSingleRegType:
1197 assert(target.getInstrInfo().constantFitsInImmedField(V9::LD, Offset));
1198 MI = BuildMI(V9::LD, 3).addMReg(SrcPtrReg).addSImm(Offset)
1199 .addMReg(DestReg, MOTy::Def);
1202 case FPDoubleRegType:
1203 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDD, Offset));
1204 MI = BuildMI(V9::LDD, 3).addMReg(SrcPtrReg).addSImm(Offset).addMReg(DestReg,
1209 assert(scratchReg >= 0 && "Need scratch reg to load %ccr from memory");
1210 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1211 cpMem2RegMI(mvec, SrcPtrReg, Offset, scratchReg, IntRegType);
1213 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1214 MI = BuildMI(V9::WRCCR, 2).addMReg(scratchReg).addMReg(DestReg+1,MOTy::Def);
1217 case FloatCCRegType: {
1218 assert(target.getInstrInfo().constantFitsInImmedField(V9::LDXFSR, Offset));
1219 unsigned fsrRegNum = getUnifiedRegNum(UltraSparcRegInfo::SpecialRegClassID,
1220 SparcSpecialRegClass::fsr);
1221 MI = BuildMI(V9::LDXFSR, 3).addMReg(SrcPtrReg).addSImm(Offset)
1222 .addMReg(fsrRegNum, MOTy::UseAndDef);
1226 assert(0 && "Unknown RegType in cpMem2RegMI");
1232 //---------------------------------------------------------------------------
1233 // Generate a copy instruction to copy a value to another. Temporarily
1234 // used by PhiElimination code.
1235 //---------------------------------------------------------------------------
1239 UltraSparcRegInfo::cpValue2Value(Value *Src, Value *Dest,
1240 std::vector<MachineInstr*>& mvec) const {
1241 int RegType = getRegType(Src->getType());
1242 MachineInstr * MI = NULL;
1246 MI = BuildMI(V9::ADD, 3).addReg(Src).addMReg(getZeroRegNum())
1249 case FPSingleRegType:
1250 MI = BuildMI(V9::FMOVS, 2).addReg(Src).addRegDef(Dest);
1252 case FPDoubleRegType:
1253 MI = BuildMI(V9::FMOVD, 2).addReg(Src).addRegDef(Dest);
1256 assert(0 && "Unknow RegType in CpValu2Value");
1267 //----------------------------------------------------------------------------
1268 // This method inserts caller saving/restoring instructons before/after
1269 // a call machine instruction. The caller saving/restoring instructions are
1272 // ** caller saving instructions
1273 // other instructions inserted for the call by ColorCallArg
1275 // other instructions inserted for the call ColorCallArg
1276 // ** caller restoring instructions
1278 //----------------------------------------------------------------------------
1282 UltraSparcRegInfo::insertCallerSavingCode
1283 (std::vector<MachineInstr*> &instrnsBefore,
1284 std::vector<MachineInstr*> &instrnsAfter,
1285 MachineInstr *CallMI,
1286 const BasicBlock *BB,
1287 PhyRegAlloc &PRA) const
1289 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
1291 // has set to record which registers were saved/restored
1293 hash_set<unsigned> PushedRegSet;
1295 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
1297 // Now find the LR of the return value of the call
1298 // The last *implicit operand* is the return value of a call
1299 // Insert it to to he PushedRegSet since we must not save that register
1300 // and restore it after the call.
1301 // We do this because, we look at the LV set *after* the instruction
1302 // to determine, which LRs must be saved across calls. The return value
1303 // of the call is live in this set - but we must not save/restore it.
1305 const Value *RetVal = argDesc->getReturnValue();
1308 LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( RetVal );
1309 assert(RetValLR && "No LR for RetValue of call");
1311 if (RetValLR->hasColor())
1312 PushedRegSet.insert(getUnifiedRegNum(RetValLR->getRegClassID(),
1313 RetValLR->getColor()));
1316 const ValueSet &LVSetAft = PRA.LVI->getLiveVarSetAfterMInst(CallMI, BB);
1317 ValueSet::const_iterator LIt = LVSetAft.begin();
1319 // for each live var in live variable set after machine inst
1320 for( ; LIt != LVSetAft.end(); ++LIt) {
1322 // get the live range corresponding to live var
1323 LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );
1325 // LR can be null if it is a const since a const
1326 // doesn't have a dominating def - see Assumptions above
1329 if( LR->hasColor() ) {
1331 unsigned RCID = LR->getRegClassID();
1332 unsigned Color = LR->getColor();
1334 if ( isRegVolatile(RCID, Color) ) {
1336 // if the value is in both LV sets (i.e., live before and after
1337 // the call machine instruction)
1339 unsigned Reg = getUnifiedRegNum(RCID, Color);
1341 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1343 // if we haven't already pushed that register
1345 unsigned RegType = getRegType(LR);
1347 // Now get two instructions - to push on stack and pop from stack
1348 // and add them to InstrnsBefore and InstrnsAfter of the
1352 PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1354 std::vector<MachineInstr*> AdIBef, AdIAft;
1356 //---- Insert code for pushing the reg on stack ----------
1358 // We may need a scratch register to copy the saved value
1359 // to/from memory. This may itself have to insert code to
1360 // free up a scratch register. Any such code should go before
1362 int scratchRegType = -1;
1363 int scratchReg = -1;
1364 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1365 { // Find a register not live in the LVSet before CallMI
1366 const ValueSet &LVSetBef =
1367 PRA.LVI->getLiveVarSetBeforeMInst(CallMI, BB);
1368 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetBef,
1369 CallMI, AdIBef, AdIAft);
1370 assert(scratchReg != getInvalidRegNum());
1371 CallMI->insertUsedReg(scratchReg);
1374 if (AdIBef.size() > 0)
1375 instrnsBefore.insert(instrnsBefore.end(),
1376 AdIBef.begin(), AdIBef.end());
1378 cpReg2MemMI(instrnsBefore, Reg,getFramePointer(),StackOff,RegType,
1381 if (AdIAft.size() > 0)
1382 instrnsBefore.insert(instrnsBefore.end(),
1383 AdIAft.begin(), AdIAft.end());
1385 //---- Insert code for popping the reg from the stack ----------
1387 // We may need a scratch register to copy the saved value
1388 // from memory. This may itself have to insert code to
1389 // free up a scratch register. Any such code should go
1390 // after the save code.
1392 scratchRegType = -1;
1394 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1395 { // Find a register not live in the LVSet after CallMI
1396 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetAft,
1397 CallMI, AdIBef, AdIAft);
1398 assert(scratchReg != getInvalidRegNum());
1399 CallMI->insertUsedReg(scratchReg);
1402 if (AdIBef.size() > 0)
1403 instrnsAfter.insert(instrnsAfter.end(),
1404 AdIBef.begin(), AdIBef.end());
1406 cpMem2RegMI(instrnsAfter, getFramePointer(), StackOff,Reg,RegType,
1409 if (AdIAft.size() > 0)
1410 instrnsAfter.insert(instrnsAfter.end(),
1411 AdIAft.begin(), AdIAft.end());
1413 PushedRegSet.insert(Reg);
1416 std::cerr << "\nFor call inst:" << *CallMI;
1417 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
1418 for_each(instrnsBefore.begin(), instrnsBefore.end(),
1419 std::mem_fun(&MachineInstr::dump));
1420 std::cerr << " -and After:\n\t ";
1421 for_each(instrnsAfter.begin(), instrnsAfter.end(),
1422 std::mem_fun(&MachineInstr::dump));
1424 } // if not already pushed
1426 } // if LR has a volatile color
1428 } // if LR has color
1430 } // if there is a LR for Var
1432 } // for each value in the LV set after instruction
1436 //---------------------------------------------------------------------------
1437 // Print the register assigned to a LR
1438 //---------------------------------------------------------------------------
1440 void UltraSparcRegInfo::printReg(const LiveRange *LR) const {
1441 unsigned RegClassID = LR->getRegClassID();
1442 std::cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1444 if (!LR->hasColor()) {
1445 std::cerr << " - could not find a color\n";
1449 // if a color is found
1451 std::cerr << " colored with color "<< LR->getColor();
1453 unsigned uRegName = getUnifiedRegNum(RegClassID, LR->getColor());
1456 std::cerr<< getUnifiedRegName(uRegName);
1457 if (RegClassID == FloatRegClassID && LR->getType() == Type::DoubleTy)
1458 std::cerr << "+" << getUnifiedRegName(uRegName+1);
1462 //---------------------------------------------------------------------------
1463 // This method examines instructions inserted by RegAlloc code before a
1464 // machine instruction to detect invalid orders that destroy values before
1465 // they are used. If it detects such conditions, it reorders the instructions.
1467 // The unordered instructions come in the UnordVec. These instructions are
1468 // instructions inserted by RegAlloc. All such instruction MUST have
1469 // their USES BEFORE THE DEFS after reordering.
1471 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1472 // this method is called.
1474 // This method uses two vectors for efficiency in accessing
1476 // Since instructions are inserted in RegAlloc, this assumes that the
1477 // first operand is the source reg and the last operand is the dest reg.
1478 // It also does not consider operands that are both use and def.
1480 // All the uses are before THE def to a register
1481 //---------------------------------------------------------------------------
1483 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr*> &UnordVec,
1484 std::vector<MachineInstr*> &OrdVec,
1485 PhyRegAlloc &PRA) const{
1488 Problem: We can have instructions inserted by RegAlloc like
1490 2. add %oy %g0 %oz, where z!=x or z==x
1492 This is wrong since %oy used by 2 is overwritten by 1
1495 We re-order the instructions so that the uses are before the defs
1500 for each instruction 'DefInst' in the UnOrdVec
1501 for each instruction 'UseInst' that follows the DefInst
1502 if the reg defined by DefInst is used by UseInst
1503 mark DefInst as not movable in this iteration
1504 If DefInst is not marked as not-movable, move DefInst to OrdVec
1505 while all instructions in DefInst are moved to OrdVec
1507 For moving, we call the move2OrdVec(). It checks whether there is a def
1508 in it for the uses in the instruction to be added to OrdVec. If there
1509 are no preceding defs, it just appends the instruction. If there is a
1510 preceding def, it puts two instructions to save the reg on stack before
1511 the load and puts a restore at use.
1516 bool DebugPrint = false;
1519 CouldMoveAll = true;
1520 std::vector<MachineInstr*>::iterator DefIt = UnordVec.begin();
1522 for( ; DefIt != UnordVec.end(); ++DefIt ) {
1524 // for each instruction in the UnordVec do ...
1526 MachineInstr *DefInst = *DefIt;
1528 if( DefInst == NULL) continue;
1530 //std::cerr << "\nInst in UnordVec = " << *DefInst;
1532 // last operand is the def (unless for a store which has no def reg)
1533 MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1535 if ((DefOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1536 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1538 // If the operand in DefInst is a def ...
1539 bool DefEqUse = false;
1541 std::vector<MachineInstr*>::iterator UseIt = DefIt;
1544 for( ; UseIt != UnordVec.end(); ++UseIt ) {
1546 MachineInstr *UseInst = *UseIt;
1547 if( UseInst == NULL) continue;
1549 // for each inst (UseInst) that is below the DefInst do ...
1550 MachineOperand& UseOp = UseInst->getOperand(0);
1552 if (!UseOp.opIsDefOnly() &&
1553 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1555 // if use is a register ...
1557 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1559 // if Def and this use are the same, it means that this use
1560 // is destroyed by a def before it is used
1562 // std::cerr << "\nCouldn't move " << *DefInst;
1565 CouldMoveAll = false;
1568 } // if two registers are equal
1570 } // if use is a register
1572 }// for all use instructions
1576 // after examining all the instructions that follow the DefInst
1577 // if there are no dependencies, we can move it to the OrdVec
1579 // std::cerr << "Moved to Ord: " << *DefInst;
1581 moveInst2OrdVec(OrdVec, DefInst, PRA);
1583 //OrdVec.push_back(DefInst);
1585 // mark the pos of DefInst with NULL to indicate that it is
1590 } // if Def is a machine register
1592 } // for all instructions in the UnordVec
1595 } while(!CouldMoveAll);
1597 if (DebugPrint && DEBUG_RA) {
1598 std::cerr << "\nAdded instructions were reordered to:\n";
1599 for(unsigned i=0; i < OrdVec.size(); i++)
1600 std::cerr << *OrdVec[i];
1608 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr*> &OrdVec,
1609 MachineInstr *UnordInst,
1610 PhyRegAlloc &PRA) const {
1611 MachineOperand& UseOp = UnordInst->getOperand(0);
1613 if (!UseOp.opIsDefOnly() &&
1614 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1616 // for the use of UnordInst, see whether there is a defining instr
1617 // before in the OrdVec
1618 bool DefEqUse = false;
1620 std::vector<MachineInstr*>::iterator OrdIt = OrdVec.begin();
1622 for( ; OrdIt != OrdVec.end(); ++OrdIt ) {
1624 MachineInstr *OrdInst = *OrdIt ;
1626 MachineOperand& DefOp =
1627 OrdInst->getOperand(OrdInst->getNumOperands()-1);
1629 if( (DefOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1630 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1632 //std::cerr << "\nDefining Ord Inst: " << *OrdInst;
1634 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1636 // we are here because there is a preceding def in the OrdVec
1637 // for the use in this intr we are going to insert. This
1638 // happened because the original code was like:
1639 // 1. add %ox %g0 %oy
1640 // 2. add %oy %g0 %ox
1641 // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1642 // Now we are processing %ox of 1.
1645 int UReg = DefOp.getMachineRegNum();
1646 int RegType = getRegType(UReg);
1647 MachineInstr *AdIBef, *AdIAft;
1650 PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1652 // Save the UReg (%ox) on stack before it's destroyed
1653 std::vector<MachineInstr*> mvec;
1654 cpReg2MemMI(mvec, UReg, getFramePointer(), StackOff, RegType);
1655 for (std::vector<MachineInstr*>::iterator MI=mvec.begin();
1656 MI != mvec.end(); ++MI)
1657 OrdIt = 1+OrdVec.insert(OrdIt, *MI);
1659 // Load directly into DReg (%oy)
1660 MachineOperand& DOp=
1661 (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1662 assert((DOp.opIsDefOnly() || DefOp.opIsDefAndUse()) &&
1663 "Last operand is not the def");
1664 const int DReg = DOp.getMachineRegNum();
1666 cpMem2RegMI(OrdVec, getFramePointer(), StackOff, DReg, RegType);
1669 std::cerr << "\nFixed CIRCULAR references by reordering:";
1670 std::cerr << "\nBefore CIRCULAR Reordering:\n";
1671 std::cerr << *UnordInst;
1672 std::cerr << *OrdInst;
1674 std::cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1675 for(unsigned i=0; i < OrdVec.size(); i++)
1676 std::cerr << *(OrdVec[i]);
1679 // Do not copy the UseInst to OrdVec
1683 }// if two registers are equal
1685 } // if Def is a register
1687 } // for each instr in OrdVec
1691 // We didn't find a def in the OrdVec, so just append this inst
1692 OrdVec.push_back( UnordInst );
1693 //std::cerr << "Reordered Inst (Moved Dn): " << *UnordInst;
1696 }// if the operand in UnordInst is a use