Sign-extend integer constants from original type size to 64 bits!
[oota-llvm.git] / lib / Target / SparcV9 / 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/MachineInstr.h"
11 #include "llvm/CodeGen/MachineInstrAnnot.h"
12 #include "llvm/CodeGen/MachineCodeForInstruction.h"
13 #include "llvm/CodeGen/MachineCodeForMethod.h"
14 #include "llvm/CodeGen/InstrForest.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/MachineRegInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Function.h"
19 #include "llvm/Type.h"
20 #include "llvm/iMemory.h"
21 using std::vector;
22
23 //*************************** Local Functions ******************************/
24
25
26 // Generate code to load the constant into a TmpInstruction (virtual reg) and
27 // returns the virtual register.
28 // 
29 static TmpInstruction*
30 InsertCodeToLoadConstant(Function *F,
31                          Value* opValue,
32                          Instruction* vmInstr,
33                          vector<MachineInstr*>& loadConstVec,
34                          TargetMachine& target)
35 {
36   // Create a tmp virtual register to hold the constant.
37   TmpInstruction* tmpReg = new TmpInstruction(opValue);
38   MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
39   mcfi.addTemp(tmpReg);
40   
41   target.getInstrInfo().CreateCodeToLoadConst(target, F, opValue, tmpReg,
42                                               loadConstVec, mcfi);
43   
44   // Record the mapping from the tmp VM instruction to machine instruction.
45   // Do this for all machine instructions that were not mapped to any
46   // other temp values created by 
47   // tmpReg->addMachineInstruction(loadConstVec.back());
48   
49   return tmpReg;
50 }
51
52
53 //---------------------------------------------------------------------------
54 // Function GetConstantValueAsUnsignedInt
55 // Function GetConstantValueAsSignedInt
56 // 
57 // Convenience functions to get the value of an integral constant, for an
58 // appropriate integer or non-integer type that can be held in a signed
59 // or unsigned integer respectively.  The type of the argument must be
60 // the following:
61 //      Signed or unsigned integer
62 //      Boolean
63 //      Pointer
64 // 
65 // isValidConstant is set to true if a valid constant was found.
66 //---------------------------------------------------------------------------
67
68 uint64_t
69 GetConstantValueAsUnsignedInt(const Value *V,
70                               bool &isValidConstant)
71 {
72   isValidConstant = true;
73
74   if (isa<Constant>(V))
75     if (const ConstantBool *CB = dyn_cast<ConstantBool>(V))
76       return (int64_t)CB->getValue();
77     else if (const ConstantSInt *CS = dyn_cast<ConstantSInt>(V))
78       return (uint64_t)CS->getValue();
79     else if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
80       return CU->getValue();
81
82   isValidConstant = false;
83   return 0;
84 }
85
86 int64_t
87 GetConstantValueAsSignedInt(const Value *V,
88                             bool &isValidConstant)
89 {
90   uint64_t C = GetConstantValueAsUnsignedInt(V, isValidConstant);
91   if (isValidConstant) {
92     if (V->getType()->isSigned() || C < INT64_MAX) // safe to cast to signed
93       return (int64_t) C;
94     else
95       isValidConstant = false;
96   }
97   return 0;
98 }
99
100
101 //---------------------------------------------------------------------------
102 // Function: FoldGetElemChain
103 // 
104 // Purpose:
105 //   Fold a chain of GetElementPtr instructions containing only
106 //   constant offsets into an equivalent (Pointer, IndexVector) pair.
107 //   Returns the pointer Value, and stores the resulting IndexVector
108 //   in argument chainIdxVec. This is a helper function for
109 //   FoldConstantIndices that does the actual folding. 
110 //---------------------------------------------------------------------------
111
112 static Value*
113 FoldGetElemChain(InstrTreeNode* ptrNode, vector<Value*>& chainIdxVec)
114 {
115   InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
116   GetElementPtrInst* gepInst =
117     dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
118
119   // ptr value is not computed in this tree or ptr value does not come from GEP
120   // instruction
121   if (gepInst == NULL)
122     return NULL;
123
124   // Return NULL if we don't fold any instructions in.
125   Value* ptrVal = NULL;
126
127   // Remember if the last instruction had a leading [0] index.
128   bool hasLeadingZero = false;
129
130   // Now chase the chain of getElementInstr instructions, if any.
131   // Check for any non-constant indices and stop there.
132   // 
133   InstructionNode* ptrChild = gepNode;
134   while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
135                       ptrChild->getOpLabel() == GetElemPtrIdx))
136     {
137       // Child is a GetElemPtr instruction
138       gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
139       User::op_iterator OI, firstIdx = gepInst->idx_begin();
140       User::op_iterator lastIdx = gepInst->idx_end();
141       bool allConstantOffsets = true;
142
143       // Check that all offsets are constant for this instruction
144       for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
145         allConstantOffsets = isa<ConstantInt>(*OI);
146
147       if (allConstantOffsets)
148         { // Get pointer value out of ptrChild.
149           ptrVal = gepInst->getPointerOperand();
150
151           // Check for a leading [0] index, if any.  It will be discarded later.
152           hasLeadingZero = (*firstIdx ==
153                               Constant::getNullValue((*firstIdx)->getType()));
154
155           // Insert its index vector at the start, skipping any leading [0]
156           chainIdxVec.insert(chainIdxVec.begin(),
157                              firstIdx + hasLeadingZero, lastIdx);
158
159           // Mark the folded node so no code is generated for it.
160           ((InstructionNode*) ptrChild)->markFoldedIntoParent();
161         }
162       else // cannot fold this getElementPtr instr. or any further ones
163         break;
164
165       ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
166     }
167
168   // If the first getElementPtr instruction had a leading [0], add it back.
169   // Note that this instruction is the *last* one successfully folded above.
170   if (ptrVal && hasLeadingZero) 
171     chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
172
173   return ptrVal;
174 }
175
176
177 //---------------------------------------------------------------------------
178 // Function: GetMemInstArgs
179 // 
180 // Purpose:
181 //   Get the pointer value and the index vector for a memory operation
182 //   (GetElementPtr, Load, or Store).  If all indices of the given memory
183 //   operation are constant, fold in constant indices in a chain of
184 //   preceding GetElementPtr instructions (if any), and return the
185 //   pointer value of the first instruction in the chain.
186 //   All folded instructions are marked so no code is generated for them.
187 //
188 // Return values:
189 //   Returns the pointer Value to use.
190 //   Returns the resulting IndexVector in idxVec.
191 //   Returns true/false in allConstantIndices if all indices are/aren't const.
192 //---------------------------------------------------------------------------
193
194
195 // Check for a constant (uint) 0.
196 inline bool
197 IsZero(Value* idx)
198 {
199   return (isa<ConstantInt>(idx) && cast<ConstantInt>(idx)->isNullValue());
200 }
201
202 Value*
203 GetMemInstArgs(const InstructionNode* memInstrNode,
204                vector<Value*>& idxVec,
205                bool& allConstantIndices)
206 {
207   allConstantIndices = true;
208   Instruction* memInst = memInstrNode->getInstruction();
209
210   // If there is a GetElemPtr instruction to fold in to this instr,
211   // it must be in the left child for Load and GetElemPtr, and in the
212   // right child for Store instructions.
213   InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
214                              ? memInstrNode->rightChild()
215                              : memInstrNode->leftChild()); 
216
217   // Default pointer is the one from the current instruction.
218   Value* ptrVal = ptrChild->getValue(); 
219
220   // GEP is the only indexed memory instruction.  gepI is used below.
221   GetElementPtrInst* gepI = dyn_cast<GetElementPtrInst>(memInst);
222
223   // If memInst is a GEP, check if all indices are constant for this instruction
224   if (gepI)
225     for (User::op_iterator OI=gepI->idx_begin(), OE=gepI->idx_end();
226          allConstantIndices && OI != OE; ++OI)
227       if (! isa<Constant>(*OI))
228         allConstantIndices = false;     // note: this also terminates loop!
229
230   // If we have only constant indices, fold chains of constant indices
231   // in this and any preceding GetElemPtr instructions.
232   bool foldedGEPs = false;
233   if (allConstantIndices)
234     if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec))
235       {
236         ptrVal = newPtr;
237         foldedGEPs = true;
238         assert((!gepI || IsZero(*gepI->idx_begin())) && "1st index not 0");
239       }
240
241   // Append the index vector of the current instruction, if any.
242   // Skip the leading [0] index if preceding GEPs were folded into this.
243   if (gepI)
244     idxVec.insert(idxVec.end(), gepI->idx_begin() +foldedGEPs, gepI->idx_end());
245
246   return ptrVal;
247 }
248
249 //------------------------------------------------------------------------ 
250 // Function Set2OperandsFromInstr
251 // Function Set3OperandsFromInstr
252 // 
253 // For the common case of 2- and 3-operand arithmetic/logical instructions,
254 // set the m/c instr. operands directly from the VM instruction's operands.
255 // Check whether the first or second operand is 0 and can use a dedicated "0"
256 // register.
257 // Check whether the second operand should use an immediate field or register.
258 // (First and third operands are never immediates for such instructions.)
259 // 
260 // Arguments:
261 // canDiscardResult: Specifies that the result operand can be discarded
262 //                   by using the dedicated "0"
263 // 
264 // op1position, op2position and resultPosition: Specify in which position
265 //                   in the machine instruction the 3 operands (arg1, arg2
266 //                   and result) should go.
267 // 
268 //------------------------------------------------------------------------ 
269
270 void
271 Set2OperandsFromInstr(MachineInstr* minstr,
272                       InstructionNode* vmInstrNode,
273                       const TargetMachine& target,
274                       bool canDiscardResult,
275                       int op1Position,
276                       int resultPosition)
277 {
278   Set3OperandsFromInstr(minstr, vmInstrNode, target,
279                         canDiscardResult, op1Position,
280                         /*op2Position*/ -1, resultPosition);
281 }
282
283
284 void
285 Set3OperandsFromInstr(MachineInstr* minstr,
286                       InstructionNode* vmInstrNode,
287                       const TargetMachine& target,
288                       bool canDiscardResult,
289                       int op1Position,
290                       int op2Position,
291                       int resultPosition)
292 {
293   assert(op1Position >= 0);
294   assert(resultPosition >= 0);
295   
296   // operand 1
297   minstr->SetMachineOperandVal(op1Position, MachineOperand::MO_VirtualRegister,
298                             vmInstrNode->leftChild()->getValue());   
299   
300   // operand 2 (if any)
301   if (op2Position >= 0)
302     minstr->SetMachineOperandVal(op2Position, MachineOperand::MO_VirtualRegister,
303                               vmInstrNode->rightChild()->getValue());   
304   
305   // result operand: if it can be discarded, use a dead register if one exists
306   if (canDiscardResult && target.getRegInfo().getZeroRegNum() >= 0)
307     minstr->SetMachineOperandReg(resultPosition,
308                               target.getRegInfo().getZeroRegNum());
309   else
310     minstr->SetMachineOperandVal(resultPosition,
311                               MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());
312 }
313
314
315 MachineOperand::MachineOperandType
316 ChooseRegOrImmed(int64_t intValue,
317                  bool isSigned,
318                  MachineOpCode opCode,
319                  const TargetMachine& target,
320                  bool canUseImmed,
321                  unsigned int& getMachineRegNum,
322                  int64_t& getImmedValue)
323 {
324   MachineOperand::MachineOperandType opType=MachineOperand::MO_VirtualRegister;
325   getMachineRegNum = 0;
326   getImmedValue = 0;
327
328   if (canUseImmed &&
329            target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
330     {
331       opType = isSigned? MachineOperand::MO_SignExtendedImmed
332                        : MachineOperand::MO_UnextendedImmed;
333       getImmedValue = intValue;
334     }
335   else if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
336     {
337       opType = MachineOperand::MO_MachineRegister;
338       getMachineRegNum = target.getRegInfo().getZeroRegNum();
339     }
340
341   return opType;
342 }
343
344
345 MachineOperand::MachineOperandType
346 ChooseRegOrImmed(Value* val,
347                  MachineOpCode opCode,
348                  const TargetMachine& target,
349                  bool canUseImmed,
350                  unsigned int& getMachineRegNum,
351                  int64_t& getImmedValue)
352 {
353   getMachineRegNum = 0;
354   getImmedValue = 0;
355
356   // To use reg or immed, constant needs to be integer, bool, or a NULL pointer
357   Constant *CPV = dyn_cast<Constant>(val);
358   if (CPV == NULL ||
359       (! CPV->getType()->isIntegral() &&
360        ! (isa<PointerType>(CPV->getType()) && CPV->isNullValue())))
361     return MachineOperand::MO_VirtualRegister;
362
363   // Now get the constant value and check if it fits in the IMMED field.
364   // Take advantage of the fact that the max unsigned value will rarely
365   // fit into any IMMED field and ignore that case (i.e., cast smaller
366   // unsigned constants to signed).
367   // 
368   int64_t intValue;
369   if (isa<PointerType>(CPV->getType()))
370     intValue = 0;                       // We checked above that it is NULL 
371   else if (ConstantBool* CB = dyn_cast<ConstantBool>(CPV))
372     intValue = (int64_t) CB->getValue();
373   else if (CPV->getType()->isSigned())
374     intValue = cast<ConstantSInt>(CPV)->getValue();
375   else
376     { // get the int value and sign-extend if original was less than 64 bits
377       intValue = (int64_t) cast<ConstantUInt>(CPV)->getValue();
378       switch(CPV->getType()->getPrimitiveID())
379         {
380         case Type::UByteTyID:  intValue = (int64_t) (int8_t) intValue; break;
381         case Type::UShortTyID: intValue = (int64_t) (short)  intValue; break;
382         case Type::UIntTyID:   intValue = (int64_t) (int)    intValue; break;
383         default: break;
384         }
385     }
386
387   return ChooseRegOrImmed(intValue, CPV->getType()->isSigned(),
388                           opCode, target, canUseImmed,
389                           getMachineRegNum, getImmedValue);
390 }
391
392
393 //---------------------------------------------------------------------------
394 // Function: FixConstantOperandsForInstr
395 // 
396 // Purpose:
397 // Special handling for constant operands of a machine instruction
398 // -- if the constant is 0, use the hardwired 0 register, if any;
399 // -- if the constant fits in the IMMEDIATE field, use that field;
400 // -- else create instructions to put the constant into a register, either
401 //    directly or by loading explicitly from the constant pool.
402 // 
403 // In the first 2 cases, the operand of `minstr' is modified in place.
404 // Returns a vector of machine instructions generated for operands that
405 // fall under case 3; these must be inserted before `minstr'.
406 //---------------------------------------------------------------------------
407
408 vector<MachineInstr*>
409 FixConstantOperandsForInstr(Instruction* vmInstr,
410                             MachineInstr* minstr,
411                             TargetMachine& target)
412 {
413   vector<MachineInstr*> loadConstVec;
414   
415   MachineOpCode opCode = minstr->getOpCode();
416   const MachineInstrInfo& instrInfo = target.getInstrInfo();
417   const MachineInstrDescriptor& instrDesc = instrInfo.getDescriptor(opCode);
418   int immedPos = instrInfo.getImmedConstantPos(opCode);
419
420   Function *F = vmInstr->getParent()->getParent();
421
422   for (unsigned op=0; op < minstr->getNumOperands(); op++)
423     {
424       const MachineOperand& mop = minstr->getOperand(op);
425           
426       // Skip the result position, preallocated machine registers, or operands
427       // that cannot be constants (CC regs or PC-relative displacements)
428       if (instrDesc.resultPos == (int) op ||
429           mop.getOperandType() == MachineOperand::MO_MachineRegister ||
430           mop.getOperandType() == MachineOperand::MO_CCRegister ||
431           mop.getOperandType() == MachineOperand::MO_PCRelativeDisp)
432         continue;
433
434       bool constantThatMustBeLoaded = false;
435       unsigned int machineRegNum = 0;
436       int64_t immedValue = 0;
437       Value* opValue = NULL;
438       MachineOperand::MachineOperandType opType =
439         MachineOperand::MO_VirtualRegister;
440
441       // Operand may be a virtual register or a compile-time constant
442       if (mop.getOperandType() == MachineOperand::MO_VirtualRegister)
443         {
444           assert(mop.getVRegValue() != NULL);
445           opValue = mop.getVRegValue();
446           if (Constant *opConst = dyn_cast<Constant>(opValue))
447             {
448               opType = ChooseRegOrImmed(opConst, opCode, target,
449                              (immedPos == (int)op), machineRegNum, immedValue);
450               if (opType == MachineOperand::MO_VirtualRegister)
451                 constantThatMustBeLoaded = true;
452             }
453         }
454       else
455         {
456           assert(mop.getOperandType() == MachineOperand::MO_SignExtendedImmed ||
457                  mop.getOperandType() == MachineOperand::MO_UnextendedImmed);
458
459           bool isSigned = (mop.getOperandType() ==
460                            MachineOperand::MO_SignExtendedImmed);
461
462           // Bit-selection flags indicate an instruction that is extracting
463           // bits from its operand so ignore this even if it is a big constant.
464           if (mop.opHiBits32() || mop.opLoBits32() ||
465               mop.opHiBits64() || mop.opLoBits64())
466             continue;
467
468           opType = ChooseRegOrImmed(mop.getImmedValue(), isSigned,
469                                     opCode, target, (immedPos == (int)op), 
470                                     machineRegNum, immedValue);
471
472           if (opType == mop.getOperandType()) 
473             continue;           // no change: this is the most common case
474
475           if (opType == MachineOperand::MO_VirtualRegister)
476             {
477               constantThatMustBeLoaded = true;
478               opValue = isSigned
479                 ? (Value*)ConstantSInt::get(Type::LongTy, immedValue)
480                 : (Value*)ConstantUInt::get(Type::ULongTy,(uint64_t)immedValue);
481             }
482         }
483
484       if (opType == MachineOperand::MO_MachineRegister)
485         minstr->SetMachineOperandReg(op, machineRegNum);
486       else if (opType == MachineOperand::MO_SignExtendedImmed ||
487                opType == MachineOperand::MO_UnextendedImmed)
488         minstr->SetMachineOperandConst(op, opType, immedValue);
489       else if (constantThatMustBeLoaded ||
490                (opValue && isa<GlobalValue>(opValue)))
491         { // opValue is a constant that must be explicitly loaded into a reg
492           assert(opValue);
493           TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
494                                                         loadConstVec, target);
495           minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
496                                        tmpReg);
497         }
498     }
499   
500   // Also, check for implicit operands used by the machine instruction
501   // (no need to check those defined since they cannot be constants).
502   // These include:
503   // -- arguments to a Call
504   // -- return value of a Return
505   // Any such operand that is a constant value needs to be fixed also.
506   // The current instructions with implicit refs (viz., Call and Return)
507   // have no immediate fields, so the constant always needs to be loaded
508   // into a register.
509   // 
510   bool isCall = instrInfo.isCall(opCode);
511   unsigned lastCallArgNum = 0;          // unused if not a call
512   CallArgsDescriptor* argDesc = NULL;   // unused if not a call
513   if (isCall)
514     argDesc = CallArgsDescriptor::get(minstr);
515   
516   for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
517     if (isa<Constant>(minstr->getImplicitRef(i)) ||
518         isa<GlobalValue>(minstr->getImplicitRef(i)))
519       {
520         Value* oldVal = minstr->getImplicitRef(i);
521         TmpInstruction* tmpReg =
522           InsertCodeToLoadConstant(F, oldVal, vmInstr, loadConstVec, target);
523         minstr->setImplicitRef(i, tmpReg);
524         
525         if (isCall)
526           { // find and replace the argument in the CallArgsDescriptor
527             unsigned i=lastCallArgNum;
528             while (argDesc->getArgInfo(i).getArgVal() != oldVal)
529               ++i;
530             assert(i < argDesc->getNumArgs() &&
531                    "Constant operands to a call *must* be in the arg list");
532             lastCallArgNum = i;
533             argDesc->getArgInfo(i).replaceArgVal(tmpReg);
534           }
535       }
536   
537   return loadConstVec;
538 }
539
540