2 //***************************************************************************
4 // SparcInstrSelection.cpp
7 // BURS instruction selection for SPARC V9 architecture.
10 // 7/02/01 - Vikram Adve - Created
11 //**************************************************************************/
13 #include "SparcInternals.h"
14 #include "llvm/CodeGen/InstrSelectionSupport.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/InstrForest.h"
17 #include "llvm/CodeGen/InstrSelection.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/iTerminators.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iOther.h"
23 #include "llvm/BasicBlock.h"
24 #include "llvm/Method.h"
25 #include "llvm/ConstPoolVals.h"
28 //******************** Internal Data Declarations ************************/
31 struct BranchPattern {
32 bool flipCondition; // should the sense of the test be reversed
33 BasicBlock* targetBB; // which basic block to branch to
34 MachineInstr* extraBranch; // if neither branch is fall-through, then this
35 // BA must be inserted after the cond'l one
38 //************************* Forward Declarations ***************************/
41 static void SetMemOperands_Internal (MachineInstr* minstr,
42 const InstructionNode* vmInstrNode,
44 Value* arrayOffsetVal,
45 const vector<ConstPoolVal*>& idxVec,
46 const TargetMachine& target);
49 //************************ Internal Functions ******************************/
51 // Convenience function to get the value of an integer constant, for an
52 // appropriate integer or non-integer type that can be held in an integer.
53 // The type of the argument must be the following:
54 // Signed or unsigned integer
58 // isValidConstant is set to true if a valid constant was found.
61 GetConstantValueAsSignedInt(const Value *V,
62 bool &isValidConstant)
64 if (!isa<ConstPoolVal>(V))
66 isValidConstant = false;
70 isValidConstant = true;
72 if (V->getType() == Type::BoolTy)
73 return (int64_t) ((ConstPoolBool*)V)->getValue();
75 if (V->getType()->isIntegral())
77 if (V->getType()->isSigned())
78 return ((ConstPoolSInt*)V)->getValue();
80 assert(V->getType()->isUnsigned());
81 uint64_t Val = ((ConstPoolUInt*)V)->getValue();
82 if (Val < INT64_MAX) // then safe to cast to signed
86 isValidConstant = false;
92 //------------------------------------------------------------------------
93 // External Function: ThisIsAChainRule
96 // Check if a given BURG rule is a chain rule.
97 //------------------------------------------------------------------------
100 ThisIsAChainRule(int eruleno)
104 case 111: // stmt: reg
105 case 113: // stmt: bool
132 static inline MachineOpCode
133 ChooseBprInstruction(const InstructionNode* instrNode)
135 MachineOpCode opCode;
137 Instruction* setCCInstr =
138 ((InstructionNode*) instrNode->leftChild())->getInstruction();
140 switch(setCCInstr->getOpcode())
142 case Instruction::SetEQ: opCode = BRZ; break;
143 case Instruction::SetNE: opCode = BRNZ; break;
144 case Instruction::SetLE: opCode = BRLEZ; break;
145 case Instruction::SetGE: opCode = BRGEZ; break;
146 case Instruction::SetLT: opCode = BRLZ; break;
147 case Instruction::SetGT: opCode = BRGZ; break;
149 assert(0 && "Unrecognized VM instruction!");
150 opCode = INVALID_OPCODE;
158 static inline MachineOpCode
159 ChooseBpccInstruction(const InstructionNode* instrNode,
160 const BinaryOperator* setCCInstr)
162 MachineOpCode opCode = INVALID_OPCODE;
164 bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
168 switch(setCCInstr->getOpcode())
170 case Instruction::SetEQ: opCode = BE; break;
171 case Instruction::SetNE: opCode = BNE; break;
172 case Instruction::SetLE: opCode = BLE; break;
173 case Instruction::SetGE: opCode = BGE; break;
174 case Instruction::SetLT: opCode = BL; break;
175 case Instruction::SetGT: opCode = BG; break;
177 assert(0 && "Unrecognized VM instruction!");
183 switch(setCCInstr->getOpcode())
185 case Instruction::SetEQ: opCode = BE; break;
186 case Instruction::SetNE: opCode = BNE; break;
187 case Instruction::SetLE: opCode = BLEU; break;
188 case Instruction::SetGE: opCode = BCC; break;
189 case Instruction::SetLT: opCode = BCS; break;
190 case Instruction::SetGT: opCode = BGU; break;
192 assert(0 && "Unrecognized VM instruction!");
200 static inline MachineOpCode
201 ChooseBFpccInstruction(const InstructionNode* instrNode,
202 const BinaryOperator* setCCInstr)
204 MachineOpCode opCode = INVALID_OPCODE;
206 switch(setCCInstr->getOpcode())
208 case Instruction::SetEQ: opCode = FBE; break;
209 case Instruction::SetNE: opCode = FBNE; break;
210 case Instruction::SetLE: opCode = FBLE; break;
211 case Instruction::SetGE: opCode = FBGE; break;
212 case Instruction::SetLT: opCode = FBL; break;
213 case Instruction::SetGT: opCode = FBG; break;
215 assert(0 && "Unrecognized VM instruction!");
223 static inline MachineOpCode
224 ChooseBccInstruction(const InstructionNode* instrNode,
227 InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
228 BinaryOperator* setCCInstr = (BinaryOperator*) setCCNode->getInstruction();
229 const Type* setCCType = setCCInstr->getOperand(0)->getType();
231 isFPBranch = (setCCType == Type::FloatTy || setCCType == Type::DoubleTy);
234 return ChooseBFpccInstruction(instrNode, setCCInstr);
236 return ChooseBpccInstruction(instrNode, setCCInstr);
240 static inline MachineOpCode
241 ChooseMovFpccInstruction(const InstructionNode* instrNode)
243 MachineOpCode opCode = INVALID_OPCODE;
245 switch(instrNode->getInstruction()->getOpcode())
247 case Instruction::SetEQ: opCode = MOVFE; break;
248 case Instruction::SetNE: opCode = MOVFNE; break;
249 case Instruction::SetLE: opCode = MOVFLE; break;
250 case Instruction::SetGE: opCode = MOVFGE; break;
251 case Instruction::SetLT: opCode = MOVFL; break;
252 case Instruction::SetGT: opCode = MOVFG; break;
254 assert(0 && "Unrecognized VM instruction!");
262 // Assumes that SUBcc v1, v2 -> v3 has been executed.
263 // In most cases, we want to clear v3 and then follow it by instruction
265 // Set mustClearReg=false if v3 need not be cleared before conditional move.
266 // Set valueToMove=0 if we want to conditionally move 0 instead of 1
267 // (i.e., we want to test inverse of a condition)
268 // (The latter two cases do not seem to arise because SetNE needs nothing.)
271 ChooseMovpccAfterSub(const InstructionNode* instrNode,
275 MachineOpCode opCode = INVALID_OPCODE;
279 switch(instrNode->getInstruction()->getOpcode())
281 case Instruction::SetEQ: opCode = MOVE; break;
282 case Instruction::SetLE: opCode = MOVLE; break;
283 case Instruction::SetGE: opCode = MOVGE; break;
284 case Instruction::SetLT: opCode = MOVL; break;
285 case Instruction::SetGT: opCode = MOVG; break;
286 case Instruction::SetNE: assert(0 && "No move required!"); break;
287 default: assert(0 && "Unrecognized VM instr!"); break;
294 static inline MachineOpCode
295 ChooseConvertToFloatInstr(const InstructionNode* instrNode,
298 MachineOpCode opCode = INVALID_OPCODE;
300 switch(instrNode->getOpLabel())
303 if (opType == Type::SByteTy || opType == Type::ShortTy || opType == Type::IntTy)
305 else if (opType == Type::LongTy)
307 else if (opType == Type::DoubleTy)
309 else if (opType == Type::FloatTy)
312 assert(0 && "Cannot convert this type to FLOAT on SPARC");
316 if (opType == Type::SByteTy || opType == Type::ShortTy || opType == Type::IntTy)
318 else if (opType == Type::LongTy)
320 else if (opType == Type::FloatTy)
322 else if (opType == Type::DoubleTy)
325 assert(0 && "Cannot convert this type to DOUBLE on SPARC");
335 static inline MachineOpCode
336 ChooseConvertToIntInstr(const InstructionNode* instrNode,
339 MachineOpCode opCode = INVALID_OPCODE;;
341 int instrType = (int) instrNode->getOpLabel();
343 if (instrType == ToSByteTy || instrType == ToShortTy || instrType == ToIntTy)
345 switch (opType->getPrimitiveID())
347 case Type::FloatTyID: opCode = FSTOI; break;
348 case Type::DoubleTyID: opCode = FDTOI; break;
350 assert(0 && "Non-numeric non-bool type cannot be converted to Int");
354 else if (instrType == ToLongTy)
356 switch (opType->getPrimitiveID())
358 case Type::FloatTyID: opCode = FSTOX; break;
359 case Type::DoubleTyID: opCode = FDTOX; break;
361 assert(0 && "Non-numeric non-bool type cannot be converted to Long");
366 assert(0 && "Should not get here, Mo!");
372 static inline MachineOpCode
373 ChooseAddInstructionByType(const Type* resultType)
375 MachineOpCode opCode = INVALID_OPCODE;
377 if (resultType->isIntegral() ||
378 isa<PointerType>(resultType) ||
379 isa<MethodType>(resultType) ||
380 resultType->isLabelType() ||
381 resultType == Type::BoolTy)
386 switch(resultType->getPrimitiveID())
388 case Type::FloatTyID: opCode = FADDS; break;
389 case Type::DoubleTyID: opCode = FADDD; break;
390 default: assert(0 && "Invalid type for ADD instruction"); break;
397 static inline MachineOpCode
398 ChooseAddInstruction(const InstructionNode* instrNode)
400 return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
404 static inline MachineInstr*
405 CreateMovFloatInstruction(const InstructionNode* instrNode,
406 const Type* resultType)
408 MachineInstr* minstr = new MachineInstr((resultType == Type::FloatTy)
410 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
411 instrNode->leftChild()->getValue());
412 minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
413 instrNode->getValue());
417 static inline MachineInstr*
418 CreateAddConstInstruction(const InstructionNode* instrNode)
420 MachineInstr* minstr = NULL;
422 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
423 assert(isa<ConstPoolVal>(constOp));
425 // Cases worth optimizing are:
426 // (1) Add with 0 for float or double: use an FMOV of appropriate type,
427 // instead of an FADD (1 vs 3 cycles). There is no integer MOV.
429 const Type* resultType = instrNode->getInstruction()->getType();
431 if (resultType == Type::FloatTy ||
432 resultType == Type::DoubleTy)
434 double dval = ((ConstPoolFP*) constOp)->getValue();
436 minstr = CreateMovFloatInstruction(instrNode, resultType);
443 static inline MachineOpCode
444 ChooseSubInstruction(const InstructionNode* instrNode)
446 MachineOpCode opCode = INVALID_OPCODE;
448 const Type* resultType = instrNode->getInstruction()->getType();
450 if (resultType->isIntegral() ||
451 resultType->isPointerType())
456 switch(resultType->getPrimitiveID())
458 case Type::FloatTyID: opCode = FSUBS; break;
459 case Type::DoubleTyID: opCode = FSUBD; break;
460 default: assert(0 && "Invalid type for SUB instruction"); break;
467 static inline MachineInstr*
468 CreateSubConstInstruction(const InstructionNode* instrNode)
470 MachineInstr* minstr = NULL;
472 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
473 assert(isa<ConstPoolVal>(constOp));
475 // Cases worth optimizing are:
476 // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
477 // instead of an FSUB (1 vs 3 cycles). There is no integer MOV.
479 const Type* resultType = instrNode->getInstruction()->getType();
481 if (resultType == Type::FloatTy ||
482 resultType == Type::DoubleTy)
484 double dval = ((ConstPoolFP*) constOp)->getValue();
486 minstr = CreateMovFloatInstruction(instrNode, resultType);
493 static inline MachineOpCode
494 ChooseFcmpInstruction(const InstructionNode* instrNode)
496 MachineOpCode opCode = INVALID_OPCODE;
498 Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
499 switch(operand->getType()->getPrimitiveID()) {
500 case Type::FloatTyID: opCode = FCMPS; break;
501 case Type::DoubleTyID: opCode = FCMPD; break;
502 default: assert(0 && "Invalid type for FCMP instruction"); break;
509 // Assumes that leftArg and rightArg are both cast instructions.
512 BothFloatToDouble(const InstructionNode* instrNode)
514 InstrTreeNode* leftArg = instrNode->leftChild();
515 InstrTreeNode* rightArg = instrNode->rightChild();
516 InstrTreeNode* leftArgArg = leftArg->leftChild();
517 InstrTreeNode* rightArgArg = rightArg->leftChild();
518 assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
520 // Check if both arguments are floats cast to double
521 return (leftArg->getValue()->getType() == Type::DoubleTy &&
522 leftArgArg->getValue()->getType() == Type::FloatTy &&
523 rightArgArg->getValue()->getType() == Type::FloatTy);
527 static inline MachineOpCode
528 ChooseMulInstruction(const InstructionNode* instrNode,
531 MachineOpCode opCode = INVALID_OPCODE;
533 if (checkCasts && BothFloatToDouble(instrNode))
535 return opCode = FSMULD;
537 // else fall through and use the regular multiply instructions
539 const Type* resultType = instrNode->getInstruction()->getType();
541 if (resultType->isIntegral())
546 switch(resultType->getPrimitiveID())
548 case Type::FloatTyID: opCode = FMULS; break;
549 case Type::DoubleTyID: opCode = FMULD; break;
550 default: assert(0 && "Invalid type for MUL instruction"); break;
557 static inline MachineInstr*
558 CreateIntNegInstruction(TargetMachine& target,
561 MachineInstr* minstr = new MachineInstr(SUB);
562 minstr->SetMachineOperand(0, target.getRegInfo().getZeroRegNum());
563 minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, vreg);
564 minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister, vreg);
569 static inline MachineInstr*
570 CreateMulConstInstruction(TargetMachine &target,
571 const InstructionNode* instrNode,
572 MachineInstr*& getMinstr2)
574 MachineInstr* minstr = NULL;
576 bool needNeg = false;
578 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
579 assert(isa<ConstPoolVal>(constOp));
581 // Cases worth optimizing are:
582 // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
583 // (2) Multiply by 2^x for integer types: replace with Shift
585 const Type* resultType = instrNode->getInstruction()->getType();
587 if (resultType->isIntegral() || resultType->isPointerType())
591 int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
594 bool needNeg = false;
601 if (C == 0 || C == 1)
603 minstr = new MachineInstr(ADD);
606 minstr->SetMachineOperand(0,
607 target.getRegInfo().getZeroRegNum());
609 minstr->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
610 instrNode->leftChild()->getValue());
611 minstr->SetMachineOperand(1,target.getRegInfo().getZeroRegNum());
613 else if (IsPowerOf2(C, pow))
615 minstr = new MachineInstr((resultType == Type::LongTy)
617 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
618 instrNode->leftChild()->getValue());
619 minstr->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
623 if (minstr && needNeg)
624 { // insert <reg = SUB 0, reg> after the instr to flip the sign
625 getMinstr2 = CreateIntNegInstruction(target,
626 instrNode->getValue());
632 if (resultType == Type::FloatTy ||
633 resultType == Type::DoubleTy)
636 double dval = ((ConstPoolFP*) constOp)->getValue();
642 minstr = new MachineInstr((resultType == Type::FloatTy)
644 minstr->SetMachineOperand(0,
645 target.getRegInfo().getZeroRegNum());
647 else if (fabs(dval) == 1)
649 bool needNeg = (dval < 0);
651 MachineOpCode opCode = needNeg
652 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
653 : (resultType == Type::FloatTy? FMOVS : FMOVD);
655 minstr = new MachineInstr(opCode);
656 minstr->SetMachineOperand(0,
657 MachineOperand::MO_VirtualRegister,
658 instrNode->leftChild()->getValue());
665 minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
666 instrNode->getValue());
672 static inline MachineOpCode
673 ChooseDivInstruction(TargetMachine &target,
674 const InstructionNode* instrNode)
676 MachineOpCode opCode = INVALID_OPCODE;
678 const Type* resultType = instrNode->getInstruction()->getType();
680 if (resultType->isIntegral())
681 opCode = resultType->isSigned()? SDIVX : UDIVX;
683 switch(resultType->getPrimitiveID())
685 case Type::FloatTyID: opCode = FDIVS; break;
686 case Type::DoubleTyID: opCode = FDIVD; break;
687 default: assert(0 && "Invalid type for DIV instruction"); break;
694 static inline MachineInstr*
695 CreateDivConstInstruction(TargetMachine &target,
696 const InstructionNode* instrNode,
697 MachineInstr*& getMinstr2)
699 MachineInstr* minstr = NULL;
702 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
703 assert(isa<ConstPoolVal>(constOp));
705 // Cases worth optimizing are:
706 // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
707 // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
709 const Type* resultType = instrNode->getInstruction()->getType();
711 if (resultType->isIntegral())
715 int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
718 bool needNeg = false;
727 minstr = new MachineInstr(ADD);
728 minstr->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
729 instrNode->leftChild()->getValue());
730 minstr->SetMachineOperand(1,target.getRegInfo().getZeroRegNum());
732 else if (IsPowerOf2(C, pow))
734 MachineOpCode opCode= ((resultType->isSigned())
735 ? (resultType==Type::LongTy)? SRAX : SRA
736 : (resultType==Type::LongTy)? SRLX : SRL);
737 minstr = new MachineInstr(opCode);
738 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
739 instrNode->leftChild()->getValue());
740 minstr->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
744 if (minstr && needNeg)
745 { // insert <reg = SUB 0, reg> after the instr to flip the sign
746 getMinstr2 = CreateIntNegInstruction(target,
747 instrNode->getValue());
753 if (resultType == Type::FloatTy ||
754 resultType == Type::DoubleTy)
757 double dval = ((ConstPoolFP*) constOp)->getValue();
759 if (isValidConst && fabs(dval) == 1)
761 bool needNeg = (dval < 0);
763 MachineOpCode opCode = needNeg
764 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
765 : (resultType == Type::FloatTy? FMOVS : FMOVD);
767 minstr = new MachineInstr(opCode);
768 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
769 instrNode->leftChild()->getValue());
775 minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
776 instrNode->getValue());
782 static inline MachineOpCode
783 ChooseLoadInstruction(const Type *DestTy)
785 switch (DestTy->getPrimitiveID()) {
787 case Type::UByteTyID: return LDUB;
788 case Type::SByteTyID: return LDSB;
789 case Type::UShortTyID: return LDUH;
790 case Type::ShortTyID: return LDSH;
791 case Type::UIntTyID: return LDUW;
792 case Type::IntTyID: return LDSW;
793 case Type::PointerTyID:
794 case Type::ULongTyID:
795 case Type::LongTyID: return LDX;
796 case Type::FloatTyID: return LD;
797 case Type::DoubleTyID: return LDD;
798 default: assert(0 && "Invalid type for Load instruction");
805 static inline MachineOpCode
806 ChooseStoreInstruction(const Type *DestTy)
808 switch (DestTy->getPrimitiveID()) {
810 case Type::UByteTyID:
811 case Type::SByteTyID: return STB;
812 case Type::UShortTyID:
813 case Type::ShortTyID: return STH;
815 case Type::IntTyID: return STW;
816 case Type::PointerTyID:
817 case Type::ULongTyID:
818 case Type::LongTyID: return STX;
819 case Type::FloatTyID: return ST;
820 case Type::DoubleTyID: return STD;
821 default: assert(0 && "Invalid type for Store instruction");
828 //------------------------------------------------------------------------
829 // Function SetOperandsForMemInstr
831 // Choose addressing mode for the given load or store instruction.
832 // Use [reg+reg] if it is an indexed reference, and the index offset is
833 // not a constant or if it cannot fit in the offset field.
834 // Use [reg+offset] in all other cases.
836 // This assumes that all array refs are "lowered" to one of these forms:
837 // %x = load (subarray*) ptr, constant ; single constant offset
838 // %x = load (subarray*) ptr, offsetVal ; single non-constant offset
839 // Generally, this should happen via strength reduction + LICM.
840 // Also, strength reduction should take care of using the same register for
841 // the loop index variable and an array index, when that is profitable.
842 //------------------------------------------------------------------------
845 SetOperandsForMemInstr(MachineInstr* minstr,
846 const InstructionNode* vmInstrNode,
847 const TargetMachine& target)
849 MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
851 // Variables to hold the index vector, ptr value, and offset value.
852 // The major work here is to extract these for all 3 instruction types
853 // and then call the common function SetMemOperands_Internal().
855 const vector<ConstPoolVal*>* idxVec = & memInst->getIndexVec();
856 vector<ConstPoolVal*>* newIdxVec = NULL;
858 Value* arrayOffsetVal = NULL;
860 // Test if a GetElemPtr instruction is being folded into this mem instrn.
861 // If so, it will be in the left child for Load and GetElemPtr,
862 // and in the right child for Store instructions.
864 InstrTreeNode* ptrChild = (vmInstrNode->getOpLabel() == Instruction::Store
865 ? vmInstrNode->rightChild()
866 : vmInstrNode->leftChild());
868 if (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
869 ptrChild->getOpLabel() == GetElemPtrIdx)
871 // There is a GetElemPtr instruction and there may be a chain of
872 // more than one. Use the pointer value of the last one in the chain.
873 // Fold the index vectors from the entire chain and from the mem
874 // instruction into one single index vector.
875 // Finally, we never fold for an array instruction so make that NULL.
877 newIdxVec = new vector<ConstPoolVal*>;
878 ptrVal = FoldGetElemChain((InstructionNode*) ptrChild, *newIdxVec);
880 newIdxVec->insert(newIdxVec->end(), idxVec->begin(), idxVec->end());
883 assert(! ((PointerType*)ptrVal->getType())->getValueType()->isArrayType()
884 && "GetElemPtr cannot be folded into array refs in selection");
888 // There is no GetElemPtr instruction.
889 // Use the pointer value and the index vector from the Mem instruction.
890 // If it is an array reference, get the array offset value.
892 ptrVal = memInst->getPtrOperand();
895 ((const PointerType*) ptrVal->getType())->getValueType();
896 if (opType->isArrayType())
898 assert((memInst->getNumOperands()
899 == (unsigned) 1 + memInst->getFirstOffsetIdx())
900 && "Array refs must be lowered before Instruction Selection");
902 arrayOffsetVal = memInst->getOperand(memInst->getFirstOffsetIdx());
906 SetMemOperands_Internal(minstr, vmInstrNode, ptrVal, arrayOffsetVal,
909 if (newIdxVec != NULL)
915 SetMemOperands_Internal(MachineInstr* minstr,
916 const InstructionNode* vmInstrNode,
918 Value* arrayOffsetVal,
919 const vector<ConstPoolVal*>& idxVec,
920 const TargetMachine& target)
922 MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
924 // Initialize so we default to storing the offset in a register.
925 int64_t smallConstOffset;
926 Value* valueForRegOffset = NULL;
927 MachineOperand::MachineOperandType offsetOpType =MachineOperand::MO_VirtualRegister;
929 // Check if there is an index vector and if so, if it translates to
930 // a small enough constant to fit in the immediate-offset field.
932 if (idxVec.size() > 0)
934 bool isConstantOffset = false;
937 const PointerType* ptrType = (PointerType*) ptrVal->getType();
939 if (ptrType->getValueType()->isStructType())
941 // the offset is always constant for structs
942 isConstantOffset = true;
944 // Compute the offset value using the index vector
945 offset = target.DataLayout.getIndexedOffset(ptrType, idxVec);
949 // It must be an array ref. Check if the offset is a constant,
950 // and that the indexing has been lowered to a single offset.
952 assert(ptrType->getValueType()->isArrayType());
953 assert(arrayOffsetVal != NULL
954 && "Expect to be given Value* for array offsets");
956 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(arrayOffsetVal))
958 isConstantOffset = true; // always constant for structs
959 assert(arrayOffsetVal->getType()->isIntegral());
960 offset = (CPV->getType()->isSigned()
961 ? ((ConstPoolSInt*)CPV)->getValue()
962 : (int64_t) ((ConstPoolUInt*)CPV)->getValue());
966 valueForRegOffset = arrayOffsetVal;
970 if (isConstantOffset)
972 // create a virtual register for the constant
973 valueForRegOffset = ConstPoolSInt::get(Type::IntTy, offset);
978 offsetOpType = MachineOperand::MO_SignExtendedImmed;
979 smallConstOffset = 0;
982 // Operand 0 is value for STORE, ptr for LOAD or GET_ELEMENT_PTR
983 // It is the left child in the instruction tree in all cases.
984 Value* leftVal = vmInstrNode->leftChild()->getValue();
985 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister, leftVal);
987 // Operand 1 is ptr for STORE, offset for LOAD or GET_ELEMENT_PTR
988 // Operand 2 is offset for STORE, result reg for LOAD or GET_ELEMENT_PTR
990 unsigned offsetOpNum = (memInst->getOpcode() == Instruction::Store)? 2 : 1;
991 if (offsetOpType == MachineOperand::MO_VirtualRegister)
993 assert(valueForRegOffset != NULL);
994 minstr->SetMachineOperand(offsetOpNum, offsetOpType, valueForRegOffset);
997 minstr->SetMachineOperand(offsetOpNum, offsetOpType, smallConstOffset);
999 if (memInst->getOpcode() == Instruction::Store)
1000 minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, ptrVal);
1002 minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1003 vmInstrNode->getValue());
1007 static inline MachineInstr*
1008 CreateIntSetInstruction(int64_t C, bool isSigned, Value* dest)
1010 MachineInstr* minstr;
1013 minstr = new MachineInstr(SETSW);
1014 minstr->SetMachineOperand(0, MachineOperand::MO_SignExtendedImmed, C);
1018 minstr = new MachineInstr(SETUW);
1019 minstr->SetMachineOperand(0, MachineOperand::MO_UnextendedImmed, C);
1022 minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, dest);
1028 // Create an instruction sequence to load a constant into a register.
1029 // This always creates either one or two instructions.
1030 // If two instructions are created, the second one is returned in getMinstr2
1032 static MachineInstr*
1033 CreateLoadConstInstr(const TargetMachine &target,
1034 Instruction* vmInstr,
1037 MachineInstr*& getMinstr2)
1039 assert(isa<ConstPoolVal>(val));
1041 MachineInstr* minstr1 = NULL;
1045 // Use a "set" instruction for known constants that can go in an integer reg.
1046 // Use a "set" instruction followed by a int-to-float conversion for known
1047 // constants that must go in a floating point reg but have an integer value.
1048 // Use a "load" instruction for all other constants, in particular,
1049 // floating point constants.
1051 const Type* valType = val->getType();
1053 if (valType->isIntegral() || valType == Type::BoolTy)
1055 bool isValidConstant;
1056 int64_t C = GetConstantValueAsSignedInt(val, isValidConstant);
1057 assert(isValidConstant && "Unrecognized constant");
1058 minstr1 = CreateIntSetInstruction(C, valType->isSigned(), dest);
1063 #undef MOVE_INT_TO_FP_REG_AVAILABLE
1064 #ifdef MOVE_INT_TO_FP_REG_AVAILABLE
1066 // This code was written to generate the following sequence:
1067 // SET[SU]W <int-const> <int-reg>
1068 // FITO[SD] <int-reg> <fp-reg>
1069 // (it really should have moved the int-reg to an fp-reg and then FITOS).
1070 // But for now the only way to move a value from an int-reg to an fp-reg
1071 // is via memory. Leave this code here but unused.
1073 assert(valType == Type::FloatTy || valType == Type::DoubleTy);
1074 double dval = ((ConstPoolFP*) val)->getValue();
1075 if (dval == (int64_t) dval)
1077 // The constant actually has an integer value, so use a
1078 // [set; int-to-float] sequence instead of a load instruction.
1080 TmpInstruction* addrReg = NULL;
1082 { // First, create an integer constant of the same value as dval
1083 ConstPoolSInt* ival = ConstPoolSInt::get(Type::IntTy,
1085 // Create another TmpInstruction for the hidden integer register
1086 addrReg = new TmpInstruction(Instruction::UserOp1, ival, NULL);
1087 vmInstr->getMachineInstrVec().addTempValue(addrReg);
1089 // Create the `SET' instruction
1090 minstr1 = CreateIntSetInstruction((int64_t)dval, true, addrReg);
1091 addrReg->addMachineInstruction(minstr1);
1094 // In which variable do we put the second instruction?
1095 MachineInstr*& instr2 = (minstr1)? getMinstr2 : minstr1;
1097 // Create the int-to-float instruction
1098 instr2 = new MachineInstr(valType == Type::FloatTy? FITOS : FITOD);
1101 instr2->SetMachineOperand(0, target.getRegInfo().getZeroRegNum());
1103 instr2->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1106 instr2->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1110 #endif MOVE_INT_TO_FP_REG_AVAILABLE
1113 // Make an instruction sequence to load the constant, viz:
1114 // SETSW <addr-of-constant>, addrReg
1115 // LOAD /*addr*/ addrReg, /*offset*/ 0, dest
1116 // set the offset field to 0.
1118 int64_t zeroOffset = 0; // to avoid ambiguity with (Value*) 0
1120 // Create another TmpInstruction for the hidden integer register
1121 TmpInstruction* addrReg =
1122 new TmpInstruction(Instruction::UserOp1, val, NULL);
1123 vmInstr->getMachineInstrVec().addTempValue(addrReg);
1125 minstr1 = new MachineInstr(SETUW);
1126 minstr1->SetMachineOperand(0, MachineOperand::MO_PCRelativeDisp,val);
1127 minstr1->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1129 addrReg->addMachineInstruction(minstr1);
1131 getMinstr2 = new MachineInstr(ChooseLoadInstruction(val->getType()));
1132 getMinstr2->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
1134 getMinstr2->SetMachineOperand(1,MachineOperand::MO_SignExtendedImmed,
1136 getMinstr2->SetMachineOperand(2,MachineOperand::MO_VirtualRegister,
1147 InsertCodeToLoadConstant(ConstPoolVal* opValue,
1148 Instruction* vmInstr,
1149 vector<MachineInstr*> loadConstVec,
1150 TargetMachine& target)
1152 // value is constant and must be loaded into a register.
1153 // First, create a tmp virtual register (TmpInstruction)
1154 // to hold the constant.
1155 // This will replace the constant operand in `minstr'.
1156 TmpInstruction* tmpReg =
1157 new TmpInstruction(Instruction::UserOp1, opValue, NULL);
1158 vmInstr->getMachineInstrVec().addTempValue(tmpReg);
1160 MachineInstr *minstr1, *minstr2;
1161 minstr1 = CreateLoadConstInstr(target, vmInstr,
1162 opValue, tmpReg, minstr2);
1164 loadConstVec.push_back(minstr1);
1165 if (minstr2 != NULL)
1166 loadConstVec.push_back(minstr2);
1168 tmpReg->addMachineInstruction(loadConstVec.back());
1174 // Special handling for constant operands:
1175 // -- if the constant is 0, use the hardwired 0 register, if any;
1176 // -- if the constant is of float or double type but has an integer value,
1177 // use int-to-float conversion instruction instead of generating a load;
1178 // -- if the constant fits in the IMMEDIATE field, use that field;
1179 // -- else insert instructions to put the constant into a register, either
1180 // directly or by loading explicitly from the constant pool.
1183 FixConstantOperands(const InstructionNode* vmInstrNode,
1184 MachineInstr** mvec,
1186 TargetMachine& target)
1188 vector<MachineInstr*> loadConstVec;
1189 loadConstVec.reserve(MAX_INSTR_PER_VMINSTR);
1191 Instruction* vmInstr = vmInstrNode->getInstruction();
1193 for (unsigned i=0; i < numInstr; i++)
1195 MachineInstr* minstr = mvec[i];
1196 const MachineInstrDescriptor& instrDesc =
1197 target.getInstrInfo().getDescriptor(minstr->getOpCode());
1199 for (unsigned op=0; op < minstr->getNumOperands(); op++)
1201 const MachineOperand& mop = minstr->getOperand(op);
1203 // skip the result position (for efficiency below) and any other
1204 // positions already marked as not a virtual register
1205 if (instrDesc.resultPos == (int) op ||
1206 mop.getOperandType() != MachineOperand::MO_VirtualRegister ||
1207 mop.getVRegValue() == NULL)
1212 Value* opValue = mop.getVRegValue();
1214 if (isa<ConstPoolVal>(opValue))
1216 unsigned int machineRegNum;
1218 MachineOperand::MachineOperandType opType =
1219 ChooseRegOrImmed(opValue, minstr->getOpCode(), target,
1220 /*canUseImmed*/ (op == 1),
1221 machineRegNum, immedValue);
1223 if (opType == MachineOperand::MO_MachineRegister)
1224 minstr->SetMachineOperand(op, machineRegNum);
1225 else if (opType == MachineOperand::MO_VirtualRegister)
1227 TmpInstruction* tmpReg =
1228 InsertCodeToLoadConstant((ConstPoolVal*) opValue,
1229 vmInstr, loadConstVec, target);
1230 minstr->SetMachineOperand(op, opType, tmpReg);
1233 minstr->SetMachineOperand(op, opType, immedValue);
1239 // Also, check for operands of the VM instruction that are implicit
1240 // operands of the machine instruction. These include:
1241 // -- arguments to a Call
1242 // -- return value of a Return
1244 // Any such operand that is a constant value needs to be fixed also.
1245 // At least these instructions with implicit uses (viz., Call and Return)
1246 // have no immediate fields, so the constant needs to be loaded into
1249 vector<Value*>& implUseVec = vmInstr->getMachineInstrVec().getImplicitUses();
1250 if (implUseVec.size() > 0)
1252 assert((vmInstr->getOpcode() == Instruction::Call ||
1253 vmInstr->getOpcode() == Instruction::Ret)
1254 && "May need to check immediate fields for other instructions");
1256 for (unsigned i=1, N=implUseVec.size(); i < N; ++i)
1257 if (isa<ConstPoolVal>(implUseVec[i]))
1259 TmpInstruction* tmpReg =
1260 InsertCodeToLoadConstant((ConstPoolVal*) implUseVec[i],
1261 vmInstr, loadConstVec, target);
1262 implUseVec[i] = tmpReg;
1267 // Finally, inserted the generated instructions in the vector
1270 unsigned numNew = loadConstVec.size();
1273 // Insert the new instructions *before* the old ones by moving
1274 // the old ones over `numNew' positions (last-to-first, of course!).
1275 // We do check *after* returning that we did not exceed the vector mvec.
1276 for (int i=numInstr-1; i >= 0; i--)
1277 mvec[i+numNew] = mvec[i];
1279 for (unsigned i=0; i < numNew; i++)
1280 mvec[i] = loadConstVec[i];
1283 return (numInstr + numNew);
1288 // Substitute operand `operandNum' of the instruction in node `treeNode'
1289 // in place the use(s) of that instruction in node `parent'.
1292 ForwardOperand(InstructionNode* treeNode,
1293 InstrTreeNode* parent,
1296 assert(treeNode && parent && "Invalid invocation of ForwardOperand");
1298 Instruction* unusedOp = treeNode->getInstruction();
1299 Value* fwdOp = unusedOp->getOperand(operandNum);
1301 // The parent itself may be a list node, so find the real parent instruction
1302 while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
1304 parent = parent->parent();
1305 assert(parent && "ERROR: Non-instruction node has no parent in tree.");
1307 InstructionNode* parentInstrNode = (InstructionNode*) parent;
1309 Instruction* userInstr = parentInstrNode->getInstruction();
1310 MachineCodeForVMInstr& mvec = userInstr->getMachineInstrVec();
1311 for (unsigned i=0, N=mvec.size(); i < N; i++)
1313 MachineInstr* minstr = mvec[i];
1314 for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; i++)
1316 const MachineOperand& mop = minstr->getOperand(i);
1317 if (mop.getOperandType() == MachineOperand::MO_VirtualRegister &&
1318 mop.getVRegValue() == unusedOp)
1320 minstr->SetMachineOperand(i, MachineOperand::MO_VirtualRegister,
1329 CreateCopyInstructionsByType(const TargetMachine& target,
1332 MachineInstr*& getMinstr2)
1334 getMinstr2 = NULL; // initialize second return value
1336 MachineInstr* minstr1 = NULL;
1338 const Type* resultType = dest->getType();
1340 MachineOpCode opCode = ChooseAddInstructionByType(resultType);
1341 if (opCode == INVALID_OPCODE)
1343 assert(0 && "Unsupported result type in CreateCopyInstructionsByType()");
1347 // if `src' is a constant that doesn't fit in the immed field, generate
1348 // a load instruction instead of an add
1349 if (isa<ConstPoolVal>(src))
1351 unsigned int machineRegNum;
1353 MachineOperand::MachineOperandType opType =
1354 ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
1355 machineRegNum, immedValue);
1357 if (opType == MachineOperand::MO_VirtualRegister)
1358 { // value is constant and cannot fit in immed field for the ADD
1359 minstr1 = CreateLoadConstInstr(target, dest, src, dest, getMinstr2);
1363 if (minstr1 == NULL)
1364 { // Create the appropriate add instruction.
1365 // Make `src' the second operand, in case it is a constant
1366 // Use (unsigned long) 0 for a NULL pointer value.
1368 const Type* nullValueType =
1369 (resultType->getPrimitiveID() == Type::PointerTyID)? Type::ULongTy
1371 minstr1 = new MachineInstr(opCode);
1372 minstr1->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1373 ConstPoolVal::getNullConstant(nullValueType));
1374 minstr1->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, src);
1375 minstr1->SetMachineOperand(2, MachineOperand::MO_VirtualRegister, dest);
1382 // This function is currently unused and incomplete but will be
1383 // used if we have a linear layout of basic blocks in LLVM code.
1384 // It decides which branch should fall-through, and whether an
1385 // extra unconditional branch is needed (when neither falls through).
1388 ChooseBranchPattern(Instruction* vmInstr, BranchPattern& brPattern)
1390 BranchInst* brInstr = (BranchInst*) vmInstr;
1392 brPattern.flipCondition = false;
1393 brPattern.targetBB = brInstr->getSuccessor(0);
1394 brPattern.extraBranch = NULL;
1396 assert(brInstr->getNumSuccessors() > 1 &&
1397 "Unnecessary analysis for unconditional branch");
1399 assert(0 && "Fold branches in peephole optimization");
1403 //******************* Externally Visible Functions *************************/
1406 //------------------------------------------------------------------------
1407 // External Function: GetInstructionsByRule
1410 // Choose machine instructions for the SPARC according to the
1411 // patterns chosen by the BURG-generated parser.
1412 //------------------------------------------------------------------------
1415 GetInstructionsByRule(InstructionNode* subtreeRoot,
1418 TargetMachine &target,
1419 MachineInstr** mvec)
1421 int numInstr = 1; // initialize for common case
1422 bool checkCast = false; // initialize here to use fall-through
1423 Value *leftVal, *rightVal;
1426 int forwardOperandNum = -1;
1427 int64_t s0=0, s8=8; // variables holding constants to avoid
1428 uint64_t u0=0; // overloading ambiguities below
1430 mvec[0] = mvec[1] = mvec[2] = mvec[3] = NULL; // just for safety
1433 // Let's check for chain rules outside the switch so that we don't have
1434 // to duplicate the list of chain rule production numbers here again
1436 if (ThisIsAChainRule(ruleForNode))
1438 // Chain rules have a single nonterminal on the RHS.
1439 // Get the rule that matches the RHS non-terminal and use that instead.
1441 assert(nts[0] && ! nts[1]
1442 && "A chain rule should have only one RHS non-terminal!");
1443 nextRule = burm_rule(subtreeRoot->state, nts[0]);
1444 nts = burm_nts[nextRule];
1445 numInstr = GetInstructionsByRule(subtreeRoot, nextRule, nts,target,mvec);
1449 switch(ruleForNode) {
1450 case 1: // stmt: Ret
1451 case 2: // stmt: RetValue(reg)
1452 // NOTE: Prepass of register allocation is responsible
1453 // for moving return value to appropriate register.
1454 // Mark the return-address register as a hidden virtual reg.
1455 // Mark the return value register as an implicit use.
1457 ReturnInst* returnInstr = (ReturnInst*) subtreeRoot->getInstruction();
1458 assert(returnInstr->getOpcode() == Instruction::Ret);
1460 Instruction* returnReg = new TmpInstruction(Instruction::UserOp1,
1462 returnInstr->getMachineInstrVec().addTempValue(returnReg);
1464 if (returnInstr->getReturnValue() != NULL)
1465 returnInstr->getMachineInstrVec().addImplicitUse(
1466 returnInstr->getReturnValue());
1468 mvec[0] = new MachineInstr(RETURN);
1469 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1471 mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,s8);
1473 returnReg->addMachineInstruction(mvec[0]);
1475 mvec[numInstr++] = new MachineInstr(NOP); // delay slot
1479 case 3: // stmt: Store(reg,reg)
1480 case 4: // stmt: Store(reg,ptrreg)
1481 mvec[0] = new MachineInstr(
1482 ChooseStoreInstruction(
1483 subtreeRoot->leftChild()->getValue()->getType()));
1484 SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1487 case 5: // stmt: BrUncond
1488 mvec[0] = new MachineInstr(BA);
1489 mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1491 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1492 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1495 mvec[numInstr++] = new MachineInstr(NOP);
1498 case 206: // stmt: BrCond(setCCconst)
1499 // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1500 // If the constant is ZERO, we can use the branch-on-integer-register
1501 // instructions and avoid the SUBcc instruction entirely.
1502 // Otherwise this is just the same as case 5, so just fall through.
1504 InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1506 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1507 ConstPoolVal* constVal = (ConstPoolVal*) constNode->getValue();
1510 if ((constVal->getType()->isIntegral()
1511 || constVal->getType()->isPointerType())
1512 && GetConstantValueAsSignedInt(constVal, isValidConst) == 0
1515 // That constant is a zero after all...
1516 // Use the left child of setCC as the first argument!
1517 mvec[0] = new MachineInstr(ChooseBprInstruction(subtreeRoot));
1518 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1519 subtreeRoot->leftChild()->leftChild()->getValue());
1520 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1521 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1524 mvec[numInstr++] = new MachineInstr(NOP);
1528 mvec[n] = new MachineInstr(BA);
1529 mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1531 mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1532 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(1));
1535 mvec[numInstr++] = new MachineInstr(NOP);
1539 // ELSE FALL THROUGH
1542 case 6: // stmt: BrCond(bool)
1543 // bool => boolean was computed with some boolean operator
1544 // (SetCC, Not, ...). We need to check whether the type was a FP,
1545 // signed int or unsigned int, and check the branching condition in
1546 // order to choose the branch to use.
1550 mvec[0] = new MachineInstr(ChooseBccInstruction(subtreeRoot,
1552 mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1553 subtreeRoot->leftChild()->getValue());
1554 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1555 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1558 mvec[numInstr++] = new MachineInstr(NOP);
1562 mvec[n] = new MachineInstr(BA);
1563 mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1565 mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1566 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(1));
1569 mvec[numInstr++] = new MachineInstr(NOP);
1573 case 208: // stmt: BrCond(boolconst)
1575 // boolconst => boolean is a constant; use BA to first or second label
1576 ConstPoolVal* constVal =
1577 cast<ConstPoolVal>(subtreeRoot->leftChild()->getValue());
1578 unsigned dest = ((ConstPoolBool*) constVal)->getValue()? 0 : 1;
1580 mvec[0] = new MachineInstr(BA);
1581 mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1583 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1584 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(dest));
1587 mvec[numInstr++] = new MachineInstr(NOP);
1591 case 8: // stmt: BrCond(boolreg)
1592 // boolreg => boolean is stored in an existing register.
1593 // Just use the branch-on-integer-register instruction!
1596 mvec[0] = new MachineInstr(BRNZ);
1597 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1598 subtreeRoot->leftChild()->getValue());
1599 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1600 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1603 mvec[numInstr++] = new MachineInstr(NOP); // delay slot
1607 mvec[n] = new MachineInstr(BA);
1608 mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1610 mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1611 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(1));
1614 mvec[numInstr++] = new MachineInstr(NOP);
1618 case 9: // stmt: Switch(reg)
1619 assert(0 && "*** SWITCH instruction is not implemented yet.");
1623 case 10: // reg: VRegList(reg, reg)
1624 assert(0 && "VRegList should never be the topmost non-chain rule");
1627 case 21: // reg: Not(reg): Implemented as reg = reg XOR-NOT 0
1628 mvec[0] = new MachineInstr(XNOR);
1629 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1630 subtreeRoot->leftChild()->getValue());
1631 mvec[0]->SetMachineOperand(1, target.getRegInfo().getZeroRegNum());
1632 mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1633 subtreeRoot->getValue());
1636 case 322: // reg: ToBoolTy(bool):
1637 case 22: // reg: ToBoolTy(reg):
1638 opType = subtreeRoot->leftChild()->getValue()->getType();
1639 assert(opType->isIntegral() || opType == Type::BoolTy);
1641 forwardOperandNum = 0;
1644 case 23: // reg: ToUByteTy(reg)
1645 case 25: // reg: ToUShortTy(reg)
1646 case 27: // reg: ToUIntTy(reg)
1647 case 29: // reg: ToULongTy(reg)
1648 opType = subtreeRoot->leftChild()->getValue()->getType();
1649 assert(opType->isIntegral() ||
1650 opType->isPointerType() ||
1651 opType == Type::BoolTy && "Cast is illegal for other types");
1653 forwardOperandNum = 0;
1656 case 24: // reg: ToSByteTy(reg)
1657 case 26: // reg: ToShortTy(reg)
1658 case 28: // reg: ToIntTy(reg)
1659 case 30: // reg: ToLongTy(reg)
1660 opType = subtreeRoot->leftChild()->getValue()->getType();
1661 if (opType->isIntegral() || opType == Type::BoolTy)
1664 forwardOperandNum = 0;
1668 mvec[0] = new MachineInstr(ChooseConvertToIntInstr(subtreeRoot,
1670 Set2OperandsFromInstr(mvec[0], subtreeRoot, target);
1674 case 31: // reg: ToFloatTy(reg):
1675 case 32: // reg: ToDoubleTy(reg):
1676 case 232: // reg: ToDoubleTy(Constant):
1678 // If this instruction has a parent (a user) in the tree
1679 // and the user is translated as an FsMULd instruction,
1680 // then the cast is unnecessary. So check that first.
1681 // In the future, we'll want to do the same for the FdMULq instruction,
1682 // so do the check here instead of only for ToFloatTy(reg).
1684 if (subtreeRoot->parent() != NULL &&
1685 ((InstructionNode*) subtreeRoot->parent())->getInstruction()->getMachineInstrVec()[0]->getOpCode() == FSMULD)
1688 forwardOperandNum = 0;
1692 opType = subtreeRoot->leftChild()->getValue()->getType();
1693 MachineOpCode opCode=ChooseConvertToFloatInstr(subtreeRoot,opType);
1694 if (opCode == INVALID_OPCODE) // no conversion needed
1697 forwardOperandNum = 0;
1701 mvec[0] = new MachineInstr(opCode);
1702 Set2OperandsFromInstr(mvec[0], subtreeRoot, target);
1707 case 19: // reg: ToArrayTy(reg):
1708 case 20: // reg: ToPointerTy(reg):
1710 forwardOperandNum = 0;
1713 case 233: // reg: Add(reg, Constant)
1714 mvec[0] = CreateAddConstInstruction(subtreeRoot);
1715 if (mvec[0] != NULL)
1717 // ELSE FALL THROUGH
1719 case 33: // reg: Add(reg, reg)
1720 mvec[0] = new MachineInstr(ChooseAddInstruction(subtreeRoot));
1721 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1724 case 234: // reg: Sub(reg, Constant)
1725 mvec[0] = CreateSubConstInstruction(subtreeRoot);
1726 if (mvec[0] != NULL)
1728 // ELSE FALL THROUGH
1730 case 34: // reg: Sub(reg, reg)
1731 mvec[0] = new MachineInstr(ChooseSubInstruction(subtreeRoot));
1732 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1735 case 135: // reg: Mul(todouble, todouble)
1739 case 35: // reg: Mul(reg, reg)
1740 mvec[0] =new MachineInstr(ChooseMulInstruction(subtreeRoot,checkCast));
1741 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1744 case 335: // reg: Mul(todouble, todoubleConst)
1748 case 235: // reg: Mul(reg, Constant)
1749 mvec[0] = CreateMulConstInstruction(target, subtreeRoot, mvec[1]);
1750 if (mvec[0] == NULL)
1752 mvec[0] = new MachineInstr(ChooseMulInstruction(subtreeRoot,
1754 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1757 if (mvec[1] != NULL)
1761 case 236: // reg: Div(reg, Constant)
1762 mvec[0] = CreateDivConstInstruction(target, subtreeRoot, mvec[1]);
1763 if (mvec[0] != NULL)
1765 if (mvec[1] != NULL)
1769 // ELSE FALL THROUGH
1771 case 36: // reg: Div(reg, reg)
1772 mvec[0] = new MachineInstr(ChooseDivInstruction(target, subtreeRoot));
1773 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1776 case 37: // reg: Rem(reg, reg)
1777 case 237: // reg: Rem(reg, Constant)
1778 assert(0 && "REM instruction unimplemented for the SPARC.");
1781 case 38: // reg: And(reg, reg)
1782 case 238: // reg: And(reg, Constant)
1783 mvec[0] = new MachineInstr(AND);
1784 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1787 case 138: // reg: And(reg, not)
1788 mvec[0] = new MachineInstr(ANDN);
1789 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1792 case 39: // reg: Or(reg, reg)
1793 case 239: // reg: Or(reg, Constant)
1794 mvec[0] = new MachineInstr(ORN);
1795 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1798 case 139: // reg: Or(reg, not)
1799 mvec[0] = new MachineInstr(ORN);
1800 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1803 case 40: // reg: Xor(reg, reg)
1804 case 240: // reg: Xor(reg, Constant)
1805 mvec[0] = new MachineInstr(XOR);
1806 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1809 case 140: // reg: Xor(reg, not)
1810 mvec[0] = new MachineInstr(XNOR);
1811 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1814 case 41: // boolconst: SetCC(reg, Constant)
1815 // Check if this is an integer comparison, and
1816 // there is a parent, and the parent decided to use
1817 // a branch-on-integer-register instead of branch-on-condition-code.
1818 // If so, the SUBcc instruction is not required.
1819 // (However, we must still check for constants to be loaded from
1820 // the constant pool so that such a load can be associated with
1821 // this instruction.)
1823 // Otherwise this is just the same as case 42, so just fall through.
1825 if (subtreeRoot->leftChild()->getValue()->getType()->isIntegral() &&
1826 subtreeRoot->parent() != NULL)
1828 InstructionNode* parent = (InstructionNode*) subtreeRoot->parent();
1829 assert(parent->getNodeType() == InstrTreeNode::NTInstructionNode);
1830 const vector<MachineInstr*>&
1831 minstrVec = parent->getInstruction()->getMachineInstrVec();
1832 MachineOpCode parentOpCode;
1833 if (parent->getInstruction()->getOpcode() == Instruction::Br &&
1834 (parentOpCode = minstrVec[0]->getOpCode()) >= BRZ &&
1835 parentOpCode <= BRGEZ)
1837 numInstr = 0; // don't forward the operand!
1841 // ELSE FALL THROUGH
1843 case 42: // bool: SetCC(reg, reg):
1845 // If result of the SetCC is only used for a single branch, we can
1846 // discard the result. Otherwise, the boolean value must go into
1847 // an integer register.
1849 bool keepBoolVal = (subtreeRoot->parent() == NULL ||
1850 ((InstructionNode*) subtreeRoot->parent())
1851 ->getInstruction()->getOpcode() !=Instruction::Br);
1852 bool subValIsBoolVal =
1853 subtreeRoot->getInstruction()->getOpcode() == Instruction::SetNE;
1854 bool keepSubVal = keepBoolVal && subValIsBoolVal;
1855 bool computeBoolVal = keepBoolVal && ! subValIsBoolVal;
1859 MachineOpCode movOpCode;
1861 if (subtreeRoot->leftChild()->getValue()->getType()->isIntegral() ||
1862 subtreeRoot->leftChild()->getValue()->getType()->isPointerType())
1864 // Integer condition: dest. should be %g0 or an integer register.
1865 // If result must be saved but condition is not SetEQ then we need
1866 // a separate instruction to compute the bool result, so discard
1867 // result of SUBcc instruction anyway.
1869 mvec[0] = new MachineInstr(SUBcc);
1870 Set3OperandsFromInstr(mvec[0], subtreeRoot, target, ! keepSubVal);
1872 // mark the 4th operand as being a CC register, and a "result"
1873 mvec[0]->SetMachineOperand(3, MachineOperand::MO_CCRegister,
1874 subtreeRoot->getValue(),/*def*/true);
1877 { // recompute bool using the integer condition codes
1879 ChooseMovpccAfterSub(subtreeRoot,mustClearReg,valueToMove);
1884 // FP condition: dest of FCMP should be some FCCn register
1885 mvec[0] = new MachineInstr(ChooseFcmpInstruction(subtreeRoot));
1886 mvec[0]->SetMachineOperand(0,MachineOperand::MO_CCRegister,
1887 subtreeRoot->getValue());
1888 mvec[0]->SetMachineOperand(1,MachineOperand::MO_VirtualRegister,
1889 subtreeRoot->leftChild()->getValue());
1890 mvec[0]->SetMachineOperand(2,MachineOperand::MO_VirtualRegister,
1891 subtreeRoot->rightChild()->getValue());
1894 {// recompute bool using the FP condition codes
1895 mustClearReg = true;
1897 movOpCode = ChooseMovFpccInstruction(subtreeRoot);
1904 {// Unconditionally set register to 0
1906 mvec[n] = new MachineInstr(SETHI);
1907 mvec[n]->SetMachineOperand(0,MachineOperand::MO_UnextendedImmed,
1909 mvec[n]->SetMachineOperand(1,MachineOperand::MO_VirtualRegister,
1910 subtreeRoot->getValue());
1913 // Now conditionally move `valueToMove' (0 or 1) into the register
1915 mvec[n] = new MachineInstr(movOpCode);
1916 mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1917 subtreeRoot->getValue());
1918 mvec[n]->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
1920 mvec[n]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1921 subtreeRoot->getValue());
1926 case 43: // boolreg: VReg
1927 case 44: // boolreg: Constant
1931 case 51: // reg: Load(reg)
1932 case 52: // reg: Load(ptrreg)
1933 case 53: // reg: LoadIdx(reg,reg)
1934 case 54: // reg: LoadIdx(ptrreg,reg)
1935 mvec[0] = new MachineInstr(ChooseLoadInstruction(
1936 subtreeRoot->getValue()->getType()));
1937 SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1940 case 55: // reg: GetElemPtr(reg)
1941 case 56: // reg: GetElemPtrIdx(reg,reg)
1942 if (subtreeRoot->parent() != NULL)
1944 // Check if the parent was an array access.
1945 // If so, we still need to generate this instruction.
1946 MemAccessInst* memInst = (MemAccessInst*)
1947 subtreeRoot->getInstruction();
1948 const PointerType* ptrType =
1949 (const PointerType*) memInst->getPtrOperand()->getType();
1950 if (! ptrType->getValueType()->isArrayType())
1951 {// we don't need a separate instr
1952 numInstr = 0; // don't forward operand!
1956 // else in all other cases we need to a separate ADD instruction
1957 mvec[0] = new MachineInstr(ADD);
1958 SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1961 case 57: // reg: Alloca: Implement as 2 instructions:
1962 // sub %sp, tmp -> %sp
1963 { // add %sp, 0 -> result
1964 Instruction* instr = subtreeRoot->getInstruction();
1965 const PointerType* instrType = (const PointerType*) instr->getType();
1966 assert(instrType->isPointerType());
1968 target.findOptimalStorageSize(instrType->getValueType());
1969 assert(tsize != 0 && "Just to check when this can happen");
1971 // Create a temporary Value to hold the constant type-size
1972 ConstPoolSInt* valueForTSize = ConstPoolSInt::get(Type::IntTy, tsize);
1974 // Instruction 1: sub %sp, tsize -> %sp
1975 // tsize is always constant, but it may have to be put into a
1976 // register if it doesn't fit in the immediate field.
1978 mvec[0] = new MachineInstr(SUB);
1979 mvec[0]->SetMachineOperand(0, /*regNum %sp=o6=r[14]*/(unsigned int)14);
1980 mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1982 mvec[0]->SetMachineOperand(2, /*regNum %sp=o6=r[14]*/(unsigned int)14);
1984 // Instruction 2: add %sp, 0 -> result
1986 mvec[1] = new MachineInstr(ADD);
1987 mvec[1]->SetMachineOperand(0, /*regNum %sp=o6=r[14]*/(unsigned int)14);
1988 mvec[1]->SetMachineOperand(1, target.getRegInfo().getZeroRegNum());
1989 mvec[1]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1994 case 58: // reg: Alloca(reg): Implement as 3 instructions:
1995 // mul num, typeSz -> tmp
1996 // sub %sp, tmp -> %sp
1997 { // add %sp, 0 -> result
1998 Instruction* instr = subtreeRoot->getInstruction();
1999 const PointerType* instrType = (const PointerType*) instr->getType();
2000 assert(instrType->isPointerType() &&
2001 instrType->getValueType()->isArrayType());
2002 const Type* eltType =
2003 ((ArrayType*) instrType->getValueType())->getElementType();
2004 int tsize = (int) target.findOptimalStorageSize(eltType);
2006 assert(tsize != 0 && "Just to check when this can happen");
2012 //else go on to create the instructions needed...
2014 // Create a temporary Value to hold the constant type-size
2015 ConstPoolSInt* valueForTSize = ConstPoolSInt::get(Type::IntTy, tsize);
2017 // Create a temporary value to hold `tmp'
2018 Instruction* tmpInstr = new TmpInstruction(Instruction::UserOp1,
2019 subtreeRoot->leftChild()->getValue(),
2020 NULL /*could insert tsize here*/);
2021 subtreeRoot->getInstruction()->getMachineInstrVec().addTempValue(tmpInstr);
2023 // Instruction 1: mul numElements, typeSize -> tmp
2024 mvec[0] = new MachineInstr(MULX);
2025 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
2026 subtreeRoot->leftChild()->getValue());
2027 mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
2029 mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
2032 tmpInstr->addMachineInstruction(mvec[0]);
2034 // Instruction 2: sub %sp, tmp -> %sp
2036 mvec[1] = new MachineInstr(SUB);
2037 mvec[1]->SetMachineOperand(0, /*regNum %sp=o6=r[14]*/(unsigned int)14);
2038 mvec[1]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
2040 mvec[1]->SetMachineOperand(2, /*regNum %sp=o6=r[14]*/(unsigned int)14);
2042 // Instruction 3: add %sp, 0 -> result
2044 mvec[2] = new MachineInstr(ADD);
2045 mvec[2]->SetMachineOperand(0, /*regNum %sp=o6=r[14]*/(unsigned int)14);
2046 mvec[2]->SetMachineOperand(1, target.getRegInfo().getZeroRegNum());
2047 mvec[2]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
2052 case 61: // reg: Call
2053 // Generate a call-indirect (i.e., JMPL) for now to expose
2054 // the potential need for registers. If an absolute address
2055 // is available, replace this with a CALL instruction.
2056 // Mark both the indirection register and the return-address
2057 // register as hidden virtual registers.
2058 // Also, mark the operands of the Call and the return value
2059 // as implicit operands of the machine instruction.
2061 CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
2062 Method* callee = callInstr->getCalledMethod();
2064 Instruction* jmpAddrReg = new TmpInstruction(Instruction::UserOp1,
2066 Instruction* retAddrReg = new TmpInstruction(Instruction::UserOp1,
2069 // Note temporary values and implicit uses in mvec
2071 // WARNING: Operands 0..N-1 must go in slots 0..N-1 of implicitUses.
2072 // The result value must go in slot N. This is assumed
2073 // in register allocation.
2075 callInstr->getMachineInstrVec().addTempValue(jmpAddrReg);
2076 callInstr->getMachineInstrVec().addTempValue(retAddrReg);
2077 for (unsigned i=0, N=callInstr->getNumOperands(); i < N; ++i)
2078 if (callInstr->getOperand(i) != callee)
2079 callInstr->getMachineInstrVec().addImplicitUse(
2080 callInstr->getOperand(i));
2081 if (callInstr->getCalledMethod()->getReturnType() == Type::VoidTy)
2082 callInstr->getMachineInstrVec().addImplicitUse(callInstr);
2084 // Generate the machine instruction and its operands
2085 mvec[0] = new MachineInstr(JMPL);
2086 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
2088 mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
2090 mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
2093 // NOTE: jmpAddrReg will be loaded by a different instruction generated
2094 // by the final code generator, so we just mark the CALL instruction
2095 // as computing that value.
2096 // The retAddrReg is actually computed by the CALL instruction.
2098 jmpAddrReg->addMachineInstruction(mvec[0]);
2099 retAddrReg->addMachineInstruction(mvec[0]);
2101 mvec[numInstr++] = new MachineInstr(NOP); // delay slot
2105 case 62: // reg: Shl(reg, reg)
2106 opType = subtreeRoot->leftChild()->getValue()->getType();
2107 assert(opType->isIntegral()
2108 || opType == Type::BoolTy
2109 || opType->isPointerType()&& "Shl unsupported for other types");
2110 mvec[0] = new MachineInstr((opType == Type::LongTy)? SLLX : SLL);
2111 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
2114 case 63: // reg: Shr(reg, reg)
2115 opType = subtreeRoot->leftChild()->getValue()->getType();
2116 assert(opType->isIntegral()
2117 || opType == Type::BoolTy
2118 || opType->isPointerType() &&"Shr unsupported for other types");
2119 mvec[0] = new MachineInstr((opType->isSigned()
2120 ? ((opType == Type::LongTy)? SRAX : SRA)
2121 : ((opType == Type::LongTy)? SRLX : SRL)));
2122 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
2125 case 64: // reg: Phi(reg,reg)
2126 { // This instruction has variable #operands, so resultPos is 0.
2127 Instruction* phi = subtreeRoot->getInstruction();
2128 mvec[0] = new MachineInstr(PHI, 1 + phi->getNumOperands());
2129 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
2130 subtreeRoot->getValue());
2131 for (unsigned i=0, N=phi->getNumOperands(); i < N; i++)
2132 mvec[0]->SetMachineOperand(i+1, MachineOperand::MO_VirtualRegister,
2133 phi->getOperand(i));
2136 case 71: // reg: VReg
2137 case 72: // reg: Constant
2138 numInstr = 0; // don't forward the value
2142 assert(0 && "Unrecognized BURG rule");
2148 if (forwardOperandNum >= 0)
2149 { // We did not generate a machine instruction but need to use operand.
2150 // If user is in the same tree, replace Value in its machine operand.
2151 // If not, insert a copy instruction which should get coalesced away
2152 // by register allocation.
2153 if (subtreeRoot->parent() != NULL)
2154 ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2157 MachineInstr *minstr1 = NULL, *minstr2 = NULL;
2158 minstr1 = CreateCopyInstructionsByType(target,
2159 subtreeRoot->getInstruction()->getOperand(forwardOperandNum),
2160 subtreeRoot->getInstruction(), minstr2);
2162 mvec[numInstr++] = minstr1;
2163 if (minstr2 != NULL)
2164 mvec[numInstr++] = minstr2;
2168 if (! ThisIsAChainRule(ruleForNode))
2169 numInstr = FixConstantOperands(subtreeRoot, mvec, numInstr, target);