Home | History | Annotate | Download | only in SelectionDAG
      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"
     32 using namespace llvm;
     33 
     34 namespace {
     35 class 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 
     79 bool 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 
    104 SDValue 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 
    111 SDValue 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 
    242 SDValue 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 
    265 SDValue 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   DebugLoc DL = Op.getDebugLoc();
    270 
    271   SDValue Mask = Op.getOperand(0);
    272   SDValue Op1 = Op.getOperand(1);
    273   SDValue Op2 = Op.getOperand(2);
    274 
    275   // If we can't even use the basic vector operations of
    276   // AND,OR,XOR, we will have to scalarize the op.
    277   if (!TLI.isOperationLegalOrCustom(ISD::AND, VT) ||
    278       !TLI.isOperationLegalOrCustom(ISD::XOR, VT) ||
    279       !TLI.isOperationLegalOrCustom(ISD::OR, VT))
    280         return DAG.UnrollVectorOp(Op.getNode());
    281 
    282   assert(VT.getSizeInBits() == Op.getOperand(1).getValueType().getSizeInBits()
    283          && "Invalid mask size");
    284   // Bitcast the operands to be the same type as the mask.
    285   // This is needed when we select between FP types because
    286   // the mask is a vector of integers.
    287   Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
    288   Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
    289 
    290   SDValue AllOnes = DAG.getConstant(
    291     APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()), VT);
    292   SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
    293 
    294   Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
    295   Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
    296   return DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
    297 }
    298 
    299 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
    300   EVT VT = Op.getOperand(0).getValueType();
    301   DebugLoc DL = Op.getDebugLoc();
    302 
    303   // Make sure that the SINT_TO_FP and SRL instructions are available.
    304   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, VT) ||
    305       !TLI.isOperationLegalOrCustom(ISD::SRL, VT))
    306       return DAG.UnrollVectorOp(Op.getNode());
    307 
    308  EVT SVT = VT.getScalarType();
    309   assert((SVT.getSizeInBits() == 64 || SVT.getSizeInBits() == 32) &&
    310       "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
    311 
    312   unsigned BW = SVT.getSizeInBits();
    313   SDValue HalfWord = DAG.getConstant(BW/2, VT);
    314 
    315   // Constants to clear the upper part of the word.
    316   // Notice that we can also use SHL+SHR, but using a constant is slightly
    317   // faster on x86.
    318   uint64_t HWMask = (SVT.getSizeInBits()==64)?0x00000000FFFFFFFF:0x0000FFFF;
    319   SDValue HalfWordMask = DAG.getConstant(HWMask, VT);
    320 
    321   // Two to the power of half-word-size.
    322   SDValue TWOHW = DAG.getConstantFP((1<<(BW/2)), Op.getValueType());
    323 
    324   // Clear upper part of LO, lower HI
    325   SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
    326   SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
    327 
    328   // Convert hi and lo to floats
    329   // Convert the hi part back to the upper values
    330   SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
    331           fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
    332   SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
    333 
    334   // Add the two halves
    335   return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
    336 }
    337 
    338 
    339 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
    340   if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
    341     SDValue Zero = DAG.getConstantFP(-0.0, Op.getValueType());
    342     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
    343                        Zero, Op.getOperand(0));
    344   }
    345   return DAG.UnrollVectorOp(Op.getNode());
    346 }
    347 
    348 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
    349   EVT VT = Op.getValueType();
    350   unsigned NumElems = VT.getVectorNumElements();
    351   EVT EltVT = VT.getVectorElementType();
    352   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
    353   EVT TmpEltVT = LHS.getValueType().getVectorElementType();
    354   DebugLoc dl = Op.getDebugLoc();
    355   SmallVector<SDValue, 8> Ops(NumElems);
    356   for (unsigned i = 0; i < NumElems; ++i) {
    357     SDValue LHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
    358                                   DAG.getIntPtrConstant(i));
    359     SDValue RHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
    360                                   DAG.getIntPtrConstant(i));
    361     Ops[i] = DAG.getNode(ISD::SETCC, dl, TLI.getSetCCResultType(TmpEltVT),
    362                          LHSElem, RHSElem, CC);
    363     Ops[i] = DAG.getNode(ISD::SELECT, dl, EltVT, Ops[i],
    364                          DAG.getConstant(APInt::getAllOnesValue
    365                                          (EltVT.getSizeInBits()), EltVT),
    366                          DAG.getConstant(0, EltVT));
    367   }
    368   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElems);
    369 }
    370 
    371 }
    372 
    373 bool SelectionDAG::LegalizeVectors() {
    374   return VectorLegalizer(*this).Run();
    375 }
    376