LegalizeVectorOps.cpp revision aec5861bb6ace3734163c000cb75ca2e22e29caa
1//===-- LegalizeVectorOps.cpp - Implement SelectionDAG::LegalizeVectors ---===//
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 the SelectionDAG::LegalizeVectors method.
11//
12// The vector legalizer looks for vector operations which might need to be
13// scalarized and legalizes them. This is a separate step from Legalize because
14// scalarizing can introduce illegal types.  For example, suppose we have an
15// ISD::SDIV of type v2i64 on x86-32.  The type is legal (for example, addition
16// on a v2i64 is legal), but ISD::SDIV isn't legal, so we have to unroll the
17// operation, which introduces nodes with the illegal type i64 which must be
18// expanded.  Similarly, suppose we have an ISD::SRA of type v16i8 on PowerPC;
19// the operation must be unrolled, which introduces nodes with the illegal
20// type i8 which must be promoted.
21//
22// This does not legalize vector manipulations like ISD::BUILD_VECTOR,
23// or operations that happen to take a vector which are custom-lowered;
24// the legalization for such operations never produces nodes
25// with illegal types, so it's okay to put off legalizing them until
26// SelectionDAG::Legalize runs.
27//
28//===----------------------------------------------------------------------===//
29
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/Target/TargetLowering.h"
32using namespace llvm;
33
34namespace {
35class VectorLegalizer {
36  SelectionDAG& DAG;
37  const TargetLowering &TLI;
38  bool Changed; // Keep track of whether anything changed
39
40  /// LegalizedNodes - For nodes that are of legal width, and that have more
41  /// than one use, this map indicates what regularized operand to use.  This
42  /// allows us to avoid legalizing the same thing more than once.
43  DenseMap<SDValue, SDValue> LegalizedNodes;
44
45  // Adds a node to the translation cache
46  void AddLegalizedOperand(SDValue From, SDValue To) {
47    LegalizedNodes.insert(std::make_pair(From, To));
48    // If someone requests legalization of the new node, return itself.
49    if (From != To)
50      LegalizedNodes.insert(std::make_pair(To, To));
51  }
52
53  // Legalizes the given node
54  SDValue LegalizeOp(SDValue Op);
55  // Assuming the node is legal, "legalize" the results
56  SDValue TranslateLegalizeResults(SDValue Op, SDValue Result);
57  // Implements unrolling a VSETCC.
58  SDValue UnrollVSETCC(SDValue Op);
59  // Implements expansion for FNEG; falls back to UnrollVectorOp if FSUB
60  // isn't legal.
61  // Implements expansion for UINT_TO_FLOAT; falls back to UnrollVectorOp if
62  // SINT_TO_FLOAT and SHR on vectors isn't legal.
63  SDValue ExpandUINT_TO_FLOAT(SDValue Op);
64  // Implement vselect in terms of XOR, AND,OR when blend is not supported
65  //  by the target.
66  SDValue ExpandVSELECT(SDValue Op);
67  SDValue ExpandFNEG(SDValue Op);
68  // Implements vector promotion; this is essentially just bitcasting the
69  // operands to a different type and bitcasting the result back to the
70  // original type.
71  SDValue PromoteVectorOp(SDValue Op);
72
73  public:
74  bool Run();
75  VectorLegalizer(SelectionDAG& dag) :
76      DAG(dag), TLI(dag.getTargetLoweringInfo()), Changed(false) {}
77};
78
79bool VectorLegalizer::Run() {
80  // The legalize process is inherently a bottom-up recursive process (users
81  // legalize their uses before themselves).  Given infinite stack space, we
82  // could just start legalizing on the root and traverse the whole graph.  In
83  // practice however, this causes us to run out of stack space on large basic
84  // blocks.  To avoid this problem, compute an ordering of the nodes where each
85  // node is only legalized after all of its operands are legalized.
86  DAG.AssignTopologicalOrder();
87  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
88       E = prior(DAG.allnodes_end()); I != llvm::next(E); ++I)
89    LegalizeOp(SDValue(I, 0));
90
91  // Finally, it's possible the root changed.  Get the new root.
92  SDValue OldRoot = DAG.getRoot();
93  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
94  DAG.setRoot(LegalizedNodes[OldRoot]);
95
96  LegalizedNodes.clear();
97
98  // Remove dead nodes now.
99  DAG.RemoveDeadNodes();
100
101  return Changed;
102}
103
104SDValue VectorLegalizer::TranslateLegalizeResults(SDValue Op, SDValue Result) {
105  // Generic legalization: just pass the operand through.
106  for (unsigned i = 0, e = Op.getNode()->getNumValues(); i != e; ++i)
107    AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
108  return Result.getValue(Op.getResNo());
109}
110
111SDValue VectorLegalizer::LegalizeOp(SDValue Op) {
112  // Note that LegalizeOp may be reentered even from single-use nodes, which
113  // means that we always must cache transformed nodes.
114  DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
115  if (I != LegalizedNodes.end()) return I->second;
116
117  SDNode* Node = Op.getNode();
118
119  // Legalize the operands
120  SmallVector<SDValue, 8> Ops;
121  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
122    Ops.push_back(LegalizeOp(Node->getOperand(i)));
123
124  SDValue Result =
125    SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops.data(), Ops.size()), 0);
126
127  bool HasVectorValue = false;
128  for (SDNode::value_iterator J = Node->value_begin(), E = Node->value_end();
129       J != E;
130       ++J)
131    HasVectorValue |= J->isVector();
132  if (!HasVectorValue)
133    return TranslateLegalizeResults(Op, Result);
134
135  EVT QueryType;
136  switch (Op.getOpcode()) {
137  default:
138    return TranslateLegalizeResults(Op, Result);
139  case ISD::ADD:
140  case ISD::SUB:
141  case ISD::MUL:
142  case ISD::SDIV:
143  case ISD::UDIV:
144  case ISD::SREM:
145  case ISD::UREM:
146  case ISD::FADD:
147  case ISD::FSUB:
148  case ISD::FMUL:
149  case ISD::FDIV:
150  case ISD::FREM:
151  case ISD::AND:
152  case ISD::OR:
153  case ISD::XOR:
154  case ISD::SHL:
155  case ISD::SRA:
156  case ISD::SRL:
157  case ISD::ROTL:
158  case ISD::ROTR:
159  case ISD::CTTZ:
160  case ISD::CTLZ:
161  case ISD::CTPOP:
162  case ISD::SELECT:
163  case ISD::VSELECT:
164  case ISD::SELECT_CC:
165  case ISD::SETCC:
166  case ISD::ZERO_EXTEND:
167  case ISD::ANY_EXTEND:
168  case ISD::TRUNCATE:
169  case ISD::SIGN_EXTEND:
170  case ISD::FP_TO_SINT:
171  case ISD::FP_TO_UINT:
172  case ISD::FNEG:
173  case ISD::FABS:
174  case ISD::FSQRT:
175  case ISD::FSIN:
176  case ISD::FCOS:
177  case ISD::FPOWI:
178  case ISD::FPOW:
179  case ISD::FLOG:
180  case ISD::FLOG2:
181  case ISD::FLOG10:
182  case ISD::FEXP:
183  case ISD::FEXP2:
184  case ISD::FCEIL:
185  case ISD::FTRUNC:
186  case ISD::FRINT:
187  case ISD::FNEARBYINT:
188  case ISD::FFLOOR:
189  case ISD::SIGN_EXTEND_INREG:
190    QueryType = Node->getValueType(0);
191    break;
192  case ISD::FP_ROUND_INREG:
193    QueryType = cast<VTSDNode>(Node->getOperand(1))->getVT();
194    break;
195  case ISD::SINT_TO_FP:
196  case ISD::UINT_TO_FP:
197    QueryType = Node->getOperand(0).getValueType();
198    break;
199  }
200
201  switch (TLI.getOperationAction(Node->getOpcode(), QueryType)) {
202  case TargetLowering::Promote:
203    // "Promote" the operation by bitcasting
204    Result = PromoteVectorOp(Op);
205    Changed = true;
206    break;
207  case TargetLowering::Legal: break;
208  case TargetLowering::Custom: {
209    SDValue Tmp1 = TLI.LowerOperation(Op, DAG);
210    if (Tmp1.getNode()) {
211      Result = Tmp1;
212      break;
213    }
214    // FALL THROUGH
215  }
216  case TargetLowering::Expand:
217    if (Node->getOpcode() == ISD::VSELECT)
218      Result = ExpandVSELECT(Op);
219    else if (Node->getOpcode() == ISD::UINT_TO_FP)
220      Result = ExpandUINT_TO_FLOAT(Op);
221    else if (Node->getOpcode() == ISD::FNEG)
222      Result = ExpandFNEG(Op);
223    else if (Node->getOpcode() == ISD::SETCC)
224      Result = UnrollVSETCC(Op);
225    else
226      Result = DAG.UnrollVectorOp(Op.getNode());
227    break;
228  }
229
230  // Make sure that the generated code is itself legal.
231  if (Result != Op) {
232    Result = LegalizeOp(Result);
233    Changed = true;
234  }
235
236  // Note that LegalizeOp may be reentered even from single-use nodes, which
237  // means that we always must cache transformed nodes.
238  AddLegalizedOperand(Op, Result);
239  return Result;
240}
241
242SDValue VectorLegalizer::PromoteVectorOp(SDValue Op) {
243  // Vector "promotion" is basically just bitcasting and doing the operation
244  // in a different type.  For example, x86 promotes ISD::AND on v2i32 to
245  // v1i64.
246  EVT VT = Op.getValueType();
247  assert(Op.getNode()->getNumValues() == 1 &&
248         "Can't promote a vector with multiple results!");
249  EVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
250  DebugLoc dl = Op.getDebugLoc();
251  SmallVector<SDValue, 4> Operands(Op.getNumOperands());
252
253  for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
254    if (Op.getOperand(j).getValueType().isVector())
255      Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
256    else
257      Operands[j] = Op.getOperand(j);
258  }
259
260  Op = DAG.getNode(Op.getOpcode(), dl, NVT, &Operands[0], Operands.size());
261
262  return DAG.getNode(ISD::BITCAST, dl, VT, Op);
263}
264
265SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
266  // Implement VSELECT in terms of XOR, AND, OR
267  // on platforms which do not support blend natively.
268  EVT VT =  Op.getOperand(0).getValueType();
269  EVT OVT = Op.getOperand(0).getValueType();
270  DebugLoc DL = Op.getDebugLoc();
271
272  SDValue Mask = Op.getOperand(0);
273  SDValue Op1 = Op.getOperand(1);
274  SDValue Op2 = Op.getOperand(2);
275
276  // If we can't even use the basic vector operations of
277  // AND,OR,XOR, we will have to scalarize the op.
278  if (!TLI.isOperationLegalOrCustom(ISD::AND, VT) ||
279      !TLI.isOperationLegalOrCustom(ISD::XOR, VT) ||
280      !TLI.isOperationLegalOrCustom(ISD::OR, VT)) {
281    return DAG.UnrollVectorOp(Op.getNode());
282  }
283
284  assert(VT.getSizeInBits() == OVT.getSizeInBits() && "Invalid mask size");
285  // Bitcast the operands to be the same type as the mask.
286  // This is needed when we select between FP types because
287  // the mask is a vector of integers.
288  Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
289  Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
290
291  SDValue AllOnes = DAG.getConstant(
292    APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()), VT);
293  SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
294
295  Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
296  Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
297  return DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
298}
299
300SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
301  EVT VT = Op.getOperand(0).getValueType();
302  DebugLoc DL = Op.getDebugLoc();
303
304  // Make sure that the SINT_TO_FP and SRL instructions are available.
305  if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, VT) ||
306      !TLI.isOperationLegalOrCustom(ISD::SRL, VT))
307      return DAG.UnrollVectorOp(Op.getNode());
308
309 EVT SVT = VT.getScalarType();
310  assert((SVT.getSizeInBits() == 64 || SVT.getSizeInBits() == 32) &&
311      "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
312
313  unsigned BW = SVT.getSizeInBits();
314  SDValue HalfWord = DAG.getConstant(BW/2, VT);
315
316  // Constants to clear the upper part of the word.
317  // Notice that we can also use SHL+SHR, but using a constant is slightly
318  // faster on x86.
319  uint64_t HWMask = (SVT.getSizeInBits()==64)?0x00000000FFFFFFFF:0x0000FFFF;
320  SDValue HalfWordMask = DAG.getConstant(HWMask, VT);
321
322  // Two to the power of half-word-size.
323  SDValue TWOHW = DAG.getConstantFP((1<<(BW/2)), Op.getValueType());
324
325  // Clear upper part of LO, lower HI
326  SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
327  SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
328
329  // Convert hi and lo to floats
330  // Convert the hi part back to the upper values
331  SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
332          fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
333  SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
334
335  // Add the two halves
336  return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
337}
338
339
340SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
341  if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
342    SDValue Zero = DAG.getConstantFP(-0.0, Op.getValueType());
343    return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
344                       Zero, Op.getOperand(0));
345  }
346  return DAG.UnrollVectorOp(Op.getNode());
347}
348
349SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
350  EVT VT = Op.getValueType();
351  unsigned NumElems = VT.getVectorNumElements();
352  EVT EltVT = VT.getVectorElementType();
353  SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
354  EVT TmpEltVT = LHS.getValueType().getVectorElementType();
355  DebugLoc dl = Op.getDebugLoc();
356  SmallVector<SDValue, 8> Ops(NumElems);
357  for (unsigned i = 0; i < NumElems; ++i) {
358    SDValue LHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
359                                  DAG.getIntPtrConstant(i));
360    SDValue RHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
361                                  DAG.getIntPtrConstant(i));
362    Ops[i] = DAG.getNode(ISD::SETCC, dl, TLI.getSetCCResultType(TmpEltVT),
363                         LHSElem, RHSElem, CC);
364    Ops[i] = DAG.getNode(ISD::SELECT, dl, EltVT, Ops[i],
365                         DAG.getConstant(APInt::getAllOnesValue
366                                         (EltVT.getSizeInBits()), EltVT),
367                         DAG.getConstant(0, EltVT));
368  }
369  return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElems);
370}
371
372}
373
374bool SelectionDAG::LegalizeVectors() {
375  return VectorLegalizer(*this).Run();
376}
377