LLVM  8.0.0svn
LegalizeVectorOps.cpp
Go to the documentation of this file.
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/ADT/APInt.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Compiler.h"
45 #include <cassert>
46 #include <cstdint>
47 #include <iterator>
48 #include <utility>
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "legalizevectorops"
53 
54 namespace {
55 
56 class VectorLegalizer {
57  SelectionDAG& DAG;
58  const TargetLowering &TLI;
59  bool Changed = false; // Keep track of whether anything changed
60 
61  /// For nodes that are of legal width, and that have more than one use, this
62  /// map indicates what regularized operand to use. This allows us to avoid
63  /// legalizing the same thing more than once.
65 
66  /// Adds a node to the translation cache.
67  void AddLegalizedOperand(SDValue From, SDValue To) {
68  LegalizedNodes.insert(std::make_pair(From, To));
69  // If someone requests legalization of the new node, return itself.
70  if (From != To)
71  LegalizedNodes.insert(std::make_pair(To, To));
72  }
73 
74  /// Legalizes the given node.
75  SDValue LegalizeOp(SDValue Op);
76 
77  /// Assuming the node is legal, "legalize" the results.
78  SDValue TranslateLegalizeResults(SDValue Op, SDValue Result);
79 
80  /// Implements unrolling a VSETCC.
81  SDValue UnrollVSETCC(SDValue Op);
82 
83  /// Implement expand-based legalization of vector operations.
84  ///
85  /// This is just a high-level routine to dispatch to specific code paths for
86  /// operations to legalize them.
87  SDValue Expand(SDValue Op);
88 
89  /// Implements expansion for FNEG; falls back to UnrollVectorOp if
90  /// FSUB isn't legal.
91  ///
92  /// Implements expansion for UINT_TO_FLOAT; falls back to UnrollVectorOp if
93  /// SINT_TO_FLOAT and SHR on vectors isn't legal.
94  SDValue ExpandUINT_TO_FLOAT(SDValue Op);
95 
96  /// Implement expansion for SIGN_EXTEND_INREG using SRL and SRA.
97  SDValue ExpandSEXTINREG(SDValue Op);
98 
99  /// Implement expansion for ANY_EXTEND_VECTOR_INREG.
100  ///
101  /// Shuffles the low lanes of the operand into place and bitcasts to the proper
102  /// type. The contents of the bits in the extended part of each element are
103  /// undef.
104  SDValue ExpandANY_EXTEND_VECTOR_INREG(SDValue Op);
105 
106  /// Implement expansion for SIGN_EXTEND_VECTOR_INREG.
107  ///
108  /// Shuffles the low lanes of the operand into place, bitcasts to the proper
109  /// type, then shifts left and arithmetic shifts right to introduce a sign
110  /// extension.
111  SDValue ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op);
112 
113  /// Implement expansion for ZERO_EXTEND_VECTOR_INREG.
114  ///
115  /// Shuffles the low lanes of the operand into place and blends zeros into
116  /// the remaining lanes, finally bitcasting to the proper type.
117  SDValue ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op);
118 
119  /// Expand bswap of vectors into a shuffle if legal.
120  SDValue ExpandBSWAP(SDValue Op);
121 
122  /// Implement vselect in terms of XOR, AND, OR when blend is not
123  /// supported by the target.
124  SDValue ExpandVSELECT(SDValue Op);
125  SDValue ExpandSELECT(SDValue Op);
126  SDValue ExpandLoad(SDValue Op);
127  SDValue ExpandStore(SDValue Op);
128  SDValue ExpandFNEG(SDValue Op);
129  SDValue ExpandFSUB(SDValue Op);
130  SDValue ExpandBITREVERSE(SDValue Op);
131  SDValue ExpandCTLZ(SDValue Op);
132  SDValue ExpandCTTZ_ZERO_UNDEF(SDValue Op);
133  SDValue ExpandStrictFPOp(SDValue Op);
134 
135  /// Implements vector promotion.
136  ///
137  /// This is essentially just bitcasting the operands to a different type and
138  /// bitcasting the result back to the original type.
139  SDValue Promote(SDValue Op);
140 
141  /// Implements [SU]INT_TO_FP vector promotion.
142  ///
143  /// This is a [zs]ext of the input operand to a larger integer type.
144  SDValue PromoteINT_TO_FP(SDValue Op);
145 
146  /// Implements FP_TO_[SU]INT vector promotion of the result type.
147  ///
148  /// It is promoted to a larger integer type. The result is then
149  /// truncated back to the original type.
150  SDValue PromoteFP_TO_INT(SDValue Op);
151 
152 public:
153  VectorLegalizer(SelectionDAG& dag) :
154  DAG(dag), TLI(dag.getTargetLoweringInfo()) {}
155 
156  /// Begin legalizer the vector operations in the DAG.
157  bool Run();
158 };
159 
160 } // end anonymous namespace
161 
162 bool VectorLegalizer::Run() {
163  // Before we start legalizing vector nodes, check if there are any vectors.
164  bool HasVectors = false;
165  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
166  E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I) {
167  // Check if the values of the nodes contain vectors. We don't need to check
168  // the operands because we are going to check their values at some point.
169  for (SDNode::value_iterator J = I->value_begin(), E = I->value_end();
170  J != E; ++J)
171  HasVectors |= J->isVector();
172 
173  // If we found a vector node we can start the legalization.
174  if (HasVectors)
175  break;
176  }
177 
178  // If this basic block has no vectors then no need to legalize vectors.
179  if (!HasVectors)
180  return false;
181 
182  // The legalize process is inherently a bottom-up recursive process (users
183  // legalize their uses before themselves). Given infinite stack space, we
184  // could just start legalizing on the root and traverse the whole graph. In
185  // practice however, this causes us to run out of stack space on large basic
186  // blocks. To avoid this problem, compute an ordering of the nodes where each
187  // node is only legalized after all of its operands are legalized.
188  DAG.AssignTopologicalOrder();
189  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
190  E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
191  LegalizeOp(SDValue(&*I, 0));
192 
193  // Finally, it's possible the root changed. Get the new root.
194  SDValue OldRoot = DAG.getRoot();
195  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
196  DAG.setRoot(LegalizedNodes[OldRoot]);
197 
198  LegalizedNodes.clear();
199 
200  // Remove dead nodes now.
201  DAG.RemoveDeadNodes();
202 
203  return Changed;
204 }
205 
206 SDValue VectorLegalizer::TranslateLegalizeResults(SDValue Op, SDValue Result) {
207  // Generic legalization: just pass the operand through.
208  for (unsigned i = 0, e = Op.getNode()->getNumValues(); i != e; ++i)
209  AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
210  return Result.getValue(Op.getResNo());
211 }
212 
213 SDValue VectorLegalizer::LegalizeOp(SDValue Op) {
214  // Note that LegalizeOp may be reentered even from single-use nodes, which
215  // means that we always must cache transformed nodes.
216  DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
217  if (I != LegalizedNodes.end()) return I->second;
218 
219  SDNode* Node = Op.getNode();
220 
221  // Legalize the operands
223  for (const SDValue &Op : Node->op_values())
224  Ops.push_back(LegalizeOp(Op));
225 
226  SDValue Result = SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops),
227  Op.getResNo());
228 
229  bool HasVectorValue = false;
230  if (Op.getOpcode() == ISD::LOAD) {
231  LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
233  if (LD->getMemoryVT().isVector() && ExtType != ISD::NON_EXTLOAD) {
234  LLVM_DEBUG(dbgs() << "\nLegalizing extending vector load: ";
235  Node->dump(&DAG));
236  switch (TLI.getLoadExtAction(LD->getExtensionType(), LD->getValueType(0),
237  LD->getMemoryVT())) {
238  default: llvm_unreachable("This action is not supported yet!");
240  return TranslateLegalizeResults(Op, Result);
242  if (SDValue Lowered = TLI.LowerOperation(Result, DAG)) {
243  if (Lowered == Result)
244  return TranslateLegalizeResults(Op, Lowered);
245  Changed = true;
246  if (Lowered->getNumValues() != Op->getNumValues()) {
247  // This expanded to something other than the load. Assume the
248  // lowering code took care of any chain values, and just handle the
249  // returned value.
250  assert(Result.getValue(1).use_empty() &&
251  "There are still live users of the old chain!");
252  return LegalizeOp(Lowered);
253  }
254  return TranslateLegalizeResults(Op, Lowered);
255  }
258  Changed = true;
259  return LegalizeOp(ExpandLoad(Op));
260  }
261  }
262  } else if (Op.getOpcode() == ISD::STORE) {
263  StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
264  EVT StVT = ST->getMemoryVT();
265  MVT ValVT = ST->getValue().getSimpleValueType();
266  if (StVT.isVector() && ST->isTruncatingStore()) {
267  LLVM_DEBUG(dbgs() << "\nLegalizing truncating vector store: ";
268  Node->dump(&DAG));
269  switch (TLI.getTruncStoreAction(ValVT, StVT)) {
270  default: llvm_unreachable("This action is not supported yet!");
272  return TranslateLegalizeResults(Op, Result);
273  case TargetLowering::Custom: {
274  SDValue Lowered = TLI.LowerOperation(Result, DAG);
275  Changed = Lowered != Result;
276  return TranslateLegalizeResults(Op, Lowered);
277  }
279  Changed = true;
280  return LegalizeOp(ExpandStore(Op));
281  }
282  }
283  } else if (Op.getOpcode() == ISD::MSCATTER || Op.getOpcode() == ISD::MSTORE)
284  HasVectorValue = true;
285 
286  for (SDNode::value_iterator J = Node->value_begin(), E = Node->value_end();
287  J != E;
288  ++J)
289  HasVectorValue |= J->isVector();
290  if (!HasVectorValue)
291  return TranslateLegalizeResults(Op, Result);
292 
294  switch (Op.getOpcode()) {
295  default:
296  return TranslateLegalizeResults(Op, Result);
297  case ISD::STRICT_FADD:
298  case ISD::STRICT_FSUB:
299  case ISD::STRICT_FMUL:
300  case ISD::STRICT_FDIV:
301  case ISD::STRICT_FREM:
302  case ISD::STRICT_FSQRT:
303  case ISD::STRICT_FMA:
304  case ISD::STRICT_FPOW:
305  case ISD::STRICT_FPOWI:
306  case ISD::STRICT_FSIN:
307  case ISD::STRICT_FCOS:
308  case ISD::STRICT_FEXP:
309  case ISD::STRICT_FEXP2:
310  case ISD::STRICT_FLOG:
311  case ISD::STRICT_FLOG10:
312  case ISD::STRICT_FLOG2:
313  case ISD::STRICT_FRINT:
315  // These pseudo-ops get legalized as if they were their non-strict
316  // equivalent. For instance, if ISD::FSQRT is legal then ISD::STRICT_FSQRT
317  // is also legal, but if ISD::FSQRT requires expansion then so does
318  // ISD::STRICT_FSQRT.
319  Action = TLI.getStrictFPOperationAction(Node->getOpcode(),
320  Node->getValueType(0));
321  break;
322  case ISD::ADD:
323  case ISD::SUB:
324  case ISD::MUL:
325  case ISD::SDIV:
326  case ISD::UDIV:
327  case ISD::SREM:
328  case ISD::UREM:
329  case ISD::SDIVREM:
330  case ISD::UDIVREM:
331  case ISD::FADD:
332  case ISD::FSUB:
333  case ISD::FMUL:
334  case ISD::FDIV:
335  case ISD::FREM:
336  case ISD::AND:
337  case ISD::OR:
338  case ISD::XOR:
339  case ISD::SHL:
340  case ISD::SRA:
341  case ISD::SRL:
342  case ISD::ROTL:
343  case ISD::ROTR:
344  case ISD::BSWAP:
345  case ISD::BITREVERSE:
346  case ISD::CTLZ:
347  case ISD::CTTZ:
350  case ISD::CTPOP:
351  case ISD::SELECT:
352  case ISD::VSELECT:
353  case ISD::SELECT_CC:
354  case ISD::SETCC:
355  case ISD::ZERO_EXTEND:
356  case ISD::ANY_EXTEND:
357  case ISD::TRUNCATE:
358  case ISD::SIGN_EXTEND:
359  case ISD::FP_TO_SINT:
360  case ISD::FP_TO_UINT:
361  case ISD::FNEG:
362  case ISD::FABS:
363  case ISD::FMINNUM:
364  case ISD::FMAXNUM:
365  case ISD::FMINNAN:
366  case ISD::FMAXNAN:
367  case ISD::FCOPYSIGN:
368  case ISD::FSQRT:
369  case ISD::FSIN:
370  case ISD::FCOS:
371  case ISD::FPOWI:
372  case ISD::FPOW:
373  case ISD::FLOG:
374  case ISD::FLOG2:
375  case ISD::FLOG10:
376  case ISD::FEXP:
377  case ISD::FEXP2:
378  case ISD::FCEIL:
379  case ISD::FTRUNC:
380  case ISD::FRINT:
381  case ISD::FNEARBYINT:
382  case ISD::FROUND:
383  case ISD::FFLOOR:
384  case ISD::FP_ROUND:
385  case ISD::FP_EXTEND:
386  case ISD::FMA:
391  case ISD::SMIN:
392  case ISD::SMAX:
393  case ISD::UMIN:
394  case ISD::UMAX:
395  case ISD::SMUL_LOHI:
396  case ISD::UMUL_LOHI:
397  case ISD::FCANONICALIZE:
398  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
399  break;
400  case ISD::FP_ROUND_INREG:
401  Action = TLI.getOperationAction(Node->getOpcode(),
402  cast<VTSDNode>(Node->getOperand(1))->getVT());
403  break;
404  case ISD::SINT_TO_FP:
405  case ISD::UINT_TO_FP:
406  Action = TLI.getOperationAction(Node->getOpcode(),
407  Node->getOperand(0).getValueType());
408  break;
409  case ISD::MSCATTER:
410  Action = TLI.getOperationAction(Node->getOpcode(),
411  cast<MaskedScatterSDNode>(Node)->getValue().getValueType());
412  break;
413  case ISD::MSTORE:
414  Action = TLI.getOperationAction(Node->getOpcode(),
415  cast<MaskedStoreSDNode>(Node)->getValue().getValueType());
416  break;
417  }
418 
419  LLVM_DEBUG(dbgs() << "\nLegalizing vector op: "; Node->dump(&DAG));
420 
421  switch (Action) {
422  default: llvm_unreachable("This action is not supported yet!");
424  Result = Promote(Op);
425  Changed = true;
426  break;
428  LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
429  break;
430  case TargetLowering::Custom: {
431  LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
432  if (SDValue Tmp1 = TLI.LowerOperation(Op, DAG)) {
433  LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
434  Result = Tmp1;
435  break;
436  }
437  LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
439  }
441  Result = Expand(Op);
442  }
443 
444  // Make sure that the generated code is itself legal.
445  if (Result != Op) {
446  Result = LegalizeOp(Result);
447  Changed = true;
448  }
449 
450  // Note that LegalizeOp may be reentered even from single-use nodes, which
451  // means that we always must cache transformed nodes.
452  AddLegalizedOperand(Op, Result);
453  return Result;
454 }
455 
456 SDValue VectorLegalizer::Promote(SDValue Op) {
457  // For a few operations there is a specific concept for promotion based on
458  // the operand's type.
459  switch (Op.getOpcode()) {
460  case ISD::SINT_TO_FP:
461  case ISD::UINT_TO_FP:
462  // "Promote" the operation by extending the operand.
463  return PromoteINT_TO_FP(Op);
464  case ISD::FP_TO_UINT:
465  case ISD::FP_TO_SINT:
466  // Promote the operation by extending the operand.
467  return PromoteFP_TO_INT(Op);
468  }
469 
470  // There are currently two cases of vector promotion:
471  // 1) Bitcasting a vector of integers to a different type to a vector of the
472  // same overall length. For example, x86 promotes ISD::AND v2i32 to v1i64.
473  // 2) Extending a vector of floats to a vector of the same number of larger
474  // floats. For example, AArch64 promotes ISD::FADD on v4f16 to v4f32.
475  MVT VT = Op.getSimpleValueType();
476  assert(Op.getNode()->getNumValues() == 1 &&
477  "Can't promote a vector with multiple results!");
478  MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
479  SDLoc dl(Op);
481 
482  for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
483  if (Op.getOperand(j).getValueType().isVector())
484  if (Op.getOperand(j)
485  .getValueType()
487  .isFloatingPoint() &&
488  NVT.isVector() && NVT.getVectorElementType().isFloatingPoint())
489  Operands[j] = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Op.getOperand(j));
490  else
491  Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
492  else
493  Operands[j] = Op.getOperand(j);
494  }
495 
496  Op = DAG.getNode(Op.getOpcode(), dl, NVT, Operands, Op.getNode()->getFlags());
497  if ((VT.isFloatingPoint() && NVT.isFloatingPoint()) ||
499  NVT.isVector() && NVT.getVectorElementType().isFloatingPoint()))
500  return DAG.getNode(ISD::FP_ROUND, dl, VT, Op, DAG.getIntPtrConstant(0, dl));
501  else
502  return DAG.getNode(ISD::BITCAST, dl, VT, Op);
503 }
504 
505 SDValue VectorLegalizer::PromoteINT_TO_FP(SDValue Op) {
506  // INT_TO_FP operations may require the input operand be promoted even
507  // when the type is otherwise legal.
508  MVT VT = Op.getOperand(0).getSimpleValueType();
509  MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
511  "Vectors have different number of elements!");
512 
513  SDLoc dl(Op);
515 
516  unsigned Opc = Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND :
518  for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
519  if (Op.getOperand(j).getValueType().isVector())
520  Operands[j] = DAG.getNode(Opc, dl, NVT, Op.getOperand(j));
521  else
522  Operands[j] = Op.getOperand(j);
523  }
524 
525  return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Operands);
526 }
527 
528 // For FP_TO_INT we promote the result type to a vector type with wider
529 // elements and then truncate the result. This is different from the default
530 // PromoteVector which uses bitcast to promote thus assumning that the
531 // promoted vector type has the same overall size.
532 SDValue VectorLegalizer::PromoteFP_TO_INT(SDValue Op) {
533  MVT VT = Op.getSimpleValueType();
534  MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
536  "Vectors have different number of elements!");
537 
538  unsigned NewOpc = Op->getOpcode();
539  // Change FP_TO_UINT to FP_TO_SINT if possible.
540  // TODO: Should we only do this if FP_TO_UINT itself isn't legal?
541  if (NewOpc == ISD::FP_TO_UINT &&
542  TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
543  NewOpc = ISD::FP_TO_SINT;
544 
545  SDLoc dl(Op);
546  SDValue Promoted = DAG.getNode(NewOpc, dl, NVT, Op.getOperand(0));
547 
548  // Assert that the converted value fits in the original type. If it doesn't
549  // (eg: because the value being converted is too big), then the result of the
550  // original operation was undefined anyway, so the assert is still correct.
551  Promoted = DAG.getNode(Op->getOpcode() == ISD::FP_TO_UINT ? ISD::AssertZext
552  : ISD::AssertSext,
553  dl, NVT, Promoted,
554  DAG.getValueType(VT.getScalarType()));
555  return DAG.getNode(ISD::TRUNCATE, dl, VT, Promoted);
556 }
557 
558 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
559  LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
560 
561  EVT SrcVT = LD->getMemoryVT();
562  EVT SrcEltVT = SrcVT.getScalarType();
563  unsigned NumElem = SrcVT.getVectorNumElements();
564 
565  SDValue NewChain;
566  SDValue Value;
567  if (SrcVT.getVectorNumElements() > 1 && !SrcEltVT.isByteSized()) {
568  SDLoc dl(Op);
569 
571  SmallVector<SDValue, 8> LoadChains;
572 
573  EVT DstEltVT = LD->getValueType(0).getScalarType();
574  SDValue Chain = LD->getChain();
575  SDValue BasePTR = LD->getBasePtr();
577 
578  // When elements in a vector is not byte-addressable, we cannot directly
579  // load each element by advancing pointer, which could only address bytes.
580  // Instead, we load all significant words, mask bits off, and concatenate
581  // them to form each element. Finally, they are extended to destination
582  // scalar type to build the destination vector.
583  EVT WideVT = TLI.getPointerTy(DAG.getDataLayout());
584 
585  assert(WideVT.isRound() &&
586  "Could not handle the sophisticated case when the widest integer is"
587  " not power of 2.");
588  assert(WideVT.bitsGE(SrcEltVT) &&
589  "Type is not legalized?");
590 
591  unsigned WideBytes = WideVT.getStoreSize();
592  unsigned Offset = 0;
593  unsigned RemainingBytes = SrcVT.getStoreSize();
594  SmallVector<SDValue, 8> LoadVals;
595  while (RemainingBytes > 0) {
596  SDValue ScalarLoad;
597  unsigned LoadBytes = WideBytes;
598 
599  if (RemainingBytes >= LoadBytes) {
600  ScalarLoad =
601  DAG.getLoad(WideVT, dl, Chain, BasePTR,
602  LD->getPointerInfo().getWithOffset(Offset),
603  MinAlign(LD->getAlignment(), Offset),
604  LD->getMemOperand()->getFlags(), LD->getAAInfo());
605  } else {
606  EVT LoadVT = WideVT;
607  while (RemainingBytes < LoadBytes) {
608  LoadBytes >>= 1; // Reduce the load size by half.
609  LoadVT = EVT::getIntegerVT(*DAG.getContext(), LoadBytes << 3);
610  }
611  ScalarLoad =
612  DAG.getExtLoad(ISD::EXTLOAD, dl, WideVT, Chain, BasePTR,
613  LD->getPointerInfo().getWithOffset(Offset), LoadVT,
614  MinAlign(LD->getAlignment(), Offset),
615  LD->getMemOperand()->getFlags(), LD->getAAInfo());
616  }
617 
618  RemainingBytes -= LoadBytes;
619  Offset += LoadBytes;
620 
621  BasePTR = DAG.getObjectPtrOffset(dl, BasePTR, LoadBytes);
622 
623  LoadVals.push_back(ScalarLoad.getValue(0));
624  LoadChains.push_back(ScalarLoad.getValue(1));
625  }
626 
627  // Extract bits, pack and extend/trunc them into destination type.
628  unsigned SrcEltBits = SrcEltVT.getSizeInBits();
629  SDValue SrcEltBitMask = DAG.getConstant((1U << SrcEltBits) - 1, dl, WideVT);
630 
631  unsigned BitOffset = 0;
632  unsigned WideIdx = 0;
633  unsigned WideBits = WideVT.getSizeInBits();
634 
635  for (unsigned Idx = 0; Idx != NumElem; ++Idx) {
636  SDValue Lo, Hi, ShAmt;
637 
638  if (BitOffset < WideBits) {
639  ShAmt = DAG.getConstant(
640  BitOffset, dl, TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
641  Lo = DAG.getNode(ISD::SRL, dl, WideVT, LoadVals[WideIdx], ShAmt);
642  Lo = DAG.getNode(ISD::AND, dl, WideVT, Lo, SrcEltBitMask);
643  }
644 
645  BitOffset += SrcEltBits;
646  if (BitOffset >= WideBits) {
647  WideIdx++;
648  BitOffset -= WideBits;
649  if (BitOffset > 0) {
650  ShAmt = DAG.getConstant(
651  SrcEltBits - BitOffset, dl,
652  TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
653  Hi = DAG.getNode(ISD::SHL, dl, WideVT, LoadVals[WideIdx], ShAmt);
654  Hi = DAG.getNode(ISD::AND, dl, WideVT, Hi, SrcEltBitMask);
655  }
656  }
657 
658  if (Hi.getNode())
659  Lo = DAG.getNode(ISD::OR, dl, WideVT, Lo, Hi);
660 
661  switch (ExtType) {
662  default: llvm_unreachable("Unknown extended-load op!");
663  case ISD::EXTLOAD:
664  Lo = DAG.getAnyExtOrTrunc(Lo, dl, DstEltVT);
665  break;
666  case ISD::ZEXTLOAD:
667  Lo = DAG.getZExtOrTrunc(Lo, dl, DstEltVT);
668  break;
669  case ISD::SEXTLOAD:
670  ShAmt =
671  DAG.getConstant(WideBits - SrcEltBits, dl,
672  TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
673  Lo = DAG.getNode(ISD::SHL, dl, WideVT, Lo, ShAmt);
674  Lo = DAG.getNode(ISD::SRA, dl, WideVT, Lo, ShAmt);
675  Lo = DAG.getSExtOrTrunc(Lo, dl, DstEltVT);
676  break;
677  }
678  Vals.push_back(Lo);
679  }
680 
681  NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
682  Value = DAG.getBuildVector(Op.getNode()->getValueType(0), dl, Vals);
683  } else {
684  SDValue Scalarized = TLI.scalarizeVectorLoad(LD, DAG);
685  // Skip past MERGE_VALUE node if known.
686  if (Scalarized->getOpcode() == ISD::MERGE_VALUES) {
687  NewChain = Scalarized.getOperand(1);
688  Value = Scalarized.getOperand(0);
689  } else {
690  NewChain = Scalarized.getValue(1);
691  Value = Scalarized.getValue(0);
692  }
693  }
694 
695  AddLegalizedOperand(Op.getValue(0), Value);
696  AddLegalizedOperand(Op.getValue(1), NewChain);
697 
698  return (Op.getResNo() ? NewChain : Value);
699 }
700 
701 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
702  StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
703  SDValue TF = TLI.scalarizeVectorStore(ST, DAG);
704  AddLegalizedOperand(Op, TF);
705  return TF;
706 }
707 
708 SDValue VectorLegalizer::Expand(SDValue Op) {
709  switch (Op->getOpcode()) {
711  return ExpandSEXTINREG(Op);
713  return ExpandANY_EXTEND_VECTOR_INREG(Op);
715  return ExpandSIGN_EXTEND_VECTOR_INREG(Op);
717  return ExpandZERO_EXTEND_VECTOR_INREG(Op);
718  case ISD::BSWAP:
719  return ExpandBSWAP(Op);
720  case ISD::VSELECT:
721  return ExpandVSELECT(Op);
722  case ISD::SELECT:
723  return ExpandSELECT(Op);
724  case ISD::UINT_TO_FP:
725  return ExpandUINT_TO_FLOAT(Op);
726  case ISD::FNEG:
727  return ExpandFNEG(Op);
728  case ISD::FSUB:
729  return ExpandFSUB(Op);
730  case ISD::SETCC:
731  return UnrollVSETCC(Op);
732  case ISD::BITREVERSE:
733  return ExpandBITREVERSE(Op);
734  case ISD::CTLZ:
736  return ExpandCTLZ(Op);
738  return ExpandCTTZ_ZERO_UNDEF(Op);
739  case ISD::STRICT_FADD:
740  case ISD::STRICT_FSUB:
741  case ISD::STRICT_FMUL:
742  case ISD::STRICT_FDIV:
743  case ISD::STRICT_FREM:
744  case ISD::STRICT_FSQRT:
745  case ISD::STRICT_FMA:
746  case ISD::STRICT_FPOW:
747  case ISD::STRICT_FPOWI:
748  case ISD::STRICT_FSIN:
749  case ISD::STRICT_FCOS:
750  case ISD::STRICT_FEXP:
751  case ISD::STRICT_FEXP2:
752  case ISD::STRICT_FLOG:
753  case ISD::STRICT_FLOG10:
754  case ISD::STRICT_FLOG2:
755  case ISD::STRICT_FRINT:
757  return ExpandStrictFPOp(Op);
758  default:
759  return DAG.UnrollVectorOp(Op.getNode());
760  }
761 }
762 
763 SDValue VectorLegalizer::ExpandSELECT(SDValue Op) {
764  // Lower a select instruction where the condition is a scalar and the
765  // operands are vectors. Lower this select to VSELECT and implement it
766  // using XOR AND OR. The selector bit is broadcasted.
767  EVT VT = Op.getValueType();
768  SDLoc DL(Op);
769 
770  SDValue Mask = Op.getOperand(0);
771  SDValue Op1 = Op.getOperand(1);
772  SDValue Op2 = Op.getOperand(2);
773 
774  assert(VT.isVector() && !Mask.getValueType().isVector()
775  && Op1.getValueType() == Op2.getValueType() && "Invalid type");
776 
777  // If we can't even use the basic vector operations of
778  // AND,OR,XOR, we will have to scalarize the op.
779  // Notice that the operation may be 'promoted' which means that it is
780  // 'bitcasted' to another type which is handled.
781  // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
782  if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
783  TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
784  TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
785  TLI.getOperationAction(ISD::BUILD_VECTOR, VT) == TargetLowering::Expand)
786  return DAG.UnrollVectorOp(Op.getNode());
787 
788  // Generate a mask operand.
790 
791  // What is the size of each element in the vector mask.
792  EVT BitTy = MaskTy.getScalarType();
793 
794  Mask = DAG.getSelect(DL, BitTy, Mask,
795  DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), DL,
796  BitTy),
797  DAG.getConstant(0, DL, BitTy));
798 
799  // Broadcast the mask so that the entire vector is all-one or all zero.
800  Mask = DAG.getSplatBuildVector(MaskTy, DL, Mask);
801 
802  // Bitcast the operands to be the same type as the mask.
803  // This is needed when we select between FP types because
804  // the mask is a vector of integers.
805  Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
806  Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
807 
808  SDValue AllOnes = DAG.getConstant(
809  APInt::getAllOnesValue(BitTy.getSizeInBits()), DL, MaskTy);
810  SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
811 
812  Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
813  Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
814  SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
815  return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
816 }
817 
818 SDValue VectorLegalizer::ExpandSEXTINREG(SDValue Op) {
819  EVT VT = Op.getValueType();
820 
821  // Make sure that the SRA and SHL instructions are available.
822  if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
823  TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
824  return DAG.UnrollVectorOp(Op.getNode());
825 
826  SDLoc DL(Op);
827  EVT OrigTy = cast<VTSDNode>(Op->getOperand(1))->getVT();
828 
829  unsigned BW = VT.getScalarSizeInBits();
830  unsigned OrigBW = OrigTy.getScalarSizeInBits();
831  SDValue ShiftSz = DAG.getConstant(BW - OrigBW, DL, VT);
832 
833  Op = Op.getOperand(0);
834  Op = DAG.getNode(ISD::SHL, DL, VT, Op, ShiftSz);
835  return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
836 }
837 
838 // Generically expand a vector anyext in register to a shuffle of the relevant
839 // lanes into the appropriate locations, with other lanes left undef.
840 SDValue VectorLegalizer::ExpandANY_EXTEND_VECTOR_INREG(SDValue Op) {
841  SDLoc DL(Op);
842  EVT VT = Op.getValueType();
843  int NumElements = VT.getVectorNumElements();
844  SDValue Src = Op.getOperand(0);
845  EVT SrcVT = Src.getValueType();
846  int NumSrcElements = SrcVT.getVectorNumElements();
847 
848  // Build a base mask of undef shuffles.
849  SmallVector<int, 16> ShuffleMask;
850  ShuffleMask.resize(NumSrcElements, -1);
851 
852  // Place the extended lanes into the correct locations.
853  int ExtLaneScale = NumSrcElements / NumElements;
854  int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
855  for (int i = 0; i < NumElements; ++i)
856  ShuffleMask[i * ExtLaneScale + EndianOffset] = i;
857 
858  return DAG.getNode(
859  ISD::BITCAST, DL, VT,
860  DAG.getVectorShuffle(SrcVT, DL, Src, DAG.getUNDEF(SrcVT), ShuffleMask));
861 }
862 
863 SDValue VectorLegalizer::ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op) {
864  SDLoc DL(Op);
865  EVT VT = Op.getValueType();
866  SDValue Src = Op.getOperand(0);
867  EVT SrcVT = Src.getValueType();
868 
869  // First build an any-extend node which can be legalized above when we
870  // recurse through it.
871  Op = DAG.getAnyExtendVectorInReg(Src, DL, VT);
872 
873  // Now we need sign extend. Do this by shifting the elements. Even if these
874  // aren't legal operations, they have a better chance of being legalized
875  // without full scalarization than the sign extension does.
876  unsigned EltWidth = VT.getScalarSizeInBits();
877  unsigned SrcEltWidth = SrcVT.getScalarSizeInBits();
878  SDValue ShiftAmount = DAG.getConstant(EltWidth - SrcEltWidth, DL, VT);
879  return DAG.getNode(ISD::SRA, DL, VT,
880  DAG.getNode(ISD::SHL, DL, VT, Op, ShiftAmount),
881  ShiftAmount);
882 }
883 
884 // Generically expand a vector zext in register to a shuffle of the relevant
885 // lanes into the appropriate locations, a blend of zero into the high bits,
886 // and a bitcast to the wider element type.
887 SDValue VectorLegalizer::ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op) {
888  SDLoc DL(Op);
889  EVT VT = Op.getValueType();
890  int NumElements = VT.getVectorNumElements();
891  SDValue Src = Op.getOperand(0);
892  EVT SrcVT = Src.getValueType();
893  int NumSrcElements = SrcVT.getVectorNumElements();
894 
895  // Build up a zero vector to blend into this one.
896  SDValue Zero = DAG.getConstant(0, DL, SrcVT);
897 
898  // Shuffle the incoming lanes into the correct position, and pull all other
899  // lanes from the zero vector.
900  SmallVector<int, 16> ShuffleMask;
901  ShuffleMask.reserve(NumSrcElements);
902  for (int i = 0; i < NumSrcElements; ++i)
903  ShuffleMask.push_back(i);
904 
905  int ExtLaneScale = NumSrcElements / NumElements;
906  int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
907  for (int i = 0; i < NumElements; ++i)
908  ShuffleMask[i * ExtLaneScale + EndianOffset] = NumSrcElements + i;
909 
910  return DAG.getNode(ISD::BITCAST, DL, VT,
911  DAG.getVectorShuffle(SrcVT, DL, Zero, Src, ShuffleMask));
912 }
913 
914 static void createBSWAPShuffleMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
915  int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
916  for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
917  for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
918  ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
919 }
920 
921 SDValue VectorLegalizer::ExpandBSWAP(SDValue Op) {
922  EVT VT = Op.getValueType();
923 
924  // Generate a byte wise shuffle mask for the BSWAP.
925  SmallVector<int, 16> ShuffleMask;
926  createBSWAPShuffleMask(VT, ShuffleMask);
927  EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
928 
929  // Only emit a shuffle if the mask is legal.
930  if (!TLI.isShuffleMaskLegal(ShuffleMask, ByteVT))
931  return DAG.UnrollVectorOp(Op.getNode());
932 
933  SDLoc DL(Op);
934  Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
935  Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT), ShuffleMask);
936  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
937 }
938 
939 SDValue VectorLegalizer::ExpandBITREVERSE(SDValue Op) {
940  EVT VT = Op.getValueType();
941 
942  // If we have the scalar operation, it's probably cheaper to unroll it.
943  if (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, VT.getScalarType()))
944  return DAG.UnrollVectorOp(Op.getNode());
945 
946  // If the vector element width is a whole number of bytes, test if its legal
947  // to BSWAP shuffle the bytes and then perform the BITREVERSE on the byte
948  // vector. This greatly reduces the number of bit shifts necessary.
949  unsigned ScalarSizeInBits = VT.getScalarSizeInBits();
950  if (ScalarSizeInBits > 8 && (ScalarSizeInBits % 8) == 0) {
951  SmallVector<int, 16> BSWAPMask;
952  createBSWAPShuffleMask(VT, BSWAPMask);
953 
954  EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, BSWAPMask.size());
955  if (TLI.isShuffleMaskLegal(BSWAPMask, ByteVT) &&
956  (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, ByteVT) ||
957  (TLI.isOperationLegalOrCustom(ISD::SHL, ByteVT) &&
958  TLI.isOperationLegalOrCustom(ISD::SRL, ByteVT) &&
959  TLI.isOperationLegalOrCustomOrPromote(ISD::AND, ByteVT) &&
960  TLI.isOperationLegalOrCustomOrPromote(ISD::OR, ByteVT)))) {
961  SDLoc DL(Op);
962  Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
963  Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
964  BSWAPMask);
965  Op = DAG.getNode(ISD::BITREVERSE, DL, ByteVT, Op);
966  return DAG.getNode(ISD::BITCAST, DL, VT, Op);
967  }
968  }
969 
970  // If we have the appropriate vector bit operations, it is better to use them
971  // than unrolling and expanding each component.
972  if (!TLI.isOperationLegalOrCustom(ISD::SHL, VT) ||
973  !TLI.isOperationLegalOrCustom(ISD::SRL, VT) ||
974  !TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
975  !TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT))
976  return DAG.UnrollVectorOp(Op.getNode());
977 
978  // Let LegalizeDAG handle this later.
979  return Op;
980 }
981 
982 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
983  // Implement VSELECT in terms of XOR, AND, OR
984  // on platforms which do not support blend natively.
985  SDLoc DL(Op);
986 
987  SDValue Mask = Op.getOperand(0);
988  SDValue Op1 = Op.getOperand(1);
989  SDValue Op2 = Op.getOperand(2);
990 
991  EVT VT = Mask.getValueType();
992 
993  // If we can't even use the basic vector operations of
994  // AND,OR,XOR, we will have to scalarize the op.
995  // Notice that the operation may be 'promoted' which means that it is
996  // 'bitcasted' to another type which is handled.
997  // This operation also isn't safe with AND, OR, XOR when the boolean
998  // type is 0/1 as we need an all ones vector constant to mask with.
999  // FIXME: Sign extend 1 to all ones if thats legal on the target.
1000  if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
1001  TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
1002  TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
1003  TLI.getBooleanContents(Op1.getValueType()) !=
1005  return DAG.UnrollVectorOp(Op.getNode());
1006 
1007  // If the mask and the type are different sizes, unroll the vector op. This
1008  // can occur when getSetCCResultType returns something that is different in
1009  // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
1010  if (VT.getSizeInBits() != Op1.getValueSizeInBits())
1011  return DAG.UnrollVectorOp(Op.getNode());
1012 
1013  // Bitcast the operands to be the same type as the mask.
1014  // This is needed when we select between FP types because
1015  // the mask is a vector of integers.
1016  Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
1017  Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
1018 
1019  SDValue AllOnes = DAG.getConstant(
1021  SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
1022 
1023  Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
1024  Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
1025  SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
1026  return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
1027 }
1028 
1029 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
1030  EVT VT = Op.getOperand(0).getValueType();
1031  SDLoc DL(Op);
1032 
1033  // Make sure that the SINT_TO_FP and SRL instructions are available.
1034  if (TLI.getOperationAction(ISD::SINT_TO_FP, VT) == TargetLowering::Expand ||
1035  TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Expand)
1036  return DAG.UnrollVectorOp(Op.getNode());
1037 
1038  unsigned BW = VT.getScalarSizeInBits();
1039  assert((BW == 64 || BW == 32) &&
1040  "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
1041 
1042  SDValue HalfWord = DAG.getConstant(BW / 2, DL, VT);
1043 
1044  // Constants to clear the upper part of the word.
1045  // Notice that we can also use SHL+SHR, but using a constant is slightly
1046  // faster on x86.
1047  uint64_t HWMask = (BW == 64) ? 0x00000000FFFFFFFF : 0x0000FFFF;
1048  SDValue HalfWordMask = DAG.getConstant(HWMask, DL, VT);
1049 
1050  // Two to the power of half-word-size.
1051  SDValue TWOHW = DAG.getConstantFP(1ULL << (BW / 2), DL, Op.getValueType());
1052 
1053  // Clear upper part of LO, lower HI
1054  SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
1055  SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
1056 
1057  // Convert hi and lo to floats
1058  // Convert the hi part back to the upper values
1059  // TODO: Can any fast-math-flags be set on these nodes?
1060  SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
1061  fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
1062  SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
1063 
1064  // Add the two halves
1065  return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
1066 }
1067 
1068 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
1069  if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
1070  SDLoc DL(Op);
1071  SDValue Zero = DAG.getConstantFP(-0.0, DL, Op.getValueType());
1072  // TODO: If FNEG had fast-math-flags, they'd get propagated to this FSUB.
1073  return DAG.getNode(ISD::FSUB, DL, Op.getValueType(),
1074  Zero, Op.getOperand(0));
1075  }
1076  return DAG.UnrollVectorOp(Op.getNode());
1077 }
1078 
1079 SDValue VectorLegalizer::ExpandFSUB(SDValue Op) {
1080  // For floating-point values, (a-b) is the same as a+(-b). If FNEG is legal,
1081  // we can defer this to operation legalization where it will be lowered as
1082  // a+(-b).
1083  EVT VT = Op.getValueType();
1084  if (TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
1085  TLI.isOperationLegalOrCustom(ISD::FADD, VT))
1086  return Op; // Defer to LegalizeDAG
1087 
1088  return DAG.UnrollVectorOp(Op.getNode());
1089 }
1090 
1091 SDValue VectorLegalizer::ExpandCTLZ(SDValue Op) {
1092  EVT VT = Op.getValueType();
1093  unsigned NumBitsPerElt = VT.getScalarSizeInBits();
1094 
1095  // If the non-ZERO_UNDEF version is supported we can use that instead.
1096  if (Op.getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
1097  TLI.isOperationLegalOrCustom(ISD::CTLZ, VT)) {
1098  SDLoc DL(Op);
1099  return DAG.getNode(ISD::CTLZ, DL, Op.getValueType(), Op.getOperand(0));
1100  }
1101 
1102  // If CTPOP is available we can lower with a CTPOP based method:
1103  // u16 ctlz(u16 x) {
1104  // x |= (x >> 1);
1105  // x |= (x >> 2);
1106  // x |= (x >> 4);
1107  // x |= (x >> 8);
1108  // return ctpop(~x);
1109  // }
1110  // Ref: "Hacker's Delight" by Henry Warren
1111  if (isPowerOf2_32(NumBitsPerElt) &&
1112  TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
1113  TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
1114  TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT) &&
1115  TLI.isOperationLegalOrCustomOrPromote(ISD::XOR, VT)) {
1116  SDLoc DL(Op);
1117  SDValue Res = Op.getOperand(0);
1118  EVT ShiftTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
1119 
1120  for (unsigned i = 1; i != NumBitsPerElt; i *= 2)
1121  Res = DAG.getNode(
1122  ISD::OR, DL, VT, Res,
1123  DAG.getNode(ISD::SRL, DL, VT, Res, DAG.getConstant(i, DL, ShiftTy)));
1124 
1125  Res = DAG.getNOT(DL, Res, VT);
1126  return DAG.getNode(ISD::CTPOP, DL, VT, Res);
1127  }
1128 
1129  // Otherwise go ahead and unroll.
1130  return DAG.UnrollVectorOp(Op.getNode());
1131 }
1132 
1133 SDValue VectorLegalizer::ExpandCTTZ_ZERO_UNDEF(SDValue Op) {
1134  // If the non-ZERO_UNDEF version is supported we can use that instead.
1135  if (TLI.isOperationLegalOrCustom(ISD::CTTZ, Op.getValueType())) {
1136  SDLoc DL(Op);
1137  return DAG.getNode(ISD::CTTZ, DL, Op.getValueType(), Op.getOperand(0));
1138  }
1139 
1140  // Otherwise go ahead and unroll.
1141  return DAG.UnrollVectorOp(Op.getNode());
1142 }
1143 
1144 SDValue VectorLegalizer::ExpandStrictFPOp(SDValue Op) {
1145  EVT VT = Op.getValueType();
1146  EVT EltVT = VT.getVectorElementType();
1147  unsigned NumElems = VT.getVectorNumElements();
1148  unsigned NumOpers = Op.getNumOperands();
1149  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1150  EVT ValueVTs[] = {EltVT, MVT::Other};
1151  SDValue Chain = Op.getOperand(0);
1152  SDLoc dl(Op);
1153 
1154  SmallVector<SDValue, 32> OpValues;
1155  SmallVector<SDValue, 32> OpChains;
1156  for (unsigned i = 0; i < NumElems; ++i) {
1158  SDValue Idx = DAG.getConstant(i, dl,
1159  TLI.getVectorIdxTy(DAG.getDataLayout()));
1160 
1161  // The Chain is the first operand.
1162  Opers.push_back(Chain);
1163 
1164  // Now process the remaining operands.
1165  for (unsigned j = 1; j < NumOpers; ++j) {
1166  SDValue Oper = Op.getOperand(j);
1167  EVT OperVT = Oper.getValueType();
1168 
1169  if (OperVT.isVector())
1170  Oper = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1171  EltVT, Oper, Idx);
1172 
1173  Opers.push_back(Oper);
1174  }
1175 
1176  SDValue ScalarOp = DAG.getNode(Op->getOpcode(), dl, ValueVTs, Opers);
1177 
1178  OpValues.push_back(ScalarOp.getValue(0));
1179  OpChains.push_back(ScalarOp.getValue(1));
1180  }
1181 
1182  SDValue Result = DAG.getBuildVector(VT, dl, OpValues);
1183  SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OpChains);
1184 
1185  AddLegalizedOperand(Op.getValue(0), Result);
1186  AddLegalizedOperand(Op.getValue(1), NewChain);
1187 
1188  return NewChain;
1189 }
1190 
1191 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
1192  EVT VT = Op.getValueType();
1193  unsigned NumElems = VT.getVectorNumElements();
1194  EVT EltVT = VT.getVectorElementType();
1195  SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
1196  EVT TmpEltVT = LHS.getValueType().getVectorElementType();
1197  SDLoc dl(Op);
1198  SmallVector<SDValue, 8> Ops(NumElems);
1199  for (unsigned i = 0; i < NumElems; ++i) {
1200  SDValue LHSElem = DAG.getNode(
1201  ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
1202  DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1203  SDValue RHSElem = DAG.getNode(
1204  ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
1205  DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1206  Ops[i] = DAG.getNode(ISD::SETCC, dl,
1207  TLI.getSetCCResultType(DAG.getDataLayout(),
1208  *DAG.getContext(), TmpEltVT),
1209  LHSElem, RHSElem, CC);
1210  Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
1211  DAG.getConstant(APInt::getAllOnesValue
1212  (EltVT.getSizeInBits()), dl, EltVT),
1213  DAG.getConstant(0, dl, EltVT));
1214  }
1215  return DAG.getBuildVector(VT, dl, Ops);
1216 }
1217 
1219  return VectorLegalizer(*this).Run();
1220 }
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
Definition: ISDOpcodes.h:541
X = FP_ROUND(Y, TRUNC) - Rounding &#39;Y&#39; from a larger floating point type down to the precision of the ...
Definition: ISDOpcodes.h:508
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
Definition: ISDOpcodes.h:562
virtual MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
EVT getValueType() const
Return the ValueType of the referenced return value.
Constrained versions of libm-equivalent floating point intrinsics.
Definition: ISDOpcodes.h:273
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:562
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition: ValueTypes.h:260
#define LLVM_FALLTHROUGH
Definition: Compiler.h:86
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition: ISDOpcodes.h:489
bool isVector() const
Return true if this is a vector value type.
const SDValue & getBasePtr() const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
const SDValue & getValue() const
bool LegalizeVectors()
This transforms the SelectionDAG into a SelectionDAG that only uses vector math operations supported ...
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
unsigned getVectorNumElements() const
const SDValue & getChain() const
unsigned getAlignment() const
Constrained versions of the binary floating point operators.
Definition: ISDOpcodes.h:266
SIGN_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register sign-extension of the low ...
Definition: ISDOpcodes.h:480
[US]{MIN/MAX} - Binary minimum or maximum or signed or unsigned integers.
Definition: ISDOpcodes.h:360
const SDNodeFlags getFlags() const
SDNode * getNode() const
get the SDNode which holds the desired result
void reserve(size_type N)
Definition: SmallVector.h:376
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition: ValueTypes.h:212
MachineMemOperand * getMemOperand() const
Return a MachineMemOperand object describing the memory reference performed by operation.
unsigned getValueSizeInBits() const
Returns the size of the value in bits.
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition: ISDOpcodes.h:407
bool isTruncatingStore() const
Return true if the op does a truncation before store.
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition: ISDOpcodes.h:210
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition: ValueTypes.h:136
Shift and rotation operations.
Definition: ISDOpcodes.h:382
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
unsigned getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition: ValueTypes.h:304
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
This file implements a class to represent arbitrary precision integral constant values and operations...
unsigned getScalarSizeInBits() const
Definition: ValueTypes.h:298
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:292
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition: ISDOpcodes.h:450
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition: ISDOpcodes.h:401
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:201
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition: ISDOpcodes.h:467
MVT getVectorElementType() const
bool use_empty() const
Return true if there are no nodes using value ResNo of Node.
This class is used to represent ISD::STORE nodes.
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition: ISDOpcodes.h:494
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a vector with the specified, possibly variable...
Definition: ISDOpcodes.h:303
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
Definition: MathExtras.h:610
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
bool bitsGE(EVT VT) const
Return true if this has no less bits than VT.
Definition: ValueTypes.h:235
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:429
Machine Value Type.
Simple binary floating point operators.
Definition: ISDOpcodes.h:260
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition: ValueTypes.h:273
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
iterator_range< value_op_iterator > op_values() const
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition: ValueTypes.h:217
const SDValue & getOperand(unsigned Num) const
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
Definition: ISDOpcodes.h:894
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition: ISDOpcodes.h:57
Bit counting operators with an undefined result for zero inputs.
Definition: ISDOpcodes.h:388
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition: ISDOpcodes.h:526
Extended Value Type.
Definition: ValueTypes.h:34
size_t size() const
Definition: SmallVector.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LegalizeAction
This enum indicates whether operations are valid for a target, and if not, what action should be used...
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
TokenFactor - This node takes multiple tokens as input and produces a single token result...
Definition: ISDOpcodes.h:50
const TargetLowering & getTargetLoweringInfo() const
Definition: SelectionDAG.h:401
Iterator for intrusive lists based on ilist_node.
BlockVerifier::State From
Returns platform specific canonical encoding of a floating point number.
Definition: ISDOpcodes.h:295
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition: ISDOpcodes.h:315
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition: ValueTypes.h:265
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:222
X = FP_ROUND_INREG(Y, VT) - This operator takes an FP register, and rounds it to a floating point val...
Definition: ISDOpcodes.h:523
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition: ValueTypes.h:96
Byte Swap and Counting operators.
Definition: ISDOpcodes.h:385
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
MachinePointerInfo getWithOffset(int64_t O) const
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT...
Definition: ValueTypes.h:73
EVT getMemoryVT() const
Return the type of the in-memory value.
Select(COND, TRUEVAL, FALSEVAL).
Definition: ISDOpcodes.h:392
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition: ISDOpcodes.h:440
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition: ISDOpcodes.h:443
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition: ISDOpcodes.h:288
FMINNAN/FMAXNAN - Behave identically to FMINNUM/FMAXNUM, except that when a single input is NaN...
Definition: ISDOpcodes.h:565
bool isVector() const
Return true if this is a vector value type.
Definition: ValueTypes.h:151
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:363
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition: ISDOpcodes.h:206
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition: ISDOpcodes.h:458
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
Definition: ISDOpcodes.h:574
#define I(x, y, z)
Definition: MD5.cpp:58
Flags getFlags() const
Return the raw flags of the source value,.
unsigned getOpcode() const
SDValue getValue(unsigned R) const
const MachinePointerInfo & getPointerInfo() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
FMA - Perform a * b + c with no intermediate rounding step.
Definition: ISDOpcodes.h:278
unsigned getResNo() const
get the index which selects a specific result in the SDNode
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:81
SetCC operator - This evaluates to a true value iff the condition is true.
Definition: ISDOpcodes.h:415
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition: ISDOpcodes.h:198
unsigned getNumOperands() const
Conversion operators.
Definition: ISDOpcodes.h:437
const SDValue & getOperand(unsigned i) const
TRUNCATE - Completely drop the high bits.
Definition: ISDOpcodes.h:446
#define LLVM_DEBUG(X)
Definition: Debug.h:123
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
Perform various unary floating-point operations inspired by libm.
Definition: ISDOpcodes.h:554
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition: ValueTypes.h:64
static void createBSWAPShuffleMask(EVT VT, SmallVectorImpl< int > &ShuffleMask)
This file describes how to lower LLVM code to machine code.
void resize(size_type N)
Definition: SmallVector.h:351
This class is used to represent ISD::LOAD nodes.