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