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"
29 UltraSparcRegInfo::UltraSparcRegInfo(const UltraSparc &tgt)
30 : TargetRegInfo(tgt), NumOfIntArgRegs(6),
31 NumOfFloatArgRegs(32), InvalidRegNum(1000) {
33 MachineRegClassArr.push_back(new SparcIntRegClass(IntRegClassID));
34 MachineRegClassArr.push_back(new SparcFloatRegClass(FloatRegClassID));
35 MachineRegClassArr.push_back(new SparcIntCCRegClass(IntCCRegClassID));
36 MachineRegClassArr.push_back(new SparcFloatCCRegClass(FloatCCRegClassID));
38 assert(SparcFloatRegClass::StartOfNonVolatileRegs == 32 &&
39 "32 Float regs are used for float arg passing");
43 // getZeroRegNum - returns the register that contains always zero.
44 // this is the unified register number
46 int UltraSparcRegInfo::getZeroRegNum() const {
47 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
48 SparcIntRegClass::g0);
51 // getCallAddressReg - returns the reg used for pushing the address when a
52 // method is called. This can be used for other purposes between calls
54 unsigned UltraSparcRegInfo::getCallAddressReg() const {
55 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
56 SparcIntRegClass::o7);
59 // Returns the register containing the return address.
60 // It should be made sure that this register contains the return
61 // value when a return instruction is reached.
63 unsigned UltraSparcRegInfo::getReturnAddressReg() const {
64 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
65 SparcIntRegClass::i7);
68 // Register get name implementations...
70 // Int register names in same order as enum in class SparcIntRegClass
71 static const char * const IntRegNames[] = {
72 "o0", "o1", "o2", "o3", "o4", "o5", "o7",
73 "l0", "l1", "l2", "l3", "l4", "l5", "l6", "l7",
74 "i0", "i1", "i2", "i3", "i4", "i5",
76 "g0", "g1", "g2", "g3", "g4", "g5", "g6", "g7",
80 const char * const SparcIntRegClass::getRegName(unsigned reg) {
81 assert(reg < NumOfAllRegs);
82 return IntRegNames[reg];
85 static const char * const FloatRegNames[] = {
86 "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9",
87 "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19",
88 "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29",
89 "f30", "f31", "f32", "f33", "f34", "f35", "f36", "f37", "f38", "f39",
90 "f40", "f41", "f42", "f43", "f44", "f45", "f46", "f47", "f48", "f49",
91 "f50", "f51", "f52", "f53", "f54", "f55", "f56", "f57", "f58", "f59",
92 "f60", "f61", "f62", "f63"
95 const char * const SparcFloatRegClass::getRegName(unsigned reg) {
96 assert (reg < NumOfAllRegs);
97 return FloatRegNames[reg];
101 static const char * const IntCCRegNames[] = {
105 const char * const SparcIntCCRegClass::getRegName(unsigned reg) {
107 return IntCCRegNames[reg];
110 static const char * const FloatCCRegNames[] = {
111 "fcc0", "fcc1", "fcc2", "fcc3"
114 const char * const SparcFloatCCRegClass::getRegName(unsigned reg) {
116 return FloatCCRegNames[reg];
119 // given the unified register number, this gives the name
120 // for generating assembly code or debugging.
122 const char * const UltraSparcRegInfo::getUnifiedRegName(int reg) const {
124 return SparcIntRegClass::getRegName(reg);
125 else if ( reg < (64 + 32) )
126 return SparcFloatRegClass::getRegName( reg - 32);
127 else if( reg < (64+32+4) )
128 return SparcFloatCCRegClass::getRegName( reg -32 - 64);
129 else if( reg < (64+32+4+2) ) // two names: %xcc and %ccr
130 return SparcIntCCRegClass::getRegName( reg -32 - 64 - 4);
131 else if (reg== InvalidRegNum) //****** TODO: Remove */
134 assert(0 && "Invalid register number");
138 // Get unified reg number for frame pointer
139 unsigned UltraSparcRegInfo::getFramePointer() const {
140 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
141 SparcIntRegClass::i6);
144 // Get unified reg number for stack pointer
145 unsigned UltraSparcRegInfo::getStackPointer() const {
146 return getUnifiedRegNum(UltraSparcRegInfo::IntRegClassID,
147 SparcIntRegClass::o6);
151 //---------------------------------------------------------------------------
152 // Finds whether a call is an indirect call
153 //---------------------------------------------------------------------------
156 isVarArgsFunction(const Type *funcType) {
157 return cast<FunctionType>(cast<PointerType>(funcType)
158 ->getElementType())->isVarArg();
162 isVarArgsCall(const MachineInstr *CallMI) {
163 Value* callee = CallMI->getOperand(0).getVRegValue();
164 // const Type* funcType = isa<Function>(callee)? callee->getType()
165 // : cast<PointerType>(callee->getType())->getElementType();
166 const Type* funcType = callee->getType();
167 return isVarArgsFunction(funcType);
171 // Get the register number for the specified integer arg#,
172 // assuming there are argNum total args, intArgNum int args,
173 // and fpArgNum FP args preceding (and not including) this one.
174 // Use INT regs for FP args if this is a varargs call.
177 // InvalidRegNum, if there is no int register available for the arg.
178 // regNum, otherwise (this is NOT the unified reg. num).
181 UltraSparcRegInfo::regNumForIntArg(bool inCallee, bool isVarArgsCall,
183 unsigned intArgNo, unsigned fpArgNo,
184 unsigned& regClassId) const
186 regClassId = IntRegClassID;
187 if (argNo >= NumOfIntArgRegs)
188 return InvalidRegNum;
190 return argNo + (inCallee? SparcIntRegClass::i0 : SparcIntRegClass::o0);
193 // Get the register number for the specified FP arg#,
194 // assuming there are argNum total args, intArgNum int args,
195 // and fpArgNum FP args preceding (and not including) this one.
196 // Use INT regs for FP args if this is a varargs call.
199 // InvalidRegNum, if there is no int register available for the arg.
200 // regNum, otherwise (this is NOT the unified reg. num).
203 UltraSparcRegInfo::regNumForFPArg(unsigned regType,
204 bool inCallee, bool isVarArgsCall,
206 unsigned intArgNo, unsigned fpArgNo,
207 unsigned& regClassId) const
210 return regNumForIntArg(inCallee, isVarArgsCall, argNo, intArgNo, fpArgNo,
214 regClassId = FloatRegClassID;
215 if (regType == FPSingleRegType)
216 return (argNo*2+1 >= NumOfFloatArgRegs)?
217 InvalidRegNum : SparcFloatRegClass::f0 + (argNo * 2 + 1);
218 else if (regType == FPDoubleRegType)
219 return (argNo*2 >= NumOfFloatArgRegs)?
220 InvalidRegNum : SparcFloatRegClass::f0 + (argNo * 2);
222 assert(0 && "Illegal FP register type");
228 //---------------------------------------------------------------------------
229 // Finds the return address of a call sparc specific call instruction
230 //---------------------------------------------------------------------------
232 // The following 4 methods are used to find the RegType (SparcInternals.h)
233 // of a LiveRange, a Value, and for a given register unified reg number.
235 int UltraSparcRegInfo::getRegType(unsigned regClassID,
236 const Type* type) const {
237 switch (regClassID) {
238 case IntRegClassID: return IntRegType;
239 case FloatRegClassID: {
240 if (type == Type::FloatTy)
241 return FPSingleRegType;
242 else if (type == Type::DoubleTy)
243 return FPDoubleRegType;
244 assert(0 && "Unknown type in FloatRegClass");
246 case IntCCRegClassID: return IntCCRegType;
247 case FloatCCRegClassID: return FloatCCRegType;
248 default: assert( 0 && "Unknown reg class ID"); return 0;
252 int UltraSparcRegInfo::getRegType(const LiveRange *LR) const {
253 return getRegType(LR->getRegClass()->getID(), LR->getType());
256 int UltraSparcRegInfo::getRegType(const Value *Val) const {
257 return getRegType(getRegClassIDOfValue(Val), Val->getType());
260 int UltraSparcRegInfo::getRegType(int unifiedRegNum) const {
261 if (unifiedRegNum < 32)
263 else if (unifiedRegNum < (32 + 32))
264 return FPSingleRegType;
265 else if (unifiedRegNum < (64 + 32))
266 return FPDoubleRegType;
267 else if (unifiedRegNum < (64+32+4))
268 return FloatCCRegType;
269 else if (unifiedRegNum < (64+32+4+2))
272 assert(0 && "Invalid unified register number in getRegType");
277 // To find the register class used for a specified Type
279 unsigned UltraSparcRegInfo::getRegClassIDOfType(const Type *type,
280 bool isCCReg) const {
281 Type::PrimitiveID ty = type->getPrimitiveID();
284 // FIXME: Comparing types like this isn't very safe...
285 if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
286 (ty == Type::FunctionTyID) || (ty == Type::PointerTyID) )
287 res = IntRegClassID; // sparc int reg (ty=0: void)
288 else if (ty <= Type::DoubleTyID)
289 res = FloatRegClassID; // sparc float reg class
291 //std::cerr << "TypeID: " << ty << "\n";
292 assert(0 && "Cannot resolve register class for type");
297 return res + 2; // corresponidng condition code regiser
302 // To find the register class to which a specified register belongs
304 unsigned UltraSparcRegInfo::getRegClassIDOfReg(int unifiedRegNum) const {
305 unsigned classId = 0;
306 (void) getClassRegNum(unifiedRegNum, classId);
310 unsigned UltraSparcRegInfo::getRegClassIDOfRegType(int regType) const {
312 case IntRegType: return IntRegClassID;
313 case FPSingleRegType:
314 case FPDoubleRegType: return FloatRegClassID;
315 case IntCCRegType: return IntCCRegClassID;
316 case FloatCCRegType: return FloatCCRegClassID;
318 assert(0 && "Invalid register type in getRegClassIDOfRegType");
323 //---------------------------------------------------------------------------
324 // Suggests a register for the ret address in the RET machine instruction.
325 // We always suggest %i7 by convention.
326 //---------------------------------------------------------------------------
327 void UltraSparcRegInfo::suggestReg4RetAddr(MachineInstr *RetMI,
328 LiveRangeInfo& LRI) const {
330 assert(target.getInstrInfo().isReturn(RetMI->getOpCode()));
332 // return address is always mapped to i7 so set it immediately
333 RetMI->SetRegForOperand(0, getUnifiedRegNum(IntRegClassID,
334 SparcIntRegClass::i7));
336 // Possible Optimization:
337 // Instead of setting the color, we can suggest one. In that case,
338 // we have to test later whether it received the suggested color.
339 // In that case, a LR has to be created at the start of method.
340 // It has to be done as follows (remove the setRegVal above):
342 // MachineOperand & MO = RetMI->getOperand(0);
343 // const Value *RetAddrVal = MO.getVRegValue();
344 // assert( RetAddrVal && "LR for ret address must be created at start");
345 // LiveRange * RetAddrLR = LRI.getLiveRangeForValue( RetAddrVal);
346 // RetAddrLR->setSuggestedColor(getUnifiedRegNum( IntRegClassID,
347 // SparcIntRegOrdr::i7) );
351 //---------------------------------------------------------------------------
352 // Suggests a register for the ret address in the JMPL/CALL machine instr.
353 // Sparc ABI dictates that %o7 be used for this purpose.
354 //---------------------------------------------------------------------------
356 UltraSparcRegInfo::suggestReg4CallAddr(MachineInstr * CallMI,
357 LiveRangeInfo& LRI) const
359 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
360 const Value *RetAddrVal = argDesc->getReturnAddrReg();
361 assert(RetAddrVal && "INTERNAL ERROR: Return address value is required");
363 // A LR must already exist for the return address.
364 LiveRange *RetAddrLR = LRI.getLiveRangeForValue(RetAddrVal);
365 assert(RetAddrLR && "INTERNAL ERROR: No LR for return address of call!");
367 unsigned RegClassID = RetAddrLR->getRegClass()->getID();
368 RetAddrLR->setColor(getUnifiedRegNum(IntRegClassID, SparcIntRegClass::o7));
373 //---------------------------------------------------------------------------
374 // This method will suggest colors to incoming args to a method.
375 // According to the Sparc ABI, the first 6 incoming args are in
376 // %i0 - %i5 (if they are integer) OR in %f0 - %f31 (if they are float).
377 // If the arg is passed on stack due to the lack of regs, NOTHING will be
378 // done - it will be colored (or spilled) as a normal live range.
379 //---------------------------------------------------------------------------
380 void UltraSparcRegInfo::suggestRegs4MethodArgs(const Function *Meth,
381 LiveRangeInfo& LRI) const
383 // check if this is a varArgs function. needed for choosing regs.
384 bool isVarArgs = isVarArgsFunction(Meth->getType());
386 // for each argument. count INT and FP arguments separately.
387 unsigned argNo=0, intArgNo=0, fpArgNo=0;
388 for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
389 I != E; ++I, ++argNo) {
391 LiveRange *LR = LRI.getLiveRangeForValue(I);
392 assert(LR && "No live range found for method arg");
394 unsigned regType = getRegType(LR);
395 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg (unused)
397 int regNum = (regType == IntRegType)
398 ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
399 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
400 : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
401 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
403 if(regNum != InvalidRegNum)
404 LR->setSuggestedColor(regNum);
409 //---------------------------------------------------------------------------
410 // This method is called after graph coloring to move incoming args to
411 // the correct hardware registers if they did not receive the correct
412 // (suggested) color through graph coloring.
413 //---------------------------------------------------------------------------
414 void UltraSparcRegInfo::colorMethodArgs(const Function *Meth,
416 AddedInstrns *FirstAI) const {
418 // check if this is a varArgs function. needed for choosing regs.
419 bool isVarArgs = isVarArgsFunction(Meth->getType());
423 // for each argument. count INT and FP arguments separately.
424 unsigned argNo=0, intArgNo=0, fpArgNo=0;
425 for(Function::const_aiterator I = Meth->abegin(), E = Meth->aend();
426 I != E; ++I, ++argNo) {
428 LiveRange *LR = LRI.getLiveRangeForValue(I);
429 assert( LR && "No live range found for method arg");
431 unsigned regType = getRegType( LR );
432 unsigned RegClassID = (LR->getRegClass())->getID();
434 // Find whether this argument is coming in a register (if not, on stack)
435 // Also find the correct register the argument must use (UniArgReg)
437 bool isArgInReg = false;
438 unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
439 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
441 int regNum = (regType == IntRegType)
442 ? regNumForIntArg(/*inCallee*/ true, isVarArgs,
443 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
444 : regNumForFPArg(regType, /*inCallee*/ true, isVarArgs,
445 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
447 if(regNum != InvalidRegNum) {
449 UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
452 if( LR->hasColor() ) { // if this arg received a register
454 unsigned UniLRReg = getUnifiedRegNum( RegClassID, LR->getColor() );
456 // if LR received the correct color, nothing to do
458 if( UniLRReg == UniArgReg )
461 // We are here because the LR did not receive the suggested
462 // but LR received another register.
463 // Now we have to copy the %i reg (or stack pos of arg)
464 // to the register the LR was colored with.
466 // if the arg is coming in UniArgReg register, it MUST go into
467 // the UniLRReg register
470 if( regClassIDOfArgReg != RegClassID ) {
471 assert(0 && "This could should work but it is not tested yet");
473 // It is a variable argument call: the float reg must go in a %o reg.
474 // We have to move an int reg to a float reg via memory.
477 RegClassID == FloatRegClassID &&
478 regClassIDOfArgReg == IntRegClassID &&
479 "This should only be an Int register for an FP argument");
481 int TmpOff = MachineFunction::get(Meth).getInfo()->pushTempValue(
482 getSpilledRegSize(regType));
483 cpReg2MemMI(FirstAI->InstrnsBefore,
484 UniArgReg, getFramePointer(), TmpOff, IntRegType);
486 cpMem2RegMI(FirstAI->InstrnsBefore,
487 getFramePointer(), TmpOff, UniLRReg, regType);
490 cpReg2RegMI(FirstAI->InstrnsBefore, UniArgReg, UniLRReg, regType);
495 // Now the arg is coming on stack. Since the LR recieved a register,
496 // we just have to load the arg on stack into that register
498 const TargetFrameInfo& frameInfo = target.getFrameInfo();
500 frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
503 cpMem2RegMI(FirstAI->InstrnsBefore,
504 getFramePointer(), offsetFromFP, UniLRReg, regType);
507 } // if LR received a color
511 // Now, the LR did not receive a color. But it has a stack offset for
513 // So, if the arg is coming in UniArgReg register, we can just move
514 // that on to the stack pos of LR
518 if( regClassIDOfArgReg != RegClassID ) {
520 "FP arguments to a varargs function should be explicitly "
521 "copied to/from int registers by instruction selection!");
523 // It must be a float arg for a variable argument call, which
524 // must come in a %o reg. Move the int reg to the stack.
526 assert(isVarArgs && regClassIDOfArgReg == IntRegClassID &&
527 "This should only be an Int register for an FP argument");
529 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
530 getFramePointer(), LR->getSpillOffFromFP(), IntRegType);
533 cpReg2MemMI(FirstAI->InstrnsBefore, UniArgReg,
534 getFramePointer(), LR->getSpillOffFromFP(), regType);
540 // Now the arg is coming on stack. Since the LR did NOT
541 // recieved a register as well, it is allocated a stack position. We
542 // can simply change the stack position of the LR. We can do this,
543 // since this method is called before any other method that makes
544 // uses of the stack pos of the LR (e.g., updateMachineInstr)
546 const TargetFrameInfo& frameInfo = target.getFrameInfo();
548 frameInfo.getIncomingArgOffset(MachineFunction::get(Meth),
551 LR->modifySpillOffFromFP( offsetFromFP );
556 } // for each incoming argument
562 //---------------------------------------------------------------------------
563 // This method is called before graph coloring to suggest colors to the
564 // outgoing call args and the return value of the call.
565 //---------------------------------------------------------------------------
566 void UltraSparcRegInfo::suggestRegs4CallArgs(MachineInstr *CallMI,
567 LiveRangeInfo& LRI) const {
568 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
570 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
572 suggestReg4CallAddr(CallMI, LRI);
574 // First color the return value of the call instruction, if any.
575 // The return value will be in %o0 if the value is an integer type,
576 // or in %f0 if the value is a float type.
578 if (const Value *RetVal = argDesc->getReturnValue()) {
579 LiveRange *RetValLR = LRI.getLiveRangeForValue(RetVal);
580 assert(RetValLR && "No LR for return Value of call!");
582 unsigned RegClassID = RetValLR->getRegClass()->getID();
584 // now suggest a register depending on the register class of ret arg
585 if( RegClassID == IntRegClassID )
586 RetValLR->setSuggestedColor(SparcIntRegClass::o0);
587 else if (RegClassID == FloatRegClassID )
588 RetValLR->setSuggestedColor(SparcFloatRegClass::f0 );
589 else assert( 0 && "Unknown reg class for return value of call\n");
592 // Now suggest colors for arguments (operands) of the call instruction.
593 // Colors are suggested only if the arg number is smaller than the
594 // the number of registers allocated for argument passing.
595 // Now, go thru call args - implicit operands of the call MI
597 unsigned NumOfCallArgs = argDesc->getNumArgs();
599 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
600 i < NumOfCallArgs; ++i, ++argNo) {
602 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
604 // get the LR of call operand (parameter)
605 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
606 assert (LR && "Must have a LR for all arguments since "
607 "all args (even consts) must be defined before");
609 unsigned regType = getRegType( LR );
610 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg (unused)
612 // Choose a register for this arg depending on whether it is
613 // an INT or FP value. Here we ignore whether or not it is a
614 // varargs calls, because FP arguments will be explicitly copied
615 // to an integer Value and handled under (argCopy != NULL) below.
616 int regNum = (regType == IntRegType)
617 ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
618 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
619 : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
620 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
622 // If a register could be allocated, use it.
623 // If not, do NOTHING as this will be colored as a normal value.
624 if(regNum != InvalidRegNum)
625 LR->setSuggestedColor(regNum);
627 // Repeat for the second copy of the argument, which would be
628 // an FP argument being passed to a function with no prototype
629 const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
632 assert(regType != IntRegType && argCopy->getType()->isInteger()
633 && "Must be passing copy of FP argument in int register");
634 int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
635 argNo, intArgNo, fpArgNo-1,
637 assert(copyRegNum != InvalidRegNum);
638 LiveRange *const copyLR = LRI.getLiveRangeForValue(argCopy);
639 copyLR->setSuggestedColor(copyRegNum);
642 } // for all call arguments
647 //---------------------------------------------------------------------------
648 // Helper method for UltraSparcRegInfo::colorCallArgs().
649 //---------------------------------------------------------------------------
652 UltraSparcRegInfo::InitializeOutgoingArg(MachineInstr* CallMI,
653 AddedInstrns *CallAI,
654 PhyRegAlloc &PRA, LiveRange* LR,
655 unsigned regType, unsigned RegClassID,
656 int UniArgRegOrNone, unsigned argNo,
657 std::vector<MachineInstr *>& AddedInstrnsBefore)
661 bool isArgInReg = false;
662 unsigned UniArgReg = BadRegClass; // unused unless initialized below
663 if (UniArgRegOrNone != InvalidRegNum)
666 UniArgReg = (unsigned) UniArgRegOrNone;
667 CallMI->insertUsedReg(UniArgReg); // mark the reg as used
670 if (LR->hasColor()) {
671 unsigned UniLRReg = getUnifiedRegNum(RegClassID, LR->getColor());
673 // if LR received the correct color, nothing to do
674 if( isArgInReg && UniArgReg == UniLRReg )
677 // The LR is allocated to a register UniLRReg and must be copied
678 // to UniArgReg or to the stack slot.
681 // Copy UniLRReg to UniArgReg
682 cpReg2RegMI(AddedInstrnsBefore, UniLRReg, UniArgReg, regType);
685 // Copy UniLRReg to the stack to pass the arg on stack.
686 const TargetFrameInfo& frameInfo = target.getFrameInfo();
687 int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
688 cpReg2MemMI(CallAI->InstrnsBefore,
689 UniLRReg, getStackPointer(), argOffset, regType);
692 } else { // LR is not colored (i.e., spilled)
695 // Insert a load instruction to load the LR to UniArgReg
696 cpMem2RegMI(AddedInstrnsBefore, getFramePointer(),
697 LR->getSpillOffFromFP(), UniArgReg, regType);
698 // Now add the instruction
702 // Now, we have to pass the arg on stack. Since LR also did NOT
703 // receive a register we have to move an argument in memory to
704 // outgoing parameter on stack.
705 // Use TReg to load and store the value.
706 // Use TmpOff to save TReg, since that may have a live value.
708 int TReg = PRA.getUniRegNotUsedByThisInst( LR->getRegClass(), CallMI );
709 int TmpOff = PRA.MF.getInfo()->
710 pushTempValue(getSpilledRegSize(getRegType(LR)));
711 const TargetFrameInfo& frameInfo = target.getFrameInfo();
712 int argOffset = frameInfo.getOutgoingArgOffset(PRA.MF, argNo);
714 MachineInstr *Ad1, *Ad2, *Ad3, *Ad4;
717 // (1) Save TReg on stack
718 // (2) Load LR value into TReg from stack pos of LR
719 // (3) Store Treg on outgoing Arg pos on stack
720 // (4) Load the old value of TReg from stack to TReg (restore it)
723 // When reverse pointers in MahineInstr are introduced:
724 // Call PRA.getUnusedRegAtMI(....) to get an unused reg. Step 1 is
725 // needed only if this fails. Currently, we cannot call the
726 // above method since we cannot find LVSetBefore without the BB
728 // NOTE: We directly add to CallAI->InstrnsBefore instead of adding to
729 // AddedInstrnsBefore since these instructions must not be reordered.
730 cpReg2MemMI(CallAI->InstrnsBefore,
731 TReg, getFramePointer(), TmpOff, regType);
732 cpMem2RegMI(CallAI->InstrnsBefore,
733 getFramePointer(), LR->getSpillOffFromFP(), TReg, regType);
734 cpReg2MemMI(CallAI->InstrnsBefore,
735 TReg, getStackPointer(), argOffset, regType);
736 cpMem2RegMI(CallAI->InstrnsBefore,
737 getFramePointer(), TmpOff, TReg, regType);
742 //---------------------------------------------------------------------------
743 // After graph coloring, we have call this method to see whehter the return
744 // value and the call args received the correct colors. If not, we have
745 // to instert copy instructions.
746 //---------------------------------------------------------------------------
748 void UltraSparcRegInfo::colorCallArgs(MachineInstr *CallMI,
750 AddedInstrns *CallAI,
752 const BasicBlock *BB) const {
754 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
756 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
758 // First color the return value of the call.
759 // If there is a LR for the return value, it means this
760 // method returns a value
764 const Value *RetVal = argDesc->getReturnValue();
767 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
770 cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
771 assert(RetValLR && "ERR:No LR for non-void return value");
774 unsigned RegClassID = (RetValLR->getRegClass())->getID();
775 bool recvCorrectColor;
776 unsigned CorrectCol; // correct color for ret value
777 unsigned UniRetReg; // unified number for CorrectCol
779 if(RegClassID == IntRegClassID)
780 CorrectCol = SparcIntRegClass::o0;
781 else if(RegClassID == FloatRegClassID)
782 CorrectCol = SparcFloatRegClass::f0;
784 assert( 0 && "Unknown RegClass");
788 // convert to unified number
789 UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
791 // Mark the register as used by this instruction
792 CallMI->insertUsedReg(UniRetReg);
794 // if the LR received the correct color, NOTHING to do
795 recvCorrectColor = RetValLR->hasColor()? RetValLR->getColor() == CorrectCol
798 // if we didn't receive the correct color for some reason,
799 // put copy instruction
800 if( !recvCorrectColor ) {
802 unsigned regType = getRegType( RetValLR );
804 if( RetValLR->hasColor() ) {
806 unsigned UniRetLRReg=getUnifiedRegNum(RegClassID,RetValLR->getColor());
808 // the return value is coming in UniRetReg but has to go into
811 cpReg2RegMI(CallAI->InstrnsAfter, UniRetReg, UniRetLRReg, regType);
816 // if the LR did NOT receive a color, we have to move the return
817 // value coming in UniRetReg to the stack pos of spilled LR
819 cpReg2MemMI(CallAI->InstrnsAfter, UniRetReg,
820 getFramePointer(),RetValLR->getSpillOffFromFP(), regType);
823 } // the LR didn't receive the suggested color
825 } // if there a return value
828 //-------------------------------------------
829 // Now color all args of the call instruction
830 //-------------------------------------------
832 std::vector<MachineInstr *> AddedInstrnsBefore;
834 unsigned NumOfCallArgs = argDesc->getNumArgs();
836 for(unsigned argNo=0, i=0, intArgNo=0, fpArgNo=0;
837 i < NumOfCallArgs; ++i, ++argNo) {
839 const Value *CallArg = argDesc->getArgInfo(i).getArgVal();
841 // get the LR of call operand (parameter)
842 LiveRange *const LR = LRI.getLiveRangeForValue(CallArg);
844 unsigned RegClassID = getRegClassIDOfValue( CallArg);
845 unsigned regType = getRegType( RegClassID, CallArg->getType() );
847 // Find whether this argument is coming in a register (if not, on stack)
848 // Also find the correct register the argument must use (UniArgReg)
850 bool isArgInReg = false;
851 unsigned UniArgReg = InvalidRegNum; // reg that LR MUST be colored with
852 unsigned regClassIDOfArgReg = BadRegClass; // reg class of chosen reg
854 // Find the register that must be used for this arg, depending on
855 // whether it is an INT or FP value. Here we ignore whether or not it
856 // is a varargs calls, because FP arguments will be explicitly copied
857 // to an integer Value and handled under (argCopy != NULL) below.
858 int regNum = (regType == IntRegType)
859 ? regNumForIntArg(/*inCallee*/ false, /*isVarArgs*/ false,
860 argNo, intArgNo++, fpArgNo, regClassIDOfArgReg)
861 : regNumForFPArg(regType, /*inCallee*/ false, /*isVarArgs*/ false,
862 argNo, intArgNo, fpArgNo++, regClassIDOfArgReg);
864 if(regNum != InvalidRegNum) {
866 UniArgReg = getUnifiedRegNum( regClassIDOfArgReg, regNum);
867 assert(regClassIDOfArgReg == RegClassID &&
868 "Moving values between reg classes must happen during selection");
871 // not possible to have a null LR since all args (even consts)
872 // must be defined before
874 cerr << " ERROR: In call instr, no LR for arg: " << RAV(CallArg) <<"\n";
875 assert(LR && "NO LR for call arg");
878 InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
879 UniArgReg, argNo, AddedInstrnsBefore);
881 // Repeat for the second copy of the argument, which would be
882 // an FP argument being passed to a function with no prototype.
883 // It may either be passed as a copy in an integer register
884 // (in argCopy), or on the stack (useStackSlot).
885 const Value *argCopy = argDesc->getArgInfo(i).getArgCopy();
888 assert(regType != IntRegType && argCopy->getType()->isInteger()
889 && "Must be passing copy of FP argument in int register");
891 unsigned copyRegClassID = getRegClassIDOfValue(argCopy);
892 unsigned copyRegType = getRegType(copyRegClassID, argCopy->getType());
894 int copyRegNum = regNumForIntArg(/*inCallee*/false, /*isVarArgs*/false,
895 argNo, intArgNo, fpArgNo-1,
897 assert(copyRegNum != InvalidRegNum);
898 assert(regClassIDOfArgReg == copyRegClassID &&
899 "Moving values between reg classes must happen during selection");
901 InitializeOutgoingArg(CallMI, CallAI, PRA,
902 LRI.getLiveRangeForValue(argCopy), copyRegType,
903 copyRegClassID, copyRegNum, argNo,
907 if (regNum != InvalidRegNum &&
908 argDesc->getArgInfo(i).usesStackSlot())
910 // Pass the argument via the stack in addition to regNum
911 assert(regType != IntRegType && "Passing an integer arg. twice?");
912 assert(!argCopy && "Passing FP arg in FP reg, INT reg, and stack?");
913 InitializeOutgoingArg(CallMI, CallAI, PRA, LR, regType, RegClassID,
914 InvalidRegNum, argNo, AddedInstrnsBefore);
916 } // for each parameter in call instruction
918 // If we added any instruction before the call instruction, verify
919 // that they are in the proper order and if not, reorder them
921 std::vector<MachineInstr *> ReorderedVec;
922 if (!AddedInstrnsBefore.empty()) {
925 cerr << "\nCalling reorder with instrns: \n";
926 for(unsigned i=0; i < AddedInstrnsBefore.size(); i++)
927 cerr << *(AddedInstrnsBefore[i]);
930 OrderAddedInstrns(AddedInstrnsBefore, ReorderedVec, PRA);
931 assert(ReorderedVec.size() >= AddedInstrnsBefore.size()
932 && "Dropped some instructions when reordering!");
935 cerr << "\nAfter reordering instrns: \n";
936 for(unsigned i = 0; i < ReorderedVec.size(); i++)
937 cerr << *ReorderedVec[i];
941 // Now insert caller saving code for this call instruction
943 insertCallerSavingCode(CallAI->InstrnsBefore, CallAI->InstrnsAfter,
946 // Then insert the final reordered code for the call arguments.
948 for(unsigned i=0; i < ReorderedVec.size(); i++)
949 CallAI->InstrnsBefore.push_back( ReorderedVec[i] );
952 //---------------------------------------------------------------------------
953 // This method is called for an LLVM return instruction to identify which
954 // values will be returned from this method and to suggest colors.
955 //---------------------------------------------------------------------------
956 void UltraSparcRegInfo::suggestReg4RetValue(MachineInstr *RetMI,
957 LiveRangeInfo &LRI) const {
959 assert( (target.getInstrInfo()).isReturn( RetMI->getOpCode() ) );
961 suggestReg4RetAddr(RetMI, LRI);
963 // if there is an implicit ref, that has to be the ret value
964 if( RetMI->getNumImplicitRefs() > 0 ) {
966 // The first implicit operand is the return value of a return instr
967 const Value *RetVal = RetMI->getImplicitRef(0);
969 LiveRange *const LR = LRI.getLiveRangeForValue( RetVal );
972 cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
973 assert(0 && "No LR for return value of non-void method");
976 unsigned RegClassID = (LR->getRegClass())->getID();
978 if (RegClassID == IntRegClassID)
979 LR->setSuggestedColor(SparcIntRegClass::i0);
980 else if (RegClassID == FloatRegClassID)
981 LR->setSuggestedColor(SparcFloatRegClass::f0);
987 //---------------------------------------------------------------------------
988 // Colors the return value of a method to %i0 or %f0, if possible. If it is
989 // not possilbe to directly color the LR, insert a copy instruction to move
990 // the LR to %i0 or %f0. When the LR is spilled, instead of the copy, we
991 // have to put a load instruction.
992 //---------------------------------------------------------------------------
993 void UltraSparcRegInfo::colorRetValue(MachineInstr *RetMI,
995 AddedInstrns *RetAI) const {
997 assert((target.getInstrInfo()).isReturn( RetMI->getOpCode()));
999 // if there is an implicit ref, that has to be the ret value
1000 if(RetMI->getNumImplicitRefs() > 0) {
1002 // The first implicit operand is the return value of a return instr
1003 const Value *RetVal = RetMI->getImplicitRef(0);
1005 LiveRange *LR = LRI.getLiveRangeForValue(RetVal);
1008 cerr << "\nNo LR for:" << RAV(RetVal) << "\n";
1009 // assert( LR && "No LR for return value of non-void method");
1013 unsigned RegClassID = getRegClassIDOfValue(RetVal);
1014 unsigned regType = getRegType( RetVal );
1016 unsigned CorrectCol;
1017 if(RegClassID == IntRegClassID)
1018 CorrectCol = SparcIntRegClass::i0;
1019 else if(RegClassID == FloatRegClassID)
1020 CorrectCol = SparcFloatRegClass::f0;
1022 assert (0 && "Unknown RegClass");
1026 // convert to unified number
1027 unsigned UniRetReg = getUnifiedRegNum(RegClassID, CorrectCol);
1029 // Mark the register as used by this instruction
1030 RetMI->insertUsedReg(UniRetReg);
1032 // if the LR received the correct color, NOTHING to do
1034 if (LR->hasColor() && LR->getColor() == CorrectCol)
1037 if (LR->hasColor()) {
1039 // We are here because the LR was allocted a regiter
1040 // It may be the suggested register or not
1042 // copy the LR of retun value to i0 or f0
1044 unsigned UniLRReg =getUnifiedRegNum( RegClassID, LR->getColor());
1046 // the LR received UniLRReg but must be colored with UniRetReg
1047 // to pass as the return value
1048 cpReg2RegMI(RetAI->InstrnsBefore, UniLRReg, UniRetReg, regType);
1050 else { // if the LR is spilled
1051 cpMem2RegMI(RetAI->InstrnsBefore, getFramePointer(),
1052 LR->getSpillOffFromFP(), UniRetReg, regType);
1053 cerr << "\nCopied the return value from stack\n";
1056 } // if there is a return value
1060 //---------------------------------------------------------------------------
1061 // Check if a specified register type needs a scratch register to be
1062 // copied to/from memory. If it does, the reg. type that must be used
1063 // for scratch registers is returned in scratchRegType.
1065 // Only the int CC register needs such a scratch register.
1066 // The FP CC registers can (and must) be copied directly to/from memory.
1067 //---------------------------------------------------------------------------
1070 UltraSparcRegInfo::regTypeNeedsScratchReg(int RegType,
1071 int& scratchRegType) const
1073 if (RegType == IntCCRegType)
1075 scratchRegType = IntRegType;
1081 //---------------------------------------------------------------------------
1082 // Copy from a register to register. Register number must be the unified
1084 //---------------------------------------------------------------------------
1087 UltraSparcRegInfo::cpReg2RegMI(vector<MachineInstr*>& mvec,
1090 int RegType) const {
1091 assert( ((int)SrcReg != InvalidRegNum) && ((int)DestReg != InvalidRegNum) &&
1092 "Invalid Register");
1094 MachineInstr * MI = NULL;
1099 if (getRegType(DestReg) == IntRegType)
1100 { // copy intCC reg to int reg
1101 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1102 MI = BuildMI(RDCCR, 2).addMReg(SrcReg+1).addMReg(DestReg, MOTy::Def);
1105 { // copy int reg to intCC reg
1106 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1107 assert(getRegType(SrcReg) == IntRegType
1108 && "Can only copy CC reg to/from integer reg");
1109 MI = BuildMI(WRCCR, 2).addMReg(SrcReg).addMReg(DestReg+1, MOTy::Def);
1113 case FloatCCRegType:
1114 assert(0 && "Cannot copy FPCC register to any other register");
1118 MI = BuildMI(ADD, 3).addMReg(SrcReg).addMReg(getZeroRegNum())
1119 .addMReg(DestReg, MOTy::Def);
1122 case FPSingleRegType:
1123 MI = BuildMI(FMOVS, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
1126 case FPDoubleRegType:
1127 MI = BuildMI(FMOVD, 2).addMReg(SrcReg).addMReg(DestReg, MOTy::Def);
1131 assert(0 && "Unknown RegType");
1139 //---------------------------------------------------------------------------
1140 // Copy from a register to memory (i.e., Store). Register number must
1141 // be the unified register number
1142 //---------------------------------------------------------------------------
1146 UltraSparcRegInfo::cpReg2MemMI(vector<MachineInstr*>& mvec,
1148 unsigned DestPtrReg,
1149 int Offset, int RegType,
1150 int scratchReg) const {
1151 MachineInstr * MI = NULL;
1154 assert(target.getInstrInfo().constantFitsInImmedField(STX, Offset));
1155 MI = BuildMI(STX, 3).addMReg(SrcReg).addMReg(DestPtrReg).addSImm(Offset);
1158 case FPSingleRegType:
1159 assert(target.getInstrInfo().constantFitsInImmedField(ST, Offset));
1160 MI = BuildMI(ST, 3).addMReg(SrcReg).addMReg(DestPtrReg).addSImm(Offset);
1163 case FPDoubleRegType:
1164 assert(target.getInstrInfo().constantFitsInImmedField(STD, Offset));
1165 MI = BuildMI(STD, 3).addMReg(SrcReg).addMReg(DestPtrReg).addSImm(Offset);
1169 assert(scratchReg >= 0 && "Need scratch reg to store %ccr to memory");
1170 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1172 // Use SrcReg+1 to get the name "%ccr" instead of "%xcc" for RDCCR
1173 MI = BuildMI(RDCCR, 2).addMReg(SrcReg+1).addMReg(scratchReg, MOTy::Def);
1176 cpReg2MemMI(mvec, scratchReg, DestPtrReg, Offset, IntRegType);
1179 case FloatCCRegType:
1180 assert(0 && "Tell Vikram if this assertion fails: we may have to mask out the other bits here");
1181 assert(target.getInstrInfo().constantFitsInImmedField(STXFSR, Offset));
1182 MI = BuildMI(STXFSR, 3).addMReg(SrcReg).addMReg(DestPtrReg).addSImm(Offset);
1186 assert(0 && "Unknown RegType in cpReg2MemMI");
1192 //---------------------------------------------------------------------------
1193 // Copy from memory to a reg (i.e., Load) Register number must be the unified
1195 //---------------------------------------------------------------------------
1199 UltraSparcRegInfo::cpMem2RegMI(vector<MachineInstr*>& mvec,
1204 int scratchReg) const {
1205 MachineInstr * MI = NULL;
1208 assert(target.getInstrInfo().constantFitsInImmedField(LDX, Offset));
1209 MI = BuildMI(LDX, 3).addMReg(SrcPtrReg).addSImm(Offset)
1210 .addMReg(DestReg, MOTy::Def);
1213 case FPSingleRegType:
1214 assert(target.getInstrInfo().constantFitsInImmedField(LD, Offset));
1215 MI = BuildMI(LD, 3).addMReg(SrcPtrReg).addSImm(Offset)
1216 .addMReg(DestReg, MOTy::Def);
1219 case FPDoubleRegType:
1220 assert(target.getInstrInfo().constantFitsInImmedField(LDD, Offset));
1221 MI = BuildMI(LDD, 3).addMReg(SrcPtrReg).addSImm(Offset).addMReg(DestReg,
1226 assert(scratchReg >= 0 && "Need scratch reg to load %ccr from memory");
1227 assert(getRegType(scratchReg) ==IntRegType && "Invalid scratch reg");
1228 cpMem2RegMI(mvec, SrcPtrReg, Offset, scratchReg, IntRegType);
1230 // Use DestReg+1 to get the name "%ccr" instead of "%xcc" for WRCCR
1231 MI = BuildMI(WRCCR, 2).addMReg(scratchReg).addMReg(DestReg+1, MOTy::Def);
1234 case FloatCCRegType:
1235 assert(0 && "Tell Vikram if this assertion fails: we may have to mask "
1236 "out the other bits here");
1237 assert(target.getInstrInfo().constantFitsInImmedField(LDXFSR, Offset));
1238 MI = BuildMI(LDXFSR, 3).addMReg(SrcPtrReg).addSImm(Offset)
1239 .addMReg(DestReg, MOTy::Def);
1243 assert(0 && "Unknown RegType in cpMem2RegMI");
1249 //---------------------------------------------------------------------------
1250 // Generate a copy instruction to copy a value to another. Temporarily
1251 // used by PhiElimination code.
1252 //---------------------------------------------------------------------------
1256 UltraSparcRegInfo::cpValue2Value(Value *Src, Value *Dest,
1257 vector<MachineInstr*>& mvec) const {
1258 int RegType = getRegType( Src );
1260 assert( (RegType==getRegType(Src)) && "Src & Dest are diff types");
1262 MachineInstr * MI = NULL;
1266 MI = BuildMI(ADD, 3).addReg(Src).addMReg(getZeroRegNum()).addRegDef(Dest);
1268 case FPSingleRegType:
1269 MI = BuildMI(FMOVS, 2).addReg(Src).addRegDef(Dest);
1271 case FPDoubleRegType:
1272 MI = BuildMI(FMOVD, 2).addReg(Src).addRegDef(Dest);
1275 assert(0 && "Unknow RegType in CpValu2Value");
1286 //----------------------------------------------------------------------------
1287 // This method inserts caller saving/restoring instructons before/after
1288 // a call machine instruction. The caller saving/restoring instructions are
1291 // ** caller saving instructions
1292 // other instructions inserted for the call by ColorCallArg
1294 // other instructions inserted for the call ColorCallArg
1295 // ** caller restoring instructions
1297 //----------------------------------------------------------------------------
1301 UltraSparcRegInfo::insertCallerSavingCode(vector<MachineInstr*>& instrnsBefore,
1302 vector<MachineInstr*>& instrnsAfter,
1303 MachineInstr *CallMI,
1304 const BasicBlock *BB,
1305 PhyRegAlloc &PRA) const
1307 assert ( (target.getInstrInfo()).isCall(CallMI->getOpCode()) );
1309 // has set to record which registers were saved/restored
1311 hash_set<unsigned> PushedRegSet;
1313 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
1315 // Now find the LR of the return value of the call
1316 // The last *implicit operand* is the return value of a call
1317 // Insert it to to he PushedRegSet since we must not save that register
1318 // and restore it after the call.
1319 // We do this because, we look at the LV set *after* the instruction
1320 // to determine, which LRs must be saved across calls. The return value
1321 // of the call is live in this set - but we must not save/restore it.
1323 const Value *RetVal = argDesc->getReturnValue();
1326 LiveRange *RetValLR = PRA.LRI.getLiveRangeForValue( RetVal );
1327 assert(RetValLR && "No LR for RetValue of call");
1329 if (RetValLR->hasColor())
1330 PushedRegSet.insert(
1331 getUnifiedRegNum((RetValLR->getRegClass())->getID(),
1332 RetValLR->getColor() ) );
1335 const ValueSet &LVSetAft = PRA.LVI->getLiveVarSetAfterMInst(CallMI, BB);
1336 ValueSet::const_iterator LIt = LVSetAft.begin();
1338 // for each live var in live variable set after machine inst
1339 for( ; LIt != LVSetAft.end(); ++LIt) {
1341 // get the live range corresponding to live var
1342 LiveRange *const LR = PRA.LRI.getLiveRangeForValue(*LIt );
1344 // LR can be null if it is a const since a const
1345 // doesn't have a dominating def - see Assumptions above
1348 if( LR->hasColor() ) {
1350 unsigned RCID = (LR->getRegClass())->getID();
1351 unsigned Color = LR->getColor();
1353 if ( isRegVolatile(RCID, Color) ) {
1355 // if the value is in both LV sets (i.e., live before and after
1356 // the call machine instruction)
1358 unsigned Reg = getUnifiedRegNum(RCID, Color);
1360 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
1362 // if we haven't already pushed that register
1364 unsigned RegType = getRegType( LR );
1366 // Now get two instructions - to push on stack and pop from stack
1367 // and add them to InstrnsBefore and InstrnsAfter of the
1371 PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1373 vector<MachineInstr*> AdIBef, AdIAft;
1375 //---- Insert code for pushing the reg on stack ----------
1377 // We may need a scratch register to copy the saved value
1378 // to/from memory. This may itself have to insert code to
1379 // free up a scratch register. Any such code should go before
1381 int scratchRegType = -1;
1382 int scratchReg = -1;
1383 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1384 { // Find a register not live in the LVSet before CallMI
1385 const ValueSet &LVSetBef =
1386 PRA.LVI->getLiveVarSetBeforeMInst(CallMI, BB);
1387 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetBef,
1388 CallMI, AdIBef, AdIAft);
1389 assert(scratchReg != getInvalidRegNum());
1390 CallMI->insertUsedReg(scratchReg);
1393 if (AdIBef.size() > 0)
1394 instrnsBefore.insert(instrnsBefore.end(),
1395 AdIBef.begin(), AdIBef.end());
1397 cpReg2MemMI(instrnsBefore, Reg,getFramePointer(),StackOff,RegType,
1400 if (AdIAft.size() > 0)
1401 instrnsBefore.insert(instrnsBefore.end(),
1402 AdIAft.begin(), AdIAft.end());
1404 //---- Insert code for popping the reg from the stack ----------
1406 // We may need a scratch register to copy the saved value
1407 // from memory. This may itself have to insert code to
1408 // free up a scratch register. Any such code should go
1409 // after the save code.
1411 scratchRegType = -1;
1413 if (regTypeNeedsScratchReg(RegType, scratchRegType))
1414 { // Find a register not live in the LVSet after CallMI
1415 scratchReg = PRA.getUsableUniRegAtMI(scratchRegType, &LVSetAft,
1416 CallMI, AdIBef, AdIAft);
1417 assert(scratchReg != getInvalidRegNum());
1418 CallMI->insertUsedReg(scratchReg);
1421 if (AdIBef.size() > 0)
1422 instrnsAfter.insert(instrnsAfter.end(),
1423 AdIBef.begin(), AdIBef.end());
1425 cpMem2RegMI(instrnsAfter, getFramePointer(), StackOff,Reg,RegType,
1428 if (AdIAft.size() > 0)
1429 instrnsAfter.insert(instrnsAfter.end(),
1430 AdIAft.begin(), AdIAft.end());
1432 PushedRegSet.insert(Reg);
1435 cerr << "\nFor call inst:" << *CallMI;
1436 cerr << " -inserted caller saving instrs: Before:\n\t ";
1437 for_each(instrnsBefore.begin(), instrnsBefore.end(),
1438 std::mem_fun(&MachineInstr::dump));
1439 cerr << " -and After:\n\t ";
1440 for_each(instrnsAfter.begin(), instrnsAfter.end(),
1441 std::mem_fun(&MachineInstr::dump));
1443 } // if not already pushed
1445 } // if LR has a volatile color
1447 } // if LR has color
1449 } // if there is a LR for Var
1451 } // for each value in the LV set after instruction
1455 //---------------------------------------------------------------------------
1456 // Print the register assigned to a LR
1457 //---------------------------------------------------------------------------
1459 void UltraSparcRegInfo::printReg(const LiveRange *LR) {
1460 unsigned RegClassID = (LR->getRegClass())->getID();
1461 cerr << " *Node " << (LR->getUserIGNode())->getIndex();
1463 if (!LR->hasColor()) {
1464 cerr << " - could not find a color\n";
1468 // if a color is found
1470 cerr << " colored with color "<< LR->getColor();
1472 if (RegClassID == IntRegClassID) {
1473 cerr<< " [" << SparcIntRegClass::getRegName(LR->getColor()) << "]\n";
1475 } else if (RegClassID == FloatRegClassID) {
1476 cerr << "[" << SparcFloatRegClass::getRegName(LR->getColor());
1477 if( LR->getType() == Type::DoubleTy)
1478 cerr << "+" << SparcFloatRegClass::getRegName(LR->getColor()+1);
1483 //---------------------------------------------------------------------------
1484 // This method examines instructions inserted by RegAlloc code before a
1485 // machine instruction to detect invalid orders that destroy values before
1486 // they are used. If it detects such conditions, it reorders the instructions.
1488 // The unordered instructions come in the UnordVec. These instructions are
1489 // instructions inserted by RegAlloc. All such instruction MUST have
1490 // their USES BEFORE THE DEFS after reordering.
1492 // The UnordVec & OrdVec must be DISTINCT. The OrdVec must be empty when
1493 // this method is called.
1495 // This method uses two vectors for efficiency in accessing
1497 // Since instructions are inserted in RegAlloc, this assumes that the
1498 // first operand is the source reg and the last operand is the dest reg.
1499 // It also does not consider operands that are both use and def.
1501 // All the uses are before THE def to a register
1502 //---------------------------------------------------------------------------
1504 void UltraSparcRegInfo::OrderAddedInstrns(std::vector<MachineInstr*> &UnordVec,
1505 std::vector<MachineInstr*> &OrdVec,
1506 PhyRegAlloc &PRA) const{
1509 Problem: We can have instructions inserted by RegAlloc like
1511 2. add %oy %g0 %oz, where z!=x or z==x
1513 This is wrong since %oy used by 2 is overwritten by 1
1516 We re-order the instructions so that the uses are before the defs
1521 for each instruction 'DefInst' in the UnOrdVec
1522 for each instruction 'UseInst' that follows the DefInst
1523 if the reg defined by DefInst is used by UseInst
1524 mark DefInst as not movable in this iteration
1525 If DefInst is not marked as not-movable, move DefInst to OrdVec
1526 while all instructions in DefInst are moved to OrdVec
1528 For moving, we call the move2OrdVec(). It checks whether there is a def
1529 in it for the uses in the instruction to be added to OrdVec. If there
1530 are no preceding defs, it just appends the instruction. If there is a
1531 preceding def, it puts two instructions to save the reg on stack before
1532 the load and puts a restore at use.
1537 bool DebugPrint = false;
1540 CouldMoveAll = true;
1541 std::vector<MachineInstr *>::iterator DefIt = UnordVec.begin();
1543 for( ; DefIt != UnordVec.end(); ++DefIt ) {
1545 // for each instruction in the UnordVec do ...
1547 MachineInstr *DefInst = *DefIt;
1549 if( DefInst == NULL) continue;
1551 //cerr << "\nInst in UnordVec = " << *DefInst;
1553 // last operand is the def (unless for a store which has no def reg)
1554 MachineOperand& DefOp = DefInst->getOperand(DefInst->getNumOperands()-1);
1556 if (DefOp.opIsDef() &&
1557 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1559 // If the operand in DefInst is a def ...
1560 bool DefEqUse = false;
1562 std::vector<MachineInstr *>::iterator UseIt = DefIt;
1565 for( ; UseIt != UnordVec.end(); ++UseIt ) {
1567 MachineInstr *UseInst = *UseIt;
1568 if( UseInst == NULL) continue;
1570 // for each inst (UseInst) that is below the DefInst do ...
1571 MachineOperand& UseOp = UseInst->getOperand(0);
1573 if (!UseOp.opIsDef() &&
1574 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1576 // if use is a register ...
1578 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1580 // if Def and this use are the same, it means that this use
1581 // is destroyed by a def before it is used
1583 // cerr << "\nCouldn't move " << *DefInst;
1586 CouldMoveAll = false;
1589 } // if two registers are equal
1591 } // if use is a register
1593 }// for all use instructions
1597 // after examining all the instructions that follow the DefInst
1598 // if there are no dependencies, we can move it to the OrdVec
1600 // cerr << "Moved to Ord: " << *DefInst;
1602 moveInst2OrdVec(OrdVec, DefInst, PRA);
1604 //OrdVec.push_back(DefInst);
1606 // mark the pos of DefInst with NULL to indicate that it is
1611 } // if Def is a machine register
1613 } // for all instructions in the UnordVec
1616 } while(!CouldMoveAll);
1618 if (DebugPrint && DEBUG_RA) {
1619 cerr << "\nAdded instructions were reordered to:\n";
1620 for(unsigned i=0; i < OrdVec.size(); i++)
1629 void UltraSparcRegInfo::moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
1630 MachineInstr *UnordInst,
1631 PhyRegAlloc &PRA) const {
1632 MachineOperand& UseOp = UnordInst->getOperand(0);
1634 if (!UseOp.opIsDef() &&
1635 UseOp.getType() == MachineOperand::MO_MachineRegister) {
1637 // for the use of UnordInst, see whether there is a defining instr
1638 // before in the OrdVec
1639 bool DefEqUse = false;
1641 std::vector<MachineInstr *>::iterator OrdIt = OrdVec.begin();
1643 for( ; OrdIt != OrdVec.end(); ++OrdIt ) {
1645 MachineInstr *OrdInst = *OrdIt ;
1647 MachineOperand& DefOp =
1648 OrdInst->getOperand(OrdInst->getNumOperands()-1);
1650 if( DefOp.opIsDef() &&
1651 DefOp.getType() == MachineOperand::MO_MachineRegister) {
1653 //cerr << "\nDefining Ord Inst: " << *OrdInst;
1655 if( DefOp.getMachineRegNum() == UseOp.getMachineRegNum() ) {
1657 // we are here because there is a preceding def in the OrdVec
1658 // for the use in this intr we are going to insert. This
1659 // happened because the original code was like:
1660 // 1. add %ox %g0 %oy
1661 // 2. add %oy %g0 %ox
1662 // In Round1, we added 2 to OrdVec but 1 remained in UnordVec
1663 // Now we are processing %ox of 1.
1666 int UReg = DefOp.getMachineRegNum();
1667 int RegType = getRegType(UReg);
1668 MachineInstr *AdIBef, *AdIAft;
1671 PRA.MF.getInfo()->pushTempValue(getSpilledRegSize(RegType));
1673 // Save the UReg (%ox) on stack before it's destroyed
1674 vector<MachineInstr*> mvec;
1675 cpReg2MemMI(mvec, UReg, getFramePointer(), StackOff, RegType);
1676 for (vector<MachineInstr*>::iterator MI=mvec.begin();
1677 MI != mvec.end(); ++MI)
1678 OrdIt = 1+OrdVec.insert(OrdIt, *MI);
1680 // Load directly into DReg (%oy)
1681 MachineOperand& DOp=
1682 (UnordInst->getOperand(UnordInst->getNumOperands()-1));
1683 assert(DOp.opIsDef() && "Last operand is not the def");
1684 const int DReg = DOp.getMachineRegNum();
1686 cpMem2RegMI(OrdVec, getFramePointer(), StackOff, DReg, RegType);
1689 cerr << "\nFixed CIRCULAR references by reordering:";
1690 cerr << "\nBefore CIRCULAR Reordering:\n";
1694 cerr << "\nAfter CIRCULAR Reordering - All Inst so far:\n";
1695 for(unsigned i=0; i < OrdVec.size(); i++)
1696 cerr << *(OrdVec[i]);
1699 // Do not copy the UseInst to OrdVec
1703 }// if two registers are equal
1705 } // if Def is a register
1707 } // for each instr in OrdVec
1711 // We didn't find a def in the OrdVec, so just append this inst
1712 OrdVec.push_back( UnordInst );
1713 //cerr << "Reordered Inst (Moved Dn): " << *UnordInst;
1716 }// if the operand in UnordInst is a use