c88fa23a90c639b5197ea6500f345f23435dd332
[oota-llvm.git] / lib / CodeGen / InstrSelection / InstrSelectionSupport.cpp
1 //===-- InstrSelectionSupport.cpp -----------------------------------------===//
2 //
3 // Target-independent instruction selection code.  See SparcInstrSelection.cpp
4 // for usage.
5 // 
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/CodeGen/InstrSelectionSupport.h"
9 #include "llvm/CodeGen/InstrSelection.h"
10 #include "llvm/CodeGen/MachineInstrAnnot.h"
11 #include "llvm/CodeGen/MachineCodeForInstruction.h"
12 #include "llvm/CodeGen/InstrForest.h"
13 #include "llvm/Target/TargetMachine.h"
14 #include "llvm/Target/TargetRegInfo.h"
15 #include "llvm/Target/TargetInstrInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/DerivedTypes.h"
19 #include "../../Target/Sparc/SparcInstrSelectionSupport.h"  // FIXME!
20
21
22 // Generate code to load the constant into a TmpInstruction (virtual reg) and
23 // returns the virtual register.
24 // 
25 static TmpInstruction*
26 InsertCodeToLoadConstant(Function *F,
27                          Value* opValue,
28                          Instruction* vmInstr,
29                          std::vector<MachineInstr*>& loadConstVec,
30                          TargetMachine& target)
31 {
32   // Create a tmp virtual register to hold the constant.
33   MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
34   TmpInstruction* tmpReg = new TmpInstruction(mcfi, opValue);
35   
36   target.getInstrInfo().CreateCodeToLoadConst(target, F, opValue, tmpReg,
37                                               loadConstVec, mcfi);
38   
39   // Record the mapping from the tmp VM instruction to machine instruction.
40   // Do this for all machine instructions that were not mapped to any
41   // other temp values created by 
42   // tmpReg->addMachineInstruction(loadConstVec.back());
43   
44   return tmpReg;
45 }
46
47
48 MachineOperand::MachineOperandType
49 ChooseRegOrImmed(int64_t intValue,
50                  bool isSigned,
51                  MachineOpCode opCode,
52                  const TargetMachine& target,
53                  bool canUseImmed,
54                  unsigned int& getMachineRegNum,
55                  int64_t& getImmedValue)
56 {
57   MachineOperand::MachineOperandType opType=MachineOperand::MO_VirtualRegister;
58   getMachineRegNum = 0;
59   getImmedValue = 0;
60
61   if (canUseImmed &&
62       target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
63     {
64       opType = isSigned? MachineOperand::MO_SignExtendedImmed
65                        : MachineOperand::MO_UnextendedImmed;
66       getImmedValue = intValue;
67     }
68   else if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
69     {
70       opType = MachineOperand::MO_MachineRegister;
71       getMachineRegNum = target.getRegInfo().getZeroRegNum();
72     }
73
74   return opType;
75 }
76
77
78 MachineOperand::MachineOperandType
79 ChooseRegOrImmed(Value* val,
80                  MachineOpCode opCode,
81                  const TargetMachine& target,
82                  bool canUseImmed,
83                  unsigned int& getMachineRegNum,
84                  int64_t& getImmedValue)
85 {
86   getMachineRegNum = 0;
87   getImmedValue = 0;
88
89   // To use reg or immed, constant needs to be integer, bool, or a NULL pointer
90   // TargetInstrInfo::ConvertConstantToIntType() does the right conversions:
91   bool isValidConstant;
92   uint64_t valueToUse =
93     target.getInstrInfo().ConvertConstantToIntType(target, val, val->getType(),
94                                                    isValidConstant);
95   if (! isValidConstant)
96     return MachineOperand::MO_VirtualRegister;
97
98   // Now check if the constant value fits in the IMMED field.
99   // 
100   return ChooseRegOrImmed((int64_t) valueToUse, val->getType()->isSigned(),
101                           opCode, target, canUseImmed,
102                           getMachineRegNum, getImmedValue);
103 }
104
105 //---------------------------------------------------------------------------
106 // Function: FixConstantOperandsForInstr
107 // 
108 // Purpose:
109 // Special handling for constant operands of a machine instruction
110 // -- if the constant is 0, use the hardwired 0 register, if any;
111 // -- if the constant fits in the IMMEDIATE field, use that field;
112 // -- else create instructions to put the constant into a register, either
113 //    directly or by loading explicitly from the constant pool.
114 // 
115 // In the first 2 cases, the operand of `minstr' is modified in place.
116 // Returns a vector of machine instructions generated for operands that
117 // fall under case 3; these must be inserted before `minstr'.
118 //---------------------------------------------------------------------------
119
120 std::vector<MachineInstr*>
121 FixConstantOperandsForInstr(Instruction* vmInstr,
122                             MachineInstr* minstr,
123                             TargetMachine& target)
124 {
125   std::vector<MachineInstr*> MVec;
126   
127   MachineOpCode opCode = minstr->getOpCode();
128   const TargetInstrInfo& instrInfo = target.getInstrInfo();
129   int resultPos = instrInfo.getResultPos(opCode);
130   int immedPos = instrInfo.getImmedConstantPos(opCode);
131
132   Function *F = vmInstr->getParent()->getParent();
133
134   for (unsigned op=0; op < minstr->getNumOperands(); op++)
135     {
136       const MachineOperand& mop = minstr->getOperand(op);
137           
138       // Skip the result position, preallocated machine registers, or operands
139       // that cannot be constants (CC regs or PC-relative displacements)
140       if (resultPos == (int)op ||
141           mop.getType() == MachineOperand::MO_MachineRegister ||
142           mop.getType() == MachineOperand::MO_CCRegister ||
143           mop.getType() == MachineOperand::MO_PCRelativeDisp)
144         continue;
145
146       bool constantThatMustBeLoaded = false;
147       unsigned int machineRegNum = 0;
148       int64_t immedValue = 0;
149       Value* opValue = NULL;
150       MachineOperand::MachineOperandType opType =
151         MachineOperand::MO_VirtualRegister;
152
153       // Operand may be a virtual register or a compile-time constant
154       if (mop.getType() == MachineOperand::MO_VirtualRegister)
155         {
156           assert(mop.getVRegValue() != NULL);
157           opValue = mop.getVRegValue();
158           if (Constant *opConst = dyn_cast<Constant>(opValue)) {
159             opType = ChooseRegOrImmed(opConst, opCode, target,
160                                       (immedPos == (int)op), machineRegNum,
161                                       immedValue);
162             if (opType == MachineOperand::MO_VirtualRegister)
163               constantThatMustBeLoaded = true;
164           }
165         }
166       else
167         {
168           assert(mop.isImmediate());
169           bool isSigned = mop.getType() == MachineOperand::MO_SignExtendedImmed;
170
171           // Bit-selection flags indicate an instruction that is extracting
172           // bits from its operand so ignore this even if it is a big constant.
173           if (mop.opHiBits32() || mop.opLoBits32() ||
174               mop.opHiBits64() || mop.opLoBits64())
175             continue;
176
177           opType = ChooseRegOrImmed(mop.getImmedValue(), isSigned,
178                                     opCode, target, (immedPos == (int)op), 
179                                     machineRegNum, immedValue);
180
181           if (opType == MachineOperand::MO_SignExtendedImmed ||
182               opType == MachineOperand::MO_UnextendedImmed) {
183             // The optype is an immediate value
184             // This means we need to change the opcode, e.g. ADDr -> ADDi
185             unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
186             minstr->setOpcode(newOpcode);
187           }
188
189           if (opType == mop.getType()) 
190             continue;           // no change: this is the most common case
191
192           if (opType == MachineOperand::MO_VirtualRegister)
193             {
194               constantThatMustBeLoaded = true;
195               opValue = isSigned
196                 ? (Value*)ConstantSInt::get(Type::LongTy, immedValue)
197                 : (Value*)ConstantUInt::get(Type::ULongTy,(uint64_t)immedValue);
198             }
199         }
200
201       if (opType == MachineOperand::MO_MachineRegister)
202         minstr->SetMachineOperandReg(op, machineRegNum);
203       else if (opType == MachineOperand::MO_SignExtendedImmed ||
204                opType == MachineOperand::MO_UnextendedImmed) {
205         minstr->SetMachineOperandConst(op, opType, immedValue);
206         // The optype is or has become an immediate
207         // This means we need to change the opcode, e.g. ADDr -> ADDi
208         unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
209         minstr->setOpcode(newOpcode);
210       } else if (constantThatMustBeLoaded ||
211                (opValue && isa<GlobalValue>(opValue)))
212         { // opValue is a constant that must be explicitly loaded into a reg
213           assert(opValue);
214           TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
215                                                             MVec, target);
216           minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
217                                        tmpReg);
218         }
219     }
220   
221   // Also, check for implicit operands used by the machine instruction
222   // (no need to check those defined since they cannot be constants).
223   // These include:
224   // -- arguments to a Call
225   // -- return value of a Return
226   // Any such operand that is a constant value needs to be fixed also.
227   // The current instructions with implicit refs (viz., Call and Return)
228   // have no immediate fields, so the constant always needs to be loaded
229   // into a register.
230   // 
231   bool isCall = instrInfo.isCall(opCode);
232   unsigned lastCallArgNum = 0;          // unused if not a call
233   CallArgsDescriptor* argDesc = NULL;   // unused if not a call
234   if (isCall)
235     argDesc = CallArgsDescriptor::get(minstr);
236   
237   for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
238     if (isa<Constant>(minstr->getImplicitRef(i)) ||
239         isa<GlobalValue>(minstr->getImplicitRef(i)))
240       {
241         Value* oldVal = minstr->getImplicitRef(i);
242         TmpInstruction* tmpReg =
243           InsertCodeToLoadConstant(F, oldVal, vmInstr, MVec, target);
244         minstr->setImplicitRef(i, tmpReg);
245         
246         if (isCall)
247           { // find and replace the argument in the CallArgsDescriptor
248             unsigned i=lastCallArgNum;
249             while (argDesc->getArgInfo(i).getArgVal() != oldVal)
250               ++i;
251             assert(i < argDesc->getNumArgs() &&
252                    "Constant operands to a call *must* be in the arg list");
253             lastCallArgNum = i;
254             argDesc->getArgInfo(i).replaceArgVal(tmpReg);
255           }
256       }
257   
258   return MVec;
259 }