LLVM  10.0.0svn
LegalizeDAG.cpp
Go to the documentation of this file.
1 //===- LegalizeDAG.cpp - Implement SelectionDAG::Legalize -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the SelectionDAG::Legalize method.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/Debug.h"
47 #include <algorithm>
48 #include <cassert>
49 #include <cstdint>
50 #include <tuple>
51 #include <utility>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "legalizedag"
56 
57 namespace {
58 
59 /// Keeps track of state when getting the sign of a floating-point value as an
60 /// integer.
61 struct FloatSignAsInt {
62  EVT FloatVT;
63  SDValue Chain;
64  SDValue FloatPtr;
65  SDValue IntPtr;
66  MachinePointerInfo IntPointerInfo;
67  MachinePointerInfo FloatPointerInfo;
68  SDValue IntValue;
69  APInt SignMask;
70  uint8_t SignBit;
71 };
72 
73 //===----------------------------------------------------------------------===//
74 /// This takes an arbitrary SelectionDAG as input and
75 /// hacks on it until the target machine can handle it. This involves
76 /// eliminating value sizes the machine cannot handle (promoting small sizes to
77 /// large sizes or splitting up large values into small values) as well as
78 /// eliminating operations the machine cannot handle.
79 ///
80 /// This code also does a small amount of optimization and recognition of idioms
81 /// as part of its processing. For example, if a target does not support a
82 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
83 /// will attempt merge setcc and brc instructions into brcc's.
84 class SelectionDAGLegalize {
85  const TargetMachine &TM;
86  const TargetLowering &TLI;
87  SelectionDAG &DAG;
88 
89  /// The set of nodes which have already been legalized. We hold a
90  /// reference to it in order to update as necessary on node deletion.
91  SmallPtrSetImpl<SDNode *> &LegalizedNodes;
92 
93  /// A set of all the nodes updated during legalization.
94  SmallSetVector<SDNode *, 16> *UpdatedNodes;
95 
96  EVT getSetCCResultType(EVT VT) const {
97  return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
98  }
99 
100  // Libcall insertion helpers.
101 
102 public:
103  SelectionDAGLegalize(SelectionDAG &DAG,
104  SmallPtrSetImpl<SDNode *> &LegalizedNodes,
105  SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
106  : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
107  LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {}
108 
109  /// Legalizes the given operation.
110  void LegalizeOp(SDNode *Node);
111 
112 private:
113  SDValue OptimizeFloatStore(StoreSDNode *ST);
114 
115  void LegalizeLoadOps(SDNode *Node);
116  void LegalizeStoreOps(SDNode *Node);
117 
118  /// Some targets cannot handle a variable
119  /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
120  /// is necessary to spill the vector being inserted into to memory, perform
121  /// the insert there, and then read the result back.
122  SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
123  const SDLoc &dl);
124  SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx,
125  const SDLoc &dl);
126 
127  /// Return a vector shuffle operation which
128  /// performs the same shuffe in terms of order or result bytes, but on a type
129  /// whose vector element type is narrower than the original shuffle type.
130  /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
131  SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl,
132  SDValue N1, SDValue N2,
133  ArrayRef<int> Mask) const;
134 
135  bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
136  bool &NeedInvert, const SDLoc &dl);
137 
138  SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
139 
140  std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
141  SDNode *Node, bool isSigned);
142  SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
143  RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
144  RTLIB::Libcall Call_F128,
145  RTLIB::Libcall Call_PPCF128);
146  SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
147  RTLIB::Libcall Call_I8,
148  RTLIB::Libcall Call_I16,
149  RTLIB::Libcall Call_I32,
150  RTLIB::Libcall Call_I64,
151  RTLIB::Libcall Call_I128);
152  SDValue ExpandArgFPLibCall(SDNode *Node,
153  RTLIB::Libcall Call_F32, RTLIB::Libcall Call_F64,
154  RTLIB::Libcall Call_F80, RTLIB::Libcall Call_F128,
155  RTLIB::Libcall Call_PPCF128);
156  void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
157  void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
158 
159  SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
160  const SDLoc &dl);
161  SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
162  const SDLoc &dl, SDValue ChainIn);
163  SDValue ExpandBUILD_VECTOR(SDNode *Node);
164  SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
165  void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
166  SmallVectorImpl<SDValue> &Results);
167  void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL,
168  SDValue Value) const;
169  SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL,
170  SDValue NewIntValue) const;
171  SDValue ExpandFCOPYSIGN(SDNode *Node) const;
172  SDValue ExpandFABS(SDNode *Node) const;
173  SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue Op0, EVT DestVT,
174  const SDLoc &dl);
175  SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
176  const SDLoc &dl);
177  SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
178  const SDLoc &dl);
179 
180  SDValue ExpandBITREVERSE(SDValue Op, const SDLoc &dl);
181  SDValue ExpandBSWAP(SDValue Op, const SDLoc &dl);
182 
183  SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
184  SDValue ExpandInsertToVectorThroughStack(SDValue Op);
185  SDValue ExpandVectorBuildThroughStack(SDNode* Node);
186 
187  SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
188  SDValue ExpandConstant(ConstantSDNode *CP);
189 
190  // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall
191  bool ExpandNode(SDNode *Node);
192  void ConvertNodeToLibcall(SDNode *Node);
193  void PromoteNode(SDNode *Node);
194 
195 public:
196  // Node replacement helpers
197 
198  void ReplacedNode(SDNode *N) {
199  LegalizedNodes.erase(N);
200  if (UpdatedNodes)
201  UpdatedNodes->insert(N);
202  }
203 
204  void ReplaceNode(SDNode *Old, SDNode *New) {
205  LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
206  dbgs() << " with: "; New->dump(&DAG));
207 
208  assert(Old->getNumValues() == New->getNumValues() &&
209  "Replacing one node with another that produces a different number "
210  "of values!");
211  DAG.ReplaceAllUsesWith(Old, New);
212  if (UpdatedNodes)
213  UpdatedNodes->insert(New);
214  ReplacedNode(Old);
215  }
216 
217  void ReplaceNode(SDValue Old, SDValue New) {
218  LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
219  dbgs() << " with: "; New->dump(&DAG));
220 
221  DAG.ReplaceAllUsesWith(Old, New);
222  if (UpdatedNodes)
223  UpdatedNodes->insert(New.getNode());
224  ReplacedNode(Old.getNode());
225  }
226 
227  void ReplaceNode(SDNode *Old, const SDValue *New) {
228  LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
229 
230  DAG.ReplaceAllUsesWith(Old, New);
231  for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
232  LLVM_DEBUG(dbgs() << (i == 0 ? " with: " : " and: ");
233  New[i]->dump(&DAG));
234  if (UpdatedNodes)
235  UpdatedNodes->insert(New[i].getNode());
236  }
237  ReplacedNode(Old);
238  }
239 
240  void ReplaceNodeWithValue(SDValue Old, SDValue New) {
241  LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
242  dbgs() << " with: "; New->dump(&DAG));
243 
244  DAG.ReplaceAllUsesOfValueWith(Old, New);
245  if (UpdatedNodes)
246  UpdatedNodes->insert(New.getNode());
247  ReplacedNode(Old.getNode());
248  }
249 };
250 
251 } // end anonymous namespace
252 
253 /// Return a vector shuffle operation which
254 /// performs the same shuffle in terms of order or result bytes, but on a type
255 /// whose vector element type is narrower than the original shuffle type.
256 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
257 SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType(
258  EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
259  ArrayRef<int> Mask) const {
260  unsigned NumMaskElts = VT.getVectorNumElements();
261  unsigned NumDestElts = NVT.getVectorNumElements();
262  unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
263 
264  assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
265 
266  if (NumEltsGrowth == 1)
267  return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask);
268 
269  SmallVector<int, 8> NewMask;
270  for (unsigned i = 0; i != NumMaskElts; ++i) {
271  int Idx = Mask[i];
272  for (unsigned j = 0; j != NumEltsGrowth; ++j) {
273  if (Idx < 0)
274  NewMask.push_back(-1);
275  else
276  NewMask.push_back(Idx * NumEltsGrowth + j);
277  }
278  }
279  assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
280  assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
281  return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask);
282 }
283 
284 /// Expands the ConstantFP node to an integer constant or
285 /// a load from the constant pool.
286 SDValue
287 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
288  bool Extend = false;
289  SDLoc dl(CFP);
290 
291  // If a FP immediate is precise when represented as a float and if the
292  // target can do an extending load from float to double, we put it into
293  // the constant pool as a float, even if it's is statically typed as a
294  // double. This shrinks FP constants and canonicalizes them for targets where
295  // an FP extending load is the same cost as a normal load (such as on the x87
296  // fp stack or PPC FP unit).
297  EVT VT = CFP->getValueType(0);
298  ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
299  if (!UseCP) {
300  assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
301  return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl,
302  (VT == MVT::f64) ? MVT::i64 : MVT::i32);
303  }
304 
305  APFloat APF = CFP->getValueAPF();
306  EVT OrigVT = VT;
307  EVT SVT = VT;
308 
309  // We don't want to shrink SNaNs. Converting the SNaN back to its real type
310  // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ).
311  if (!APF.isSignaling()) {
312  while (SVT != MVT::f32 && SVT != MVT::f16) {
313  SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
315  // Only do this if the target has a native EXTLOAD instruction from
316  // smaller type.
317  TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) &&
318  TLI.ShouldShrinkFPConstant(OrigVT)) {
319  Type *SType = SVT.getTypeForEVT(*DAG.getContext());
320  LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
321  VT = SVT;
322  Extend = true;
323  }
324  }
325  }
326 
327  SDValue CPIdx =
328  DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout()));
329  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
330  if (Extend) {
331  SDValue Result = DAG.getExtLoad(
332  ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx,
333  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT,
334  Alignment);
335  return Result;
336  }
337  SDValue Result = DAG.getLoad(
338  OrigVT, dl, DAG.getEntryNode(), CPIdx,
339  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
340  return Result;
341 }
342 
343 /// Expands the Constant node to a load from the constant pool.
344 SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) {
345  SDLoc dl(CP);
346  EVT VT = CP->getValueType(0);
347  SDValue CPIdx = DAG.getConstantPool(CP->getConstantIntValue(),
348  TLI.getPointerTy(DAG.getDataLayout()));
349  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
350  SDValue Result = DAG.getLoad(
351  VT, dl, DAG.getEntryNode(), CPIdx,
352  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
353  return Result;
354 }
355 
356 /// Some target cannot handle a variable insertion index for the
357 /// INSERT_VECTOR_ELT instruction. In this case, it
358 /// is necessary to spill the vector being inserted into to memory, perform
359 /// the insert there, and then read the result back.
360 SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec,
361  SDValue Val,
362  SDValue Idx,
363  const SDLoc &dl) {
364  SDValue Tmp1 = Vec;
365  SDValue Tmp2 = Val;
366  SDValue Tmp3 = Idx;
367 
368  // If the target doesn't support this, we have to spill the input vector
369  // to a temporary stack slot, update the element, then reload it. This is
370  // badness. We could also load the value into a vector register (either
371  // with a "move to register" or "extload into register" instruction, then
372  // permute it into place, if the idx is a constant and if the idx is
373  // supported by the target.
374  EVT VT = Tmp1.getValueType();
375  EVT EltVT = VT.getVectorElementType();
376  SDValue StackPtr = DAG.CreateStackTemporary(VT);
377 
378  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
379 
380  // Store the vector.
381  SDValue Ch = DAG.getStore(
382  DAG.getEntryNode(), dl, Tmp1, StackPtr,
383  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
384 
385  SDValue StackPtr2 = TLI.getVectorElementPointer(DAG, StackPtr, VT, Tmp3);
386 
387  // Store the scalar value.
388  Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT);
389  // Load the updated vector.
390  return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack(
391  DAG.getMachineFunction(), SPFI));
392 }
393 
394 SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
395  SDValue Idx,
396  const SDLoc &dl) {
397  if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
398  // SCALAR_TO_VECTOR requires that the type of the value being inserted
399  // match the element type of the vector being created, except for
400  // integers in which case the inserted value can be over width.
401  EVT EltVT = Vec.getValueType().getVectorElementType();
402  if (Val.getValueType() == EltVT ||
403  (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
404  SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
405  Vec.getValueType(), Val);
406 
407  unsigned NumElts = Vec.getValueType().getVectorNumElements();
408  // We generate a shuffle of InVec and ScVec, so the shuffle mask
409  // should be 0,1,2,3,4,5... with the appropriate element replaced with
410  // elt 0 of the RHS.
411  SmallVector<int, 8> ShufOps;
412  for (unsigned i = 0; i != NumElts; ++i)
413  ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
414 
415  return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps);
416  }
417  }
418  return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
419 }
420 
421 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
422  LLVM_DEBUG(dbgs() << "Optimizing float store operations\n");
423  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
424  // FIXME: We shouldn't do this for TargetConstantFP's.
425  // FIXME: move this to the DAG Combiner! Note that we can't regress due
426  // to phase ordering between legalized code and the dag combiner. This
427  // probably means that we need to integrate dag combiner and legalizer
428  // together.
429  // We generally can't do this one for long doubles.
430  SDValue Chain = ST->getChain();
431  SDValue Ptr = ST->getBasePtr();
432  unsigned Alignment = ST->getAlignment();
433  MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
434  AAMDNodes AAInfo = ST->getAAInfo();
435  SDLoc dl(ST);
436  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
437  if (CFP->getValueType(0) == MVT::f32 &&
438  TLI.isTypeLegal(MVT::i32)) {
439  SDValue Con = DAG.getConstant(CFP->getValueAPF().
440  bitcastToAPInt().zextOrTrunc(32),
441  SDLoc(CFP), MVT::i32);
442  return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(), Alignment,
443  MMOFlags, AAInfo);
444  }
445 
446  if (CFP->getValueType(0) == MVT::f64) {
447  // If this target supports 64-bit registers, do a single 64-bit store.
448  if (TLI.isTypeLegal(MVT::i64)) {
449  SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
450  zextOrTrunc(64), SDLoc(CFP), MVT::i64);
451  return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
452  Alignment, MMOFlags, AAInfo);
453  }
454 
455  if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
456  // Otherwise, if the target supports 32-bit registers, use 2 32-bit
457  // stores. If the target supports neither 32- nor 64-bits, this
458  // xform is certainly not worth it.
459  const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
460  SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
461  SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
462  if (DAG.getDataLayout().isBigEndian())
463  std::swap(Lo, Hi);
464 
465  Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), Alignment,
466  MMOFlags, AAInfo);
467  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
468  DAG.getConstant(4, dl, Ptr.getValueType()));
469  Hi = DAG.getStore(Chain, dl, Hi, Ptr,
470  ST->getPointerInfo().getWithOffset(4),
471  MinAlign(Alignment, 4U), MMOFlags, AAInfo);
472 
473  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
474  }
475  }
476  }
477  return SDValue(nullptr, 0);
478 }
479 
480 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
481  StoreSDNode *ST = cast<StoreSDNode>(Node);
482  SDValue Chain = ST->getChain();
483  SDValue Ptr = ST->getBasePtr();
484  SDLoc dl(Node);
485 
486  unsigned Alignment = ST->getAlignment();
487  MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
488  AAMDNodes AAInfo = ST->getAAInfo();
489 
490  if (!ST->isTruncatingStore()) {
491  LLVM_DEBUG(dbgs() << "Legalizing store operation\n");
492  if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
493  ReplaceNode(ST, OptStore);
494  return;
495  }
496 
497  SDValue Value = ST->getValue();
498  MVT VT = Value.getSimpleValueType();
499  switch (TLI.getOperationAction(ISD::STORE, VT)) {
500  default: llvm_unreachable("This action is not supported yet!");
501  case TargetLowering::Legal: {
502  // If this is an unaligned store and the target doesn't support it,
503  // expand it.
504  EVT MemVT = ST->getMemoryVT();
505  const DataLayout &DL = DAG.getDataLayout();
506  if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
507  *ST->getMemOperand())) {
508  LLVM_DEBUG(dbgs() << "Expanding unsupported unaligned store\n");
509  SDValue Result = TLI.expandUnalignedStore(ST, DAG);
510  ReplaceNode(SDValue(ST, 0), Result);
511  } else
512  LLVM_DEBUG(dbgs() << "Legal store\n");
513  break;
514  }
515  case TargetLowering::Custom: {
516  LLVM_DEBUG(dbgs() << "Trying custom lowering\n");
517  SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
518  if (Res && Res != SDValue(Node, 0))
519  ReplaceNode(SDValue(Node, 0), Res);
520  return;
521  }
523  MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
524  assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
525  "Can only promote stores to same size type");
526  Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
527  SDValue Result =
528  DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
529  Alignment, MMOFlags, AAInfo);
530  ReplaceNode(SDValue(Node, 0), Result);
531  break;
532  }
533  }
534  return;
535  }
536 
537  LLVM_DEBUG(dbgs() << "Legalizing truncating store operations\n");
538  SDValue Value = ST->getValue();
539  EVT StVT = ST->getMemoryVT();
540  unsigned StWidth = StVT.getSizeInBits();
541  auto &DL = DAG.getDataLayout();
542 
543  if (StWidth != StVT.getStoreSizeInBits()) {
544  // Promote to a byte-sized store with upper bits zero if not
545  // storing an integral number of bytes. For example, promote
546  // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
547  EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
548  StVT.getStoreSizeInBits());
549  Value = DAG.getZeroExtendInReg(Value, dl, StVT);
550  SDValue Result =
551  DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT,
552  Alignment, MMOFlags, AAInfo);
553  ReplaceNode(SDValue(Node, 0), Result);
554  } else if (StWidth & (StWidth - 1)) {
555  // If not storing a power-of-2 number of bits, expand as two stores.
556  assert(!StVT.isVector() && "Unsupported truncstore!");
557  unsigned LogStWidth = Log2_32(StWidth);
558  assert(LogStWidth < 32);
559  unsigned RoundWidth = 1 << LogStWidth;
560  assert(RoundWidth < StWidth);
561  unsigned ExtraWidth = StWidth - RoundWidth;
562  assert(ExtraWidth < RoundWidth);
563  assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
564  "Store size not an integral number of bytes!");
565  EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
566  EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
567  SDValue Lo, Hi;
568  unsigned IncrementSize;
569 
570  if (DL.isLittleEndian()) {
571  // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
572  // Store the bottom RoundWidth bits.
573  Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
574  RoundVT, Alignment, MMOFlags, AAInfo);
575 
576  // Store the remaining ExtraWidth bits.
577  IncrementSize = RoundWidth / 8;
578  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
579  DAG.getConstant(IncrementSize, dl,
580  Ptr.getValueType()));
581  Hi = DAG.getNode(
582  ISD::SRL, dl, Value.getValueType(), Value,
583  DAG.getConstant(RoundWidth, dl,
584  TLI.getShiftAmountTy(Value.getValueType(), DL)));
585  Hi = DAG.getTruncStore(
586  Chain, dl, Hi, Ptr,
587  ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT,
588  MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo);
589  } else {
590  // Big endian - avoid unaligned stores.
591  // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
592  // Store the top RoundWidth bits.
593  Hi = DAG.getNode(
594  ISD::SRL, dl, Value.getValueType(), Value,
595  DAG.getConstant(ExtraWidth, dl,
596  TLI.getShiftAmountTy(Value.getValueType(), DL)));
597  Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(),
598  RoundVT, Alignment, MMOFlags, AAInfo);
599 
600  // Store the remaining ExtraWidth bits.
601  IncrementSize = RoundWidth / 8;
602  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
603  DAG.getConstant(IncrementSize, dl,
604  Ptr.getValueType()));
605  Lo = DAG.getTruncStore(
606  Chain, dl, Value, Ptr,
607  ST->getPointerInfo().getWithOffset(IncrementSize), ExtraVT,
608  MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo);
609  }
610 
611  // The order of the stores doesn't matter.
612  SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
613  ReplaceNode(SDValue(Node, 0), Result);
614  } else {
615  switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
616  default: llvm_unreachable("This action is not supported yet!");
617  case TargetLowering::Legal: {
618  EVT MemVT = ST->getMemoryVT();
619  // If this is an unaligned store and the target doesn't support it,
620  // expand it.
621  if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
622  *ST->getMemOperand())) {
623  SDValue Result = TLI.expandUnalignedStore(ST, DAG);
624  ReplaceNode(SDValue(ST, 0), Result);
625  }
626  break;
627  }
628  case TargetLowering::Custom: {
629  SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
630  if (Res && Res != SDValue(Node, 0))
631  ReplaceNode(SDValue(Node, 0), Res);
632  return;
633  }
635  assert(!StVT.isVector() &&
636  "Vector Stores are handled in LegalizeVectorOps");
637 
638  SDValue Result;
639 
640  // TRUNCSTORE:i16 i32 -> STORE i16
641  if (TLI.isTypeLegal(StVT)) {
642  Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
643  Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
644  Alignment, MMOFlags, AAInfo);
645  } else {
646  // The in-memory type isn't legal. Truncate to the type it would promote
647  // to, and then do a truncstore.
648  Value = DAG.getNode(ISD::TRUNCATE, dl,
649  TLI.getTypeToTransformTo(*DAG.getContext(), StVT),
650  Value);
651  Result = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
652  StVT, Alignment, MMOFlags, AAInfo);
653  }
654 
655  ReplaceNode(SDValue(Node, 0), Result);
656  break;
657  }
658  }
659 }
660 
661 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
662  LoadSDNode *LD = cast<LoadSDNode>(Node);
663  SDValue Chain = LD->getChain(); // The chain.
664  SDValue Ptr = LD->getBasePtr(); // The base pointer.
665  SDValue Value; // The value returned by the load op.
666  SDLoc dl(Node);
667 
669  if (ExtType == ISD::NON_EXTLOAD) {
670  LLVM_DEBUG(dbgs() << "Legalizing non-extending load operation\n");
671  MVT VT = Node->getSimpleValueType(0);
672  SDValue RVal = SDValue(Node, 0);
673  SDValue RChain = SDValue(Node, 1);
674 
675  switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
676  default: llvm_unreachable("This action is not supported yet!");
677  case TargetLowering::Legal: {
678  EVT MemVT = LD->getMemoryVT();
679  const DataLayout &DL = DAG.getDataLayout();
680  // If this is an unaligned load and the target doesn't support it,
681  // expand it.
682  if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
683  *LD->getMemOperand())) {
684  std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG);
685  }
686  break;
687  }
689  if (SDValue Res = TLI.LowerOperation(RVal, DAG)) {
690  RVal = Res;
691  RChain = Res.getValue(1);
692  }
693  break;
694 
696  MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
697  assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
698  "Can only promote loads to same size type");
699 
700  SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
701  RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
702  RChain = Res.getValue(1);
703  break;
704  }
705  }
706  if (RChain.getNode() != Node) {
707  assert(RVal.getNode() != Node && "Load must be completely replaced");
708  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
709  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
710  if (UpdatedNodes) {
711  UpdatedNodes->insert(RVal.getNode());
712  UpdatedNodes->insert(RChain.getNode());
713  }
714  ReplacedNode(Node);
715  }
716  return;
717  }
718 
719  LLVM_DEBUG(dbgs() << "Legalizing extending load operation\n");
720  EVT SrcVT = LD->getMemoryVT();
721  unsigned SrcWidth = SrcVT.getSizeInBits();
722  unsigned Alignment = LD->getAlignment();
723  MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
724  AAMDNodes AAInfo = LD->getAAInfo();
725 
726  if (SrcWidth != SrcVT.getStoreSizeInBits() &&
727  // Some targets pretend to have an i1 loading operation, and actually
728  // load an i8. This trick is correct for ZEXTLOAD because the top 7
729  // bits are guaranteed to be zero; it helps the optimizers understand
730  // that these bits are zero. It is also useful for EXTLOAD, since it
731  // tells the optimizers that those bits are undefined. It would be
732  // nice to have an effective generic way of getting these benefits...
733  // Until such a way is found, don't insist on promoting i1 here.
734  (SrcVT != MVT::i1 ||
735  TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) ==
737  // Promote to a byte-sized load if not loading an integral number of
738  // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
739  unsigned NewWidth = SrcVT.getStoreSizeInBits();
740  EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
741  SDValue Ch;
742 
743  // The extra bits are guaranteed to be zero, since we stored them that
744  // way. A zext load from NVT thus automatically gives zext from SrcVT.
745 
746  ISD::LoadExtType NewExtType =
748 
749  SDValue Result =
750  DAG.getExtLoad(NewExtType, dl, Node->getValueType(0), Chain, Ptr,
751  LD->getPointerInfo(), NVT, Alignment, MMOFlags, AAInfo);
752 
753  Ch = Result.getValue(1); // The chain.
754 
755  if (ExtType == ISD::SEXTLOAD)
756  // Having the top bits zero doesn't help when sign extending.
757  Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
758  Result.getValueType(),
759  Result, DAG.getValueType(SrcVT));
760  else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
761  // All the top bits are guaranteed to be zero - inform the optimizers.
762  Result = DAG.getNode(ISD::AssertZext, dl,
763  Result.getValueType(), Result,
764  DAG.getValueType(SrcVT));
765 
766  Value = Result;
767  Chain = Ch;
768  } else if (SrcWidth & (SrcWidth - 1)) {
769  // If not loading a power-of-2 number of bits, expand as two loads.
770  assert(!SrcVT.isVector() && "Unsupported extload!");
771  unsigned LogSrcWidth = Log2_32(SrcWidth);
772  assert(LogSrcWidth < 32);
773  unsigned RoundWidth = 1 << LogSrcWidth;
774  assert(RoundWidth < SrcWidth);
775  unsigned ExtraWidth = SrcWidth - RoundWidth;
776  assert(ExtraWidth < RoundWidth);
777  assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
778  "Load size not an integral number of bytes!");
779  EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
780  EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
781  SDValue Lo, Hi, Ch;
782  unsigned IncrementSize;
783  auto &DL = DAG.getDataLayout();
784 
785  if (DL.isLittleEndian()) {
786  // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
787  // Load the bottom RoundWidth bits.
788  Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
789  LD->getPointerInfo(), RoundVT, Alignment, MMOFlags,
790  AAInfo);
791 
792  // Load the remaining ExtraWidth bits.
793  IncrementSize = RoundWidth / 8;
794  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
795  DAG.getConstant(IncrementSize, dl,
796  Ptr.getValueType()));
797  Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
798  LD->getPointerInfo().getWithOffset(IncrementSize),
799  ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags,
800  AAInfo);
801 
802  // Build a factor node to remember that this load is independent of
803  // the other one.
804  Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
805  Hi.getValue(1));
806 
807  // Move the top bits to the right place.
808  Hi = DAG.getNode(
809  ISD::SHL, dl, Hi.getValueType(), Hi,
810  DAG.getConstant(RoundWidth, dl,
811  TLI.getShiftAmountTy(Hi.getValueType(), DL)));
812 
813  // Join the hi and lo parts.
814  Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
815  } else {
816  // Big endian - avoid unaligned loads.
817  // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
818  // Load the top RoundWidth bits.
819  Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
820  LD->getPointerInfo(), RoundVT, Alignment, MMOFlags,
821  AAInfo);
822 
823  // Load the remaining ExtraWidth bits.
824  IncrementSize = RoundWidth / 8;
825  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
826  DAG.getConstant(IncrementSize, dl,
827  Ptr.getValueType()));
828  Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
829  LD->getPointerInfo().getWithOffset(IncrementSize),
830  ExtraVT, MinAlign(Alignment, IncrementSize), MMOFlags,
831  AAInfo);
832 
833  // Build a factor node to remember that this load is independent of
834  // the other one.
835  Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
836  Hi.getValue(1));
837 
838  // Move the top bits to the right place.
839  Hi = DAG.getNode(
840  ISD::SHL, dl, Hi.getValueType(), Hi,
841  DAG.getConstant(ExtraWidth, dl,
842  TLI.getShiftAmountTy(Hi.getValueType(), DL)));
843 
844  // Join the hi and lo parts.
845  Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
846  }
847 
848  Chain = Ch;
849  } else {
850  bool isCustom = false;
851  switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0),
852  SrcVT.getSimpleVT())) {
853  default: llvm_unreachable("This action is not supported yet!");
855  isCustom = true;
858  Value = SDValue(Node, 0);
859  Chain = SDValue(Node, 1);
860 
861  if (isCustom) {
862  if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
863  Value = Res;
864  Chain = Res.getValue(1);
865  }
866  } else {
867  // If this is an unaligned load and the target doesn't support it,
868  // expand it.
869  EVT MemVT = LD->getMemoryVT();
870  const DataLayout &DL = DAG.getDataLayout();
871  if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
872  *LD->getMemOperand())) {
873  std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG);
874  }
875  }
876  break;
877 
878  case TargetLowering::Expand: {
879  EVT DestVT = Node->getValueType(0);
880  if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) {
881  // If the source type is not legal, see if there is a legal extload to
882  // an intermediate type that we can then extend further.
883  EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT());
884  if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
885  TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) {
886  // If we are loading a legal type, this is a non-extload followed by a
887  // full extend.
888  ISD::LoadExtType MidExtType =
889  (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
890 
891  SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
892  SrcVT, LD->getMemOperand());
893  unsigned ExtendOp =
895  Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
896  Chain = Load.getValue(1);
897  break;
898  }
899 
900  // Handle the special case of fp16 extloads. EXTLOAD doesn't have the
901  // normal undefined upper bits behavior to allow using an in-reg extend
902  // with the illegal FP type, so load as an integer and do the
903  // from-integer conversion.
904  if (SrcVT.getScalarType() == MVT::f16) {
905  EVT ISrcVT = SrcVT.changeTypeToInteger();
906  EVT IDestVT = DestVT.changeTypeToInteger();
907  EVT ILoadVT = TLI.getRegisterType(IDestVT.getSimpleVT());
908 
909  SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, ILoadVT, Chain,
910  Ptr, ISrcVT, LD->getMemOperand());
911  Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result);
912  Chain = Result.getValue(1);
913  break;
914  }
915  }
916 
917  assert(!SrcVT.isVector() &&
918  "Vector Loads are handled in LegalizeVectorOps");
919 
920  // FIXME: This does not work for vectors on most targets. Sign-
921  // and zero-extend operations are currently folded into extending
922  // loads, whether they are legal or not, and then we end up here
923  // without any support for legalizing them.
924  assert(ExtType != ISD::EXTLOAD &&
925  "EXTLOAD should always be supported!");
926  // Turn the unsupported load into an EXTLOAD followed by an
927  // explicit zero/sign extend inreg.
928  SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
929  Node->getValueType(0),
930  Chain, Ptr, SrcVT,
931  LD->getMemOperand());
932  SDValue ValRes;
933  if (ExtType == ISD::SEXTLOAD)
934  ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
935  Result.getValueType(),
936  Result, DAG.getValueType(SrcVT));
937  else
938  ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
939  Value = ValRes;
940  Chain = Result.getValue(1);
941  break;
942  }
943  }
944  }
945 
946  // Since loads produce two values, make sure to remember that we legalized
947  // both of them.
948  if (Chain.getNode() != Node) {
949  assert(Value.getNode() != Node && "Load must be completely replaced");
950  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
951  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
952  if (UpdatedNodes) {
953  UpdatedNodes->insert(Value.getNode());
954  UpdatedNodes->insert(Chain.getNode());
955  }
956  ReplacedNode(Node);
957  }
958 }
959 
960 /// Return a legal replacement for the given operation, with all legal operands.
961 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
962  LLVM_DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
963 
964  // Allow illegal target nodes and illegal registers.
965  if (Node->getOpcode() == ISD::TargetConstant ||
966  Node->getOpcode() == ISD::Register)
967  return;
968 
969 #ifndef NDEBUG
970  for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
971  assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
973  "Unexpected illegal type!");
974 
975  for (const SDValue &Op : Node->op_values())
976  assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) ==
978  Op.getOpcode() == ISD::TargetConstant ||
979  Op.getOpcode() == ISD::Register) &&
980  "Unexpected illegal type!");
981 #endif
982 
983  // Figure out the correct action; the way to query this varies by opcode
985  bool SimpleFinishLegalizing = true;
986  switch (Node->getOpcode()) {
989  case ISD::INTRINSIC_VOID:
990  case ISD::STACKSAVE:
991  Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
992  break;
994  Action = TLI.getOperationAction(Node->getOpcode(),
995  Node->getValueType(0));
996  break;
997  case ISD::VAARG:
998  Action = TLI.getOperationAction(Node->getOpcode(),
999  Node->getValueType(0));
1000  if (Action != TargetLowering::Promote)
1001  Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
1002  break;
1003  case ISD::FP_TO_FP16:
1004  case ISD::SINT_TO_FP:
1005  case ISD::UINT_TO_FP:
1007  case ISD::LROUND:
1008  case ISD::LLROUND:
1009  case ISD::LRINT:
1010  case ISD::LLRINT:
1011  Action = TLI.getOperationAction(Node->getOpcode(),
1012  Node->getOperand(0).getValueType());
1013  break;
1014  case ISD::SIGN_EXTEND_INREG: {
1015  EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1016  Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1017  break;
1018  }
1019  case ISD::ATOMIC_STORE:
1020  Action = TLI.getOperationAction(Node->getOpcode(),
1021  Node->getOperand(2).getValueType());
1022  break;
1023  case ISD::SELECT_CC:
1024  case ISD::SETCC:
1025  case ISD::BR_CC: {
1026  unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
1027  Node->getOpcode() == ISD::SETCC ? 2 : 1;
1028  unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
1029  MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1030  ISD::CondCode CCCode =
1031  cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
1032  Action = TLI.getCondCodeAction(CCCode, OpVT);
1033  if (Action == TargetLowering::Legal) {
1034  if (Node->getOpcode() == ISD::SELECT_CC)
1035  Action = TLI.getOperationAction(Node->getOpcode(),
1036  Node->getValueType(0));
1037  else
1038  Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1039  }
1040  break;
1041  }
1042  case ISD::LOAD:
1043  case ISD::STORE:
1044  // FIXME: Model these properly. LOAD and STORE are complicated, and
1045  // STORE expects the unlegalized operand in some cases.
1046  SimpleFinishLegalizing = false;
1047  break;
1048  case ISD::CALLSEQ_START:
1049  case ISD::CALLSEQ_END:
1050  // FIXME: This shouldn't be necessary. These nodes have special properties
1051  // dealing with the recursive nature of legalization. Removing this
1052  // special case should be done as part of making LegalizeDAG non-recursive.
1053  SimpleFinishLegalizing = false;
1054  break;
1055  case ISD::EXTRACT_ELEMENT:
1056  case ISD::FLT_ROUNDS_:
1057  case ISD::MERGE_VALUES:
1058  case ISD::EH_RETURN:
1060  case ISD::EH_DWARF_CFA:
1061  case ISD::EH_SJLJ_SETJMP:
1062  case ISD::EH_SJLJ_LONGJMP:
1064  // These operations lie about being legal: when they claim to be legal,
1065  // they should actually be expanded.
1066  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1067  if (Action == TargetLowering::Legal)
1068  Action = TargetLowering::Expand;
1069  break;
1070  case ISD::INIT_TRAMPOLINE:
1072  case ISD::FRAMEADDR:
1073  case ISD::RETURNADDR:
1074  case ISD::ADDROFRETURNADDR:
1075  case ISD::SPONENTRY:
1076  // These operations lie about being legal: when they claim to be legal,
1077  // they should actually be custom-lowered.
1078  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1079  if (Action == TargetLowering::Legal)
1080  Action = TargetLowering::Custom;
1081  break;
1082  case ISD::READCYCLECOUNTER:
1083  // READCYCLECOUNTER returns an i64, even if type legalization might have
1084  // expanded that to several smaller types.
1085  Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64);
1086  break;
1087  case ISD::READ_REGISTER:
1088  case ISD::WRITE_REGISTER:
1089  // Named register is legal in the DAG, but blocked by register name
1090  // selection if not implemented by target (to chose the correct register)
1091  // They'll be converted to Copy(To/From)Reg.
1092  Action = TargetLowering::Legal;
1093  break;
1094  case ISD::DEBUGTRAP:
1095  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1096  if (Action == TargetLowering::Expand) {
1097  // replace ISD::DEBUGTRAP with ISD::TRAP
1098  SDValue NewVal;
1099  NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1100  Node->getOperand(0));
1101  ReplaceNode(Node, NewVal.getNode());
1102  LegalizeOp(NewVal.getNode());
1103  return;
1104  }
1105  break;
1106  case ISD::STRICT_LRINT:
1107  case ISD::STRICT_LLRINT:
1108  case ISD::STRICT_LROUND:
1109  case ISD::STRICT_LLROUND:
1110  // These pseudo-ops are the same as the other STRICT_ ops except
1111  // they are registered with setOperationAction() using the input type
1112  // instead of the output type.
1113  Action = TLI.getStrictFPOperationAction(Node->getOpcode(),
1114  Node->getOperand(1).getValueType());
1115  break;
1116  case ISD::SADDSAT:
1117  case ISD::UADDSAT:
1118  case ISD::SSUBSAT:
1119  case ISD::USUBSAT: {
1120  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1121  break;
1122  }
1123  case ISD::SMULFIX:
1124  case ISD::SMULFIXSAT:
1125  case ISD::UMULFIX:
1126  case ISD::UMULFIXSAT: {
1127  unsigned Scale = Node->getConstantOperandVal(2);
1128  Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
1129  Node->getValueType(0), Scale);
1130  break;
1131  }
1132  case ISD::MSCATTER:
1133  Action = TLI.getOperationAction(Node->getOpcode(),
1134  cast<MaskedScatterSDNode>(Node)->getValue().getValueType());
1135  break;
1136  case ISD::MSTORE:
1137  Action = TLI.getOperationAction(Node->getOpcode(),
1138  cast<MaskedStoreSDNode>(Node)->getValue().getValueType());
1139  break;
1140  case ISD::VECREDUCE_FADD:
1141  case ISD::VECREDUCE_FMUL:
1142  case ISD::VECREDUCE_ADD:
1143  case ISD::VECREDUCE_MUL:
1144  case ISD::VECREDUCE_AND:
1145  case ISD::VECREDUCE_OR:
1146  case ISD::VECREDUCE_XOR:
1147  case ISD::VECREDUCE_SMAX:
1148  case ISD::VECREDUCE_SMIN:
1149  case ISD::VECREDUCE_UMAX:
1150  case ISD::VECREDUCE_UMIN:
1151  case ISD::VECREDUCE_FMAX:
1152  case ISD::VECREDUCE_FMIN:
1153  Action = TLI.getOperationAction(
1154  Node->getOpcode(), Node->getOperand(0).getValueType());
1155  break;
1156  default:
1157  if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1158  Action = TargetLowering::Legal;
1159  } else {
1160  Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1161  }
1162  break;
1163  }
1164 
1165  if (SimpleFinishLegalizing) {
1166  SDNode *NewNode = Node;
1167  switch (Node->getOpcode()) {
1168  default: break;
1169  case ISD::SHL:
1170  case ISD::SRL:
1171  case ISD::SRA:
1172  case ISD::ROTL:
1173  case ISD::ROTR: {
1174  // Legalizing shifts/rotates requires adjusting the shift amount
1175  // to the appropriate width.
1176  SDValue Op0 = Node->getOperand(0);
1177  SDValue Op1 = Node->getOperand(1);
1178  if (!Op1.getValueType().isVector()) {
1179  SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1);
1180  // The getShiftAmountOperand() may create a new operand node or
1181  // return the existing one. If new operand is created we need
1182  // to update the parent node.
1183  // Do not try to legalize SAO here! It will be automatically legalized
1184  // in the next round.
1185  if (SAO != Op1)
1186  NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO);
1187  }
1188  }
1189  break;
1190  case ISD::FSHL:
1191  case ISD::FSHR:
1192  case ISD::SRL_PARTS:
1193  case ISD::SRA_PARTS:
1194  case ISD::SHL_PARTS: {
1195  // Legalizing shifts/rotates requires adjusting the shift amount
1196  // to the appropriate width.
1197  SDValue Op0 = Node->getOperand(0);
1198  SDValue Op1 = Node->getOperand(1);
1199  SDValue Op2 = Node->getOperand(2);
1200  if (!Op2.getValueType().isVector()) {
1201  SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2);
1202  // The getShiftAmountOperand() may create a new operand node or
1203  // return the existing one. If new operand is created we need
1204  // to update the parent node.
1205  if (SAO != Op2)
1206  NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO);
1207  }
1208  break;
1209  }
1210  }
1211 
1212  if (NewNode != Node) {
1213  ReplaceNode(Node, NewNode);
1214  Node = NewNode;
1215  }
1216  switch (Action) {
1217  case TargetLowering::Legal:
1218  LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
1219  return;
1221  LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
1222  // FIXME: The handling for custom lowering with multiple results is
1223  // a complete mess.
1224  if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
1225  if (!(Res.getNode() != Node || Res.getResNo() != 0))
1226  return;
1227 
1228  if (Node->getNumValues() == 1) {
1229  LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1230  // We can just directly replace this node with the lowered value.
1231  ReplaceNode(SDValue(Node, 0), Res);
1232  return;
1233  }
1234 
1235  SmallVector<SDValue, 8> ResultVals;
1236  for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1237  ResultVals.push_back(Res.getValue(i));
1238  LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1239  ReplaceNode(Node, ResultVals.data());
1240  return;
1241  }
1242  LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
1245  if (ExpandNode(Node))
1246  return;
1249  ConvertNodeToLibcall(Node);
1250  return;
1252  PromoteNode(Node);
1253  return;
1254  }
1255  }
1256 
1257  switch (Node->getOpcode()) {
1258  default:
1259 #ifndef NDEBUG
1260  dbgs() << "NODE: ";
1261  Node->dump( &DAG);
1262  dbgs() << "\n";
1263 #endif
1264  llvm_unreachable("Do not know how to legalize this operator!");
1265 
1266  case ISD::CALLSEQ_START:
1267  case ISD::CALLSEQ_END:
1268  break;
1269  case ISD::LOAD:
1270  return LegalizeLoadOps(Node);
1271  case ISD::STORE:
1272  return LegalizeStoreOps(Node);
1273  }
1274 }
1275 
1276 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1277  SDValue Vec = Op.getOperand(0);
1278  SDValue Idx = Op.getOperand(1);
1279  SDLoc dl(Op);
1280 
1281  // Before we generate a new store to a temporary stack slot, see if there is
1282  // already one that we can use. There often is because when we scalarize
1283  // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1284  // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1285  // the vector. If all are expanded here, we don't want one store per vector
1286  // element.
1287 
1288  // Caches for hasPredecessorHelper
1291  Visited.insert(Op.getNode());
1292  Worklist.push_back(Idx.getNode());
1293  SDValue StackPtr, Ch;
1294  for (SDNode::use_iterator UI = Vec.getNode()->use_begin(),
1295  UE = Vec.getNode()->use_end(); UI != UE; ++UI) {
1296  SDNode *User = *UI;
1297  if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1298  if (ST->isIndexed() || ST->isTruncatingStore() ||
1299  ST->getValue() != Vec)
1300  continue;
1301 
1302  // Make sure that nothing else could have stored into the destination of
1303  // this store.
1304  if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1305  continue;
1306 
1307  // If the index is dependent on the store we will introduce a cycle when
1308  // creating the load (the load uses the index, and by replacing the chain
1309  // we will make the index dependent on the load). Also, the store might be
1310  // dependent on the extractelement and introduce a cycle when creating
1311  // the load.
1312  if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) ||
1313  ST->hasPredecessor(Op.getNode()))
1314  continue;
1315 
1316  StackPtr = ST->getBasePtr();
1317  Ch = SDValue(ST, 0);
1318  break;
1319  }
1320  }
1321 
1322  EVT VecVT = Vec.getValueType();
1323 
1324  if (!Ch.getNode()) {
1325  // Store the value to a temporary stack slot, then LOAD the returned part.
1326  StackPtr = DAG.CreateStackTemporary(VecVT);
1327  Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1328  MachinePointerInfo());
1329  }
1330 
1331  StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1332 
1333  SDValue NewLoad;
1334 
1335  if (Op.getValueType().isVector())
1336  NewLoad =
1337  DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo());
1338  else
1339  NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1341  VecVT.getVectorElementType());
1342 
1343  // Replace the chain going out of the store, by the one out of the load.
1344  DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
1345 
1346  // We introduced a cycle though, so update the loads operands, making sure
1347  // to use the original store's chain as an incoming chain.
1348  SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(),
1349  NewLoad->op_end());
1350  NewLoadOperands[0] = Ch;
1351  NewLoad =
1352  SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
1353  return NewLoad;
1354 }
1355 
1356 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1357  assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1358 
1359  SDValue Vec = Op.getOperand(0);
1360  SDValue Part = Op.getOperand(1);
1361  SDValue Idx = Op.getOperand(2);
1362  SDLoc dl(Op);
1363 
1364  // Store the value to a temporary stack slot, then LOAD the returned part.
1365  EVT VecVT = Vec.getValueType();
1366  SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
1367  int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1368  MachinePointerInfo PtrInfo =
1369  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1370 
1371  // First store the whole vector.
1372  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo);
1373 
1374  // Then store the inserted part.
1375  SDValue SubStackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1376 
1377  // Store the subvector.
1378  Ch = DAG.getStore(Ch, dl, Part, SubStackPtr, MachinePointerInfo());
1379 
1380  // Finally, load the updated vector.
1381  return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo);
1382 }
1383 
1384 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1385  // We can't handle this case efficiently. Allocate a sufficiently
1386  // aligned object on the stack, store each element into it, then load
1387  // the result as a vector.
1388  // Create the stack frame object.
1389  EVT VT = Node->getValueType(0);
1390  EVT EltVT = VT.getVectorElementType();
1391  SDLoc dl(Node);
1392  SDValue FIPtr = DAG.CreateStackTemporary(VT);
1393  int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1394  MachinePointerInfo PtrInfo =
1395  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1396 
1397  // Emit a store of each element to the stack slot.
1398  SmallVector<SDValue, 8> Stores;
1399  unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1400  assert(TypeByteSize > 0 && "Vector element type too small for stack store!");
1401  // Store (in the right endianness) the elements to memory.
1402  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1403  // Ignore undef elements.
1404  if (Node->getOperand(i).isUndef()) continue;
1405 
1406  unsigned Offset = TypeByteSize*i;
1407 
1408  SDValue Idx = DAG.getConstant(Offset, dl, FIPtr.getValueType());
1409  Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1410 
1411  // If the destination vector element type is narrower than the source
1412  // element type, only store the bits necessary.
1413  if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1414  Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1415  Node->getOperand(i), Idx,
1416  PtrInfo.getWithOffset(Offset), EltVT));
1417  } else
1418  Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
1419  Idx, PtrInfo.getWithOffset(Offset)));
1420  }
1421 
1422  SDValue StoreChain;
1423  if (!Stores.empty()) // Not all undef elements?
1424  StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1425  else
1426  StoreChain = DAG.getEntryNode();
1427 
1428  // Result is a load from the stack slot.
1429  return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo);
1430 }
1431 
1432 /// Bitcast a floating-point value to an integer value. Only bitcast the part
1433 /// containing the sign bit if the target has no integer value capable of
1434 /// holding all bits of the floating-point value.
1435 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State,
1436  const SDLoc &DL,
1437  SDValue Value) const {
1438  EVT FloatVT = Value.getValueType();
1439  unsigned NumBits = FloatVT.getSizeInBits();
1440  State.FloatVT = FloatVT;
1441  EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
1442  // Convert to an integer of the same size.
1443  if (TLI.isTypeLegal(IVT)) {
1444  State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value);
1445  State.SignMask = APInt::getSignMask(NumBits);
1446  State.SignBit = NumBits - 1;
1447  return;
1448  }
1449 
1450  auto &DataLayout = DAG.getDataLayout();
1451  // Store the float to memory, then load the sign part out as an integer.
1452  MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8);
1453  // First create a temporary that is aligned for both the load and store.
1454  SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1455  int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1456  // Then store the float to it.
1457  State.FloatPtr = StackPtr;
1458  MachineFunction &MF = DAG.getMachineFunction();
1459  State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI);
1460  State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr,
1461  State.FloatPointerInfo);
1462 
1463  SDValue IntPtr;
1464  if (DataLayout.isBigEndian()) {
1465  assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1466  // Load out a legal integer with the same sign bit as the float.
1467  IntPtr = StackPtr;
1468  State.IntPointerInfo = State.FloatPointerInfo;
1469  } else {
1470  // Advance the pointer so that the loaded byte will contain the sign bit.
1471  unsigned ByteOffset = (FloatVT.getSizeInBits() / 8) - 1;
1472  IntPtr = DAG.getNode(ISD::ADD, DL, StackPtr.getValueType(), StackPtr,
1473  DAG.getConstant(ByteOffset, DL, StackPtr.getValueType()));
1474  State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI,
1475  ByteOffset);
1476  }
1477 
1478  State.IntPtr = IntPtr;
1479  State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr,
1480  State.IntPointerInfo, MVT::i8);
1481  State.SignMask = APInt::getOneBitSet(LoadTy.getSizeInBits(), 7);
1482  State.SignBit = 7;
1483 }
1484 
1485 /// Replace the integer value produced by getSignAsIntValue() with a new value
1486 /// and cast the result back to a floating-point type.
1487 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State,
1488  const SDLoc &DL,
1489  SDValue NewIntValue) const {
1490  if (!State.Chain)
1491  return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue);
1492 
1493  // Override the part containing the sign bit in the value stored on the stack.
1494  SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr,
1495  State.IntPointerInfo, MVT::i8);
1496  return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr,
1497  State.FloatPointerInfo);
1498 }
1499 
1500 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const {
1501  SDLoc DL(Node);
1502  SDValue Mag = Node->getOperand(0);
1503  SDValue Sign = Node->getOperand(1);
1504 
1505  // Get sign bit into an integer value.
1506  FloatSignAsInt SignAsInt;
1507  getSignAsIntValue(SignAsInt, DL, Sign);
1508 
1509  EVT IntVT = SignAsInt.IntValue.getValueType();
1510  SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1511  SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue,
1512  SignMask);
1513 
1514  // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X)
1515  EVT FloatVT = Mag.getValueType();
1516  if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) &&
1517  TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) {
1518  SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag);
1519  SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue);
1520  SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit,
1521  DAG.getConstant(0, DL, IntVT), ISD::SETNE);
1522  return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue);
1523  }
1524 
1525  // Transform Mag value to integer, and clear the sign bit.
1526  FloatSignAsInt MagAsInt;
1527  getSignAsIntValue(MagAsInt, DL, Mag);
1528  EVT MagVT = MagAsInt.IntValue.getValueType();
1529  SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT);
1530  SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue,
1531  ClearSignMask);
1532 
1533  // Get the signbit at the right position for MagAsInt.
1534  int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit;
1535  EVT ShiftVT = IntVT;
1536  if (SignBit.getValueSizeInBits() < ClearedSign.getValueSizeInBits()) {
1537  SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit);
1538  ShiftVT = MagVT;
1539  }
1540  if (ShiftAmount > 0) {
1541  SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT);
1542  SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst);
1543  } else if (ShiftAmount < 0) {
1544  SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT);
1545  SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst);
1546  }
1547  if (SignBit.getValueSizeInBits() > ClearedSign.getValueSizeInBits()) {
1548  SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit);
1549  }
1550 
1551  // Store the part with the modified sign and convert back to float.
1552  SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit);
1553  return modifySignAsInt(MagAsInt, DL, CopiedSign);
1554 }
1555 
1556 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const {
1557  SDLoc DL(Node);
1558  SDValue Value = Node->getOperand(0);
1559 
1560  // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal.
1561  EVT FloatVT = Value.getValueType();
1562  if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) {
1563  SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT);
1564  return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero);
1565  }
1566 
1567  // Transform value to integer, clear the sign bit and transform back.
1568  FloatSignAsInt ValueAsInt;
1569  getSignAsIntValue(ValueAsInt, DL, Value);
1570  EVT IntVT = ValueAsInt.IntValue.getValueType();
1571  SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT);
1572  SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue,
1573  ClearSignMask);
1574  return modifySignAsInt(ValueAsInt, DL, ClearedSign);
1575 }
1576 
1577 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1579  unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1580  assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1581  " not tell us which reg is the stack pointer!");
1582  SDLoc dl(Node);
1583  EVT VT = Node->getValueType(0);
1584  SDValue Tmp1 = SDValue(Node, 0);
1585  SDValue Tmp2 = SDValue(Node, 1);
1586  SDValue Tmp3 = Node->getOperand(2);
1587  SDValue Chain = Tmp1.getOperand(0);
1588 
1589  // Chain the dynamic stack allocation so that it doesn't modify the stack
1590  // pointer when other instructions are using the stack.
1591  Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
1592 
1593  SDValue Size = Tmp2.getOperand(1);
1594  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1595  Chain = SP.getValue(1);
1596  unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1597  unsigned StackAlign =
1598  DAG.getSubtarget().getFrameLowering()->getStackAlignment();
1599  Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
1600  if (Align > StackAlign)
1601  Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1602  DAG.getConstant(-(uint64_t)Align, dl, VT));
1603  Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
1604 
1605  Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
1606  DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
1607 
1608  Results.push_back(Tmp1);
1609  Results.push_back(Tmp2);
1610 }
1611 
1612 /// Legalize a SETCC with given LHS and RHS and condition code CC on the current
1613 /// target.
1614 ///
1615 /// If the SETCC has been legalized using AND / OR, then the legalized node
1616 /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
1617 /// will be set to false.
1618 ///
1619 /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
1620 /// then the values of LHS and RHS will be swapped, CC will be set to the
1621 /// new condition, and NeedInvert will be set to false.
1622 ///
1623 /// If the SETCC has been legalized using the inverse condcode, then LHS and
1624 /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert
1625 /// will be set to true. The caller must invert the result of the SETCC with
1626 /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect
1627 /// of a true/false result.
1628 ///
1629 /// \returns true if the SetCC has been legalized, false if it hasn't.
1630 bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT, SDValue &LHS,
1631  SDValue &RHS, SDValue &CC,
1632  bool &NeedInvert,
1633  const SDLoc &dl) {
1634  MVT OpVT = LHS.getSimpleValueType();
1635  ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1636  NeedInvert = false;
1637  switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1638  default: llvm_unreachable("Unknown condition code action!");
1639  case TargetLowering::Legal:
1640  // Nothing to do.
1641  break;
1642  case TargetLowering::Expand: {
1644  if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
1645  std::swap(LHS, RHS);
1646  CC = DAG.getCondCode(InvCC);
1647  return true;
1648  }
1649  // Swapping operands didn't work. Try inverting the condition.
1650  bool NeedSwap = false;
1651  InvCC = getSetCCInverse(CCCode, OpVT.isInteger());
1652  if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
1653  // If inverting the condition is not enough, try swapping operands
1654  // on top of it.
1655  InvCC = ISD::getSetCCSwappedOperands(InvCC);
1656  NeedSwap = true;
1657  }
1658  if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
1659  CC = DAG.getCondCode(InvCC);
1660  NeedInvert = true;
1661  if (NeedSwap)
1662  std::swap(LHS, RHS);
1663  return true;
1664  }
1665 
1667  unsigned Opc = 0;
1668  switch (CCCode) {
1669  default: llvm_unreachable("Don't know how to expand this condition!");
1670  case ISD::SETO:
1671  assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT)
1672  && "If SETO is expanded, SETOEQ must be legal!");
1673  CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break;
1674  case ISD::SETUO:
1675  assert(TLI.isCondCodeLegal(ISD::SETUNE, OpVT)
1676  && "If SETUO is expanded, SETUNE must be legal!");
1677  CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break;
1678  case ISD::SETOEQ:
1679  case ISD::SETOGT:
1680  case ISD::SETOGE:
1681  case ISD::SETOLT:
1682  case ISD::SETOLE:
1683  case ISD::SETONE:
1684  case ISD::SETUEQ:
1685  case ISD::SETUNE:
1686  case ISD::SETUGT:
1687  case ISD::SETUGE:
1688  case ISD::SETULT:
1689  case ISD::SETULE:
1690  // If we are floating point, assign and break, otherwise fall through.
1691  if (!OpVT.isInteger()) {
1692  // We can use the 4th bit to tell if we are the unordered
1693  // or ordered version of the opcode.
1694  CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
1695  Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
1696  CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
1697  break;
1698  }
1699  // Fallthrough if we are unsigned integer.
1701  case ISD::SETLE:
1702  case ISD::SETGT:
1703  case ISD::SETGE:
1704  case ISD::SETLT:
1705  case ISD::SETNE:
1706  case ISD::SETEQ:
1707  // If all combinations of inverting the condition and swapping operands
1708  // didn't work then we have no means to expand the condition.
1709  llvm_unreachable("Don't know how to expand this condition!");
1710  }
1711 
1712  SDValue SetCC1, SetCC2;
1713  if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
1714  // If we aren't the ordered or unorder operation,
1715  // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
1716  SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1717  SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1718  } else {
1719  // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
1720  SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1);
1721  SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2);
1722  }
1723  LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1724  RHS = SDValue();
1725  CC = SDValue();
1726  return true;
1727  }
1728  }
1729  return false;
1730 }
1731 
1732 /// Emit a store/load combination to the stack. This stores
1733 /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
1734 /// a load from the stack slot to DestVT, extending it if needed.
1735 /// The resultant code need not be legal.
1736 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1737  EVT DestVT, const SDLoc &dl) {
1738  return EmitStackConvert(SrcOp, SlotVT, DestVT, dl, DAG.getEntryNode());
1739 }
1740 
1741 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1742  EVT DestVT, const SDLoc &dl,
1743  SDValue Chain) {
1744  // Create the stack frame object.
1745  unsigned SrcAlign = DAG.getDataLayout().getPrefTypeAlignment(
1746  SrcOp.getValueType().getTypeForEVT(*DAG.getContext()));
1747  SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1748 
1749  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1750  int SPFI = StackPtrFI->getIndex();
1751  MachinePointerInfo PtrInfo =
1752  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
1753 
1754  unsigned SrcSize = SrcOp.getValueSizeInBits();
1755  unsigned SlotSize = SlotVT.getSizeInBits();
1756  unsigned DestSize = DestVT.getSizeInBits();
1757  Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1758  unsigned DestAlign = DAG.getDataLayout().getPrefTypeAlignment(DestType);
1759 
1760  // Emit a store to the stack slot. Use a truncstore if the input value is
1761  // later than DestVT.
1762  SDValue Store;
1763 
1764  if (SrcSize > SlotSize)
1765  Store = DAG.getTruncStore(Chain, dl, SrcOp, FIPtr, PtrInfo,
1766  SlotVT, SrcAlign);
1767  else {
1768  assert(SrcSize == SlotSize && "Invalid store");
1769  Store =
1770  DAG.getStore(Chain, dl, SrcOp, FIPtr, PtrInfo, SrcAlign);
1771  }
1772 
1773  // Result is a load from the stack slot.
1774  if (SlotSize == DestSize)
1775  return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign);
1776 
1777  assert(SlotSize < DestSize && "Unknown extension!");
1778  return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT,
1779  DestAlign);
1780 }
1781 
1782 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1783  SDLoc dl(Node);
1784  // Create a vector sized/aligned stack slot, store the value to element #0,
1785  // then load the whole vector back out.
1786  SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1787 
1788  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1789  int SPFI = StackPtrFI->getIndex();
1790 
1791  SDValue Ch = DAG.getTruncStore(
1792  DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr,
1793  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI),
1794  Node->getValueType(0).getVectorElementType());
1795  return DAG.getLoad(
1796  Node->getValueType(0), dl, Ch, StackPtr,
1797  MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
1798 }
1799 
1800 static bool
1802  const TargetLowering &TLI, SDValue &Res) {
1803  unsigned NumElems = Node->getNumOperands();
1804  SDLoc dl(Node);
1805  EVT VT = Node->getValueType(0);
1806 
1807  // Try to group the scalars into pairs, shuffle the pairs together, then
1808  // shuffle the pairs of pairs together, etc. until the vector has
1809  // been built. This will work only if all of the necessary shuffle masks
1810  // are legal.
1811 
1812  // We do this in two phases; first to check the legality of the shuffles,
1813  // and next, assuming that all shuffles are legal, to create the new nodes.
1814  for (int Phase = 0; Phase < 2; ++Phase) {
1816  NewIntermedVals;
1817  for (unsigned i = 0; i < NumElems; ++i) {
1818  SDValue V = Node->getOperand(i);
1819  if (V.isUndef())
1820  continue;
1821 
1822  SDValue Vec;
1823  if (Phase)
1824  Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1825  IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1826  }
1827 
1828  while (IntermedVals.size() > 2) {
1829  NewIntermedVals.clear();
1830  for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1831  // This vector and the next vector are shuffled together (simply to
1832  // append the one to the other).
1833  SmallVector<int, 16> ShuffleVec(NumElems, -1);
1834 
1835  SmallVector<int, 16> FinalIndices;
1836  FinalIndices.reserve(IntermedVals[i].second.size() +
1837  IntermedVals[i+1].second.size());
1838 
1839  int k = 0;
1840  for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1841  ++j, ++k) {
1842  ShuffleVec[k] = j;
1843  FinalIndices.push_back(IntermedVals[i].second[j]);
1844  }
1845  for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1846  ++j, ++k) {
1847  ShuffleVec[k] = NumElems + j;
1848  FinalIndices.push_back(IntermedVals[i+1].second[j]);
1849  }
1850 
1851  SDValue Shuffle;
1852  if (Phase)
1853  Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1854  IntermedVals[i+1].first,
1855  ShuffleVec);
1856  else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1857  return false;
1858  NewIntermedVals.push_back(
1859  std::make_pair(Shuffle, std::move(FinalIndices)));
1860  }
1861 
1862  // If we had an odd number of defined values, then append the last
1863  // element to the array of new vectors.
1864  if ((IntermedVals.size() & 1) != 0)
1865  NewIntermedVals.push_back(IntermedVals.back());
1866 
1867  IntermedVals.swap(NewIntermedVals);
1868  }
1869 
1870  assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
1871  "Invalid number of intermediate vectors");
1872  SDValue Vec1 = IntermedVals[0].first;
1873  SDValue Vec2;
1874  if (IntermedVals.size() > 1)
1875  Vec2 = IntermedVals[1].first;
1876  else if (Phase)
1877  Vec2 = DAG.getUNDEF(VT);
1878 
1879  SmallVector<int, 16> ShuffleVec(NumElems, -1);
1880  for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
1881  ShuffleVec[IntermedVals[0].second[i]] = i;
1882  for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
1883  ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
1884 
1885  if (Phase)
1886  Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
1887  else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1888  return false;
1889  }
1890 
1891  return true;
1892 }
1893 
1894 /// Expand a BUILD_VECTOR node on targets that don't
1895 /// support the operation, but do support the resultant vector type.
1896 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1897  unsigned NumElems = Node->getNumOperands();
1898  SDValue Value1, Value2;
1899  SDLoc dl(Node);
1900  EVT VT = Node->getValueType(0);
1901  EVT OpVT = Node->getOperand(0).getValueType();
1902  EVT EltVT = VT.getVectorElementType();
1903 
1904  // If the only non-undef value is the low element, turn this into a
1905  // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
1906  bool isOnlyLowElement = true;
1907  bool MoreThanTwoValues = false;
1908  bool isConstant = true;
1909  for (unsigned i = 0; i < NumElems; ++i) {
1910  SDValue V = Node->getOperand(i);
1911  if (V.isUndef())
1912  continue;
1913  if (i > 0)
1914  isOnlyLowElement = false;
1915  if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1916  isConstant = false;
1917 
1918  if (!Value1.getNode()) {
1919  Value1 = V;
1920  } else if (!Value2.getNode()) {
1921  if (V != Value1)
1922  Value2 = V;
1923  } else if (V != Value1 && V != Value2) {
1924  MoreThanTwoValues = true;
1925  }
1926  }
1927 
1928  if (!Value1.getNode())
1929  return DAG.getUNDEF(VT);
1930 
1931  if (isOnlyLowElement)
1932  return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1933 
1934  // If all elements are constants, create a load from the constant pool.
1935  if (isConstant) {
1937  for (unsigned i = 0, e = NumElems; i != e; ++i) {
1938  if (ConstantFPSDNode *V =
1939  dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1940  CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1941  } else if (ConstantSDNode *V =
1942  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1943  if (OpVT==EltVT)
1944  CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1945  else {
1946  // If OpVT and EltVT don't match, EltVT is not legal and the
1947  // element values have been promoted/truncated earlier. Undo this;
1948  // we don't want a v16i8 to become a v16i32 for example.
1949  const ConstantInt *CI = V->getConstantIntValue();
1950  CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1951  CI->getZExtValue()));
1952  }
1953  } else {
1954  assert(Node->getOperand(i).isUndef());
1955  Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1956  CV.push_back(UndefValue::get(OpNTy));
1957  }
1958  }
1959  Constant *CP = ConstantVector::get(CV);
1960  SDValue CPIdx =
1961  DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout()));
1962  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1963  return DAG.getLoad(
1964  VT, dl, DAG.getEntryNode(), CPIdx,
1965  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
1966  Alignment);
1967  }
1968 
1969  SmallSet<SDValue, 16> DefinedValues;
1970  for (unsigned i = 0; i < NumElems; ++i) {
1971  if (Node->getOperand(i).isUndef())
1972  continue;
1973  DefinedValues.insert(Node->getOperand(i));
1974  }
1975 
1976  if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
1977  if (!MoreThanTwoValues) {
1978  SmallVector<int, 8> ShuffleVec(NumElems, -1);
1979  for (unsigned i = 0; i < NumElems; ++i) {
1980  SDValue V = Node->getOperand(i);
1981  if (V.isUndef())
1982  continue;
1983  ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1984  }
1985  if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1986  // Get the splatted value into the low element of a vector register.
1987  SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1988  SDValue Vec2;
1989  if (Value2.getNode())
1990  Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1991  else
1992  Vec2 = DAG.getUNDEF(VT);
1993 
1994  // Return shuffle(LowValVec, undef, <0,0,0,0>)
1995  return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
1996  }
1997  } else {
1998  SDValue Res;
1999  if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
2000  return Res;
2001  }
2002  }
2003 
2004  // Otherwise, we can't handle this case efficiently.
2005  return ExpandVectorBuildThroughStack(Node);
2006 }
2007 
2008 // Expand a node into a call to a libcall. If the result value
2009 // does not fit into a register, return the lo part and set the hi part to the
2010 // by-reg argument. If it does fit into a single register, return the result
2011 // and leave the Hi part unset.
2012 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2013  bool isSigned) {
2015  TargetLowering::ArgListEntry Entry;
2016  for (const SDValue &Op : Node->op_values()) {
2017  EVT ArgVT = Op.getValueType();
2018  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2019  Entry.Node = Op;
2020  Entry.Ty = ArgTy;
2021  Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
2022  Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
2023  Args.push_back(Entry);
2024  }
2025  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2026  TLI.getPointerTy(DAG.getDataLayout()));
2027 
2028  EVT RetVT = Node->getValueType(0);
2029  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2030 
2031  // By default, the input chain to this libcall is the entry node of the
2032  // function. If the libcall is going to be emitted as a tail call then
2033  // TLI.isUsedByReturnOnly will change it to the right chain if the return
2034  // node which is being folded has a non-entry input chain.
2035  SDValue InChain = DAG.getEntryNode();
2036 
2037  // isTailCall may be true since the callee does not reference caller stack
2038  // frame. Check if it's in the right position and that the return types match.
2039  SDValue TCChain = InChain;
2040  const Function &F = DAG.getMachineFunction().getFunction();
2041  bool isTailCall =
2042  TLI.isInTailCallPosition(DAG, Node, TCChain) &&
2043  (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
2044  if (isTailCall)
2045  InChain = TCChain;
2046 
2048  bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned);
2049  CLI.setDebugLoc(SDLoc(Node))
2050  .setChain(InChain)
2051  .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2052  std::move(Args))
2053  .setTailCall(isTailCall)
2054  .setSExtResult(signExtend)
2055  .setZExtResult(!signExtend)
2057 
2058  std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2059 
2060  if (!CallInfo.second.getNode()) {
2061  LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump(&DAG));
2062  // It's a tailcall, return the chain (which is the DAG root).
2063  return DAG.getRoot();
2064  }
2065 
2066  LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump(&DAG));
2067  return CallInfo.first;
2068 }
2069 
2070 // Expand a node into a call to a libcall. Similar to
2071 // ExpandLibCall except that the first operand is the in-chain.
2072 std::pair<SDValue, SDValue>
2073 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
2074  SDNode *Node,
2075  bool isSigned) {
2076  SDValue InChain = Node->getOperand(0);
2077 
2079  TargetLowering::ArgListEntry Entry;
2080  for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2081  EVT ArgVT = Node->getOperand(i).getValueType();
2082  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2083  Entry.Node = Node->getOperand(i);
2084  Entry.Ty = ArgTy;
2085  Entry.IsSExt = isSigned;
2086  Entry.IsZExt = !isSigned;
2087  Args.push_back(Entry);
2088  }
2089  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2090  TLI.getPointerTy(DAG.getDataLayout()));
2091 
2092  Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2093 
2095  CLI.setDebugLoc(SDLoc(Node))
2096  .setChain(InChain)
2097  .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2098  std::move(Args))
2099  .setSExtResult(isSigned)
2100  .setZExtResult(!isSigned);
2101 
2102  std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2103 
2104  return CallInfo;
2105 }
2106 
2107 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2108  RTLIB::Libcall Call_F32,
2109  RTLIB::Libcall Call_F64,
2110  RTLIB::Libcall Call_F80,
2111  RTLIB::Libcall Call_F128,
2112  RTLIB::Libcall Call_PPCF128) {
2113  if (Node->isStrictFPOpcode())
2114  Node = DAG.mutateStrictFPToFP(Node);
2115 
2116  RTLIB::Libcall LC;
2117  switch (Node->getSimpleValueType(0).SimpleTy) {
2118  default: llvm_unreachable("Unexpected request for libcall!");
2119  case MVT::f32: LC = Call_F32; break;
2120  case MVT::f64: LC = Call_F64; break;
2121  case MVT::f80: LC = Call_F80; break;
2122  case MVT::f128: LC = Call_F128; break;
2123  case MVT::ppcf128: LC = Call_PPCF128; break;
2124  }
2125  return ExpandLibCall(LC, Node, false);
2126 }
2127 
2128 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2129  RTLIB::Libcall Call_I8,
2130  RTLIB::Libcall Call_I16,
2131  RTLIB::Libcall Call_I32,
2132  RTLIB::Libcall Call_I64,
2133  RTLIB::Libcall Call_I128) {
2134  RTLIB::Libcall LC;
2135  switch (Node->getSimpleValueType(0).SimpleTy) {
2136  default: llvm_unreachable("Unexpected request for libcall!");
2137  case MVT::i8: LC = Call_I8; break;
2138  case MVT::i16: LC = Call_I16; break;
2139  case MVT::i32: LC = Call_I32; break;
2140  case MVT::i64: LC = Call_I64; break;
2141  case MVT::i128: LC = Call_I128; break;
2142  }
2143  return ExpandLibCall(LC, Node, isSigned);
2144 }
2145 
2146 /// Expand the node to a libcall based on first argument type (for instance
2147 /// lround and its variant).
2148 SDValue SelectionDAGLegalize::ExpandArgFPLibCall(SDNode* Node,
2149  RTLIB::Libcall Call_F32,
2150  RTLIB::Libcall Call_F64,
2151  RTLIB::Libcall Call_F80,
2152  RTLIB::Libcall Call_F128,
2153  RTLIB::Libcall Call_PPCF128) {
2154  if (Node->isStrictFPOpcode())
2155  Node = DAG.mutateStrictFPToFP(Node);
2156 
2157  RTLIB::Libcall LC;
2158  switch (Node->getOperand(0).getValueType().getSimpleVT().SimpleTy) {
2159  default: llvm_unreachable("Unexpected request for libcall!");
2160  case MVT::f32: LC = Call_F32; break;
2161  case MVT::f64: LC = Call_F64; break;
2162  case MVT::f80: LC = Call_F80; break;
2163  case MVT::f128: LC = Call_F128; break;
2164  case MVT::ppcf128: LC = Call_PPCF128; break;
2165  }
2166 
2167  return ExpandLibCall(LC, Node, false);
2168 }
2169 
2170 /// Issue libcalls to __{u}divmod to compute div / rem pairs.
2171 void
2172 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2173  SmallVectorImpl<SDValue> &Results) {
2174  unsigned Opcode = Node->getOpcode();
2175  bool isSigned = Opcode == ISD::SDIVREM;
2176 
2177  RTLIB::Libcall LC;
2178  switch (Node->getSimpleValueType(0).SimpleTy) {
2179  default: llvm_unreachable("Unexpected request for libcall!");
2180  case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
2181  case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2182  case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2183  case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2184  case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2185  }
2186 
2187  // The input chain to this libcall is the entry node of the function.
2188  // Legalizing the call will automatically add the previous call to the
2189  // dependence.
2190  SDValue InChain = DAG.getEntryNode();
2191 
2192  EVT RetVT = Node->getValueType(0);
2193  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2194 
2196  TargetLowering::ArgListEntry Entry;
2197  for (const SDValue &Op : Node->op_values()) {
2198  EVT ArgVT = Op.getValueType();
2199  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2200  Entry.Node = Op;
2201  Entry.Ty = ArgTy;
2202  Entry.IsSExt = isSigned;
2203  Entry.IsZExt = !isSigned;
2204  Args.push_back(Entry);
2205  }
2206 
2207  // Also pass the return address of the remainder.
2208  SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2209  Entry.Node = FIPtr;
2210  Entry.Ty = RetTy->getPointerTo();
2211  Entry.IsSExt = isSigned;
2212  Entry.IsZExt = !isSigned;
2213  Args.push_back(Entry);
2214 
2215  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2216  TLI.getPointerTy(DAG.getDataLayout()));
2217 
2218  SDLoc dl(Node);
2220  CLI.setDebugLoc(dl)
2221  .setChain(InChain)
2222  .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2223  std::move(Args))
2224  .setSExtResult(isSigned)
2225  .setZExtResult(!isSigned);
2226 
2227  std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2228 
2229  // Remainder is loaded back from the stack frame.
2230  SDValue Rem =
2231  DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo());
2232  Results.push_back(CallInfo.first);
2233  Results.push_back(Rem);
2234 }
2235 
2236 /// Return true if sincos libcall is available.
2237 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
2238  RTLIB::Libcall LC;
2239  switch (Node->getSimpleValueType(0).SimpleTy) {
2240  default: llvm_unreachable("Unexpected request for libcall!");
2241  case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2242  case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2243  case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2244  case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2245  case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2246  }
2247  return TLI.getLibcallName(LC) != nullptr;
2248 }
2249 
2250 /// Only issue sincos libcall if both sin and cos are needed.
2251 static bool useSinCos(SDNode *Node) {
2252  unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2253  ? ISD::FCOS : ISD::FSIN;
2254 
2255  SDValue Op0 = Node->getOperand(0);
2256  for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2257  UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2258  SDNode *User = *UI;
2259  if (User == Node)
2260  continue;
2261  // The other user might have been turned into sincos already.
2262  if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2263  return true;
2264  }
2265  return false;
2266 }
2267 
2268 /// Issue libcalls to sincos to compute sin / cos pairs.
2269 void
2270 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
2271  SmallVectorImpl<SDValue> &Results) {
2272  RTLIB::Libcall LC;
2273  switch (Node->getSimpleValueType(0).SimpleTy) {
2274  default: llvm_unreachable("Unexpected request for libcall!");
2275  case MVT::f32: LC = RTLIB::SINCOS_F32; break;
2276  case MVT::f64: LC = RTLIB::SINCOS_F64; break;
2277  case MVT::f80: LC = RTLIB::SINCOS_F80; break;
2278  case MVT::f128: LC = RTLIB::SINCOS_F128; break;
2279  case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2280  }
2281 
2282  // The input chain to this libcall is the entry node of the function.
2283  // Legalizing the call will automatically add the previous call to the
2284  // dependence.
2285  SDValue InChain = DAG.getEntryNode();
2286 
2287  EVT RetVT = Node->getValueType(0);
2288  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2289 
2291  TargetLowering::ArgListEntry Entry;
2292 
2293  // Pass the argument.
2294  Entry.Node = Node->getOperand(0);
2295  Entry.Ty = RetTy;
2296  Entry.IsSExt = false;
2297  Entry.IsZExt = false;
2298  Args.push_back(Entry);
2299 
2300  // Pass the return address of sin.
2301  SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
2302  Entry.Node = SinPtr;
2303  Entry.Ty = RetTy->getPointerTo();
2304  Entry.IsSExt = false;
2305  Entry.IsZExt = false;
2306  Args.push_back(Entry);
2307 
2308  // Also pass the return address of the cos.
2309  SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
2310  Entry.Node = CosPtr;
2311  Entry.Ty = RetTy->getPointerTo();
2312  Entry.IsSExt = false;
2313  Entry.IsZExt = false;
2314  Args.push_back(Entry);
2315 
2316  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2317  TLI.getPointerTy(DAG.getDataLayout()));
2318 
2319  SDLoc dl(Node);
2321  CLI.setDebugLoc(dl).setChain(InChain).setLibCallee(
2322  TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee,
2323  std::move(Args));
2324 
2325  std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2326 
2327  Results.push_back(
2328  DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo()));
2329  Results.push_back(
2330  DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo()));
2331 }
2332 
2333 /// This function is responsible for legalizing a
2334 /// INT_TO_FP operation of the specified operand when the target requests that
2335 /// we expand it. At this point, we know that the result and operand types are
2336 /// legal for the target.
2337 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned, SDValue Op0,
2338  EVT DestVT,
2339  const SDLoc &dl) {
2340  EVT SrcVT = Op0.getValueType();
2341 
2342  // TODO: Should any fast-math-flags be set for the created nodes?
2343  LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n");
2344  if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64)) {
2345  LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double "
2346  "expansion\n");
2347 
2348  // Get the stack frame index of a 8 byte buffer.
2349  SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2350 
2351  // word offset constant for Hi/Lo address computation
2352  SDValue WordOff = DAG.getConstant(sizeof(int), dl,
2353  StackSlot.getValueType());
2354  // set up Hi and Lo (into buffer) address based on endian
2355  SDValue Hi = StackSlot;
2356  SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(),
2357  StackSlot, WordOff);
2358  if (DAG.getDataLayout().isLittleEndian())
2359  std::swap(Hi, Lo);
2360 
2361  // if signed map to unsigned space
2362  SDValue Op0Mapped;
2363  if (isSigned) {
2364  // constant used to invert sign bit (signed to unsigned mapping)
2365  SDValue SignBit = DAG.getConstant(0x80000000u, dl, MVT::i32);
2366  Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2367  } else {
2368  Op0Mapped = Op0;
2369  }
2370  // store the lo of the constructed double - based on integer input
2371  SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op0Mapped, Lo,
2372  MachinePointerInfo());
2373  // initial hi portion of constructed double
2374  SDValue InitialHi = DAG.getConstant(0x43300000u, dl, MVT::i32);
2375  // store the hi of the constructed double - biased exponent
2376  SDValue Store2 =
2377  DAG.getStore(Store1, dl, InitialHi, Hi, MachinePointerInfo());
2378  // load the constructed double
2379  SDValue Load =
2380  DAG.getLoad(MVT::f64, dl, Store2, StackSlot, MachinePointerInfo());
2381  // FP constant to bias correct the final result
2382  SDValue Bias = DAG.getConstantFP(isSigned ?
2383  BitsToDouble(0x4330000080000000ULL) :
2384  BitsToDouble(0x4330000000000000ULL),
2385  dl, MVT::f64);
2386  // subtract the bias
2387  SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2388  // final result
2389  SDValue Result = DAG.getFPExtendOrRound(Sub, dl, DestVT);
2390  return Result;
2391  }
2392  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2393  // Code below here assumes !isSigned without checking again.
2394 
2395  SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2396 
2397  SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0,
2398  DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2399  SDValue Zero = DAG.getIntPtrConstant(0, dl),
2400  Four = DAG.getIntPtrConstant(4, dl);
2401  SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2402  SignSet, Four, Zero);
2403 
2404  // If the sign bit of the integer is set, the large number will be treated
2405  // as a negative number. To counteract this, the dynamic code adds an
2406  // offset depending on the data type.
2407  uint64_t FF;
2408  switch (SrcVT.getSimpleVT().SimpleTy) {
2409  default: llvm_unreachable("Unsupported integer type!");
2410  case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
2411  case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
2412  case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
2413  case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
2414  }
2415  if (DAG.getDataLayout().isLittleEndian())
2416  FF <<= 32;
2417  Constant *FudgeFactor = ConstantInt::get(
2418  Type::getInt64Ty(*DAG.getContext()), FF);
2419 
2420  SDValue CPIdx =
2421  DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout()));
2422  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2423  CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
2424  Alignment = std::min(Alignment, 4u);
2425  SDValue FudgeInReg;
2426  if (DestVT == MVT::f32)
2427  FudgeInReg = DAG.getLoad(
2428  MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2429  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2430  Alignment);
2431  else {
2432  SDValue Load = DAG.getExtLoad(
2433  ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx,
2434  MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
2435  Alignment);
2436  HandleSDNode Handle(Load);
2437  LegalizeOp(Load.getNode());
2438  FudgeInReg = Handle.getValue();
2439  }
2440 
2441  return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2442 }
2443 
2444 /// This function is responsible for legalizing a
2445 /// *INT_TO_FP operation of the specified operand when the target requests that
2446 /// we promote it. At this point, we know that the result and operand types are
2447 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2448 /// operation that takes a larger input.
2449 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT,
2450  bool isSigned,
2451  const SDLoc &dl) {
2452  // First step, figure out the appropriate *INT_TO_FP operation to use.
2453  EVT NewInTy = LegalOp.getValueType();
2454 
2455  unsigned OpToUse = 0;
2456 
2457  // Scan for the appropriate larger type to use.
2458  while (true) {
2459  NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2460  assert(NewInTy.isInteger() && "Ran out of possibilities!");
2461 
2462  // If the target supports SINT_TO_FP of this type, use it.
2463  if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2464  OpToUse = ISD::SINT_TO_FP;
2465  break;
2466  }
2467  if (isSigned) continue;
2468 
2469  // If the target supports UINT_TO_FP of this type, use it.
2470  if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2471  OpToUse = ISD::UINT_TO_FP;
2472  break;
2473  }
2474 
2475  // Otherwise, try a larger type.
2476  }
2477 
2478  // Okay, we found the operation and type to use. Zero extend our input to the
2479  // desired type then run the operation on it.
2480  return DAG.getNode(OpToUse, dl, DestVT,
2481  DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2482  dl, NewInTy, LegalOp));
2483 }
2484 
2485 /// This function is responsible for legalizing a
2486 /// FP_TO_*INT operation of the specified operand when the target requests that
2487 /// we promote it. At this point, we know that the result and operand types are
2488 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2489 /// operation that returns a larger result.
2490 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT,
2491  bool isSigned,
2492  const SDLoc &dl) {
2493  // First step, figure out the appropriate FP_TO*INT operation to use.
2494  EVT NewOutTy = DestVT;
2495 
2496  unsigned OpToUse = 0;
2497 
2498  // Scan for the appropriate larger type to use.
2499  while (true) {
2500  NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2501  assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2502 
2503  // A larger signed type can hold all unsigned values of the requested type,
2504  // so using FP_TO_SINT is valid
2505  if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2506  OpToUse = ISD::FP_TO_SINT;
2507  break;
2508  }
2509 
2510  // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
2511  if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2512  OpToUse = ISD::FP_TO_UINT;
2513  break;
2514  }
2515 
2516  // Otherwise, try a larger type.
2517  }
2518 
2519  // Okay, we found the operation and type to use.
2520  SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2521 
2522  // Truncate the result of the extended FP_TO_*INT operation to the desired
2523  // size.
2524  return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2525 }
2526 
2527 /// Legalize a BITREVERSE scalar/vector operation as a series of mask + shifts.
2528 SDValue SelectionDAGLegalize::ExpandBITREVERSE(SDValue Op, const SDLoc &dl) {
2529  EVT VT = Op.getValueType();
2530  EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2531  unsigned Sz = VT.getScalarSizeInBits();
2532 
2533  SDValue Tmp, Tmp2, Tmp3;
2534 
2535  // If we can, perform BSWAP first and then the mask+swap the i4, then i2
2536  // and finally the i1 pairs.
2537  // TODO: We can easily support i4/i2 legal types if any target ever does.
2538  if (Sz >= 8 && isPowerOf2_32(Sz)) {
2539  // Create the masks - repeating the pattern every byte.
2540  APInt MaskHi4 = APInt::getSplat(Sz, APInt(8, 0xF0));
2541  APInt MaskHi2 = APInt::getSplat(Sz, APInt(8, 0xCC));
2542  APInt MaskHi1 = APInt::getSplat(Sz, APInt(8, 0xAA));
2543  APInt MaskLo4 = APInt::getSplat(Sz, APInt(8, 0x0F));
2544  APInt MaskLo2 = APInt::getSplat(Sz, APInt(8, 0x33));
2545  APInt MaskLo1 = APInt::getSplat(Sz, APInt(8, 0x55));
2546 
2547  // BSWAP if the type is wider than a single byte.
2548  Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
2549 
2550  // swap i4: ((V & 0xF0) >> 4) | ((V & 0x0F) << 4)
2551  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi4, dl, VT));
2552  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo4, dl, VT));
2553  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(4, dl, SHVT));
2554  Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
2555  Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2556 
2557  // swap i2: ((V & 0xCC) >> 2) | ((V & 0x33) << 2)
2558  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi2, dl, VT));
2559  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo2, dl, VT));
2560  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(2, dl, SHVT));
2561  Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
2562  Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2563 
2564  // swap i1: ((V & 0xAA) >> 1) | ((V & 0x55) << 1)
2565  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskHi1, dl, VT));
2566  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(MaskLo1, dl, VT));
2567  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp2, DAG.getConstant(1, dl, SHVT));
2568  Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
2569  Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
2570  return Tmp;
2571  }
2572 
2573  Tmp = DAG.getConstant(0, dl, VT);
2574  for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
2575  if (I < J)
2576  Tmp2 =
2577  DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
2578  else
2579  Tmp2 =
2580  DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
2581 
2582  APInt Shift(Sz, 1);
2583  Shift <<= J;
2584  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
2585  Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
2586  }
2587 
2588  return Tmp;
2589 }
2590 
2591 /// Open code the operations for BSWAP of the specified operation.
2592 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, const SDLoc &dl) {
2593  EVT VT = Op.getValueType();
2594  EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2595  SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2596  switch (VT.getSimpleVT().getScalarType().SimpleTy) {
2597  default: llvm_unreachable("Unhandled Expand type in BSWAP!");
2598  case MVT::i16:
2599  // Use a rotate by 8. This can be further expanded if necessary.
2600  return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2601  case MVT::i32:
2602  Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2603  Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2604  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2605  Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2606  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2607  DAG.getConstant(0xFF0000, dl, VT));
2608  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
2609  Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2610  Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2611  return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2612  case MVT::i64:
2613  Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2614  Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2615  Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2616  Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2617  Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
2618  Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
2619  Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
2620  Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
2621  Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
2622  DAG.getConstant(255ULL<<48, dl, VT));
2623  Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
2624  DAG.getConstant(255ULL<<40, dl, VT));
2625  Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
2626  DAG.getConstant(255ULL<<32, dl, VT));
2627  Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
2628  DAG.getConstant(255ULL<<24, dl, VT));
2629  Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
2630  DAG.getConstant(255ULL<<16, dl, VT));
2631  Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
2632  DAG.getConstant(255ULL<<8 , dl, VT));
2633  Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2634  Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2635  Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2636  Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2637  Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2638  Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2639  return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2640  }
2641 }
2642 
2643 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2644  LLVM_DEBUG(dbgs() << "Trying to expand node\n");
2646  SDLoc dl(Node);
2647  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2648  bool NeedInvert;
2649  switch (Node->getOpcode()) {
2650  case ISD::ABS:
2651  if (TLI.expandABS(Node, Tmp1, DAG))
2652  Results.push_back(Tmp1);
2653  break;
2654  case ISD::CTPOP:
2655  if (TLI.expandCTPOP(Node, Tmp1, DAG))
2656  Results.push_back(Tmp1);
2657  break;
2658  case ISD::CTLZ:
2659  case ISD::CTLZ_ZERO_UNDEF:
2660  if (TLI.expandCTLZ(Node, Tmp1, DAG))
2661  Results.push_back(Tmp1);
2662  break;
2663  case ISD::CTTZ:
2664  case ISD::CTTZ_ZERO_UNDEF:
2665  if (TLI.expandCTTZ(Node, Tmp1, DAG))
2666  Results.push_back(Tmp1);
2667  break;
2668  case ISD::BITREVERSE:
2669  Results.push_back(ExpandBITREVERSE(Node->getOperand(0), dl));
2670  break;
2671  case ISD::BSWAP:
2672  Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2673  break;
2674  case ISD::FRAMEADDR:
2675  case ISD::RETURNADDR:
2677  Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
2678  break;
2679  case ISD::EH_DWARF_CFA: {
2680  SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl,
2681  TLI.getPointerTy(DAG.getDataLayout()));
2682  SDValue Offset = DAG.getNode(ISD::ADD, dl,
2683  CfaArg.getValueType(),
2684  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
2685  CfaArg.getValueType()),
2686  CfaArg);
2687  SDValue FA = DAG.getNode(
2688  ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout()),
2689  DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())));
2690  Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(),
2691  FA, Offset));
2692  break;
2693  }
2694  case ISD::FLT_ROUNDS_:
2695  Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
2696  break;
2697  case ISD::EH_RETURN:
2698  case ISD::EH_LABEL:
2699  case ISD::PREFETCH:
2700  case ISD::VAEND:
2701  case ISD::EH_SJLJ_LONGJMP:
2702  // If the target didn't expand these, there's nothing to do, so just
2703  // preserve the chain and be done.
2704  Results.push_back(Node->getOperand(0));
2705  break;
2706  case ISD::READCYCLECOUNTER:
2707  // If the target didn't expand this, just return 'zero' and preserve the
2708  // chain.
2709  Results.append(Node->getNumValues() - 1,
2710  DAG.getConstant(0, dl, Node->getValueType(0)));
2711  Results.push_back(Node->getOperand(0));
2712  break;
2713  case ISD::EH_SJLJ_SETJMP:
2714  // If the target didn't expand this, just return 'zero' and preserve the
2715  // chain.
2716  Results.push_back(DAG.getConstant(0, dl, MVT::i32));
2717  Results.push_back(Node->getOperand(0));
2718  break;
2719  case ISD::ATOMIC_LOAD: {
2720  // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
2721  SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
2722  SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2723  SDValue Swap = DAG.getAtomicCmpSwap(
2724  ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2725  Node->getOperand(0), Node->getOperand(1), Zero, Zero,
2726  cast<AtomicSDNode>(Node)->getMemOperand());
2727  Results.push_back(Swap.getValue(0));
2728  Results.push_back(Swap.getValue(1));
2729  break;
2730  }
2731  case ISD::ATOMIC_STORE: {
2732  // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
2733  SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2734  cast<AtomicSDNode>(Node)->getMemoryVT(),
2735  Node->getOperand(0),
2736  Node->getOperand(1), Node->getOperand(2),
2737  cast<AtomicSDNode>(Node)->getMemOperand());
2738  Results.push_back(Swap.getValue(1));
2739  break;
2740  }
2742  // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
2743  // splits out the success value as a comparison. Expanding the resulting
2744  // ATOMIC_CMP_SWAP will produce a libcall.
2745  SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2746  SDValue Res = DAG.getAtomicCmpSwap(
2747  ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2748  Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
2749  Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand());
2750 
2751  SDValue ExtRes = Res;
2752  SDValue LHS = Res;
2753  SDValue RHS = Node->getOperand(1);
2754 
2755  EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT();
2756  EVT OuterType = Node->getValueType(0);
2757  switch (TLI.getExtendForAtomicOps()) {
2758  case ISD::SIGN_EXTEND:
2759  LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res,
2760  DAG.getValueType(AtomicType));
2761  RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType,
2762  Node->getOperand(2), DAG.getValueType(AtomicType));
2763  ExtRes = LHS;
2764  break;
2765  case ISD::ZERO_EXTEND:
2766  LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res,
2767  DAG.getValueType(AtomicType));
2768  RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
2769  ExtRes = LHS;
2770  break;
2771  case ISD::ANY_EXTEND:
2772  LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType);
2773  RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
2774  break;
2775  default:
2776  llvm_unreachable("Invalid atomic op extension");
2777  }
2778 
2779  SDValue Success =
2780  DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ);
2781 
2782  Results.push_back(ExtRes.getValue(0));
2783  Results.push_back(Success);
2784  Results.push_back(Res.getValue(1));
2785  break;
2786  }
2788  ExpandDYNAMIC_STACKALLOC(Node, Results);
2789  break;
2790  case ISD::MERGE_VALUES:
2791  for (unsigned i = 0; i < Node->getNumValues(); i++)
2792  Results.push_back(Node->getOperand(i));
2793  break;
2794  case ISD::UNDEF: {
2795  EVT VT = Node->getValueType(0);
2796  if (VT.isInteger())
2797  Results.push_back(DAG.getConstant(0, dl, VT));
2798  else {
2799  assert(VT.isFloatingPoint() && "Unknown value type!");
2800  Results.push_back(DAG.getConstantFP(0, dl, VT));
2801  }
2802  break;
2803  }
2804  case ISD::STRICT_FP_ROUND:
2805  // This expansion does not honor the "strict" properties anyway,
2806  // so prefer falling back to the non-strict operation if legal.
2807  if (TLI.getStrictFPOperationAction(Node->getOpcode(),
2808  Node->getValueType(0))
2810  break;
2811  Tmp1 = EmitStackConvert(Node->getOperand(1),
2812  Node->getValueType(0),
2813  Node->getValueType(0), dl, Node->getOperand(0));
2814  ReplaceNode(Node, Tmp1.getNode());
2815  LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_ROUND node\n");
2816  return true;
2817  case ISD::FP_ROUND:
2818  case ISD::BITCAST:
2819  Tmp1 = EmitStackConvert(Node->getOperand(0),
2820  Node->getValueType(0),
2821  Node->getValueType(0), dl);
2822  Results.push_back(Tmp1);
2823  break;
2824  case ISD::STRICT_FP_EXTEND:
2825  // This expansion does not honor the "strict" properties anyway,
2826  // so prefer falling back to the non-strict operation if legal.
2827  if (TLI.getStrictFPOperationAction(Node->getOpcode(),
2828  Node->getValueType(0))
2830  break;
2831  Tmp1 = EmitStackConvert(Node->getOperand(1),
2832  Node->getOperand(1).getValueType(),
2833  Node->getValueType(0), dl, Node->getOperand(0));
2834  ReplaceNode(Node, Tmp1.getNode());
2835  LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_EXTEND node\n");
2836  return true;
2837  case ISD::FP_EXTEND:
2838  Tmp1 = EmitStackConvert(Node->getOperand(0),
2839  Node->getOperand(0).getValueType(),
2840  Node->getValueType(0), dl);
2841  Results.push_back(Tmp1);
2842  break;
2843  case ISD::SIGN_EXTEND_INREG: {
2844  EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2845  EVT VT = Node->getValueType(0);
2846 
2847  // An in-register sign-extend of a boolean is a negation:
2848  // 'true' (1) sign-extended is -1.
2849  // 'false' (0) sign-extended is 0.
2850  // However, we must mask the high bits of the source operand because the
2851  // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero.
2852 
2853  // TODO: Do this for vectors too?
2854  if (ExtraVT.getSizeInBits() == 1) {
2855  SDValue One = DAG.getConstant(1, dl, VT);
2856  SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One);
2857  SDValue Zero = DAG.getConstant(0, dl, VT);
2858  SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And);
2859  Results.push_back(Neg);
2860  break;
2861  }
2862 
2863  // NOTE: we could fall back on load/store here too for targets without
2864  // SRA. However, it is doubtful that any exist.
2865  EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2866  unsigned BitsDiff = VT.getScalarSizeInBits() -
2867  ExtraVT.getScalarSizeInBits();
2868  SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy);
2869  Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2870  Node->getOperand(0), ShiftCst);
2871  Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2872  Results.push_back(Tmp1);
2873  break;
2874  }
2875  case ISD::UINT_TO_FP:
2876  if (TLI.expandUINT_TO_FP(Node, Tmp1, DAG)) {
2877  Results.push_back(Tmp1);
2878  break;
2879  }
2881  case ISD::SINT_TO_FP:
2882  Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2883  Node->getOperand(0), Node->getValueType(0), dl);
2884  Results.push_back(Tmp1);
2885  break;
2886  case ISD::FP_TO_SINT:
2887  if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
2888  Results.push_back(Tmp1);
2889  break;
2891  if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) {
2892  ReplaceNode(Node, Tmp1.getNode());
2893  LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_SINT node\n");
2894  return true;
2895  }
2896  break;
2897  case ISD::FP_TO_UINT:
2898  if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG))
2899  Results.push_back(Tmp1);
2900  break;
2902  if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) {
2903  // Relink the chain.
2904  DAG.ReplaceAllUsesOfValueWith(SDValue(Node,1), Tmp2);
2905  // Replace the new UINT result.
2906  ReplaceNodeWithValue(SDValue(Node, 0), Tmp1);
2907  LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_UINT node\n");
2908  return true;
2909  }
2910  break;
2911  case ISD::VAARG:
2912  Results.push_back(DAG.expandVAArg(Node));
2913  Results.push_back(Results[0].getValue(1));
2914  break;
2915  case ISD::VACOPY:
2916  Results.push_back(DAG.expandVACopy(Node));
2917  break;
2919  if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2920  // This must be an access of the only element. Return it.
2921  Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
2922  Node->getOperand(0));
2923  else
2924  Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2925  Results.push_back(Tmp1);
2926  break;
2928  Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2929  break;
2930  case ISD::INSERT_SUBVECTOR:
2931  Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
2932  break;
2933  case ISD::CONCAT_VECTORS:
2934  Results.push_back(ExpandVectorBuildThroughStack(Node));
2935  break;
2936  case ISD::SCALAR_TO_VECTOR:
2937  Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2938  break;
2940  Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2941  Node->getOperand(1),
2942  Node->getOperand(2), dl));
2943  break;
2944  case ISD::VECTOR_SHUFFLE: {
2945  SmallVector<int, 32> NewMask;
2946  ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
2947 
2948  EVT VT = Node->getValueType(0);
2949  EVT EltVT = VT.getVectorElementType();
2950  SDValue Op0 = Node->getOperand(0);
2951  SDValue Op1 = Node->getOperand(1);
2952  if (!TLI.isTypeLegal(EltVT)) {
2953  EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
2954 
2955  // BUILD_VECTOR operands are allowed to be wider than the element type.
2956  // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
2957  // it.
2958  if (NewEltVT.bitsLT(EltVT)) {
2959  // Convert shuffle node.
2960  // If original node was v4i64 and the new EltVT is i32,
2961  // cast operands to v8i32 and re-build the mask.
2962 
2963  // Calculate new VT, the size of the new VT should be equal to original.
2964  EVT NewVT =
2965  EVT::getVectorVT(*DAG.getContext(), NewEltVT,
2966  VT.getSizeInBits() / NewEltVT.getSizeInBits());
2967  assert(NewVT.bitsEq(VT));
2968 
2969  // cast operands to new VT
2970  Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
2971  Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
2972 
2973  // Convert the shuffle mask
2974  unsigned int factor =
2976 
2977  // EltVT gets smaller
2978  assert(factor > 0);
2979 
2980  for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
2981  if (Mask[i] < 0) {
2982  for (unsigned fi = 0; fi < factor; ++fi)
2983  NewMask.push_back(Mask[i]);
2984  }
2985  else {
2986  for (unsigned fi = 0; fi < factor; ++fi)
2987  NewMask.push_back(Mask[i]*factor+fi);
2988  }
2989  }
2990  Mask = NewMask;
2991  VT = NewVT;
2992  }
2993  EltVT = NewEltVT;
2994  }
2995  unsigned NumElems = VT.getVectorNumElements();
2997  for (unsigned i = 0; i != NumElems; ++i) {
2998  if (Mask[i] < 0) {
2999  Ops.push_back(DAG.getUNDEF(EltVT));
3000  continue;
3001  }
3002  unsigned Idx = Mask[i];
3003  if (Idx < NumElems)
3004  Ops.push_back(DAG.getNode(
3005  ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
3006  DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))));
3007  else
3008  Ops.push_back(DAG.getNode(
3009  ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
3010  DAG.getConstant(Idx - NumElems, dl,
3011  TLI.getVectorIdxTy(DAG.getDataLayout()))));
3012  }
3013 
3014  Tmp1 = DAG.getBuildVector(VT, dl, Ops);
3015  // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3016  Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3017  Results.push_back(Tmp1);
3018  break;
3019  }
3020  case ISD::EXTRACT_ELEMENT: {
3021  EVT OpTy = Node->getOperand(0).getValueType();
3022  if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3023  // 1 -> Hi
3024  Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3025  DAG.getConstant(OpTy.getSizeInBits() / 2, dl,
3026  TLI.getShiftAmountTy(
3027  Node->getOperand(0).getValueType(),
3028  DAG.getDataLayout())));
3029  Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3030  } else {
3031  // 0 -> Lo
3032  Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3033  Node->getOperand(0));
3034  }
3035  Results.push_back(Tmp1);
3036  break;
3037  }
3038  case ISD::STACKSAVE:
3039  // Expand to CopyFromReg if the target set
3040  // StackPointerRegisterToSaveRestore.
3041  if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3042  Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3043  Node->getValueType(0)));
3044  Results.push_back(Results[0].getValue(1));
3045  } else {
3046  Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3047  Results.push_back(Node->getOperand(0));
3048  }
3049  break;
3050  case ISD::STACKRESTORE:
3051  // Expand to CopyToReg if the target set
3052  // StackPointerRegisterToSaveRestore.
3053  if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3054  Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3055  Node->getOperand(1)));
3056  } else {
3057  Results.push_back(Node->getOperand(0));
3058  }
3059  break;
3061  Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3062  Results.push_back(Results[0].getValue(0));
3063  break;
3064  case ISD::FCOPYSIGN:
3065  Results.push_back(ExpandFCOPYSIGN(Node));
3066  break;
3067  case ISD::FNEG:
3068  // Expand Y = FNEG(X) -> Y = SUB -0.0, X
3069  Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0));
3070  // TODO: If FNEG has fast-math-flags, propagate them to the FSUB.
3071  Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3072  Node->getOperand(0));
3073  Results.push_back(Tmp1);
3074  break;
3075  case ISD::FABS:
3076  Results.push_back(ExpandFABS(Node));
3077  break;
3078  case ISD::SMIN:
3079  case ISD::SMAX:
3080  case ISD::UMIN:
3081  case ISD::UMAX: {
3082  // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
3083  ISD::CondCode Pred;
3084  switch (Node->getOpcode()) {
3085  default: llvm_unreachable("How did we get here?");
3086  case ISD::SMAX: Pred = ISD::SETGT; break;
3087  case ISD::SMIN: Pred = ISD::SETLT; break;
3088  case ISD::UMAX: Pred = ISD::SETUGT; break;
3089  case ISD::UMIN: Pred = ISD::SETULT; break;
3090  }
3091  Tmp1 = Node->getOperand(0);
3092  Tmp2 = Node->getOperand(1);
3093  Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
3094  Results.push_back(Tmp1);
3095  break;
3096  }
3097  case ISD::FMINNUM:
3098  case ISD::FMAXNUM: {
3099  if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG))
3100  Results.push_back(Expanded);
3101  break;
3102  }
3103  case ISD::FSIN:
3104  case ISD::FCOS: {
3105  EVT VT = Node->getValueType(0);
3106  // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3107  // fcos which share the same operand and both are used.
3108  if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3109  isSinCosLibcallAvailable(Node, TLI))
3110  && useSinCos(Node)) {
3111  SDVTList VTs = DAG.getVTList(VT, VT);
3112  Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3113  if (Node->getOpcode() == ISD::FCOS)
3114  Tmp1 = Tmp1.getValue(1);
3115  Results.push_back(Tmp1);
3116  }
3117  break;
3118  }
3119  case ISD::FMAD:
3120  llvm_unreachable("Illegal fmad should never be formed");
3121 
3122  case ISD::FP16_TO_FP:
3123  if (Node->getValueType(0) != MVT::f32) {
3124  // We can extend to types bigger than f32 in two steps without changing
3125  // the result. Since "f16 -> f32" is much more commonly available, give
3126  // CodeGen the option of emitting that before resorting to a libcall.
3127  SDValue Res =
3128  DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3129  Results.push_back(
3130  DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3131  }
3132  break;
3133  case ISD::FP_TO_FP16:
3134  LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n");
3135  if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) {
3136  SDValue Op = Node->getOperand(0);
3137  MVT SVT = Op.getSimpleValueType();
3138  if ((SVT == MVT::f64 || SVT == MVT::f80) &&
3139  TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) {
3140  // Under fastmath, we can expand this node into a fround followed by
3141  // a float-half conversion.
3142  SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
3143  DAG.getIntPtrConstant(0, dl));
3144  Results.push_back(
3145  DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal));
3146  }
3147  }
3148  break;
3149  case ISD::ConstantFP: {
3150  ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3151  // Check to see if this FP immediate is already legal.
3152  // If this is a legal constant, turn it into a TargetConstantFP node.
3153  if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0),
3154  DAG.getMachineFunction().getFunction().hasOptSize()))
3155  Results.push_back(ExpandConstantFP(CFP, true));
3156  break;
3157  }
3158  case ISD::Constant: {
3159  ConstantSDNode *CP = cast<ConstantSDNode>(Node);
3160  Results.push_back(ExpandConstant(CP));
3161  break;
3162  }
3163  case ISD::FSUB: {
3164  EVT VT = Node->getValueType(0);
3165  if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3166  TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) {
3167  const SDNodeFlags Flags = Node->getFlags();
3168  Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3169  Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
3170  Results.push_back(Tmp1);
3171  }
3172  break;
3173  }
3174  case ISD::SUB: {
3175  EVT VT = Node->getValueType(0);
3176  assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3177  TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3178  "Don't know how to expand this subtraction!");
3179  Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3180  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
3181  VT));
3182  Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
3183  Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3184  break;
3185  }
3186  case ISD::UREM:
3187  case ISD::SREM: {
3188  EVT VT = Node->getValueType(0);
3189  bool isSigned = Node->getOpcode() == ISD::SREM;
3190  unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3191  unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3192  Tmp2 = Node->getOperand(0);
3193  Tmp3 = Node->getOperand(1);
3194  if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3195  SDVTList VTs = DAG.getVTList(VT, VT);
3196  Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3197  Results.push_back(Tmp1);
3198  } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3199  // X % Y -> X-X/Y*Y
3200  Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3201  Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3202  Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3203  Results.push_back(Tmp1);
3204  }
3205  break;
3206  }
3207  case ISD::UDIV:
3208  case ISD::SDIV: {
3209  bool isSigned = Node->getOpcode() == ISD::SDIV;
3210  unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3211  EVT VT = Node->getValueType(0);
3212  if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3213  SDVTList VTs = DAG.getVTList(VT, VT);
3214  Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3215  Node->getOperand(1));
3216  Results.push_back(Tmp1);
3217  }
3218  break;
3219  }
3220  case ISD::MULHU:
3221  case ISD::MULHS: {
3222  unsigned ExpandOpcode =
3224  EVT VT = Node->getValueType(0);
3225  SDVTList VTs = DAG.getVTList(VT, VT);
3226 
3227  Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3228  Node->getOperand(1));
3229  Results.push_back(Tmp1.getValue(1));
3230  break;
3231  }
3232  case ISD::UMUL_LOHI:
3233  case ISD::SMUL_LOHI: {
3234  SDValue LHS = Node->getOperand(0);
3235  SDValue RHS = Node->getOperand(1);
3236  MVT VT = LHS.getSimpleValueType();
3237  unsigned MULHOpcode =
3239 
3240  if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) {
3241  Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS));
3242  Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS));
3243  break;
3244  }
3245 
3246  SmallVector<SDValue, 4> Halves;
3247  EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext());
3248  assert(TLI.isTypeLegal(HalfType));
3249  if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, Node, LHS, RHS, Halves,
3250  HalfType, DAG,
3252  for (unsigned i = 0; i < 2; ++i) {
3253  SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]);
3254  SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]);
3255  SDValue Shift = DAG.getConstant(
3256  HalfType.getScalarSizeInBits(), dl,
3257  TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3258  Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3259  Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3260  }
3261  break;
3262  }
3263  break;
3264  }
3265  case ISD::MUL: {
3266  EVT VT = Node->getValueType(0);
3267  SDVTList VTs = DAG.getVTList(VT, VT);
3268  // See if multiply or divide can be lowered using two-result operations.
3269  // We just need the low half of the multiply; try both the signed
3270  // and unsigned forms. If the target supports both SMUL_LOHI and
3271  // UMUL_LOHI, form a preference by checking which forms of plain
3272  // MULH it supports.
3273  bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3274  bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3275  bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3276  bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3277  unsigned OpToUse = 0;
3278  if (HasSMUL_LOHI && !HasMULHS) {
3279  OpToUse = ISD::SMUL_LOHI;
3280  } else if (HasUMUL_LOHI && !HasMULHU) {
3281  OpToUse = ISD::UMUL_LOHI;
3282  } else if (HasSMUL_LOHI) {
3283  OpToUse = ISD::SMUL_LOHI;
3284  } else if (HasUMUL_LOHI) {
3285  OpToUse = ISD::UMUL_LOHI;
3286  }
3287  if (OpToUse) {
3288  Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3289  Node->getOperand(1)));
3290  break;
3291  }
3292 
3293  SDValue Lo, Hi;
3294  EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3295  if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3296  TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3297  TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3298  TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3299  TLI.expandMUL(Node, Lo, Hi, HalfType, DAG,
3301  Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3302  Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3303  SDValue Shift =
3304  DAG.getConstant(HalfType.getSizeInBits(), dl,
3305  TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3306  Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3307  Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3308  }
3309  break;
3310  }
3311  case ISD::FSHL:
3312  case ISD::FSHR:
3313  if (TLI.expandFunnelShift(Node, Tmp1, DAG))
3314  Results.push_back(Tmp1);
3315  break;
3316  case ISD::ROTL:
3317  case ISD::ROTR:
3318  if (TLI.expandROT(Node, Tmp1, DAG))
3319  Results.push_back(Tmp1);
3320  break;
3321  case ISD::SADDSAT:
3322  case ISD::UADDSAT:
3323  case ISD::SSUBSAT:
3324  case ISD::USUBSAT:
3325  Results.push_back(TLI.expandAddSubSat(Node, DAG));
3326  break;
3327  case ISD::SMULFIX:
3328  case ISD::SMULFIXSAT:
3329  case ISD::UMULFIX:
3330  case ISD::UMULFIXSAT:
3331  Results.push_back(TLI.expandFixedPointMul(Node, DAG));
3332  break;
3333  case ISD::ADDCARRY:
3334  case ISD::SUBCARRY: {
3335  SDValue LHS = Node->getOperand(0);
3336  SDValue RHS = Node->getOperand(1);
3337  SDValue Carry = Node->getOperand(2);
3338 
3339  bool IsAdd = Node->getOpcode() == ISD::ADDCARRY;
3340 
3341  // Initial add of the 2 operands.
3342  unsigned Op = IsAdd ? ISD::ADD : ISD::SUB;
3343  EVT VT = LHS.getValueType();
3344  SDValue Sum = DAG.getNode(Op, dl, VT, LHS, RHS);
3345 
3346  // Initial check for overflow.
3347  EVT CarryType = Node->getValueType(1);
3348  EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3349  ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
3350  SDValue Overflow = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3351 
3352  // Add of the sum and the carry.
3353  SDValue CarryExt =
3354  DAG.getZeroExtendInReg(DAG.getZExtOrTrunc(Carry, dl, VT), dl, MVT::i1);
3355  SDValue Sum2 = DAG.getNode(Op, dl, VT, Sum, CarryExt);
3356 
3357  // Second check for overflow. If we are adding, we can only overflow if the
3358  // initial sum is all 1s ang the carry is set, resulting in a new sum of 0.
3359  // If we are subtracting, we can only overflow if the initial sum is 0 and
3360  // the carry is set, resulting in a new sum of all 1s.
3361  SDValue Zero = DAG.getConstant(0, dl, VT);
3362  SDValue Overflow2 =
3363  IsAdd ? DAG.getSetCC(dl, SetCCType, Sum2, Zero, ISD::SETEQ)
3364  : DAG.getSetCC(dl, SetCCType, Sum, Zero, ISD::SETEQ);
3365  Overflow2 = DAG.getNode(ISD::AND, dl, SetCCType, Overflow2,
3366  DAG.getZExtOrTrunc(Carry, dl, SetCCType));
3367 
3368  SDValue ResultCarry =
3369  DAG.getNode(ISD::OR, dl, SetCCType, Overflow, Overflow2);
3370 
3371  Results.push_back(Sum2);
3372  Results.push_back(DAG.getBoolExtOrTrunc(ResultCarry, dl, CarryType, VT));
3373  break;
3374  }
3375  case ISD::SADDO:
3376  case ISD::SSUBO: {
3377  SDValue Result, Overflow;
3378  TLI.expandSADDSUBO(Node, Result, Overflow, DAG);
3379  Results.push_back(Result);
3380  Results.push_back(Overflow);
3381  break;
3382  }
3383  case ISD::UADDO:
3384  case ISD::USUBO: {
3385  SDValue Result, Overflow;
3386  TLI.expandUADDSUBO(Node, Result, Overflow, DAG);
3387  Results.push_back(Result);
3388  Results.push_back(Overflow);
3389  break;
3390  }
3391  case ISD::UMULO:
3392  case ISD::SMULO: {
3393  SDValue Result, Overflow;
3394  if (TLI.expandMULO(Node, Result, Overflow, DAG)) {
3395  Results.push_back(Result);
3396  Results.push_back(Overflow);
3397  }
3398  break;
3399  }
3400  case ISD::BUILD_PAIR: {
3401  EVT PairTy = Node->getValueType(0);
3402  Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3403  Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3404  Tmp2 = DAG.getNode(
3405  ISD::SHL, dl, PairTy, Tmp2,
3406  DAG.getConstant(PairTy.getSizeInBits() / 2, dl,
3407  TLI.getShiftAmountTy(PairTy, DAG.getDataLayout())));
3408  Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3409  break;
3410  }
3411  case ISD::SELECT:
3412  Tmp1 = Node->getOperand(0);
3413  Tmp2 = Node->getOperand(1);
3414  Tmp3 = Node->getOperand(2);
3415  if (Tmp1.getOpcode() == ISD::SETCC) {
3416  Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3417  Tmp2, Tmp3,
3418  cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3419  } else {
3420  Tmp1 = DAG.getSelectCC(dl, Tmp1,
3421  DAG.getConstant(0, dl, Tmp1.getValueType()),
3422  Tmp2, Tmp3, ISD::SETNE);
3423  }
3424  Tmp1->setFlags(Node->getFlags());
3425  Results.push_back(Tmp1);
3426  break;
3427  case ISD::BR_JT: {
3428  SDValue Chain = Node->getOperand(0);
3429  SDValue Table = Node->getOperand(1);
3430  SDValue Index = Node->getOperand(2);
3431 
3432  const DataLayout &TD = DAG.getDataLayout();
3433  EVT PTy = TLI.getPointerTy(TD);
3434 
3435  unsigned EntrySize =
3436  DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3437 
3438  // For power-of-two jumptable entry sizes convert multiplication to a shift.
3439  // This transformation needs to be done here since otherwise the MIPS
3440  // backend will end up emitting a three instruction multiply sequence
3441  // instead of a single shift and MSP430 will call a runtime function.
3442  if (llvm::isPowerOf2_32(EntrySize))
3443  Index = DAG.getNode(
3444  ISD::SHL, dl, Index.getValueType(), Index,
3445  DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType()));
3446  else
3447  Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
3448  DAG.getConstant(EntrySize, dl, Index.getValueType()));
3449  SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3450  Index, Table);
3451 
3452  EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3453  SDValue LD = DAG.getExtLoad(
3454  ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3455  MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT);
3456  Addr = LD;
3457  if (TLI.isJumpTableRelative()) {
3458  // For PIC, the sequence is:
3459  // BRIND(load(Jumptable + index) + RelocBase)
3460  // RelocBase can be JumpTable, GOT or some sort of global base.
3461  Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3462  TLI.getPICJumpTableRelocBase(Table, DAG));
3463  }
3464 
3465  Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, DAG);
3466  Results.push_back(Tmp1);
3467  break;
3468  }
3469  case ISD::BRCOND:
3470  // Expand brcond's setcc into its constituent parts and create a BR_CC
3471  // Node.
3472  Tmp1 = Node->getOperand(0);
3473  Tmp2 = Node->getOperand(1);
3474  if (Tmp2.getOpcode() == ISD::SETCC) {
3475  Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3476  Tmp1, Tmp2.getOperand(2),
3477  Tmp2.getOperand(0), Tmp2.getOperand(1),
3478  Node->getOperand(2));
3479  } else {
3480  // We test only the i1 bit. Skip the AND if UNDEF or another AND.
3481  if (Tmp2.isUndef() ||
3482  (Tmp2.getOpcode() == ISD::AND &&
3483  isa<ConstantSDNode>(Tmp2.getOperand(1)) &&
3484  cast<ConstantSDNode>(Tmp2.getOperand(1))->getZExtValue() == 1))
3485  Tmp3 = Tmp2;
3486  else
3487  Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3488  DAG.getConstant(1, dl, Tmp2.getValueType()));
3489  Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3490  DAG.getCondCode(ISD::SETNE), Tmp3,
3491  DAG.getConstant(0, dl, Tmp3.getValueType()),
3492  Node->getOperand(2));
3493  }
3494  Results.push_back(Tmp1);
3495  break;
3496  case ISD::SETCC: {
3497  Tmp1 = Node->getOperand(0);
3498  Tmp2 = Node->getOperand(1);
3499  Tmp3 = Node->getOperand(2);
3500  bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2,
3501  Tmp3, NeedInvert, dl);
3502 
3503  if (Legalized) {
3504  // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3505  // condition code, create a new SETCC node.
3506  if (Tmp3.getNode())
3507  Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3508  Tmp1, Tmp2, Tmp3, Node->getFlags());
3509 
3510  // If we expanded the SETCC by inverting the condition code, then wrap
3511  // the existing SETCC in a NOT to restore the intended condition.
3512  if (NeedInvert)
3513  Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3514 
3515  Results.push_back(Tmp1);
3516  break;
3517  }
3518 
3519  // Otherwise, SETCC for the given comparison type must be completely
3520  // illegal; expand it into a SELECT_CC.
3521  EVT VT = Node->getValueType(0);
3522  int TrueValue;
3523  switch (TLI.getBooleanContents(Tmp1.getValueType())) {
3526  TrueValue = 1;
3527  break;
3529  TrueValue = -1;
3530  break;
3531  }
3532  Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3533  DAG.getConstant(TrueValue, dl, VT),
3534  DAG.getConstant(0, dl, VT),
3535  Tmp3);
3536  Tmp1->setFlags(Node->getFlags());
3537  Results.push_back(Tmp1);
3538  break;
3539  }
3540  case ISD::SELECT_CC: {
3541  Tmp1 = Node->getOperand(0); // LHS
3542  Tmp2 = Node->getOperand(1); // RHS
3543  Tmp3 = Node->getOperand(2); // True
3544  Tmp4 = Node->getOperand(3); // False
3545  EVT VT = Node->getValueType(0);
3546  SDValue CC = Node->getOperand(4);
3547  ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3548 
3549  if (TLI.isCondCodeLegalOrCustom(CCOp, Tmp1.getSimpleValueType())) {
3550  // If the condition code is legal, then we need to expand this
3551  // node using SETCC and SELECT.
3552  EVT CmpVT = Tmp1.getValueType();
3553  assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3554  "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3555  "expanded.");
3556  EVT CCVT = getSetCCResultType(CmpVT);
3557  SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC, Node->getFlags());
3558  Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3559  break;
3560  }
3561 
3562  // SELECT_CC is legal, so the condition code must not be.
3563  bool Legalized = false;
3564  // Try to legalize by inverting the condition. This is for targets that
3565  // might support an ordered version of a condition, but not the unordered
3566  // version (or vice versa).
3567  ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp,
3568  Tmp1.getValueType().isInteger());
3569  if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) {
3570  // Use the new condition code and swap true and false
3571  Legalized = true;
3572  Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
3573  Tmp1->setFlags(Node->getFlags());
3574  } else {
3575  // If The inverse is not legal, then try to swap the arguments using
3576  // the inverse condition code.
3577  ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
3578  if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) {
3579  // The swapped inverse condition is legal, so swap true and false,
3580  // lhs and rhs.
3581  Legalized = true;
3582  Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
3583  Tmp1->setFlags(Node->getFlags());
3584  }
3585  }
3586 
3587  if (!Legalized) {
3588  Legalized = LegalizeSetCCCondCode(
3589  getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert,
3590  dl);
3591 
3592  assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
3593 
3594  // If we expanded the SETCC by inverting the condition code, then swap
3595  // the True/False operands to match.
3596  if (NeedInvert)
3597  std::swap(Tmp3, Tmp4);
3598 
3599  // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3600  // condition code, create a new SELECT_CC node.
3601  if (CC.getNode()) {
3602  Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
3603  Tmp1, Tmp2, Tmp3, Tmp4, CC);
3604  } else {
3605  Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
3606  CC = DAG.getCondCode(ISD::SETNE);
3607  Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
3608  Tmp2, Tmp3, Tmp4, CC);
3609  }
3610  Tmp1->setFlags(Node->getFlags());
3611  }
3612  Results.push_back(Tmp1);
3613  break;
3614  }
3615  case ISD::BR_CC: {
3616  Tmp1 = Node->getOperand(0); // Chain
3617  Tmp2 = Node->getOperand(2); // LHS
3618  Tmp3 = Node->getOperand(3); // RHS
3619  Tmp4 = Node->getOperand(1); // CC
3620 
3621  bool Legalized = LegalizeSetCCCondCode(getSetCCResultType(
3622  Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl);
3623  (void)Legalized;
3624  assert(Legalized && "Can't legalize BR_CC with legal condition!");
3625 
3626  assert(!NeedInvert && "Don't know how to invert BR_CC!");
3627 
3628  // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
3629  // node.
3630  if (Tmp4.getNode()) {
3631  Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
3632  Tmp4, Tmp2, Tmp3, Node->getOperand(4));
3633  } else {
3634  Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
3635  Tmp4 = DAG.getCondCode(ISD::SETNE);
3636  Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
3637  Tmp2, Tmp3, Node->getOperand(4));
3638  }
3639  Results.push_back(Tmp1);
3640  break;
3641  }
3642  case ISD::BUILD_VECTOR:
3643  Results.push_back(ExpandBUILD_VECTOR(Node));
3644  break;
3645  case ISD::SRA:
3646  case ISD::SRL:
3647  case ISD::SHL: {
3648  // Scalarize vector SRA/SRL/SHL.
3649  EVT VT = Node->getValueType(0);
3650  assert(VT.isVector() && "Unable to legalize non-vector shift");
3651  assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
3652  unsigned NumElem = VT.getVectorNumElements();
3653 
3654  SmallVector<SDValue, 8> Scalars;
3655  for (unsigned Idx = 0; Idx < NumElem; Idx++) {
3656  SDValue Ex = DAG.getNode(
3657  ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(0),
3658  DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3659  SDValue Sh = DAG.getNode(
3660  ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(1),
3661  DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3662  Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
3663  VT.getScalarType(), Ex, Sh));
3664  }
3665 
3666  SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars);
3667  ReplaceNode(SDValue(Node, 0), Result);
3668  break;
3669  }
3670  case ISD::VECREDUCE_FADD:
3671  case ISD::VECREDUCE_FMUL:
3672  case ISD::VECREDUCE_ADD:
3673  case ISD::VECREDUCE_MUL:
3674  case ISD::VECREDUCE_AND:
3675  case ISD::VECREDUCE_OR:
3676  case ISD::VECREDUCE_XOR:
3677  case ISD::VECREDUCE_SMAX:
3678  case ISD::VECREDUCE_SMIN:
3679  case ISD::VECREDUCE_UMAX:
3680  case ISD::VECREDUCE_UMIN:
3681  case ISD::VECREDUCE_FMAX:
3682  case ISD::VECREDUCE_FMIN:
3683  Results.push_back(TLI.expandVecReduce(Node, DAG));
3684  break;
3686  case ISD::GlobalAddress:
3687  case ISD::GlobalTLSAddress:
3688  case ISD::ExternalSymbol:
3689  case ISD::ConstantPool:
3690  case ISD::JumpTable:
3693  case ISD::INTRINSIC_VOID:
3694  // FIXME: Custom lowering for these operations shouldn't return null!
3695  break;
3696  }
3697 
3698  if (Results.empty() && Node->isStrictFPOpcode()) {
3699  // FIXME: We were asked to expand a strict floating-point operation,
3700  // but there is currently no expansion implemented that would preserve
3701  // the "strict" properties. For now, we just fall back to the non-strict
3702  // version if that is legal on the target. The actual mutation of the
3703  // operation will happen in SelectionDAGISel::DoInstructionSelection.
3704  switch (Node->getOpcode()) {
3705  default:
3706  if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3707  Node->getValueType(0))
3709  return true;
3710  break;
3711  case ISD::STRICT_LRINT:
3712  case ISD::STRICT_LLRINT:
3713  case ISD::STRICT_LROUND:
3714  case ISD::STRICT_LLROUND:
3715  // These are registered by the operand type instead of the value
3716  // type. Reflect that here.
3717  if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3718  Node->getOperand(1).getValueType())
3720  return true;
3721  break;
3722  }
3723  }
3724 
3725  // Replace the original node with the legalized result.
3726  if (Results.empty()) {
3727  LLVM_DEBUG(dbgs() << "Cannot expand node\n");
3728  return false;
3729  }
3730 
3731  LLVM_DEBUG(dbgs() << "Successfully expanded node\n");
3732  ReplaceNode(Node, Results.data());
3733  return true;
3734 }
3735 
3736 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
3737  LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n");
3739  SDLoc dl(Node);
3740  // FIXME: Check flags on the node to see if we can use a finite call.
3741  bool CanUseFiniteLibCall = TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath;
3742  unsigned Opc = Node->getOpcode();
3743  switch (Opc) {
3744  case ISD::ATOMIC_FENCE: {
3745  // If the target didn't lower this, lower it to '__sync_synchronize()' call
3746  // FIXME: handle "fence singlethread" more efficiently.
3748 
3750  CLI.setDebugLoc(dl)
3751  .setChain(Node->getOperand(0))
3752  .setLibCallee(
3753  CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3754  DAG.getExternalSymbol("__sync_synchronize",
3755  TLI.getPointerTy(DAG.getDataLayout())),
3756  std::move(Args));
3757 
3758  std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3759 
3760  Results.push_back(CallResult.second);
3761  break;
3762  }
3763  // By default, atomic intrinsics are marked Legal and lowered. Targets
3764  // which don't support them directly, however, may want libcalls, in which
3765  // case they mark them Expand, and we get here.
3766  case ISD::ATOMIC_SWAP:
3767  case ISD::ATOMIC_LOAD_ADD:
3768  case ISD::ATOMIC_LOAD_SUB:
3769  case ISD::ATOMIC_LOAD_AND:
3770  case ISD::ATOMIC_LOAD_CLR:
3771  case ISD::ATOMIC_LOAD_OR:
3772  case ISD::ATOMIC_LOAD_XOR:
3773  case ISD::ATOMIC_LOAD_NAND:
3774  case ISD::ATOMIC_LOAD_MIN:
3775  case ISD::ATOMIC_LOAD_MAX:
3776  case ISD::ATOMIC_LOAD_UMIN:
3777  case ISD::ATOMIC_LOAD_UMAX:
3778  case ISD::ATOMIC_CMP_SWAP: {
3779  MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
3780  RTLIB::Libcall LC = RTLIB::getSYNC(Opc, VT);
3781  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!");
3782 
3783  std::pair<SDValue, SDValue> Tmp = ExpandChainLibCall(LC, Node, false);
3784  Results.push_back(Tmp.first);
3785  Results.push_back(Tmp.second);
3786  break;
3787  }
3788  case ISD::TRAP: {
3789  // If this operation is not supported, lower it to 'abort()' call
3792  CLI.setDebugLoc(dl)
3793  .setChain(Node->getOperand(0))
3794  .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3795  DAG.getExternalSymbol(
3796  "abort", TLI.getPointerTy(DAG.getDataLayout())),
3797  std::move(Args));
3798  std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3799 
3800  Results.push_back(CallResult.second);
3801  break;
3802  }
3803  case ISD::FMINNUM:
3804  case ISD::STRICT_FMINNUM:
3805  Results.push_back(ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64,
3806  RTLIB::FMIN_F80, RTLIB::FMIN_F128,
3807  RTLIB::FMIN_PPCF128));
3808  break;
3809  case ISD::FMAXNUM:
3810  case ISD::STRICT_FMAXNUM:
3811  Results.push_back(ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64,
3812  RTLIB::FMAX_F80, RTLIB::FMAX_F128,
3813  RTLIB::FMAX_PPCF128));
3814  break;
3815  case ISD::FSQRT:
3816  case ISD::STRICT_FSQRT:
3817  Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3818  RTLIB::SQRT_F80, RTLIB::SQRT_F128,
3819  RTLIB::SQRT_PPCF128));
3820  break;
3821  case ISD::FCBRT:
3822  Results.push_back(ExpandFPLibCall(Node, RTLIB::CBRT_F32, RTLIB::CBRT_F64,
3823  RTLIB::CBRT_F80, RTLIB::CBRT_F128,
3824  RTLIB::CBRT_PPCF128));
3825  break;
3826  case ISD::FSIN:
3827  case ISD::STRICT_FSIN:
3828  Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3829  RTLIB::SIN_F80, RTLIB::SIN_F128,
3830  RTLIB::SIN_PPCF128));
3831  break;
3832  case ISD::FCOS:
3833  case ISD::STRICT_FCOS:
3834  Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3835  RTLIB::COS_F80, RTLIB::COS_F128,
3836  RTLIB::COS_PPCF128));
3837  break;
3838  case ISD::FSINCOS:
3839  // Expand into sincos libcall.
3840  ExpandSinCosLibCall(Node, Results);
3841  break;
3842  case ISD::FLOG:
3843  case ISD::STRICT_FLOG:
3844  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log_finite))
3845  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_FINITE_F32,
3846  RTLIB::LOG_FINITE_F64,
3847  RTLIB::LOG_FINITE_F80,
3848  RTLIB::LOG_FINITE_F128,
3849  RTLIB::LOG_FINITE_PPCF128));
3850  else
3851  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3852  RTLIB::LOG_F80, RTLIB::LOG_F128,
3853  RTLIB::LOG_PPCF128));
3854  break;
3855  case ISD::FLOG2:
3856  case ISD::STRICT_FLOG2:
3857  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log2_finite))
3858  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_FINITE_F32,
3859  RTLIB::LOG2_FINITE_F64,
3860  RTLIB::LOG2_FINITE_F80,
3861  RTLIB::LOG2_FINITE_F128,
3862  RTLIB::LOG2_FINITE_PPCF128));
3863  else
3864  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3865  RTLIB::LOG2_F80, RTLIB::LOG2_F128,
3866  RTLIB::LOG2_PPCF128));
3867  break;
3868  case ISD::FLOG10:
3869  case ISD::STRICT_FLOG10:
3870  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_log10_finite))
3871  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_FINITE_F32,
3872  RTLIB::LOG10_FINITE_F64,
3873  RTLIB::LOG10_FINITE_F80,
3874  RTLIB::LOG10_FINITE_F128,
3875  RTLIB::LOG10_FINITE_PPCF128));
3876  else
3877  Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3878  RTLIB::LOG10_F80, RTLIB::LOG10_F128,
3879  RTLIB::LOG10_PPCF128));
3880  break;
3881  case ISD::FEXP:
3882  case ISD::STRICT_FEXP:
3883  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_exp_finite))
3884  Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_FINITE_F32,
3885  RTLIB::EXP_FINITE_F64,
3886  RTLIB::EXP_FINITE_F80,
3887  RTLIB::EXP_FINITE_F128,
3888  RTLIB::EXP_FINITE_PPCF128));
3889  else
3890  Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3891  RTLIB::EXP_F80, RTLIB::EXP_F128,
3892  RTLIB::EXP_PPCF128));
3893  break;
3894  case ISD::FEXP2:
3895  case ISD::STRICT_FEXP2:
3896  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_exp2_finite))
3897  Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_FINITE_F32,
3898  RTLIB::EXP2_FINITE_F64,
3899  RTLIB::EXP2_FINITE_F80,
3900  RTLIB::EXP2_FINITE_F128,
3901  RTLIB::EXP2_FINITE_PPCF128));
3902  else
3903  Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3904  RTLIB::EXP2_F80, RTLIB::EXP2_F128,
3905  RTLIB::EXP2_PPCF128));
3906  break;
3907  case ISD::FTRUNC:
3908  case ISD::STRICT_FTRUNC:
3909  Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3910  RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
3911  RTLIB::TRUNC_PPCF128));
3912  break;
3913  case ISD::FFLOOR:
3914  case ISD::STRICT_FFLOOR:
3915  Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3916  RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
3917  RTLIB::FLOOR_PPCF128));
3918  break;
3919  case ISD::FCEIL:
3920  case ISD::STRICT_FCEIL:
3921  Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3922  RTLIB::CEIL_F80, RTLIB::CEIL_F128,
3923  RTLIB::CEIL_PPCF128));
3924  break;
3925  case ISD::FRINT:
3926  case ISD::STRICT_FRINT:
3927  Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
3928  RTLIB::RINT_F80, RTLIB::RINT_F128,
3929  RTLIB::RINT_PPCF128));
3930  break;
3931  case ISD::FNEARBYINT:
3933  Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
3934  RTLIB::NEARBYINT_F64,
3935  RTLIB::NEARBYINT_F80,
3936  RTLIB::NEARBYINT_F128,
3937  RTLIB::NEARBYINT_PPCF128));
3938  break;
3939  case ISD::FROUND:
3940  case ISD::STRICT_FROUND:
3941  Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32,
3942  RTLIB::ROUND_F64,
3943  RTLIB::ROUND_F80,
3944  RTLIB::ROUND_F128,
3945  RTLIB::ROUND_PPCF128));
3946  break;
3947  case ISD::FPOWI:
3948  case ISD::STRICT_FPOWI:
3949  Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
3950  RTLIB::POWI_F80, RTLIB::POWI_F128,
3951  RTLIB::POWI_PPCF128));
3952  break;
3953  case ISD::FPOW:
3954  case ISD::STRICT_FPOW:
3955  if (CanUseFiniteLibCall && DAG.getLibInfo().has(LibFunc_pow_finite))
3956  Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_FINITE_F32,
3957  RTLIB::POW_FINITE_F64,
3958  RTLIB::POW_FINITE_F80,
3959  RTLIB::POW_FINITE_F128,
3960  RTLIB::POW_FINITE_PPCF128));
3961  else
3962  Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3963  RTLIB::POW_F80, RTLIB::POW_F128,
3964  RTLIB::POW_PPCF128));
3965  break;
3966  case ISD::LROUND:
3967  case ISD::STRICT_LROUND:
3968  Results.push_back(ExpandArgFPLibCall(Node, RTLIB::LROUND_F32,
3969  RTLIB::LROUND_F64, RTLIB::LROUND_F80,
3970  RTLIB::LROUND_F128,
3971  RTLIB::LROUND_PPCF128));
3972  break;
3973  case ISD::LLROUND:
3974  case ISD::STRICT_LLROUND:
3975  Results.push_back(ExpandArgFPLibCall(Node, RTLIB::LLROUND_F32,
3976  RTLIB::LLROUND_F64, RTLIB::LLROUND_F80,
3977  RTLIB::LLROUND_F128,
3978  RTLIB::LLROUND_PPCF128));
3979  break;
3980  case ISD::LRINT:
3981  case ISD::STRICT_LRINT:
3982  Results.push_back(ExpandArgFPLibCall(Node, RTLIB::LRINT_F32,
3983  RTLIB::LRINT_F64, RTLIB::LRINT_F80,
3984  RTLIB::LRINT_F128,
3985  RTLIB::LRINT_PPCF128));
3986  break;
3987  case ISD::LLRINT:
3988  case ISD::STRICT_LLRINT:
3989  Results.push_back(ExpandArgFPLibCall(Node, RTLIB::LLRINT_F32,
3990  RTLIB::LLRINT_F64, RTLIB::LLRINT_F80,
3991  RTLIB::LLRINT_F128,
3992  RTLIB::LLRINT_PPCF128));
3993  break;
3994  case ISD::FDIV:
3995  Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3996  RTLIB::DIV_F80, RTLIB::DIV_F128,
3997  RTLIB::DIV_PPCF128));
3998  break;
3999  case ISD::FREM:
4000  case ISD::STRICT_FREM:
4001  Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
4002  RTLIB::REM_F80, RTLIB::REM_F128,
4003  RTLIB::REM_PPCF128));
4004  break;
4005  case ISD::FMA:
4006  case ISD::STRICT_FMA:
4007  Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
4008  RTLIB::FMA_F80, RTLIB::FMA_F128,
4009  RTLIB::FMA_PPCF128));
4010  break;
4011  case ISD::FADD:
4012  Results.push_back(ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64,
4013  RTLIB::ADD_F80, RTLIB::ADD_F128,
4014  RTLIB::ADD_PPCF128));
4015  break;
4016  case ISD::FMUL:
4017  Results.push_back(ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64,
4018  RTLIB::MUL_F80, RTLIB::MUL_F128,
4019  RTLIB::MUL_PPCF128));
4020  break;
4021  case ISD::FP16_TO_FP:
4022  if (Node->getValueType(0) == MVT::f32) {
4023  Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
4024  }
4025  break;
4026  case ISD::FP_TO_FP16: {
4027  RTLIB::Libcall LC =
4029  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
4030  Results.push_back(ExpandLibCall(LC, Node, false));
4031  break;
4032  }
4033  case ISD::FSUB:
4034  Results.push_back(ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64,
4035  RTLIB::SUB_F80, RTLIB::SUB_F128,
4036  RTLIB::SUB_PPCF128));
4037  break;
4038  case ISD::SREM:
4039  Results.push_back(ExpandIntLibCall(Node, true,
4040  RTLIB::SREM_I8,
4041  RTLIB::SREM_I16, RTLIB::SREM_I32,
4042  RTLIB::SREM_I64, RTLIB::SREM_I128));
4043  break;
4044  case ISD::UREM:
4045  Results.push_back(ExpandIntLibCall(Node, false,
4046  RTLIB::UREM_I8,
4047  RTLIB::UREM_I16, RTLIB::UREM_I32,
4048  RTLIB::UREM_I64, RTLIB::UREM_I128));
4049  break;
4050  case ISD::SDIV:
4051  Results.push_back(ExpandIntLibCall(Node, true,
4052  RTLIB::SDIV_I8,
4053  RTLIB::SDIV_I16, RTLIB::SDIV_I32,
4054  RTLIB::SDIV_I64, RTLIB::SDIV_I128));
4055  break;
4056  case ISD::UDIV:
4057  Results.push_back(ExpandIntLibCall(Node, false,
4058  RTLIB::UDIV_I8,
4059  RTLIB::UDIV_I16, RTLIB::UDIV_I32,
4060  RTLIB::UDIV_I64, RTLIB::UDIV_I128));
4061  break;
4062  case ISD::SDIVREM:
4063  case ISD::UDIVREM:
4064  // Expand into divrem libcall
4065  ExpandDivRemLibCall(Node, Results);
4066  break;
4067  case ISD::MUL:
4068  Results.push_back(ExpandIntLibCall(Node, false,
4069  RTLIB::MUL_I8,
4070  RTLIB::MUL_I16, RTLIB::MUL_I32,
4071  RTLIB::MUL_I64, RTLIB::MUL_I128));
4072  break;
4073  case ISD::CTLZ_ZERO_UNDEF:
4074  switch (Node->getSimpleValueType(0).SimpleTy) {
4075  default:
4076  llvm_unreachable("LibCall explicitly requested, but not available");
4077  case MVT::i32:
4078  Results.push_back(ExpandLibCall(RTLIB::CTLZ_I32, Node, false));
4079  break;
4080  case MVT::i64:
4081  Results.push_back(ExpandLibCall(RTLIB::CTLZ_I64, Node, false));
4082  break;
4083  case MVT::i128:
4084  Results.push_back(ExpandLibCall(RTLIB::CTLZ_I128, Node, false));
4085  break;
4086  }
4087  break;
4088  }
4089 
4090  // Replace the original node with the legalized result.
4091  if (!Results.empty()) {
4092  LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n");
4093  ReplaceNode(Node, Results.data());
4094  } else
4095  LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n");
4096 }
4097 
4098 // Determine the vector type to use in place of an original scalar element when
4099 // promoting equally sized vectors.
4101  MVT EltVT, MVT NewEltVT) {
4102  unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
4103  MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
4104  assert(TLI.isTypeLegal(MidVT) && "unexpected");
4105  return MidVT;
4106 }
4107 
4108 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4109  LLVM_DEBUG(dbgs() << "Trying to promote node\n");
4111  MVT OVT = Node->getSimpleValueType(0);
4112  if (Node->getOpcode() == ISD::UINT_TO_FP ||
4113  Node->getOpcode() == ISD::SINT_TO_FP ||
4114  Node->getOpcode() == ISD::SETCC ||
4115  Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
4116  Node->getOpcode() == ISD::INSERT_VECTOR_ELT) {
4117  OVT = Node->getOperand(0).getSimpleValueType();
4118  }
4119  if (Node->getOpcode() == ISD::BR_CC)
4120  OVT = Node->getOperand(2).getSimpleValueType();
4121  MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4122  SDLoc dl(Node);
4123  SDValue Tmp1, Tmp2, Tmp3;
4124  switch (Node->getOpcode()) {
4125  case ISD::CTTZ:
4126  case ISD::CTTZ_ZERO_UNDEF:
4127  case ISD::CTLZ:
4128  case ISD::CTLZ_ZERO_UNDEF:
4129  case ISD::CTPOP:
4130  // Zero extend the argument.
4131  Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4132  if (Node->getOpcode() == ISD::CTTZ) {
4133  // The count is the same in the promoted type except if the original
4134  // value was zero. This can be handled by setting the bit just off
4135  // the top of the original type.
4136  auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(),
4137  OVT.getSizeInBits());
4138  Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1,
4139  DAG.getConstant(TopBit, dl, NVT));
4140  }
4141  // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4142  // already the correct result.
4143  Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4144  if (Node->getOpcode() == ISD::CTLZ ||
4145  Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4146  // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4147  Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4148  DAG.getConstant(NVT.getSizeInBits() -
4149  OVT.getSizeInBits(), dl, NVT));
4150  }
4151  Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4152  break;
4153  case ISD::BITREVERSE:
4154  case ISD::BSWAP: {
4155  unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4156  Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4157  Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4158  Tmp1 = DAG.getNode(
4159  ISD::SRL, dl, NVT, Tmp1,
4160  DAG.getConstant(DiffBits, dl,
4161  TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
4162 
4163  Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4164  break;
4165  }
4166  case ISD::FP_TO_UINT:
4167  case ISD::FP_TO_SINT:
4168  Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
4169  Node->getOpcode() == ISD::FP_TO_SINT, dl);
4170  Results.push_back(Tmp1);
4171  break;
4172  case ISD::UINT_TO_FP:
4173  case ISD::SINT_TO_FP:
4174  Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
4175  Node->getOpcode() == ISD::SINT_TO_FP, dl);
4176  Results.push_back(Tmp1);
4177  break;
4178  case ISD::VAARG: {
4179  SDValue Chain = Node->getOperand(0); // Get the chain.
4180  SDValue Ptr = Node->getOperand(1); // Get the pointer.
4181 
4182  unsigned TruncOp;
4183  if (OVT.isVector()) {
4184  TruncOp = ISD::BITCAST;
4185  } else {
4186  assert(OVT.isInteger()
4187  && "VAARG promotion is supported only for vectors or integer types");
4188  TruncOp = ISD::TRUNCATE;
4189  }
4190 
4191  // Perform the larger operation, then convert back
4192  Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4193  Node->getConstantOperandVal(3));
4194  Chain = Tmp1.getValue(1);
4195 
4196  Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4197 
4198  // Modified the chain result - switch anything that used the old chain to
4199  // use the new one.
4200  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4201  DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4202  if (UpdatedNodes) {
4203  UpdatedNodes->insert(Tmp2.getNode());
4204  UpdatedNodes->insert(Chain.getNode());
4205  }
4206  ReplacedNode(Node);
4207  break;
4208  }
4209  case ISD::MUL:
4210  case ISD::SDIV:
4211  case ISD::SREM:
4212  case ISD::UDIV:
4213  case ISD::UREM:
4214  case ISD::AND:
4215  case ISD::OR:
4216  case ISD::XOR: {
4217  unsigned ExtOp, TruncOp;
4218  if (OVT.isVector()) {
4219  ExtOp = ISD::BITCAST;
4220  TruncOp = ISD::BITCAST;
4221  } else {
4222  assert(OVT.isInteger() && "Cannot promote logic operation");
4223 
4224  switch (Node->getOpcode()) {
4225  default:
4226  ExtOp = ISD::ANY_EXTEND;
4227  break;
4228  case ISD::SDIV:
4229  case ISD::SREM:
4230  ExtOp = ISD::SIGN_EXTEND;
4231  break;
4232  case ISD::UDIV:
4233  case ISD::UREM:
4234  ExtOp = ISD::ZERO_EXTEND;
4235  break;
4236  }
4237  TruncOp = ISD::TRUNCATE;
4238  }
4239  // Promote each of the values to the new type.
4240  Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4241  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4242  // Perform the larger operation, then convert back
4243  Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4244  Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4245  break;
4246  }
4247  case ISD::UMUL_LOHI:
4248  case ISD::SMUL_LOHI: {
4249  // Promote to a multiply in a wider integer type.
4250  unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND
4251  : ISD::SIGN_EXTEND;
4252  Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4253  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4254  Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2);
4255 
4256  auto &DL = DAG.getDataLayout();
4257  unsigned OriginalSize = OVT.getScalarSizeInBits();
4258  Tmp2 = DAG.getNode(
4259  ISD::SRL, dl, NVT, Tmp1,
4260  DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT)));
4261  Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4262  Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
4263  break;
4264  }
4265  case ISD::SELECT: {
4266  unsigned ExtOp, TruncOp;
4267  if (Node->getValueType(0).isVector() ||
4268  Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4269  ExtOp = ISD::BITCAST;
4270  TruncOp = ISD::BITCAST;
4271  } else if (Node->getValueType(0).isInteger()) {
4272  ExtOp = ISD::ANY_EXTEND;
4273  TruncOp = ISD::TRUNCATE;
4274  } else {
4275  ExtOp = ISD::FP_EXTEND;
4276  TruncOp = ISD::FP_ROUND;
4277  }
4278  Tmp1 = Node->getOperand(0);
4279  // Promote each of the values to the new type.
4280  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4281  Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4282  // Perform the larger operation, then round down.
4283  Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4284  Tmp1->setFlags(Node->getFlags());
4285  if (TruncOp != ISD::FP_ROUND)
4286  Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4287  else
4288  Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4289  DAG.getIntPtrConstant(0, dl));
4290  Results.push_back(Tmp1);
4291  break;
4292  }
4293  case ISD::VECTOR_SHUFFLE: {
4294  ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4295 
4296  // Cast the two input vectors.
4297  Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4298  Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4299 
4300  // Convert the shuffle mask to the right # elements.
4301  Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4302  Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4303  Results.push_back(Tmp1);
4304  break;
4305  }
4306  case ISD::SETCC: {
4307  unsigned ExtOp = ISD::FP_EXTEND;
4308  if (NVT.isInteger()) {
4309  ISD::CondCode CCCode =
4310  cast<CondCodeSDNode>(Node->getOperand(2))->get();
4312  }
4313  Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4314  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4315  Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), Tmp1,
4316  Tmp2, Node->getOperand(2), Node->getFlags()));
4317  break;
4318  }
4319  case ISD::BR_CC: {
4320  unsigned ExtOp = ISD::FP_EXTEND;
4321  if (NVT.isInteger()) {
4322  ISD::CondCode CCCode =
4323  cast<CondCodeSDNode>(Node->getOperand(1))->get();
4325  }
4326  Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4327  Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
4328  Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
4329  Node->getOperand(0), Node->getOperand(1),
4330  Tmp1, Tmp2, Node->getOperand(4)));
4331  break;
4332  }
4333  case ISD::FADD:
4334  case ISD::FSUB:
4335  case ISD::FMUL:
4336  case ISD::FDIV:
4337  case ISD::FREM:
4338  case ISD::FMINNUM:
4339  case ISD::FMAXNUM:
4340  case ISD::FPOW:
4341  Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4342  Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4343  Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
4344  Node->getFlags());
4345  Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4346  Tmp3, DAG.getIntPtrConstant(0, dl)));
4347  break;
4348  case ISD::FMA:
4349  Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4350  Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4351  Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
4352  Results.push_back(
4353  DAG.getNode(ISD::FP_ROUND, dl, OVT,
4354  DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
4355  DAG.getIntPtrConstant(0, dl)));
4356  break;
4357  case ISD::FCOPYSIGN:
4358  case ISD::FPOWI: {
4359  Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4360  Tmp2 = Node->getOperand(1);
4361  Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4362 
4363  // fcopysign doesn't change anything but the sign bit, so
4364  // (fp_round (fcopysign (fpext a), b))
4365  // is as precise as
4366  // (fp_round (fpext a))
4367  // which is a no-op. Mark it as a TRUNCating FP_ROUND.
4368  const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
4369  Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4370  Tmp3, DAG.getIntPtrConstant(isTrunc, dl)));
4371  break;
4372  }
4373  case ISD::FFLOOR:
4374  case ISD::FCEIL:
4375  case ISD::FRINT:
4376  case ISD::FNEARBYINT:
4377  case ISD::FROUND:
4378  case ISD::FTRUNC:
4379  case ISD::FNEG:
4380  case ISD::FSQRT:
4381  case ISD::FSIN:
4382  case ISD::FCOS:
4383  case ISD::FLOG:
4384  case ISD::FLOG2:
4385  case ISD::FLOG10:
4386  case ISD::FABS:
4387  case ISD::FEXP:
4388  case ISD::FEXP2:
4389  Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4390  Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4391  Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4392  Tmp2, DAG.getIntPtrConstant(0, dl)));
4393  break;
4394  case ISD::BUILD_VECTOR: {
4395  MVT EltVT = OVT.getVectorElementType();
4396  MVT NewEltVT = NVT.getVectorElementType();
4397 
4398  // Handle bitcasts to a different vector type with the same total bit size
4399  //
4400  // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
4401  // =>
4402  // v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
4403 
4404  assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4405  "Invalid promote type for build_vector");
4406  assert(NewEltVT.bitsLT(EltVT) && "not handled");
4407 
4408  MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4409 
4410  SmallVector<SDValue, 8> NewOps;
4411  for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
4412  SDValue Op = Node->getOperand(I);
4413  NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
4414  }
4415 
4416  SDLoc SL(Node);
4417  SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps);
4418  SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4419  Results.push_back(CvtVec);
4420  break;
4421  }
4422  case ISD::EXTRACT_VECTOR_ELT: {
4423  MVT EltVT = OVT.getVectorElementType();
4424  MVT NewEltVT = NVT.getVectorElementType();
4425 
4426  // Handle bitcasts to a different vector type with the same total bit size.
4427  //
4428  // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
4429  // =>
4430  // v4i32:castx = bitcast x:v2i64
4431  //
4432  // i64 = bitcast
4433  // (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
4434  // (i32 (extract_vector_elt castx, (2 * y + 1)))
4435  //
4436 
4437  assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4438  "Invalid promote type for extract_vector_elt");
4439  assert(NewEltVT.bitsLT(EltVT) && "not handled");
4440 
4441  MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4442  unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4443 
4444  SDValue Idx = Node->getOperand(1);
4445  EVT IdxVT = Idx.getValueType();
4446  SDLoc SL(Node);
4447  SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
4448  SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4449 
4450  SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4451 
4452  SmallVector<SDValue, 8> NewOps;
4453  for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4454  SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4455  SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4456 
4457  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4458  CastVec, TmpIdx);
4459  NewOps.push_back(Elt);
4460  }
4461 
4462  SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps);
4463  Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
4464  break;
4465  }
4466  case ISD::INSERT_VECTOR_ELT: {
4467  MVT EltVT = OVT.getVectorElementType();
4468  MVT NewEltVT = NVT.getVectorElementType();
4469 
4470  // Handle bitcasts to a different vector type with the same total bit size
4471  //
4472  // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
4473  // =>
4474  // v4i32:castx = bitcast x:v2i64
4475  // v2i32:casty = bitcast y:i64
4476  //
4477  // v2i64 = bitcast
4478  // (v4i32 insert_vector_elt
4479  // (v4i32 insert_vector_elt v4i32:castx,
4480  // (extract_vector_elt casty, 0), 2 * z),
4481  // (extract_vector_elt casty, 1), (2 * z + 1))
4482 
4483  assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4484  "Invalid promote type for insert_vector_elt");
4485  assert(NewEltVT.bitsLT(EltVT) && "not handled");
4486 
4487  MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4488  unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4489 
4490  SDValue Val = Node->getOperand(1);
4491  SDValue Idx = Node->getOperand(2);
4492  EVT IdxVT = Idx.getValueType();
4493  SDLoc SL(Node);
4494 
4495  SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
4496  SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4497 
4498  SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4499  SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4500 
4501  SDValue NewVec = CastVec;
4502  for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4503  SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4504  SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4505 
4506  SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4507  CastVal, IdxOffset);
4508 
4509  NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
4510  NewVec, Elt, InEltIdx);
4511  }
4512 
4513  Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
4514  break;
4515  }
4516  case ISD::SCALAR_TO_VECTOR: {
4517  MVT EltVT = OVT.getVectorElementType();
4518  MVT NewEltVT = NVT.getVectorElementType();
4519 
4520  // Handle bitcasts to different vector type with the same total bit size.
4521  //
4522  // e.g. v2i64 = scalar_to_vector x:i64
4523  // =>
4524  // concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
4525  //
4526 
4527  MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4528  SDValue Val = Node->getOperand(0);
4529  SDLoc SL(Node);
4530 
4531  SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4532  SDValue Undef = DAG.getUNDEF(MidVT);
4533 
4534  SmallVector<SDValue, 8> NewElts;
4535  NewElts.push_back(CastVal);
4536  for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
4537  NewElts.push_back(Undef);
4538 
4539  SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
4540  SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4541  Results.push_back(CvtVec);
4542  break;
4543  }
4544  case ISD::ATOMIC_SWAP: {
4545  AtomicSDNode *AM = cast<AtomicSDNode>(Node);
4546  SDLoc SL(Node);
4547  SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal());
4548  assert(NVT.getSizeInBits() == OVT.getSizeInBits() &&
4549  "unexpected promotion type");
4550  assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() &&
4551  "unexpected atomic_swap with illegal type");
4552 
4553  SDValue NewAtomic
4554  = DAG.getAtomic(ISD::ATOMIC_SWAP, SL, NVT,
4555  DAG.getVTList(NVT, MVT::Other),
4556  { AM->getChain(), AM->getBasePtr(), CastVal },
4557  AM->getMemOperand());
4558  Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic));
4559  Results.push_back(NewAtomic.getValue(1));
4560  break;
4561  }
4562  }
4563 
4564  // Replace the original node with the legalized result.
4565  if (!Results.empty()) {
4566  LLVM_DEBUG(dbgs() << "Successfully promoted node\n");
4567  ReplaceNode(Node, Results.data());
4568  } else
4569  LLVM_DEBUG(dbgs() << "Could not promote node\n");
4570 }
4571 
4572 /// This is the entry point for the file.
4574  AssignTopologicalOrder();
4575 
4576  SmallPtrSet<SDNode *, 16> LegalizedNodes;
4577  // Use a delete listener to remove nodes which were deleted during
4578  // legalization from LegalizeNodes. This is needed to handle the situation
4579  // where a new node is allocated by the object pool to the same address of a
4580  // previously deleted node.
4581  DAGNodeDeletedListener DeleteListener(
4582  *this,
4583  [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); });
4584 
4585  SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
4586 
4587  // Visit all the nodes. We start in topological order, so that we see
4588  // nodes with their original operands intact. Legalization can produce
4589  // new nodes which may themselves need to be legalized. Iterate until all
4590  // nodes have been legalized.
4591  while (true) {
4592  bool AnyLegalized = false;
4593  for (auto NI = allnodes_end(); NI != allnodes_begin();) {
4594  --NI;
4595 
4596  SDNode *N = &*NI;
4597  if (N->use_empty() && N != getRoot().getNode()) {
4598  ++NI;
4599  DeleteNode(N);
4600  continue;
4601  }
4602 
4603  if (LegalizedNodes.insert(N).second) {
4604  AnyLegalized = true;
4605  Legalizer.LegalizeOp(N);
4606 
4607  if (N->use_empty() && N != getRoot().getNode()) {
4608  ++NI;
4609  DeleteNode(N);
4610  }
4611  }
4612  }
4613  if (!AnyLegalized)
4614  break;
4615 
4616  }
4617 
4618  // Remove dead nodes now.
4619  RemoveDeadNodes();
4620 }
4621 
4623  SmallSetVector<SDNode *, 16> &UpdatedNodes) {
4624  SmallPtrSet<SDNode *, 16> LegalizedNodes;
4625  SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
4626 
4627  // Directly insert the node in question, and legalize it. This will recurse
4628  // as needed through operands.
4629  LegalizedNodes.insert(N);
4630  Legalizer.LegalizeOp(N);
4631 
4632  return LegalizedNodes.count(N);
4633 }
bool LegalizeOp(SDNode *N, SmallSetVector< SDNode *, 16 > &UpdatedNodes)
Transforms a SelectionDAG node and any operands to it into a node that is compatible with the target ...
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
Definition: ISDOpcodes.h:796
static Constant * getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1710
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
Definition: ISDOpcodes.h:596
X = FP_ROUND(Y, TRUNC) - Rounding &#39;Y&#39; from a larger floating point type down to the precision of the ...
Definition: ISDOpcodes.h:570
BUILTIN_OP_END - This must be the last enum value in this list.
Definition: ISDOpcodes.h:914
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:112
FMINNUM/FMAXNUM - Perform floating-point minimum or maximum on two values.
Definition: ISDOpcodes.h:623
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isInteger() const
Return true if this is an integer or a vector integer type.
void setFlags(SDNodeFlags NewFlags)
static bool isConstant(const MachineInstr &MI)
bool isUndef() const
static MachinePointerInfo getJumpTable(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a jump table entry.
Constrained versions of libm-equivalent floating point intrinsics.
Definition: ISDOpcodes.h:300
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant, which is required to be operand #1) half of the integer or float value specified as operand #0.
Definition: ISDOpcodes.h:183
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:561
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool isIndexed() const
Return true if this is a pre/post inc/dec load/store.
NodeType getExtForLoadExtType(bool IsFP, LoadExtType)
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR (an vector value) starting with the ...
Definition: ISDOpcodes.h:390
BR_CC - Conditional branch.
Definition: ISDOpcodes.h:679
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static MVT getVectorVT(MVT VT, unsigned NumElements)
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition: ISDOpcodes.h:399
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition: ValueTypes.h:259
const SDValue & getVal() const
Same as the corresponding unsaturated fixed point instructions, but the result is clamped between the...
Definition: ISDOpcodes.h:284
bool isVector() const
Return true if this is a vector value type.
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
Libcall getSYNC(unsigned Opc, MVT VT)
Return the SYNC_FETCH_AND_* value for the given opcode and type, or UNKNOWN_LIBCALL if there is none...
const SDValue & getBasePtr() const
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
void push_back(const T &Elt)
Definition: SmallVector.h:211
const SDValue & getValue() const
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain...
Definition: ISDOpcodes.h:731
SDVTList getVTList() const
This file contains the declarations for metadata subclasses.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition: ValueTypes.h:252
Libcall
RTLIB::Libcall enum - This enum defines all of the runtime library calls the backend can emit...
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition: ISDOpcodes.h:250
const SDValue & getBasePtr() const
unsigned getVectorNumElements() const
const SDValue & getChain() const
Function Alias Analysis Results
static MVT getPromotedVectorElementType(const TargetLowering &TLI, MVT EltVT, MVT NewEltVT)
unsigned getAlignment() const
Val, Success, OUTCHAIN = ATOMIC_CMP_SWAP_WITH_SUCCESS(INCHAIN, ptr, cmp, swap) N.b.
Definition: ISDOpcodes.h:834
unsigned second
APInt trunc(unsigned width) const
Truncate to new width.
Definition: APInt.cpp:865
static uint32_t Concat[]
MVT getSimpleValueType(unsigned ResNo) const
Return the type of a specified result as a simple type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition: ValueTypes.h:140
F(f)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
static IntegerType * getInt64Ty(LLVMContext &C)
Definition: Type.cpp:181
[US]{MIN/MAX} - Binary minimum or maximum or signed or unsigned integers.
Definition: ISDOpcodes.h:416
const SDNodeFlags getFlags() const
SDNode * getNode() const
get the SDNode which holds the desired result
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
Same for subtraction.
Definition: ISDOpcodes.h:253
void reserve(size_type N)
Definition: SmallVector.h:369
bool isByteSized() const
Return true if the bit size is a multiple of 8.
Definition: ValueTypes.h:211
MachineMemOperand * getMemOperand() const
Return a MachineMemOperand object describing the memory reference performed by operation.
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1 at the ...
Definition: ISDOpcodes.h:385
The address of the GOT.
Definition: ISDOpcodes.h:65
unsigned getValueSizeInBits() const
Returns the size of the value in bits.
OUTCHAIN = ATOMIC_FENCE(INCHAIN, ordering, scope) This corresponds to the fence instruction.
Definition: ISDOpcodes.h:813
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition: ISDOpcodes.h:467
std::pair< MCSymbol *, MachineModuleInfoImpl::StubValueTy > PairTy
Libcall getFPROUND(EVT OpVT, EVT RetVT)
getFPROUND - Return the FPROUND_*_* value for the given types, or UNKNOWN_LIBCALL if there is none...
const ConstantFP * getConstantFPValue() const
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition: ISDOpcodes.h:158
bool isTruncatingStore() const
Return true if the op does a truncation before store.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode *> &Visited, SmallVectorImpl< const SDNode *> &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic...
Definition: ISDOpcodes.h:113
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition: ISDOpcodes.h:209
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition: ValueTypes.h:135
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations...
Definition: ISDOpcodes.h:488
static uint32_t getAlignment(const MCSectionCOFF &Sec)
Shift and rotation operations.
Definition: ISDOpcodes.h:442
Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
Definition: ValueTypes.cpp:264
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth...
Definition: ISDOpcodes.h:425
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
Definition: Type.cpp:659
CallLoweringInfo & setChain(SDValue InChain)
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition: ISDOpcodes.h:190
RESULT = [US]MULFIX(LHS, RHS, SCALE) - Perform fixed point multiplication on 2 integers with the same...
Definition: ISDOpcodes.h:279
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
op_iterator op_end() const
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
FLT_ROUNDS_ - Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest 2 Round to ...
Definition: ISDOpcodes.h:578
SimpleValueType SimpleTy
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence, and carry arbitrary information that target might want to know.
Definition: ISDOpcodes.h:745
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA)...
Definition: ISDOpcodes.h:95
Val, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amt) Val, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN, ptr, amt) For double-word atomic operations: ValLo, ValHi, OUTCHAIN = ATOMIC_SWAP(INCHAIN, ptr, amtLo, amtHi) ValLo, ValHi, OUTCHAIN = ATOMIC_LOAD_[OpName](INCHAIN, ptr, amtLo, amtHi) These correspond to the atomicrmw instruction.
Definition: ISDOpcodes.h:842
const DataLayout & getDataLayout() const
Definition: SelectionDAG.h:417
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG...
Definition: ISDOpcodes.h:72
This is an SDNode representing atomic operations.
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...
This represents a list of ValueType&#39;s that has been intern&#39;d by a SelectionDAG.
STACKSAVE - STACKSAVE has one operand, an input chain.
Definition: ISDOpcodes.h:727
FRAME_TO_ARGS_OFFSET - This node represents offset from frame pointer to first (possible) on-stack ar...
Definition: ISDOpcodes.h:90
unsigned getSizeInBits() const
unsigned getScalarSizeInBits() const
Definition: ValueTypes.h:297
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:291
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition: ISDOpcodes.h:510
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:141
OUTCHAIN = EH_SJLJ_SETUP_DISPATCH(INCHAIN) The target initializes the dispatch table here...
Definition: ISDOpcodes.h:117
falkor hwpf fix Falkor HW Prefetch Fix Late Phase
const TargetMachine & getTarget() const
Definition: SelectionDAG.h:418
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:200
bool bitsLT(MVT VT) const
Return true if this has less bits than VT.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
CallLoweringInfo & setZExtResult(bool Value=true)