LLVM  9.0.0svn
AMDGPUISelLowering.cpp
Go to the documentation of this file.
1 //===-- AMDGPUISelLowering.cpp - AMDGPU Common DAG lowering functions -----===//
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 /// \file
10 /// This is the parent TargetLowering class for hardware code gen
11 /// targets.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #define AMDGPU_LOG2E_F 1.44269504088896340735992468100189214f
16 #define AMDGPU_LN2_F 0.693147180559945309417232121458176568f
17 #define AMDGPU_LN10_F 2.30258509299404568401799145468436421f
18 
19 #include "AMDGPUISelLowering.h"
20 #include "AMDGPU.h"
21 #include "AMDGPUCallLowering.h"
22 #include "AMDGPUFrameLowering.h"
23 #include "AMDGPURegisterInfo.h"
24 #include "AMDGPUSubtarget.h"
25 #include "AMDGPUTargetMachine.h"
26 #include "Utils/AMDGPUBaseInfo.h"
28 #include "SIInstrInfo.h"
29 #include "SIMachineFunctionInfo.h"
31 #include "llvm/CodeGen/Analysis.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DiagnosticInfo.h"
39 #include "llvm/Support/KnownBits.h"
40 using namespace llvm;
41 
42 static bool allocateCCRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
43  CCValAssign::LocInfo LocInfo,
44  ISD::ArgFlagsTy ArgFlags, CCState &State,
45  const TargetRegisterClass *RC,
46  unsigned NumRegs) {
47  ArrayRef<MCPhysReg> RegList = makeArrayRef(RC->begin(), NumRegs);
48  unsigned RegResult = State.AllocateReg(RegList);
49  if (RegResult == AMDGPU::NoRegister)
50  return false;
51 
52  State.addLoc(CCValAssign::getReg(ValNo, ValVT, RegResult, LocVT, LocInfo));
53  return true;
54 }
55 
56 static bool allocateSGPRTuple(unsigned ValNo, MVT ValVT, MVT LocVT,
57  CCValAssign::LocInfo LocInfo,
58  ISD::ArgFlagsTy ArgFlags, CCState &State) {
59  switch (LocVT.SimpleTy) {
60  case MVT::i64:
61  case MVT::f64:
62  case MVT::v2i32:
63  case MVT::v2f32:
64  case MVT::v4i16:
65  case MVT::v4f16: {
66  // Up to SGPR0-SGPR39
67  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
68  &AMDGPU::SGPR_64RegClass, 20);
69  }
70  default:
71  return false;
72  }
73 }
74 
75 // Allocate up to VGPR31.
76 //
77 // TODO: Since there are no VGPR alignent requirements would it be better to
78 // split into individual scalar registers?
79 static bool allocateVGPRTuple(unsigned ValNo, MVT ValVT, MVT LocVT,
80  CCValAssign::LocInfo LocInfo,
81  ISD::ArgFlagsTy ArgFlags, CCState &State) {
82  switch (LocVT.SimpleTy) {
83  case MVT::i64:
84  case MVT::f64:
85  case MVT::v2i32:
86  case MVT::v2f32:
87  case MVT::v4i16:
88  case MVT::v4f16: {
89  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
90  &AMDGPU::VReg_64RegClass, 31);
91  }
92  case MVT::v4i32:
93  case MVT::v4f32:
94  case MVT::v2i64:
95  case MVT::v2f64: {
96  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
97  &AMDGPU::VReg_128RegClass, 29);
98  }
99  case MVT::v8i32:
100  case MVT::v8f32: {
101  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
102  &AMDGPU::VReg_256RegClass, 25);
103 
104  }
105  case MVT::v16i32:
106  case MVT::v16f32: {
107  return allocateCCRegs(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State,
108  &AMDGPU::VReg_512RegClass, 17);
109 
110  }
111  default:
112  return false;
113  }
114 }
115 
116 #include "AMDGPUGenCallingConv.inc"
117 
118 // Find a larger type to do a load / store of a vector with.
120  unsigned StoreSize = VT.getStoreSizeInBits();
121  if (StoreSize <= 32)
122  return EVT::getIntegerVT(Ctx, StoreSize);
123 
124  assert(StoreSize % 32 == 0 && "Store size not a multiple of 32");
125  return EVT::getVectorVT(Ctx, MVT::i32, StoreSize / 32);
126 }
127 
129  EVT VT = Op.getValueType();
130  KnownBits Known = DAG.computeKnownBits(Op);
131  return VT.getSizeInBits() - Known.countMinLeadingZeros();
132 }
133 
135  EVT VT = Op.getValueType();
136 
137  // In order for this to be a signed 24-bit value, bit 23, must
138  // be a sign bit.
139  return VT.getSizeInBits() - DAG.ComputeNumSignBits(Op);
140 }
141 
143  const AMDGPUSubtarget &STI)
144  : TargetLowering(TM), Subtarget(&STI) {
145  // Lower floating point store/load to integer store/load to reduce the number
146  // of patterns in tablegen.
149 
152 
155 
158 
161 
164 
167 
170 
173 
176 
179 
180  // There are no 64-bit extloads. These should be done as a 32-bit extload and
181  // an extension to 64-bit.
182  for (MVT VT : MVT::integer_valuetypes()) {
186  }
187 
188  for (MVT VT : MVT::integer_valuetypes()) {
189  if (VT == MVT::i64)
190  continue;
191 
196 
201 
206  }
207 
208  for (MVT VT : MVT::integer_vector_valuetypes()) {
221  }
222 
227 
232 
237 
240 
243 
246 
249 
252 
255 
258 
261 
264 
267 
270 
275 
280 
285 
288 
291 
294 
297 
298 
303 
306 
307  // This is totally unsupported, just custom lower to produce an error.
309 
310  // Library functions. These default to Expand, but we have instructions
311  // for them.
322 
325 
329 
330 
333 
336 
337  // Expand to fneg + fadd.
339 
358 
362 
363  const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
364  for (MVT VT : ScalarIntVTs) {
365  // These should use [SU]DIVREM, so set them to expand
370 
371  // GPU does not have divrem function for signed or unsigned.
374 
375  // GPU does not have [S|U]MUL_LOHI functions as a single instruction.
378 
382 
383  // AMDGPU uses ADDC/SUBC/ADDE/SUBE
388  }
389 
390  // The hardware supports 32-bit ROTR, but not ROTL.
392  setOperationAction(ISD::ROTL, MVT::i64, Expand);
393  setOperationAction(ISD::ROTR, MVT::i64, Expand);
394 
395  setOperationAction(ISD::MUL, MVT::i64, Expand);
403 
408 
409  setOperationAction(ISD::CTTZ, MVT::i64, Custom);
411  setOperationAction(ISD::CTLZ, MVT::i64, Custom);
413 
414  static const MVT::SimpleValueType VectorIntTypes[] = {
416  };
417 
418  for (MVT VT : VectorIntTypes) {
419  // Expand the following operations for the current type by default.
454  }
455 
456  static const MVT::SimpleValueType FloatVectorTypes[] = {
458  };
459 
460  for (MVT VT : FloatVectorTypes) {
491  }
492 
493  // This causes using an unrolled select operation rather than expansion with
494  // bit operations. This is in general better, but the alternative using BFI
495  // instructions may be better if the select sources are SGPRs.
498 
501 
504 
505  setOperationAction(ISD::SELECT, MVT::v5f32, Promote);
506  AddPromotedToType(ISD::SELECT, MVT::v5f32, MVT::v5i32);
507 
508  // There are no libcalls of any kind.
509  for (int I = 0; I < RTLIB::UNKNOWN_LIBCALL; ++I)
510  setLibcallName(static_cast<RTLIB::Libcall>(I), nullptr);
511 
514 
516  setJumpIsExpensive(true);
517 
518  // FIXME: This is only partially true. If we have to do vector compares, any
519  // SGPR pair can be a condition register. If we have a uniform condition, we
520  // are better off doing SALU operations, where there is only one SCC. For now,
521  // we don't have a way of knowing during instruction selection if a condition
522  // will be uniform and we always use vector compares. Assume we are using
523  // vector compares until that is fixed.
525 
527 
528  // We want to find all load dependencies for long chains of stores to enable
529  // merging into very wide vectors. The problem is with vectors with > 4
530  // elements. MergeConsecutiveStores will attempt to merge these because x8/x16
531  // vectors are a legal type, even though we have to split the loads
532  // usually. When we can more precisely specify load legality per address
533  // space, we should be able to make FindBetterChain/MergeConsecutiveStores
534  // smarter so that they can figure out what to do in 2 iterations without all
535  // N > 4 stores on the same chain.
537 
538  // memcpy/memmove/memset are expanded in the IR, so we shouldn't need to worry
539  // about these during lowering.
540  MaxStoresPerMemcpy = 0xffffffff;
541  MaxStoresPerMemmove = 0xffffffff;
542  MaxStoresPerMemset = 0xffffffff;
543 
561 }
562 
563 //===----------------------------------------------------------------------===//
564 // Target Information
565 //===----------------------------------------------------------------------===//
566 
568 static bool fnegFoldsIntoOp(unsigned Opc) {
569  switch (Opc) {
570  case ISD::FADD:
571  case ISD::FSUB:
572  case ISD::FMUL:
573  case ISD::FMA:
574  case ISD::FMAD:
575  case ISD::FMINNUM:
576  case ISD::FMAXNUM:
577  case ISD::FMINNUM_IEEE:
578  case ISD::FMAXNUM_IEEE:
579  case ISD::FSIN:
580  case ISD::FTRUNC:
581  case ISD::FRINT:
582  case ISD::FNEARBYINT:
583  case ISD::FCANONICALIZE:
584  case AMDGPUISD::RCP:
587  case AMDGPUISD::SIN_HW:
591  case AMDGPUISD::FMED3:
592  return true;
593  default:
594  return false;
595  }
596 }
597 
598 /// \p returns true if the operation will definitely need to use a 64-bit
599 /// encoding, and thus will use a VOP3 encoding regardless of the source
600 /// modifiers.
602 static bool opMustUseVOP3Encoding(const SDNode *N, MVT VT) {
603  return N->getNumOperands() > 2 || VT == MVT::f64;
604 }
605 
606 // Most FP instructions support source modifiers, but this could be refined
607 // slightly.
609 static bool hasSourceMods(const SDNode *N) {
610  if (isa<MemSDNode>(N))
611  return false;
612 
613  switch (N->getOpcode()) {
614  case ISD::CopyToReg:
615  case ISD::SELECT:
616  case ISD::FDIV:
617  case ISD::FREM:
618  case ISD::INLINEASM:
619  case ISD::INLINEASM_BR:
623 
624  // TODO: Should really be looking at the users of the bitcast. These are
625  // problematic because bitcasts are used to legalize all stores to integer
626  // types.
627  case ISD::BITCAST:
628  return false;
629  default:
630  return true;
631  }
632 }
633 
635  unsigned CostThreshold) {
636  // Some users (such as 3-operand FMA/MAD) must use a VOP3 encoding, and thus
637  // it is truly free to use a source modifier in all cases. If there are
638  // multiple users but for each one will necessitate using VOP3, there will be
639  // a code size increase. Try to avoid increasing code size unless we know it
640  // will save on the instruction count.
641  unsigned NumMayIncreaseSize = 0;
642  MVT VT = N->getValueType(0).getScalarType().getSimpleVT();
643 
644  // XXX - Should this limit number of uses to check?
645  for (const SDNode *U : N->uses()) {
646  if (!hasSourceMods(U))
647  return false;
648 
649  if (!opMustUseVOP3Encoding(U, VT)) {
650  if (++NumMayIncreaseSize > CostThreshold)
651  return false;
652  }
653  }
654 
655  return true;
656 }
657 
659  return MVT::i32;
660 }
661 
663  return true;
664 }
665 
666 // The backend supports 32 and 64 bit floating point immediates.
667 // FIXME: Why are we reporting vectors of FP immediates as legal?
669  bool ForCodeSize) const {
670  EVT ScalarVT = VT.getScalarType();
671  return (ScalarVT == MVT::f32 || ScalarVT == MVT::f64 ||
672  (ScalarVT == MVT::f16 && Subtarget->has16BitInsts()));
673 }
674 
675 // We don't want to shrink f64 / f32 constants.
677  EVT ScalarVT = VT.getScalarType();
678  return (ScalarVT != MVT::f32 && ScalarVT != MVT::f64);
679 }
680 
682  ISD::LoadExtType ExtTy,
683  EVT NewVT) const {
684  // TODO: This may be worth removing. Check regression tests for diffs.
685  if (!TargetLoweringBase::shouldReduceLoadWidth(N, ExtTy, NewVT))
686  return false;
687 
688  unsigned NewSize = NewVT.getStoreSizeInBits();
689 
690  // If we are reducing to a 32-bit load, this is always better.
691  if (NewSize == 32)
692  return true;
693 
694  EVT OldVT = N->getValueType(0);
695  unsigned OldSize = OldVT.getStoreSizeInBits();
696 
697  MemSDNode *MN = cast<MemSDNode>(N);
698  unsigned AS = MN->getAddressSpace();
699  // Do not shrink an aligned scalar load to sub-dword.
700  // Scalar engine cannot do sub-dword loads.
701  if (OldSize >= 32 && NewSize < 32 && MN->getAlignment() >= 4 &&
704  (isa<LoadSDNode>(N) &&
705  AS == AMDGPUAS::GLOBAL_ADDRESS && MN->isInvariant())) &&
707  return false;
708 
709  // Don't produce extloads from sub 32-bit types. SI doesn't have scalar
710  // extloads, so doing one requires using a buffer_load. In cases where we
711  // still couldn't use a scalar load, using the wider load shouldn't really
712  // hurt anything.
713 
714  // If the old size already had to be an extload, there's no harm in continuing
715  // to reduce the width.
716  return (OldSize < 32);
717 }
718 
720  EVT CastTy) const {
721 
722  assert(LoadTy.getSizeInBits() == CastTy.getSizeInBits());
723 
724  if (LoadTy.getScalarType() == MVT::i32)
725  return false;
726 
727  unsigned LScalarSize = LoadTy.getScalarSizeInBits();
728  unsigned CastScalarSize = CastTy.getScalarSizeInBits();
729 
730  return (LScalarSize < CastScalarSize) ||
731  (CastScalarSize >= 32);
732 }
733 
734 // SI+ has instructions for cttz / ctlz for 32-bit values. This is probably also
735 // profitable with the expansion for 64-bit since it's generally good to
736 // speculate things.
737 // FIXME: These should really have the size as a parameter.
739  return true;
740 }
741 
743  return true;
744 }
745 
747  switch (N->getOpcode()) {
748  default:
749  return false;
750  case ISD::EntryToken:
751  case ISD::TokenFactor:
752  return true;
754  {
755  unsigned IntrID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
756  switch (IntrID) {
757  default:
758  return false;
759  case Intrinsic::amdgcn_readfirstlane:
760  case Intrinsic::amdgcn_readlane:
761  return true;
762  }
763  }
764  break;
765  case ISD::LOAD:
766  {
767  const LoadSDNode * L = dyn_cast<LoadSDNode>(N);
768  if (L->getMemOperand()->getAddrSpace()
770  return true;
771  return false;
772  }
773  break;
774  }
775 }
776 
777 //===---------------------------------------------------------------------===//
778 // Target Properties
779 //===---------------------------------------------------------------------===//
780 
782  assert(VT.isFloatingPoint());
783 
784  // Packed operations do not have a fabs modifier.
785  return VT == MVT::f32 || VT == MVT::f64 ||
786  (Subtarget->has16BitInsts() && VT == MVT::f16);
787 }
788 
790  assert(VT.isFloatingPoint());
791  return VT == MVT::f32 || VT == MVT::f64 ||
792  (Subtarget->has16BitInsts() && VT == MVT::f16) ||
793  (Subtarget->hasVOP3PInsts() && VT == MVT::v2f16);
794 }
795 
797  unsigned NumElem,
798  unsigned AS) const {
799  return true;
800 }
801 
803  // There are few operations which truly have vector input operands. Any vector
804  // operation is going to involve operations on each component, and a
805  // build_vector will be a copy per element, so it always makes sense to use a
806  // build_vector input in place of the extracted element to avoid a copy into a
807  // super register.
808  //
809  // We should probably only do this if all users are extracts only, but this
810  // should be the common case.
811  return true;
812 }
813 
815  // Truncate is just accessing a subregister.
816 
817  unsigned SrcSize = Source.getSizeInBits();
818  unsigned DestSize = Dest.getSizeInBits();
819 
820  return DestSize < SrcSize && DestSize % 32 == 0 ;
821 }
822 
824  // Truncate is just accessing a subregister.
825 
826  unsigned SrcSize = Source->getScalarSizeInBits();
827  unsigned DestSize = Dest->getScalarSizeInBits();
828 
829  if (DestSize== 16 && Subtarget->has16BitInsts())
830  return SrcSize >= 32;
831 
832  return DestSize < SrcSize && DestSize % 32 == 0;
833 }
834 
835 bool AMDGPUTargetLowering::isZExtFree(Type *Src, Type *Dest) const {
836  unsigned SrcSize = Src->getScalarSizeInBits();
837  unsigned DestSize = Dest->getScalarSizeInBits();
838 
839  if (SrcSize == 16 && Subtarget->has16BitInsts())
840  return DestSize >= 32;
841 
842  return SrcSize == 32 && DestSize == 64;
843 }
844 
845 bool AMDGPUTargetLowering::isZExtFree(EVT Src, EVT Dest) const {
846  // Any register load of a 64-bit value really requires 2 32-bit moves. For all
847  // practical purposes, the extra mov 0 to load a 64-bit is free. As used,
848  // this will enable reducing 64-bit operations the 32-bit, which is always
849  // good.
850 
851  if (Src == MVT::i16)
852  return Dest == MVT::i32 ||Dest == MVT::i64 ;
853 
854  return Src == MVT::i32 && Dest == MVT::i64;
855 }
856 
858  return isZExtFree(Val.getValueType(), VT2);
859 }
860 
862  // There aren't really 64-bit registers, but pairs of 32-bit ones and only a
863  // limited number of native 64-bit operations. Shrinking an operation to fit
864  // in a single 32-bit register should always be helpful. As currently used,
865  // this is much less general than the name suggests, and is only used in
866  // places trying to reduce the sizes of loads. Shrinking loads to < 32-bits is
867  // not profitable, and may actually be harmful.
868  return SrcVT.getSizeInBits() > 32 && DestVT.getSizeInBits() == 32;
869 }
870 
871 //===---------------------------------------------------------------------===//
872 // TargetLowering Callbacks
873 //===---------------------------------------------------------------------===//
874 
876  bool IsVarArg) {
877  switch (CC) {
885  return CC_AMDGPU;
886  case CallingConv::C:
887  case CallingConv::Fast:
888  case CallingConv::Cold:
889  return CC_AMDGPU_Func;
892  default:
893  report_fatal_error("Unsupported calling convention for call");
894  }
895 }
896 
898  bool IsVarArg) {
899  switch (CC) {
902  llvm_unreachable("kernels should not be handled here");
910  return RetCC_SI_Shader;
911  case CallingConv::C:
912  case CallingConv::Fast:
913  case CallingConv::Cold:
914  return RetCC_AMDGPU_Func;
915  default:
916  report_fatal_error("Unsupported calling convention.");
917  }
918 }
919 
920 /// The SelectionDAGBuilder will automatically promote function arguments
921 /// with illegal types. However, this does not work for the AMDGPU targets
922 /// since the function arguments are stored in memory as these illegal types.
923 /// In order to handle this properly we need to get the original types sizes
924 /// from the LLVM IR Function and fixup the ISD:InputArg values before
925 /// passing them to AnalyzeFormalArguments()
926 
927 /// When the SelectionDAGBuilder computes the Ins, it takes care of splitting
928 /// input values across multiple registers. Each item in the Ins array
929 /// represents a single value that will be stored in registers. Ins[x].VT is
930 /// the value type of the value that will be stored in the register, so
931 /// whatever SDNode we lower the argument to needs to be this type.
932 ///
933 /// In order to correctly lower the arguments we need to know the size of each
934 /// argument. Since Ins[x].VT gives us the size of the register that will
935 /// hold the value, we need to look at Ins[x].ArgVT to see the 'real' type
936 /// for the orignal function argument so that we can deduce the correct memory
937 /// type to use for Ins[x]. In most cases the correct memory type will be
938 /// Ins[x].ArgVT. However, this will not always be the case. If, for example,
939 /// we have a kernel argument of type v8i8, this argument will be split into
940 /// 8 parts and each part will be represented by its own item in the Ins array.
941 /// For each part the Ins[x].ArgVT will be the v8i8, which is the full type of
942 /// the argument before it was split. From this, we deduce that the memory type
943 /// for each individual part is i8. We pass the memory type as LocVT to the
944 /// calling convention analysis function and the register type (Ins[x].VT) as
945 /// the ValVT.
947  CCState &State,
948  const SmallVectorImpl<ISD::InputArg> &Ins) const {
949  const MachineFunction &MF = State.getMachineFunction();
950  const Function &Fn = MF.getFunction();
951  LLVMContext &Ctx = Fn.getParent()->getContext();
953  const unsigned ExplicitOffset = ST.getExplicitKernelArgOffset(Fn);
955 
956  unsigned MaxAlign = 1;
957  uint64_t ExplicitArgOffset = 0;
958  const DataLayout &DL = Fn.getParent()->getDataLayout();
959 
960  unsigned InIndex = 0;
961 
962  for (const Argument &Arg : Fn.args()) {
963  Type *BaseArgTy = Arg.getType();
964  unsigned Align = DL.getABITypeAlignment(BaseArgTy);
965  MaxAlign = std::max(Align, MaxAlign);
966  unsigned AllocSize = DL.getTypeAllocSize(BaseArgTy);
967 
968  uint64_t ArgOffset = alignTo(ExplicitArgOffset, Align) + ExplicitOffset;
969  ExplicitArgOffset = alignTo(ExplicitArgOffset, Align) + AllocSize;
970 
971  // We're basically throwing away everything passed into us and starting over
972  // to get accurate in-memory offsets. The "PartOffset" is completely useless
973  // to us as computed in Ins.
974  //
975  // We also need to figure out what type legalization is trying to do to get
976  // the correct memory offsets.
977 
978  SmallVector<EVT, 16> ValueVTs;
980  ComputeValueVTs(*this, DL, BaseArgTy, ValueVTs, &Offsets, ArgOffset);
981 
982  for (unsigned Value = 0, NumValues = ValueVTs.size();
983  Value != NumValues; ++Value) {
984  uint64_t BasePartOffset = Offsets[Value];
985 
986  EVT ArgVT = ValueVTs[Value];
987  EVT MemVT = ArgVT;
988  MVT RegisterVT = getRegisterTypeForCallingConv(Ctx, CC, ArgVT);
989  unsigned NumRegs = getNumRegistersForCallingConv(Ctx, CC, ArgVT);
990 
991  if (NumRegs == 1) {
992  // This argument is not split, so the IR type is the memory type.
993  if (ArgVT.isExtended()) {
994  // We have an extended type, like i24, so we should just use the
995  // register type.
996  MemVT = RegisterVT;
997  } else {
998  MemVT = ArgVT;
999  }
1000  } else if (ArgVT.isVector() && RegisterVT.isVector() &&
1001  ArgVT.getScalarType() == RegisterVT.getScalarType()) {
1002  assert(ArgVT.getVectorNumElements() > RegisterVT.getVectorNumElements());
1003  // We have a vector value which has been split into a vector with
1004  // the same scalar type, but fewer elements. This should handle
1005  // all the floating-point vector types.
1006  MemVT = RegisterVT;
1007  } else if (ArgVT.isVector() &&
1008  ArgVT.getVectorNumElements() == NumRegs) {
1009  // This arg has been split so that each element is stored in a separate
1010  // register.
1011  MemVT = ArgVT.getScalarType();
1012  } else if (ArgVT.isExtended()) {
1013  // We have an extended type, like i65.
1014  MemVT = RegisterVT;
1015  } else {
1016  unsigned MemoryBits = ArgVT.getStoreSizeInBits() / NumRegs;
1017  assert(ArgVT.getStoreSizeInBits() % NumRegs == 0);
1018  if (RegisterVT.isInteger()) {
1019  MemVT = EVT::getIntegerVT(State.getContext(), MemoryBits);
1020  } else if (RegisterVT.isVector()) {
1021  assert(!RegisterVT.getScalarType().isFloatingPoint());
1022  unsigned NumElements = RegisterVT.getVectorNumElements();
1023  assert(MemoryBits % NumElements == 0);
1024  // This vector type has been split into another vector type with
1025  // a different elements size.
1026  EVT ScalarVT = EVT::getIntegerVT(State.getContext(),
1027  MemoryBits / NumElements);
1028  MemVT = EVT::getVectorVT(State.getContext(), ScalarVT, NumElements);
1029  } else {
1030  llvm_unreachable("cannot deduce memory type.");
1031  }
1032  }
1033 
1034  // Convert one element vectors to scalar.
1035  if (MemVT.isVector() && MemVT.getVectorNumElements() == 1)
1036  MemVT = MemVT.getScalarType();
1037 
1038  // Round up vec3/vec5 argument.
1039  if (MemVT.isVector() && !MemVT.isPow2VectorType()) {
1040  assert(MemVT.getVectorNumElements() == 3 ||
1041  MemVT.getVectorNumElements() == 5);
1042  MemVT = MemVT.getPow2VectorType(State.getContext());
1043  }
1044 
1045  unsigned PartOffset = 0;
1046  for (unsigned i = 0; i != NumRegs; ++i) {
1047  State.addLoc(CCValAssign::getCustomMem(InIndex++, RegisterVT,
1048  BasePartOffset + PartOffset,
1049  MemVT.getSimpleVT(),
1051  PartOffset += MemVT.getStoreSize();
1052  }
1053  }
1054  }
1055 }
1056 
1058  SDValue Chain, CallingConv::ID CallConv,
1059  bool isVarArg,
1060  const SmallVectorImpl<ISD::OutputArg> &Outs,
1061  const SmallVectorImpl<SDValue> &OutVals,
1062  const SDLoc &DL, SelectionDAG &DAG) const {
1063  // FIXME: Fails for r600 tests
1064  //assert(!isVarArg && Outs.empty() && OutVals.empty() &&
1065  // "wave terminate should not have return values");
1066  return DAG.getNode(AMDGPUISD::ENDPGM, DL, MVT::Other, Chain);
1067 }
1068 
1069 //===---------------------------------------------------------------------===//
1070 // Target specific lowering
1071 //===---------------------------------------------------------------------===//
1072 
1073 /// Selects the correct CCAssignFn for a given CallingConvention value.
1075  bool IsVarArg) {
1076  return AMDGPUCallLowering::CCAssignFnForCall(CC, IsVarArg);
1077 }
1078 
1080  bool IsVarArg) {
1081  return AMDGPUCallLowering::CCAssignFnForReturn(CC, IsVarArg);
1082 }
1083 
1085  SelectionDAG &DAG,
1086  MachineFrameInfo &MFI,
1087  int ClobberedFI) const {
1088  SmallVector<SDValue, 8> ArgChains;
1089  int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
1090  int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
1091 
1092  // Include the original chain at the beginning of the list. When this is
1093  // used by target LowerCall hooks, this helps legalize find the
1094  // CALLSEQ_BEGIN node.
1095  ArgChains.push_back(Chain);
1096 
1097  // Add a chain value for each stack argument corresponding
1098  for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1099  UE = DAG.getEntryNode().getNode()->use_end();
1100  U != UE; ++U) {
1101  if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) {
1102  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) {
1103  if (FI->getIndex() < 0) {
1104  int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
1105  int64_t InLastByte = InFirstByte;
1106  InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
1107 
1108  if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1109  (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1110  ArgChains.push_back(SDValue(L, 1));
1111  }
1112  }
1113  }
1114  }
1115 
1116  // Build a tokenfactor for all the chains.
1117  return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
1118 }
1119 
1121  SmallVectorImpl<SDValue> &InVals,
1122  StringRef Reason) const {
1123  SDValue Callee = CLI.Callee;
1124  SelectionDAG &DAG = CLI.DAG;
1125 
1126  const Function &Fn = DAG.getMachineFunction().getFunction();
1127 
1128  StringRef FuncName("<unknown>");
1129 
1130  if (const ExternalSymbolSDNode *G = dyn_cast<ExternalSymbolSDNode>(Callee))
1131  FuncName = G->getSymbol();
1132  else if (const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1133  FuncName = G->getGlobal()->getName();
1134 
1135  DiagnosticInfoUnsupported NoCalls(
1136  Fn, Reason + FuncName, CLI.DL.getDebugLoc());
1137  DAG.getContext()->diagnose(NoCalls);
1138 
1139  if (!CLI.IsTailCall) {
1140  for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
1141  InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
1142  }
1143 
1144  return DAG.getEntryNode();
1145 }
1146 
1148  SmallVectorImpl<SDValue> &InVals) const {
1149  return lowerUnhandledCall(CLI, InVals, "unsupported call to function ");
1150 }
1151 
1153  SelectionDAG &DAG) const {
1154  const Function &Fn = DAG.getMachineFunction().getFunction();
1155 
1156  DiagnosticInfoUnsupported NoDynamicAlloca(Fn, "unsupported dynamic alloca",
1157  SDLoc(Op).getDebugLoc());
1158  DAG.getContext()->diagnose(NoDynamicAlloca);
1159  auto Ops = {DAG.getConstant(0, SDLoc(), Op.getValueType()), Op.getOperand(0)};
1160  return DAG.getMergeValues(Ops, SDLoc());
1161 }
1162 
1164  SelectionDAG &DAG) const {
1165  switch (Op.getOpcode()) {
1166  default:
1167  Op->print(errs(), &DAG);
1168  llvm_unreachable("Custom lowering code for this"
1169  "instruction is not implemented yet!");
1170  break;
1171  case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
1172  case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
1173  case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
1174  case ISD::UDIVREM: return LowerUDIVREM(Op, DAG);
1175  case ISD::SDIVREM: return LowerSDIVREM(Op, DAG);
1176  case ISD::FREM: return LowerFREM(Op, DAG);
1177  case ISD::FCEIL: return LowerFCEIL(Op, DAG);
1178  case ISD::FTRUNC: return LowerFTRUNC(Op, DAG);
1179  case ISD::FRINT: return LowerFRINT(Op, DAG);
1180  case ISD::FNEARBYINT: return LowerFNEARBYINT(Op, DAG);
1181  case ISD::FROUND: return LowerFROUND(Op, DAG);
1182  case ISD::FFLOOR: return LowerFFLOOR(Op, DAG);
1183  case ISD::FLOG:
1184  return LowerFLOG(Op, DAG, 1 / AMDGPU_LOG2E_F);
1185  case ISD::FLOG10:
1186  return LowerFLOG(Op, DAG, AMDGPU_LN2_F / AMDGPU_LN10_F);
1187  case ISD::FEXP:
1188  return lowerFEXP(Op, DAG);
1189  case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
1190  case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
1191  case ISD::FP_TO_FP16: return LowerFP_TO_FP16(Op, DAG);
1192  case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
1193  case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
1194  case ISD::CTTZ:
1195  case ISD::CTTZ_ZERO_UNDEF:
1196  case ISD::CTLZ:
1197  case ISD::CTLZ_ZERO_UNDEF:
1198  return LowerCTLZ_CTTZ(Op, DAG);
1199  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1200  }
1201  return Op;
1202 }
1203 
1206  SelectionDAG &DAG) const {
1207  switch (N->getOpcode()) {
1209  // Different parts of legalization seem to interpret which type of
1210  // sign_extend_inreg is the one to check for custom lowering. The extended
1211  // from type is what really matters, but some places check for custom
1212  // lowering of the result type. This results in trying to use
1213  // ReplaceNodeResults to sext_in_reg to an illegal type, so we'll just do
1214  // nothing here and let the illegal result integer be handled normally.
1215  return;
1216  default:
1217  return;
1218  }
1219 }
1220 
1221 static bool hasDefinedInitializer(const GlobalValue *GV) {
1222  const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
1223  if (!GVar || !GVar->hasInitializer())
1224  return false;
1225 
1226  return !isa<UndefValue>(GVar->getInitializer());
1227 }
1228 
1230  SDValue Op,
1231  SelectionDAG &DAG) const {
1232 
1233  const DataLayout &DL = DAG.getDataLayout();
1234  GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Op);
1235  const GlobalValue *GV = G->getGlobal();
1236 
1239  if (!MFI->isEntryFunction()) {
1240  const Function &Fn = DAG.getMachineFunction().getFunction();
1241  DiagnosticInfoUnsupported BadLDSDecl(
1242  Fn, "local memory global used by non-kernel function", SDLoc(Op).getDebugLoc());
1243  DAG.getContext()->diagnose(BadLDSDecl);
1244  }
1245 
1246  // XXX: What does the value of G->getOffset() mean?
1247  assert(G->getOffset() == 0 &&
1248  "Do not know what to do with an non-zero offset");
1249 
1250  // TODO: We could emit code to handle the initialization somewhere.
1251  if (!hasDefinedInitializer(GV)) {
1252  unsigned Offset = MFI->allocateLDSGlobal(DL, *GV);
1253  return DAG.getConstant(Offset, SDLoc(Op), Op.getValueType());
1254  }
1255  }
1256 
1257  const Function &Fn = DAG.getMachineFunction().getFunction();
1258  DiagnosticInfoUnsupported BadInit(
1259  Fn, "unsupported initializer for address space", SDLoc(Op).getDebugLoc());
1260  DAG.getContext()->diagnose(BadInit);
1261  return SDValue();
1262 }
1263 
1265  SelectionDAG &DAG) const {
1267 
1268  EVT VT = Op.getValueType();
1269  if (VT == MVT::v4i16 || VT == MVT::v4f16) {
1270  SDLoc SL(Op);
1271  SDValue Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(0));
1272  SDValue Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Op.getOperand(1));
1273 
1274  SDValue BV = DAG.getBuildVector(MVT::v2i32, SL, { Lo, Hi });
1275  return DAG.getNode(ISD::BITCAST, SL, VT, BV);
1276  }
1277 
1278  for (const SDUse &U : Op->ops())
1279  DAG.ExtractVectorElements(U.get(), Args);
1280 
1281  return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1282 }
1283 
1285  SelectionDAG &DAG) const {
1286 
1288  unsigned Start = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1289  EVT VT = Op.getValueType();
1290  DAG.ExtractVectorElements(Op.getOperand(0), Args, Start,
1291  VT.getVectorNumElements());
1292 
1293  return DAG.getBuildVector(Op.getValueType(), SDLoc(Op), Args);
1294 }
1295 
1296 /// Generate Min/Max node
1298  SDValue LHS, SDValue RHS,
1299  SDValue True, SDValue False,
1300  SDValue CC,
1301  DAGCombinerInfo &DCI) const {
1302  if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
1303  return SDValue();
1304 
1305  SelectionDAG &DAG = DCI.DAG;
1306  ISD::CondCode CCOpcode = cast<CondCodeSDNode>(CC)->get();
1307  switch (CCOpcode) {
1308  case ISD::SETOEQ:
1309  case ISD::SETONE:
1310  case ISD::SETUNE:
1311  case ISD::SETNE:
1312  case ISD::SETUEQ:
1313  case ISD::SETEQ:
1314  case ISD::SETFALSE:
1315  case ISD::SETFALSE2:
1316  case ISD::SETTRUE:
1317  case ISD::SETTRUE2:
1318  case ISD::SETUO:
1319  case ISD::SETO:
1320  break;
1321  case ISD::SETULE:
1322  case ISD::SETULT: {
1323  if (LHS == True)
1324  return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1325  return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1326  }
1327  case ISD::SETOLE:
1328  case ISD::SETOLT:
1329  case ISD::SETLE:
1330  case ISD::SETLT: {
1331  // Ordered. Assume ordered for undefined.
1332 
1333  // Only do this after legalization to avoid interfering with other combines
1334  // which might occur.
1335  if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1336  !DCI.isCalledByLegalizer())
1337  return SDValue();
1338 
1339  // We need to permute the operands to get the correct NaN behavior. The
1340  // selected operand is the second one based on the failing compare with NaN,
1341  // so permute it based on the compare type the hardware uses.
1342  if (LHS == True)
1343  return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1344  return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1345  }
1346  case ISD::SETUGE:
1347  case ISD::SETUGT: {
1348  if (LHS == True)
1349  return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, RHS, LHS);
1350  return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, LHS, RHS);
1351  }
1352  case ISD::SETGT:
1353  case ISD::SETGE:
1354  case ISD::SETOGE:
1355  case ISD::SETOGT: {
1356  if (DCI.getDAGCombineLevel() < AfterLegalizeDAG &&
1357  !DCI.isCalledByLegalizer())
1358  return SDValue();
1359 
1360  if (LHS == True)
1361  return DAG.getNode(AMDGPUISD::FMAX_LEGACY, DL, VT, LHS, RHS);
1362  return DAG.getNode(AMDGPUISD::FMIN_LEGACY, DL, VT, RHS, LHS);
1363  }
1364  case ISD::SETCC_INVALID:
1365  llvm_unreachable("Invalid setcc condcode!");
1366  }
1367  return SDValue();
1368 }
1369 
1370 std::pair<SDValue, SDValue>
1372  SDLoc SL(Op);
1373 
1374  SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1375 
1376  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1377  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1378 
1379  SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1380  SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1381 
1382  return std::make_pair(Lo, Hi);
1383 }
1384 
1386  SDLoc SL(Op);
1387 
1388  SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1389  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
1390  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
1391 }
1392 
1394  SDLoc SL(Op);
1395 
1396  SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Op);
1397  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
1398  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
1399 }
1400 
1401 // Split a vector type into two parts. The first part is a power of two vector.
1402 // The second part is whatever is left over, and is a scalar if it would
1403 // otherwise be a 1-vector.
1404 std::pair<EVT, EVT>
1406  EVT LoVT, HiVT;
1407  EVT EltVT = VT.getVectorElementType();
1408  unsigned NumElts = VT.getVectorNumElements();
1409  unsigned LoNumElts = PowerOf2Ceil((NumElts + 1) / 2);
1410  LoVT = EVT::getVectorVT(*DAG.getContext(), EltVT, LoNumElts);
1411  HiVT = NumElts - LoNumElts == 1
1412  ? EltVT
1413  : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts - LoNumElts);
1414  return std::make_pair(LoVT, HiVT);
1415 }
1416 
1417 // Split a vector value into two parts of types LoVT and HiVT. HiVT could be
1418 // scalar.
1419 std::pair<SDValue, SDValue>
1421  const EVT &LoVT, const EVT &HiVT,
1422  SelectionDAG &DAG) const {
1423  assert(LoVT.getVectorNumElements() +
1424  (HiVT.isVector() ? HiVT.getVectorNumElements() : 1) <=
1426  "More vector elements requested than available!");
1427  auto IdxTy = getVectorIdxTy(DAG.getDataLayout());
1428  SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
1429  DAG.getConstant(0, DL, IdxTy));
1430  SDValue Hi = DAG.getNode(
1432  HiVT, N, DAG.getConstant(LoVT.getVectorNumElements(), DL, IdxTy));
1433  return std::make_pair(Lo, Hi);
1434 }
1435 
1437  SelectionDAG &DAG) const {
1438  LoadSDNode *Load = cast<LoadSDNode>(Op);
1439  EVT VT = Op.getValueType();
1440 
1441 
1442  // If this is a 2 element vector, we really want to scalarize and not create
1443  // weird 1 element vectors.
1444  if (VT.getVectorNumElements() == 2)
1445  return scalarizeVectorLoad(Load, DAG);
1446 
1447  SDValue BasePtr = Load->getBasePtr();
1448  EVT MemVT = Load->getMemoryVT();
1449  SDLoc SL(Op);
1450 
1451  const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1452 
1453  EVT LoVT, HiVT;
1454  EVT LoMemVT, HiMemVT;
1455  SDValue Lo, Hi;
1456 
1457  std::tie(LoVT, HiVT) = getSplitDestVTs(VT, DAG);
1458  std::tie(LoMemVT, HiMemVT) = getSplitDestVTs(MemVT, DAG);
1459  std::tie(Lo, Hi) = splitVector(Op, SL, LoVT, HiVT, DAG);
1460 
1461  unsigned Size = LoMemVT.getStoreSize();
1462  unsigned BaseAlign = Load->getAlignment();
1463  unsigned HiAlign = MinAlign(BaseAlign, Size);
1464 
1465  SDValue LoLoad = DAG.getExtLoad(Load->getExtensionType(), SL, LoVT,
1466  Load->getChain(), BasePtr, SrcValue, LoMemVT,
1467  BaseAlign, Load->getMemOperand()->getFlags());
1468  SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, Size);
1469  SDValue HiLoad =
1470  DAG.getExtLoad(Load->getExtensionType(), SL, HiVT, Load->getChain(),
1471  HiPtr, SrcValue.getWithOffset(LoMemVT.getStoreSize()),
1472  HiMemVT, HiAlign, Load->getMemOperand()->getFlags());
1473 
1474  auto IdxTy = getVectorIdxTy(DAG.getDataLayout());
1475  SDValue Join;
1476  if (LoVT == HiVT) {
1477  // This is the case that the vector is power of two so was evenly split.
1478  Join = DAG.getNode(ISD::CONCAT_VECTORS, SL, VT, LoLoad, HiLoad);
1479  } else {
1480  Join = DAG.getNode(ISD::INSERT_SUBVECTOR, SL, VT, DAG.getUNDEF(VT), LoLoad,
1481  DAG.getConstant(0, SL, IdxTy));
1482  Join = DAG.getNode(HiVT.isVector() ? ISD::INSERT_SUBVECTOR
1484  SL, VT, Join, HiLoad,
1485  DAG.getConstant(LoVT.getVectorNumElements(), SL, IdxTy));
1486  }
1487 
1488  SDValue Ops[] = {Join, DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
1489  LoLoad.getValue(1), HiLoad.getValue(1))};
1490 
1491  return DAG.getMergeValues(Ops, SL);
1492 }
1493 
1494 // Widen a vector load from vec3 to vec4.
1496  SelectionDAG &DAG) const {
1497  LoadSDNode *Load = cast<LoadSDNode>(Op);
1498  EVT VT = Op.getValueType();
1499  assert(VT.getVectorNumElements() == 3);
1500  SDValue BasePtr = Load->getBasePtr();
1501  EVT MemVT = Load->getMemoryVT();
1502  SDLoc SL(Op);
1503  const MachinePointerInfo &SrcValue = Load->getMemOperand()->getPointerInfo();
1504  unsigned BaseAlign = Load->getAlignment();
1505 
1506  EVT WideVT =
1507  EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
1508  EVT WideMemVT =
1509  EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 4);
1510  SDValue WideLoad = DAG.getExtLoad(
1511  Load->getExtensionType(), SL, WideVT, Load->getChain(), BasePtr, SrcValue,
1512  WideMemVT, BaseAlign, Load->getMemOperand()->getFlags());
1513  return DAG.getMergeValues(
1514  {DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, VT, WideLoad,
1515  DAG.getConstant(0, SL, getVectorIdxTy(DAG.getDataLayout()))),
1516  WideLoad.getValue(1)},
1517  SL);
1518 }
1519 
1521  SelectionDAG &DAG) const {
1522  StoreSDNode *Store = cast<StoreSDNode>(Op);
1523  SDValue Val = Store->getValue();
1524  EVT VT = Val.getValueType();
1525 
1526  // If this is a 2 element vector, we really want to scalarize and not create
1527  // weird 1 element vectors.
1528  if (VT.getVectorNumElements() == 2)
1529  return scalarizeVectorStore(Store, DAG);
1530 
1531  EVT MemVT = Store->getMemoryVT();
1532  SDValue Chain = Store->getChain();
1533  SDValue BasePtr = Store->getBasePtr();
1534  SDLoc SL(Op);
1535 
1536  EVT LoVT, HiVT;
1537  EVT LoMemVT, HiMemVT;
1538  SDValue Lo, Hi;
1539 
1540  std::tie(LoVT, HiVT) = getSplitDestVTs(VT, DAG);
1541  std::tie(LoMemVT, HiMemVT) = getSplitDestVTs(MemVT, DAG);
1542  std::tie(Lo, Hi) = splitVector(Val, SL, LoVT, HiVT, DAG);
1543 
1544  SDValue HiPtr = DAG.getObjectPtrOffset(SL, BasePtr, LoMemVT.getStoreSize());
1545 
1546  const MachinePointerInfo &SrcValue = Store->getMemOperand()->getPointerInfo();
1547  unsigned BaseAlign = Store->getAlignment();
1548  unsigned Size = LoMemVT.getStoreSize();
1549  unsigned HiAlign = MinAlign(BaseAlign, Size);
1550 
1551  SDValue LoStore =
1552  DAG.getTruncStore(Chain, SL, Lo, BasePtr, SrcValue, LoMemVT, BaseAlign,
1553  Store->getMemOperand()->getFlags());
1554  SDValue HiStore =
1555  DAG.getTruncStore(Chain, SL, Hi, HiPtr, SrcValue.getWithOffset(Size),
1556  HiMemVT, HiAlign, Store->getMemOperand()->getFlags());
1557 
1558  return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoStore, HiStore);
1559 }
1560 
1561 // This is a shortcut for integer division because we have fast i32<->f32
1562 // conversions, and fast f32 reciprocal instructions. The fractional part of a
1563 // float is enough to accurately represent up to a 24-bit signed integer.
1565  bool Sign) const {
1566  SDLoc DL(Op);
1567  EVT VT = Op.getValueType();
1568  SDValue LHS = Op.getOperand(0);
1569  SDValue RHS = Op.getOperand(1);
1570  MVT IntVT = MVT::i32;
1571  MVT FltVT = MVT::f32;
1572 
1573  unsigned LHSSignBits = DAG.ComputeNumSignBits(LHS);
1574  if (LHSSignBits < 9)
1575  return SDValue();
1576 
1577  unsigned RHSSignBits = DAG.ComputeNumSignBits(RHS);
1578  if (RHSSignBits < 9)
1579  return SDValue();
1580 
1581  unsigned BitSize = VT.getSizeInBits();
1582  unsigned SignBits = std::min(LHSSignBits, RHSSignBits);
1583  unsigned DivBits = BitSize - SignBits;
1584  if (Sign)
1585  ++DivBits;
1586 
1589 
1590  SDValue jq = DAG.getConstant(1, DL, IntVT);
1591 
1592  if (Sign) {
1593  // char|short jq = ia ^ ib;
1594  jq = DAG.getNode(ISD::XOR, DL, VT, LHS, RHS);
1595 
1596  // jq = jq >> (bitsize - 2)
1597  jq = DAG.getNode(ISD::SRA, DL, VT, jq,
1598  DAG.getConstant(BitSize - 2, DL, VT));
1599 
1600  // jq = jq | 0x1
1601  jq = DAG.getNode(ISD::OR, DL, VT, jq, DAG.getConstant(1, DL, VT));
1602  }
1603 
1604  // int ia = (int)LHS;
1605  SDValue ia = LHS;
1606 
1607  // int ib, (int)RHS;
1608  SDValue ib = RHS;
1609 
1610  // float fa = (float)ia;
1611  SDValue fa = DAG.getNode(ToFp, DL, FltVT, ia);
1612 
1613  // float fb = (float)ib;
1614  SDValue fb = DAG.getNode(ToFp, DL, FltVT, ib);
1615 
1616  SDValue fq = DAG.getNode(ISD::FMUL, DL, FltVT,
1617  fa, DAG.getNode(AMDGPUISD::RCP, DL, FltVT, fb));
1618 
1619  // fq = trunc(fq);
1620  fq = DAG.getNode(ISD::FTRUNC, DL, FltVT, fq);
1621 
1622  // float fqneg = -fq;
1623  SDValue fqneg = DAG.getNode(ISD::FNEG, DL, FltVT, fq);
1624 
1625  // float fr = mad(fqneg, fb, fa);
1626  unsigned OpCode = Subtarget->hasFP32Denormals() ?
1628  (unsigned)ISD::FMAD;
1629  SDValue fr = DAG.getNode(OpCode, DL, FltVT, fqneg, fb, fa);
1630 
1631  // int iq = (int)fq;
1632  SDValue iq = DAG.getNode(ToInt, DL, IntVT, fq);
1633 
1634  // fr = fabs(fr);
1635  fr = DAG.getNode(ISD::FABS, DL, FltVT, fr);
1636 
1637  // fb = fabs(fb);
1638  fb = DAG.getNode(ISD::FABS, DL, FltVT, fb);
1639 
1640  EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
1641 
1642  // int cv = fr >= fb;
1643  SDValue cv = DAG.getSetCC(DL, SetCCVT, fr, fb, ISD::SETOGE);
1644 
1645  // jq = (cv ? jq : 0);
1646  jq = DAG.getNode(ISD::SELECT, DL, VT, cv, jq, DAG.getConstant(0, DL, VT));
1647 
1648  // dst = iq + jq;
1649  SDValue Div = DAG.getNode(ISD::ADD, DL, VT, iq, jq);
1650 
1651  // Rem needs compensation, it's easier to recompute it
1652  SDValue Rem = DAG.getNode(ISD::MUL, DL, VT, Div, RHS);
1653  Rem = DAG.getNode(ISD::SUB, DL, VT, LHS, Rem);
1654 
1655  // Truncate to number of bits this divide really is.
1656  if (Sign) {
1657  SDValue InRegSize
1658  = DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), DivBits));
1659  Div = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Div, InRegSize);
1660  Rem = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Rem, InRegSize);
1661  } else {
1662  SDValue TruncMask = DAG.getConstant((UINT64_C(1) << DivBits) - 1, DL, VT);
1663  Div = DAG.getNode(ISD::AND, DL, VT, Div, TruncMask);
1664  Rem = DAG.getNode(ISD::AND, DL, VT, Rem, TruncMask);
1665  }
1666 
1667  return DAG.getMergeValues({ Div, Rem }, DL);
1668 }
1669 
1671  SelectionDAG &DAG,
1673  SDLoc DL(Op);
1674  EVT VT = Op.getValueType();
1675 
1676  assert(VT == MVT::i64 && "LowerUDIVREM64 expects an i64");
1677 
1678  EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
1679 
1680  SDValue One = DAG.getConstant(1, DL, HalfVT);
1681  SDValue Zero = DAG.getConstant(0, DL, HalfVT);
1682 
1683  //HiLo split
1684  SDValue LHS = Op.getOperand(0);
1685  SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
1686  SDValue LHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, One);
1687 
1688  SDValue RHS = Op.getOperand(1);
1689  SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
1690  SDValue RHS_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, One);
1691 
1692  if (DAG.MaskedValueIsZero(RHS, APInt::getHighBitsSet(64, 32)) &&
1693  DAG.MaskedValueIsZero(LHS, APInt::getHighBitsSet(64, 32))) {
1694 
1695  SDValue Res = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
1696  LHS_Lo, RHS_Lo);
1697 
1698  SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(0), Zero});
1699  SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {Res.getValue(1), Zero});
1700 
1701  Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV));
1702  Results.push_back(DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM));
1703  return;
1704  }
1705 
1706  if (isTypeLegal(MVT::i64)) {
1707  // Compute denominator reciprocal.
1708  unsigned FMAD = Subtarget->hasFP32Denormals() ?
1710  (unsigned)ISD::FMAD;
1711 
1712  SDValue Cvt_Lo = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Lo);
1713  SDValue Cvt_Hi = DAG.getNode(ISD::UINT_TO_FP, DL, MVT::f32, RHS_Hi);
1714  SDValue Mad1 = DAG.getNode(FMAD, DL, MVT::f32, Cvt_Hi,
1715  DAG.getConstantFP(APInt(32, 0x4f800000).bitsToFloat(), DL, MVT::f32),
1716  Cvt_Lo);
1717  SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, DL, MVT::f32, Mad1);
1718  SDValue Mul1 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Rcp,
1719  DAG.getConstantFP(APInt(32, 0x5f7ffffc).bitsToFloat(), DL, MVT::f32));
1720  SDValue Mul2 = DAG.getNode(ISD::FMUL, DL, MVT::f32, Mul1,
1721  DAG.getConstantFP(APInt(32, 0x2f800000).bitsToFloat(), DL, MVT::f32));
1722  SDValue Trunc = DAG.getNode(ISD::FTRUNC, DL, MVT::f32, Mul2);
1723  SDValue Mad2 = DAG.getNode(FMAD, DL, MVT::f32, Trunc,
1724  DAG.getConstantFP(APInt(32, 0xcf800000).bitsToFloat(), DL, MVT::f32),
1725  Mul1);
1726  SDValue Rcp_Lo = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Mad2);
1727  SDValue Rcp_Hi = DAG.getNode(ISD::FP_TO_UINT, DL, HalfVT, Trunc);
1728  SDValue Rcp64 = DAG.getBitcast(VT,
1729  DAG.getBuildVector(MVT::v2i32, DL, {Rcp_Lo, Rcp_Hi}));
1730 
1731  SDValue Zero64 = DAG.getConstant(0, DL, VT);
1732  SDValue One64 = DAG.getConstant(1, DL, VT);
1733  SDValue Zero1 = DAG.getConstant(0, DL, MVT::i1);
1734  SDVTList HalfCarryVT = DAG.getVTList(HalfVT, MVT::i1);
1735 
1736  SDValue Neg_RHS = DAG.getNode(ISD::SUB, DL, VT, Zero64, RHS);
1737  SDValue Mullo1 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Rcp64);
1738  SDValue Mulhi1 = DAG.getNode(ISD::MULHU, DL, VT, Rcp64, Mullo1);
1739  SDValue Mulhi1_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1740  Zero);
1741  SDValue Mulhi1_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi1,
1742  One);
1743 
1744  SDValue Add1_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Lo,
1745  Mulhi1_Lo, Zero1);
1746  SDValue Add1_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Rcp_Hi,
1747  Mulhi1_Hi, Add1_Lo.getValue(1));
1748  SDValue Add1_HiNc = DAG.getNode(ISD::ADD, DL, HalfVT, Rcp_Hi, Mulhi1_Hi);
1749  SDValue Add1 = DAG.getBitcast(VT,
1750  DAG.getBuildVector(MVT::v2i32, DL, {Add1_Lo, Add1_Hi}));
1751 
1752  SDValue Mullo2 = DAG.getNode(ISD::MUL, DL, VT, Neg_RHS, Add1);
1753  SDValue Mulhi2 = DAG.getNode(ISD::MULHU, DL, VT, Add1, Mullo2);
1754  SDValue Mulhi2_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1755  Zero);
1756  SDValue Mulhi2_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mulhi2,
1757  One);
1758 
1759  SDValue Add2_Lo = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_Lo,
1760  Mulhi2_Lo, Zero1);
1761  SDValue Add2_HiC = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add1_HiNc,
1762  Mulhi2_Hi, Add1_Lo.getValue(1));
1763  SDValue Add2_Hi = DAG.getNode(ISD::ADDCARRY, DL, HalfCarryVT, Add2_HiC,
1764  Zero, Add2_Lo.getValue(1));
1765  SDValue Add2 = DAG.getBitcast(VT,
1766  DAG.getBuildVector(MVT::v2i32, DL, {Add2_Lo, Add2_Hi}));
1767  SDValue Mulhi3 = DAG.getNode(ISD::MULHU, DL, VT, LHS, Add2);
1768 
1769  SDValue Mul3 = DAG.getNode(ISD::MUL, DL, VT, RHS, Mulhi3);
1770 
1771  SDValue Mul3_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, Zero);
1772  SDValue Mul3_Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, Mul3, One);
1773  SDValue Sub1_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Lo,
1774  Mul3_Lo, Zero1);
1775  SDValue Sub1_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, LHS_Hi,
1776  Mul3_Hi, Sub1_Lo.getValue(1));
1777  SDValue Sub1_Mi = DAG.getNode(ISD::SUB, DL, HalfVT, LHS_Hi, Mul3_Hi);
1778  SDValue Sub1 = DAG.getBitcast(VT,
1779  DAG.getBuildVector(MVT::v2i32, DL, {Sub1_Lo, Sub1_Hi}));
1780 
1781  SDValue MinusOne = DAG.getConstant(0xffffffffu, DL, HalfVT);
1782  SDValue C1 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, MinusOne, Zero,
1783  ISD::SETUGE);
1784  SDValue C2 = DAG.getSelectCC(DL, Sub1_Lo, RHS_Lo, MinusOne, Zero,
1785  ISD::SETUGE);
1786  SDValue C3 = DAG.getSelectCC(DL, Sub1_Hi, RHS_Hi, C2, C1, ISD::SETEQ);
1787 
1788  // TODO: Here and below portions of the code can be enclosed into if/endif.
1789  // Currently control flow is unconditional and we have 4 selects after
1790  // potential endif to substitute PHIs.
1791 
1792  // if C3 != 0 ...
1793  SDValue Sub2_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Lo,
1794  RHS_Lo, Zero1);
1795  SDValue Sub2_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub1_Mi,
1796  RHS_Hi, Sub1_Lo.getValue(1));
1797  SDValue Sub2_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1798  Zero, Sub2_Lo.getValue(1));
1799  SDValue Sub2 = DAG.getBitcast(VT,
1800  DAG.getBuildVector(MVT::v2i32, DL, {Sub2_Lo, Sub2_Hi}));
1801 
1802  SDValue Add3 = DAG.getNode(ISD::ADD, DL, VT, Mulhi3, One64);
1803 
1804  SDValue C4 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, MinusOne, Zero,
1805  ISD::SETUGE);
1806  SDValue C5 = DAG.getSelectCC(DL, Sub2_Lo, RHS_Lo, MinusOne, Zero,
1807  ISD::SETUGE);
1808  SDValue C6 = DAG.getSelectCC(DL, Sub2_Hi, RHS_Hi, C5, C4, ISD::SETEQ);
1809 
1810  // if (C6 != 0)
1811  SDValue Add4 = DAG.getNode(ISD::ADD, DL, VT, Add3, One64);
1812 
1813  SDValue Sub3_Lo = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Lo,
1814  RHS_Lo, Zero1);
1815  SDValue Sub3_Mi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub2_Mi,
1816  RHS_Hi, Sub2_Lo.getValue(1));
1817  SDValue Sub3_Hi = DAG.getNode(ISD::SUBCARRY, DL, HalfCarryVT, Sub3_Mi,
1818  Zero, Sub3_Lo.getValue(1));
1819  SDValue Sub3 = DAG.getBitcast(VT,
1820  DAG.getBuildVector(MVT::v2i32, DL, {Sub3_Lo, Sub3_Hi}));
1821 
1822  // endif C6
1823  // endif C3
1824 
1825  SDValue Sel1 = DAG.getSelectCC(DL, C6, Zero, Add4, Add3, ISD::SETNE);
1826  SDValue Div = DAG.getSelectCC(DL, C3, Zero, Sel1, Mulhi3, ISD::SETNE);
1827 
1828  SDValue Sel2 = DAG.getSelectCC(DL, C6, Zero, Sub3, Sub2, ISD::SETNE);
1829  SDValue Rem = DAG.getSelectCC(DL, C3, Zero, Sel2, Sub1, ISD::SETNE);
1830 
1831  Results.push_back(Div);
1832  Results.push_back(Rem);
1833 
1834  return;
1835  }
1836 
1837  // r600 expandion.
1838  // Get Speculative values
1839  SDValue DIV_Part = DAG.getNode(ISD::UDIV, DL, HalfVT, LHS_Hi, RHS_Lo);
1840  SDValue REM_Part = DAG.getNode(ISD::UREM, DL, HalfVT, LHS_Hi, RHS_Lo);
1841 
1842  SDValue REM_Lo = DAG.getSelectCC(DL, RHS_Hi, Zero, REM_Part, LHS_Hi, ISD::SETEQ);
1843  SDValue REM = DAG.getBuildVector(MVT::v2i32, DL, {REM_Lo, Zero});
1844  REM = DAG.getNode(ISD::BITCAST, DL, MVT::i64, REM);
1845 
1846  SDValue DIV_Hi = DAG.getSelectCC(DL, RHS_Hi, Zero, DIV_Part, Zero, ISD::SETEQ);
1847  SDValue DIV_Lo = Zero;
1848 
1849  const unsigned halfBitWidth = HalfVT.getSizeInBits();
1850 
1851  for (unsigned i = 0; i < halfBitWidth; ++i) {
1852  const unsigned bitPos = halfBitWidth - i - 1;
1853  SDValue POS = DAG.getConstant(bitPos, DL, HalfVT);
1854  // Get value of high bit
1855  SDValue HBit = DAG.getNode(ISD::SRL, DL, HalfVT, LHS_Lo, POS);
1856  HBit = DAG.getNode(ISD::AND, DL, HalfVT, HBit, One);
1857  HBit = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, HBit);
1858 
1859  // Shift
1860  REM = DAG.getNode(ISD::SHL, DL, VT, REM, DAG.getConstant(1, DL, VT));
1861  // Add LHS high bit
1862  REM = DAG.getNode(ISD::OR, DL, VT, REM, HBit);
1863 
1864  SDValue BIT = DAG.getConstant(1ULL << bitPos, DL, HalfVT);
1865  SDValue realBIT = DAG.getSelectCC(DL, REM, RHS, BIT, Zero, ISD::SETUGE);
1866 
1867  DIV_Lo = DAG.getNode(ISD::OR, DL, HalfVT, DIV_Lo, realBIT);
1868 
1869  // Update REM
1870  SDValue REM_sub = DAG.getNode(ISD::SUB, DL, VT, REM, RHS);
1871  REM = DAG.getSelectCC(DL, REM, RHS, REM_sub, REM, ISD::SETUGE);
1872  }
1873 
1874  SDValue DIV = DAG.getBuildVector(MVT::v2i32, DL, {DIV_Lo, DIV_Hi});
1875  DIV = DAG.getNode(ISD::BITCAST, DL, MVT::i64, DIV);
1876  Results.push_back(DIV);
1877  Results.push_back(REM);
1878 }
1879 
1881  SelectionDAG &DAG) const {
1882  SDLoc DL(Op);
1883  EVT VT = Op.getValueType();
1884 
1885  if (VT == MVT::i64) {
1887  LowerUDIVREM64(Op, DAG, Results);
1888  return DAG.getMergeValues(Results, DL);
1889  }
1890 
1891  if (VT == MVT::i32) {
1892  if (SDValue Res = LowerDIVREM24(Op, DAG, false))
1893  return Res;
1894  }
1895 
1896  SDValue Num = Op.getOperand(0);
1897  SDValue Den = Op.getOperand(1);
1898 
1899  // RCP = URECIP(Den) = 2^32 / Den + e
1900  // e is rounding error.
1901  SDValue RCP = DAG.getNode(AMDGPUISD::URECIP, DL, VT, Den);
1902 
1903  // RCP_LO = mul(RCP, Den) */
1904  SDValue RCP_LO = DAG.getNode(ISD::MUL, DL, VT, RCP, Den);
1905 
1906  // RCP_HI = mulhu (RCP, Den) */
1907  SDValue RCP_HI = DAG.getNode(ISD::MULHU, DL, VT, RCP, Den);
1908 
1909  // NEG_RCP_LO = -RCP_LO
1910  SDValue NEG_RCP_LO = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
1911  RCP_LO);
1912 
1913  // ABS_RCP_LO = (RCP_HI == 0 ? NEG_RCP_LO : RCP_LO)
1914  SDValue ABS_RCP_LO = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1915  NEG_RCP_LO, RCP_LO,
1916  ISD::SETEQ);
1917  // Calculate the rounding error from the URECIP instruction
1918  // E = mulhu(ABS_RCP_LO, RCP)
1919  SDValue E = DAG.getNode(ISD::MULHU, DL, VT, ABS_RCP_LO, RCP);
1920 
1921  // RCP_A_E = RCP + E
1922  SDValue RCP_A_E = DAG.getNode(ISD::ADD, DL, VT, RCP, E);
1923 
1924  // RCP_S_E = RCP - E
1925  SDValue RCP_S_E = DAG.getNode(ISD::SUB, DL, VT, RCP, E);
1926 
1927  // Tmp0 = (RCP_HI == 0 ? RCP_A_E : RCP_SUB_E)
1928  SDValue Tmp0 = DAG.getSelectCC(DL, RCP_HI, DAG.getConstant(0, DL, VT),
1929  RCP_A_E, RCP_S_E,
1930  ISD::SETEQ);
1931  // Quotient = mulhu(Tmp0, Num)
1932  SDValue Quotient = DAG.getNode(ISD::MULHU, DL, VT, Tmp0, Num);
1933 
1934  // Num_S_Remainder = Quotient * Den
1935  SDValue Num_S_Remainder = DAG.getNode(ISD::MUL, DL, VT, Quotient, Den);
1936 
1937  // Remainder = Num - Num_S_Remainder
1938  SDValue Remainder = DAG.getNode(ISD::SUB, DL, VT, Num, Num_S_Remainder);
1939 
1940  // Remainder_GE_Den = (Remainder >= Den ? -1 : 0)
1941  SDValue Remainder_GE_Den = DAG.getSelectCC(DL, Remainder, Den,
1942  DAG.getConstant(-1, DL, VT),
1943  DAG.getConstant(0, DL, VT),
1944  ISD::SETUGE);
1945  // Remainder_GE_Zero = (Num >= Num_S_Remainder ? -1 : 0)
1946  SDValue Remainder_GE_Zero = DAG.getSelectCC(DL, Num,
1947  Num_S_Remainder,
1948  DAG.getConstant(-1, DL, VT),
1949  DAG.getConstant(0, DL, VT),
1950  ISD::SETUGE);
1951  // Tmp1 = Remainder_GE_Den & Remainder_GE_Zero
1952  SDValue Tmp1 = DAG.getNode(ISD::AND, DL, VT, Remainder_GE_Den,
1953  Remainder_GE_Zero);
1954 
1955  // Calculate Division result:
1956 
1957  // Quotient_A_One = Quotient + 1
1958  SDValue Quotient_A_One = DAG.getNode(ISD::ADD, DL, VT, Quotient,
1959  DAG.getConstant(1, DL, VT));
1960 
1961  // Quotient_S_One = Quotient - 1
1962  SDValue Quotient_S_One = DAG.getNode(ISD::SUB, DL, VT, Quotient,
1963  DAG.getConstant(1, DL, VT));
1964 
1965  // Div = (Tmp1 == 0 ? Quotient : Quotient_A_One)
1966  SDValue Div = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1967  Quotient, Quotient_A_One, ISD::SETEQ);
1968 
1969  // Div = (Remainder_GE_Zero == 0 ? Quotient_S_One : Div)
1970  Div = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1971  Quotient_S_One, Div, ISD::SETEQ);
1972 
1973  // Calculate Rem result:
1974 
1975  // Remainder_S_Den = Remainder - Den
1976  SDValue Remainder_S_Den = DAG.getNode(ISD::SUB, DL, VT, Remainder, Den);
1977 
1978  // Remainder_A_Den = Remainder + Den
1979  SDValue Remainder_A_Den = DAG.getNode(ISD::ADD, DL, VT, Remainder, Den);
1980 
1981  // Rem = (Tmp1 == 0 ? Remainder : Remainder_S_Den)
1982  SDValue Rem = DAG.getSelectCC(DL, Tmp1, DAG.getConstant(0, DL, VT),
1983  Remainder, Remainder_S_Den, ISD::SETEQ);
1984 
1985  // Rem = (Remainder_GE_Zero == 0 ? Remainder_A_Den : Rem)
1986  Rem = DAG.getSelectCC(DL, Remainder_GE_Zero, DAG.getConstant(0, DL, VT),
1987  Remainder_A_Den, Rem, ISD::SETEQ);
1988  SDValue Ops[2] = {
1989  Div,
1990  Rem
1991  };
1992  return DAG.getMergeValues(Ops, DL);
1993 }
1994 
1996  SelectionDAG &DAG) const {
1997  SDLoc DL(Op);
1998  EVT VT = Op.getValueType();
1999 
2000  SDValue LHS = Op.getOperand(0);
2001  SDValue RHS = Op.getOperand(1);
2002 
2003  SDValue Zero = DAG.getConstant(0, DL, VT);
2004  SDValue NegOne = DAG.getConstant(-1, DL, VT);
2005 
2006  if (VT == MVT::i32) {
2007  if (SDValue Res = LowerDIVREM24(Op, DAG, true))
2008  return Res;
2009  }
2010 
2011  if (VT == MVT::i64 &&
2012  DAG.ComputeNumSignBits(LHS) > 32 &&
2013  DAG.ComputeNumSignBits(RHS) > 32) {
2014  EVT HalfVT = VT.getHalfSizedIntegerVT(*DAG.getContext());
2015 
2016  //HiLo split
2017  SDValue LHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, LHS, Zero);
2018  SDValue RHS_Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, HalfVT, RHS, Zero);
2019  SDValue DIVREM = DAG.getNode(ISD::SDIVREM, DL, DAG.getVTList(HalfVT, HalfVT),
2020  LHS_Lo, RHS_Lo);
2021  SDValue Res[2] = {
2022  DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(0)),
2023  DAG.getNode(ISD::SIGN_EXTEND, DL, VT, DIVREM.getValue(1))
2024  };
2025  return DAG.getMergeValues(Res, DL);
2026  }
2027 
2028  SDValue LHSign = DAG.getSelectCC(DL, LHS, Zero, NegOne, Zero, ISD::SETLT);
2029  SDValue RHSign = DAG.getSelectCC(DL, RHS, Zero, NegOne, Zero, ISD::SETLT);
2030  SDValue DSign = DAG.getNode(ISD::XOR, DL, VT, LHSign, RHSign);
2031  SDValue RSign = LHSign; // Remainder sign is the same as LHS
2032 
2033  LHS = DAG.getNode(ISD::ADD, DL, VT, LHS, LHSign);
2034  RHS = DAG.getNode(ISD::ADD, DL, VT, RHS, RHSign);
2035 
2036  LHS = DAG.getNode(ISD::XOR, DL, VT, LHS, LHSign);
2037  RHS = DAG.getNode(ISD::XOR, DL, VT, RHS, RHSign);
2038 
2039  SDValue Div = DAG.getNode(ISD::UDIVREM, DL, DAG.getVTList(VT, VT), LHS, RHS);
2040  SDValue Rem = Div.getValue(1);
2041 
2042  Div = DAG.getNode(ISD::XOR, DL, VT, Div, DSign);
2043  Rem = DAG.getNode(ISD::XOR, DL, VT, Rem, RSign);
2044 
2045  Div = DAG.getNode(ISD::SUB, DL, VT, Div, DSign);
2046  Rem = DAG.getNode(ISD::SUB, DL, VT, Rem, RSign);
2047 
2048  SDValue Res[2] = {
2049  Div,
2050  Rem
2051  };
2052  return DAG.getMergeValues(Res, DL);
2053 }
2054 
2055 // (frem x, y) -> (fsub x, (fmul (ftrunc (fdiv x, y)), y))
2057  SDLoc SL(Op);
2058  EVT VT = Op.getValueType();
2059  SDValue X = Op.getOperand(0);
2060  SDValue Y = Op.getOperand(1);
2061 
2062  // TODO: Should this propagate fast-math-flags?
2063 
2064  SDValue Div = DAG.getNode(ISD::FDIV, SL, VT, X, Y);
2065  SDValue Floor = DAG.getNode(ISD::FTRUNC, SL, VT, Div);
2066  SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Floor, Y);
2067 
2068  return DAG.getNode(ISD::FSUB, SL, VT, X, Mul);
2069 }
2070 
2072  SDLoc SL(Op);
2073  SDValue Src = Op.getOperand(0);
2074 
2075  // result = trunc(src)
2076  // if (src > 0.0 && src != result)
2077  // result += 1.0
2078 
2079  SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2080 
2081  const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
2082  const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
2083 
2084  EVT SetCCVT =
2086 
2087  SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOGT);
2088  SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2089  SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2090 
2091  SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, One, Zero);
2092  // TODO: Should this propagate fast-math-flags?
2093  return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2094 }
2095 
2097  SelectionDAG &DAG) {
2098  const unsigned FractBits = 52;
2099  const unsigned ExpBits = 11;
2100 
2101  SDValue ExpPart = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
2102  Hi,
2103  DAG.getConstant(FractBits - 32, SL, MVT::i32),
2104  DAG.getConstant(ExpBits, SL, MVT::i32));
2105  SDValue Exp = DAG.getNode(ISD::SUB, SL, MVT::i32, ExpPart,
2106  DAG.getConstant(1023, SL, MVT::i32));
2107 
2108  return Exp;
2109 }
2110 
2112  SDLoc SL(Op);
2113  SDValue Src = Op.getOperand(0);
2114 
2115  assert(Op.getValueType() == MVT::f64);
2116 
2117  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2118  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2119 
2120  SDValue VecSrc = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2121 
2122  // Extract the upper half, since this is where we will find the sign and
2123  // exponent.
2124  SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, VecSrc, One);
2125 
2126  SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2127 
2128  const unsigned FractBits = 52;
2129 
2130  // Extract the sign bit.
2131  const SDValue SignBitMask = DAG.getConstant(UINT32_C(1) << 31, SL, MVT::i32);
2132  SDValue SignBit = DAG.getNode(ISD::AND, SL, MVT::i32, Hi, SignBitMask);
2133 
2134  // Extend back to 64-bits.
2135  SDValue SignBit64 = DAG.getBuildVector(MVT::v2i32, SL, {Zero, SignBit});
2136  SignBit64 = DAG.getNode(ISD::BITCAST, SL, MVT::i64, SignBit64);
2137 
2138  SDValue BcInt = DAG.getNode(ISD::BITCAST, SL, MVT::i64, Src);
2139  const SDValue FractMask
2140  = DAG.getConstant((UINT64_C(1) << FractBits) - 1, SL, MVT::i64);
2141 
2142  SDValue Shr = DAG.getNode(ISD::SRA, SL, MVT::i64, FractMask, Exp);
2143  SDValue Not = DAG.getNOT(SL, Shr, MVT::i64);
2144  SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, BcInt, Not);
2145 
2146  EVT SetCCVT =
2148 
2149  const SDValue FiftyOne = DAG.getConstant(FractBits - 1, SL, MVT::i32);
2150 
2151  SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2152  SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2153 
2154  SDValue Tmp1 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpLt0, SignBit64, Tmp0);
2155  SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, ExpGt51, BcInt, Tmp1);
2156 
2157  return DAG.getNode(ISD::BITCAST, SL, MVT::f64, Tmp2);
2158 }
2159 
2161  SDLoc SL(Op);
2162  SDValue Src = Op.getOperand(0);
2163 
2164  assert(Op.getValueType() == MVT::f64);
2165 
2166  APFloat C1Val(APFloat::IEEEdouble(), "0x1.0p+52");
2167  SDValue C1 = DAG.getConstantFP(C1Val, SL, MVT::f64);
2168  SDValue CopySign = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, C1, Src);
2169 
2170  // TODO: Should this propagate fast-math-flags?
2171 
2172  SDValue Tmp1 = DAG.getNode(ISD::FADD, SL, MVT::f64, Src, CopySign);
2173  SDValue Tmp2 = DAG.getNode(ISD::FSUB, SL, MVT::f64, Tmp1, CopySign);
2174 
2175  SDValue Fabs = DAG.getNode(ISD::FABS, SL, MVT::f64, Src);
2176 
2177  APFloat C2Val(APFloat::IEEEdouble(), "0x1.fffffffffffffp+51");
2178  SDValue C2 = DAG.getConstantFP(C2Val, SL, MVT::f64);
2179 
2180  EVT SetCCVT =
2182  SDValue Cond = DAG.getSetCC(SL, SetCCVT, Fabs, C2, ISD::SETOGT);
2183 
2184  return DAG.getSelect(SL, MVT::f64, Cond, Src, Tmp2);
2185 }
2186 
2188  // FNEARBYINT and FRINT are the same, except in their handling of FP
2189  // exceptions. Those aren't really meaningful for us, and OpenCL only has
2190  // rint, so just treat them as equivalent.
2191  return DAG.getNode(ISD::FRINT, SDLoc(Op), Op.getValueType(), Op.getOperand(0));
2192 }
2193 
2194 // XXX - May require not supporting f32 denormals?
2195 
2196 // Don't handle v2f16. The extra instructions to scalarize and repack around the
2197 // compare and vselect end up producing worse code than scalarizing the whole
2198 // operation.
2200  SDLoc SL(Op);
2201  SDValue X = Op.getOperand(0);
2202  EVT VT = Op.getValueType();
2203 
2204  SDValue T = DAG.getNode(ISD::FTRUNC, SL, VT, X);
2205 
2206  // TODO: Should this propagate fast-math-flags?
2207 
2208  SDValue Diff = DAG.getNode(ISD::FSUB, SL, VT, X, T);
2209 
2210  SDValue AbsDiff = DAG.getNode(ISD::FABS, SL, VT, Diff);
2211 
2212  const SDValue Zero = DAG.getConstantFP(0.0, SL, VT);
2213  const SDValue One = DAG.getConstantFP(1.0, SL, VT);
2214  const SDValue Half = DAG.getConstantFP(0.5, SL, VT);
2215 
2216  SDValue SignOne = DAG.getNode(ISD::FCOPYSIGN, SL, VT, One, X);
2217 
2218  EVT SetCCVT =
2219  getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
2220 
2221  SDValue Cmp = DAG.getSetCC(SL, SetCCVT, AbsDiff, Half, ISD::SETOGE);
2222 
2223  SDValue Sel = DAG.getNode(ISD::SELECT, SL, VT, Cmp, SignOne, Zero);
2224 
2225  return DAG.getNode(ISD::FADD, SL, VT, T, Sel);
2226 }
2227 
2229  SDLoc SL(Op);
2230  SDValue X = Op.getOperand(0);
2231 
2232  SDValue L = DAG.getNode(ISD::BITCAST, SL, MVT::i64, X);
2233 
2234  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2235  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2236  const SDValue NegOne = DAG.getConstant(-1, SL, MVT::i32);
2237  const SDValue FiftyOne = DAG.getConstant(51, SL, MVT::i32);
2238  EVT SetCCVT =
2240 
2241  SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
2242 
2243  SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BC, One);
2244 
2245  SDValue Exp = extractF64Exponent(Hi, SL, DAG);
2246 
2247  const SDValue Mask = DAG.getConstant(INT64_C(0x000fffffffffffff), SL,
2248  MVT::i64);
2249 
2250  SDValue M = DAG.getNode(ISD::SRA, SL, MVT::i64, Mask, Exp);
2251  SDValue D = DAG.getNode(ISD::SRA, SL, MVT::i64,
2252  DAG.getConstant(INT64_C(0x0008000000000000), SL,
2253  MVT::i64),
2254  Exp);
2255 
2256  SDValue Tmp0 = DAG.getNode(ISD::AND, SL, MVT::i64, L, M);
2257  SDValue Tmp1 = DAG.getSetCC(SL, SetCCVT,
2258  DAG.getConstant(0, SL, MVT::i64), Tmp0,
2259  ISD::SETNE);
2260 
2261  SDValue Tmp2 = DAG.getNode(ISD::SELECT, SL, MVT::i64, Tmp1,
2262  D, DAG.getConstant(0, SL, MVT::i64));
2263  SDValue K = DAG.getNode(ISD::ADD, SL, MVT::i64, L, Tmp2);
2264 
2265  K = DAG.getNode(ISD::AND, SL, MVT::i64, K, DAG.getNOT(SL, M, MVT::i64));
2266  K = DAG.getNode(ISD::BITCAST, SL, MVT::f64, K);
2267 
2268  SDValue ExpLt0 = DAG.getSetCC(SL, SetCCVT, Exp, Zero, ISD::SETLT);
2269  SDValue ExpGt51 = DAG.getSetCC(SL, SetCCVT, Exp, FiftyOne, ISD::SETGT);
2270  SDValue ExpEqNegOne = DAG.getSetCC(SL, SetCCVT, NegOne, Exp, ISD::SETEQ);
2271 
2272  SDValue Mag = DAG.getNode(ISD::SELECT, SL, MVT::f64,
2273  ExpEqNegOne,
2274  DAG.getConstantFP(1.0, SL, MVT::f64),
2275  DAG.getConstantFP(0.0, SL, MVT::f64));
2276 
2277  SDValue S = DAG.getNode(ISD::FCOPYSIGN, SL, MVT::f64, Mag, X);
2278 
2279  K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpLt0, S, K);
2280  K = DAG.getNode(ISD::SELECT, SL, MVT::f64, ExpGt51, X, K);
2281 
2282  return K;
2283 }
2284 
2286  EVT VT = Op.getValueType();
2287 
2288  if (VT == MVT::f32 || VT == MVT::f16)
2289  return LowerFROUND32_16(Op, DAG);
2290 
2291  if (VT == MVT::f64)
2292  return LowerFROUND64(Op, DAG);
2293 
2294  llvm_unreachable("unhandled type");
2295 }
2296 
2298  SDLoc SL(Op);
2299  SDValue Src = Op.getOperand(0);
2300 
2301  // result = trunc(src);
2302  // if (src < 0.0 && src != result)
2303  // result += -1.0.
2304 
2305  SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2306 
2307  const SDValue Zero = DAG.getConstantFP(0.0, SL, MVT::f64);
2308  const SDValue NegOne = DAG.getConstantFP(-1.0, SL, MVT::f64);
2309 
2310  EVT SetCCVT =
2312 
2313  SDValue Lt0 = DAG.getSetCC(SL, SetCCVT, Src, Zero, ISD::SETOLT);
2314  SDValue NeTrunc = DAG.getSetCC(SL, SetCCVT, Src, Trunc, ISD::SETONE);
2315  SDValue And = DAG.getNode(ISD::AND, SL, SetCCVT, Lt0, NeTrunc);
2316 
2317  SDValue Add = DAG.getNode(ISD::SELECT, SL, MVT::f64, And, NegOne, Zero);
2318  // TODO: Should this propagate fast-math-flags?
2319  return DAG.getNode(ISD::FADD, SL, MVT::f64, Trunc, Add);
2320 }
2321 
2323  double Log2BaseInverted) const {
2324  EVT VT = Op.getValueType();
2325 
2326  SDLoc SL(Op);
2327  SDValue Operand = Op.getOperand(0);
2328  SDValue Log2Operand = DAG.getNode(ISD::FLOG2, SL, VT, Operand);
2329  SDValue Log2BaseInvertedOperand = DAG.getConstantFP(Log2BaseInverted, SL, VT);
2330 
2331  return DAG.getNode(ISD::FMUL, SL, VT, Log2Operand, Log2BaseInvertedOperand);
2332 }
2333 
2334 // Return M_LOG2E of appropriate type
2335 static SDValue getLog2EVal(SelectionDAG &DAG, const SDLoc &SL, EVT VT) {
2336  switch (VT.getScalarType().getSimpleVT().SimpleTy) {
2337  case MVT::f32:
2338  return DAG.getConstantFP(1.44269504088896340735992468100189214f, SL, VT);
2339  case MVT::f16:
2340  return DAG.getConstantFP(
2341  APFloat(APFloat::IEEEhalf(), "1.44269504088896340735992468100189214"),
2342  SL, VT);
2343  case MVT::f64:
2344  return DAG.getConstantFP(
2345  APFloat(APFloat::IEEEdouble(), "0x1.71547652b82fep+0"), SL, VT);
2346  default:
2347  llvm_unreachable("unsupported fp type");
2348  }
2349 }
2350 
2351 // exp2(M_LOG2E_F * f);
2353  EVT VT = Op.getValueType();
2354  SDLoc SL(Op);
2355  SDValue Src = Op.getOperand(0);
2356 
2357  const SDValue K = getLog2EVal(DAG, SL, VT);
2358  SDValue Mul = DAG.getNode(ISD::FMUL, SL, VT, Src, K, Op->getFlags());
2359  return DAG.getNode(ISD::FEXP2, SL, VT, Mul, Op->getFlags());
2360 }
2361 
2362 static bool isCtlzOpc(unsigned Opc) {
2363  return Opc == ISD::CTLZ || Opc == ISD::CTLZ_ZERO_UNDEF;
2364 }
2365 
2366 static bool isCttzOpc(unsigned Opc) {
2367  return Opc == ISD::CTTZ || Opc == ISD::CTTZ_ZERO_UNDEF;
2368 }
2369 
2371  SDLoc SL(Op);
2372  SDValue Src = Op.getOperand(0);
2373  bool ZeroUndef = Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF ||
2375 
2376  unsigned ISDOpc, NewOpc;
2377  if (isCtlzOpc(Op.getOpcode())) {
2378  ISDOpc = ISD::CTLZ_ZERO_UNDEF;
2379  NewOpc = AMDGPUISD::FFBH_U32;
2380  } else if (isCttzOpc(Op.getOpcode())) {
2381  ISDOpc = ISD::CTTZ_ZERO_UNDEF;
2382  NewOpc = AMDGPUISD::FFBL_B32;
2383  } else
2384  llvm_unreachable("Unexpected OPCode!!!");
2385 
2386 
2387  if (ZeroUndef && Src.getValueType() == MVT::i32)
2388  return DAG.getNode(NewOpc, SL, MVT::i32, Src);
2389 
2390  SDValue Vec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2391 
2392  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
2393  const SDValue One = DAG.getConstant(1, SL, MVT::i32);
2394 
2395  SDValue Lo = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, Zero);
2396  SDValue Hi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Vec, One);
2397 
2398  EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2399  *DAG.getContext(), MVT::i32);
2400 
2401  SDValue HiOrLo = isCtlzOpc(Op.getOpcode()) ? Hi : Lo;
2402  SDValue Hi0orLo0 = DAG.getSetCC(SL, SetCCVT, HiOrLo, Zero, ISD::SETEQ);
2403 
2404  SDValue OprLo = DAG.getNode(ISDOpc, SL, MVT::i32, Lo);
2405  SDValue OprHi = DAG.getNode(ISDOpc, SL, MVT::i32, Hi);
2406 
2407  const SDValue Bits32 = DAG.getConstant(32, SL, MVT::i32);
2408  SDValue Add, NewOpr;
2409  if (isCtlzOpc(Op.getOpcode())) {
2410  Add = DAG.getNode(ISD::ADD, SL, MVT::i32, OprLo, Bits32);
2411  // ctlz(x) = hi_32(x) == 0 ? ctlz(lo_32(x)) + 32 : ctlz(hi_32(x))
2412  NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0orLo0, Add, OprHi);
2413  } else {
2414  Add = DAG.getNode(ISD::ADD, SL, MVT::i32, OprHi, Bits32);
2415  // cttz(x) = lo_32(x) == 0 ? cttz(hi_32(x)) + 32 : cttz(lo_32(x))
2416  NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32, Hi0orLo0, Add, OprLo);
2417  }
2418 
2419  if (!ZeroUndef) {
2420  // Test if the full 64-bit input is zero.
2421 
2422  // FIXME: DAG combines turn what should be an s_and_b64 into a v_or_b32,
2423  // which we probably don't want.
2424  SDValue LoOrHi = isCtlzOpc(Op.getOpcode()) ? Lo : Hi;
2425  SDValue Lo0OrHi0 = DAG.getSetCC(SL, SetCCVT, LoOrHi, Zero, ISD::SETEQ);
2426  SDValue SrcIsZero = DAG.getNode(ISD::AND, SL, SetCCVT, Lo0OrHi0, Hi0orLo0);
2427 
2428  // TODO: If i64 setcc is half rate, it can result in 1 fewer instruction
2429  // with the same cycles, otherwise it is slower.
2430  // SDValue SrcIsZero = DAG.getSetCC(SL, SetCCVT, Src,
2431  // DAG.getConstant(0, SL, MVT::i64), ISD::SETEQ);
2432 
2433  const SDValue Bits32 = DAG.getConstant(64, SL, MVT::i32);
2434 
2435  // The instruction returns -1 for 0 input, but the defined intrinsic
2436  // behavior is to return the number of bits.
2437  NewOpr = DAG.getNode(ISD::SELECT, SL, MVT::i32,
2438  SrcIsZero, Bits32, NewOpr);
2439  }
2440 
2441  return DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i64, NewOpr);
2442 }
2443 
2445  bool Signed) const {
2446  // Unsigned
2447  // cul2f(ulong u)
2448  //{
2449  // uint lz = clz(u);
2450  // uint e = (u != 0) ? 127U + 63U - lz : 0;
2451  // u = (u << lz) & 0x7fffffffffffffffUL;
2452  // ulong t = u & 0xffffffffffUL;
2453  // uint v = (e << 23) | (uint)(u >> 40);
2454  // uint r = t > 0x8000000000UL ? 1U : (t == 0x8000000000UL ? v & 1U : 0U);
2455  // return as_float(v + r);
2456  //}
2457  // Signed
2458  // cl2f(long l)
2459  //{
2460  // long s = l >> 63;
2461  // float r = cul2f((l + s) ^ s);
2462  // return s ? -r : r;
2463  //}
2464 
2465  SDLoc SL(Op);
2466  SDValue Src = Op.getOperand(0);
2467  SDValue L = Src;
2468 
2469  SDValue S;
2470  if (Signed) {
2471  const SDValue SignBit = DAG.getConstant(63, SL, MVT::i64);
2472  S = DAG.getNode(ISD::SRA, SL, MVT::i64, L, SignBit);
2473 
2474  SDValue LPlusS = DAG.getNode(ISD::ADD, SL, MVT::i64, L, S);
2475  L = DAG.getNode(ISD::XOR, SL, MVT::i64, LPlusS, S);
2476  }
2477 
2478  EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(),
2479  *DAG.getContext(), MVT::f32);
2480 
2481 
2482  SDValue ZeroI32 = DAG.getConstant(0, SL, MVT::i32);
2483  SDValue ZeroI64 = DAG.getConstant(0, SL, MVT::i64);
2484  SDValue LZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SL, MVT::i64, L);
2485  LZ = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LZ);
2486 
2487  SDValue K = DAG.getConstant(127U + 63U, SL, MVT::i32);
2488  SDValue E = DAG.getSelect(SL, MVT::i32,
2489  DAG.getSetCC(SL, SetCCVT, L, ZeroI64, ISD::SETNE),
2490  DAG.getNode(ISD::SUB, SL, MVT::i32, K, LZ),
2491  ZeroI32);
2492 
2493  SDValue U = DAG.getNode(ISD::AND, SL, MVT::i64,
2494  DAG.getNode(ISD::SHL, SL, MVT::i64, L, LZ),
2495  DAG.getConstant((-1ULL) >> 1, SL, MVT::i64));
2496 
2497  SDValue T = DAG.getNode(ISD::AND, SL, MVT::i64, U,
2498  DAG.getConstant(0xffffffffffULL, SL, MVT::i64));
2499 
2500  SDValue UShl = DAG.getNode(ISD::SRL, SL, MVT::i64,
2501  U, DAG.getConstant(40, SL, MVT::i64));
2502 
2503  SDValue V = DAG.getNode(ISD::OR, SL, MVT::i32,
2504  DAG.getNode(ISD::SHL, SL, MVT::i32, E, DAG.getConstant(23, SL, MVT::i32)),
2505  DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, UShl));
2506 
2507  SDValue C = DAG.getConstant(0x8000000000ULL, SL, MVT::i64);
2508  SDValue RCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETUGT);
2509  SDValue TCmp = DAG.getSetCC(SL, SetCCVT, T, C, ISD::SETEQ);
2510 
2511  SDValue One = DAG.getConstant(1, SL, MVT::i32);
2512 
2513  SDValue VTrunc1 = DAG.getNode(ISD::AND, SL, MVT::i32, V, One);
2514 
2515  SDValue R = DAG.getSelect(SL, MVT::i32,
2516  RCmp,
2517  One,
2518  DAG.getSelect(SL, MVT::i32, TCmp, VTrunc1, ZeroI32));
2519  R = DAG.getNode(ISD::ADD, SL, MVT::i32, V, R);
2520  R = DAG.getNode(ISD::BITCAST, SL, MVT::f32, R);
2521 
2522  if (!Signed)
2523  return R;
2524 
2525  SDValue RNeg = DAG.getNode(ISD::FNEG, SL, MVT::f32, R);
2526  return DAG.getSelect(SL, MVT::f32, DAG.getSExtOrTrunc(S, SL, SetCCVT), RNeg, R);
2527 }
2528 
2530  bool Signed) const {
2531  SDLoc SL(Op);
2532  SDValue Src = Op.getOperand(0);
2533 
2534  SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Src);
2535 
2537  DAG.getConstant(0, SL, MVT::i32));
2539  DAG.getConstant(1, SL, MVT::i32));
2540 
2541  SDValue CvtHi = DAG.getNode(Signed ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
2542  SL, MVT::f64, Hi);
2543 
2544  SDValue CvtLo = DAG.getNode(ISD::UINT_TO_FP, SL, MVT::f64, Lo);
2545 
2546  SDValue LdExp = DAG.getNode(AMDGPUISD::LDEXP, SL, MVT::f64, CvtHi,
2547  DAG.getConstant(32, SL, MVT::i32));
2548  // TODO: Should this propagate fast-math-flags?
2549  return DAG.getNode(ISD::FADD, SL, MVT::f64, LdExp, CvtLo);
2550 }
2551 
2553  SelectionDAG &DAG) const {
2554  assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2555  "operation should be legal");
2556 
2557  // TODO: Factor out code common with LowerSINT_TO_FP.
2558 
2559  EVT DestVT = Op.getValueType();
2560  if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2561  SDLoc DL(Op);
2562  SDValue Src = Op.getOperand(0);
2563 
2564  SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2565  SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2566  SDValue FPRound =
2567  DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2568 
2569  return FPRound;
2570  }
2571 
2572  if (DestVT == MVT::f32)
2573  return LowerINT_TO_FP32(Op, DAG, false);
2574 
2575  assert(DestVT == MVT::f64);
2576  return LowerINT_TO_FP64(Op, DAG, false);
2577 }
2578 
2580  SelectionDAG &DAG) const {
2581  assert(Op.getOperand(0).getValueType() == MVT::i64 &&
2582  "operation should be legal");
2583 
2584  // TODO: Factor out code common with LowerUINT_TO_FP.
2585 
2586  EVT DestVT = Op.getValueType();
2587  if (Subtarget->has16BitInsts() && DestVT == MVT::f16) {
2588  SDLoc DL(Op);
2589  SDValue Src = Op.getOperand(0);
2590 
2591  SDValue IntToFp32 = DAG.getNode(Op.getOpcode(), DL, MVT::f32, Src);
2592  SDValue FPRoundFlag = DAG.getIntPtrConstant(0, SDLoc(Op));
2593  SDValue FPRound =
2594  DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, IntToFp32, FPRoundFlag);
2595 
2596  return FPRound;
2597  }
2598 
2599  if (DestVT == MVT::f32)
2600  return LowerINT_TO_FP32(Op, DAG, true);
2601 
2602  assert(DestVT == MVT::f64);
2603  return LowerINT_TO_FP64(Op, DAG, true);
2604 }
2605 
2607  bool Signed) const {
2608  SDLoc SL(Op);
2609 
2610  SDValue Src = Op.getOperand(0);
2611 
2612  SDValue Trunc = DAG.getNode(ISD::FTRUNC, SL, MVT::f64, Src);
2613 
2614  SDValue K0 = DAG.getConstantFP(BitsToDouble(UINT64_C(0x3df0000000000000)), SL,
2615  MVT::f64);
2616  SDValue K1 = DAG.getConstantFP(BitsToDouble(UINT64_C(0xc1f0000000000000)), SL,
2617  MVT::f64);
2618  // TODO: Should this propagate fast-math-flags?
2619  SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, Trunc, K0);
2620 
2621  SDValue FloorMul = DAG.getNode(ISD::FFLOOR, SL, MVT::f64, Mul);
2622 
2623 
2624  SDValue Fma = DAG.getNode(ISD::FMA, SL, MVT::f64, FloorMul, K1, Trunc);
2625 
2626  SDValue Hi = DAG.getNode(Signed ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, SL,
2627  MVT::i32, FloorMul);
2628  SDValue Lo = DAG.getNode(ISD::FP_TO_UINT, SL, MVT::i32, Fma);
2629 
2630  SDValue Result = DAG.getBuildVector(MVT::v2i32, SL, {Lo, Hi});
2631 
2632  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Result);
2633 }
2634 
2636  SDLoc DL(Op);
2637  SDValue N0 = Op.getOperand(0);
2638 
2639  // Convert to target node to get known bits
2640  if (N0.getValueType() == MVT::f32)
2641  return DAG.getNode(AMDGPUISD::FP_TO_FP16, DL, Op.getValueType(), N0);
2642 
2644  // There is a generic expand for FP_TO_FP16 with unsafe fast math.
2645  return SDValue();
2646  }
2647 
2649 
2650  // f64 -> f16 conversion using round-to-nearest-even rounding mode.
2651  const unsigned ExpMask = 0x7ff;
2652  const unsigned ExpBiasf64 = 1023;
2653  const unsigned ExpBiasf16 = 15;
2654  SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
2655  SDValue One = DAG.getConstant(1, DL, MVT::i32);
2656  SDValue U = DAG.getNode(ISD::BITCAST, DL, MVT::i64, N0);
2657  SDValue UH = DAG.getNode(ISD::SRL, DL, MVT::i64, U,
2658  DAG.getConstant(32, DL, MVT::i64));
2659  UH = DAG.getZExtOrTrunc(UH, DL, MVT::i32);
2660  U = DAG.getZExtOrTrunc(U, DL, MVT::i32);
2661  SDValue E = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2662  DAG.getConstant(20, DL, MVT::i64));
2663  E = DAG.getNode(ISD::AND, DL, MVT::i32, E,
2664  DAG.getConstant(ExpMask, DL, MVT::i32));
2665  // Subtract the fp64 exponent bias (1023) to get the real exponent and
2666  // add the f16 bias (15) to get the biased exponent for the f16 format.
2667  E = DAG.getNode(ISD::ADD, DL, MVT::i32, E,
2668  DAG.getConstant(-ExpBiasf64 + ExpBiasf16, DL, MVT::i32));
2669 
2670  SDValue M = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2671  DAG.getConstant(8, DL, MVT::i32));
2672  M = DAG.getNode(ISD::AND, DL, MVT::i32, M,
2673  DAG.getConstant(0xffe, DL, MVT::i32));
2674 
2675  SDValue MaskedSig = DAG.getNode(ISD::AND, DL, MVT::i32, UH,
2676  DAG.getConstant(0x1ff, DL, MVT::i32));
2677  MaskedSig = DAG.getNode(ISD::OR, DL, MVT::i32, MaskedSig, U);
2678 
2679  SDValue Lo40Set = DAG.getSelectCC(DL, MaskedSig, Zero, Zero, One, ISD::SETEQ);
2680  M = DAG.getNode(ISD::OR, DL, MVT::i32, M, Lo40Set);
2681 
2682  // (M != 0 ? 0x0200 : 0) | 0x7c00;
2683  SDValue I = DAG.getNode(ISD::OR, DL, MVT::i32,
2684  DAG.getSelectCC(DL, M, Zero, DAG.getConstant(0x0200, DL, MVT::i32),
2685  Zero, ISD::SETNE), DAG.getConstant(0x7c00, DL, MVT::i32));
2686 
2687  // N = M | (E << 12);
2688  SDValue N = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2689  DAG.getNode(ISD::SHL, DL, MVT::i32, E,
2690  DAG.getConstant(12, DL, MVT::i32)));
2691 
2692  // B = clamp(1-E, 0, 13);
2693  SDValue OneSubExp = DAG.getNode(ISD::SUB, DL, MVT::i32,
2694  One, E);
2695  SDValue B = DAG.getNode(ISD::SMAX, DL, MVT::i32, OneSubExp, Zero);
2696  B = DAG.getNode(ISD::SMIN, DL, MVT::i32, B,
2697  DAG.getConstant(13, DL, MVT::i32));
2698 
2699  SDValue SigSetHigh = DAG.getNode(ISD::OR, DL, MVT::i32, M,
2700  DAG.getConstant(0x1000, DL, MVT::i32));
2701 
2702  SDValue D = DAG.getNode(ISD::SRL, DL, MVT::i32, SigSetHigh, B);
2703  SDValue D0 = DAG.getNode(ISD::SHL, DL, MVT::i32, D, B);
2704  SDValue D1 = DAG.getSelectCC(DL, D0, SigSetHigh, One, Zero, ISD::SETNE);
2705  D = DAG.getNode(ISD::OR, DL, MVT::i32, D, D1);
2706 
2707  SDValue V = DAG.getSelectCC(DL, E, One, D, N, ISD::SETLT);
2708  SDValue VLow3 = DAG.getNode(ISD::AND, DL, MVT::i32, V,
2709  DAG.getConstant(0x7, DL, MVT::i32));
2710  V = DAG.getNode(ISD::SRL, DL, MVT::i32, V,
2711  DAG.getConstant(2, DL, MVT::i32));
2712  SDValue V0 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(3, DL, MVT::i32),
2713  One, Zero, ISD::SETEQ);
2714  SDValue V1 = DAG.getSelectCC(DL, VLow3, DAG.getConstant(5, DL, MVT::i32),
2715  One, Zero, ISD::SETGT);
2716  V1 = DAG.getNode(ISD::OR, DL, MVT::i32, V0, V1);
2717  V = DAG.getNode(ISD::ADD, DL, MVT::i32, V, V1);
2718 
2719  V = DAG.getSelectCC(DL, E, DAG.getConstant(30, DL, MVT::i32),
2720  DAG.getConstant(0x7c00, DL, MVT::i32), V, ISD::SETGT);
2721  V = DAG.getSelectCC(DL, E, DAG.getConstant(1039, DL, MVT::i32),
2722  I, V, ISD::SETEQ);
2723 
2724  // Extract the sign bit.
2725  SDValue Sign = DAG.getNode(ISD::SRL, DL, MVT::i32, UH,
2726  DAG.getConstant(16, DL, MVT::i32));
2727  Sign = DAG.getNode(ISD::AND, DL, MVT::i32, Sign,
2728  DAG.getConstant(0x8000, DL, MVT::i32));
2729 
2730  V = DAG.getNode(ISD::OR, DL, MVT::i32, Sign, V);
2731  return DAG.getZExtOrTrunc(V, DL, Op.getValueType());
2732 }
2733 
2735  SelectionDAG &DAG) const {
2736  SDValue Src = Op.getOperand(0);
2737 
2738  // TODO: Factor out code common with LowerFP_TO_UINT.
2739 
2740  EVT SrcVT = Src.getValueType();
2741  if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2742  SDLoc DL(Op);
2743 
2744  SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2745  SDValue FpToInt32 =
2746  DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2747 
2748  return FpToInt32;
2749  }
2750 
2751  if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2752  return LowerFP64_TO_INT(Op, DAG, true);
2753 
2754  return SDValue();
2755 }
2756 
2758  SelectionDAG &DAG) const {
2759  SDValue Src = Op.getOperand(0);
2760 
2761  // TODO: Factor out code common with LowerFP_TO_SINT.
2762 
2763  EVT SrcVT = Src.getValueType();
2764  if (Subtarget->has16BitInsts() && SrcVT == MVT::f16) {
2765  SDLoc DL(Op);
2766 
2767  SDValue FPExtend = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Src);
2768  SDValue FpToInt32 =
2769  DAG.getNode(Op.getOpcode(), DL, MVT::i64, FPExtend);
2770 
2771  return FpToInt32;
2772  }
2773 
2774  if (Op.getValueType() == MVT::i64 && Src.getValueType() == MVT::f64)
2775  return LowerFP64_TO_INT(Op, DAG, false);
2776 
2777  return SDValue();
2778 }
2779 
2781  SelectionDAG &DAG) const {
2782  EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2783  MVT VT = Op.getSimpleValueType();
2784  MVT ScalarVT = VT.getScalarType();
2785 
2786  assert(VT.isVector());
2787 
2788  SDValue Src = Op.getOperand(0);
2789  SDLoc DL(Op);
2790 
2791  // TODO: Don't scalarize on Evergreen?
2792  unsigned NElts = VT.getVectorNumElements();
2794  DAG.ExtractVectorElements(Src, Args, 0, NElts);
2795 
2796  SDValue VTOp = DAG.getValueType(ExtraVT.getScalarType());
2797  for (unsigned I = 0; I < NElts; ++I)
2798  Args[I] = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ScalarVT, Args[I], VTOp);
2799 
2800  return DAG.getBuildVector(VT, DL, Args);
2801 }
2802 
2803 //===----------------------------------------------------------------------===//
2804 // Custom DAG optimizations
2805 //===----------------------------------------------------------------------===//
2806 
2807 static bool isU24(SDValue Op, SelectionDAG &DAG) {
2808  return AMDGPUTargetLowering::numBitsUnsigned(Op, DAG) <= 24;
2809 }
2810 
2811 static bool isI24(SDValue Op, SelectionDAG &DAG) {
2812  EVT VT = Op.getValueType();
2813  return VT.getSizeInBits() >= 24 && // Types less than 24-bit should be treated
2814  // as unsigned 24-bit values.
2816 }
2817 
2818 static SDValue simplifyI24(SDNode *Node24,
2820  SelectionDAG &DAG = DCI.DAG;
2821  SDValue LHS = Node24->getOperand(0);
2822  SDValue RHS = Node24->getOperand(1);
2823 
2824  APInt Demanded = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 24);
2825 
2826  // First try to simplify using GetDemandedBits which allows the operands to
2827  // have other uses, but will only perform simplifications that involve
2828  // bypassing some nodes for this user.
2829  SDValue DemandedLHS = DAG.GetDemandedBits(LHS, Demanded);
2830  SDValue DemandedRHS = DAG.GetDemandedBits(RHS, Demanded);
2831  if (DemandedLHS || DemandedRHS)
2832  return DAG.getNode(Node24->getOpcode(), SDLoc(Node24), Node24->getVTList(),
2833  DemandedLHS ? DemandedLHS : LHS,
2834  DemandedRHS ? DemandedRHS : RHS);
2835 
2836  // Now try SimplifyDemandedBits which can simplify the nodes used by our
2837  // operands if this node is the only user.
2838  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2839  if (TLI.SimplifyDemandedBits(LHS, Demanded, DCI))
2840  return SDValue(Node24, 0);
2841  if (TLI.SimplifyDemandedBits(RHS, Demanded, DCI))
2842  return SDValue(Node24, 0);
2843 
2844  return SDValue();
2845 }
2846 
2847 template <typename IntTy>
2849  uint32_t Width, const SDLoc &DL) {
2850  if (Width + Offset < 32) {
2851  uint32_t Shl = static_cast<uint32_t>(Src0) << (32 - Offset - Width);
2852  IntTy Result = static_cast<IntTy>(Shl) >> (32 - Width);
2853  return DAG.getConstant(Result, DL, MVT::i32);
2854  }
2855 
2856  return DAG.getConstant(Src0 >> Offset, DL, MVT::i32);
2857 }
2858 
2859 static bool hasVolatileUser(SDNode *Val) {
2860  for (SDNode *U : Val->uses()) {
2861  if (MemSDNode *M = dyn_cast<MemSDNode>(U)) {
2862  if (M->isVolatile())
2863  return true;
2864  }
2865  }
2866 
2867  return false;
2868 }
2869 
2871  // i32 vectors are the canonical memory type.
2872  if (VT.getScalarType() == MVT::i32 || isTypeLegal(VT))
2873  return false;
2874 
2875  if (!VT.isByteSized())
2876  return false;
2877 
2878  unsigned Size = VT.getStoreSize();
2879 
2880  if ((Size == 1 || Size == 2 || Size == 4) && !VT.isVector())
2881  return false;
2882 
2883  if (Size == 3 || (Size > 4 && (Size % 4 != 0)))
2884  return false;
2885 
2886  return true;
2887 }
2888 
2889 // Replace load of an illegal type with a store of a bitcast to a friendlier
2890 // type.
2892  DAGCombinerInfo &DCI) const {
2893  if (!DCI.isBeforeLegalize())
2894  return SDValue();
2895 
2896  LoadSDNode *LN = cast<LoadSDNode>(N);
2897  if (LN->isVolatile() || !ISD::isNormalLoad(LN) || hasVolatileUser(LN))
2898  return SDValue();
2899 
2900  SDLoc SL(N);
2901  SelectionDAG &DAG = DCI.DAG;
2902  EVT VT = LN->getMemoryVT();
2903 
2904  unsigned Size = VT.getStoreSize();
2905  unsigned Align = LN->getAlignment();
2906  if (Align < Size && isTypeLegal(VT)) {
2907  bool IsFast;
2908  unsigned AS = LN->getAddressSpace();
2909 
2910  // Expand unaligned loads earlier than legalization. Due to visitation order
2911  // problems during legalization, the emitted instructions to pack and unpack
2912  // the bytes again are not eliminated in the case of an unaligned copy.
2913  if (!allowsMisalignedMemoryAccesses(VT, AS, Align, &IsFast)) {
2914  if (VT.isVector())
2915  return scalarizeVectorLoad(LN, DAG);
2916 
2917  SDValue Ops[2];
2918  std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(LN, DAG);
2919  return DAG.getMergeValues(Ops, SDLoc(N));
2920  }
2921 
2922  if (!IsFast)
2923  return SDValue();
2924  }
2925 
2926  if (!shouldCombineMemoryType(VT))
2927  return SDValue();
2928 
2929  EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2930 
2931  SDValue NewLoad
2932  = DAG.getLoad(NewVT, SL, LN->getChain(),
2933  LN->getBasePtr(), LN->getMemOperand());
2934 
2935  SDValue BC = DAG.getNode(ISD::BITCAST, SL, VT, NewLoad);
2936  DCI.CombineTo(N, BC, NewLoad.getValue(1));
2937  return SDValue(N, 0);
2938 }
2939 
2940 // Replace store of an illegal type with a store of a bitcast to a friendlier
2941 // type.
2943  DAGCombinerInfo &DCI) const {
2944  if (!DCI.isBeforeLegalize())
2945  return SDValue();
2946 
2947  StoreSDNode *SN = cast<StoreSDNode>(N);
2948  if (SN->isVolatile() || !ISD::isNormalStore(SN))
2949  return SDValue();
2950 
2951  EVT VT = SN->getMemoryVT();
2952  unsigned Size = VT.getStoreSize();
2953 
2954  SDLoc SL(N);
2955  SelectionDAG &DAG = DCI.DAG;
2956  unsigned Align = SN->getAlignment();
2957  if (Align < Size && isTypeLegal(VT)) {
2958  bool IsFast;
2959  unsigned AS = SN->getAddressSpace();
2960 
2961  // Expand unaligned stores earlier than legalization. Due to visitation
2962  // order problems during legalization, the emitted instructions to pack and
2963  // unpack the bytes again are not eliminated in the case of an unaligned
2964  // copy.
2965  if (!allowsMisalignedMemoryAccesses(VT, AS, Align, &IsFast)) {
2966  if (VT.isVector())
2967  return scalarizeVectorStore(SN, DAG);
2968 
2969  return expandUnalignedStore(SN, DAG);
2970  }
2971 
2972  if (!IsFast)
2973  return SDValue();
2974  }
2975 
2976  if (!shouldCombineMemoryType(VT))
2977  return SDValue();
2978 
2979  EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
2980  SDValue Val = SN->getValue();
2981 
2982  //DCI.AddToWorklist(Val.getNode());
2983 
2984  bool OtherUses = !Val.hasOneUse();
2985  SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NewVT, Val);
2986  if (OtherUses) {
2987  SDValue CastBack = DAG.getNode(ISD::BITCAST, SL, VT, CastVal);
2988  DAG.ReplaceAllUsesOfValueWith(Val, CastBack);
2989  }
2990 
2991  return DAG.getStore(SN->getChain(), SL, CastVal,
2992  SN->getBasePtr(), SN->getMemOperand());
2993 }
2994 
2995 // FIXME: This should go in generic DAG combiner with an isTruncateFree check,
2996 // but isTruncateFree is inaccurate for i16 now because of SALU vs. VALU
2997 // issues.
2999  DAGCombinerInfo &DCI) const {
3000  SelectionDAG &DAG = DCI.DAG;
3001  SDValue N0 = N->getOperand(0);
3002 
3003  // (vt2 (assertzext (truncate vt0:x), vt1)) ->
3004  // (vt2 (truncate (assertzext vt0:x, vt1)))
3005  if (N0.getOpcode() == ISD::TRUNCATE) {
3006  SDValue N1 = N->getOperand(1);
3007  EVT ExtVT = cast<VTSDNode>(N1)->getVT();
3008  SDLoc SL(N);
3009 
3010  SDValue Src = N0.getOperand(0);
3011  EVT SrcVT = Src.getValueType();
3012  if (SrcVT.bitsGE(ExtVT)) {
3013  SDValue NewInReg = DAG.getNode(N->getOpcode(), SL, SrcVT, Src, N1);
3014  return DAG.getNode(ISD::TRUNCATE, SL, N->getValueType(0), NewInReg);
3015  }
3016  }
3017 
3018  return SDValue();
3019 }
3020 /// Split the 64-bit value \p LHS into two 32-bit components, and perform the
3021 /// binary operation \p Opc to it with the corresponding constant operands.
3023  DAGCombinerInfo &DCI, const SDLoc &SL,
3024  unsigned Opc, SDValue LHS,
3025  uint32_t ValLo, uint32_t ValHi) const {
3026  SelectionDAG &DAG = DCI.DAG;
3027  SDValue Lo, Hi;
3028  std::tie(Lo, Hi) = split64BitValue(LHS, DAG);
3029 
3030  SDValue LoRHS = DAG.getConstant(ValLo, SL, MVT::i32);
3031  SDValue HiRHS = DAG.getConstant(ValHi, SL, MVT::i32);
3032 
3033  SDValue LoAnd = DAG.getNode(Opc, SL, MVT::i32, Lo, LoRHS);
3034  SDValue HiAnd = DAG.getNode(Opc, SL, MVT::i32, Hi, HiRHS);
3035 
3036  // Re-visit the ands. It's possible we eliminated one of them and it could
3037  // simplify the vector.
3038  DCI.AddToWorklist(Lo.getNode());
3039  DCI.AddToWorklist(Hi.getNode());
3040 
3041  SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {LoAnd, HiAnd});
3042  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3043 }
3044 
3046  DAGCombinerInfo &DCI) const {
3047  EVT VT = N->getValueType(0);
3048 
3050  if (!RHS)
3051  return SDValue();
3052 
3053  SDValue LHS = N->getOperand(0);
3054  unsigned RHSVal = RHS->getZExtValue();
3055  if (!RHSVal)
3056  return LHS;
3057 
3058  SDLoc SL(N);
3059  SelectionDAG &DAG = DCI.DAG;
3060 
3061  switch (LHS->getOpcode()) {
3062  default:
3063  break;
3064  case ISD::ZERO_EXTEND:
3065  case ISD::SIGN_EXTEND:
3066  case ISD::ANY_EXTEND: {
3067  SDValue X = LHS->getOperand(0);
3068 
3069  if (VT == MVT::i32 && RHSVal == 16 && X.getValueType() == MVT::i16 &&
3071  // Prefer build_vector as the canonical form if packed types are legal.
3072  // (shl ([asz]ext i16:x), 16 -> build_vector 0, x
3073  SDValue Vec = DAG.getBuildVector(MVT::v2i16, SL,
3074  { DAG.getConstant(0, SL, MVT::i16), LHS->getOperand(0) });
3075  return DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec);
3076  }
3077 
3078  // shl (ext x) => zext (shl x), if shift does not overflow int
3079  if (VT != MVT::i64)
3080  break;
3081  KnownBits Known = DAG.computeKnownBits(X);
3082  unsigned LZ = Known.countMinLeadingZeros();
3083  if (LZ < RHSVal)
3084  break;
3085  EVT XVT = X.getValueType();
3086  SDValue Shl = DAG.getNode(ISD::SHL, SL, XVT, X, SDValue(RHS, 0));
3087  return DAG.getZExtOrTrunc(Shl, SL, VT);
3088  }
3089  }
3090 
3091  if (VT != MVT::i64)
3092  return SDValue();
3093 
3094  // i64 (shl x, C) -> (build_pair 0, (shl x, C -32))
3095 
3096  // On some subtargets, 64-bit shift is a quarter rate instruction. In the
3097  // common case, splitting this into a move and a 32-bit shift is faster and
3098  // the same code size.
3099  if (RHSVal < 32)
3100  return SDValue();
3101 
3102  SDValue ShiftAmt = DAG.getConstant(RHSVal - 32, SL, MVT::i32);
3103 
3104  SDValue Lo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, LHS);
3105  SDValue NewShift = DAG.getNode(ISD::SHL, SL, MVT::i32, Lo, ShiftAmt);
3106 
3107  const SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
3108 
3109  SDValue Vec = DAG.getBuildVector(MVT::v2i32, SL, {Zero, NewShift});
3110  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
3111 }
3112 
3114  DAGCombinerInfo &DCI) const {
3115  if (N->getValueType(0) != MVT::i64)
3116  return SDValue();
3117 
3118  const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3119  if (!RHS)
3120  return SDValue();
3121 
3122  SelectionDAG &DAG = DCI.DAG;
3123  SDLoc SL(N);
3124  unsigned RHSVal = RHS->getZExtValue();
3125 
3126  // (sra i64:x, 32) -> build_pair x, (sra hi_32(x), 31)
3127  if (RHSVal == 32) {
3128  SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
3129  SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
3130  DAG.getConstant(31, SL, MVT::i32));
3131 
3132  SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {Hi, NewShift});
3133  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
3134  }
3135 
3136  // (sra i64:x, 63) -> build_pair (sra hi_32(x), 31), (sra hi_32(x), 31)
3137  if (RHSVal == 63) {
3138  SDValue Hi = getHiHalf64(N->getOperand(0), DAG);
3139  SDValue NewShift = DAG.getNode(ISD::SRA, SL, MVT::i32, Hi,
3140  DAG.getConstant(31, SL, MVT::i32));
3141  SDValue BuildVec = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, NewShift});
3142  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildVec);
3143  }
3144 
3145  return SDValue();
3146 }
3147 
3149  DAGCombinerInfo &DCI) const {
3150  if (N->getValueType(0) != MVT::i64)
3151  return SDValue();
3152 
3153  const ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
3154  if (!RHS)
3155  return SDValue();
3156 
3157  unsigned ShiftAmt = RHS->getZExtValue();
3158  if (ShiftAmt < 32)
3159  return SDValue();
3160 
3161  // srl i64:x, C for C >= 32
3162  // =>
3163  // build_pair (srl hi_32(x), C - 32), 0
3164 
3165  SelectionDAG &DAG = DCI.DAG;
3166  SDLoc SL(N);
3167 
3168  SDValue One = DAG.getConstant(1, SL, MVT::i32);
3169  SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
3170 
3171  SDValue VecOp = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, N->getOperand(0));
3173  VecOp, One);
3174 
3175  SDValue NewConst = DAG.getConstant(ShiftAmt - 32, SL, MVT::i32);
3176  SDValue NewShift = DAG.getNode(ISD::SRL, SL, MVT::i32, Hi, NewConst);
3177 
3178  SDValue BuildPair = DAG.getBuildVector(MVT::v2i32, SL, {NewShift, Zero});
3179 
3180  return DAG.getNode(ISD::BITCAST, SL, MVT::i64, BuildPair);
3181 }
3182 
3184  SDNode *N, DAGCombinerInfo &DCI) const {
3185  SDLoc SL(N);
3186  SelectionDAG &DAG = DCI.DAG;
3187  EVT VT = N->getValueType(0);
3188  SDValue Src = N->getOperand(0);
3189 
3190  // vt1 (truncate (bitcast (build_vector vt0:x, ...))) -> vt1 (bitcast vt0:x)
3191  if (Src.getOpcode() == ISD::BITCAST && !VT.isVector()) {
3192  SDValue Vec = Src.getOperand(0);
3193  if (Vec.getOpcode() == ISD::BUILD_VECTOR) {
3194  SDValue Elt0 = Vec.getOperand(0);
3195  EVT EltVT = Elt0.getValueType();
3196  if (VT.getSizeInBits() <= EltVT.getSizeInBits()) {
3197  if (EltVT.isFloatingPoint()) {
3198  Elt0 = DAG.getNode(ISD::BITCAST, SL,
3199  EltVT.changeTypeToInteger(), Elt0);
3200  }
3201 
3202  return DAG.getNode(ISD::TRUNCATE, SL, VT, Elt0);
3203  }
3204  }
3205  }
3206 
3207  // Equivalent of above for accessing the high element of a vector as an
3208  // integer operation.
3209  // trunc (srl (bitcast (build_vector x, y))), 16 -> trunc (bitcast y)
3210  if (Src.getOpcode() == ISD::SRL && !VT.isVector()) {
3211  if (auto K = isConstOrConstSplat(Src.getOperand(1))) {
3212  if (2 * K->getZExtValue() == Src.getValueType().getScalarSizeInBits()) {
3213  SDValue BV = stripBitcast(Src.getOperand(0));
3214  if (BV.getOpcode() == ISD::BUILD_VECTOR &&
3215  BV.getValueType().getVectorNumElements() == 2) {
3216  SDValue SrcElt = BV.getOperand(1);
3217  EVT SrcEltVT = SrcElt.getValueType();
3218  if (SrcEltVT.isFloatingPoint()) {
3219  SrcElt = DAG.getNode(ISD::BITCAST, SL,
3220  SrcEltVT.changeTypeToInteger(), SrcElt);
3221  }
3222 
3223  return DAG.getNode(ISD::TRUNCATE, SL, VT, SrcElt);
3224  }
3225  }
3226  }
3227  }
3228 
3229  // Partially shrink 64-bit shifts to 32-bit if reduced to 16-bit.
3230  //
3231  // i16 (trunc (srl i64:x, K)), K <= 16 ->
3232  // i16 (trunc (srl (i32 (trunc x), K)))
3233  if (VT.getScalarSizeInBits() < 32) {
3234  EVT SrcVT = Src.getValueType();
3235  if (SrcVT.getScalarSizeInBits() > 32 &&
3236  (Src.getOpcode() == ISD::SRL ||
3237  Src.getOpcode() == ISD::SRA ||
3238  Src.getOpcode() == ISD::SHL)) {
3239  SDValue Amt = Src.getOperand(1);
3240  KnownBits Known = DAG.computeKnownBits(Amt);
3241  unsigned Size = VT.getScalarSizeInBits();
3242  if ((Known.isConstant() && Known.getConstant().ule(Size)) ||
3243  (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size))) {
3244  EVT MidVT = VT.isVector() ?
3247 
3248  EVT NewShiftVT = getShiftAmountTy(MidVT, DAG.getDataLayout());
3249  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MidVT,
3250  Src.getOperand(0));
3251  DCI.AddToWorklist(Trunc.getNode());
3252 
3253  if (Amt.getValueType() != NewShiftVT) {
3254  Amt = DAG.getZExtOrTrunc(Amt, SL, NewShiftVT);
3255  DCI.AddToWorklist(Amt.getNode());
3256  }
3257 
3258  SDValue ShrunkShift = DAG.getNode(Src.getOpcode(), SL, MidVT,
3259  Trunc, Amt);
3260  return DAG.getNode(ISD::TRUNCATE, SL, VT, ShrunkShift);
3261  }
3262  }
3263  }
3264 
3265  return SDValue();
3266 }
3267 
3268 // We need to specifically handle i64 mul here to avoid unnecessary conversion
3269 // instructions. If we only match on the legalized i64 mul expansion,
3270 // SimplifyDemandedBits will be unable to remove them because there will be
3271 // multiple uses due to the separate mul + mulh[su].
3272 static SDValue getMul24(SelectionDAG &DAG, const SDLoc &SL,
3273  SDValue N0, SDValue N1, unsigned Size, bool Signed) {
3274  if (Size <= 32) {
3275  unsigned MulOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3276  return DAG.getNode(MulOpc, SL, MVT::i32, N0, N1);
3277  }
3278 
3279  // Because we want to eliminate extension instructions before the
3280  // operation, we need to create a single user here (i.e. not the separate
3281  // mul_lo + mul_hi) so that SimplifyDemandedBits will deal with it.
3282 
3283  unsigned MulOpc = Signed ? AMDGPUISD::MUL_LOHI_I24 : AMDGPUISD::MUL_LOHI_U24;
3284 
3285  SDValue Mul = DAG.getNode(MulOpc, SL,
3286  DAG.getVTList(MVT::i32, MVT::i32), N0, N1);
3287 
3288  return DAG.getNode(ISD::BUILD_PAIR, SL, MVT::i64,
3289  Mul.getValue(0), Mul.getValue(1));
3290 }
3291 
3293  DAGCombinerInfo &DCI) const {
3294  EVT VT = N->getValueType(0);
3295 
3296  unsigned Size = VT.getSizeInBits();
3297  if (VT.isVector() || Size > 64)
3298  return SDValue();
3299 
3300  // There are i16 integer mul/mad.
3301  if (Subtarget->has16BitInsts() && VT.getScalarType().bitsLE(MVT::i16))
3302  return SDValue();
3303 
3304  SelectionDAG &DAG = DCI.DAG;
3305  SDLoc DL(N);
3306 
3307  SDValue N0 = N->getOperand(0);
3308  SDValue N1 = N->getOperand(1);
3309 
3310  // SimplifyDemandedBits has the annoying habit of turning useful zero_extends
3311  // in the source into any_extends if the result of the mul is truncated. Since
3312  // we can assume the high bits are whatever we want, use the underlying value
3313  // to avoid the unknown high bits from interfering.
3314  if (N0.getOpcode() == ISD::ANY_EXTEND)
3315  N0 = N0.getOperand(0);
3316 
3317  if (N1.getOpcode() == ISD::ANY_EXTEND)
3318  N1 = N1.getOperand(0);
3319 
3320  SDValue Mul;
3321 
3322  if (Subtarget->hasMulU24() && isU24(N0, DAG) && isU24(N1, DAG)) {
3323  N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3324  N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3325  Mul = getMul24(DAG, DL, N0, N1, Size, false);
3326  } else if (Subtarget->hasMulI24() && isI24(N0, DAG) && isI24(N1, DAG)) {
3327  N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3328  N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3329  Mul = getMul24(DAG, DL, N0, N1, Size, true);
3330  } else {
3331  return SDValue();
3332  }
3333 
3334  // We need to use sext even for MUL_U24, because MUL_U24 is used
3335  // for signed multiply of 8 and 16-bit types.
3336  return DAG.getSExtOrTrunc(Mul, DL, VT);
3337 }
3338 
3340  DAGCombinerInfo &DCI) const {
3341  EVT VT = N->getValueType(0);
3342 
3343  if (!Subtarget->hasMulI24() || VT.isVector())
3344  return SDValue();
3345 
3346  SelectionDAG &DAG = DCI.DAG;
3347  SDLoc DL(N);
3348 
3349  SDValue N0 = N->getOperand(0);
3350  SDValue N1 = N->getOperand(1);
3351 
3352  if (!isI24(N0, DAG) || !isI24(N1, DAG))
3353  return SDValue();
3354 
3355  N0 = DAG.getSExtOrTrunc(N0, DL, MVT::i32);
3356  N1 = DAG.getSExtOrTrunc(N1, DL, MVT::i32);
3357 
3358  SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_I24, DL, MVT::i32, N0, N1);
3359  DCI.AddToWorklist(Mulhi.getNode());
3360  return DAG.getSExtOrTrunc(Mulhi, DL, VT);
3361 }
3362 
3364  DAGCombinerInfo &DCI) const {
3365  EVT VT = N->getValueType(0);
3366 
3367  if (!Subtarget->hasMulU24() || VT.isVector() || VT.getSizeInBits() > 32)
3368  return SDValue();
3369 
3370  SelectionDAG &DAG = DCI.DAG;
3371  SDLoc DL(N);
3372 
3373  SDValue N0 = N->getOperand(0);
3374  SDValue N1 = N->getOperand(1);
3375 
3376  if (!isU24(N0, DAG) || !isU24(N1, DAG))
3377  return SDValue();
3378 
3379  N0 = DAG.getZExtOrTrunc(N0, DL, MVT::i32);
3380  N1 = DAG.getZExtOrTrunc(N1, DL, MVT::i32);
3381 
3382  SDValue Mulhi = DAG.getNode(AMDGPUISD::MULHI_U24, DL, MVT::i32, N0, N1);
3383  DCI.AddToWorklist(Mulhi.getNode());
3384  return DAG.getZExtOrTrunc(Mulhi, DL, VT);
3385 }
3386 
3388  SDNode *N, DAGCombinerInfo &DCI) const {
3389  SelectionDAG &DAG = DCI.DAG;
3390 
3391  // Simplify demanded bits before splitting into multiple users.
3392  if (SDValue V = simplifyI24(N, DCI))
3393  return V;
3394 
3395  SDValue N0 = N->getOperand(0);
3396  SDValue N1 = N->getOperand(1);
3397 
3398  bool Signed = (N->getOpcode() == AMDGPUISD::MUL_LOHI_I24);
3399 
3400  unsigned MulLoOpc = Signed ? AMDGPUISD::MUL_I24 : AMDGPUISD::MUL_U24;
3401  unsigned MulHiOpc = Signed ? AMDGPUISD::MULHI_I24 : AMDGPUISD::MULHI_U24;
3402 
3403  SDLoc SL(N);
3404 
3405  SDValue MulLo = DAG.getNode(MulLoOpc, SL, MVT::i32, N0, N1);
3406  SDValue MulHi = DAG.getNode(MulHiOpc, SL, MVT::i32, N0, N1);
3407  return DAG.getMergeValues({ MulLo, MulHi }, SL);
3408 }
3409 
3410 static bool isNegativeOne(SDValue Val) {
3411  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val))
3412  return C->isAllOnesValue();
3413  return false;
3414 }
3415 
3416 SDValue AMDGPUTargetLowering::getFFBX_U32(SelectionDAG &DAG,
3417  SDValue Op,
3418  const SDLoc &DL,
3419  unsigned Opc) const {
3420  EVT VT = Op.getValueType();
3421  EVT LegalVT = getTypeToTransformTo(*DAG.getContext(), VT);
3422  if (LegalVT != MVT::i32 && (Subtarget->has16BitInsts() &&
3423  LegalVT != MVT::i16))
3424  return SDValue();
3425 
3426  if (VT != MVT::i32)
3427  Op = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, Op);
3428 
3429  SDValue FFBX = DAG.getNode(Opc, DL, MVT::i32, Op);
3430  if (VT != MVT::i32)
3431  FFBX = DAG.getNode(ISD::TRUNCATE, DL, VT, FFBX);
3432 
3433  return FFBX;
3434 }
3435 
3436 // The native instructions return -1 on 0 input. Optimize out a select that
3437 // produces -1 on 0.
3438 //
3439 // TODO: If zero is not undef, we could also do this if the output is compared
3440 // against the bitwidth.
3441 //
3442 // TODO: Should probably combine against FFBH_U32 instead of ctlz directly.
3444  SDValue LHS, SDValue RHS,
3445  DAGCombinerInfo &DCI) const {
3446  ConstantSDNode *CmpRhs = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3447  if (!CmpRhs || !CmpRhs->isNullValue())
3448  return SDValue();
3449 
3450  SelectionDAG &DAG = DCI.DAG;
3451  ISD::CondCode CCOpcode = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
3452  SDValue CmpLHS = Cond.getOperand(0);
3453 
3454  unsigned Opc = isCttzOpc(RHS.getOpcode()) ? AMDGPUISD::FFBL_B32 :
3456 
3457  // select (setcc x, 0, eq), -1, (ctlz_zero_undef x) -> ffbh_u32 x
3458  // select (setcc x, 0, eq), -1, (cttz_zero_undef x) -> ffbl_u32 x
3459  if (CCOpcode == ISD::SETEQ &&
3460  (isCtlzOpc(RHS.getOpcode()) || isCttzOpc(RHS.getOpcode())) &&
3461  RHS.getOperand(0) == CmpLHS &&
3462  isNegativeOne(LHS)) {
3463  return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3464  }
3465 
3466  // select (setcc x, 0, ne), (ctlz_zero_undef x), -1 -> ffbh_u32 x
3467  // select (setcc x, 0, ne), (cttz_zero_undef x), -1 -> ffbl_u32 x
3468  if (CCOpcode == ISD::SETNE &&
3469  (isCtlzOpc(LHS.getOpcode()) || isCttzOpc(RHS.getOpcode())) &&
3470  LHS.getOperand(0) == CmpLHS &&
3471  isNegativeOne(RHS)) {
3472  return getFFBX_U32(DAG, CmpLHS, SL, Opc);
3473  }
3474 
3475  return SDValue();
3476 }
3477 
3479  unsigned Op,
3480  const SDLoc &SL,
3481  SDValue Cond,
3482  SDValue N1,
3483  SDValue N2) {
3484  SelectionDAG &DAG = DCI.DAG;
3485  EVT VT = N1.getValueType();
3486 
3487  SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT, Cond,
3488  N1.getOperand(0), N2.getOperand(0));
3489  DCI.AddToWorklist(NewSelect.getNode());
3490  return DAG.getNode(Op, SL, VT, NewSelect);
3491 }
3492 
3493 // Pull a free FP operation out of a select so it may fold into uses.
3494 //
3495 // select c, (fneg x), (fneg y) -> fneg (select c, x, y)
3496 // select c, (fneg x), k -> fneg (select c, x, (fneg k))
3497 //
3498 // select c, (fabs x), (fabs y) -> fabs (select c, x, y)
3499 // select c, (fabs x), +k -> fabs (select c, x, k)
3501  SDValue N) {
3502  SelectionDAG &DAG = DCI.DAG;
3503  SDValue Cond = N.getOperand(0);
3504  SDValue LHS = N.getOperand(1);
3505  SDValue RHS = N.getOperand(2);
3506 
3507  EVT VT = N.getValueType();
3508  if ((LHS.getOpcode() == ISD::FABS && RHS.getOpcode() == ISD::FABS) ||
3509  (LHS.getOpcode() == ISD::FNEG && RHS.getOpcode() == ISD::FNEG)) {
3510  return distributeOpThroughSelect(DCI, LHS.getOpcode(),
3511  SDLoc(N), Cond, LHS, RHS);
3512  }
3513 
3514  bool Inv = false;
3515  if (RHS.getOpcode() == ISD::FABS || RHS.getOpcode() == ISD::FNEG) {
3516  std::swap(LHS, RHS);
3517  Inv = true;
3518  }
3519 
3520  // TODO: Support vector constants.
3522  if ((LHS.getOpcode() == ISD::FNEG || LHS.getOpcode() == ISD::FABS) && CRHS) {
3523  SDLoc SL(N);
3524  // If one side is an fneg/fabs and the other is a constant, we can push the
3525  // fneg/fabs down. If it's an fabs, the constant needs to be non-negative.
3526  SDValue NewLHS = LHS.getOperand(0);
3527  SDValue NewRHS = RHS;
3528 
3529  // Careful: if the neg can be folded up, don't try to pull it back down.
3530  bool ShouldFoldNeg = true;
3531 
3532  if (NewLHS.hasOneUse()) {
3533  unsigned Opc = NewLHS.getOpcode();
3534  if (LHS.getOpcode() == ISD::FNEG && fnegFoldsIntoOp(Opc))
3535  ShouldFoldNeg = false;
3536  if (LHS.getOpcode() == ISD::FABS && Opc == ISD::FMUL)
3537  ShouldFoldNeg = false;
3538  }
3539 
3540  if (ShouldFoldNeg) {
3541  if (LHS.getOpcode() == ISD::FNEG)
3542  NewRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3543  else if (CRHS->isNegative())
3544  return SDValue();
3545 
3546  if (Inv)
3547  std::swap(NewLHS, NewRHS);
3548 
3549  SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, VT,
3550  Cond, NewLHS, NewRHS);
3551  DCI.AddToWorklist(NewSelect.getNode());
3552  return DAG.getNode(LHS.getOpcode(), SL, VT, NewSelect);
3553  }
3554  }
3555 
3556  return SDValue();
3557 }
3558 
3559 
3561  DAGCombinerInfo &DCI) const {
3562  if (SDValue Folded = foldFreeOpFromSelect(DCI, SDValue(N, 0)))
3563  return Folded;
3564 
3565  SDValue Cond = N->getOperand(0);
3566  if (Cond.getOpcode() != ISD::SETCC)
3567  return SDValue();
3568 
3569  EVT VT = N->getValueType(0);
3570  SDValue LHS = Cond.getOperand(0);
3571  SDValue RHS = Cond.getOperand(1);
3572  SDValue CC = Cond.getOperand(2);
3573 
3574  SDValue True = N->getOperand(1);
3575  SDValue False = N->getOperand(2);
3576 
3577  if (Cond.hasOneUse()) { // TODO: Look for multiple select uses.
3578  SelectionDAG &DAG = DCI.DAG;
3579  if ((DAG.isConstantValueOfAnyType(True) ||
3580  DAG.isConstantValueOfAnyType(True)) &&
3581  (!DAG.isConstantValueOfAnyType(False) &&
3582  !DAG.isConstantValueOfAnyType(False))) {
3583  // Swap cmp + select pair to move constant to false input.
3584  // This will allow using VOPC cndmasks more often.
3585  // select (setcc x, y), k, x -> select (setcc y, x) x, x
3586 
3587  SDLoc SL(N);
3588  ISD::CondCode NewCC = getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3589  LHS.getValueType().isInteger());
3590 
3591  SDValue NewCond = DAG.getSetCC(SL, Cond.getValueType(), LHS, RHS, NewCC);
3592  return DAG.getNode(ISD::SELECT, SL, VT, NewCond, False, True);
3593  }
3594 
3595  if (VT == MVT::f32 && Subtarget->hasFminFmaxLegacy()) {
3596  SDValue MinMax
3597  = combineFMinMaxLegacy(SDLoc(N), VT, LHS, RHS, True, False, CC, DCI);
3598  // Revisit this node so we can catch min3/max3/med3 patterns.
3599  //DCI.AddToWorklist(MinMax.getNode());
3600  return MinMax;
3601  }
3602  }
3603 
3604  // There's no reason to not do this if the condition has other uses.
3605  return performCtlz_CttzCombine(SDLoc(N), Cond, True, False, DCI);
3606 }
3607 
3608 static bool isInv2Pi(const APFloat &APF) {
3609  static const APFloat KF16(APFloat::IEEEhalf(), APInt(16, 0x3118));
3610  static const APFloat KF32(APFloat::IEEEsingle(), APInt(32, 0x3e22f983));
3611  static const APFloat KF64(APFloat::IEEEdouble(), APInt(64, 0x3fc45f306dc9c882));
3612 
3613  return APF.bitwiseIsEqual(KF16) ||
3614  APF.bitwiseIsEqual(KF32) ||
3615  APF.bitwiseIsEqual(KF64);
3616 }
3617 
3618 // 0 and 1.0 / (0.5 * pi) do not have inline immmediates, so there is an
3619 // additional cost to negate them.
3621  if (const ConstantFPSDNode *C = isConstOrConstSplatFP(N)) {
3622  if (C->isZero() && !C->isNegative())
3623  return true;
3624 
3625  if (Subtarget->hasInv2PiInlineImm() && isInv2Pi(C->getValueAPF()))
3626  return true;
3627  }
3628 
3629  return false;
3630 }
3631 
3632 static unsigned inverseMinMax(unsigned Opc) {
3633  switch (Opc) {
3634  case ISD::FMAXNUM:
3635  return ISD::FMINNUM;
3636  case ISD::FMINNUM:
3637  return ISD::FMAXNUM;
3638  case ISD::FMAXNUM_IEEE:
3639  return ISD::FMINNUM_IEEE;
3640  case ISD::FMINNUM_IEEE:
3641  return ISD::FMAXNUM_IEEE;
3643  return AMDGPUISD::FMIN_LEGACY;
3645  return AMDGPUISD::FMAX_LEGACY;
3646  default:
3647  llvm_unreachable("invalid min/max opcode");
3648  }
3649 }
3650 
3652  DAGCombinerInfo &DCI) const {
3653  SelectionDAG &DAG = DCI.DAG;
3654  SDValue N0 = N->getOperand(0);
3655  EVT VT = N->getValueType(0);
3656 
3657  unsigned Opc = N0.getOpcode();
3658 
3659  // If the input has multiple uses and we can either fold the negate down, or
3660  // the other uses cannot, give up. This both prevents unprofitable
3661  // transformations and infinite loops: we won't repeatedly try to fold around
3662  // a negate that has no 'good' form.
3663  if (N0.hasOneUse()) {
3664  // This may be able to fold into the source, but at a code size cost. Don't
3665  // fold if the fold into the user is free.
3666  if (allUsesHaveSourceMods(N, 0))
3667  return SDValue();
3668  } else {
3669  if (fnegFoldsIntoOp(Opc) &&
3671  return SDValue();
3672  }
3673 
3674  SDLoc SL(N);
3675  switch (Opc) {
3676  case ISD::FADD: {
3677  if (!mayIgnoreSignedZero(N0))
3678  return SDValue();
3679 
3680  // (fneg (fadd x, y)) -> (fadd (fneg x), (fneg y))
3681  SDValue LHS = N0.getOperand(0);
3682  SDValue RHS = N0.getOperand(1);
3683 
3684  if (LHS.getOpcode() != ISD::FNEG)
3685  LHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3686  else
3687  LHS = LHS.getOperand(0);
3688 
3689  if (RHS.getOpcode() != ISD::FNEG)
3690  RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3691  else
3692  RHS = RHS.getOperand(0);
3693 
3694  SDValue Res = DAG.getNode(ISD::FADD, SL, VT, LHS, RHS, N0->getFlags());
3695  if (Res.getOpcode() != ISD::FADD)
3696  return SDValue(); // Op got folded away.
3697  if (!N0.hasOneUse())
3698  DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3699  return Res;
3700  }
3701  case ISD::FMUL:
3702  case AMDGPUISD::FMUL_LEGACY: {
3703  // (fneg (fmul x, y)) -> (fmul x, (fneg y))
3704  // (fneg (fmul_legacy x, y)) -> (fmul_legacy x, (fneg y))
3705  SDValue LHS = N0.getOperand(0);
3706  SDValue RHS = N0.getOperand(1);
3707 
3708  if (LHS.getOpcode() == ISD::FNEG)
3709  LHS = LHS.getOperand(0);
3710  else if (RHS.getOpcode() == ISD::FNEG)
3711  RHS = RHS.getOperand(0);
3712  else
3713  RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3714 
3715  SDValue Res = DAG.getNode(Opc, SL, VT, LHS, RHS, N0->getFlags());
3716  if (Res.getOpcode() != Opc)
3717  return SDValue(); // Op got folded away.
3718  if (!N0.hasOneUse())
3719  DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3720  return Res;
3721  }
3722  case ISD::FMA:
3723  case ISD::FMAD: {
3724  if (!mayIgnoreSignedZero(N0))
3725  return SDValue();
3726 
3727  // (fneg (fma x, y, z)) -> (fma x, (fneg y), (fneg z))
3728  SDValue LHS = N0.getOperand(0);
3729  SDValue MHS = N0.getOperand(1);
3730  SDValue RHS = N0.getOperand(2);
3731 
3732  if (LHS.getOpcode() == ISD::FNEG)
3733  LHS = LHS.getOperand(0);
3734  else if (MHS.getOpcode() == ISD::FNEG)
3735  MHS = MHS.getOperand(0);
3736  else
3737  MHS = DAG.getNode(ISD::FNEG, SL, VT, MHS);
3738 
3739  if (RHS.getOpcode() != ISD::FNEG)
3740  RHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3741  else
3742  RHS = RHS.getOperand(0);
3743 
3744  SDValue Res = DAG.getNode(Opc, SL, VT, LHS, MHS, RHS);
3745  if (Res.getOpcode() != Opc)
3746  return SDValue(); // Op got folded away.
3747  if (!N0.hasOneUse())
3748  DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3749  return Res;
3750  }
3751  case ISD::FMAXNUM:
3752  case ISD::FMINNUM:
3753  case ISD::FMAXNUM_IEEE:
3754  case ISD::FMINNUM_IEEE:
3756  case AMDGPUISD::FMIN_LEGACY: {
3757  // fneg (fmaxnum x, y) -> fminnum (fneg x), (fneg y)
3758  // fneg (fminnum x, y) -> fmaxnum (fneg x), (fneg y)
3759  // fneg (fmax_legacy x, y) -> fmin_legacy (fneg x), (fneg y)
3760  // fneg (fmin_legacy x, y) -> fmax_legacy (fneg x), (fneg y)
3761 
3762  SDValue LHS = N0.getOperand(0);
3763  SDValue RHS = N0.getOperand(1);
3764 
3765  // 0 doesn't have a negated inline immediate.
3766  // TODO: This constant check should be generalized to other operations.
3767  if (isConstantCostlierToNegate(RHS))
3768  return SDValue();
3769 
3770  SDValue NegLHS = DAG.getNode(ISD::FNEG, SL, VT, LHS);
3771  SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
3772  unsigned Opposite = inverseMinMax(Opc);
3773 
3774  SDValue Res = DAG.getNode(Opposite, SL, VT, NegLHS, NegRHS, N0->getFlags());
3775  if (Res.getOpcode() != Opposite)
3776  return SDValue(); // Op got folded away.
3777  if (!N0.hasOneUse())
3778  DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3779  return Res;
3780  }
3781  case AMDGPUISD::FMED3: {
3782  SDValue Ops[3];
3783  for (unsigned I = 0; I < 3; ++I)
3784  Ops[I] = DAG.getNode(ISD::FNEG, SL, VT, N0->getOperand(I), N0->getFlags());
3785 
3786  SDValue Res = DAG.getNode(AMDGPUISD::FMED3, SL, VT, Ops, N0->getFlags());
3787  if (Res.getOpcode() != AMDGPUISD::FMED3)
3788  return SDValue(); // Op got folded away.
3789  if (!N0.hasOneUse())
3790  DAG.ReplaceAllUsesWith(N0, DAG.getNode(ISD::FNEG, SL, VT, Res));
3791  return Res;
3792  }
3793  case ISD::FP_EXTEND:
3794  case ISD::FTRUNC:
3795  case ISD::FRINT:
3796  case ISD::FNEARBYINT: // XXX - Should fround be handled?
3797  case ISD::FSIN:
3798  case ISD::FCANONICALIZE:
3799  case AMDGPUISD::RCP:
3800  case AMDGPUISD::RCP_LEGACY:
3801  case AMDGPUISD::RCP_IFLAG:
3802  case AMDGPUISD::SIN_HW: {
3803  SDValue CvtSrc = N0.getOperand(0);
3804  if (CvtSrc.getOpcode() == ISD::FNEG) {
3805  // (fneg (fp_extend (fneg x))) -> (fp_extend x)
3806  // (fneg (rcp (fneg x))) -> (rcp x)
3807  return DAG.getNode(Opc, SL, VT, CvtSrc.getOperand(0));
3808  }
3809 
3810  if (!N0.hasOneUse())
3811  return SDValue();
3812 
3813  // (fneg (fp_extend x)) -> (fp_extend (fneg x))
3814  // (fneg (rcp x)) -> (rcp (fneg x))
3815  SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3816  return DAG.getNode(Opc, SL, VT, Neg, N0->getFlags());
3817  }
3818  case ISD::FP_ROUND: {
3819  SDValue CvtSrc = N0.getOperand(0);
3820 
3821  if (CvtSrc.getOpcode() == ISD::FNEG) {
3822  // (fneg (fp_round (fneg x))) -> (fp_round x)
3823  return DAG.getNode(ISD::FP_ROUND, SL, VT,
3824  CvtSrc.getOperand(0), N0.getOperand(1));
3825  }
3826 
3827  if (!N0.hasOneUse())
3828  return SDValue();
3829 
3830  // (fneg (fp_round x)) -> (fp_round (fneg x))
3831  SDValue Neg = DAG.getNode(ISD::FNEG, SL, CvtSrc.getValueType(), CvtSrc);
3832  return DAG.getNode(ISD::FP_ROUND, SL, VT, Neg, N0.getOperand(1));
3833  }
3834  case ISD::FP16_TO_FP: {
3835  // v_cvt_f32_f16 supports source modifiers on pre-VI targets without legal
3836  // f16, but legalization of f16 fneg ends up pulling it out of the source.
3837  // Put the fneg back as a legal source operation that can be matched later.
3838  SDLoc SL(N);
3839 
3840  SDValue Src = N0.getOperand(0);
3841  EVT SrcVT = Src.getValueType();
3842 
3843  // fneg (fp16_to_fp x) -> fp16_to_fp (xor x, 0x8000)
3844  SDValue IntFNeg = DAG.getNode(ISD::XOR, SL, SrcVT, Src,
3845  DAG.getConstant(0x8000, SL, SrcVT));
3846  return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFNeg);
3847  }
3848  default:
3849  return SDValue();
3850  }
3851 }
3852 
3854  DAGCombinerInfo &DCI) const {
3855  SelectionDAG &DAG = DCI.DAG;
3856  SDValue N0 = N->getOperand(0);
3857 
3858  if (!N0.hasOneUse())
3859  return SDValue();
3860 
3861  switch (N0.getOpcode()) {
3862  case ISD::FP16_TO_FP: {
3863  assert(!Subtarget->has16BitInsts() && "should only see if f16 is illegal");
3864  SDLoc SL(N);
3865  SDValue Src = N0.getOperand(0);
3866  EVT SrcVT = Src.getValueType();
3867 
3868  // fabs (fp16_to_fp x) -> fp16_to_fp (and x, 0x7fff)
3869  SDValue IntFAbs = DAG.getNode(ISD::AND, SL, SrcVT, Src,
3870  DAG.getConstant(0x7fff, SL, SrcVT));
3871  return DAG.getNode(ISD::FP16_TO_FP, SL, N->getValueType(0), IntFAbs);
3872  }
3873  default:
3874  return SDValue();
3875  }
3876 }
3877 
3879  DAGCombinerInfo &DCI) const {
3880  const auto *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
3881  if (!CFP)
3882  return SDValue();
3883 
3884  // XXX - Should this flush denormals?
3885  const APFloat &Val = CFP->getValueAPF();
3886  APFloat One(Val.getSemantics(), "1.0");
3887  return DCI.DAG.getConstantFP(One / Val, SDLoc(N), N->getValueType(0));
3888 }
3889 
3891  DAGCombinerInfo &DCI) const {
3892  SelectionDAG &DAG = DCI.DAG;
3893  SDLoc DL(N);
3894 
3895  switch(N->getOpcode()) {
3896  default:
3897  break;
3898  case ISD::BITCAST: {
3899  EVT DestVT = N->getValueType(0);
3900 
3901  // Push casts through vector builds. This helps avoid emitting a large
3902  // number of copies when materializing floating point vector constants.
3903  //
3904  // vNt1 bitcast (vNt0 (build_vector t0:x, t0:y)) =>
3905  // vnt1 = build_vector (t1 (bitcast t0:x)), (t1 (bitcast t0:y))
3906  if (DestVT.isVector()) {
3907  SDValue Src = N->getOperand(0);
3908  if (Src.getOpcode() == ISD::BUILD_VECTOR) {
3909  EVT SrcVT = Src.getValueType();
3910  unsigned NElts = DestVT.getVectorNumElements();
3911 
3912  if (SrcVT.getVectorNumElements() == NElts) {
3913  EVT DestEltVT = DestVT.getVectorElementType();
3914 
3915  SmallVector<SDValue, 8> CastedElts;
3916  SDLoc SL(N);
3917  for (unsigned I = 0, E = SrcVT.getVectorNumElements(); I != E; ++I) {
3918  SDValue Elt = Src.getOperand(I);
3919  CastedElts.push_back(DAG.getNode(ISD::BITCAST, DL, DestEltVT, Elt));
3920  }
3921 
3922  return DAG.getBuildVector(DestVT, SL, CastedElts);
3923  }
3924  }
3925  }
3926 
3927  if (DestVT.getSizeInBits() != 64 && !DestVT.isVector())
3928  break;
3929 
3930  // Fold bitcasts of constants.
3931  //
3932  // v2i32 (bitcast i64:k) -> build_vector lo_32(k), hi_32(k)
3933  // TODO: Generalize and move to DAGCombiner
3934  SDValue Src = N->getOperand(0);
3935  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Src)) {
3936  if (Src.getValueType() == MVT::i64) {
3937  SDLoc SL(N);
3938  uint64_t CVal = C->getZExtValue();
3940  DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3941  DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3942  return DAG.getNode(ISD::BITCAST, SL, DestVT, BV);
3943  }
3944  }
3945 
3946  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Src)) {
3947  const APInt &Val = C->getValueAPF().bitcastToAPInt();
3948  SDLoc SL(N);
3949  uint64_t CVal = Val.getZExtValue();
3951  DAG.getConstant(Lo_32(CVal), SL, MVT::i32),
3952  DAG.getConstant(Hi_32(CVal), SL, MVT::i32));
3953 
3954  return DAG.getNode(ISD::BITCAST, SL, DestVT, Vec);
3955  }
3956 
3957  break;
3958  }
3959  case ISD::SHL: {
3961  break;
3962 
3963  return performShlCombine(N, DCI);
3964  }
3965  case ISD::SRL: {
3967  break;
3968 
3969  return performSrlCombine(N, DCI);
3970  }
3971  case ISD::SRA: {
3973  break;
3974 
3975  return performSraCombine(N, DCI);
3976  }
3977  case ISD::TRUNCATE:
3978  return performTruncateCombine(N, DCI);
3979  case ISD::MUL:
3980  return performMulCombine(N, DCI);
3981  case ISD::MULHS:
3982  return performMulhsCombine(N, DCI);
3983  case ISD::MULHU:
3984  return performMulhuCombine(N, DCI);
3985  case AMDGPUISD::MUL_I24:
3986  case AMDGPUISD::MUL_U24:
3987  case AMDGPUISD::MULHI_I24:
3988  case AMDGPUISD::MULHI_U24: {
3989  if (SDValue V = simplifyI24(N, DCI))
3990  return V;
3991  return SDValue();
3992  }
3995  return performMulLoHi24Combine(N, DCI);
3996  case ISD::SELECT:
3997  return performSelectCombine(N, DCI);
3998  case ISD::FNEG:
3999  return performFNegCombine(N, DCI);
4000  case ISD::FABS:
4001  return performFAbsCombine(N, DCI);
4002  case AMDGPUISD::BFE_I32:
4003  case AMDGPUISD::BFE_U32: {
4004  assert(!N->getValueType(0).isVector() &&
4005  "Vector handling of BFE not implemented");
4007  if (!Width)
4008  break;
4009 
4010  uint32_t WidthVal = Width->getZExtValue() & 0x1f;
4011  if (WidthVal == 0)
4012  return DAG.getConstant(0, DL, MVT::i32);
4013 
4015  if (!Offset)
4016  break;
4017 
4018  SDValue BitsFrom = N->getOperand(0);
4019  uint32_t OffsetVal = Offset->getZExtValue() & 0x1f;
4020 
4021  bool Signed = N->getOpcode() == AMDGPUISD::BFE_I32;
4022 
4023  if (OffsetVal == 0) {
4024  // This is already sign / zero extended, so try to fold away extra BFEs.
4025  unsigned SignBits = Signed ? (32 - WidthVal + 1) : (32 - WidthVal);
4026 
4027  unsigned OpSignBits = DAG.ComputeNumSignBits(BitsFrom);
4028  if (OpSignBits >= SignBits)
4029  return BitsFrom;
4030 
4031  EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), WidthVal);
4032  if (Signed) {
4033  // This is a sign_extend_inreg. Replace it to take advantage of existing
4034  // DAG Combines. If not eliminated, we will match back to BFE during
4035  // selection.
4036 
4037  // TODO: The sext_inreg of extended types ends, although we can could
4038  // handle them in a single BFE.
4039  return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i32, BitsFrom,
4040  DAG.getValueType(SmallVT));
4041  }
4042 
4043  return DAG.getZeroExtendInReg(BitsFrom, DL, SmallVT);
4044  }
4045 
4046  if (ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(BitsFrom)) {
4047  if (Signed) {
4048  return constantFoldBFE<int32_t>(DAG,
4049  CVal->getSExtValue(),
4050  OffsetVal,
4051  WidthVal,
4052  DL);
4053  }
4054 
4055  return constantFoldBFE<uint32_t>(DAG,
4056  CVal->getZExtValue(),
4057  OffsetVal,
4058  WidthVal,
4059  DL);
4060  }
4061 
4062  if ((OffsetVal + WidthVal) >= 32 &&
4063  !(Subtarget->hasSDWA() && OffsetVal == 16 && WidthVal == 16)) {
4064  SDValue ShiftVal = DAG.getConstant(OffsetVal, DL, MVT::i32);
4065  return DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, MVT::i32,
4066  BitsFrom, ShiftVal);
4067  }
4068 
4069  if (BitsFrom.hasOneUse()) {
4070  APInt Demanded = APInt::getBitsSet(32,
4071  OffsetVal,
4072  OffsetVal + WidthVal);
4073 
4074  KnownBits Known;
4076  !DCI.isBeforeLegalizeOps());
4077  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4078  if (TLI.ShrinkDemandedConstant(BitsFrom, Demanded, TLO) ||
4079  TLI.SimplifyDemandedBits(BitsFrom, Demanded, Known, TLO)) {
4080  DCI.CommitTargetLoweringOpt(TLO);
4081  }
4082  }
4083 
4084  break;
4085  }
4086  case ISD::LOAD:
4087  return performLoadCombine(N, DCI);
4088  case ISD::STORE:
4089  return performStoreCombine(N, DCI);
4090  case AMDGPUISD::RCP:
4091  case AMDGPUISD::RCP_IFLAG:
4092  return performRcpCombine(N, DCI);
4093  case ISD::AssertZext:
4094  case ISD::AssertSext:
4095  return performAssertSZExtCombine(N, DCI);
4096  }
4097  return SDValue();
4098 }
4099 
4100 //===----------------------------------------------------------------------===//
4101 // Helper functions
4102 //===----------------------------------------------------------------------===//
4103 
4105  const TargetRegisterClass *RC,
4106  unsigned Reg, EVT VT,
4107  const SDLoc &SL,
4108  bool RawReg) const {
4109  MachineFunction &MF = DAG.getMachineFunction();
4111  unsigned VReg;
4112 
4113  if (!MRI.isLiveIn(Reg)) {
4114  VReg = MRI.