* Switch over to cleaner TmpInstruction model
[oota-llvm.git] / lib / Target / SparcV9 / InstrSelection / InstrSelectionSupport.cpp
1 // $Id$ -*-c++-*-
2 //***************************************************************************
3 // File:
4 //      InstrSelectionSupport.h
5 // 
6 // Purpose:
7 //      Target-independent instruction selection code.
8 //      See SparcInstrSelection.cpp for usage.
9 //      
10 // History:
11 //      10/10/01         -  Vikram Adve  -  Created
12 //**************************************************************************/
13
14 #include "llvm/CodeGen/InstrSelectionSupport.h"
15 #include "llvm/CodeGen/InstrSelection.h"
16 #include "llvm/CodeGen/MachineInstr.h"
17 #include "llvm/CodeGen/MachineCodeForInstruction.h"
18 #include "llvm/CodeGen/MachineCodeForMethod.h"
19 #include "llvm/CodeGen/InstrForest.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/MachineRegInfo.h"
22 #include "llvm/ConstantVals.h"
23 #include "llvm/Method.h"
24 #include "llvm/BasicBlock.h"
25 #include "llvm/Type.h"
26 #include "llvm/iMemory.h"
27 using std::vector;
28
29 //*************************** Local Functions ******************************/
30
31
32 static TmpInstruction*
33 InsertCodeToLoadConstant(Value* opValue,
34                          Instruction* vmInstr,
35                          vector<MachineInstr*>& loadConstVec,
36                          TargetMachine& target)
37 {
38   vector<TmpInstruction*> tempVec;
39   
40   // Create a tmp virtual register to hold the constant.
41   TmpInstruction* tmpReg = new TmpInstruction(opValue);
42   MachineCodeForInstruction &MCFI = MachineCodeForInstruction::get(vmInstr);
43   MCFI.addTemp(tmpReg);
44   
45   target.getInstrInfo().CreateCodeToLoadConst(opValue, tmpReg,
46                                               loadConstVec, tempVec);
47   
48   // Register the new tmp values created for this m/c instruction sequence
49   for (unsigned i=0; i < tempVec.size(); i++)
50     MCFI.addTemp(tempVec[i]);
51   
52   // Record the mapping from the tmp VM instruction to machine instruction.
53   // Do this for all machine instructions that were not mapped to any
54   // other temp values created by 
55   // tmpReg->addMachineInstruction(loadConstVec.back());
56   
57   return tmpReg;
58 }
59
60
61 //---------------------------------------------------------------------------
62 // Function GetConstantValueAsSignedInt
63 // 
64 // Convenience function to get the value of an integer constant, for an
65 // appropriate integer or non-integer type that can be held in an integer.
66 // The type of the argument must be the following:
67 //      Signed or unsigned integer
68 //      Boolean
69 //      Pointer
70 // 
71 // isValidConstant is set to true if a valid constant was found.
72 //---------------------------------------------------------------------------
73
74 int64_t
75 GetConstantValueAsSignedInt(const Value *V,
76                             bool &isValidConstant)
77 {
78   if (!isa<Constant>(V))
79     {
80       isValidConstant = false;
81       return 0;
82     }
83   
84   isValidConstant = true;
85   
86   if (V->getType() == Type::BoolTy)
87     return (int64_t) cast<ConstantBool>(V)->getValue();
88   
89   if (V->getType()->isIntegral())
90     {
91       if (V->getType()->isSigned())
92         return cast<ConstantSInt>(V)->getValue();
93       
94       assert(V->getType()->isUnsigned());
95       uint64_t Val = cast<ConstantUInt>(V)->getValue();
96       if (Val < INT64_MAX)     // then safe to cast to signed
97         return (int64_t)Val;
98     }
99
100   isValidConstant = false;
101   return 0;
102 }
103
104
105 //---------------------------------------------------------------------------
106 // Function: FoldGetElemChain
107 // 
108 // Purpose:
109 //   Fold a chain of GetElementPtr instructions into an equivalent
110 //   (Pointer, IndexVector) pair.  Returns the pointer Value, and
111 //   stores the resulting IndexVector in argument chainIdxVec.
112 //---------------------------------------------------------------------------
113
114 Value*
115 FoldGetElemChain(const InstructionNode* getElemInstrNode,
116                  vector<Value*>& chainIdxVec)
117 {
118   MemAccessInst* getElemInst = (MemAccessInst*)
119     getElemInstrNode->getInstruction();
120   
121   // Initialize return values from the incoming instruction
122   Value* ptrVal = getElemInst->getPointerOperand();
123   chainIdxVec = getElemInst->copyIndices();
124   
125   // Now chase the chain of getElementInstr instructions, if any
126   InstrTreeNode* ptrChild = getElemInstrNode->leftChild();
127   while (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
128          ptrChild->getOpLabel() == GetElemPtrIdx)
129     {
130       // Child is a GetElemPtr instruction
131       getElemInst = (MemAccessInst*)
132         ((InstructionNode*) ptrChild)->getInstruction();
133       const vector<Value*>& idxVec = getElemInst->copyIndices();
134       
135       // Get the pointer value out of ptrChild and *prepend* its index vector
136       ptrVal = getElemInst->getPointerOperand();
137       chainIdxVec.insert(chainIdxVec.begin(), idxVec.begin(), idxVec.end());
138       
139       ptrChild = ptrChild->leftChild();
140     }
141   
142   return ptrVal;
143 }
144
145
146 //------------------------------------------------------------------------ 
147 // Function Set2OperandsFromInstr
148 // Function Set3OperandsFromInstr
149 // 
150 // For the common case of 2- and 3-operand arithmetic/logical instructions,
151 // set the m/c instr. operands directly from the VM instruction's operands.
152 // Check whether the first or second operand is 0 and can use a dedicated "0"
153 // register.
154 // Check whether the second operand should use an immediate field or register.
155 // (First and third operands are never immediates for such instructions.)
156 // 
157 // Arguments:
158 // canDiscardResult: Specifies that the result operand can be discarded
159 //                   by using the dedicated "0"
160 // 
161 // op1position, op2position and resultPosition: Specify in which position
162 //                   in the machine instruction the 3 operands (arg1, arg2
163 //                   and result) should go.
164 // 
165 // RETURN VALUE: unsigned int flags, where
166 //      flags & 0x01    => operand 1 is constant and needs a register
167 //      flags & 0x02    => operand 2 is constant and needs a register
168 //------------------------------------------------------------------------ 
169
170 void
171 Set2OperandsFromInstr(MachineInstr* minstr,
172                       InstructionNode* vmInstrNode,
173                       const TargetMachine& target,
174                       bool canDiscardResult,
175                       int op1Position,
176                       int resultPosition)
177 {
178   Set3OperandsFromInstr(minstr, vmInstrNode, target,
179                         canDiscardResult, op1Position,
180                         /*op2Position*/ -1, resultPosition);
181 }
182
183
184 void
185 Set3OperandsFromInstr(MachineInstr* minstr,
186                       InstructionNode* vmInstrNode,
187                       const TargetMachine& target,
188                       bool canDiscardResult,
189                       int op1Position,
190                       int op2Position,
191                       int resultPosition)
192 {
193   assert(op1Position >= 0);
194   assert(resultPosition >= 0);
195   
196   // operand 1
197   minstr->SetMachineOperand(op1Position, MachineOperand::MO_VirtualRegister,
198                             vmInstrNode->leftChild()->getValue());   
199   
200   // operand 2 (if any)
201   if (op2Position >= 0)
202     minstr->SetMachineOperand(op2Position, MachineOperand::MO_VirtualRegister,
203                               vmInstrNode->rightChild()->getValue());   
204   
205   // result operand: if it can be discarded, use a dead register if one exists
206   if (canDiscardResult && target.getRegInfo().getZeroRegNum() >= 0)
207     minstr->SetMachineOperand(resultPosition,
208                               target.getRegInfo().getZeroRegNum());
209   else
210     minstr->SetMachineOperand(resultPosition,
211                               MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());
212 }
213
214
215 MachineOperand::MachineOperandType
216 ChooseRegOrImmed(Value* val,
217                  MachineOpCode opCode,
218                  const TargetMachine& target,
219                  bool canUseImmed,
220                  unsigned int& getMachineRegNum,
221                  int64_t& getImmedValue)
222 {
223   MachineOperand::MachineOperandType opType =
224     MachineOperand::MO_VirtualRegister;
225   getMachineRegNum = 0;
226   getImmedValue = 0;
227   
228   // Check for the common case first: argument is not constant
229   // 
230   Constant *CPV = dyn_cast<Constant>(val);
231   if (!CPV) return opType;
232
233   if (ConstantBool *CPB = dyn_cast<ConstantBool>(CPV))
234     {
235       if (!CPB->getValue() && target.getRegInfo().getZeroRegNum() >= 0)
236         {
237           getMachineRegNum = target.getRegInfo().getZeroRegNum();
238           return MachineOperand::MO_MachineRegister;
239         }
240
241       getImmedValue = 1;
242       return MachineOperand::MO_SignExtendedImmed;
243     }
244   
245   // Otherwise it needs to be an integer or a NULL pointer
246   if (! CPV->getType()->isIntegral() &&
247       ! (CPV->getType()->isPointerType() &&
248          CPV->isNullValue()))
249     return opType;
250   
251   // Now get the constant value and check if it fits in the IMMED field.
252   // Take advantage of the fact that the max unsigned value will rarely
253   // fit into any IMMED field and ignore that case (i.e., cast smaller
254   // unsigned constants to signed).
255   // 
256   int64_t intValue;
257   if (CPV->getType()->isPointerType())
258     {
259       intValue = 0;
260     }
261   else if (CPV->getType()->isSigned())
262     {
263       intValue = cast<ConstantSInt>(CPV)->getValue();
264     }
265   else
266     {
267       uint64_t V = cast<ConstantUInt>(CPV)->getValue();
268       if (V >= INT64_MAX) return opType;
269       intValue = (int64_t)V;
270     }
271
272   if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
273     {
274       opType = MachineOperand::MO_MachineRegister;
275       getMachineRegNum = target.getRegInfo().getZeroRegNum();
276     }
277   else if (canUseImmed &&
278            target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
279     {
280       opType = MachineOperand::MO_SignExtendedImmed;
281       getImmedValue = intValue;
282     }
283   
284   return opType;
285 }
286
287
288 //---------------------------------------------------------------------------
289 // Function: FixConstantOperandsForInstr
290 // 
291 // Purpose:
292 // Special handling for constant operands of a machine instruction
293 // -- if the constant is 0, use the hardwired 0 register, if any;
294 // -- if the constant fits in the IMMEDIATE field, use that field;
295 // -- else create instructions to put the constant into a register, either
296 //    directly or by loading explicitly from the constant pool.
297 // 
298 // In the first 2 cases, the operand of `minstr' is modified in place.
299 // Returns a vector of machine instructions generated for operands that
300 // fall under case 3; these must be inserted before `minstr'.
301 //---------------------------------------------------------------------------
302
303 vector<MachineInstr*>
304 FixConstantOperandsForInstr(Instruction* vmInstr,
305                             MachineInstr* minstr,
306                             TargetMachine& target)
307 {
308   vector<MachineInstr*> loadConstVec;
309   
310   const MachineInstrDescriptor& instrDesc =
311     target.getInstrInfo().getDescriptor(minstr->getOpCode());
312   
313   Method* method = vmInstr->getParent()->getParent();
314   
315   for (unsigned op=0; op < minstr->getNumOperands(); op++)
316     {
317       const MachineOperand& mop = minstr->getOperand(op);
318           
319       // skip the result position (for efficiency below) and any other
320       // positions already marked as not a virtual register
321       if (instrDesc.resultPos == (int) op || 
322           mop.getOperandType() != MachineOperand::MO_VirtualRegister ||
323           mop.getVRegValue() == NULL)
324         {
325           continue;
326         }
327           
328       Value* opValue = mop.getVRegValue();
329       bool constantThatMustBeLoaded = false;
330       
331       if (Constant *OpConst = dyn_cast<Constant>(opValue)) {
332           unsigned int machineRegNum;
333           int64_t immedValue;
334           MachineOperand::MachineOperandType opType =
335             ChooseRegOrImmed(opValue, minstr->getOpCode(), target,
336                              (target.getInstrInfo().getImmmedConstantPos(minstr->getOpCode()) == (int) op),
337                              machineRegNum, immedValue);
338           
339           if (opType == MachineOperand::MO_MachineRegister)
340             minstr->SetMachineOperand(op, machineRegNum);
341           else if (opType == MachineOperand::MO_VirtualRegister)
342             constantThatMustBeLoaded = true; // load is generated below
343           else
344             minstr->SetMachineOperand(op, opType, immedValue);
345
346           if (constantThatMustBeLoaded)
347             { // register the value so it is emitted in the assembly
348               MachineCodeForMethod::get(method).addToConstantPool(OpConst);
349             }
350         }
351       
352       if (constantThatMustBeLoaded || isa<GlobalValue>(opValue))
353         { // opValue is a constant that must be explicitly loaded into a reg.
354           TmpInstruction* tmpReg = InsertCodeToLoadConstant(opValue, vmInstr,
355                                                         loadConstVec, target);
356           minstr->SetMachineOperand(op, MachineOperand::MO_VirtualRegister,
357                                         tmpReg);
358         }
359     }
360   
361   // 
362   // Also, check for implicit operands used (not those defined) by the
363   // machine instruction.  These include:
364   // -- arguments to a Call
365   // -- return value of a Return
366   // Any such operand that is a constant value needs to be fixed also.
367   // The current instructions with implicit refs (viz., Call and Return)
368   // have no immediate fields, so the constant always needs to be loaded
369   // into a register.
370   // 
371   for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
372     if (isa<Constant>(minstr->getImplicitRef(i)) ||
373         isa<GlobalValue>(minstr->getImplicitRef(i)))
374       {
375         Value* oldVal = minstr->getImplicitRef(i);
376         TmpInstruction* tmpReg =
377           InsertCodeToLoadConstant(oldVal, vmInstr, loadConstVec, target);
378         minstr->setImplicitRef(i, tmpReg);
379         
380         if (Constant *C = dyn_cast<Constant>(oldVal))
381           { // register the value so it is emitted in the assembly
382             MachineCodeForMethod::get(method).addToConstantPool(C);
383           }
384       }
385   
386   return loadConstVec;
387 }
388
389