When extending a liveinterval by commuting, don't throw away the live ranges that...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeFloatTypes.cpp
1 //===-------- LegalizeFloatTypes.cpp - Legalization of float types --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements float type expansion and conversion of float types to
11 // integer types on behalf of LegalizeTypes.
12 // Converting to integer is the act of turning a computation in an illegal
13 // floating point type into a computation in an integer type of the same size.
14 // For example, turning f32 arithmetic into operations using i32.  Also known as
15 // "soft float".  The result is equivalent to bitcasting the float value to the
16 // integer type.
17 // Expansion is the act of changing a computation in an illegal type to be a
18 // computation in multiple registers of a smaller type.  For example,
19 // implementing ppcf128 arithmetic in two f64 registers.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "LegalizeTypes.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 using namespace llvm;
28
29 /// GetFPLibCall - Return the right libcall for the given floating point type.
30 static RTLIB::Libcall GetFPLibCall(MVT VT,
31                                    RTLIB::Libcall Call_F32,
32                                    RTLIB::Libcall Call_F64,
33                                    RTLIB::Libcall Call_F80,
34                                    RTLIB::Libcall Call_PPCF128) {
35   return
36     VT == MVT::f32 ? Call_F32 :
37     VT == MVT::f64 ? Call_F64 :
38     VT == MVT::f80 ? Call_F80 :
39     VT == MVT::ppcf128 ? Call_PPCF128 :
40     RTLIB::UNKNOWN_LIBCALL;
41 }
42
43 //===----------------------------------------------------------------------===//
44 //  Result Float to Integer Conversion.
45 //===----------------------------------------------------------------------===//
46
47 void DAGTypeLegalizer::PromoteFloatResult(SDNode *N, unsigned ResNo) {
48   DEBUG(cerr << "Promote float result " << ResNo << ": "; N->dump(&DAG);
49         cerr << "\n");
50   SDOperand R = SDOperand();
51
52   // FIXME: Custom lowering for float-to-int?
53 #if 0
54   // See if the target wants to custom convert this node to an integer.
55   if (TLI.getOperationAction(N->getOpcode(), N->getValueType(0)) ==
56       TargetLowering::Custom) {
57     // If the target wants to, allow it to lower this itself.
58     if (SDNode *P = TLI.FloatToIntOperationResult(N, DAG)) {
59       // Everything that once used N now uses P.  We are guaranteed that the
60       // result value types of N and the result value types of P match.
61       ReplaceNodeWith(N, P);
62       return;
63     }
64   }
65 #endif
66
67   switch (N->getOpcode()) {
68   default:
69 #ifndef NDEBUG
70     cerr << "PromoteFloatResult #" << ResNo << ": ";
71     N->dump(&DAG); cerr << "\n";
72 #endif
73     assert(0 && "Do not know how to convert the result of this operator!");
74     abort();
75
76     case ISD::BIT_CONVERT: R = PromoteFloatRes_BIT_CONVERT(N); break;
77     case ISD::BUILD_PAIR:  R = PromoteFloatRes_BUILD_PAIR(N); break;
78     case ISD::ConstantFP:
79       R = PromoteFloatRes_ConstantFP(cast<ConstantFPSDNode>(N));
80       break;
81     case ISD::FCOPYSIGN:   R = PromoteFloatRes_FCOPYSIGN(N); break;
82     case ISD::LOAD:        R = PromoteFloatRes_LOAD(N); break;
83     case ISD::SINT_TO_FP:
84     case ISD::UINT_TO_FP:  R = PromoteFloatRes_XINT_TO_FP(N); break;
85
86     case ISD::FADD: R = PromoteFloatRes_FADD(N); break;
87     case ISD::FMUL: R = PromoteFloatRes_FMUL(N); break;
88     case ISD::FSUB: R = PromoteFloatRes_FSUB(N); break;
89   }
90
91   // If R is null, the sub-method took care of registering the result.
92   if (R.Val)
93     SetPromotedFloat(SDOperand(N, ResNo), R);
94 }
95
96 SDOperand DAGTypeLegalizer::PromoteFloatRes_BIT_CONVERT(SDNode *N) {
97   return BitConvertToInteger(N->getOperand(0));
98 }
99
100 SDOperand DAGTypeLegalizer::PromoteFloatRes_BUILD_PAIR(SDNode *N) {
101   // Convert the inputs to integers, and build a new pair out of them.
102   return DAG.getNode(ISD::BUILD_PAIR,
103                      TLI.getTypeToTransformTo(N->getValueType(0)),
104                      BitConvertToInteger(N->getOperand(0)),
105                      BitConvertToInteger(N->getOperand(1)));
106 }
107
108 SDOperand DAGTypeLegalizer::PromoteFloatRes_ConstantFP(ConstantFPSDNode *N) {
109   return DAG.getConstant(N->getValueAPF().convertToAPInt(),
110                          TLI.getTypeToTransformTo(N->getValueType(0)));
111 }
112
113 SDOperand DAGTypeLegalizer::PromoteFloatRes_FADD(SDNode *N) {
114   MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
115   SDOperand Ops[2] = { GetPromotedFloat(N->getOperand(0)),
116                        GetPromotedFloat(N->getOperand(1)) };
117   return MakeLibCall(GetFPLibCall(N->getValueType(0),
118                                   RTLIB::ADD_F32,
119                                   RTLIB::ADD_F64,
120                                   RTLIB::ADD_F80,
121                                   RTLIB::ADD_PPCF128),
122                      NVT, Ops, 2, false/*sign irrelevant*/);
123 }
124
125 SDOperand DAGTypeLegalizer::PromoteFloatRes_FCOPYSIGN(SDNode *N) {
126   SDOperand LHS = GetPromotedFloat(N->getOperand(0));
127   SDOperand RHS = BitConvertToInteger(N->getOperand(1));
128
129   MVT LVT = LHS.getValueType();
130   MVT RVT = RHS.getValueType();
131
132   unsigned LSize = LVT.getSizeInBits();
133   unsigned RSize = RVT.getSizeInBits();
134
135   // First get the sign bit of second operand.
136   SDOperand SignBit = DAG.getNode(ISD::SHL, RVT, DAG.getConstant(1, RVT),
137                                   DAG.getConstant(RSize - 1,
138                                                   TLI.getShiftAmountTy()));
139   SignBit = DAG.getNode(ISD::AND, RVT, RHS, SignBit);
140
141   // Shift right or sign-extend it if the two operands have different types.
142   int SizeDiff = RVT.getSizeInBits() - LVT.getSizeInBits();
143   if (SizeDiff > 0) {
144     SignBit = DAG.getNode(ISD::SRL, RVT, SignBit,
145                           DAG.getConstant(SizeDiff, TLI.getShiftAmountTy()));
146     SignBit = DAG.getNode(ISD::TRUNCATE, LVT, SignBit);
147   } else if (SizeDiff < 0) {
148     SignBit = DAG.getNode(ISD::ANY_EXTEND, LVT, SignBit);
149     SignBit = DAG.getNode(ISD::SHL, LVT, SignBit,
150                           DAG.getConstant(-SizeDiff, TLI.getShiftAmountTy()));
151   }
152
153   // Clear the sign bit of the first operand.
154   SDOperand Mask = DAG.getNode(ISD::SHL, LVT, DAG.getConstant(1, LVT),
155                                DAG.getConstant(LSize - 1,
156                                                TLI.getShiftAmountTy()));
157   Mask = DAG.getNode(ISD::SUB, LVT, Mask, DAG.getConstant(1, LVT));
158   LHS = DAG.getNode(ISD::AND, LVT, LHS, Mask);
159
160   // Or the value with the sign bit.
161   return DAG.getNode(ISD::OR, LVT, LHS, SignBit);
162 }
163
164 SDOperand DAGTypeLegalizer::PromoteFloatRes_FMUL(SDNode *N) {
165   MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
166   SDOperand Ops[2] = { GetPromotedFloat(N->getOperand(0)),
167                        GetPromotedFloat(N->getOperand(1)) };
168   return MakeLibCall(GetFPLibCall(N->getValueType(0),
169                                   RTLIB::MUL_F32,
170                                   RTLIB::MUL_F64,
171                                   RTLIB::MUL_F80,
172                                   RTLIB::MUL_PPCF128),
173                      NVT, Ops, 2, false/*sign irrelevant*/);
174 }
175
176 SDOperand DAGTypeLegalizer::PromoteFloatRes_FSUB(SDNode *N) {
177   MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
178   SDOperand Ops[2] = { GetPromotedFloat(N->getOperand(0)),
179                        GetPromotedFloat(N->getOperand(1)) };
180   return MakeLibCall(GetFPLibCall(N->getValueType(0),
181                                   RTLIB::SUB_F32,
182                                   RTLIB::SUB_F64,
183                                   RTLIB::SUB_F80,
184                                   RTLIB::SUB_PPCF128),
185                      NVT, Ops, 2, false/*sign irrelevant*/);
186 }
187
188 SDOperand DAGTypeLegalizer::PromoteFloatRes_LOAD(SDNode *N) {
189   LoadSDNode *L = cast<LoadSDNode>(N);
190   MVT VT = N->getValueType(0);
191   MVT NVT = TLI.getTypeToTransformTo(VT);
192
193   if (L->getExtensionType() == ISD::NON_EXTLOAD)
194      return DAG.getLoad(L->getAddressingMode(), L->getExtensionType(),
195                         NVT, L->getChain(), L->getBasePtr(), L->getOffset(),
196                         L->getSrcValue(), L->getSrcValueOffset(), NVT,
197                         L->isVolatile(), L->getAlignment());
198
199   // Do a non-extending load followed by FP_EXTEND.
200   SDOperand NL = DAG.getLoad(L->getAddressingMode(), ISD::NON_EXTLOAD,
201                              L->getMemoryVT(), L->getChain(),
202                              L->getBasePtr(), L->getOffset(),
203                              L->getSrcValue(), L->getSrcValueOffset(),
204                              L->getMemoryVT(),
205                              L->isVolatile(), L->getAlignment());
206   return BitConvertToInteger(DAG.getNode(ISD::FP_EXTEND, VT, NL));
207 }
208
209 SDOperand DAGTypeLegalizer::PromoteFloatRes_XINT_TO_FP(SDNode *N) {
210   bool isSigned = N->getOpcode() == ISD::SINT_TO_FP;
211   MVT DestVT = N->getValueType(0);
212   SDOperand Op = N->getOperand(0);
213
214   if (Op.getValueType() == MVT::i32) {
215     // simple 32-bit [signed|unsigned] integer to float/double expansion
216
217     // Get the stack frame index of a 8 byte buffer.
218     SDOperand StackSlot = DAG.CreateStackTemporary(MVT::f64);
219
220     // word offset constant for Hi/Lo address computation
221     SDOperand Offset =
222       DAG.getConstant(MVT(MVT::i32).getSizeInBits() / 8,
223                       TLI.getPointerTy());
224     // set up Hi and Lo (into buffer) address based on endian
225     SDOperand Hi = StackSlot;
226     SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot, Offset);
227     if (TLI.isLittleEndian())
228       std::swap(Hi, Lo);
229
230     // if signed map to unsigned space
231     SDOperand OpMapped;
232     if (isSigned) {
233       // constant used to invert sign bit (signed to unsigned mapping)
234       SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
235       OpMapped = DAG.getNode(ISD::XOR, MVT::i32, Op, SignBit);
236     } else {
237       OpMapped = Op;
238     }
239     // store the lo of the constructed double - based on integer input
240     SDOperand Store1 = DAG.getStore(DAG.getEntryNode(),
241                                     OpMapped, Lo, NULL, 0);
242     // initial hi portion of constructed double
243     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
244     // store the hi of the constructed double - biased exponent
245     SDOperand Store2=DAG.getStore(Store1, InitialHi, Hi, NULL, 0);
246     // load the constructed double
247     SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot, NULL, 0);
248     // FP constant to bias correct the final result
249     SDOperand Bias = DAG.getConstantFP(isSigned ?
250                                             BitsToDouble(0x4330000080000000ULL)
251                                           : BitsToDouble(0x4330000000000000ULL),
252                                      MVT::f64);
253     // subtract the bias
254     SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
255     // final result
256     SDOperand Result;
257     // handle final rounding
258     if (DestVT == MVT::f64) {
259       // do nothing
260       Result = Sub;
261     } else if (DestVT.bitsLT(MVT::f64)) {
262       Result = DAG.getNode(ISD::FP_ROUND, DestVT, Sub,
263                            DAG.getIntPtrConstant(0));
264     } else if (DestVT.bitsGT(MVT::f64)) {
265       Result = DAG.getNode(ISD::FP_EXTEND, DestVT, Sub);
266     }
267     return BitConvertToInteger(Result);
268   }
269   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
270   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op);
271
272   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultType(Op), Op,
273                                    DAG.getConstant(0, Op.getValueType()),
274                                    ISD::SETLT);
275   SDOperand Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
276   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
277                                     SignSet, Four, Zero);
278
279   // If the sign bit of the integer is set, the large number will be treated
280   // as a negative number.  To counteract this, the dynamic code adds an
281   // offset depending on the data type.
282   uint64_t FF;
283   switch (Op.getValueType().getSimpleVT()) {
284   default: assert(0 && "Unsupported integer type!");
285   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
286   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
287   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
288   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
289   }
290   if (TLI.isLittleEndian()) FF <<= 32;
291   static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
292
293   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
294   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
295   SDOperand FudgeInReg;
296   if (DestVT == MVT::f32)
297     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
298                              PseudoSourceValue::getConstantPool(), 0);
299   else {
300     FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, DestVT,
301                                 DAG.getEntryNode(), CPIdx,
302                                 PseudoSourceValue::getConstantPool(), 0,
303                                 MVT::f32);
304   }
305
306   return BitConvertToInteger(DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg));
307 }
308
309
310 //===----------------------------------------------------------------------===//
311 //  Operand Float to Integer Conversion..
312 //===----------------------------------------------------------------------===//
313
314 bool DAGTypeLegalizer::PromoteFloatOperand(SDNode *N, unsigned OpNo) {
315   DEBUG(cerr << "Promote float operand " << OpNo << ": "; N->dump(&DAG);
316         cerr << "\n");
317   SDOperand Res(0, 0);
318
319   // FIXME: Custom lowering for float-to-int?
320 #if 0
321   if (TLI.getOperationAction(N->getOpcode(), N->getOperand(OpNo).getValueType())
322       == TargetLowering::Custom)
323     Res = TLI.LowerOperation(SDOperand(N, 0), DAG);
324 #endif
325
326   if (Res.Val == 0) {
327     switch (N->getOpcode()) {
328     default:
329 #ifndef NDEBUG
330       cerr << "PromoteFloatOperand Op #" << OpNo << ": ";
331       N->dump(&DAG); cerr << "\n";
332 #endif
333       assert(0 && "Do not know how to convert this operator's operand!");
334       abort();
335
336       case ISD::BIT_CONVERT: Res = PromoteFloatOp_BIT_CONVERT(N); break;
337     }
338   }
339
340   // If the result is null, the sub-method took care of registering results etc.
341   if (!Res.Val) return false;
342
343   // If the result is N, the sub-method updated N in place.  Check to see if any
344   // operands are new, and if so, mark them.
345   if (Res.Val == N) {
346     // Mark N as new and remark N and its operands.  This allows us to correctly
347     // revisit N if it needs another step of promotion and allows us to visit
348     // any new operands to N.
349     ReanalyzeNode(N);
350     return true;
351   }
352
353   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
354          "Invalid operand expansion");
355
356   ReplaceValueWith(SDOperand(N, 0), Res);
357   return false;
358 }
359
360 SDOperand DAGTypeLegalizer::PromoteFloatOp_BIT_CONVERT(SDNode *N) {
361   return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0),
362                      GetPromotedFloat(N->getOperand(0)));
363 }
364
365
366 //===----------------------------------------------------------------------===//
367 //  Float Result Expansion
368 //===----------------------------------------------------------------------===//
369
370 /// ExpandFloatResult - This method is called when the specified result of the
371 /// specified node is found to need expansion.  At this point, the node may also
372 /// have invalid operands or may have other results that need promotion, we just
373 /// know that (at least) one result needs expansion.
374 void DAGTypeLegalizer::ExpandFloatResult(SDNode *N, unsigned ResNo) {
375   DEBUG(cerr << "Expand float result: "; N->dump(&DAG); cerr << "\n");
376   SDOperand Lo, Hi;
377   Lo = Hi = SDOperand();
378
379   // See if the target wants to custom expand this node.
380   if (TLI.getOperationAction(N->getOpcode(), N->getValueType(0)) ==
381           TargetLowering::Custom) {
382     // If the target wants to, allow it to lower this itself.
383     if (SDNode *P = TLI.ExpandOperationResult(N, DAG)) {
384       // Everything that once used N now uses P.  We are guaranteed that the
385       // result value types of N and the result value types of P match.
386       ReplaceNodeWith(N, P);
387       return;
388     }
389   }
390
391   switch (N->getOpcode()) {
392   default:
393 #ifndef NDEBUG
394     cerr << "ExpandFloatResult #" << ResNo << ": ";
395     N->dump(&DAG); cerr << "\n";
396 #endif
397     assert(0 && "Do not know how to expand the result of this operator!");
398     abort();
399   }
400
401   // If Lo/Hi is null, the sub-method took care of registering results etc.
402   if (Lo.Val)
403     SetExpandedFloat(SDOperand(N, ResNo), Lo, Hi);
404 }
405
406
407 //===----------------------------------------------------------------------===//
408 //  Float Operand Expansion
409 //===----------------------------------------------------------------------===//
410
411 /// ExpandFloatOperand - This method is called when the specified operand of the
412 /// specified node is found to need expansion.  At this point, all of the result
413 /// types of the node are known to be legal, but other operands of the node may
414 /// need promotion or expansion as well as the specified one.
415 bool DAGTypeLegalizer::ExpandFloatOperand(SDNode *N, unsigned OpNo) {
416   DEBUG(cerr << "Expand float operand: "; N->dump(&DAG); cerr << "\n");
417   SDOperand Res(0, 0);
418
419   if (TLI.getOperationAction(N->getOpcode(), N->getOperand(OpNo).getValueType())
420       == TargetLowering::Custom)
421     Res = TLI.LowerOperation(SDOperand(N, 0), DAG);
422
423   if (Res.Val == 0) {
424     switch (N->getOpcode()) {
425     default:
426   #ifndef NDEBUG
427       cerr << "ExpandFloatOperand Op #" << OpNo << ": ";
428       N->dump(&DAG); cerr << "\n";
429   #endif
430       assert(0 && "Do not know how to expand this operator's operand!");
431       abort();
432     }
433   }
434
435   // If the result is null, the sub-method took care of registering results etc.
436   if (!Res.Val) return false;
437   // If the result is N, the sub-method updated N in place.  Check to see if any
438   // operands are new, and if so, mark them.
439   if (Res.Val == N) {
440     // Mark N as new and remark N and its operands.  This allows us to correctly
441     // revisit N if it needs another step of expansion and allows us to visit
442     // any new operands to N.
443     ReanalyzeNode(N);
444     return true;
445   }
446
447   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
448          "Invalid operand expansion");
449
450   ReplaceValueWith(SDOperand(N, 0), Res);
451   return false;
452 }