Add function GetConstantValueAsUnsignedInt.
[oota-llvm.git] / lib / Target / SparcV9 / InstrSelection / InstrSelectionSupport.cpp
1 //***************************************************************************
2 // File:
3 //      InstrSelectionSupport.h
4 // 
5 // Purpose:
6 //      Target-independent instruction selection code.
7 //      See SparcInstrSelection.cpp for usage.
8 //      
9 // History:
10 //      10/10/01         -  Vikram Adve  -  Created
11 //**************************************************************************/
12
13 #include "llvm/CodeGen/InstrSelectionSupport.h"
14 #include "llvm/CodeGen/InstrSelection.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineInstrAnnot.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/Constants.h"
23 #include "llvm/Function.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 // Generate code to load the constant into a TmpInstruction (virtual reg) and
33 // returns the virtual register.
34 // 
35 static TmpInstruction*
36 InsertCodeToLoadConstant(Function *F,
37                          Value* opValue,
38                          Instruction* vmInstr,
39                          vector<MachineInstr*>& loadConstVec,
40                          TargetMachine& target)
41 {
42   // Create a tmp virtual register to hold the constant.
43   TmpInstruction* tmpReg = new TmpInstruction(opValue);
44   MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
45   mcfi.addTemp(tmpReg);
46   
47   target.getInstrInfo().CreateCodeToLoadConst(target, F, opValue, tmpReg,
48                                               loadConstVec, mcfi);
49   
50   // Record the mapping from the tmp VM instruction to machine instruction.
51   // Do this for all machine instructions that were not mapped to any
52   // other temp values created by 
53   // tmpReg->addMachineInstruction(loadConstVec.back());
54   
55   return tmpReg;
56 }
57
58
59 //---------------------------------------------------------------------------
60 // Function GetConstantValueAsUnsignedInt
61 // Function GetConstantValueAsSignedInt
62 // 
63 // Convenience functions to get the value of an integral constant, for an
64 // appropriate integer or non-integer type that can be held in a signed
65 // or unsigned integer respectively.  The type of the argument must be
66 // 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 uint64_t
75 GetConstantValueAsUnsignedInt(const Value *V,
76                               bool &isValidConstant)
77 {
78   isValidConstant = true;
79
80   if (isa<Constant>(V))
81     if (V->getType() == Type::BoolTy)
82       return (int64_t) cast<ConstantBool>(V)->getValue();
83     else if (V->getType()->isIntegral())
84       return (V->getType()->isUnsigned()
85               ? cast<ConstantUInt>(V)->getValue()
86               : (uint64_t) cast<ConstantSInt>(V)->getValue());
87
88   isValidConstant = false;
89   return 0;
90 }
91
92 int64_t
93 GetConstantValueAsSignedInt(const Value *V,
94                             bool &isValidConstant)
95 {
96   uint64_t C = GetConstantValueAsUnsignedInt(V, isValidConstant);
97   if (isValidConstant) {
98     if (V->getType()->isSigned() || C < INT64_MAX) // safe to cast to signed
99       return (int64_t) C;
100     else
101       isValidConstant = false;
102   }
103   return 0;
104 }
105
106 //---------------------------------------------------------------------------
107 // Function: FoldGetElemChain
108 // 
109 // Purpose:
110 //   Fold a chain of GetElementPtr instructions containing only
111 //   constant offsets into an equivalent (Pointer, IndexVector) pair.
112 //   Returns the pointer Value, and stores the resulting IndexVector
113 //   in argument chainIdxVec.
114 //---------------------------------------------------------------------------
115
116 Value*
117 FoldGetElemChain(const InstructionNode* getElemInstrNode,
118                  vector<Value*>& chainIdxVec)
119 {
120   MemAccessInst* getElemInst = (MemAccessInst*)
121     getElemInstrNode->getInstruction();
122   
123   // Return NULL if we don't fold any instructions in.
124   Value* ptrVal = NULL;
125   
126   // Remember if the last instruction had a leading [0] index.
127   bool hasLeadingZero = false;
128   
129   // Now chase the chain of getElementInstr instructions, if any.
130   // Check for any non-constant indices and stop there.
131   // 
132   const InstrTreeNode* ptrChild = getElemInstrNode;
133   while (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
134          ptrChild->getOpLabel() == GetElemPtrIdx)
135     {
136       // Child is a GetElemPtr instruction
137       getElemInst = cast<MemAccessInst>(ptrChild->getValue());
138       MemAccessInst::op_iterator OI, firstIdx = getElemInst->idx_begin();
139       MemAccessInst::op_iterator lastIdx = getElemInst->idx_end();
140       bool allConstantOffsets = true;
141
142       // Check that all offsets are constant for this instruction
143       for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
144         allConstantOffsets = isa<ConstantInt>(*OI);
145
146       if (allConstantOffsets)
147         { // Get pointer value out of ptrChild.
148           ptrVal = getElemInst->getPointerOperand();
149
150           // Check for a leading [0] index, if any.  It will be discarded later.
151           ConstantUInt* CV = dyn_cast<ConstantUInt>((Value*) *firstIdx);
152           hasLeadingZero = bool(CV && CV->getValue() == 0);
153
154           // Insert its index vector at the start, skipping any leading [0]
155           chainIdxVec.insert(chainIdxVec.begin(),
156                              firstIdx + hasLeadingZero, lastIdx);
157
158           // Mark the folded node so no code is generated for it.
159           ((InstructionNode*) ptrChild)->markFoldedIntoParent();
160         }
161       else // cannot fold this getElementPtr instr. or any further ones
162         break;
163
164       ptrChild = ptrChild->leftChild();
165     }
166
167   // If the first getElementPtr instruction had a leading [0], add it back.
168   // Note that this instruction is the *last* one successfully folded above.
169   if (ptrVal && hasLeadingZero) 
170     chainIdxVec.insert(chainIdxVec.begin(), ConstantUInt::get(Type::UIntTy,0));
171
172   return ptrVal;
173 }
174
175
176 //------------------------------------------------------------------------ 
177 // Function Set2OperandsFromInstr
178 // Function Set3OperandsFromInstr
179 // 
180 // For the common case of 2- and 3-operand arithmetic/logical instructions,
181 // set the m/c instr. operands directly from the VM instruction's operands.
182 // Check whether the first or second operand is 0 and can use a dedicated "0"
183 // register.
184 // Check whether the second operand should use an immediate field or register.
185 // (First and third operands are never immediates for such instructions.)
186 // 
187 // Arguments:
188 // canDiscardResult: Specifies that the result operand can be discarded
189 //                   by using the dedicated "0"
190 // 
191 // op1position, op2position and resultPosition: Specify in which position
192 //                   in the machine instruction the 3 operands (arg1, arg2
193 //                   and result) should go.
194 // 
195 //------------------------------------------------------------------------ 
196
197 void
198 Set2OperandsFromInstr(MachineInstr* minstr,
199                       InstructionNode* vmInstrNode,
200                       const TargetMachine& target,
201                       bool canDiscardResult,
202                       int op1Position,
203                       int resultPosition)
204 {
205   Set3OperandsFromInstr(minstr, vmInstrNode, target,
206                         canDiscardResult, op1Position,
207                         /*op2Position*/ -1, resultPosition);
208 }
209
210
211 void
212 Set3OperandsFromInstr(MachineInstr* minstr,
213                       InstructionNode* vmInstrNode,
214                       const TargetMachine& target,
215                       bool canDiscardResult,
216                       int op1Position,
217                       int op2Position,
218                       int resultPosition)
219 {
220   assert(op1Position >= 0);
221   assert(resultPosition >= 0);
222   
223   // operand 1
224   minstr->SetMachineOperandVal(op1Position, MachineOperand::MO_VirtualRegister,
225                             vmInstrNode->leftChild()->getValue());   
226   
227   // operand 2 (if any)
228   if (op2Position >= 0)
229     minstr->SetMachineOperandVal(op2Position, MachineOperand::MO_VirtualRegister,
230                               vmInstrNode->rightChild()->getValue());   
231   
232   // result operand: if it can be discarded, use a dead register if one exists
233   if (canDiscardResult && target.getRegInfo().getZeroRegNum() >= 0)
234     minstr->SetMachineOperandReg(resultPosition,
235                               target.getRegInfo().getZeroRegNum());
236   else
237     minstr->SetMachineOperandVal(resultPosition,
238                               MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());
239 }
240
241
242 MachineOperand::MachineOperandType
243 ChooseRegOrImmed(Value* val,
244                  MachineOpCode opCode,
245                  const TargetMachine& target,
246                  bool canUseImmed,
247                  unsigned int& getMachineRegNum,
248                  int64_t& getImmedValue)
249 {
250   MachineOperand::MachineOperandType opType =
251     MachineOperand::MO_VirtualRegister;
252   getMachineRegNum = 0;
253   getImmedValue = 0;
254   
255   // Check for the common case first: argument is not constant
256   // 
257   Constant *CPV = dyn_cast<Constant>(val);
258   if (!CPV) return opType;
259
260   if (ConstantBool *CPB = dyn_cast<ConstantBool>(CPV))
261     {
262       if (!CPB->getValue() && target.getRegInfo().getZeroRegNum() >= 0)
263         {
264           getMachineRegNum = target.getRegInfo().getZeroRegNum();
265           return MachineOperand::MO_MachineRegister;
266         }
267
268       getImmedValue = 1;
269       return MachineOperand::MO_SignExtendedImmed;
270     }
271   
272   // Otherwise it needs to be an integer or a NULL pointer
273   if (! CPV->getType()->isIntegral() &&
274       ! (isa<PointerType>(CPV->getType()) &&
275          CPV->isNullValue()))
276     return opType;
277   
278   // Now get the constant value and check if it fits in the IMMED field.
279   // Take advantage of the fact that the max unsigned value will rarely
280   // fit into any IMMED field and ignore that case (i.e., cast smaller
281   // unsigned constants to signed).
282   // 
283   int64_t intValue;
284   if (isa<PointerType>(CPV->getType()))
285     {
286       intValue = 0;
287     }
288   else if (CPV->getType()->isSigned())
289     {
290       intValue = cast<ConstantSInt>(CPV)->getValue();
291     }
292   else
293     {
294       uint64_t V = cast<ConstantUInt>(CPV)->getValue();
295       if (V >= INT64_MAX) return opType;
296       intValue = (int64_t)V;
297     }
298
299   if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
300     {
301       opType = MachineOperand::MO_MachineRegister;
302       getMachineRegNum = target.getRegInfo().getZeroRegNum();
303     }
304   else if (canUseImmed &&
305            target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
306     {
307       opType = CPV->getType()->isSigned()
308         ? MachineOperand::MO_SignExtendedImmed
309         : MachineOperand::MO_UnextendedImmed;
310       getImmedValue = intValue;
311     }
312   
313   return opType;
314 }
315
316
317 //---------------------------------------------------------------------------
318 // Function: FixConstantOperandsForInstr
319 // 
320 // Purpose:
321 // Special handling for constant operands of a machine instruction
322 // -- if the constant is 0, use the hardwired 0 register, if any;
323 // -- if the constant fits in the IMMEDIATE field, use that field;
324 // -- else create instructions to put the constant into a register, either
325 //    directly or by loading explicitly from the constant pool.
326 // 
327 // In the first 2 cases, the operand of `minstr' is modified in place.
328 // Returns a vector of machine instructions generated for operands that
329 // fall under case 3; these must be inserted before `minstr'.
330 //---------------------------------------------------------------------------
331
332 vector<MachineInstr*>
333 FixConstantOperandsForInstr(Instruction* vmInstr,
334                             MachineInstr* minstr,
335                             TargetMachine& target)
336 {
337   vector<MachineInstr*> loadConstVec;
338   
339   const MachineInstrDescriptor& instrDesc =
340     target.getInstrInfo().getDescriptor(minstr->getOpCode());
341   
342   Function *F = vmInstr->getParent()->getParent();
343   
344   for (unsigned op=0; op < minstr->getNumOperands(); op++)
345     {
346       const MachineOperand& mop = minstr->getOperand(op);
347           
348       // skip the result position (for efficiency below) and any other
349       // positions already marked as not a virtual register
350       if (instrDesc.resultPos == (int) op || 
351           mop.getOperandType() != MachineOperand::MO_VirtualRegister ||
352           mop.getVRegValue() == NULL)
353         {
354           continue;
355         }
356           
357       Value* opValue = mop.getVRegValue();
358       bool constantThatMustBeLoaded = false;
359       
360       if (Constant *opConst = dyn_cast<Constant>(opValue))
361         {
362           unsigned int machineRegNum;
363           int64_t immedValue;
364           MachineOperand::MachineOperandType opType =
365             ChooseRegOrImmed(opValue, minstr->getOpCode(), target,
366                              (target.getInstrInfo().getImmedConstantPos(minstr->getOpCode()) == (int) op),
367                              machineRegNum, immedValue);
368           
369           if (opType == MachineOperand::MO_MachineRegister)
370             minstr->SetMachineOperandReg(op, machineRegNum);
371           else if (opType == MachineOperand::MO_VirtualRegister)
372             constantThatMustBeLoaded = true; // load is generated below
373           else
374             minstr->SetMachineOperandConst(op, opType, immedValue);
375         }
376       
377       if (constantThatMustBeLoaded || isa<GlobalValue>(opValue))
378         { // opValue is a constant that must be explicitly loaded into a reg.
379           TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue,vmInstr,
380                                                             loadConstVec,
381                                                             target);
382           minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
383                                        tmpReg);
384         }
385     }
386   
387   // 
388   // Also, check for implicit operands used by the machine instruction
389   // (no need to check those defined since they cannot be constants).
390   // These include:
391   // -- arguments to a Call
392   // -- return value of a Return
393   // Any such operand that is a constant value needs to be fixed also.
394   // The current instructions with implicit refs (viz., Call and Return)
395   // have no immediate fields, so the constant always needs to be loaded
396   // into a register.
397   // 
398   bool isCall = target.getInstrInfo().isCall(minstr->getOpCode());
399   unsigned lastCallArgNum = 0;          // unused if not a call
400   CallArgsDescriptor* argDesc = NULL;   // unused if not a call
401   if (isCall)
402     argDesc = CallArgsDescriptor::get(minstr);
403   
404   for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
405     if (isa<Constant>(minstr->getImplicitRef(i)) ||
406         isa<GlobalValue>(minstr->getImplicitRef(i)))
407       {
408         Value* oldVal = minstr->getImplicitRef(i);
409         TmpInstruction* tmpReg =
410           InsertCodeToLoadConstant(F, oldVal, vmInstr, loadConstVec, target);
411         minstr->setImplicitRef(i, tmpReg);
412         
413         if (isCall)
414           { // find and replace the argument in the CallArgsDescriptor
415             unsigned i=lastCallArgNum;
416             while (argDesc->getArgInfo(i).getArgVal() != oldVal)
417               ++i;
418             assert(i < argDesc->getNumArgs() &&
419                    "Constant operands to a call *must* be in the arg list");
420             lastCallArgNum = i;
421             argDesc->getArgInfo(i).replaceArgVal(tmpReg);
422           }
423       }
424   
425   return loadConstVec;
426 }
427
428