1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/TargetLowering.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/CodeGen/CallingConvLower.h"
16 #include "llvm/CodeGen/CodeGenCommonISel.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineJumpTableInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/TargetRegisterInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/DivisionByConstantInfo.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/KnownBits.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include <cctype>
35 using namespace llvm;
36 
37 /// NOTE: The TargetMachine owns TLOF.
38 TargetLowering::TargetLowering(const TargetMachine &tm)
39     : TargetLoweringBase(tm) {}
40 
41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
42   return nullptr;
43 }
44 
45 bool TargetLowering::isPositionIndependent() const {
46   return getTargetMachine().isPositionIndependent();
47 }
48 
49 /// Check whether a given call node is in tail position within its function. If
50 /// so, it sets Chain to the input chain of the tail call.
51 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
52                                           SDValue &Chain) const {
53   const Function &F = DAG.getMachineFunction().getFunction();
54 
55   // First, check if tail calls have been disabled in this function.
56   if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
57     return false;
58 
59   // Conservatively require the attributes of the call to match those of
60   // the return. Ignore following attributes because they don't affect the
61   // call sequence.
62   AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
63   for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
64                            Attribute::DereferenceableOrNull, Attribute::NoAlias,
65                            Attribute::NonNull, Attribute::NoUndef})
66     CallerAttrs.removeAttribute(Attr);
67 
68   if (CallerAttrs.hasAttributes())
69     return false;
70 
71   // It's not safe to eliminate the sign / zero extension of the return value.
72   if (CallerAttrs.contains(Attribute::ZExt) ||
73       CallerAttrs.contains(Attribute::SExt))
74     return false;
75 
76   // Check if the only use is a function return node.
77   return isUsedByReturnOnly(Node, Chain);
78 }
79 
80 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
81     const uint32_t *CallerPreservedMask,
82     const SmallVectorImpl<CCValAssign> &ArgLocs,
83     const SmallVectorImpl<SDValue> &OutVals) const {
84   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
85     const CCValAssign &ArgLoc = ArgLocs[I];
86     if (!ArgLoc.isRegLoc())
87       continue;
88     MCRegister Reg = ArgLoc.getLocReg();
89     // Only look at callee saved registers.
90     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
91       continue;
92     // Check that we pass the value used for the caller.
93     // (We look for a CopyFromReg reading a virtual register that is used
94     //  for the function live-in value of register Reg)
95     SDValue Value = OutVals[I];
96     if (Value->getOpcode() == ISD::AssertZext)
97       Value = Value.getOperand(0);
98     if (Value->getOpcode() != ISD::CopyFromReg)
99       return false;
100     Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
101     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
102       return false;
103   }
104   return true;
105 }
106 
107 /// Set CallLoweringInfo attribute flags based on a call instruction
108 /// and called function attributes.
109 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call,
110                                                      unsigned ArgIdx) {
111   IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
112   IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
113   IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
114   IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
115   IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
116   IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
117   IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated);
118   IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
119   IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
120   IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
121   IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync);
122   IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
123   Alignment = Call->getParamStackAlign(ArgIdx);
124   IndirectType = nullptr;
125   assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 &&
126          "multiple ABI attributes?");
127   if (IsByVal) {
128     IndirectType = Call->getParamByValType(ArgIdx);
129     if (!Alignment)
130       Alignment = Call->getParamAlign(ArgIdx);
131   }
132   if (IsPreallocated)
133     IndirectType = Call->getParamPreallocatedType(ArgIdx);
134   if (IsInAlloca)
135     IndirectType = Call->getParamInAllocaType(ArgIdx);
136   if (IsSRet)
137     IndirectType = Call->getParamStructRetType(ArgIdx);
138 }
139 
140 /// Generate a libcall taking the given operands as arguments and returning a
141 /// result of type RetVT.
142 std::pair<SDValue, SDValue>
143 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
144                             ArrayRef<SDValue> Ops,
145                             MakeLibCallOptions CallOptions,
146                             const SDLoc &dl,
147                             SDValue InChain) const {
148   if (!InChain)
149     InChain = DAG.getEntryNode();
150 
151   TargetLowering::ArgListTy Args;
152   Args.reserve(Ops.size());
153 
154   TargetLowering::ArgListEntry Entry;
155   for (unsigned i = 0; i < Ops.size(); ++i) {
156     SDValue NewOp = Ops[i];
157     Entry.Node = NewOp;
158     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
159     Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(),
160                                                  CallOptions.IsSExt);
161     Entry.IsZExt = !Entry.IsSExt;
162 
163     if (CallOptions.IsSoften &&
164         !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) {
165       Entry.IsSExt = Entry.IsZExt = false;
166     }
167     Args.push_back(Entry);
168   }
169 
170   if (LC == RTLIB::UNKNOWN_LIBCALL)
171     report_fatal_error("Unsupported library call operation!");
172   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
173                                          getPointerTy(DAG.getDataLayout()));
174 
175   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
176   TargetLowering::CallLoweringInfo CLI(DAG);
177   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt);
178   bool zeroExtend = !signExtend;
179 
180   if (CallOptions.IsSoften &&
181       !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) {
182     signExtend = zeroExtend = false;
183   }
184 
185   CLI.setDebugLoc(dl)
186       .setChain(InChain)
187       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
188       .setNoReturn(CallOptions.DoesNotReturn)
189       .setDiscardResult(!CallOptions.IsReturnValueUsed)
190       .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization)
191       .setSExtResult(signExtend)
192       .setZExtResult(zeroExtend);
193   return LowerCallTo(CLI);
194 }
195 
196 bool TargetLowering::findOptimalMemOpLowering(
197     std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS,
198     unsigned SrcAS, const AttributeList &FuncAttributes) const {
199   if (Limit != ~unsigned(0) && Op.isMemcpyWithFixedDstAlign() &&
200       Op.getSrcAlign() < Op.getDstAlign())
201     return false;
202 
203   EVT VT = getOptimalMemOpType(Op, FuncAttributes);
204 
205   if (VT == MVT::Other) {
206     // Use the largest integer type whose alignment constraints are satisfied.
207     // We only need to check DstAlign here as SrcAlign is always greater or
208     // equal to DstAlign (or zero).
209     VT = MVT::i64;
210     if (Op.isFixedDstAlign())
211       while (Op.getDstAlign() < (VT.getSizeInBits() / 8) &&
212              !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign()))
213         VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
214     assert(VT.isInteger());
215 
216     // Find the largest legal integer type.
217     MVT LVT = MVT::i64;
218     while (!isTypeLegal(LVT))
219       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
220     assert(LVT.isInteger());
221 
222     // If the type we've chosen is larger than the largest legal integer type
223     // then use that instead.
224     if (VT.bitsGT(LVT))
225       VT = LVT;
226   }
227 
228   unsigned NumMemOps = 0;
229   uint64_t Size = Op.size();
230   while (Size) {
231     unsigned VTSize = VT.getSizeInBits() / 8;
232     while (VTSize > Size) {
233       // For now, only use non-vector load / store's for the left-over pieces.
234       EVT NewVT = VT;
235       unsigned NewVTSize;
236 
237       bool Found = false;
238       if (VT.isVector() || VT.isFloatingPoint()) {
239         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
240         if (isOperationLegalOrCustom(ISD::STORE, NewVT) &&
241             isSafeMemOpType(NewVT.getSimpleVT()))
242           Found = true;
243         else if (NewVT == MVT::i64 &&
244                  isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
245                  isSafeMemOpType(MVT::f64)) {
246           // i64 is usually not legal on 32-bit targets, but f64 may be.
247           NewVT = MVT::f64;
248           Found = true;
249         }
250       }
251 
252       if (!Found) {
253         do {
254           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
255           if (NewVT == MVT::i8)
256             break;
257         } while (!isSafeMemOpType(NewVT.getSimpleVT()));
258       }
259       NewVTSize = NewVT.getSizeInBits() / 8;
260 
261       // If the new VT cannot cover all of the remaining bits, then consider
262       // issuing a (or a pair of) unaligned and overlapping load / store.
263       bool Fast;
264       if (NumMemOps && Op.allowOverlap() && NewVTSize < Size &&
265           allowsMisalignedMemoryAccesses(
266               VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
267               MachineMemOperand::MONone, &Fast) &&
268           Fast)
269         VTSize = Size;
270       else {
271         VT = NewVT;
272         VTSize = NewVTSize;
273       }
274     }
275 
276     if (++NumMemOps > Limit)
277       return false;
278 
279     MemOps.push_back(VT);
280     Size -= VTSize;
281   }
282 
283   return true;
284 }
285 
286 /// Soften the operands of a comparison. This code is shared among BR_CC,
287 /// SELECT_CC, and SETCC handlers.
288 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
289                                          SDValue &NewLHS, SDValue &NewRHS,
290                                          ISD::CondCode &CCCode,
291                                          const SDLoc &dl, const SDValue OldLHS,
292                                          const SDValue OldRHS) const {
293   SDValue Chain;
294   return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
295                              OldRHS, Chain);
296 }
297 
298 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
299                                          SDValue &NewLHS, SDValue &NewRHS,
300                                          ISD::CondCode &CCCode,
301                                          const SDLoc &dl, const SDValue OldLHS,
302                                          const SDValue OldRHS,
303                                          SDValue &Chain,
304                                          bool IsSignaling) const {
305   // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
306   // not supporting it. We can update this code when libgcc provides such
307   // functions.
308 
309   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
310          && "Unsupported setcc type!");
311 
312   // Expand into one or more soft-fp libcall(s).
313   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
314   bool ShouldInvertCC = false;
315   switch (CCCode) {
316   case ISD::SETEQ:
317   case ISD::SETOEQ:
318     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
319           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
320           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
321     break;
322   case ISD::SETNE:
323   case ISD::SETUNE:
324     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
325           (VT == MVT::f64) ? RTLIB::UNE_F64 :
326           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
327     break;
328   case ISD::SETGE:
329   case ISD::SETOGE:
330     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
331           (VT == MVT::f64) ? RTLIB::OGE_F64 :
332           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
333     break;
334   case ISD::SETLT:
335   case ISD::SETOLT:
336     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
337           (VT == MVT::f64) ? RTLIB::OLT_F64 :
338           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
339     break;
340   case ISD::SETLE:
341   case ISD::SETOLE:
342     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
343           (VT == MVT::f64) ? RTLIB::OLE_F64 :
344           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
345     break;
346   case ISD::SETGT:
347   case ISD::SETOGT:
348     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
349           (VT == MVT::f64) ? RTLIB::OGT_F64 :
350           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
351     break;
352   case ISD::SETO:
353     ShouldInvertCC = true;
354     LLVM_FALLTHROUGH;
355   case ISD::SETUO:
356     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
357           (VT == MVT::f64) ? RTLIB::UO_F64 :
358           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
359     break;
360   case ISD::SETONE:
361     // SETONE = O && UNE
362     ShouldInvertCC = true;
363     LLVM_FALLTHROUGH;
364   case ISD::SETUEQ:
365     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
366           (VT == MVT::f64) ? RTLIB::UO_F64 :
367           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
368     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
369           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
370           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
371     break;
372   default:
373     // Invert CC for unordered comparisons
374     ShouldInvertCC = true;
375     switch (CCCode) {
376     case ISD::SETULT:
377       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
378             (VT == MVT::f64) ? RTLIB::OGE_F64 :
379             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
380       break;
381     case ISD::SETULE:
382       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
383             (VT == MVT::f64) ? RTLIB::OGT_F64 :
384             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
385       break;
386     case ISD::SETUGT:
387       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
388             (VT == MVT::f64) ? RTLIB::OLE_F64 :
389             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
390       break;
391     case ISD::SETUGE:
392       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
393             (VT == MVT::f64) ? RTLIB::OLT_F64 :
394             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
395       break;
396     default: llvm_unreachable("Do not know how to soften this setcc!");
397     }
398   }
399 
400   // Use the target specific return value for comparions lib calls.
401   EVT RetVT = getCmpLibcallReturnType();
402   SDValue Ops[2] = {NewLHS, NewRHS};
403   TargetLowering::MakeLibCallOptions CallOptions;
404   EVT OpsVT[2] = { OldLHS.getValueType(),
405                    OldRHS.getValueType() };
406   CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true);
407   auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain);
408   NewLHS = Call.first;
409   NewRHS = DAG.getConstant(0, dl, RetVT);
410 
411   CCCode = getCmpLibcallCC(LC1);
412   if (ShouldInvertCC) {
413     assert(RetVT.isInteger());
414     CCCode = getSetCCInverse(CCCode, RetVT);
415   }
416 
417   if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
418     // Update Chain.
419     Chain = Call.second;
420   } else {
421     EVT SetCCVT =
422         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
423     SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
424     auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain);
425     CCCode = getCmpLibcallCC(LC2);
426     if (ShouldInvertCC)
427       CCCode = getSetCCInverse(CCCode, RetVT);
428     NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
429     if (Chain)
430       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
431                           Call2.second);
432     NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
433                          Tmp.getValueType(), Tmp, NewLHS);
434     NewRHS = SDValue();
435   }
436 }
437 
438 /// Return the entry encoding for a jump table in the current function. The
439 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
440 unsigned TargetLowering::getJumpTableEncoding() const {
441   // In non-pic modes, just use the address of a block.
442   if (!isPositionIndependent())
443     return MachineJumpTableInfo::EK_BlockAddress;
444 
445   // In PIC mode, if the target supports a GPRel32 directive, use it.
446   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
447     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
448 
449   // Otherwise, use a label difference.
450   return MachineJumpTableInfo::EK_LabelDifference32;
451 }
452 
453 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
454                                                  SelectionDAG &DAG) const {
455   // If our PIC model is GP relative, use the global offset table as the base.
456   unsigned JTEncoding = getJumpTableEncoding();
457 
458   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
459       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
460     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
461 
462   return Table;
463 }
464 
465 /// This returns the relocation base for the given PIC jumptable, the same as
466 /// getPICJumpTableRelocBase, but as an MCExpr.
467 const MCExpr *
468 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
469                                              unsigned JTI,MCContext &Ctx) const{
470   // The normal PIC reloc base is the label at the start of the jump table.
471   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
472 }
473 
474 bool
475 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
476   const TargetMachine &TM = getTargetMachine();
477   const GlobalValue *GV = GA->getGlobal();
478 
479   // If the address is not even local to this DSO we will have to load it from
480   // a got and then add the offset.
481   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
482     return false;
483 
484   // If the code is position independent we will have to add a base register.
485   if (isPositionIndependent())
486     return false;
487 
488   // Otherwise we can do it.
489   return true;
490 }
491 
492 //===----------------------------------------------------------------------===//
493 //  Optimization Methods
494 //===----------------------------------------------------------------------===//
495 
496 /// If the specified instruction has a constant integer operand and there are
497 /// bits set in that constant that are not demanded, then clear those bits and
498 /// return true.
499 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
500                                             const APInt &DemandedBits,
501                                             const APInt &DemandedElts,
502                                             TargetLoweringOpt &TLO) const {
503   SDLoc DL(Op);
504   unsigned Opcode = Op.getOpcode();
505 
506   // Do target-specific constant optimization.
507   if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
508     return TLO.New.getNode();
509 
510   // FIXME: ISD::SELECT, ISD::SELECT_CC
511   switch (Opcode) {
512   default:
513     break;
514   case ISD::XOR:
515   case ISD::AND:
516   case ISD::OR: {
517     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
518     if (!Op1C || Op1C->isOpaque())
519       return false;
520 
521     // If this is a 'not' op, don't touch it because that's a canonical form.
522     const APInt &C = Op1C->getAPIntValue();
523     if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
524       return false;
525 
526     if (!C.isSubsetOf(DemandedBits)) {
527       EVT VT = Op.getValueType();
528       SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
529       SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
530       return TLO.CombineTo(Op, NewOp);
531     }
532 
533     break;
534   }
535   }
536 
537   return false;
538 }
539 
540 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
541                                             const APInt &DemandedBits,
542                                             TargetLoweringOpt &TLO) const {
543   EVT VT = Op.getValueType();
544   APInt DemandedElts = VT.isVector()
545                            ? APInt::getAllOnes(VT.getVectorNumElements())
546                            : APInt(1, 1);
547   return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
548 }
549 
550 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
551 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
552 /// generalized for targets with other types of implicit widening casts.
553 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
554                                       const APInt &Demanded,
555                                       TargetLoweringOpt &TLO) const {
556   assert(Op.getNumOperands() == 2 &&
557          "ShrinkDemandedOp only supports binary operators!");
558   assert(Op.getNode()->getNumValues() == 1 &&
559          "ShrinkDemandedOp only supports nodes with one result!");
560 
561   SelectionDAG &DAG = TLO.DAG;
562   SDLoc dl(Op);
563 
564   // Early return, as this function cannot handle vector types.
565   if (Op.getValueType().isVector())
566     return false;
567 
568   // Don't do this if the node has another user, which may require the
569   // full value.
570   if (!Op.getNode()->hasOneUse())
571     return false;
572 
573   // Search for the smallest integer type with free casts to and from
574   // Op's type. For expedience, just check power-of-2 integer types.
575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
576   unsigned DemandedSize = Demanded.getActiveBits();
577   unsigned SmallVTBits = DemandedSize;
578   if (!isPowerOf2_32(SmallVTBits))
579     SmallVTBits = NextPowerOf2(SmallVTBits);
580   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
581     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
582     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
583         TLI.isZExtFree(SmallVT, Op.getValueType())) {
584       // We found a type with free casts.
585       SDValue X = DAG.getNode(
586           Op.getOpcode(), dl, SmallVT,
587           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
588           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
589       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
590       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
591       return TLO.CombineTo(Op, Z);
592     }
593   }
594   return false;
595 }
596 
597 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
598                                           DAGCombinerInfo &DCI) const {
599   SelectionDAG &DAG = DCI.DAG;
600   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
601                         !DCI.isBeforeLegalizeOps());
602   KnownBits Known;
603 
604   bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
605   if (Simplified) {
606     DCI.AddToWorklist(Op.getNode());
607     DCI.CommitTargetLoweringOpt(TLO);
608   }
609   return Simplified;
610 }
611 
612 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
613                                           const APInt &DemandedElts,
614                                           DAGCombinerInfo &DCI) const {
615   SelectionDAG &DAG = DCI.DAG;
616   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
617                         !DCI.isBeforeLegalizeOps());
618   KnownBits Known;
619 
620   bool Simplified =
621       SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
622   if (Simplified) {
623     DCI.AddToWorklist(Op.getNode());
624     DCI.CommitTargetLoweringOpt(TLO);
625   }
626   return Simplified;
627 }
628 
629 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
630                                           KnownBits &Known,
631                                           TargetLoweringOpt &TLO,
632                                           unsigned Depth,
633                                           bool AssumeSingleUse) const {
634   EVT VT = Op.getValueType();
635 
636   // TODO: We can probably do more work on calculating the known bits and
637   // simplifying the operations for scalable vectors, but for now we just
638   // bail out.
639   if (VT.isScalableVector()) {
640     // Pretend we don't know anything for now.
641     Known = KnownBits(DemandedBits.getBitWidth());
642     return false;
643   }
644 
645   APInt DemandedElts = VT.isVector()
646                            ? APInt::getAllOnes(VT.getVectorNumElements())
647                            : APInt(1, 1);
648   return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
649                               AssumeSingleUse);
650 }
651 
652 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
653 // TODO: Under what circumstances can we create nodes? Constant folding?
654 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
655     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
656     SelectionDAG &DAG, unsigned Depth) const {
657   // Limit search depth.
658   if (Depth >= SelectionDAG::MaxRecursionDepth)
659     return SDValue();
660 
661   // Ignore UNDEFs.
662   if (Op.isUndef())
663     return SDValue();
664 
665   // Not demanding any bits/elts from Op.
666   if (DemandedBits == 0 || DemandedElts == 0)
667     return DAG.getUNDEF(Op.getValueType());
668 
669   bool IsLE = DAG.getDataLayout().isLittleEndian();
670   unsigned NumElts = DemandedElts.getBitWidth();
671   unsigned BitWidth = DemandedBits.getBitWidth();
672   KnownBits LHSKnown, RHSKnown;
673   switch (Op.getOpcode()) {
674   case ISD::BITCAST: {
675     SDValue Src = peekThroughBitcasts(Op.getOperand(0));
676     EVT SrcVT = Src.getValueType();
677     EVT DstVT = Op.getValueType();
678     if (SrcVT == DstVT)
679       return Src;
680 
681     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
682     unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
683     if (NumSrcEltBits == NumDstEltBits)
684       if (SDValue V = SimplifyMultipleUseDemandedBits(
685               Src, DemandedBits, DemandedElts, DAG, Depth + 1))
686         return DAG.getBitcast(DstVT, V);
687 
688     if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
689       unsigned Scale = NumDstEltBits / NumSrcEltBits;
690       unsigned NumSrcElts = SrcVT.getVectorNumElements();
691       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
692       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
693       for (unsigned i = 0; i != Scale; ++i) {
694         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
695         unsigned BitOffset = EltOffset * NumSrcEltBits;
696         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
697         if (!Sub.isZero()) {
698           DemandedSrcBits |= Sub;
699           for (unsigned j = 0; j != NumElts; ++j)
700             if (DemandedElts[j])
701               DemandedSrcElts.setBit((j * Scale) + i);
702         }
703       }
704 
705       if (SDValue V = SimplifyMultipleUseDemandedBits(
706               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
707         return DAG.getBitcast(DstVT, V);
708     }
709 
710     // TODO - bigendian once we have test coverage.
711     if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
712       unsigned Scale = NumSrcEltBits / NumDstEltBits;
713       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
714       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
715       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
716       for (unsigned i = 0; i != NumElts; ++i)
717         if (DemandedElts[i]) {
718           unsigned Offset = (i % Scale) * NumDstEltBits;
719           DemandedSrcBits.insertBits(DemandedBits, Offset);
720           DemandedSrcElts.setBit(i / Scale);
721         }
722 
723       if (SDValue V = SimplifyMultipleUseDemandedBits(
724               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
725         return DAG.getBitcast(DstVT, V);
726     }
727 
728     break;
729   }
730   case ISD::AND: {
731     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
732     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
733 
734     // If all of the demanded bits are known 1 on one side, return the other.
735     // These bits cannot contribute to the result of the 'and' in this
736     // context.
737     if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
738       return Op.getOperand(0);
739     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
740       return Op.getOperand(1);
741     break;
742   }
743   case ISD::OR: {
744     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
745     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
746 
747     // If all of the demanded bits are known zero on one side, return the
748     // other.  These bits cannot contribute to the result of the 'or' in this
749     // context.
750     if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
751       return Op.getOperand(0);
752     if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
753       return Op.getOperand(1);
754     break;
755   }
756   case ISD::XOR: {
757     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
758     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
759 
760     // If all of the demanded bits are known zero on one side, return the
761     // other.
762     if (DemandedBits.isSubsetOf(RHSKnown.Zero))
763       return Op.getOperand(0);
764     if (DemandedBits.isSubsetOf(LHSKnown.Zero))
765       return Op.getOperand(1);
766     break;
767   }
768   case ISD::SHL: {
769     // If we are only demanding sign bits then we can use the shift source
770     // directly.
771     if (const APInt *MaxSA =
772             DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
773       SDValue Op0 = Op.getOperand(0);
774       unsigned ShAmt = MaxSA->getZExtValue();
775       unsigned NumSignBits =
776           DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
777       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
778       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
779         return Op0;
780     }
781     break;
782   }
783   case ISD::SETCC: {
784     SDValue Op0 = Op.getOperand(0);
785     SDValue Op1 = Op.getOperand(1);
786     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
787     // If (1) we only need the sign-bit, (2) the setcc operands are the same
788     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
789     // -1, we may be able to bypass the setcc.
790     if (DemandedBits.isSignMask() &&
791         Op0.getScalarValueSizeInBits() == BitWidth &&
792         getBooleanContents(Op0.getValueType()) ==
793             BooleanContent::ZeroOrNegativeOneBooleanContent) {
794       // If we're testing X < 0, then this compare isn't needed - just use X!
795       // FIXME: We're limiting to integer types here, but this should also work
796       // if we don't care about FP signed-zero. The use of SETLT with FP means
797       // that we don't care about NaNs.
798       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
799           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
800         return Op0;
801     }
802     break;
803   }
804   case ISD::SIGN_EXTEND_INREG: {
805     // If none of the extended bits are demanded, eliminate the sextinreg.
806     SDValue Op0 = Op.getOperand(0);
807     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
808     unsigned ExBits = ExVT.getScalarSizeInBits();
809     if (DemandedBits.getActiveBits() <= ExBits)
810       return Op0;
811     // If the input is already sign extended, just drop the extension.
812     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
813     if (NumSignBits >= (BitWidth - ExBits + 1))
814       return Op0;
815     break;
816   }
817   case ISD::ANY_EXTEND_VECTOR_INREG:
818   case ISD::SIGN_EXTEND_VECTOR_INREG:
819   case ISD::ZERO_EXTEND_VECTOR_INREG: {
820     // If we only want the lowest element and none of extended bits, then we can
821     // return the bitcasted source vector.
822     SDValue Src = Op.getOperand(0);
823     EVT SrcVT = Src.getValueType();
824     EVT DstVT = Op.getValueType();
825     if (IsLE && DemandedElts == 1 &&
826         DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
827         DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
828       return DAG.getBitcast(DstVT, Src);
829     }
830     break;
831   }
832   case ISD::INSERT_VECTOR_ELT: {
833     // If we don't demand the inserted element, return the base vector.
834     SDValue Vec = Op.getOperand(0);
835     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
836     EVT VecVT = Vec.getValueType();
837     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
838         !DemandedElts[CIdx->getZExtValue()])
839       return Vec;
840     break;
841   }
842   case ISD::INSERT_SUBVECTOR: {
843     SDValue Vec = Op.getOperand(0);
844     SDValue Sub = Op.getOperand(1);
845     uint64_t Idx = Op.getConstantOperandVal(2);
846     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
847     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
848     // If we don't demand the inserted subvector, return the base vector.
849     if (DemandedSubElts == 0)
850       return Vec;
851     // If this simply widens the lowest subvector, see if we can do it earlier.
852     if (Idx == 0 && Vec.isUndef()) {
853       if (SDValue NewSub = SimplifyMultipleUseDemandedBits(
854               Sub, DemandedBits, DemandedSubElts, DAG, Depth + 1))
855         return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
856                            Op.getOperand(0), NewSub, Op.getOperand(2));
857     }
858     break;
859   }
860   case ISD::VECTOR_SHUFFLE: {
861     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
862 
863     // If all the demanded elts are from one operand and are inline,
864     // then we can use the operand directly.
865     bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
866     for (unsigned i = 0; i != NumElts; ++i) {
867       int M = ShuffleMask[i];
868       if (M < 0 || !DemandedElts[i])
869         continue;
870       AllUndef = false;
871       IdentityLHS &= (M == (int)i);
872       IdentityRHS &= ((M - NumElts) == i);
873     }
874 
875     if (AllUndef)
876       return DAG.getUNDEF(Op.getValueType());
877     if (IdentityLHS)
878       return Op.getOperand(0);
879     if (IdentityRHS)
880       return Op.getOperand(1);
881     break;
882   }
883   default:
884     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
885       if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode(
886               Op, DemandedBits, DemandedElts, DAG, Depth))
887         return V;
888     break;
889   }
890   return SDValue();
891 }
892 
893 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
894     SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG,
895     unsigned Depth) const {
896   EVT VT = Op.getValueType();
897   APInt DemandedElts = VT.isVector()
898                            ? APInt::getAllOnes(VT.getVectorNumElements())
899                            : APInt(1, 1);
900   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
901                                          Depth);
902 }
903 
904 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts(
905     SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
906     unsigned Depth) const {
907   APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
908   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
909                                          Depth);
910 }
911 
912 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
913 //      or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
914 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG,
915                                  const TargetLowering &TLI,
916                                  const APInt &DemandedBits,
917                                  const APInt &DemandedElts,
918                                  unsigned Depth) {
919   assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
920          "SRL or SRA node is required here!");
921   // Is the right shift using an immediate value of 1?
922   ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
923   if (!N1C || !N1C->isOne())
924     return SDValue();
925 
926   // We are looking for an avgfloor
927   // add(ext, ext)
928   // or one of these as a avgceil
929   // add(add(ext, ext), 1)
930   // add(add(ext, 1), ext)
931   // add(ext, add(ext, 1))
932   SDValue Add = Op.getOperand(0);
933   if (Add.getOpcode() != ISD::ADD)
934     return SDValue();
935 
936   SDValue ExtOpA = Add.getOperand(0);
937   SDValue ExtOpB = Add.getOperand(1);
938   auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3) {
939     ConstantSDNode *ConstOp;
940     if ((ConstOp = isConstOrConstSplat(Op1, DemandedElts)) &&
941         ConstOp->isOne()) {
942       ExtOpA = Op2;
943       ExtOpB = Op3;
944       return true;
945     }
946     if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
947         ConstOp->isOne()) {
948       ExtOpA = Op1;
949       ExtOpB = Op3;
950       return true;
951     }
952     if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
953         ConstOp->isOne()) {
954       ExtOpA = Op1;
955       ExtOpB = Op2;
956       return true;
957     }
958     return false;
959   };
960   bool IsCeil =
961       (ExtOpA.getOpcode() == ISD::ADD &&
962        MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB)) ||
963       (ExtOpB.getOpcode() == ISD::ADD &&
964        MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA));
965 
966   // If the shift is signed (sra):
967   //  - Needs >= 2 sign bit for both operands.
968   //  - Needs >= 2 zero bits.
969   // If the shift is unsigned (srl):
970   //  - Needs >= 1 zero bit for both operands.
971   //  - Needs 1 demanded bit zero and >= 2 sign bits.
972   unsigned ShiftOpc = Op.getOpcode();
973   bool IsSigned = false;
974   unsigned KnownBits;
975   unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
976   unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
977   unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
978   unsigned NumZeroA =
979       DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
980   unsigned NumZeroB =
981       DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
982   unsigned NumZero = std::min(NumZeroA, NumZeroB);
983 
984   switch (ShiftOpc) {
985   default:
986     llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
987   case ISD::SRA: {
988     if (NumZero >= 2 && NumSigned < NumZero) {
989       IsSigned = false;
990       KnownBits = NumZero;
991       break;
992     }
993     if (NumSigned >= 1) {
994       IsSigned = true;
995       KnownBits = NumSigned;
996       break;
997     }
998     return SDValue();
999   }
1000   case ISD::SRL: {
1001     if (NumZero >= 1 && NumSigned < NumZero) {
1002       IsSigned = false;
1003       KnownBits = NumZero;
1004       break;
1005     }
1006     if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1007       IsSigned = true;
1008       KnownBits = NumSigned;
1009       break;
1010     }
1011     return SDValue();
1012   }
1013   }
1014 
1015   unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1016                            : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1017 
1018   // Find the smallest power-2 type that is legal for this vector size and
1019   // operation, given the original type size and the number of known sign/zero
1020   // bits.
1021   EVT VT = Op.getValueType();
1022   unsigned MinWidth =
1023       std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1024   EVT NVT = EVT::getIntegerVT(*DAG.getContext(), PowerOf2Ceil(MinWidth));
1025   if (VT.isVector())
1026     NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1027   if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT))
1028     return SDValue();
1029 
1030   SDLoc DL(Op);
1031   SDValue ResultAVG =
1032       DAG.getNode(AVGOpc, DL, NVT, DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpA),
1033                   DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpB));
1034   return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT,
1035                      ResultAVG);
1036 }
1037 
1038 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1039 /// result of Op are ever used downstream. If we can use this information to
1040 /// simplify Op, create a new simplified DAG node and return true, returning the
1041 /// original and new nodes in Old and New. Otherwise, analyze the expression and
1042 /// return a mask of Known bits for the expression (used to simplify the
1043 /// caller).  The Known bits may only be accurate for those bits in the
1044 /// OriginalDemandedBits and OriginalDemandedElts.
1045 bool TargetLowering::SimplifyDemandedBits(
1046     SDValue Op, const APInt &OriginalDemandedBits,
1047     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1048     unsigned Depth, bool AssumeSingleUse) const {
1049   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1050   assert(Op.getScalarValueSizeInBits() == BitWidth &&
1051          "Mask size mismatches value type size!");
1052 
1053   // Don't know anything.
1054   Known = KnownBits(BitWidth);
1055 
1056   // TODO: We can probably do more work on calculating the known bits and
1057   // simplifying the operations for scalable vectors, but for now we just
1058   // bail out.
1059   if (Op.getValueType().isScalableVector())
1060     return false;
1061 
1062   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1063   unsigned NumElts = OriginalDemandedElts.getBitWidth();
1064   assert((!Op.getValueType().isVector() ||
1065           NumElts == Op.getValueType().getVectorNumElements()) &&
1066          "Unexpected vector size");
1067 
1068   APInt DemandedBits = OriginalDemandedBits;
1069   APInt DemandedElts = OriginalDemandedElts;
1070   SDLoc dl(Op);
1071   auto &DL = TLO.DAG.getDataLayout();
1072 
1073   // Undef operand.
1074   if (Op.isUndef())
1075     return false;
1076 
1077   if (Op.getOpcode() == ISD::Constant) {
1078     // We know all of the bits for a constant!
1079     Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue());
1080     return false;
1081   }
1082 
1083   if (Op.getOpcode() == ISD::ConstantFP) {
1084     // We know all of the bits for a floating point constant!
1085     Known = KnownBits::makeConstant(
1086         cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1087     return false;
1088   }
1089 
1090   // Other users may use these bits.
1091   EVT VT = Op.getValueType();
1092   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
1093     if (Depth != 0) {
1094       // If not at the root, Just compute the Known bits to
1095       // simplify things downstream.
1096       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1097       return false;
1098     }
1099     // If this is the root being simplified, allow it to have multiple uses,
1100     // just set the DemandedBits/Elts to all bits.
1101     DemandedBits = APInt::getAllOnes(BitWidth);
1102     DemandedElts = APInt::getAllOnes(NumElts);
1103   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1104     // Not demanding any bits/elts from Op.
1105     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1106   } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1107     // Limit search depth.
1108     return false;
1109   }
1110 
1111   KnownBits Known2;
1112   switch (Op.getOpcode()) {
1113   case ISD::TargetConstant:
1114     llvm_unreachable("Can't simplify this node");
1115   case ISD::SCALAR_TO_VECTOR: {
1116     if (!DemandedElts[0])
1117       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1118 
1119     KnownBits SrcKnown;
1120     SDValue Src = Op.getOperand(0);
1121     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1122     APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1123     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1124       return true;
1125 
1126     // Upper elements are undef, so only get the knownbits if we just demand
1127     // the bottom element.
1128     if (DemandedElts == 1)
1129       Known = SrcKnown.anyextOrTrunc(BitWidth);
1130     break;
1131   }
1132   case ISD::BUILD_VECTOR:
1133     // Collect the known bits that are shared by every demanded element.
1134     // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1135     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1136     return false; // Don't fall through, will infinitely loop.
1137   case ISD::LOAD: {
1138     auto *LD = cast<LoadSDNode>(Op);
1139     if (getTargetConstantFromLoad(LD)) {
1140       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1141       return false; // Don't fall through, will infinitely loop.
1142     }
1143     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1144       // If this is a ZEXTLoad and we are looking at the loaded value.
1145       EVT MemVT = LD->getMemoryVT();
1146       unsigned MemBits = MemVT.getScalarSizeInBits();
1147       Known.Zero.setBitsFrom(MemBits);
1148       return false; // Don't fall through, will infinitely loop.
1149     }
1150     break;
1151   }
1152   case ISD::INSERT_VECTOR_ELT: {
1153     SDValue Vec = Op.getOperand(0);
1154     SDValue Scl = Op.getOperand(1);
1155     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1156     EVT VecVT = Vec.getValueType();
1157 
1158     // If index isn't constant, assume we need all vector elements AND the
1159     // inserted element.
1160     APInt DemandedVecElts(DemandedElts);
1161     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1162       unsigned Idx = CIdx->getZExtValue();
1163       DemandedVecElts.clearBit(Idx);
1164 
1165       // Inserted element is not required.
1166       if (!DemandedElts[Idx])
1167         return TLO.CombineTo(Op, Vec);
1168     }
1169 
1170     KnownBits KnownScl;
1171     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1172     APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1173     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1174       return true;
1175 
1176     Known = KnownScl.anyextOrTrunc(BitWidth);
1177 
1178     KnownBits KnownVec;
1179     if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1180                              Depth + 1))
1181       return true;
1182 
1183     if (!!DemandedVecElts)
1184       Known = KnownBits::commonBits(Known, KnownVec);
1185 
1186     return false;
1187   }
1188   case ISD::INSERT_SUBVECTOR: {
1189     // Demand any elements from the subvector and the remainder from the src its
1190     // inserted into.
1191     SDValue Src = Op.getOperand(0);
1192     SDValue Sub = Op.getOperand(1);
1193     uint64_t Idx = Op.getConstantOperandVal(2);
1194     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1195     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1196     APInt DemandedSrcElts = DemandedElts;
1197     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
1198 
1199     KnownBits KnownSub, KnownSrc;
1200     if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1201                              Depth + 1))
1202       return true;
1203     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1204                              Depth + 1))
1205       return true;
1206 
1207     Known.Zero.setAllBits();
1208     Known.One.setAllBits();
1209     if (!!DemandedSubElts)
1210       Known = KnownBits::commonBits(Known, KnownSub);
1211     if (!!DemandedSrcElts)
1212       Known = KnownBits::commonBits(Known, KnownSrc);
1213 
1214     // Attempt to avoid multi-use src if we don't need anything from it.
1215     if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1216         !DemandedSrcElts.isAllOnes()) {
1217       SDValue NewSub = SimplifyMultipleUseDemandedBits(
1218           Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1219       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1220           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1221       if (NewSub || NewSrc) {
1222         NewSub = NewSub ? NewSub : Sub;
1223         NewSrc = NewSrc ? NewSrc : Src;
1224         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1225                                         Op.getOperand(2));
1226         return TLO.CombineTo(Op, NewOp);
1227       }
1228     }
1229     break;
1230   }
1231   case ISD::EXTRACT_SUBVECTOR: {
1232     // Offset the demanded elts by the subvector index.
1233     SDValue Src = Op.getOperand(0);
1234     if (Src.getValueType().isScalableVector())
1235       break;
1236     uint64_t Idx = Op.getConstantOperandVal(1);
1237     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1238     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1239 
1240     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1241                              Depth + 1))
1242       return true;
1243 
1244     // Attempt to avoid multi-use src if we don't need anything from it.
1245     if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1246       SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
1247           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1248       if (DemandedSrc) {
1249         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1250                                         Op.getOperand(1));
1251         return TLO.CombineTo(Op, NewOp);
1252       }
1253     }
1254     break;
1255   }
1256   case ISD::CONCAT_VECTORS: {
1257     Known.Zero.setAllBits();
1258     Known.One.setAllBits();
1259     EVT SubVT = Op.getOperand(0).getValueType();
1260     unsigned NumSubVecs = Op.getNumOperands();
1261     unsigned NumSubElts = SubVT.getVectorNumElements();
1262     for (unsigned i = 0; i != NumSubVecs; ++i) {
1263       APInt DemandedSubElts =
1264           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1265       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1266                                Known2, TLO, Depth + 1))
1267         return true;
1268       // Known bits are shared by every demanded subvector element.
1269       if (!!DemandedSubElts)
1270         Known = KnownBits::commonBits(Known, Known2);
1271     }
1272     break;
1273   }
1274   case ISD::VECTOR_SHUFFLE: {
1275     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1276 
1277     // Collect demanded elements from shuffle operands..
1278     APInt DemandedLHS(NumElts, 0);
1279     APInt DemandedRHS(NumElts, 0);
1280     for (unsigned i = 0; i != NumElts; ++i) {
1281       if (!DemandedElts[i])
1282         continue;
1283       int M = ShuffleMask[i];
1284       if (M < 0) {
1285         // For UNDEF elements, we don't know anything about the common state of
1286         // the shuffle result.
1287         DemandedLHS.clearAllBits();
1288         DemandedRHS.clearAllBits();
1289         break;
1290       }
1291       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
1292       if (M < (int)NumElts)
1293         DemandedLHS.setBit(M);
1294       else
1295         DemandedRHS.setBit(M - NumElts);
1296     }
1297 
1298     if (!!DemandedLHS || !!DemandedRHS) {
1299       SDValue Op0 = Op.getOperand(0);
1300       SDValue Op1 = Op.getOperand(1);
1301 
1302       Known.Zero.setAllBits();
1303       Known.One.setAllBits();
1304       if (!!DemandedLHS) {
1305         if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1306                                  Depth + 1))
1307           return true;
1308         Known = KnownBits::commonBits(Known, Known2);
1309       }
1310       if (!!DemandedRHS) {
1311         if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1312                                  Depth + 1))
1313           return true;
1314         Known = KnownBits::commonBits(Known, Known2);
1315       }
1316 
1317       // Attempt to avoid multi-use ops if we don't need anything from them.
1318       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1319           Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1320       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1321           Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1322       if (DemandedOp0 || DemandedOp1) {
1323         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1324         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1325         SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1326         return TLO.CombineTo(Op, NewOp);
1327       }
1328     }
1329     break;
1330   }
1331   case ISD::AND: {
1332     SDValue Op0 = Op.getOperand(0);
1333     SDValue Op1 = Op.getOperand(1);
1334 
1335     // If the RHS is a constant, check to see if the LHS would be zero without
1336     // using the bits from the RHS.  Below, we use knowledge about the RHS to
1337     // simplify the LHS, here we're using information from the LHS to simplify
1338     // the RHS.
1339     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
1340       // Do not increment Depth here; that can cause an infinite loop.
1341       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1342       // If the LHS already has zeros where RHSC does, this 'and' is dead.
1343       if ((LHSKnown.Zero & DemandedBits) ==
1344           (~RHSC->getAPIntValue() & DemandedBits))
1345         return TLO.CombineTo(Op, Op0);
1346 
1347       // If any of the set bits in the RHS are known zero on the LHS, shrink
1348       // the constant.
1349       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1350                                  DemandedElts, TLO))
1351         return true;
1352 
1353       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1354       // constant, but if this 'and' is only clearing bits that were just set by
1355       // the xor, then this 'and' can be eliminated by shrinking the mask of
1356       // the xor. For example, for a 32-bit X:
1357       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1358       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1359           LHSKnown.One == ~RHSC->getAPIntValue()) {
1360         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1361         return TLO.CombineTo(Op, Xor);
1362       }
1363     }
1364 
1365     // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1366     // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1367     if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR &&
1368         (Op0.getOperand(0).isUndef() ||
1369          ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) &&
1370         Op0->hasOneUse()) {
1371       unsigned NumSubElts =
1372           Op0.getOperand(1).getValueType().getVectorNumElements();
1373       unsigned SubIdx = Op0.getConstantOperandVal(2);
1374       APInt DemandedSub =
1375           APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1376       KnownBits KnownSubMask =
1377           TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1378       if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1379         SDValue NewAnd =
1380             TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1381         SDValue NewInsert =
1382             TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1383                             Op0.getOperand(1), Op0.getOperand(2));
1384         return TLO.CombineTo(Op, NewInsert);
1385       }
1386     }
1387 
1388     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1389                              Depth + 1))
1390       return true;
1391     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1392     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1393                              Known2, TLO, Depth + 1))
1394       return true;
1395     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1396 
1397     // If all of the demanded bits are known one on one side, return the other.
1398     // These bits cannot contribute to the result of the 'and'.
1399     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1400       return TLO.CombineTo(Op, Op0);
1401     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1402       return TLO.CombineTo(Op, Op1);
1403     // If all of the demanded bits in the inputs are known zeros, return zero.
1404     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1405       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1406     // If the RHS is a constant, see if we can simplify it.
1407     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1408                                TLO))
1409       return true;
1410     // If the operation can be done in a smaller type, do so.
1411     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1412       return true;
1413 
1414     // Attempt to avoid multi-use ops if we don't need anything from them.
1415     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1416       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1417           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1418       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1419           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1420       if (DemandedOp0 || DemandedOp1) {
1421         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1422         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1423         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1424         return TLO.CombineTo(Op, NewOp);
1425       }
1426     }
1427 
1428     Known &= Known2;
1429     break;
1430   }
1431   case ISD::OR: {
1432     SDValue Op0 = Op.getOperand(0);
1433     SDValue Op1 = Op.getOperand(1);
1434 
1435     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1436                              Depth + 1))
1437       return true;
1438     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1439     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1440                              Known2, TLO, Depth + 1))
1441       return true;
1442     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1443 
1444     // If all of the demanded bits are known zero on one side, return the other.
1445     // These bits cannot contribute to the result of the 'or'.
1446     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1447       return TLO.CombineTo(Op, Op0);
1448     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1449       return TLO.CombineTo(Op, Op1);
1450     // If the RHS is a constant, see if we can simplify it.
1451     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1452       return true;
1453     // If the operation can be done in a smaller type, do so.
1454     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1455       return true;
1456 
1457     // Attempt to avoid multi-use ops if we don't need anything from them.
1458     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1459       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1460           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1461       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1462           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1463       if (DemandedOp0 || DemandedOp1) {
1464         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1465         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1466         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1467         return TLO.CombineTo(Op, NewOp);
1468       }
1469     }
1470 
1471     Known |= Known2;
1472     break;
1473   }
1474   case ISD::XOR: {
1475     SDValue Op0 = Op.getOperand(0);
1476     SDValue Op1 = Op.getOperand(1);
1477 
1478     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1479                              Depth + 1))
1480       return true;
1481     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1482     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1483                              Depth + 1))
1484       return true;
1485     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1486 
1487     // If all of the demanded bits are known zero on one side, return the other.
1488     // These bits cannot contribute to the result of the 'xor'.
1489     if (DemandedBits.isSubsetOf(Known.Zero))
1490       return TLO.CombineTo(Op, Op0);
1491     if (DemandedBits.isSubsetOf(Known2.Zero))
1492       return TLO.CombineTo(Op, Op1);
1493     // If the operation can be done in a smaller type, do so.
1494     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1495       return true;
1496 
1497     // If all of the unknown bits are known to be zero on one side or the other
1498     // turn this into an *inclusive* or.
1499     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1500     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1501       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1502 
1503     ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1504     if (C) {
1505       // If one side is a constant, and all of the set bits in the constant are
1506       // also known set on the other side, turn this into an AND, as we know
1507       // the bits will be cleared.
1508       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1509       // NB: it is okay if more bits are known than are requested
1510       if (C->getAPIntValue() == Known2.One) {
1511         SDValue ANDC =
1512             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1513         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1514       }
1515 
1516       // If the RHS is a constant, see if we can change it. Don't alter a -1
1517       // constant because that's a 'not' op, and that is better for combining
1518       // and codegen.
1519       if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1520         // We're flipping all demanded bits. Flip the undemanded bits too.
1521         SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1522         return TLO.CombineTo(Op, New);
1523       }
1524 
1525       unsigned Op0Opcode = Op0.getOpcode();
1526       if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1527         if (ConstantSDNode *ShiftC =
1528                 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1529           // Don't crash on an oversized shift. We can not guarantee that a
1530           // bogus shift has been simplified to undef.
1531           if (ShiftC->getAPIntValue().ult(BitWidth)) {
1532             uint64_t ShiftAmt = ShiftC->getZExtValue();
1533             APInt Ones = APInt::getAllOnes(BitWidth);
1534             Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1535                                          : Ones.lshr(ShiftAmt);
1536             if (C->getAPIntValue() == Ones) {
1537               // If the xor constant is a shifted -1, do a 'not' before the
1538               // shift:
1539               // xor (X << ShiftC), XorC --> (not X) << ShiftC
1540               // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1541               SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1542               return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1543                                                        Op0.getOperand(1)));
1544             }
1545           }
1546         }
1547       }
1548     }
1549 
1550     // If we can't turn this into a 'not', try to shrink the constant.
1551     if (!C || !C->isAllOnes())
1552       if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1553         return true;
1554 
1555     // Attempt to avoid multi-use ops if we don't need anything from them.
1556     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1557       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1558           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1559       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1560           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1561       if (DemandedOp0 || DemandedOp1) {
1562         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1563         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1564         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1565         return TLO.CombineTo(Op, NewOp);
1566       }
1567     }
1568 
1569     Known ^= Known2;
1570     break;
1571   }
1572   case ISD::SELECT:
1573     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
1574                              Depth + 1))
1575       return true;
1576     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
1577                              Depth + 1))
1578       return true;
1579     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1580     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1581 
1582     // If the operands are constants, see if we can simplify them.
1583     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1584       return true;
1585 
1586     // Only known if known in both the LHS and RHS.
1587     Known = KnownBits::commonBits(Known, Known2);
1588     break;
1589   case ISD::VSELECT:
1590     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1591                              Known, TLO, Depth + 1))
1592       return true;
1593     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1594                              Known2, TLO, Depth + 1))
1595       return true;
1596     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1597     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1598 
1599     // Only known if known in both the LHS and RHS.
1600     Known = KnownBits::commonBits(Known, Known2);
1601     break;
1602   case ISD::SELECT_CC:
1603     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
1604                              Depth + 1))
1605       return true;
1606     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
1607                              Depth + 1))
1608       return true;
1609     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1610     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1611 
1612     // If the operands are constants, see if we can simplify them.
1613     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1614       return true;
1615 
1616     // Only known if known in both the LHS and RHS.
1617     Known = KnownBits::commonBits(Known, Known2);
1618     break;
1619   case ISD::SETCC: {
1620     SDValue Op0 = Op.getOperand(0);
1621     SDValue Op1 = Op.getOperand(1);
1622     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1623     // If (1) we only need the sign-bit, (2) the setcc operands are the same
1624     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1625     // -1, we may be able to bypass the setcc.
1626     if (DemandedBits.isSignMask() &&
1627         Op0.getScalarValueSizeInBits() == BitWidth &&
1628         getBooleanContents(Op0.getValueType()) ==
1629             BooleanContent::ZeroOrNegativeOneBooleanContent) {
1630       // If we're testing X < 0, then this compare isn't needed - just use X!
1631       // FIXME: We're limiting to integer types here, but this should also work
1632       // if we don't care about FP signed-zero. The use of SETLT with FP means
1633       // that we don't care about NaNs.
1634       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1635           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
1636         return TLO.CombineTo(Op, Op0);
1637 
1638       // TODO: Should we check for other forms of sign-bit comparisons?
1639       // Examples: X <= -1, X >= 0
1640     }
1641     if (getBooleanContents(Op0.getValueType()) ==
1642             TargetLowering::ZeroOrOneBooleanContent &&
1643         BitWidth > 1)
1644       Known.Zero.setBitsFrom(1);
1645     break;
1646   }
1647   case ISD::SHL: {
1648     SDValue Op0 = Op.getOperand(0);
1649     SDValue Op1 = Op.getOperand(1);
1650     EVT ShiftVT = Op1.getValueType();
1651 
1652     if (const APInt *SA =
1653             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1654       unsigned ShAmt = SA->getZExtValue();
1655       if (ShAmt == 0)
1656         return TLO.CombineTo(Op, Op0);
1657 
1658       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1659       // single shift.  We can do this if the bottom bits (which are shifted
1660       // out) are never demanded.
1661       // TODO - support non-uniform vector amounts.
1662       if (Op0.getOpcode() == ISD::SRL) {
1663         if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1664           if (const APInt *SA2 =
1665                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1666             unsigned C1 = SA2->getZExtValue();
1667             unsigned Opc = ISD::SHL;
1668             int Diff = ShAmt - C1;
1669             if (Diff < 0) {
1670               Diff = -Diff;
1671               Opc = ISD::SRL;
1672             }
1673             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1674             return TLO.CombineTo(
1675                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1676           }
1677         }
1678       }
1679 
1680       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1681       // are not demanded. This will likely allow the anyext to be folded away.
1682       // TODO - support non-uniform vector amounts.
1683       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1684         SDValue InnerOp = Op0.getOperand(0);
1685         EVT InnerVT = InnerOp.getValueType();
1686         unsigned InnerBits = InnerVT.getScalarSizeInBits();
1687         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1688             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1689           EVT ShTy = getShiftAmountTy(InnerVT, DL);
1690           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1691             ShTy = InnerVT;
1692           SDValue NarrowShl =
1693               TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1694                               TLO.DAG.getConstant(ShAmt, dl, ShTy));
1695           return TLO.CombineTo(
1696               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1697         }
1698 
1699         // Repeat the SHL optimization above in cases where an extension
1700         // intervenes: (shl (anyext (shr x, c1)), c2) to
1701         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
1702         // aren't demanded (as above) and that the shifted upper c1 bits of
1703         // x aren't demanded.
1704         // TODO - support non-uniform vector amounts.
1705         if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
1706             InnerOp.hasOneUse()) {
1707           if (const APInt *SA2 =
1708                   TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) {
1709             unsigned InnerShAmt = SA2->getZExtValue();
1710             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1711                 DemandedBits.getActiveBits() <=
1712                     (InnerBits - InnerShAmt + ShAmt) &&
1713                 DemandedBits.countTrailingZeros() >= ShAmt) {
1714               SDValue NewSA =
1715                   TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1716               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1717                                                InnerOp.getOperand(0));
1718               return TLO.CombineTo(
1719                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1720             }
1721           }
1722         }
1723       }
1724 
1725       APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1726       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1727                                Depth + 1))
1728         return true;
1729       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1730       Known.Zero <<= ShAmt;
1731       Known.One <<= ShAmt;
1732       // low bits known zero.
1733       Known.Zero.setLowBits(ShAmt);
1734 
1735       // Attempt to avoid multi-use ops if we don't need anything from them.
1736       if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1737         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1738             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1739         if (DemandedOp0) {
1740           SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
1741           return TLO.CombineTo(Op, NewOp);
1742         }
1743       }
1744 
1745       // Try shrinking the operation as long as the shift amount will still be
1746       // in range.
1747       if ((ShAmt < DemandedBits.getActiveBits()) &&
1748           ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1749         return true;
1750     } else {
1751       // This is a variable shift, so we can't shift the demand mask by a known
1752       // amount. But if we are not demanding high bits, then we are not
1753       // demanding those bits from the pre-shifted operand either.
1754       if (unsigned CTLZ = DemandedBits.countLeadingZeros()) {
1755         APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
1756         if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
1757                                  Depth + 1)) {
1758           SDNodeFlags Flags = Op.getNode()->getFlags();
1759           if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
1760             // Disable the nsw and nuw flags. We can no longer guarantee that we
1761             // won't wrap after simplification.
1762             Flags.setNoSignedWrap(false);
1763             Flags.setNoUnsignedWrap(false);
1764             Op->setFlags(Flags);
1765           }
1766           return true;
1767         }
1768         Known.resetAll();
1769       }
1770     }
1771 
1772     // If we are only demanding sign bits then we can use the shift source
1773     // directly.
1774     if (const APInt *MaxSA =
1775             TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
1776       unsigned ShAmt = MaxSA->getZExtValue();
1777       unsigned NumSignBits =
1778           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1779       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1780       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
1781         return TLO.CombineTo(Op, Op0);
1782     }
1783     break;
1784   }
1785   case ISD::SRL: {
1786     SDValue Op0 = Op.getOperand(0);
1787     SDValue Op1 = Op.getOperand(1);
1788     EVT ShiftVT = Op1.getValueType();
1789 
1790     // Try to match AVG patterns.
1791     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1792                                         DemandedElts, Depth + 1))
1793       return TLO.CombineTo(Op, AVG);
1794 
1795     if (const APInt *SA =
1796             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1797       unsigned ShAmt = SA->getZExtValue();
1798       if (ShAmt == 0)
1799         return TLO.CombineTo(Op, Op0);
1800 
1801       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1802       // single shift.  We can do this if the top bits (which are shifted out)
1803       // are never demanded.
1804       // TODO - support non-uniform vector amounts.
1805       if (Op0.getOpcode() == ISD::SHL) {
1806         if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
1807           if (const APInt *SA2 =
1808                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1809             unsigned C1 = SA2->getZExtValue();
1810             unsigned Opc = ISD::SRL;
1811             int Diff = ShAmt - C1;
1812             if (Diff < 0) {
1813               Diff = -Diff;
1814               Opc = ISD::SHL;
1815             }
1816             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1817             return TLO.CombineTo(
1818                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1819           }
1820         }
1821       }
1822 
1823       APInt InDemandedMask = (DemandedBits << ShAmt);
1824 
1825       // If the shift is exact, then it does demand the low bits (and knows that
1826       // they are zero).
1827       if (Op->getFlags().hasExact())
1828         InDemandedMask.setLowBits(ShAmt);
1829 
1830       // Compute the new bits that are at the top now.
1831       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1832                                Depth + 1))
1833         return true;
1834       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1835       Known.Zero.lshrInPlace(ShAmt);
1836       Known.One.lshrInPlace(ShAmt);
1837       // High bits known zero.
1838       Known.Zero.setHighBits(ShAmt);
1839     }
1840     break;
1841   }
1842   case ISD::SRA: {
1843     SDValue Op0 = Op.getOperand(0);
1844     SDValue Op1 = Op.getOperand(1);
1845     EVT ShiftVT = Op1.getValueType();
1846 
1847     // If we only want bits that already match the signbit then we don't need
1848     // to shift.
1849     unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1850     if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
1851         NumHiDemandedBits)
1852       return TLO.CombineTo(Op, Op0);
1853 
1854     // If this is an arithmetic shift right and only the low-bit is set, we can
1855     // always convert this into a logical shr, even if the shift amount is
1856     // variable.  The low bit of the shift cannot be an input sign bit unless
1857     // the shift amount is >= the size of the datatype, which is undefined.
1858     if (DemandedBits.isOne())
1859       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1860 
1861     // Try to match AVG patterns.
1862     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1863                                         DemandedElts, Depth + 1))
1864       return TLO.CombineTo(Op, AVG);
1865 
1866     if (const APInt *SA =
1867             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1868       unsigned ShAmt = SA->getZExtValue();
1869       if (ShAmt == 0)
1870         return TLO.CombineTo(Op, Op0);
1871 
1872       APInt InDemandedMask = (DemandedBits << ShAmt);
1873 
1874       // If the shift is exact, then it does demand the low bits (and knows that
1875       // they are zero).
1876       if (Op->getFlags().hasExact())
1877         InDemandedMask.setLowBits(ShAmt);
1878 
1879       // If any of the demanded bits are produced by the sign extension, we also
1880       // demand the input sign bit.
1881       if (DemandedBits.countLeadingZeros() < ShAmt)
1882         InDemandedMask.setSignBit();
1883 
1884       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1885                                Depth + 1))
1886         return true;
1887       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1888       Known.Zero.lshrInPlace(ShAmt);
1889       Known.One.lshrInPlace(ShAmt);
1890 
1891       // If the input sign bit is known to be zero, or if none of the top bits
1892       // are demanded, turn this into an unsigned shift right.
1893       if (Known.Zero[BitWidth - ShAmt - 1] ||
1894           DemandedBits.countLeadingZeros() >= ShAmt) {
1895         SDNodeFlags Flags;
1896         Flags.setExact(Op->getFlags().hasExact());
1897         return TLO.CombineTo(
1898             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
1899       }
1900 
1901       int Log2 = DemandedBits.exactLogBase2();
1902       if (Log2 >= 0) {
1903         // The bit must come from the sign.
1904         SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
1905         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
1906       }
1907 
1908       if (Known.One[BitWidth - ShAmt - 1])
1909         // New bits are known one.
1910         Known.One.setHighBits(ShAmt);
1911 
1912       // Attempt to avoid multi-use ops if we don't need anything from them.
1913       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1914         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1915             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1916         if (DemandedOp0) {
1917           SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
1918           return TLO.CombineTo(Op, NewOp);
1919         }
1920       }
1921     }
1922     break;
1923   }
1924   case ISD::FSHL:
1925   case ISD::FSHR: {
1926     SDValue Op0 = Op.getOperand(0);
1927     SDValue Op1 = Op.getOperand(1);
1928     SDValue Op2 = Op.getOperand(2);
1929     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
1930 
1931     if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
1932       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1933 
1934       // For fshl, 0-shift returns the 1st arg.
1935       // For fshr, 0-shift returns the 2nd arg.
1936       if (Amt == 0) {
1937         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
1938                                  Known, TLO, Depth + 1))
1939           return true;
1940         break;
1941       }
1942 
1943       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1944       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1945       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
1946       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
1947       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1948                                Depth + 1))
1949         return true;
1950       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
1951                                Depth + 1))
1952         return true;
1953 
1954       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
1955       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
1956       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1957       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1958       Known.One |= Known2.One;
1959       Known.Zero |= Known2.Zero;
1960 
1961       // Attempt to avoid multi-use ops if we don't need anything from them.
1962       if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
1963           !DemandedElts.isAllOnes()) {
1964         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1965             Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
1966         SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1967             Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
1968         if (DemandedOp0 || DemandedOp1) {
1969           DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
1970           DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
1971           SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
1972                                           DemandedOp1, Op2);
1973           return TLO.CombineTo(Op, NewOp);
1974         }
1975       }
1976     }
1977 
1978     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1979     if (isPowerOf2_32(BitWidth)) {
1980       APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
1981       if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts,
1982                                Known2, TLO, Depth + 1))
1983         return true;
1984     }
1985     break;
1986   }
1987   case ISD::ROTL:
1988   case ISD::ROTR: {
1989     SDValue Op0 = Op.getOperand(0);
1990     SDValue Op1 = Op.getOperand(1);
1991     bool IsROTL = (Op.getOpcode() == ISD::ROTL);
1992 
1993     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
1994     if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
1995       return TLO.CombineTo(Op, Op0);
1996 
1997     if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1998       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1999       unsigned RevAmt = BitWidth - Amt;
2000 
2001       // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2002       // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2003       APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2004       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2005                                Depth + 1))
2006         return true;
2007 
2008       // rot*(x, 0) --> x
2009       if (Amt == 0)
2010         return TLO.CombineTo(Op, Op0);
2011 
2012       // See if we don't demand either half of the rotated bits.
2013       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2014           DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) {
2015         Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2016         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2017       }
2018       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2019           DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) {
2020         Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2021         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2022       }
2023     }
2024 
2025     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2026     if (isPowerOf2_32(BitWidth)) {
2027       APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2028       if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2029                                Depth + 1))
2030         return true;
2031     }
2032     break;
2033   }
2034   case ISD::UMIN: {
2035     // Check if one arg is always less than (or equal) to the other arg.
2036     SDValue Op0 = Op.getOperand(0);
2037     SDValue Op1 = Op.getOperand(1);
2038     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2039     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2040     Known = KnownBits::umin(Known0, Known1);
2041     if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2042       return TLO.CombineTo(Op, IsULE.value() ? Op0 : Op1);
2043     if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2044       return TLO.CombineTo(Op, IsULT.value() ? Op0 : Op1);
2045     break;
2046   }
2047   case ISD::UMAX: {
2048     // Check if one arg is always greater than (or equal) to the other arg.
2049     SDValue Op0 = Op.getOperand(0);
2050     SDValue Op1 = Op.getOperand(1);
2051     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2052     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2053     Known = KnownBits::umax(Known0, Known1);
2054     if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2055       return TLO.CombineTo(Op, IsUGE.value() ? Op0 : Op1);
2056     if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2057       return TLO.CombineTo(Op, IsUGT.value() ? Op0 : Op1);
2058     break;
2059   }
2060   case ISD::BITREVERSE: {
2061     SDValue Src = Op.getOperand(0);
2062     APInt DemandedSrcBits = DemandedBits.reverseBits();
2063     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2064                              Depth + 1))
2065       return true;
2066     Known.One = Known2.One.reverseBits();
2067     Known.Zero = Known2.Zero.reverseBits();
2068     break;
2069   }
2070   case ISD::BSWAP: {
2071     SDValue Src = Op.getOperand(0);
2072 
2073     // If the only bits demanded come from one byte of the bswap result,
2074     // just shift the input byte into position to eliminate the bswap.
2075     unsigned NLZ = DemandedBits.countLeadingZeros();
2076     unsigned NTZ = DemandedBits.countTrailingZeros();
2077 
2078     // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
2079     // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
2080     // have 14 leading zeros, round to 8.
2081     NLZ = alignDown(NLZ, 8);
2082     NTZ = alignDown(NTZ, 8);
2083     // If we need exactly one byte, we can do this transformation.
2084     if (BitWidth - NLZ - NTZ == 8) {
2085       // Replace this with either a left or right shift to get the byte into
2086       // the right place.
2087       unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2088       if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2089         EVT ShiftAmtTy = getShiftAmountTy(VT, DL);
2090         unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2091         SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy);
2092         SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2093         return TLO.CombineTo(Op, NewOp);
2094       }
2095     }
2096 
2097     APInt DemandedSrcBits = DemandedBits.byteSwap();
2098     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2099                              Depth + 1))
2100       return true;
2101     Known.One = Known2.One.byteSwap();
2102     Known.Zero = Known2.Zero.byteSwap();
2103     break;
2104   }
2105   case ISD::CTPOP: {
2106     // If only 1 bit is demanded, replace with PARITY as long as we're before
2107     // op legalization.
2108     // FIXME: Limit to scalars for now.
2109     if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2110       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2111                                                Op.getOperand(0)));
2112 
2113     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2114     break;
2115   }
2116   case ISD::SIGN_EXTEND_INREG: {
2117     SDValue Op0 = Op.getOperand(0);
2118     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2119     unsigned ExVTBits = ExVT.getScalarSizeInBits();
2120 
2121     // If we only care about the highest bit, don't bother shifting right.
2122     if (DemandedBits.isSignMask()) {
2123       unsigned MinSignedBits =
2124           TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2125       bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2126       // However if the input is already sign extended we expect the sign
2127       // extension to be dropped altogether later and do not simplify.
2128       if (!AlreadySignExtended) {
2129         // Compute the correct shift amount type, which must be getShiftAmountTy
2130         // for scalar types after legalization.
2131         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl,
2132                                                getShiftAmountTy(VT, DL));
2133         return TLO.CombineTo(Op,
2134                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2135       }
2136     }
2137 
2138     // If none of the extended bits are demanded, eliminate the sextinreg.
2139     if (DemandedBits.getActiveBits() <= ExVTBits)
2140       return TLO.CombineTo(Op, Op0);
2141 
2142     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2143 
2144     // Since the sign extended bits are demanded, we know that the sign
2145     // bit is demanded.
2146     InputDemandedBits.setBit(ExVTBits - 1);
2147 
2148     if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2149                              Depth + 1))
2150       return true;
2151     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2152 
2153     // If the sign bit of the input is known set or clear, then we know the
2154     // top bits of the result.
2155 
2156     // If the input sign bit is known zero, convert this into a zero extension.
2157     if (Known.Zero[ExVTBits - 1])
2158       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2159 
2160     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2161     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2162       Known.One.setBitsFrom(ExVTBits);
2163       Known.Zero &= Mask;
2164     } else { // Input sign bit unknown
2165       Known.Zero &= Mask;
2166       Known.One &= Mask;
2167     }
2168     break;
2169   }
2170   case ISD::BUILD_PAIR: {
2171     EVT HalfVT = Op.getOperand(0).getValueType();
2172     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2173 
2174     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2175     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2176 
2177     KnownBits KnownLo, KnownHi;
2178 
2179     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2180       return true;
2181 
2182     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2183       return true;
2184 
2185     Known.Zero = KnownLo.Zero.zext(BitWidth) |
2186                  KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
2187 
2188     Known.One = KnownLo.One.zext(BitWidth) |
2189                 KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
2190     break;
2191   }
2192   case ISD::ZERO_EXTEND:
2193   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2194     SDValue Src = Op.getOperand(0);
2195     EVT SrcVT = Src.getValueType();
2196     unsigned InBits = SrcVT.getScalarSizeInBits();
2197     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2198     bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2199 
2200     // If none of the top bits are demanded, convert this into an any_extend.
2201     if (DemandedBits.getActiveBits() <= InBits) {
2202       // If we only need the non-extended bits of the bottom element
2203       // then we can just bitcast to the result.
2204       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2205           VT.getSizeInBits() == SrcVT.getSizeInBits())
2206         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2207 
2208       unsigned Opc =
2209           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2210       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2211         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2212     }
2213 
2214     APInt InDemandedBits = DemandedBits.trunc(InBits);
2215     APInt InDemandedElts = DemandedElts.zext(InElts);
2216     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2217                              Depth + 1))
2218       return true;
2219     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2220     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2221     Known = Known.zext(BitWidth);
2222 
2223     // Attempt to avoid multi-use ops if we don't need anything from them.
2224     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2225             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2226       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2227     break;
2228   }
2229   case ISD::SIGN_EXTEND:
2230   case ISD::SIGN_EXTEND_VECTOR_INREG: {
2231     SDValue Src = Op.getOperand(0);
2232     EVT SrcVT = Src.getValueType();
2233     unsigned InBits = SrcVT.getScalarSizeInBits();
2234     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2235     bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2236 
2237     // If none of the top bits are demanded, convert this into an any_extend.
2238     if (DemandedBits.getActiveBits() <= InBits) {
2239       // If we only need the non-extended bits of the bottom element
2240       // then we can just bitcast to the result.
2241       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2242           VT.getSizeInBits() == SrcVT.getSizeInBits())
2243         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2244 
2245       unsigned Opc =
2246           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2247       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2248         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2249     }
2250 
2251     APInt InDemandedBits = DemandedBits.trunc(InBits);
2252     APInt InDemandedElts = DemandedElts.zext(InElts);
2253 
2254     // Since some of the sign extended bits are demanded, we know that the sign
2255     // bit is demanded.
2256     InDemandedBits.setBit(InBits - 1);
2257 
2258     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2259                              Depth + 1))
2260       return true;
2261     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2262     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2263 
2264     // If the sign bit is known one, the top bits match.
2265     Known = Known.sext(BitWidth);
2266 
2267     // If the sign bit is known zero, convert this to a zero extend.
2268     if (Known.isNonNegative()) {
2269       unsigned Opc =
2270           IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND;
2271       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2272         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2273     }
2274 
2275     // Attempt to avoid multi-use ops if we don't need anything from them.
2276     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2277             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2278       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2279     break;
2280   }
2281   case ISD::ANY_EXTEND:
2282   case ISD::ANY_EXTEND_VECTOR_INREG: {
2283     SDValue Src = Op.getOperand(0);
2284     EVT SrcVT = Src.getValueType();
2285     unsigned InBits = SrcVT.getScalarSizeInBits();
2286     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2287     bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2288 
2289     // If we only need the bottom element then we can just bitcast.
2290     // TODO: Handle ANY_EXTEND?
2291     if (IsLE && IsVecInReg && DemandedElts == 1 &&
2292         VT.getSizeInBits() == SrcVT.getSizeInBits())
2293       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2294 
2295     APInt InDemandedBits = DemandedBits.trunc(InBits);
2296     APInt InDemandedElts = DemandedElts.zext(InElts);
2297     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2298                              Depth + 1))
2299       return true;
2300     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2301     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2302     Known = Known.anyext(BitWidth);
2303 
2304     // Attempt to avoid multi-use ops if we don't need anything from them.
2305     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2306             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2307       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2308     break;
2309   }
2310   case ISD::TRUNCATE: {
2311     SDValue Src = Op.getOperand(0);
2312 
2313     // Simplify the input, using demanded bit information, and compute the known
2314     // zero/one bits live out.
2315     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2316     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2317     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2318                              Depth + 1))
2319       return true;
2320     Known = Known.trunc(BitWidth);
2321 
2322     // Attempt to avoid multi-use ops if we don't need anything from them.
2323     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2324             Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2325       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2326 
2327     // If the input is only used by this truncate, see if we can shrink it based
2328     // on the known demanded bits.
2329     if (Src.getNode()->hasOneUse()) {
2330       switch (Src.getOpcode()) {
2331       default:
2332         break;
2333       case ISD::SRL:
2334         // Shrink SRL by a constant if none of the high bits shifted in are
2335         // demanded.
2336         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2337           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2338           // undesirable.
2339           break;
2340 
2341         const APInt *ShAmtC =
2342             TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts);
2343         if (!ShAmtC || ShAmtC->uge(BitWidth))
2344           break;
2345         uint64_t ShVal = ShAmtC->getZExtValue();
2346 
2347         APInt HighBits =
2348             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2349         HighBits.lshrInPlace(ShVal);
2350         HighBits = HighBits.trunc(BitWidth);
2351 
2352         if (!(HighBits & DemandedBits)) {
2353           // None of the shifted in bits are needed.  Add a truncate of the
2354           // shift input, then shift it.
2355           SDValue NewShAmt = TLO.DAG.getConstant(
2356               ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes()));
2357           SDValue NewTrunc =
2358               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2359           return TLO.CombineTo(
2360               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2361         }
2362         break;
2363       }
2364     }
2365 
2366     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2367     break;
2368   }
2369   case ISD::AssertZext: {
2370     // AssertZext demands all of the high bits, plus any of the low bits
2371     // demanded by its users.
2372     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2373     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
2374     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2375                              TLO, Depth + 1))
2376       return true;
2377     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2378 
2379     Known.Zero |= ~InMask;
2380     break;
2381   }
2382   case ISD::EXTRACT_VECTOR_ELT: {
2383     SDValue Src = Op.getOperand(0);
2384     SDValue Idx = Op.getOperand(1);
2385     ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2386     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2387 
2388     if (SrcEltCnt.isScalable())
2389       return false;
2390 
2391     // Demand the bits from every vector element without a constant index.
2392     unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2393     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2394     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2395       if (CIdx->getAPIntValue().ult(NumSrcElts))
2396         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2397 
2398     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2399     // anything about the extended bits.
2400     APInt DemandedSrcBits = DemandedBits;
2401     if (BitWidth > EltBitWidth)
2402       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2403 
2404     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2405                              Depth + 1))
2406       return true;
2407 
2408     // Attempt to avoid multi-use ops if we don't need anything from them.
2409     if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2410       if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2411               Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2412         SDValue NewOp =
2413             TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2414         return TLO.CombineTo(Op, NewOp);
2415       }
2416     }
2417 
2418     Known = Known2;
2419     if (BitWidth > EltBitWidth)
2420       Known = Known.anyext(BitWidth);
2421     break;
2422   }
2423   case ISD::BITCAST: {
2424     SDValue Src = Op.getOperand(0);
2425     EVT SrcVT = Src.getValueType();
2426     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2427 
2428     // If this is an FP->Int bitcast and if the sign bit is the only
2429     // thing demanded, turn this into a FGETSIGN.
2430     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2431         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2432         SrcVT.isFloatingPoint()) {
2433       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
2434       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
2435       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
2436           SrcVT != MVT::f128) {
2437         // Cannot eliminate/lower SHL for f128 yet.
2438         EVT Ty = OpVTLegal ? VT : MVT::i32;
2439         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2440         // place.  We expect the SHL to be eliminated by other optimizations.
2441         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
2442         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
2443         if (!OpVTLegal && OpVTSizeInBits > 32)
2444           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
2445         unsigned ShVal = Op.getValueSizeInBits() - 1;
2446         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
2447         return TLO.CombineTo(Op,
2448                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2449       }
2450     }
2451 
2452     // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2453     // Demand the elt/bit if any of the original elts/bits are demanded.
2454     if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2455       unsigned Scale = BitWidth / NumSrcEltBits;
2456       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2457       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2458       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2459       for (unsigned i = 0; i != Scale; ++i) {
2460         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2461         unsigned BitOffset = EltOffset * NumSrcEltBits;
2462         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2463         if (!Sub.isZero()) {
2464           DemandedSrcBits |= Sub;
2465           for (unsigned j = 0; j != NumElts; ++j)
2466             if (DemandedElts[j])
2467               DemandedSrcElts.setBit((j * Scale) + i);
2468         }
2469       }
2470 
2471       APInt KnownSrcUndef, KnownSrcZero;
2472       if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2473                                      KnownSrcZero, TLO, Depth + 1))
2474         return true;
2475 
2476       KnownBits KnownSrcBits;
2477       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2478                                KnownSrcBits, TLO, Depth + 1))
2479         return true;
2480     } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2481       // TODO - bigendian once we have test coverage.
2482       unsigned Scale = NumSrcEltBits / BitWidth;
2483       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2484       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2485       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2486       for (unsigned i = 0; i != NumElts; ++i)
2487         if (DemandedElts[i]) {
2488           unsigned Offset = (i % Scale) * BitWidth;
2489           DemandedSrcBits.insertBits(DemandedBits, Offset);
2490           DemandedSrcElts.setBit(i / Scale);
2491         }
2492 
2493       if (SrcVT.isVector()) {
2494         APInt KnownSrcUndef, KnownSrcZero;
2495         if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2496                                        KnownSrcZero, TLO, Depth + 1))
2497           return true;
2498       }
2499 
2500       KnownBits KnownSrcBits;
2501       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2502                                KnownSrcBits, TLO, Depth + 1))
2503         return true;
2504     }
2505 
2506     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
2507     // recursive call where Known may be useful to the caller.
2508     if (Depth > 0) {
2509       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2510       return false;
2511     }
2512     break;
2513   }
2514   case ISD::MUL:
2515     if (DemandedBits.isPowerOf2()) {
2516       // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
2517       // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
2518       // odd (has LSB set), then the left-shifted low bit of X is the answer.
2519       unsigned CTZ = DemandedBits.countTrailingZeros();
2520       ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
2521       if (C && C->getAPIntValue().countTrailingZeros() == CTZ) {
2522         EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2523         SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy);
2524         SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
2525         return TLO.CombineTo(Op, Shl);
2526       }
2527     }
2528     // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
2529     // X * X is odd iff X is odd.
2530     // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
2531     if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
2532       SDValue One = TLO.DAG.getConstant(1, dl, VT);
2533       SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
2534       return TLO.CombineTo(Op, And1);
2535     }
2536     LLVM_FALLTHROUGH;
2537   case ISD::ADD:
2538   case ISD::SUB: {
2539     // Add, Sub, and Mul don't demand any bits in positions beyond that
2540     // of the highest bit demanded of them.
2541     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2542     SDNodeFlags Flags = Op.getNode()->getFlags();
2543     unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
2544     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2545     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
2546                              Depth + 1) ||
2547         SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
2548                              Depth + 1) ||
2549         // See if the operation should be performed at a smaller bit width.
2550         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
2551       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
2552         // Disable the nsw and nuw flags. We can no longer guarantee that we
2553         // won't wrap after simplification.
2554         Flags.setNoSignedWrap(false);
2555         Flags.setNoUnsignedWrap(false);
2556         Op->setFlags(Flags);
2557       }
2558       return true;
2559     }
2560 
2561     // Attempt to avoid multi-use ops if we don't need anything from them.
2562     if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2563       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2564           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2565       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2566           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2567       if (DemandedOp0 || DemandedOp1) {
2568         Flags.setNoSignedWrap(false);
2569         Flags.setNoUnsignedWrap(false);
2570         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2571         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2572         SDValue NewOp =
2573             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2574         return TLO.CombineTo(Op, NewOp);
2575       }
2576     }
2577 
2578     // If we have a constant operand, we may be able to turn it into -1 if we
2579     // do not demand the high bits. This can make the constant smaller to
2580     // encode, allow more general folding, or match specialized instruction
2581     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2582     // is probably not useful (and could be detrimental).
2583     ConstantSDNode *C = isConstOrConstSplat(Op1);
2584     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2585     if (C && !C->isAllOnes() && !C->isOne() &&
2586         (C->getAPIntValue() | HighMask).isAllOnes()) {
2587       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
2588       // Disable the nsw and nuw flags. We can no longer guarantee that we
2589       // won't wrap after simplification.
2590       Flags.setNoSignedWrap(false);
2591       Flags.setNoUnsignedWrap(false);
2592       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
2593       return TLO.CombineTo(Op, NewOp);
2594     }
2595 
2596     // Match a multiply with a disguised negated-power-of-2 and convert to a
2597     // an equivalent shift-left amount.
2598     // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2599     auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
2600       if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
2601         return 0;
2602 
2603       // Don't touch opaque constants. Also, ignore zero and power-of-2
2604       // multiplies. Those will get folded later.
2605       ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
2606       if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
2607           !MulC->getAPIntValue().isPowerOf2()) {
2608         APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
2609         if (UnmaskedC.isNegatedPowerOf2())
2610           return (-UnmaskedC).logBase2();
2611       }
2612       return 0;
2613     };
2614 
2615     auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) {
2616       EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2617       SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy);
2618       SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
2619       SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
2620       return TLO.CombineTo(Op, Res);
2621     };
2622 
2623     if (isOperationLegalOrCustom(ISD::SHL, VT)) {
2624       if (Op.getOpcode() == ISD::ADD) {
2625         // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2626         if (unsigned ShAmt = getShiftLeftAmt(Op0))
2627           return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
2628         // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
2629         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2630           return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
2631       }
2632       if (Op.getOpcode() == ISD::SUB) {
2633         // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
2634         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2635           return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
2636       }
2637     }
2638 
2639     LLVM_FALLTHROUGH;
2640   }
2641   default:
2642     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2643       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
2644                                             Known, TLO, Depth))
2645         return true;
2646       break;
2647     }
2648 
2649     // Just use computeKnownBits to compute output bits.
2650     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2651     break;
2652   }
2653 
2654   // If we know the value of all of the demanded bits, return this as a
2655   // constant.
2656   if (!isTargetCanonicalConstantNode(Op) &&
2657       DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
2658     // Avoid folding to a constant if any OpaqueConstant is involved.
2659     const SDNode *N = Op.getNode();
2660     for (SDNode *Op :
2661          llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) {
2662       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
2663         if (C->isOpaque())
2664           return false;
2665     }
2666     if (VT.isInteger())
2667       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
2668     if (VT.isFloatingPoint())
2669       return TLO.CombineTo(
2670           Op,
2671           TLO.DAG.getConstantFP(
2672               APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT));
2673   }
2674 
2675   return false;
2676 }
2677 
2678 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
2679                                                 const APInt &DemandedElts,
2680                                                 DAGCombinerInfo &DCI) const {
2681   SelectionDAG &DAG = DCI.DAG;
2682   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2683                         !DCI.isBeforeLegalizeOps());
2684 
2685   APInt KnownUndef, KnownZero;
2686   bool Simplified =
2687       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
2688   if (Simplified) {
2689     DCI.AddToWorklist(Op.getNode());
2690     DCI.CommitTargetLoweringOpt(TLO);
2691   }
2692 
2693   return Simplified;
2694 }
2695 
2696 /// Given a vector binary operation and known undefined elements for each input
2697 /// operand, compute whether each element of the output is undefined.
2698 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
2699                                          const APInt &UndefOp0,
2700                                          const APInt &UndefOp1) {
2701   EVT VT = BO.getValueType();
2702   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2703          "Vector binop only");
2704 
2705   EVT EltVT = VT.getVectorElementType();
2706   unsigned NumElts = VT.getVectorNumElements();
2707   assert(UndefOp0.getBitWidth() == NumElts &&
2708          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2709 
2710   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2711                                    const APInt &UndefVals) {
2712     if (UndefVals[Index])
2713       return DAG.getUNDEF(EltVT);
2714 
2715     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2716       // Try hard to make sure that the getNode() call is not creating temporary
2717       // nodes. Ignore opaque integers because they do not constant fold.
2718       SDValue Elt = BV->getOperand(Index);
2719       auto *C = dyn_cast<ConstantSDNode>(Elt);
2720       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2721         return Elt;
2722     }
2723 
2724     return SDValue();
2725   };
2726 
2727   APInt KnownUndef = APInt::getZero(NumElts);
2728   for (unsigned i = 0; i != NumElts; ++i) {
2729     // If both inputs for this element are either constant or undef and match
2730     // the element type, compute the constant/undef result for this element of
2731     // the vector.
2732     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2733     // not handle FP constants. The code within getNode() should be refactored
2734     // to avoid the danger of creating a bogus temporary node here.
2735     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2736     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2737     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2738       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2739         KnownUndef.setBit(i);
2740   }
2741   return KnownUndef;
2742 }
2743 
2744 bool TargetLowering::SimplifyDemandedVectorElts(
2745     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
2746     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
2747     bool AssumeSingleUse) const {
2748   EVT VT = Op.getValueType();
2749   unsigned Opcode = Op.getOpcode();
2750   APInt DemandedElts = OriginalDemandedElts;
2751   unsigned NumElts = DemandedElts.getBitWidth();
2752   assert(VT.isVector() && "Expected vector op");
2753 
2754   KnownUndef = KnownZero = APInt::getZero(NumElts);
2755 
2756   const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo();
2757   if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO))
2758     return false;
2759 
2760   // TODO: For now we assume we know nothing about scalable vectors.
2761   if (VT.isScalableVector())
2762     return false;
2763 
2764   assert(VT.getVectorNumElements() == NumElts &&
2765          "Mask size mismatches value type element count!");
2766 
2767   // Undef operand.
2768   if (Op.isUndef()) {
2769     KnownUndef.setAllBits();
2770     return false;
2771   }
2772 
2773   // If Op has other users, assume that all elements are needed.
2774   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
2775     DemandedElts.setAllBits();
2776 
2777   // Not demanding any elements from Op.
2778   if (DemandedElts == 0) {
2779     KnownUndef.setAllBits();
2780     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2781   }
2782 
2783   // Limit search depth.
2784   if (Depth >= SelectionDAG::MaxRecursionDepth)
2785     return false;
2786 
2787   SDLoc DL(Op);
2788   unsigned EltSizeInBits = VT.getScalarSizeInBits();
2789   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
2790 
2791   // Helper for demanding the specified elements and all the bits of both binary
2792   // operands.
2793   auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
2794     SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
2795                                                            TLO.DAG, Depth + 1);
2796     SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
2797                                                            TLO.DAG, Depth + 1);
2798     if (NewOp0 || NewOp1) {
2799       SDValue NewOp = TLO.DAG.getNode(
2800           Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1);
2801       return TLO.CombineTo(Op, NewOp);
2802     }
2803     return false;
2804   };
2805 
2806   switch (Opcode) {
2807   case ISD::SCALAR_TO_VECTOR: {
2808     if (!DemandedElts[0]) {
2809       KnownUndef.setAllBits();
2810       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2811     }
2812     SDValue ScalarSrc = Op.getOperand(0);
2813     if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
2814       SDValue Src = ScalarSrc.getOperand(0);
2815       SDValue Idx = ScalarSrc.getOperand(1);
2816       EVT SrcVT = Src.getValueType();
2817 
2818       ElementCount SrcEltCnt = SrcVT.getVectorElementCount();
2819 
2820       if (SrcEltCnt.isScalable())
2821         return false;
2822 
2823       unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2824       if (isNullConstant(Idx)) {
2825         APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0);
2826         APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts);
2827         APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts);
2828         if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2829                                        TLO, Depth + 1))
2830           return true;
2831       }
2832     }
2833     KnownUndef.setHighBits(NumElts - 1);
2834     break;
2835   }
2836   case ISD::BITCAST: {
2837     SDValue Src = Op.getOperand(0);
2838     EVT SrcVT = Src.getValueType();
2839 
2840     // We only handle vectors here.
2841     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2842     if (!SrcVT.isVector())
2843       break;
2844 
2845     // Fast handling of 'identity' bitcasts.
2846     unsigned NumSrcElts = SrcVT.getVectorNumElements();
2847     if (NumSrcElts == NumElts)
2848       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
2849                                         KnownZero, TLO, Depth + 1);
2850 
2851     APInt SrcDemandedElts, SrcZero, SrcUndef;
2852 
2853     // Bitcast from 'large element' src vector to 'small element' vector, we
2854     // must demand a source element if any DemandedElt maps to it.
2855     if ((NumElts % NumSrcElts) == 0) {
2856       unsigned Scale = NumElts / NumSrcElts;
2857       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2858       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2859                                      TLO, Depth + 1))
2860         return true;
2861 
2862       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2863       // of the large element.
2864       // TODO - bigendian once we have test coverage.
2865       if (IsLE) {
2866         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
2867         APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
2868         for (unsigned i = 0; i != NumElts; ++i)
2869           if (DemandedElts[i]) {
2870             unsigned Ofs = (i % Scale) * EltSizeInBits;
2871             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
2872           }
2873 
2874         KnownBits Known;
2875         if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
2876                                  TLO, Depth + 1))
2877           return true;
2878 
2879         // The bitcast has split each wide element into a number of
2880         // narrow subelements. We have just computed the Known bits
2881         // for wide elements. See if element splitting results in
2882         // some subelements being zero. Only for demanded elements!
2883         for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
2884           if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
2885                    .isAllOnes())
2886             continue;
2887           for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
2888             unsigned Elt = Scale * SrcElt + SubElt;
2889             if (DemandedElts[Elt])
2890               KnownZero.setBit(Elt);
2891           }
2892         }
2893       }
2894 
2895       // If the src element is zero/undef then all the output elements will be -
2896       // only demanded elements are guaranteed to be correct.
2897       for (unsigned i = 0; i != NumSrcElts; ++i) {
2898         if (SrcDemandedElts[i]) {
2899           if (SrcZero[i])
2900             KnownZero.setBits(i * Scale, (i + 1) * Scale);
2901           if (SrcUndef[i])
2902             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2903         }
2904       }
2905     }
2906 
2907     // Bitcast from 'small element' src vector to 'large element' vector, we
2908     // demand all smaller source elements covered by the larger demanded element
2909     // of this vector.
2910     if ((NumSrcElts % NumElts) == 0) {
2911       unsigned Scale = NumSrcElts / NumElts;
2912       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2913       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2914                                      TLO, Depth + 1))
2915         return true;
2916 
2917       // If all the src elements covering an output element are zero/undef, then
2918       // the output element will be as well, assuming it was demanded.
2919       for (unsigned i = 0; i != NumElts; ++i) {
2920         if (DemandedElts[i]) {
2921           if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
2922             KnownZero.setBit(i);
2923           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
2924             KnownUndef.setBit(i);
2925         }
2926       }
2927     }
2928     break;
2929   }
2930   case ISD::BUILD_VECTOR: {
2931     // Check all elements and simplify any unused elements with UNDEF.
2932     if (!DemandedElts.isAllOnes()) {
2933       // Don't simplify BROADCASTS.
2934       if (llvm::any_of(Op->op_values(),
2935                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2936         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2937         bool Updated = false;
2938         for (unsigned i = 0; i != NumElts; ++i) {
2939           if (!DemandedElts[i] && !Ops[i].isUndef()) {
2940             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2941             KnownUndef.setBit(i);
2942             Updated = true;
2943           }
2944         }
2945         if (Updated)
2946           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2947       }
2948     }
2949     for (unsigned i = 0; i != NumElts; ++i) {
2950       SDValue SrcOp = Op.getOperand(i);
2951       if (SrcOp.isUndef()) {
2952         KnownUndef.setBit(i);
2953       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2954                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2955         KnownZero.setBit(i);
2956       }
2957     }
2958     break;
2959   }
2960   case ISD::CONCAT_VECTORS: {
2961     EVT SubVT = Op.getOperand(0).getValueType();
2962     unsigned NumSubVecs = Op.getNumOperands();
2963     unsigned NumSubElts = SubVT.getVectorNumElements();
2964     for (unsigned i = 0; i != NumSubVecs; ++i) {
2965       SDValue SubOp = Op.getOperand(i);
2966       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2967       APInt SubUndef, SubZero;
2968       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2969                                      Depth + 1))
2970         return true;
2971       KnownUndef.insertBits(SubUndef, i * NumSubElts);
2972       KnownZero.insertBits(SubZero, i * NumSubElts);
2973     }
2974 
2975     // Attempt to avoid multi-use ops if we don't need anything from them.
2976     if (!DemandedElts.isAllOnes()) {
2977       bool FoundNewSub = false;
2978       SmallVector<SDValue, 2> DemandedSubOps;
2979       for (unsigned i = 0; i != NumSubVecs; ++i) {
2980         SDValue SubOp = Op.getOperand(i);
2981         APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2982         SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts(
2983             SubOp, SubElts, TLO.DAG, Depth + 1);
2984         DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
2985         FoundNewSub = NewSubOp ? true : FoundNewSub;
2986       }
2987       if (FoundNewSub) {
2988         SDValue NewOp =
2989             TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
2990         return TLO.CombineTo(Op, NewOp);
2991       }
2992     }
2993     break;
2994   }
2995   case ISD::INSERT_SUBVECTOR: {
2996     // Demand any elements from the subvector and the remainder from the src its
2997     // inserted into.
2998     SDValue Src = Op.getOperand(0);
2999     SDValue Sub = Op.getOperand(1);
3000     uint64_t Idx = Op.getConstantOperandVal(2);
3001     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3002     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3003     APInt DemandedSrcElts = DemandedElts;
3004     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3005 
3006     APInt SubUndef, SubZero;
3007     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3008                                    Depth + 1))
3009       return true;
3010 
3011     // If none of the src operand elements are demanded, replace it with undef.
3012     if (!DemandedSrcElts && !Src.isUndef())
3013       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3014                                                TLO.DAG.getUNDEF(VT), Sub,
3015                                                Op.getOperand(2)));
3016 
3017     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3018                                    TLO, Depth + 1))
3019       return true;
3020     KnownUndef.insertBits(SubUndef, Idx);
3021     KnownZero.insertBits(SubZero, Idx);
3022 
3023     // Attempt to avoid multi-use ops if we don't need anything from them.
3024     if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3025       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
3026           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3027       SDValue NewSub = SimplifyMultipleUseDemandedVectorElts(
3028           Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3029       if (NewSrc || NewSub) {
3030         NewSrc = NewSrc ? NewSrc : Src;
3031         NewSub = NewSub ? NewSub : Sub;
3032         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3033                                         NewSub, Op.getOperand(2));
3034         return TLO.CombineTo(Op, NewOp);
3035       }
3036     }
3037     break;
3038   }
3039   case ISD::EXTRACT_SUBVECTOR: {
3040     // Offset the demanded elts by the subvector index.
3041     SDValue Src = Op.getOperand(0);
3042     if (Src.getValueType().isScalableVector())
3043       break;
3044     uint64_t Idx = Op.getConstantOperandVal(1);
3045     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3046     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3047 
3048     APInt SrcUndef, SrcZero;
3049     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3050                                    Depth + 1))
3051       return true;
3052     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3053     KnownZero = SrcZero.extractBits(NumElts, Idx);
3054 
3055     // Attempt to avoid multi-use ops if we don't need anything from them.
3056     if (!DemandedElts.isAllOnes()) {
3057       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
3058           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3059       if (NewSrc) {
3060         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3061                                         Op.getOperand(1));
3062         return TLO.CombineTo(Op, NewOp);
3063       }
3064     }
3065     break;
3066   }
3067   case ISD::INSERT_VECTOR_ELT: {
3068     SDValue Vec = Op.getOperand(0);
3069     SDValue Scl = Op.getOperand(1);
3070     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3071 
3072     // For a legal, constant insertion index, if we don't need this insertion
3073     // then strip it, else remove it from the demanded elts.
3074     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3075       unsigned Idx = CIdx->getZExtValue();
3076       if (!DemandedElts[Idx])
3077         return TLO.CombineTo(Op, Vec);
3078 
3079       APInt DemandedVecElts(DemandedElts);
3080       DemandedVecElts.clearBit(Idx);
3081       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3082                                      KnownZero, TLO, Depth + 1))
3083         return true;
3084 
3085       KnownUndef.setBitVal(Idx, Scl.isUndef());
3086 
3087       KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3088       break;
3089     }
3090 
3091     APInt VecUndef, VecZero;
3092     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3093                                    Depth + 1))
3094       return true;
3095     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3096     break;
3097   }
3098   case ISD::VSELECT: {
3099     SDValue Sel = Op.getOperand(0);
3100     SDValue LHS = Op.getOperand(1);
3101     SDValue RHS = Op.getOperand(2);
3102 
3103     // Try to transform the select condition based on the current demanded
3104     // elements.
3105     APInt UndefSel, UndefZero;
3106     if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, UndefZero, TLO,
3107                                    Depth + 1))
3108       return true;
3109 
3110     // See if we can simplify either vselect operand.
3111     APInt DemandedLHS(DemandedElts);
3112     APInt DemandedRHS(DemandedElts);
3113     APInt UndefLHS, ZeroLHS;
3114     APInt UndefRHS, ZeroRHS;
3115     if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3116                                    Depth + 1))
3117       return true;
3118     if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3119                                    Depth + 1))
3120       return true;
3121 
3122     KnownUndef = UndefLHS & UndefRHS;
3123     KnownZero = ZeroLHS & ZeroRHS;
3124 
3125     // If we know that the selected element is always zero, we don't need the
3126     // select value element.
3127     APInt DemandedSel = DemandedElts & ~KnownZero;
3128     if (DemandedSel != DemandedElts)
3129       if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, UndefZero, TLO,
3130                                      Depth + 1))
3131         return true;
3132 
3133     break;
3134   }
3135   case ISD::VECTOR_SHUFFLE: {
3136     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3137 
3138     // Collect demanded elements from shuffle operands..
3139     APInt DemandedLHS(NumElts, 0);
3140     APInt DemandedRHS(NumElts, 0);
3141     for (unsigned i = 0; i != NumElts; ++i) {
3142       int M = ShuffleMask[i];
3143       if (M < 0 || !DemandedElts[i])
3144         continue;
3145       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3146       if (M < (int)NumElts)
3147         DemandedLHS.setBit(M);
3148       else
3149         DemandedRHS.setBit(M - NumElts);
3150     }
3151 
3152     // See if we can simplify either shuffle operand.
3153     APInt UndefLHS, ZeroLHS;
3154     APInt UndefRHS, ZeroRHS;
3155     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
3156                                    ZeroLHS, TLO, Depth + 1))
3157       return true;
3158     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
3159                                    ZeroRHS, TLO, Depth + 1))
3160       return true;
3161 
3162     // Simplify mask using undef elements from LHS/RHS.
3163     bool Updated = false;
3164     bool IdentityLHS = true, IdentityRHS = true;
3165     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
3166     for (unsigned i = 0; i != NumElts; ++i) {
3167       int &M = NewMask[i];
3168       if (M < 0)
3169         continue;
3170       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3171           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3172         Updated = true;
3173         M = -1;
3174       }
3175       IdentityLHS &= (M < 0) || (M == (int)i);
3176       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3177     }
3178 
3179     // Update legal shuffle masks based on demanded elements if it won't reduce
3180     // to Identity which can cause premature removal of the shuffle mask.
3181     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3182       SDValue LegalShuffle =
3183           buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1),
3184                                   NewMask, TLO.DAG);
3185       if (LegalShuffle)
3186         return TLO.CombineTo(Op, LegalShuffle);
3187     }
3188 
3189     // Propagate undef/zero elements from LHS/RHS.
3190     for (unsigned i = 0; i != NumElts; ++i) {
3191       int M = ShuffleMask[i];
3192       if (M < 0) {
3193         KnownUndef.setBit(i);
3194       } else if (M < (int)NumElts) {
3195         if (UndefLHS[M])
3196           KnownUndef.setBit(i);
3197         if (ZeroLHS[M])
3198           KnownZero.setBit(i);
3199       } else {
3200         if (UndefRHS[M - NumElts])
3201           KnownUndef.setBit(i);
3202         if (ZeroRHS[M - NumElts])
3203           KnownZero.setBit(i);
3204       }
3205     }
3206     break;
3207   }
3208   case ISD::ANY_EXTEND_VECTOR_INREG:
3209   case ISD::SIGN_EXTEND_VECTOR_INREG:
3210   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3211     APInt SrcUndef, SrcZero;
3212     SDValue Src = Op.getOperand(0);
3213     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3214     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3215     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3216                                    Depth + 1))
3217       return true;
3218     KnownZero = SrcZero.zextOrTrunc(NumElts);
3219     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3220 
3221     if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3222         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3223         DemandedSrcElts == 1) {
3224       // aext - if we just need the bottom element then we can bitcast.
3225       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3226     }
3227 
3228     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3229       // zext(undef) upper bits are guaranteed to be zero.
3230       if (DemandedElts.isSubsetOf(KnownUndef))
3231         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3232       KnownUndef.clearAllBits();
3233 
3234       // zext - if we just need the bottom element then we can mask:
3235       // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3236       if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3237           Op->isOnlyUserOf(Src.getNode()) &&
3238           Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3239         SDLoc DL(Op);
3240         EVT SrcVT = Src.getValueType();
3241         EVT SrcSVT = SrcVT.getScalarType();
3242         SmallVector<SDValue> MaskElts;
3243         MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3244         MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3245         SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3246         if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3247                 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3248           Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3249           return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3250         }
3251       }
3252     }
3253     break;
3254   }
3255 
3256   // TODO: There are more binop opcodes that could be handled here - MIN,
3257   // MAX, saturated math, etc.
3258   case ISD::ADD: {
3259     SDValue Op0 = Op.getOperand(0);
3260     SDValue Op1 = Op.getOperand(1);
3261     if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3262       APInt UndefLHS, ZeroLHS;
3263       if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3264                                      Depth + 1, /*AssumeSingleUse*/ true))
3265         return true;
3266     }
3267     LLVM_FALLTHROUGH;
3268   }
3269   case ISD::OR:
3270   case ISD::XOR:
3271   case ISD::SUB:
3272   case ISD::FADD:
3273   case ISD::FSUB:
3274   case ISD::FMUL:
3275   case ISD::FDIV:
3276   case ISD::FREM: {
3277     SDValue Op0 = Op.getOperand(0);
3278     SDValue Op1 = Op.getOperand(1);
3279 
3280     APInt UndefRHS, ZeroRHS;
3281     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3282                                    Depth + 1))
3283       return true;
3284     APInt UndefLHS, ZeroLHS;
3285     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3286                                    Depth + 1))
3287       return true;
3288 
3289     KnownZero = ZeroLHS & ZeroRHS;
3290     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3291 
3292     // Attempt to avoid multi-use ops if we don't need anything from them.
3293     // TODO - use KnownUndef to relax the demandedelts?
3294     if (!DemandedElts.isAllOnes())
3295       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3296         return true;
3297     break;
3298   }
3299   case ISD::SHL:
3300   case ISD::SRL:
3301   case ISD::SRA:
3302   case ISD::ROTL:
3303   case ISD::ROTR: {
3304     SDValue Op0 = Op.getOperand(0);
3305     SDValue Op1 = Op.getOperand(1);
3306 
3307     APInt UndefRHS, ZeroRHS;
3308     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3309                                    Depth + 1))
3310       return true;
3311     APInt UndefLHS, ZeroLHS;
3312     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3313                                    Depth + 1))
3314       return true;
3315 
3316     KnownZero = ZeroLHS;
3317     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3318 
3319     // Attempt to avoid multi-use ops if we don't need anything from them.
3320     // TODO - use KnownUndef to relax the demandedelts?
3321     if (!DemandedElts.isAllOnes())
3322       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3323         return true;
3324     break;
3325   }
3326   case ISD::MUL:
3327   case ISD::AND: {
3328     SDValue Op0 = Op.getOperand(0);
3329     SDValue Op1 = Op.getOperand(1);
3330 
3331     APInt SrcUndef, SrcZero;
3332     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
3333                                    Depth + 1))
3334       return true;
3335     if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
3336                                    TLO, Depth + 1))
3337       return true;
3338 
3339     // If either side has a zero element, then the result element is zero, even
3340     // if the other is an UNDEF.
3341     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
3342     // and then handle 'and' nodes with the rest of the binop opcodes.
3343     KnownZero |= SrcZero;
3344     KnownUndef &= SrcUndef;
3345     KnownUndef &= ~KnownZero;
3346 
3347     // Attempt to avoid multi-use ops if we don't need anything from them.
3348     // TODO - use KnownUndef to relax the demandedelts?
3349     if (!DemandedElts.isAllOnes())
3350       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3351         return true;
3352     break;
3353   }
3354   case ISD::TRUNCATE:
3355   case ISD::SIGN_EXTEND:
3356   case ISD::ZERO_EXTEND:
3357     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3358                                    KnownZero, TLO, Depth + 1))
3359       return true;
3360 
3361     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3362       // zext(undef) upper bits are guaranteed to be zero.
3363       if (DemandedElts.isSubsetOf(KnownUndef))
3364         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3365       KnownUndef.clearAllBits();
3366     }
3367     break;
3368   default: {
3369     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3370       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3371                                                   KnownZero, TLO, Depth))
3372         return true;
3373     } else {
3374       KnownBits Known;
3375       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3376       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
3377                                TLO, Depth, AssumeSingleUse))
3378         return true;
3379     }
3380     break;
3381   }
3382   }
3383   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
3384 
3385   // Constant fold all undef cases.
3386   // TODO: Handle zero cases as well.
3387   if (DemandedElts.isSubsetOf(KnownUndef))
3388     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3389 
3390   return false;
3391 }
3392 
3393 /// Determine which of the bits specified in Mask are known to be either zero or
3394 /// one and return them in the Known.
3395 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
3396                                                    KnownBits &Known,
3397                                                    const APInt &DemandedElts,
3398                                                    const SelectionDAG &DAG,
3399                                                    unsigned Depth) const {
3400   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3401           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3402           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3403           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3404          "Should use MaskedValueIsZero if you don't know whether Op"
3405          " is a target node!");
3406   Known.resetAll();
3407 }
3408 
3409 void TargetLowering::computeKnownBitsForTargetInstr(
3410     GISelKnownBits &Analysis, Register R, KnownBits &Known,
3411     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
3412     unsigned Depth) const {
3413   Known.resetAll();
3414 }
3415 
3416 void TargetLowering::computeKnownBitsForFrameIndex(
3417   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
3418   // The low bits are known zero if the pointer is aligned.
3419   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
3420 }
3421 
3422 Align TargetLowering::computeKnownAlignForTargetInstr(
3423   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
3424   unsigned Depth) const {
3425   return Align(1);
3426 }
3427 
3428 /// This method can be implemented by targets that want to expose additional
3429 /// information about sign bits to the DAG Combiner.
3430 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
3431                                                          const APInt &,
3432                                                          const SelectionDAG &,
3433                                                          unsigned Depth) const {
3434   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3435           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3436           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3437           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3438          "Should use ComputeNumSignBits if you don't know whether Op"
3439          " is a target node!");
3440   return 1;
3441 }
3442 
3443 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
3444   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
3445   const MachineRegisterInfo &MRI, unsigned Depth) const {
3446   return 1;
3447 }
3448 
3449 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
3450     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
3451     TargetLoweringOpt &TLO, unsigned Depth) const {
3452   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3453           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3454           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3455           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3456          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
3457          " is a target node!");
3458   return false;
3459 }
3460 
3461 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
3462     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3463     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
3464   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3465           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3466           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3467           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3468          "Should use SimplifyDemandedBits if you don't know whether Op"
3469          " is a target node!");
3470   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
3471   return false;
3472 }
3473 
3474 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
3475     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3476     SelectionDAG &DAG, unsigned Depth) const {
3477   assert(
3478       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3479        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3480        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3481        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3482       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
3483       " is a target node!");
3484   return SDValue();
3485 }
3486 
3487 SDValue
3488 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3489                                         SDValue N1, MutableArrayRef<int> Mask,
3490                                         SelectionDAG &DAG) const {
3491   bool LegalMask = isShuffleMaskLegal(Mask, VT);
3492   if (!LegalMask) {
3493     std::swap(N0, N1);
3494     ShuffleVectorSDNode::commuteMask(Mask);
3495     LegalMask = isShuffleMaskLegal(Mask, VT);
3496   }
3497 
3498   if (!LegalMask)
3499     return SDValue();
3500 
3501   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
3502 }
3503 
3504 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
3505   return nullptr;
3506 }
3507 
3508 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
3509     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3510     bool PoisonOnly, unsigned Depth) const {
3511   assert(
3512       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3513        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3514        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3515        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3516       "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
3517       " is a target node!");
3518   return false;
3519 }
3520 
3521 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
3522                                                   const SelectionDAG &DAG,
3523                                                   bool SNaN,
3524                                                   unsigned Depth) const {
3525   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3526           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3527           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3528           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3529          "Should use isKnownNeverNaN if you don't know whether Op"
3530          " is a target node!");
3531   return false;
3532 }
3533 
3534 bool TargetLowering::isSplatValueForTargetNode(SDValue Op,
3535                                                const APInt &DemandedElts,
3536                                                APInt &UndefElts,
3537                                                unsigned Depth) const {
3538   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3539           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3540           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3541           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3542          "Should use isSplatValue if you don't know whether Op"
3543          " is a target node!");
3544   return false;
3545 }
3546 
3547 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
3548 // work with truncating build vectors and vectors with elements of less than
3549 // 8 bits.
3550 bool TargetLowering::isConstTrueVal(SDValue N) const {
3551   if (!N)
3552     return false;
3553 
3554   unsigned EltWidth;
3555   APInt CVal;
3556   if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
3557                                                /*AllowTruncation=*/true)) {
3558     CVal = CN->getAPIntValue();
3559     EltWidth = N.getValueType().getScalarSizeInBits();
3560   } else
3561     return false;
3562 
3563   // If this is a truncating splat, truncate the splat value.
3564   // Otherwise, we may fail to match the expected values below.
3565   if (EltWidth < CVal.getBitWidth())
3566     CVal = CVal.trunc(EltWidth);
3567 
3568   switch (getBooleanContents(N.getValueType())) {
3569   case UndefinedBooleanContent:
3570     return CVal[0];
3571   case ZeroOrOneBooleanContent:
3572     return CVal.isOne();
3573   case ZeroOrNegativeOneBooleanContent:
3574     return CVal.isAllOnes();
3575   }
3576 
3577   llvm_unreachable("Invalid boolean contents");
3578 }
3579 
3580 bool TargetLowering::isConstFalseVal(SDValue N) const {
3581   if (!N)
3582     return false;
3583 
3584   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3585   if (!CN) {
3586     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3587     if (!BV)
3588       return false;
3589 
3590     // Only interested in constant splats, we don't care about undef
3591     // elements in identifying boolean constants and getConstantSplatNode
3592     // returns NULL if all ops are undef;
3593     CN = BV->getConstantSplatNode();
3594     if (!CN)
3595       return false;
3596   }
3597 
3598   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3599     return !CN->getAPIntValue()[0];
3600 
3601   return CN->isZero();
3602 }
3603 
3604 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3605                                        bool SExt) const {
3606   if (VT == MVT::i1)
3607     return N->isOne();
3608 
3609   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3610   switch (Cnt) {
3611   case TargetLowering::ZeroOrOneBooleanContent:
3612     // An extended value of 1 is always true, unless its original type is i1,
3613     // in which case it will be sign extended to -1.
3614     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3615   case TargetLowering::UndefinedBooleanContent:
3616   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3617     return N->isAllOnes() && SExt;
3618   }
3619   llvm_unreachable("Unexpected enumeration.");
3620 }
3621 
3622 /// This helper function of SimplifySetCC tries to optimize the comparison when
3623 /// either operand of the SetCC node is a bitwise-and instruction.
3624 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3625                                          ISD::CondCode Cond, const SDLoc &DL,
3626                                          DAGCombinerInfo &DCI) const {
3627   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3628     std::swap(N0, N1);
3629 
3630   SelectionDAG &DAG = DCI.DAG;
3631   EVT OpVT = N0.getValueType();
3632   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3633       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3634     return SDValue();
3635 
3636   // (X & Y) != 0 --> zextOrTrunc(X & Y)
3637   // iff everything but LSB is known zero:
3638   if (Cond == ISD::SETNE && isNullConstant(N1) &&
3639       (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent ||
3640        getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) {
3641     unsigned NumEltBits = OpVT.getScalarSizeInBits();
3642     APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
3643     if (DAG.MaskedValueIsZero(N0, UpperBits))
3644       return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
3645   }
3646 
3647   // Match these patterns in any of their permutations:
3648   // (X & Y) == Y
3649   // (X & Y) != Y
3650   SDValue X, Y;
3651   if (N0.getOperand(0) == N1) {
3652     X = N0.getOperand(1);
3653     Y = N0.getOperand(0);
3654   } else if (N0.getOperand(1) == N1) {
3655     X = N0.getOperand(0);
3656     Y = N0.getOperand(1);
3657   } else {
3658     return SDValue();
3659   }
3660 
3661   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3662   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
3663     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3664     // Note that where Y is variable and is known to have at most one bit set
3665     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3666     // equivalent when Y == 0.
3667     assert(OpVT.isInteger());
3668     Cond = ISD::getSetCCInverse(Cond, OpVT);
3669     if (DCI.isBeforeLegalizeOps() ||
3670         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3671       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3672   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3673     // If the target supports an 'and-not' or 'and-complement' logic operation,
3674     // try to use that to make a comparison operation more efficient.
3675     // But don't do this transform if the mask is a single bit because there are
3676     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3677     // 'rlwinm' on PPC).
3678 
3679     // Bail out if the compare operand that we want to turn into a zero is
3680     // already a zero (otherwise, infinite loop).
3681     auto *YConst = dyn_cast<ConstantSDNode>(Y);
3682     if (YConst && YConst->isZero())
3683       return SDValue();
3684 
3685     // Transform this into: ~X & Y == 0.
3686     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3687     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3688     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3689   }
3690 
3691   return SDValue();
3692 }
3693 
3694 /// There are multiple IR patterns that could be checking whether certain
3695 /// truncation of a signed number would be lossy or not. The pattern which is
3696 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
3697 /// We are looking for the following pattern: (KeptBits is a constant)
3698 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
3699 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
3700 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
3701 /// We will unfold it into the natural trunc+sext pattern:
3702 ///   ((%x << C) a>> C) dstcond %x
3703 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
3704 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
3705     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
3706     const SDLoc &DL) const {
3707   // We must be comparing with a constant.
3708   ConstantSDNode *C1;
3709   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
3710     return SDValue();
3711 
3712   // N0 should be:  add %x, (1 << (KeptBits-1))
3713   if (N0->getOpcode() != ISD::ADD)
3714     return SDValue();
3715 
3716   // And we must be 'add'ing a constant.
3717   ConstantSDNode *C01;
3718   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
3719     return SDValue();
3720 
3721   SDValue X = N0->getOperand(0);
3722   EVT XVT = X.getValueType();
3723 
3724   // Validate constants ...
3725 
3726   APInt I1 = C1->getAPIntValue();
3727 
3728   ISD::CondCode NewCond;
3729   if (Cond == ISD::CondCode::SETULT) {
3730     NewCond = ISD::CondCode::SETEQ;
3731   } else if (Cond == ISD::CondCode::SETULE) {
3732     NewCond = ISD::CondCode::SETEQ;
3733     // But need to 'canonicalize' the constant.
3734     I1 += 1;
3735   } else if (Cond == ISD::CondCode::SETUGT) {
3736     NewCond = ISD::CondCode::SETNE;
3737     // But need to 'canonicalize' the constant.
3738     I1 += 1;
3739   } else if (Cond == ISD::CondCode::SETUGE) {
3740     NewCond = ISD::CondCode::SETNE;
3741   } else
3742     return SDValue();
3743 
3744   APInt I01 = C01->getAPIntValue();
3745 
3746   auto checkConstants = [&I1, &I01]() -> bool {
3747     // Both of them must be power-of-two, and the constant from setcc is bigger.
3748     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
3749   };
3750 
3751   if (checkConstants()) {
3752     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
3753   } else {
3754     // What if we invert constants? (and the target predicate)
3755     I1.negate();
3756     I01.negate();
3757     assert(XVT.isInteger());
3758     NewCond = getSetCCInverse(NewCond, XVT);
3759     if (!checkConstants())
3760       return SDValue();
3761     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
3762   }
3763 
3764   // They are power-of-two, so which bit is set?
3765   const unsigned KeptBits = I1.logBase2();
3766   const unsigned KeptBitsMinusOne = I01.logBase2();
3767 
3768   // Magic!
3769   if (KeptBits != (KeptBitsMinusOne + 1))
3770     return SDValue();
3771   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
3772 
3773   // We don't want to do this in every single case.
3774   SelectionDAG &DAG = DCI.DAG;
3775   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
3776           XVT, KeptBits))
3777     return SDValue();
3778 
3779   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
3780   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
3781 
3782   // Unfold into:  ((%x << C) a>> C) cond %x
3783   // Where 'cond' will be either 'eq' or 'ne'.
3784   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
3785   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
3786   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
3787   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
3788 
3789   return T2;
3790 }
3791 
3792 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3793 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
3794     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
3795     DAGCombinerInfo &DCI, const SDLoc &DL) const {
3796   assert(isConstOrConstSplat(N1C) &&
3797          isConstOrConstSplat(N1C)->getAPIntValue().isZero() &&
3798          "Should be a comparison with 0.");
3799   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3800          "Valid only for [in]equality comparisons.");
3801 
3802   unsigned NewShiftOpcode;
3803   SDValue X, C, Y;
3804 
3805   SelectionDAG &DAG = DCI.DAG;
3806   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3807 
3808   // Look for '(C l>>/<< Y)'.
3809   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
3810     // The shift should be one-use.
3811     if (!V.hasOneUse())
3812       return false;
3813     unsigned OldShiftOpcode = V.getOpcode();
3814     switch (OldShiftOpcode) {
3815     case ISD::SHL:
3816       NewShiftOpcode = ISD::SRL;
3817       break;
3818     case ISD::SRL:
3819       NewShiftOpcode = ISD::SHL;
3820       break;
3821     default:
3822       return false; // must be a logical shift.
3823     }
3824     // We should be shifting a constant.
3825     // FIXME: best to use isConstantOrConstantVector().
3826     C = V.getOperand(0);
3827     ConstantSDNode *CC =
3828         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3829     if (!CC)
3830       return false;
3831     Y = V.getOperand(1);
3832 
3833     ConstantSDNode *XC =
3834         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3835     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3836         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
3837   };
3838 
3839   // LHS of comparison should be an one-use 'and'.
3840   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
3841     return SDValue();
3842 
3843   X = N0.getOperand(0);
3844   SDValue Mask = N0.getOperand(1);
3845 
3846   // 'and' is commutative!
3847   if (!Match(Mask)) {
3848     std::swap(X, Mask);
3849     if (!Match(Mask))
3850       return SDValue();
3851   }
3852 
3853   EVT VT = X.getValueType();
3854 
3855   // Produce:
3856   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
3857   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
3858   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
3859   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
3860   return T2;
3861 }
3862 
3863 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
3864 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
3865 /// handle the commuted versions of these patterns.
3866 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
3867                                            ISD::CondCode Cond, const SDLoc &DL,
3868                                            DAGCombinerInfo &DCI) const {
3869   unsigned BOpcode = N0.getOpcode();
3870   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
3871          "Unexpected binop");
3872   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
3873 
3874   // (X + Y) == X --> Y == 0
3875   // (X - Y) == X --> Y == 0
3876   // (X ^ Y) == X --> Y == 0
3877   SelectionDAG &DAG = DCI.DAG;
3878   EVT OpVT = N0.getValueType();
3879   SDValue X = N0.getOperand(0);
3880   SDValue Y = N0.getOperand(1);
3881   if (X == N1)
3882     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
3883 
3884   if (Y != N1)
3885     return SDValue();
3886 
3887   // (X + Y) == Y --> X == 0
3888   // (X ^ Y) == Y --> X == 0
3889   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
3890     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
3891 
3892   // The shift would not be valid if the operands are boolean (i1).
3893   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
3894     return SDValue();
3895 
3896   // (X - Y) == Y --> X == Y << 1
3897   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
3898                                  !DCI.isBeforeLegalize());
3899   SDValue One = DAG.getConstant(1, DL, ShiftVT);
3900   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
3901   if (!DCI.isCalledByLegalizer())
3902     DCI.AddToWorklist(YShl1.getNode());
3903   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
3904 }
3905 
3906 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT,
3907                                       SDValue N0, const APInt &C1,
3908                                       ISD::CondCode Cond, const SDLoc &dl,
3909                                       SelectionDAG &DAG) {
3910   // Look through truncs that don't change the value of a ctpop.
3911   // FIXME: Add vector support? Need to be careful with setcc result type below.
3912   SDValue CTPOP = N0;
3913   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
3914       N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits()))
3915     CTPOP = N0.getOperand(0);
3916 
3917   if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
3918     return SDValue();
3919 
3920   EVT CTVT = CTPOP.getValueType();
3921   SDValue CTOp = CTPOP.getOperand(0);
3922 
3923   // If this is a vector CTPOP, keep the CTPOP if it is legal.
3924   // TODO: Should we check if CTPOP is legal(or custom) for scalars?
3925   if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT))
3926     return SDValue();
3927 
3928   // (ctpop x) u< 2 -> (x & x-1) == 0
3929   // (ctpop x) u> 1 -> (x & x-1) != 0
3930   if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
3931     unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
3932     if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
3933       return SDValue();
3934     if (C1 == 0 && (Cond == ISD::SETULT))
3935       return SDValue(); // This is handled elsewhere.
3936 
3937     unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
3938 
3939     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3940     SDValue Result = CTOp;
3941     for (unsigned i = 0; i < Passes; i++) {
3942       SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
3943       Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
3944     }
3945     ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
3946     return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
3947   }
3948 
3949   // If ctpop is not supported, expand a power-of-2 comparison based on it.
3950   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
3951     // For scalars, keep CTPOP if it is legal or custom.
3952     if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT))
3953       return SDValue();
3954     // This is based on X86's custom lowering for CTPOP which produces more
3955     // instructions than the expansion here.
3956 
3957     // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3958     // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3959     SDValue Zero = DAG.getConstant(0, dl, CTVT);
3960     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3961     assert(CTVT.isInteger());
3962     ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT);
3963     SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3964     SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3965     SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
3966     SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
3967     unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
3968     return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
3969   }
3970 
3971   return SDValue();
3972 }
3973 
3974 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1,
3975                                    ISD::CondCode Cond, const SDLoc &dl,
3976                                    SelectionDAG &DAG) {
3977   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
3978     return SDValue();
3979 
3980   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
3981   if (!C1 || !(C1->isZero() || C1->isAllOnes()))
3982     return SDValue();
3983 
3984   auto getRotateSource = [](SDValue X) {
3985     if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
3986       return X.getOperand(0);
3987     return SDValue();
3988   };
3989 
3990   // Peek through a rotated value compared against 0 or -1:
3991   // (rot X, Y) == 0/-1 --> X == 0/-1
3992   // (rot X, Y) != 0/-1 --> X != 0/-1
3993   if (SDValue R = getRotateSource(N0))
3994     return DAG.getSetCC(dl, VT, R, N1, Cond);
3995 
3996   // Peek through an 'or' of a rotated value compared against 0:
3997   // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
3998   // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
3999   //
4000   // TODO: Add the 'and' with -1 sibling.
4001   // TODO: Recurse through a series of 'or' ops to find the rotate.
4002   EVT OpVT = N0.getValueType();
4003   if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
4004     if (SDValue R = getRotateSource(N0.getOperand(0))) {
4005       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
4006       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4007     }
4008     if (SDValue R = getRotateSource(N0.getOperand(1))) {
4009       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
4010       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4011     }
4012   }
4013 
4014   return SDValue();
4015 }
4016 
4017 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1,
4018                                         ISD::CondCode Cond, const SDLoc &dl,
4019                                         SelectionDAG &DAG) {
4020   // If we are testing for all-bits-clear, we might be able to do that with
4021   // less shifting since bit-order does not matter.
4022   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4023     return SDValue();
4024 
4025   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4026   if (!C1 || !C1->isZero())
4027     return SDValue();
4028 
4029   if (!N0.hasOneUse() ||
4030       (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
4031     return SDValue();
4032 
4033   unsigned BitWidth = N0.getScalarValueSizeInBits();
4034   auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
4035   if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth))
4036     return SDValue();
4037 
4038   // Canonicalize fshr as fshl to reduce pattern-matching.
4039   unsigned ShAmt = ShAmtC->getZExtValue();
4040   if (N0.getOpcode() == ISD::FSHR)
4041     ShAmt = BitWidth - ShAmt;
4042 
4043   // Match an 'or' with a specific operand 'Other' in either commuted variant.
4044   SDValue X, Y;
4045   auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
4046     if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
4047       return false;
4048     if (Or.getOperand(0) == Other) {
4049       X = Or.getOperand(0);
4050       Y = Or.getOperand(1);
4051       return true;
4052     }
4053     if (Or.getOperand(1) == Other) {
4054       X = Or.getOperand(1);
4055       Y = Or.getOperand(0);
4056       return true;
4057     }
4058     return false;
4059   };
4060 
4061   EVT OpVT = N0.getValueType();
4062   EVT ShAmtVT = N0.getOperand(2).getValueType();
4063   SDValue F0 = N0.getOperand(0);
4064   SDValue F1 = N0.getOperand(1);
4065   if (matchOr(F0, F1)) {
4066     // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4067     SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4068     SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4069     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4070     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4071   }
4072   if (matchOr(F1, F0)) {
4073     // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4074     SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4075     SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4076     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4077     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4078   }
4079 
4080   return SDValue();
4081 }
4082 
4083 /// Try to simplify a setcc built with the specified operands and cc. If it is
4084 /// unable to simplify it, return a null SDValue.
4085 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
4086                                       ISD::CondCode Cond, bool foldBooleans,
4087                                       DAGCombinerInfo &DCI,
4088                                       const SDLoc &dl) const {
4089   SelectionDAG &DAG = DCI.DAG;
4090   const DataLayout &Layout = DAG.getDataLayout();
4091   EVT OpVT = N0.getValueType();
4092 
4093   // Constant fold or commute setcc.
4094   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
4095     return Fold;
4096 
4097   bool N0ConstOrSplat =
4098       isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4099   bool N1ConstOrSplat =
4100       isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4101 
4102   // Ensure that the constant occurs on the RHS and fold constant comparisons.
4103   // TODO: Handle non-splat vector constants. All undef causes trouble.
4104   // FIXME: We can't yet fold constant scalable vector splats, so avoid an
4105   // infinite loop here when we encounter one.
4106   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
4107   if (N0ConstOrSplat && (!OpVT.isScalableVector() || !N1ConstOrSplat) &&
4108       (DCI.isBeforeLegalizeOps() ||
4109        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
4110     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4111 
4112   // If we have a subtract with the same 2 non-constant operands as this setcc
4113   // -- but in reverse order -- then try to commute the operands of this setcc
4114   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
4115   // instruction on some targets.
4116   if (!N0ConstOrSplat && !N1ConstOrSplat &&
4117       (DCI.isBeforeLegalizeOps() ||
4118        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
4119       DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
4120       !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
4121     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4122 
4123   if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
4124     return V;
4125 
4126   if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
4127     return V;
4128 
4129   if (auto *N1C = isConstOrConstSplat(N1)) {
4130     const APInt &C1 = N1C->getAPIntValue();
4131 
4132     // Optimize some CTPOP cases.
4133     if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
4134       return V;
4135 
4136     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
4137     // equality comparison, then we're just comparing whether X itself is
4138     // zero.
4139     if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
4140         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
4141         isPowerOf2_32(N0.getScalarValueSizeInBits())) {
4142       if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
4143         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4144             ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
4145           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
4146             // (srl (ctlz x), 5) == 0  -> X != 0
4147             // (srl (ctlz x), 5) != 1  -> X != 0
4148             Cond = ISD::SETNE;
4149           } else {
4150             // (srl (ctlz x), 5) != 0  -> X == 0
4151             // (srl (ctlz x), 5) == 1  -> X == 0
4152             Cond = ISD::SETEQ;
4153           }
4154           SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
4155           return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
4156                               Cond);
4157         }
4158       }
4159     }
4160   }
4161 
4162   // FIXME: Support vectors.
4163   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4164     const APInt &C1 = N1C->getAPIntValue();
4165 
4166     // (zext x) == C --> x == (trunc C)
4167     // (sext x) == C --> x == (trunc C)
4168     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4169         DCI.isBeforeLegalize() && N0->hasOneUse()) {
4170       unsigned MinBits = N0.getValueSizeInBits();
4171       SDValue PreExt;
4172       bool Signed = false;
4173       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
4174         // ZExt
4175         MinBits = N0->getOperand(0).getValueSizeInBits();
4176         PreExt = N0->getOperand(0);
4177       } else if (N0->getOpcode() == ISD::AND) {
4178         // DAGCombine turns costly ZExts into ANDs
4179         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
4180           if ((C->getAPIntValue()+1).isPowerOf2()) {
4181             MinBits = C->getAPIntValue().countTrailingOnes();
4182             PreExt = N0->getOperand(0);
4183           }
4184       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
4185         // SExt
4186         MinBits = N0->getOperand(0).getValueSizeInBits();
4187         PreExt = N0->getOperand(0);
4188         Signed = true;
4189       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
4190         // ZEXTLOAD / SEXTLOAD
4191         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
4192           MinBits = LN0->getMemoryVT().getSizeInBits();
4193           PreExt = N0;
4194         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
4195           Signed = true;
4196           MinBits = LN0->getMemoryVT().getSizeInBits();
4197           PreExt = N0;
4198         }
4199       }
4200 
4201       // Figure out how many bits we need to preserve this constant.
4202       unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits();
4203 
4204       // Make sure we're not losing bits from the constant.
4205       if (MinBits > 0 &&
4206           MinBits < C1.getBitWidth() &&
4207           MinBits >= ReqdBits) {
4208         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
4209         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
4210           // Will get folded away.
4211           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
4212           if (MinBits == 1 && C1 == 1)
4213             // Invert the condition.
4214             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
4215                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4216           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
4217           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
4218         }
4219 
4220         // If truncating the setcc operands is not desirable, we can still
4221         // simplify the expression in some cases:
4222         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
4223         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
4224         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
4225         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
4226         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
4227         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
4228         SDValue TopSetCC = N0->getOperand(0);
4229         unsigned N0Opc = N0->getOpcode();
4230         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
4231         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
4232             TopSetCC.getOpcode() == ISD::SETCC &&
4233             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
4234             (isConstFalseVal(N1) ||
4235              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
4236 
4237           bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
4238                          (!N1C->isZero() && Cond == ISD::SETNE);
4239 
4240           if (!Inverse)
4241             return TopSetCC;
4242 
4243           ISD::CondCode InvCond = ISD::getSetCCInverse(
4244               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
4245               TopSetCC.getOperand(0).getValueType());
4246           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
4247                                       TopSetCC.getOperand(1),
4248                                       InvCond);
4249         }
4250       }
4251     }
4252 
4253     // If the LHS is '(and load, const)', the RHS is 0, the test is for
4254     // equality or unsigned, and all 1 bits of the const are in the same
4255     // partial word, see if we can shorten the load.
4256     if (DCI.isBeforeLegalize() &&
4257         !ISD::isSignedIntSetCC(Cond) &&
4258         N0.getOpcode() == ISD::AND && C1 == 0 &&
4259         N0.getNode()->hasOneUse() &&
4260         isa<LoadSDNode>(N0.getOperand(0)) &&
4261         N0.getOperand(0).getNode()->hasOneUse() &&
4262         isa<ConstantSDNode>(N0.getOperand(1))) {
4263       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
4264       APInt bestMask;
4265       unsigned bestWidth = 0, bestOffset = 0;
4266       if (Lod->isSimple() && Lod->isUnindexed()) {
4267         unsigned origWidth = N0.getValueSizeInBits();
4268         unsigned maskWidth = origWidth;
4269         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
4270         // 8 bits, but have to be careful...
4271         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
4272           origWidth = Lod->getMemoryVT().getSizeInBits();
4273         const APInt &Mask = N0.getConstantOperandAPInt(1);
4274         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
4275           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
4276           for (unsigned offset=0; offset<origWidth/width; offset++) {
4277             if (Mask.isSubsetOf(newMask)) {
4278               if (Layout.isLittleEndian())
4279                 bestOffset = (uint64_t)offset * (width/8);
4280               else
4281                 bestOffset = (origWidth/width - offset - 1) * (width/8);
4282               bestMask = Mask.lshr(offset * (width/8) * 8);
4283               bestWidth = width;
4284               break;
4285             }
4286             newMask <<= width;
4287           }
4288         }
4289       }
4290       if (bestWidth) {
4291         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
4292         if (newVT.isRound() &&
4293             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
4294           SDValue Ptr = Lod->getBasePtr();
4295           if (bestOffset != 0)
4296             Ptr =
4297                 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl);
4298           SDValue NewLoad =
4299               DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
4300                           Lod->getPointerInfo().getWithOffset(bestOffset),
4301                           Lod->getOriginalAlign());
4302           return DAG.getSetCC(dl, VT,
4303                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
4304                                       DAG.getConstant(bestMask.trunc(bestWidth),
4305                                                       dl, newVT)),
4306                               DAG.getConstant(0LL, dl, newVT), Cond);
4307         }
4308       }
4309     }
4310 
4311     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
4312     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
4313       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
4314 
4315       // If the comparison constant has bits in the upper part, the
4316       // zero-extended value could never match.
4317       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
4318                                               C1.getBitWidth() - InSize))) {
4319         switch (Cond) {
4320         case ISD::SETUGT:
4321         case ISD::SETUGE:
4322         case ISD::SETEQ:
4323           return DAG.getConstant(0, dl, VT);
4324         case ISD::SETULT:
4325         case ISD::SETULE:
4326         case ISD::SETNE:
4327           return DAG.getConstant(1, dl, VT);
4328         case ISD::SETGT:
4329         case ISD::SETGE:
4330           // True if the sign bit of C1 is set.
4331           return DAG.getConstant(C1.isNegative(), dl, VT);
4332         case ISD::SETLT:
4333         case ISD::SETLE:
4334           // True if the sign bit of C1 isn't set.
4335           return DAG.getConstant(C1.isNonNegative(), dl, VT);
4336         default:
4337           break;
4338         }
4339       }
4340 
4341       // Otherwise, we can perform the comparison with the low bits.
4342       switch (Cond) {
4343       case ISD::SETEQ:
4344       case ISD::SETNE:
4345       case ISD::SETUGT:
4346       case ISD::SETUGE:
4347       case ISD::SETULT:
4348       case ISD::SETULE: {
4349         EVT newVT = N0.getOperand(0).getValueType();
4350         if (DCI.isBeforeLegalizeOps() ||
4351             (isOperationLegal(ISD::SETCC, newVT) &&
4352              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
4353           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
4354           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
4355 
4356           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
4357                                           NewConst, Cond);
4358           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
4359         }
4360         break;
4361       }
4362       default:
4363         break; // todo, be more careful with signed comparisons
4364       }
4365     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4366                (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4367                !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(),
4368                                       OpVT)) {
4369       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
4370       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
4371       EVT ExtDstTy = N0.getValueType();
4372       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
4373 
4374       // If the constant doesn't fit into the number of bits for the source of
4375       // the sign extension, it is impossible for both sides to be equal.
4376       if (C1.getMinSignedBits() > ExtSrcTyBits)
4377         return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
4378 
4379       assert(ExtDstTy == N0.getOperand(0).getValueType() &&
4380              ExtDstTy != ExtSrcTy && "Unexpected types!");
4381       APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
4382       SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
4383                                    DAG.getConstant(Imm, dl, ExtDstTy));
4384       if (!DCI.isCalledByLegalizer())
4385         DCI.AddToWorklist(ZextOp.getNode());
4386       // Otherwise, make this a use of a zext.
4387       return DAG.getSetCC(dl, VT, ZextOp,
4388                           DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
4389     } else if ((N1C->isZero() || N1C->isOne()) &&
4390                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4391       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
4392       if (N0.getOpcode() == ISD::SETCC &&
4393           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
4394           (N0.getValueType() == MVT::i1 ||
4395            getBooleanContents(N0.getOperand(0).getValueType()) ==
4396                        ZeroOrOneBooleanContent)) {
4397         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
4398         if (TrueWhenTrue)
4399           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
4400         // Invert the condition.
4401         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4402         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
4403         if (DCI.isBeforeLegalizeOps() ||
4404             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
4405           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
4406       }
4407 
4408       if ((N0.getOpcode() == ISD::XOR ||
4409            (N0.getOpcode() == ISD::AND &&
4410             N0.getOperand(0).getOpcode() == ISD::XOR &&
4411             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
4412           isOneConstant(N0.getOperand(1))) {
4413         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
4414         // can only do this if the top bits are known zero.
4415         unsigned BitWidth = N0.getValueSizeInBits();
4416         if (DAG.MaskedValueIsZero(N0,
4417                                   APInt::getHighBitsSet(BitWidth,
4418                                                         BitWidth-1))) {
4419           // Okay, get the un-inverted input value.
4420           SDValue Val;
4421           if (N0.getOpcode() == ISD::XOR) {
4422             Val = N0.getOperand(0);
4423           } else {
4424             assert(N0.getOpcode() == ISD::AND &&
4425                     N0.getOperand(0).getOpcode() == ISD::XOR);
4426             // ((X^1)&1)^1 -> X & 1
4427             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
4428                               N0.getOperand(0).getOperand(0),
4429                               N0.getOperand(1));
4430           }
4431 
4432           return DAG.getSetCC(dl, VT, Val, N1,
4433                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4434         }
4435       } else if (N1C->isOne()) {
4436         SDValue Op0 = N0;
4437         if (Op0.getOpcode() == ISD::TRUNCATE)
4438           Op0 = Op0.getOperand(0);
4439 
4440         if ((Op0.getOpcode() == ISD::XOR) &&
4441             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
4442             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
4443           SDValue XorLHS = Op0.getOperand(0);
4444           SDValue XorRHS = Op0.getOperand(1);
4445           // Ensure that the input setccs return an i1 type or 0/1 value.
4446           if (Op0.getValueType() == MVT::i1 ||
4447               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
4448                       ZeroOrOneBooleanContent &&
4449                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
4450                         ZeroOrOneBooleanContent)) {
4451             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
4452             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
4453             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
4454           }
4455         }
4456         if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
4457           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
4458           if (Op0.getValueType().bitsGT(VT))
4459             Op0 = DAG.getNode(ISD::AND, dl, VT,
4460                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
4461                           DAG.getConstant(1, dl, VT));
4462           else if (Op0.getValueType().bitsLT(VT))
4463             Op0 = DAG.getNode(ISD::AND, dl, VT,
4464                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
4465                         DAG.getConstant(1, dl, VT));
4466 
4467           return DAG.getSetCC(dl, VT, Op0,
4468                               DAG.getConstant(0, dl, Op0.getValueType()),
4469                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4470         }
4471         if (Op0.getOpcode() == ISD::AssertZext &&
4472             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
4473           return DAG.getSetCC(dl, VT, Op0,
4474                               DAG.getConstant(0, dl, Op0.getValueType()),
4475                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4476       }
4477     }
4478 
4479     // Given:
4480     //   icmp eq/ne (urem %x, %y), 0
4481     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
4482     //   icmp eq/ne %x, 0
4483     if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
4484         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4485       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
4486       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
4487       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
4488         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4489     }
4490 
4491     // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
4492     //  and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
4493     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4494         N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) &&
4495         N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
4496         N1C && N1C->isAllOnes()) {
4497       return DAG.getSetCC(dl, VT, N0.getOperand(0),
4498                           DAG.getConstant(0, dl, OpVT),
4499                           Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE);
4500     }
4501 
4502     if (SDValue V =
4503             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
4504       return V;
4505   }
4506 
4507   // These simplifications apply to splat vectors as well.
4508   // TODO: Handle more splat vector cases.
4509   if (auto *N1C = isConstOrConstSplat(N1)) {
4510     const APInt &C1 = N1C->getAPIntValue();
4511 
4512     APInt MinVal, MaxVal;
4513     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
4514     if (ISD::isSignedIntSetCC(Cond)) {
4515       MinVal = APInt::getSignedMinValue(OperandBitSize);
4516       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
4517     } else {
4518       MinVal = APInt::getMinValue(OperandBitSize);
4519       MaxVal = APInt::getMaxValue(OperandBitSize);
4520     }
4521 
4522     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
4523     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
4524       // X >= MIN --> true
4525       if (C1 == MinVal)
4526         return DAG.getBoolConstant(true, dl, VT, OpVT);
4527 
4528       if (!VT.isVector()) { // TODO: Support this for vectors.
4529         // X >= C0 --> X > (C0 - 1)
4530         APInt C = C1 - 1;
4531         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
4532         if ((DCI.isBeforeLegalizeOps() ||
4533              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4534             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4535                                   isLegalICmpImmediate(C.getSExtValue())))) {
4536           return DAG.getSetCC(dl, VT, N0,
4537                               DAG.getConstant(C, dl, N1.getValueType()),
4538                               NewCC);
4539         }
4540       }
4541     }
4542 
4543     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
4544       // X <= MAX --> true
4545       if (C1 == MaxVal)
4546         return DAG.getBoolConstant(true, dl, VT, OpVT);
4547 
4548       // X <= C0 --> X < (C0 + 1)
4549       if (!VT.isVector()) { // TODO: Support this for vectors.
4550         APInt C = C1 + 1;
4551         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
4552         if ((DCI.isBeforeLegalizeOps() ||
4553              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4554             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4555                                   isLegalICmpImmediate(C.getSExtValue())))) {
4556           return DAG.getSetCC(dl, VT, N0,
4557                               DAG.getConstant(C, dl, N1.getValueType()),
4558                               NewCC);
4559         }
4560       }
4561     }
4562 
4563     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
4564       if (C1 == MinVal)
4565         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
4566 
4567       // TODO: Support this for vectors after legalize ops.
4568       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4569         // Canonicalize setlt X, Max --> setne X, Max
4570         if (C1 == MaxVal)
4571           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4572 
4573         // If we have setult X, 1, turn it into seteq X, 0
4574         if (C1 == MinVal+1)
4575           return DAG.getSetCC(dl, VT, N0,
4576                               DAG.getConstant(MinVal, dl, N0.getValueType()),
4577                               ISD::SETEQ);
4578       }
4579     }
4580 
4581     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
4582       if (C1 == MaxVal)
4583         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
4584 
4585       // TODO: Support this for vectors after legalize ops.
4586       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4587         // Canonicalize setgt X, Min --> setne X, Min
4588         if (C1 == MinVal)
4589           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4590 
4591         // If we have setugt X, Max-1, turn it into seteq X, Max
4592         if (C1 == MaxVal-1)
4593           return DAG.getSetCC(dl, VT, N0,
4594                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
4595                               ISD::SETEQ);
4596       }
4597     }
4598 
4599     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
4600       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4601       if (C1.isZero())
4602         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
4603                 VT, N0, N1, Cond, DCI, dl))
4604           return CC;
4605 
4606       // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
4607       // For example, when high 32-bits of i64 X are known clear:
4608       // all bits clear: (X | (Y<<32)) ==  0 --> (X | Y) ==  0
4609       // all bits set:   (X | (Y<<32)) == -1 --> (X & Y) == -1
4610       bool CmpZero = N1C->getAPIntValue().isZero();
4611       bool CmpNegOne = N1C->getAPIntValue().isAllOnes();
4612       if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
4613         // Match or(lo,shl(hi,bw/2)) pattern.
4614         auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
4615           unsigned EltBits = V.getScalarValueSizeInBits();
4616           if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
4617             return false;
4618           SDValue LHS = V.getOperand(0);
4619           SDValue RHS = V.getOperand(1);
4620           APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
4621           // Unshifted element must have zero upperbits.
4622           if (RHS.getOpcode() == ISD::SHL &&
4623               isa<ConstantSDNode>(RHS.getOperand(1)) &&
4624               RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4625               DAG.MaskedValueIsZero(LHS, HiBits)) {
4626             Lo = LHS;
4627             Hi = RHS.getOperand(0);
4628             return true;
4629           }
4630           if (LHS.getOpcode() == ISD::SHL &&
4631               isa<ConstantSDNode>(LHS.getOperand(1)) &&
4632               LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4633               DAG.MaskedValueIsZero(RHS, HiBits)) {
4634             Lo = RHS;
4635             Hi = LHS.getOperand(0);
4636             return true;
4637           }
4638           return false;
4639         };
4640 
4641         auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
4642           unsigned EltBits = N0.getScalarValueSizeInBits();
4643           unsigned HalfBits = EltBits / 2;
4644           APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
4645           SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
4646           SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
4647           SDValue NewN0 =
4648               DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
4649           SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
4650           return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
4651         };
4652 
4653         SDValue Lo, Hi;
4654         if (IsConcat(N0, Lo, Hi))
4655           return MergeConcat(Lo, Hi);
4656 
4657         if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
4658           SDValue Lo0, Lo1, Hi0, Hi1;
4659           if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
4660               IsConcat(N0.getOperand(1), Lo1, Hi1)) {
4661             return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
4662                                DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
4663           }
4664         }
4665       }
4666     }
4667 
4668     // If we have "setcc X, C0", check to see if we can shrink the immediate
4669     // by changing cc.
4670     // TODO: Support this for vectors after legalize ops.
4671     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4672       // SETUGT X, SINTMAX  -> SETLT X, 0
4673       // SETUGE X, SINTMIN -> SETLT X, 0
4674       if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
4675           (Cond == ISD::SETUGE && C1.isMinSignedValue()))
4676         return DAG.getSetCC(dl, VT, N0,
4677                             DAG.getConstant(0, dl, N1.getValueType()),
4678                             ISD::SETLT);
4679 
4680       // SETULT X, SINTMIN  -> SETGT X, -1
4681       // SETULE X, SINTMAX  -> SETGT X, -1
4682       if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
4683           (Cond == ISD::SETULE && C1.isMaxSignedValue()))
4684         return DAG.getSetCC(dl, VT, N0,
4685                             DAG.getAllOnesConstant(dl, N1.getValueType()),
4686                             ISD::SETGT);
4687     }
4688   }
4689 
4690   // Back to non-vector simplifications.
4691   // TODO: Can we do these for vector splats?
4692   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4693     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4694     const APInt &C1 = N1C->getAPIntValue();
4695     EVT ShValTy = N0.getValueType();
4696 
4697     // Fold bit comparisons when we can. This will result in an
4698     // incorrect value when boolean false is negative one, unless
4699     // the bitsize is 1 in which case the false value is the same
4700     // in practice regardless of the representation.
4701     if ((VT.getSizeInBits() == 1 ||
4702          getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) &&
4703         (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4704         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
4705         N0.getOpcode() == ISD::AND) {
4706       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4707         EVT ShiftTy =
4708             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4709         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
4710           // Perform the xform if the AND RHS is a single bit.
4711           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
4712           if (AndRHS->getAPIntValue().isPowerOf2() &&
4713               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4714             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4715                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4716                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4717           }
4718         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
4719           // (X & 8) == 8  -->  (X & 8) >> 3
4720           // Perform the xform if C1 is a single bit.
4721           unsigned ShCt = C1.logBase2();
4722           if (C1.isPowerOf2() &&
4723               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4724             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4725                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4726                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4727           }
4728         }
4729       }
4730     }
4731 
4732     if (C1.getMinSignedBits() <= 64 &&
4733         !isLegalICmpImmediate(C1.getSExtValue())) {
4734       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4735       // (X & -256) == 256 -> (X >> 8) == 1
4736       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4737           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
4738         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4739           const APInt &AndRHSC = AndRHS->getAPIntValue();
4740           if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) {
4741             unsigned ShiftBits = AndRHSC.countTrailingZeros();
4742             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4743               SDValue Shift =
4744                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
4745                             DAG.getConstant(ShiftBits, dl, ShiftTy));
4746               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
4747               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
4748             }
4749           }
4750         }
4751       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
4752                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
4753         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
4754         // X <  0x100000000 -> (X >> 32) <  1
4755         // X >= 0x100000000 -> (X >> 32) >= 1
4756         // X <= 0x0ffffffff -> (X >> 32) <  1
4757         // X >  0x0ffffffff -> (X >> 32) >= 1
4758         unsigned ShiftBits;
4759         APInt NewC = C1;
4760         ISD::CondCode NewCond = Cond;
4761         if (AdjOne) {
4762           ShiftBits = C1.countTrailingOnes();
4763           NewC = NewC + 1;
4764           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4765         } else {
4766           ShiftBits = C1.countTrailingZeros();
4767         }
4768         NewC.lshrInPlace(ShiftBits);
4769         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
4770             isLegalICmpImmediate(NewC.getSExtValue()) &&
4771             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4772           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4773                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
4774           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
4775           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
4776         }
4777       }
4778     }
4779   }
4780 
4781   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
4782     auto *CFP = cast<ConstantFPSDNode>(N1);
4783     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
4784 
4785     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
4786     // constant if knowing that the operand is non-nan is enough.  We prefer to
4787     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
4788     // materialize 0.0.
4789     if (Cond == ISD::SETO || Cond == ISD::SETUO)
4790       return DAG.getSetCC(dl, VT, N0, N0, Cond);
4791 
4792     // setcc (fneg x), C -> setcc swap(pred) x, -C
4793     if (N0.getOpcode() == ISD::FNEG) {
4794       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
4795       if (DCI.isBeforeLegalizeOps() ||
4796           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
4797         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
4798         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
4799       }
4800     }
4801 
4802     // If the condition is not legal, see if we can find an equivalent one
4803     // which is legal.
4804     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
4805       // If the comparison was an awkward floating-point == or != and one of
4806       // the comparison operands is infinity or negative infinity, convert the
4807       // condition to a less-awkward <= or >=.
4808       if (CFP->getValueAPF().isInfinity()) {
4809         bool IsNegInf = CFP->getValueAPF().isNegative();
4810         ISD::CondCode NewCond = ISD::SETCC_INVALID;
4811         switch (Cond) {
4812         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
4813         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
4814         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
4815         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
4816         default: break;
4817         }
4818         if (NewCond != ISD::SETCC_INVALID &&
4819             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
4820           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4821       }
4822     }
4823   }
4824 
4825   if (N0 == N1) {
4826     // The sext(setcc()) => setcc() optimization relies on the appropriate
4827     // constant being emitted.
4828     assert(!N0.getValueType().isInteger() &&
4829            "Integer types should be handled by FoldSetCC");
4830 
4831     bool EqTrue = ISD::isTrueWhenEqual(Cond);
4832     unsigned UOF = ISD::getUnorderedFlavor(Cond);
4833     if (UOF == 2) // FP operators that are undefined on NaNs.
4834       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4835     if (UOF == unsigned(EqTrue))
4836       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4837     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
4838     // if it is not already.
4839     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4840     if (NewCond != Cond &&
4841         (DCI.isBeforeLegalizeOps() ||
4842                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
4843       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4844   }
4845 
4846   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4847       N0.getValueType().isInteger()) {
4848     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4849         N0.getOpcode() == ISD::XOR) {
4850       // Simplify (X+Y) == (X+Z) -->  Y == Z
4851       if (N0.getOpcode() == N1.getOpcode()) {
4852         if (N0.getOperand(0) == N1.getOperand(0))
4853           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
4854         if (N0.getOperand(1) == N1.getOperand(1))
4855           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
4856         if (isCommutativeBinOp(N0.getOpcode())) {
4857           // If X op Y == Y op X, try other combinations.
4858           if (N0.getOperand(0) == N1.getOperand(1))
4859             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
4860                                 Cond);
4861           if (N0.getOperand(1) == N1.getOperand(0))
4862             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
4863                                 Cond);
4864         }
4865       }
4866 
4867       // If RHS is a legal immediate value for a compare instruction, we need
4868       // to be careful about increasing register pressure needlessly.
4869       bool LegalRHSImm = false;
4870 
4871       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4872         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4873           // Turn (X+C1) == C2 --> X == C2-C1
4874           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
4875             return DAG.getSetCC(
4876                 dl, VT, N0.getOperand(0),
4877                 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
4878                                 dl, N0.getValueType()),
4879                 Cond);
4880 
4881           // Turn (X^C1) == C2 --> X == C1^C2
4882           if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
4883             return DAG.getSetCC(
4884                 dl, VT, N0.getOperand(0),
4885                 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
4886                                 dl, N0.getValueType()),
4887                 Cond);
4888         }
4889 
4890         // Turn (C1-X) == C2 --> X == C1-C2
4891         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4892           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
4893             return DAG.getSetCC(
4894                 dl, VT, N0.getOperand(1),
4895                 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
4896                                 dl, N0.getValueType()),
4897                 Cond);
4898 
4899         // Could RHSC fold directly into a compare?
4900         if (RHSC->getValueType(0).getSizeInBits() <= 64)
4901           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
4902       }
4903 
4904       // (X+Y) == X --> Y == 0 and similar folds.
4905       // Don't do this if X is an immediate that can fold into a cmp
4906       // instruction and X+Y has other uses. It could be an induction variable
4907       // chain, and the transform would increase register pressure.
4908       if (!LegalRHSImm || N0.hasOneUse())
4909         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
4910           return V;
4911     }
4912 
4913     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4914         N1.getOpcode() == ISD::XOR)
4915       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
4916         return V;
4917 
4918     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
4919       return V;
4920   }
4921 
4922   // Fold remainder of division by a constant.
4923   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
4924       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4925     AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4926 
4927     // When division is cheap or optimizing for minimum size,
4928     // fall through to DIVREM creation by skipping this fold.
4929     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
4930       if (N0.getOpcode() == ISD::UREM) {
4931         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
4932           return Folded;
4933       } else if (N0.getOpcode() == ISD::SREM) {
4934         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
4935           return Folded;
4936       }
4937     }
4938   }
4939 
4940   // Fold away ALL boolean setcc's.
4941   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
4942     SDValue Temp;
4943     switch (Cond) {
4944     default: llvm_unreachable("Unknown integer setcc!");
4945     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
4946       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4947       N0 = DAG.getNOT(dl, Temp, OpVT);
4948       if (!DCI.isCalledByLegalizer())
4949         DCI.AddToWorklist(Temp.getNode());
4950       break;
4951     case ISD::SETNE:  // X != Y   -->  (X^Y)
4952       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4953       break;
4954     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
4955     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
4956       Temp = DAG.getNOT(dl, N0, OpVT);
4957       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
4958       if (!DCI.isCalledByLegalizer())
4959         DCI.AddToWorklist(Temp.getNode());
4960       break;
4961     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
4962     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
4963       Temp = DAG.getNOT(dl, N1, OpVT);
4964       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
4965       if (!DCI.isCalledByLegalizer())
4966         DCI.AddToWorklist(Temp.getNode());
4967       break;
4968     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
4969     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
4970       Temp = DAG.getNOT(dl, N0, OpVT);
4971       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
4972       if (!DCI.isCalledByLegalizer())
4973         DCI.AddToWorklist(Temp.getNode());
4974       break;
4975     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
4976     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
4977       Temp = DAG.getNOT(dl, N1, OpVT);
4978       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
4979       break;
4980     }
4981     if (VT.getScalarType() != MVT::i1) {
4982       if (!DCI.isCalledByLegalizer())
4983         DCI.AddToWorklist(N0.getNode());
4984       // FIXME: If running after legalize, we probably can't do this.
4985       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
4986       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
4987     }
4988     return N0;
4989   }
4990 
4991   // Could not fold it.
4992   return SDValue();
4993 }
4994 
4995 /// Returns true (and the GlobalValue and the offset) if the node is a
4996 /// GlobalAddress + offset.
4997 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
4998                                     int64_t &Offset) const {
4999 
5000   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
5001 
5002   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
5003     GA = GASD->getGlobal();
5004     Offset += GASD->getOffset();
5005     return true;
5006   }
5007 
5008   if (N->getOpcode() == ISD::ADD) {
5009     SDValue N1 = N->getOperand(0);
5010     SDValue N2 = N->getOperand(1);
5011     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
5012       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
5013         Offset += V->getSExtValue();
5014         return true;
5015       }
5016     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
5017       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
5018         Offset += V->getSExtValue();
5019         return true;
5020       }
5021     }
5022   }
5023 
5024   return false;
5025 }
5026 
5027 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
5028                                           DAGCombinerInfo &DCI) const {
5029   // Default implementation: no optimization.
5030   return SDValue();
5031 }
5032 
5033 //===----------------------------------------------------------------------===//
5034 //  Inline Assembler Implementation Methods
5035 //===----------------------------------------------------------------------===//
5036 
5037 TargetLowering::ConstraintType
5038 TargetLowering::getConstraintType(StringRef Constraint) const {
5039   unsigned S = Constraint.size();
5040 
5041   if (S == 1) {
5042     switch (Constraint[0]) {
5043     default: break;
5044     case 'r':
5045       return C_RegisterClass;
5046     case 'm': // memory
5047     case 'o': // offsetable
5048     case 'V': // not offsetable
5049       return C_Memory;
5050     case 'p': // Address.
5051       return C_Address;
5052     case 'n': // Simple Integer
5053     case 'E': // Floating Point Constant
5054     case 'F': // Floating Point Constant
5055       return C_Immediate;
5056     case 'i': // Simple Integer or Relocatable Constant
5057     case 's': // Relocatable Constant
5058     case 'X': // Allow ANY value.
5059     case 'I': // Target registers.
5060     case 'J':
5061     case 'K':
5062     case 'L':
5063     case 'M':
5064     case 'N':
5065     case 'O':
5066     case 'P':
5067     case '<':
5068     case '>':
5069       return C_Other;
5070     }
5071   }
5072 
5073   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
5074     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
5075       return C_Memory;
5076     return C_Register;
5077   }
5078   return C_Unknown;
5079 }
5080 
5081 /// Try to replace an X constraint, which matches anything, with another that
5082 /// has more specific requirements based on the type of the corresponding
5083 /// operand.
5084 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5085   if (ConstraintVT.isInteger())
5086     return "r";
5087   if (ConstraintVT.isFloatingPoint())
5088     return "f"; // works for many targets
5089   return nullptr;
5090 }
5091 
5092 SDValue TargetLowering::LowerAsmOutputForConstraint(
5093     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
5094     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
5095   return SDValue();
5096 }
5097 
5098 /// Lower the specified operand into the Ops vector.
5099 /// If it is invalid, don't add anything to Ops.
5100 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
5101                                                   std::string &Constraint,
5102                                                   std::vector<SDValue> &Ops,
5103                                                   SelectionDAG &DAG) const {
5104 
5105   if (Constraint.length() > 1) return;
5106 
5107   char ConstraintLetter = Constraint[0];
5108   switch (ConstraintLetter) {
5109   default: break;
5110   case 'X':    // Allows any operand
5111   case 'i':    // Simple Integer or Relocatable Constant
5112   case 'n':    // Simple Integer
5113   case 's': {  // Relocatable Constant
5114 
5115     ConstantSDNode *C;
5116     uint64_t Offset = 0;
5117 
5118     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
5119     // etc., since getelementpointer is variadic. We can't use
5120     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
5121     // while in this case the GA may be furthest from the root node which is
5122     // likely an ISD::ADD.
5123     while (true) {
5124       if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
5125         // gcc prints these as sign extended.  Sign extend value to 64 bits
5126         // now; without this it would get ZExt'd later in
5127         // ScheduleDAGSDNodes::EmitNode, which is very generic.
5128         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
5129         BooleanContent BCont = getBooleanContents(MVT::i64);
5130         ISD::NodeType ExtOpc =
5131             IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
5132         int64_t ExtVal =
5133             ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
5134         Ops.push_back(
5135             DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
5136         return;
5137       }
5138       if (ConstraintLetter != 'n') {
5139         if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5140           Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5141                                                    GA->getValueType(0),
5142                                                    Offset + GA->getOffset()));
5143           return;
5144         }
5145         if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
5146           Ops.push_back(DAG.getTargetBlockAddress(
5147               BA->getBlockAddress(), BA->getValueType(0),
5148               Offset + BA->getOffset(), BA->getTargetFlags()));
5149           return;
5150         }
5151         if (isa<BasicBlockSDNode>(Op)) {
5152           Ops.push_back(Op);
5153           return;
5154         }
5155       }
5156       const unsigned OpCode = Op.getOpcode();
5157       if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
5158         if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
5159           Op = Op.getOperand(1);
5160         // Subtraction is not commutative.
5161         else if (OpCode == ISD::ADD &&
5162                  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
5163           Op = Op.getOperand(0);
5164         else
5165           return;
5166         Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
5167         continue;
5168       }
5169       return;
5170     }
5171     break;
5172   }
5173   }
5174 }
5175 
5176 std::pair<unsigned, const TargetRegisterClass *>
5177 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
5178                                              StringRef Constraint,
5179                                              MVT VT) const {
5180   if (Constraint.empty() || Constraint[0] != '{')
5181     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
5182   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
5183 
5184   // Remove the braces from around the name.
5185   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
5186 
5187   std::pair<unsigned, const TargetRegisterClass *> R =
5188       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
5189 
5190   // Figure out which register class contains this reg.
5191   for (const TargetRegisterClass *RC : RI->regclasses()) {
5192     // If none of the value types for this register class are valid, we
5193     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
5194     if (!isLegalRC(*RI, *RC))
5195       continue;
5196 
5197     for (const MCPhysReg &PR : *RC) {
5198       if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
5199         std::pair<unsigned, const TargetRegisterClass *> S =
5200             std::make_pair(PR, RC);
5201 
5202         // If this register class has the requested value type, return it,
5203         // otherwise keep searching and return the first class found
5204         // if no other is found which explicitly has the requested type.
5205         if (RI->isTypeLegalForClass(*RC, VT))
5206           return S;
5207         if (!R.second)
5208           R = S;
5209       }
5210     }
5211   }
5212 
5213   return R;
5214 }
5215 
5216 //===----------------------------------------------------------------------===//
5217 // Constraint Selection.
5218 
5219 /// Return true of this is an input operand that is a matching constraint like
5220 /// "4".
5221 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
5222   assert(!ConstraintCode.empty() && "No known constraint!");
5223   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
5224 }
5225 
5226 /// If this is an input matching constraint, this method returns the output
5227 /// operand it matches.
5228 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
5229   assert(!ConstraintCode.empty() && "No known constraint!");
5230   return atoi(ConstraintCode.c_str());
5231 }
5232 
5233 /// Split up the constraint string from the inline assembly value into the
5234 /// specific constraints and their prefixes, and also tie in the associated
5235 /// operand values.
5236 /// If this returns an empty vector, and if the constraint string itself
5237 /// isn't empty, there was an error parsing.
5238 TargetLowering::AsmOperandInfoVector
5239 TargetLowering::ParseConstraints(const DataLayout &DL,
5240                                  const TargetRegisterInfo *TRI,
5241                                  const CallBase &Call) const {
5242   /// Information about all of the constraints.
5243   AsmOperandInfoVector ConstraintOperands;
5244   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
5245   unsigned maCount = 0; // Largest number of multiple alternative constraints.
5246 
5247   // Do a prepass over the constraints, canonicalizing them, and building up the
5248   // ConstraintOperands list.
5249   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5250   unsigned ResNo = 0; // ResNo - The result number of the next output.
5251   unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
5252 
5253   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
5254     ConstraintOperands.emplace_back(std::move(CI));
5255     AsmOperandInfo &OpInfo = ConstraintOperands.back();
5256 
5257     // Update multiple alternative constraint count.
5258     if (OpInfo.multipleAlternatives.size() > maCount)
5259       maCount = OpInfo.multipleAlternatives.size();
5260 
5261     OpInfo.ConstraintVT = MVT::Other;
5262 
5263     // Compute the value type for each operand.
5264     switch (OpInfo.Type) {
5265     case InlineAsm::isOutput:
5266       // Indirect outputs just consume an argument.
5267       if (OpInfo.isIndirect) {
5268         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5269         break;
5270       }
5271 
5272       // The return value of the call is this value.  As such, there is no
5273       // corresponding argument.
5274       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
5275       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
5276         OpInfo.ConstraintVT =
5277             getSimpleValueType(DL, STy->getElementType(ResNo));
5278       } else {
5279         assert(ResNo == 0 && "Asm only has one result!");
5280         OpInfo.ConstraintVT =
5281             getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
5282       }
5283       ++ResNo;
5284       break;
5285     case InlineAsm::isInput:
5286       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5287       break;
5288     case InlineAsm::isLabel:
5289       OpInfo.CallOperandVal =
5290           cast<CallBrInst>(&Call)->getBlockAddressForIndirectDest(LabelNo);
5291       OpInfo.ConstraintVT =
5292           getAsmOperandValueType(DL, OpInfo.CallOperandVal->getType())
5293               .getSimpleVT();
5294       ++LabelNo;
5295       continue;
5296     case InlineAsm::isClobber:
5297       // Nothing to do.
5298       break;
5299     }
5300 
5301     if (OpInfo.CallOperandVal) {
5302       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
5303       if (OpInfo.isIndirect) {
5304         OpTy = Call.getParamElementType(ArgNo);
5305         assert(OpTy && "Indirect operand must have elementtype attribute");
5306       }
5307 
5308       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5309       if (StructType *STy = dyn_cast<StructType>(OpTy))
5310         if (STy->getNumElements() == 1)
5311           OpTy = STy->getElementType(0);
5312 
5313       // If OpTy is not a single value, it may be a struct/union that we
5314       // can tile with integers.
5315       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5316         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
5317         switch (BitSize) {
5318         default: break;
5319         case 1:
5320         case 8:
5321         case 16:
5322         case 32:
5323         case 64:
5324         case 128:
5325           OpTy = IntegerType::get(OpTy->getContext(), BitSize);
5326           break;
5327         }
5328       }
5329 
5330       EVT VT = getAsmOperandValueType(DL, OpTy, true);
5331       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
5332       ArgNo++;
5333     }
5334   }
5335 
5336   // If we have multiple alternative constraints, select the best alternative.
5337   if (!ConstraintOperands.empty()) {
5338     if (maCount) {
5339       unsigned bestMAIndex = 0;
5340       int bestWeight = -1;
5341       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
5342       int weight = -1;
5343       unsigned maIndex;
5344       // Compute the sums of the weights for each alternative, keeping track
5345       // of the best (highest weight) one so far.
5346       for (maIndex = 0; maIndex < maCount; ++maIndex) {
5347         int weightSum = 0;
5348         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5349              cIndex != eIndex; ++cIndex) {
5350           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5351           if (OpInfo.Type == InlineAsm::isClobber)
5352             continue;
5353 
5354           // If this is an output operand with a matching input operand,
5355           // look up the matching input. If their types mismatch, e.g. one
5356           // is an integer, the other is floating point, or their sizes are
5357           // different, flag it as an maCantMatch.
5358           if (OpInfo.hasMatchingInput()) {
5359             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5360             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5361               if ((OpInfo.ConstraintVT.isInteger() !=
5362                    Input.ConstraintVT.isInteger()) ||
5363                   (OpInfo.ConstraintVT.getSizeInBits() !=
5364                    Input.ConstraintVT.getSizeInBits())) {
5365                 weightSum = -1; // Can't match.
5366                 break;
5367               }
5368             }
5369           }
5370           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
5371           if (weight == -1) {
5372             weightSum = -1;
5373             break;
5374           }
5375           weightSum += weight;
5376         }
5377         // Update best.
5378         if (weightSum > bestWeight) {
5379           bestWeight = weightSum;
5380           bestMAIndex = maIndex;
5381         }
5382       }
5383 
5384       // Now select chosen alternative in each constraint.
5385       for (AsmOperandInfo &cInfo : ConstraintOperands)
5386         if (cInfo.Type != InlineAsm::isClobber)
5387           cInfo.selectAlternative(bestMAIndex);
5388     }
5389   }
5390 
5391   // Check and hook up tied operands, choose constraint code to use.
5392   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5393        cIndex != eIndex; ++cIndex) {
5394     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5395 
5396     // If this is an output operand with a matching input operand, look up the
5397     // matching input. If their types mismatch, e.g. one is an integer, the
5398     // other is floating point, or their sizes are different, flag it as an
5399     // error.
5400     if (OpInfo.hasMatchingInput()) {
5401       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5402 
5403       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5404         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
5405             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
5406                                          OpInfo.ConstraintVT);
5407         std::pair<unsigned, const TargetRegisterClass *> InputRC =
5408             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
5409                                          Input.ConstraintVT);
5410         if ((OpInfo.ConstraintVT.isInteger() !=
5411              Input.ConstraintVT.isInteger()) ||
5412             (MatchRC.second != InputRC.second)) {
5413           report_fatal_error("Unsupported asm: input constraint"
5414                              " with a matching output constraint of"
5415                              " incompatible type!");
5416         }
5417       }
5418     }
5419   }
5420 
5421   return ConstraintOperands;
5422 }
5423 
5424 /// Return an integer indicating how general CT is.
5425 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
5426   switch (CT) {
5427   case TargetLowering::C_Immediate:
5428   case TargetLowering::C_Other:
5429   case TargetLowering::C_Unknown:
5430     return 0;
5431   case TargetLowering::C_Register:
5432     return 1;
5433   case TargetLowering::C_RegisterClass:
5434     return 2;
5435   case TargetLowering::C_Memory:
5436   case TargetLowering::C_Address:
5437     return 3;
5438   }
5439   llvm_unreachable("Invalid constraint type");
5440 }
5441 
5442 /// Examine constraint type and operand type and determine a weight value.
5443 /// This object must already have been set up with the operand type
5444 /// and the current alternative constraint selected.
5445 TargetLowering::ConstraintWeight
5446   TargetLowering::getMultipleConstraintMatchWeight(
5447     AsmOperandInfo &info, int maIndex) const {
5448   InlineAsm::ConstraintCodeVector *rCodes;
5449   if (maIndex >= (int)info.multipleAlternatives.size())
5450     rCodes = &info.Codes;
5451   else
5452     rCodes = &info.multipleAlternatives[maIndex].Codes;
5453   ConstraintWeight BestWeight = CW_Invalid;
5454 
5455   // Loop over the options, keeping track of the most general one.
5456   for (const std::string &rCode : *rCodes) {
5457     ConstraintWeight weight =
5458         getSingleConstraintMatchWeight(info, rCode.c_str());
5459     if (weight > BestWeight)
5460       BestWeight = weight;
5461   }
5462 
5463   return BestWeight;
5464 }
5465 
5466 /// Examine constraint type and operand type and determine a weight value.
5467 /// This object must already have been set up with the operand type
5468 /// and the current alternative constraint selected.
5469 TargetLowering::ConstraintWeight
5470   TargetLowering::getSingleConstraintMatchWeight(
5471     AsmOperandInfo &info, const char *constraint) const {
5472   ConstraintWeight weight = CW_Invalid;
5473   Value *CallOperandVal = info.CallOperandVal;
5474     // If we don't have a value, we can't do a match,
5475     // but allow it at the lowest weight.
5476   if (!CallOperandVal)
5477     return CW_Default;
5478   // Look at the constraint type.
5479   switch (*constraint) {
5480     case 'i': // immediate integer.
5481     case 'n': // immediate integer with a known value.
5482       if (isa<ConstantInt>(CallOperandVal))
5483         weight = CW_Constant;
5484       break;
5485     case 's': // non-explicit intregal immediate.
5486       if (isa<GlobalValue>(CallOperandVal))
5487         weight = CW_Constant;
5488       break;
5489     case 'E': // immediate float if host format.
5490     case 'F': // immediate float.
5491       if (isa<ConstantFP>(CallOperandVal))
5492         weight = CW_Constant;
5493       break;
5494     case '<': // memory operand with autodecrement.
5495     case '>': // memory operand with autoincrement.
5496     case 'm': // memory operand.
5497     case 'o': // offsettable memory operand
5498     case 'V': // non-offsettable memory operand
5499       weight = CW_Memory;
5500       break;
5501     case 'r': // general register.
5502     case 'g': // general register, memory operand or immediate integer.
5503               // note: Clang converts "g" to "imr".
5504       if (CallOperandVal->getType()->isIntegerTy())
5505         weight = CW_Register;
5506       break;
5507     case 'X': // any operand.
5508   default:
5509     weight = CW_Default;
5510     break;
5511   }
5512   return weight;
5513 }
5514 
5515 /// If there are multiple different constraints that we could pick for this
5516 /// operand (e.g. "imr") try to pick the 'best' one.
5517 /// This is somewhat tricky: constraints fall into four classes:
5518 ///    Other         -> immediates and magic values
5519 ///    Register      -> one specific register
5520 ///    RegisterClass -> a group of regs
5521 ///    Memory        -> memory
5522 /// Ideally, we would pick the most specific constraint possible: if we have
5523 /// something that fits into a register, we would pick it.  The problem here
5524 /// is that if we have something that could either be in a register or in
5525 /// memory that use of the register could cause selection of *other*
5526 /// operands to fail: they might only succeed if we pick memory.  Because of
5527 /// this the heuristic we use is:
5528 ///
5529 ///  1) If there is an 'other' constraint, and if the operand is valid for
5530 ///     that constraint, use it.  This makes us take advantage of 'i'
5531 ///     constraints when available.
5532 ///  2) Otherwise, pick the most general constraint present.  This prefers
5533 ///     'm' over 'r', for example.
5534 ///
5535 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
5536                              const TargetLowering &TLI,
5537                              SDValue Op, SelectionDAG *DAG) {
5538   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
5539   unsigned BestIdx = 0;
5540   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
5541   int BestGenerality = -1;
5542 
5543   // Loop over the options, keeping track of the most general one.
5544   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
5545     TargetLowering::ConstraintType CType =
5546       TLI.getConstraintType(OpInfo.Codes[i]);
5547 
5548     // Indirect 'other' or 'immediate' constraints are not allowed.
5549     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
5550                                CType == TargetLowering::C_Register ||
5551                                CType == TargetLowering::C_RegisterClass))
5552       continue;
5553 
5554     // If this is an 'other' or 'immediate' constraint, see if the operand is
5555     // valid for it. For example, on X86 we might have an 'rI' constraint. If
5556     // the operand is an integer in the range [0..31] we want to use I (saving a
5557     // load of a register), otherwise we must use 'r'.
5558     if ((CType == TargetLowering::C_Other ||
5559          CType == TargetLowering::C_Immediate) && Op.getNode()) {
5560       assert(OpInfo.Codes[i].size() == 1 &&
5561              "Unhandled multi-letter 'other' constraint");
5562       std::vector<SDValue> ResultOps;
5563       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
5564                                        ResultOps, *DAG);
5565       if (!ResultOps.empty()) {
5566         BestType = CType;
5567         BestIdx = i;
5568         break;
5569       }
5570     }
5571 
5572     // Things with matching constraints can only be registers, per gcc
5573     // documentation.  This mainly affects "g" constraints.
5574     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
5575       continue;
5576 
5577     // This constraint letter is more general than the previous one, use it.
5578     int Generality = getConstraintGenerality(CType);
5579     if (Generality > BestGenerality) {
5580       BestType = CType;
5581       BestIdx = i;
5582       BestGenerality = Generality;
5583     }
5584   }
5585 
5586   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
5587   OpInfo.ConstraintType = BestType;
5588 }
5589 
5590 /// Determines the constraint code and constraint type to use for the specific
5591 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5592 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5593                                             SDValue Op,
5594                                             SelectionDAG *DAG) const {
5595   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
5596 
5597   // Single-letter constraints ('r') are very common.
5598   if (OpInfo.Codes.size() == 1) {
5599     OpInfo.ConstraintCode = OpInfo.Codes[0];
5600     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5601   } else {
5602     ChooseConstraint(OpInfo, *this, Op, DAG);
5603   }
5604 
5605   // 'X' matches anything.
5606   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
5607     // Constants are handled elsewhere.  For Functions, the type here is the
5608     // type of the result, which is not what we want to look at; leave them
5609     // alone.
5610     Value *v = OpInfo.CallOperandVal;
5611     if (isa<ConstantInt>(v) || isa<Function>(v)) {
5612       return;
5613     }
5614 
5615     if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
5616       OpInfo.ConstraintCode = "i";
5617       return;
5618     }
5619 
5620     // Otherwise, try to resolve it to something we know about by looking at
5621     // the actual operand type.
5622     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
5623       OpInfo.ConstraintCode = Repl;
5624       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5625     }
5626   }
5627 }
5628 
5629 /// Given an exact SDIV by a constant, create a multiplication
5630 /// with the multiplicative inverse of the constant.
5631 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
5632                               const SDLoc &dl, SelectionDAG &DAG,
5633                               SmallVectorImpl<SDNode *> &Created) {
5634   SDValue Op0 = N->getOperand(0);
5635   SDValue Op1 = N->getOperand(1);
5636   EVT VT = N->getValueType(0);
5637   EVT SVT = VT.getScalarType();
5638   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
5639   EVT ShSVT = ShVT.getScalarType();
5640 
5641   bool UseSRA = false;
5642   SmallVector<SDValue, 16> Shifts, Factors;
5643 
5644   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5645     if (C->isZero())
5646       return false;
5647     APInt Divisor = C->getAPIntValue();
5648     unsigned Shift = Divisor.countTrailingZeros();
5649     if (Shift) {
5650       Divisor.ashrInPlace(Shift);
5651       UseSRA = true;
5652     }
5653     // Calculate the multiplicative inverse, using Newton's method.
5654     APInt t;
5655     APInt Factor = Divisor;
5656     while ((t = Divisor * Factor) != 1)
5657       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
5658     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
5659     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
5660     return true;
5661   };
5662 
5663   // Collect all magic values from the build vector.
5664   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
5665     return SDValue();
5666 
5667   SDValue Shift, Factor;
5668   if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
5669     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5670     Factor = DAG.getBuildVector(VT, dl, Factors);
5671   } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
5672     assert(Shifts.size() == 1 && Factors.size() == 1 &&
5673            "Expected matchUnaryPredicate to return one element for scalable "
5674            "vectors");
5675     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5676     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5677   } else {
5678     assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
5679     Shift = Shifts[0];
5680     Factor = Factors[0];
5681   }
5682 
5683   SDValue Res = Op0;
5684 
5685   // Shift the value upfront if it is even, so the LSB is one.
5686   if (UseSRA) {
5687     // TODO: For UDIV use SRL instead of SRA.
5688     SDNodeFlags Flags;
5689     Flags.setExact(true);
5690     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
5691     Created.push_back(Res.getNode());
5692   }
5693 
5694   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
5695 }
5696 
5697 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
5698                               SelectionDAG &DAG,
5699                               SmallVectorImpl<SDNode *> &Created) const {
5700   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5702   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5703     return SDValue(N, 0); // Lower SDIV as SDIV
5704   return SDValue();
5705 }
5706 
5707 SDValue
5708 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor,
5709                               SelectionDAG &DAG,
5710                               SmallVectorImpl<SDNode *> &Created) const {
5711   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5712   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5713   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5714     return SDValue(N, 0); // Lower SREM as SREM
5715   return SDValue();
5716 }
5717 
5718 /// Given an ISD::SDIV node expressing a divide by constant,
5719 /// return a DAG expression to select that will generate the same value by
5720 /// multiplying by a magic number.
5721 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5722 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
5723                                   bool IsAfterLegalization,
5724                                   SmallVectorImpl<SDNode *> &Created) const {
5725   SDLoc dl(N);
5726   EVT VT = N->getValueType(0);
5727   EVT SVT = VT.getScalarType();
5728   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5729   EVT ShSVT = ShVT.getScalarType();
5730   unsigned EltBits = VT.getScalarSizeInBits();
5731   EVT MulVT;
5732 
5733   // Check to see if we can do this.
5734   // FIXME: We should be more aggressive here.
5735   if (!isTypeLegal(VT)) {
5736     // Limit this to simple scalars for now.
5737     if (VT.isVector() || !VT.isSimple())
5738       return SDValue();
5739 
5740     // If this type will be promoted to a large enough type with a legal
5741     // multiply operation, we can go ahead and do this transform.
5742     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5743       return SDValue();
5744 
5745     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5746     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5747         !isOperationLegal(ISD::MUL, MulVT))
5748       return SDValue();
5749   }
5750 
5751   // If the sdiv has an 'exact' bit we can use a simpler lowering.
5752   if (N->getFlags().hasExact())
5753     return BuildExactSDIV(*this, N, dl, DAG, Created);
5754 
5755   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
5756 
5757   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5758     if (C->isZero())
5759       return false;
5760 
5761     const APInt &Divisor = C->getAPIntValue();
5762     SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor);
5763     int NumeratorFactor = 0;
5764     int ShiftMask = -1;
5765 
5766     if (Divisor.isOne() || Divisor.isAllOnes()) {
5767       // If d is +1/-1, we just multiply the numerator by +1/-1.
5768       NumeratorFactor = Divisor.getSExtValue();
5769       magics.Magic = 0;
5770       magics.ShiftAmount = 0;
5771       ShiftMask = 0;
5772     } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
5773       // If d > 0 and m < 0, add the numerator.
5774       NumeratorFactor = 1;
5775     } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
5776       // If d < 0 and m > 0, subtract the numerator.
5777       NumeratorFactor = -1;
5778     }
5779 
5780     MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT));
5781     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
5782     Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
5783     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
5784     return true;
5785   };
5786 
5787   SDValue N0 = N->getOperand(0);
5788   SDValue N1 = N->getOperand(1);
5789 
5790   // Collect the shifts / magic values from each element.
5791   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
5792     return SDValue();
5793 
5794   SDValue MagicFactor, Factor, Shift, ShiftMask;
5795   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5796     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5797     Factor = DAG.getBuildVector(VT, dl, Factors);
5798     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5799     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
5800   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5801     assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
5802            Shifts.size() == 1 && ShiftMasks.size() == 1 &&
5803            "Expected matchUnaryPredicate to return one element for scalable "
5804            "vectors");
5805     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5806     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5807     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5808     ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
5809   } else {
5810     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5811     MagicFactor = MagicFactors[0];
5812     Factor = Factors[0];
5813     Shift = Shifts[0];
5814     ShiftMask = ShiftMasks[0];
5815   }
5816 
5817   // Multiply the numerator (operand 0) by the magic value.
5818   // FIXME: We should support doing a MUL in a wider type.
5819   auto GetMULHS = [&](SDValue X, SDValue Y) {
5820     // If the type isn't legal, use a wider mul of the the type calculated
5821     // earlier.
5822     if (!isTypeLegal(VT)) {
5823       X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
5824       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
5825       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5826       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5827                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5828       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5829     }
5830 
5831     if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization))
5832       return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
5833     if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) {
5834       SDValue LoHi =
5835           DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5836       return SDValue(LoHi.getNode(), 1);
5837     }
5838     return SDValue();
5839   };
5840 
5841   SDValue Q = GetMULHS(N0, MagicFactor);
5842   if (!Q)
5843     return SDValue();
5844 
5845   Created.push_back(Q.getNode());
5846 
5847   // (Optionally) Add/subtract the numerator using Factor.
5848   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
5849   Created.push_back(Factor.getNode());
5850   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
5851   Created.push_back(Q.getNode());
5852 
5853   // Shift right algebraic by shift value.
5854   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
5855   Created.push_back(Q.getNode());
5856 
5857   // Extract the sign bit, mask it and add it to the quotient.
5858   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
5859   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
5860   Created.push_back(T.getNode());
5861   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
5862   Created.push_back(T.getNode());
5863   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
5864 }
5865 
5866 /// Given an ISD::UDIV node expressing a divide by constant,
5867 /// return a DAG expression to select that will generate the same value by
5868 /// multiplying by a magic number.
5869 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5870 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
5871                                   bool IsAfterLegalization,
5872                                   SmallVectorImpl<SDNode *> &Created) const {
5873   SDLoc dl(N);
5874   EVT VT = N->getValueType(0);
5875   EVT SVT = VT.getScalarType();
5876   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5877   EVT ShSVT = ShVT.getScalarType();
5878   unsigned EltBits = VT.getScalarSizeInBits();
5879   EVT MulVT;
5880 
5881   // Check to see if we can do this.
5882   // FIXME: We should be more aggressive here.
5883   if (!isTypeLegal(VT)) {
5884     // Limit this to simple scalars for now.
5885     if (VT.isVector() || !VT.isSimple())
5886       return SDValue();
5887 
5888     // If this type will be promoted to a large enough type with a legal
5889     // multiply operation, we can go ahead and do this transform.
5890     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5891       return SDValue();
5892 
5893     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5894     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5895         !isOperationLegal(ISD::MUL, MulVT))
5896       return SDValue();
5897   }
5898 
5899   bool UseNPQ = false;
5900   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5901 
5902   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
5903     if (C->isZero())
5904       return false;
5905     // FIXME: We should use a narrower constant when the upper
5906     // bits are known to be zero.
5907     const APInt& Divisor = C->getAPIntValue();
5908     UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor);
5909     unsigned PreShift = 0, PostShift = 0;
5910 
5911     // If the divisor is even, we can avoid using the expensive fixup by
5912     // shifting the divided value upfront.
5913     if (magics.IsAdd != 0 && !Divisor[0]) {
5914       PreShift = Divisor.countTrailingZeros();
5915       // Get magic number for the shifted divisor.
5916       magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
5917       assert(magics.IsAdd == 0 && "Should use cheap fixup now");
5918     }
5919 
5920     APInt Magic = magics.Magic;
5921 
5922     unsigned SelNPQ;
5923     if (magics.IsAdd == 0 || Divisor.isOne()) {
5924       assert(magics.ShiftAmount < Divisor.getBitWidth() &&
5925              "We shouldn't generate an undefined shift!");
5926       PostShift = magics.ShiftAmount;
5927       SelNPQ = false;
5928     } else {
5929       PostShift = magics.ShiftAmount - 1;
5930       SelNPQ = true;
5931     }
5932 
5933     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
5934     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
5935     NPQFactors.push_back(
5936         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5937                                : APInt::getZero(EltBits),
5938                         dl, SVT));
5939     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
5940     UseNPQ |= SelNPQ;
5941     return true;
5942   };
5943 
5944   SDValue N0 = N->getOperand(0);
5945   SDValue N1 = N->getOperand(1);
5946 
5947   // Collect the shifts/magic values from each element.
5948   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
5949     return SDValue();
5950 
5951   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
5952   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5953     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
5954     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5955     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
5956     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
5957   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5958     assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
5959            NPQFactors.size() == 1 && PostShifts.size() == 1 &&
5960            "Expected matchUnaryPredicate to return one for scalable vectors");
5961     PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
5962     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5963     NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
5964     PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
5965   } else {
5966     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5967     PreShift = PreShifts[0];
5968     MagicFactor = MagicFactors[0];
5969     PostShift = PostShifts[0];
5970   }
5971 
5972   SDValue Q = N0;
5973   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
5974   Created.push_back(Q.getNode());
5975 
5976   // FIXME: We should support doing a MUL in a wider type.
5977   auto GetMULHU = [&](SDValue X, SDValue Y) {
5978     // If the type isn't legal, use a wider mul of the the type calculated
5979     // earlier.
5980     if (!isTypeLegal(VT)) {
5981       X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
5982       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
5983       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5984       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5985                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5986       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5987     }
5988 
5989     if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization))
5990       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
5991     if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) {
5992       SDValue LoHi =
5993           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5994       return SDValue(LoHi.getNode(), 1);
5995     }
5996     return SDValue(); // No mulhu or equivalent
5997   };
5998 
5999   // Multiply the numerator (operand 0) by the magic value.
6000   Q = GetMULHU(Q, MagicFactor);
6001   if (!Q)
6002     return SDValue();
6003 
6004   Created.push_back(Q.getNode());
6005 
6006   if (UseNPQ) {
6007     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
6008     Created.push_back(NPQ.getNode());
6009 
6010     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
6011     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
6012     if (VT.isVector())
6013       NPQ = GetMULHU(NPQ, NPQFactor);
6014     else
6015       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
6016 
6017     Created.push_back(NPQ.getNode());
6018 
6019     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
6020     Created.push_back(Q.getNode());
6021   }
6022 
6023   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
6024   Created.push_back(Q.getNode());
6025 
6026   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6027 
6028   SDValue One = DAG.getConstant(1, dl, VT);
6029   SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
6030   return DAG.getSelect(dl, VT, IsOne, N0, Q);
6031 }
6032 
6033 /// If all values in Values that *don't* match the predicate are same 'splat'
6034 /// value, then replace all values with that splat value.
6035 /// Else, if AlternativeReplacement was provided, then replace all values that
6036 /// do match predicate with AlternativeReplacement value.
6037 static void
6038 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
6039                           std::function<bool(SDValue)> Predicate,
6040                           SDValue AlternativeReplacement = SDValue()) {
6041   SDValue Replacement;
6042   // Is there a value for which the Predicate does *NOT* match? What is it?
6043   auto SplatValue = llvm::find_if_not(Values, Predicate);
6044   if (SplatValue != Values.end()) {
6045     // Does Values consist only of SplatValue's and values matching Predicate?
6046     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
6047           return Value == *SplatValue || Predicate(Value);
6048         })) // Then we shall replace values matching predicate with SplatValue.
6049       Replacement = *SplatValue;
6050   }
6051   if (!Replacement) {
6052     // Oops, we did not find the "baseline" splat value.
6053     if (!AlternativeReplacement)
6054       return; // Nothing to do.
6055     // Let's replace with provided value then.
6056     Replacement = AlternativeReplacement;
6057   }
6058   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
6059 }
6060 
6061 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
6062 /// where the divisor is constant and the comparison target is zero,
6063 /// return a DAG expression that will generate the same comparison result
6064 /// using only multiplications, additions and shifts/rotations.
6065 /// Ref: "Hacker's Delight" 10-17.
6066 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
6067                                         SDValue CompTargetNode,
6068                                         ISD::CondCode Cond,
6069                                         DAGCombinerInfo &DCI,
6070                                         const SDLoc &DL) const {
6071   SmallVector<SDNode *, 5> Built;
6072   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6073                                          DCI, DL, Built)) {
6074     for (SDNode *N : Built)
6075       DCI.AddToWorklist(N);
6076     return Folded;
6077   }
6078 
6079   return SDValue();
6080 }
6081 
6082 SDValue
6083 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
6084                                   SDValue CompTargetNode, ISD::CondCode Cond,
6085                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6086                                   SmallVectorImpl<SDNode *> &Created) const {
6087   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
6088   // - D must be constant, with D = D0 * 2^K where D0 is odd
6089   // - P is the multiplicative inverse of D0 modulo 2^W
6090   // - Q = floor(((2^W) - 1) / D)
6091   // where W is the width of the common type of N and D.
6092   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6093          "Only applicable for (in)equality comparisons.");
6094 
6095   SelectionDAG &DAG = DCI.DAG;
6096 
6097   EVT VT = REMNode.getValueType();
6098   EVT SVT = VT.getScalarType();
6099   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6100   EVT ShSVT = ShVT.getScalarType();
6101 
6102   // If MUL is unavailable, we cannot proceed in any case.
6103   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6104     return SDValue();
6105 
6106   bool ComparingWithAllZeros = true;
6107   bool AllComparisonsWithNonZerosAreTautological = true;
6108   bool HadTautologicalLanes = false;
6109   bool AllLanesAreTautological = true;
6110   bool HadEvenDivisor = false;
6111   bool AllDivisorsArePowerOfTwo = true;
6112   bool HadTautologicalInvertedLanes = false;
6113   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
6114 
6115   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
6116     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6117     if (CDiv->isZero())
6118       return false;
6119 
6120     const APInt &D = CDiv->getAPIntValue();
6121     const APInt &Cmp = CCmp->getAPIntValue();
6122 
6123     ComparingWithAllZeros &= Cmp.isZero();
6124 
6125     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6126     // if C2 is not less than C1, the comparison is always false.
6127     // But we will only be able to produce the comparison that will give the
6128     // opposive tautological answer. So this lane would need to be fixed up.
6129     bool TautologicalInvertedLane = D.ule(Cmp);
6130     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
6131 
6132     // If all lanes are tautological (either all divisors are ones, or divisor
6133     // is not greater than the constant we are comparing with),
6134     // we will prefer to avoid the fold.
6135     bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
6136     HadTautologicalLanes |= TautologicalLane;
6137     AllLanesAreTautological &= TautologicalLane;
6138 
6139     // If we are comparing with non-zero, we need'll need  to subtract said
6140     // comparison value from the LHS. But there is no point in doing that if
6141     // every lane where we are comparing with non-zero is tautological..
6142     if (!Cmp.isZero())
6143       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
6144 
6145     // Decompose D into D0 * 2^K
6146     unsigned K = D.countTrailingZeros();
6147     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6148     APInt D0 = D.lshr(K);
6149 
6150     // D is even if it has trailing zeros.
6151     HadEvenDivisor |= (K != 0);
6152     // D is a power-of-two if D0 is one.
6153     // If all divisors are power-of-two, we will prefer to avoid the fold.
6154     AllDivisorsArePowerOfTwo &= D0.isOne();
6155 
6156     // P = inv(D0, 2^W)
6157     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6158     unsigned W = D.getBitWidth();
6159     APInt P = D0.zext(W + 1)
6160                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6161                   .trunc(W);
6162     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6163     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6164 
6165     // Q = floor((2^W - 1) u/ D)
6166     // R = ((2^W - 1) u% D)
6167     APInt Q, R;
6168     APInt::udivrem(APInt::getAllOnes(W), D, Q, R);
6169 
6170     // If we are comparing with zero, then that comparison constant is okay,
6171     // else it may need to be one less than that.
6172     if (Cmp.ugt(R))
6173       Q -= 1;
6174 
6175     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6176            "We are expecting that K is always less than all-ones for ShSVT");
6177 
6178     // If the lane is tautological the result can be constant-folded.
6179     if (TautologicalLane) {
6180       // Set P and K amount to a bogus values so we can try to splat them.
6181       P = 0;
6182       K = -1;
6183       // And ensure that comparison constant is tautological,
6184       // it will always compare true/false.
6185       Q = -1;
6186     }
6187 
6188     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6189     KAmts.push_back(
6190         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6191     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6192     return true;
6193   };
6194 
6195   SDValue N = REMNode.getOperand(0);
6196   SDValue D = REMNode.getOperand(1);
6197 
6198   // Collect the values from each element.
6199   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
6200     return SDValue();
6201 
6202   // If all lanes are tautological, the result can be constant-folded.
6203   if (AllLanesAreTautological)
6204     return SDValue();
6205 
6206   // If this is a urem by a powers-of-two, avoid the fold since it can be
6207   // best implemented as a bit test.
6208   if (AllDivisorsArePowerOfTwo)
6209     return SDValue();
6210 
6211   SDValue PVal, KVal, QVal;
6212   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6213     if (HadTautologicalLanes) {
6214       // Try to turn PAmts into a splat, since we don't care about the values
6215       // that are currently '0'. If we can't, just keep '0'`s.
6216       turnVectorIntoSplatVector(PAmts, isNullConstant);
6217       // Try to turn KAmts into a splat, since we don't care about the values
6218       // that are currently '-1'. If we can't, change them to '0'`s.
6219       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6220                                 DAG.getConstant(0, DL, ShSVT));
6221     }
6222 
6223     PVal = DAG.getBuildVector(VT, DL, PAmts);
6224     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6225     QVal = DAG.getBuildVector(VT, DL, QAmts);
6226   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6227     assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
6228            "Expected matchBinaryPredicate to return one element for "
6229            "SPLAT_VECTORs");
6230     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6231     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6232     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6233   } else {
6234     PVal = PAmts[0];
6235     KVal = KAmts[0];
6236     QVal = QAmts[0];
6237   }
6238 
6239   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
6240     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
6241       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
6242     assert(CompTargetNode.getValueType() == N.getValueType() &&
6243            "Expecting that the types on LHS and RHS of comparisons match.");
6244     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
6245   }
6246 
6247   // (mul N, P)
6248   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6249   Created.push_back(Op0.getNode());
6250 
6251   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6252   // divisors as a performance improvement, since rotating by 0 is a no-op.
6253   if (HadEvenDivisor) {
6254     // We need ROTR to do this.
6255     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6256       return SDValue();
6257     // UREM: (rotr (mul N, P), K)
6258     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6259     Created.push_back(Op0.getNode());
6260   }
6261 
6262   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
6263   SDValue NewCC =
6264       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6265                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6266   if (!HadTautologicalInvertedLanes)
6267     return NewCC;
6268 
6269   // If any lanes previously compared always-false, the NewCC will give
6270   // always-true result for them, so we need to fixup those lanes.
6271   // Or the other way around for inequality predicate.
6272   assert(VT.isVector() && "Can/should only get here for vectors.");
6273   Created.push_back(NewCC.getNode());
6274 
6275   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6276   // if C2 is not less than C1, the comparison is always false.
6277   // But we have produced the comparison that will give the
6278   // opposive tautological answer. So these lanes would need to be fixed up.
6279   SDValue TautologicalInvertedChannels =
6280       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
6281   Created.push_back(TautologicalInvertedChannels.getNode());
6282 
6283   // NOTE: we avoid letting illegal types through even if we're before legalize
6284   // ops – legalization has a hard time producing good code for this.
6285   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
6286     // If we have a vector select, let's replace the comparison results in the
6287     // affected lanes with the correct tautological result.
6288     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
6289                                               DL, SETCCVT, SETCCVT);
6290     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
6291                        Replacement, NewCC);
6292   }
6293 
6294   // Else, we can just invert the comparison result in the appropriate lanes.
6295   //
6296   // NOTE: see the note above VSELECT above.
6297   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
6298     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
6299                        TautologicalInvertedChannels);
6300 
6301   return SDValue(); // Don't know how to lower.
6302 }
6303 
6304 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
6305 /// where the divisor is constant and the comparison target is zero,
6306 /// return a DAG expression that will generate the same comparison result
6307 /// using only multiplications, additions and shifts/rotations.
6308 /// Ref: "Hacker's Delight" 10-17.
6309 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
6310                                         SDValue CompTargetNode,
6311                                         ISD::CondCode Cond,
6312                                         DAGCombinerInfo &DCI,
6313                                         const SDLoc &DL) const {
6314   SmallVector<SDNode *, 7> Built;
6315   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6316                                          DCI, DL, Built)) {
6317     assert(Built.size() <= 7 && "Max size prediction failed.");
6318     for (SDNode *N : Built)
6319       DCI.AddToWorklist(N);
6320     return Folded;
6321   }
6322 
6323   return SDValue();
6324 }
6325 
6326 SDValue
6327 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
6328                                   SDValue CompTargetNode, ISD::CondCode Cond,
6329                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6330                                   SmallVectorImpl<SDNode *> &Created) const {
6331   // Fold:
6332   //   (seteq/ne (srem N, D), 0)
6333   // To:
6334   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
6335   //
6336   // - D must be constant, with D = D0 * 2^K where D0 is odd
6337   // - P is the multiplicative inverse of D0 modulo 2^W
6338   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
6339   // - Q = floor((2 * A) / (2^K))
6340   // where W is the width of the common type of N and D.
6341   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6342          "Only applicable for (in)equality comparisons.");
6343 
6344   SelectionDAG &DAG = DCI.DAG;
6345 
6346   EVT VT = REMNode.getValueType();
6347   EVT SVT = VT.getScalarType();
6348   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6349   EVT ShSVT = ShVT.getScalarType();
6350 
6351   // If we are after ops legalization, and MUL is unavailable, we can not
6352   // proceed.
6353   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6354     return SDValue();
6355 
6356   // TODO: Could support comparing with non-zero too.
6357   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
6358   if (!CompTarget || !CompTarget->isZero())
6359     return SDValue();
6360 
6361   bool HadIntMinDivisor = false;
6362   bool HadOneDivisor = false;
6363   bool AllDivisorsAreOnes = true;
6364   bool HadEvenDivisor = false;
6365   bool NeedToApplyOffset = false;
6366   bool AllDivisorsArePowerOfTwo = true;
6367   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
6368 
6369   auto BuildSREMPattern = [&](ConstantSDNode *C) {
6370     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6371     if (C->isZero())
6372       return false;
6373 
6374     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
6375 
6376     // WARNING: this fold is only valid for positive divisors!
6377     APInt D = C->getAPIntValue();
6378     if (D.isNegative())
6379       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
6380 
6381     HadIntMinDivisor |= D.isMinSignedValue();
6382 
6383     // If all divisors are ones, we will prefer to avoid the fold.
6384     HadOneDivisor |= D.isOne();
6385     AllDivisorsAreOnes &= D.isOne();
6386 
6387     // Decompose D into D0 * 2^K
6388     unsigned K = D.countTrailingZeros();
6389     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6390     APInt D0 = D.lshr(K);
6391 
6392     if (!D.isMinSignedValue()) {
6393       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
6394       // we don't care about this lane in this fold, we'll special-handle it.
6395       HadEvenDivisor |= (K != 0);
6396     }
6397 
6398     // D is a power-of-two if D0 is one. This includes INT_MIN.
6399     // If all divisors are power-of-two, we will prefer to avoid the fold.
6400     AllDivisorsArePowerOfTwo &= D0.isOne();
6401 
6402     // P = inv(D0, 2^W)
6403     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6404     unsigned W = D.getBitWidth();
6405     APInt P = D0.zext(W + 1)
6406                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6407                   .trunc(W);
6408     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6409     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6410 
6411     // A = floor((2^(W - 1) - 1) / D0) & -2^K
6412     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
6413     A.clearLowBits(K);
6414 
6415     if (!D.isMinSignedValue()) {
6416       // If divisor INT_MIN, then we don't care about this lane in this fold,
6417       // we'll special-handle it.
6418       NeedToApplyOffset |= A != 0;
6419     }
6420 
6421     // Q = floor((2 * A) / (2^K))
6422     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
6423 
6424     assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) &&
6425            "We are expecting that A is always less than all-ones for SVT");
6426     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6427            "We are expecting that K is always less than all-ones for ShSVT");
6428 
6429     // If the divisor is 1 the result can be constant-folded. Likewise, we
6430     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
6431     if (D.isOne()) {
6432       // Set P, A and K to a bogus values so we can try to splat them.
6433       P = 0;
6434       A = -1;
6435       K = -1;
6436 
6437       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
6438       Q = -1;
6439     }
6440 
6441     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6442     AAmts.push_back(DAG.getConstant(A, DL, SVT));
6443     KAmts.push_back(
6444         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6445     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6446     return true;
6447   };
6448 
6449   SDValue N = REMNode.getOperand(0);
6450   SDValue D = REMNode.getOperand(1);
6451 
6452   // Collect the values from each element.
6453   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
6454     return SDValue();
6455 
6456   // If this is a srem by a one, avoid the fold since it can be constant-folded.
6457   if (AllDivisorsAreOnes)
6458     return SDValue();
6459 
6460   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
6461   // since it can be best implemented as a bit test.
6462   if (AllDivisorsArePowerOfTwo)
6463     return SDValue();
6464 
6465   SDValue PVal, AVal, KVal, QVal;
6466   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6467     if (HadOneDivisor) {
6468       // Try to turn PAmts into a splat, since we don't care about the values
6469       // that are currently '0'. If we can't, just keep '0'`s.
6470       turnVectorIntoSplatVector(PAmts, isNullConstant);
6471       // Try to turn AAmts into a splat, since we don't care about the
6472       // values that are currently '-1'. If we can't, change them to '0'`s.
6473       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
6474                                 DAG.getConstant(0, DL, SVT));
6475       // Try to turn KAmts into a splat, since we don't care about the values
6476       // that are currently '-1'. If we can't, change them to '0'`s.
6477       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6478                                 DAG.getConstant(0, DL, ShSVT));
6479     }
6480 
6481     PVal = DAG.getBuildVector(VT, DL, PAmts);
6482     AVal = DAG.getBuildVector(VT, DL, AAmts);
6483     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6484     QVal = DAG.getBuildVector(VT, DL, QAmts);
6485   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6486     assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
6487            QAmts.size() == 1 &&
6488            "Expected matchUnaryPredicate to return one element for scalable "
6489            "vectors");
6490     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6491     AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
6492     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6493     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6494   } else {
6495     assert(isa<ConstantSDNode>(D) && "Expected a constant");
6496     PVal = PAmts[0];
6497     AVal = AAmts[0];
6498     KVal = KAmts[0];
6499     QVal = QAmts[0];
6500   }
6501 
6502   // (mul N, P)
6503   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6504   Created.push_back(Op0.getNode());
6505 
6506   if (NeedToApplyOffset) {
6507     // We need ADD to do this.
6508     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
6509       return SDValue();
6510 
6511     // (add (mul N, P), A)
6512     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
6513     Created.push_back(Op0.getNode());
6514   }
6515 
6516   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6517   // divisors as a performance improvement, since rotating by 0 is a no-op.
6518   if (HadEvenDivisor) {
6519     // We need ROTR to do this.
6520     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6521       return SDValue();
6522     // SREM: (rotr (add (mul N, P), A), K)
6523     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6524     Created.push_back(Op0.getNode());
6525   }
6526 
6527   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
6528   SDValue Fold =
6529       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6530                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6531 
6532   // If we didn't have lanes with INT_MIN divisor, then we're done.
6533   if (!HadIntMinDivisor)
6534     return Fold;
6535 
6536   // That fold is only valid for positive divisors. Which effectively means,
6537   // it is invalid for INT_MIN divisors. So if we have such a lane,
6538   // we must fix-up results for said lanes.
6539   assert(VT.isVector() && "Can/should only get here for vectors.");
6540 
6541   // NOTE: we avoid letting illegal types through even if we're before legalize
6542   // ops – legalization has a hard time producing good code for the code that
6543   // follows.
6544   if (!isOperationLegalOrCustom(ISD::SETEQ, VT) ||
6545       !isOperationLegalOrCustom(ISD::AND, VT) ||
6546       !isOperationLegalOrCustom(Cond, VT) ||
6547       !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT))
6548     return SDValue();
6549 
6550   Created.push_back(Fold.getNode());
6551 
6552   SDValue IntMin = DAG.getConstant(
6553       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
6554   SDValue IntMax = DAG.getConstant(
6555       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
6556   SDValue Zero =
6557       DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT);
6558 
6559   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
6560   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
6561   Created.push_back(DivisorIsIntMin.getNode());
6562 
6563   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
6564   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
6565   Created.push_back(Masked.getNode());
6566   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
6567   Created.push_back(MaskedIsZero.getNode());
6568 
6569   // To produce final result we need to blend 2 vectors: 'SetCC' and
6570   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
6571   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
6572   // constant-folded, select can get lowered to a shuffle with constant mask.
6573   SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin,
6574                                 MaskedIsZero, Fold);
6575 
6576   return Blended;
6577 }
6578 
6579 bool TargetLowering::
6580 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
6581   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
6582     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
6583                                 "be a constant integer");
6584     return true;
6585   }
6586 
6587   return false;
6588 }
6589 
6590 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
6591                                          const DenormalMode &Mode) const {
6592   SDLoc DL(Op);
6593   EVT VT = Op.getValueType();
6594   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6595   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6596   // Testing it with denormal inputs to avoid wrong estimate.
6597   if (Mode.Input == DenormalMode::IEEE) {
6598     // This is specifically a check for the handling of denormal inputs,
6599     // not the result.
6600 
6601     // Test = fabs(X) < SmallestNormal
6602     const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
6603     APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
6604     SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
6605     SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
6606     return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
6607   }
6608   // Test = X == 0.0
6609   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
6610 }
6611 
6612 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
6613                                              bool LegalOps, bool OptForSize,
6614                                              NegatibleCost &Cost,
6615                                              unsigned Depth) const {
6616   // fneg is removable even if it has multiple uses.
6617   if (Op.getOpcode() == ISD::FNEG) {
6618     Cost = NegatibleCost::Cheaper;
6619     return Op.getOperand(0);
6620   }
6621 
6622   // Don't recurse exponentially.
6623   if (Depth > SelectionDAG::MaxRecursionDepth)
6624     return SDValue();
6625 
6626   // Pre-increment recursion depth for use in recursive calls.
6627   ++Depth;
6628   const SDNodeFlags Flags = Op->getFlags();
6629   const TargetOptions &Options = DAG.getTarget().Options;
6630   EVT VT = Op.getValueType();
6631   unsigned Opcode = Op.getOpcode();
6632 
6633   // Don't allow anything with multiple uses unless we know it is free.
6634   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
6635     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
6636                         isFPExtFree(VT, Op.getOperand(0).getValueType());
6637     if (!IsFreeExtend)
6638       return SDValue();
6639   }
6640 
6641   auto RemoveDeadNode = [&](SDValue N) {
6642     if (N && N.getNode()->use_empty())
6643       DAG.RemoveDeadNode(N.getNode());
6644   };
6645 
6646   SDLoc DL(Op);
6647 
6648   // Because getNegatedExpression can delete nodes we need a handle to keep
6649   // temporary nodes alive in case the recursion manages to create an identical
6650   // node.
6651   std::list<HandleSDNode> Handles;
6652 
6653   switch (Opcode) {
6654   case ISD::ConstantFP: {
6655     // Don't invert constant FP values after legalization unless the target says
6656     // the negated constant is legal.
6657     bool IsOpLegal =
6658         isOperationLegal(ISD::ConstantFP, VT) ||
6659         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
6660                      OptForSize);
6661 
6662     if (LegalOps && !IsOpLegal)
6663       break;
6664 
6665     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
6666     V.changeSign();
6667     SDValue CFP = DAG.getConstantFP(V, DL, VT);
6668 
6669     // If we already have the use of the negated floating constant, it is free
6670     // to negate it even it has multiple uses.
6671     if (!Op.hasOneUse() && CFP.use_empty())
6672       break;
6673     Cost = NegatibleCost::Neutral;
6674     return CFP;
6675   }
6676   case ISD::BUILD_VECTOR: {
6677     // Only permit BUILD_VECTOR of constants.
6678     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
6679           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
6680         }))
6681       break;
6682 
6683     bool IsOpLegal =
6684         (isOperationLegal(ISD::ConstantFP, VT) &&
6685          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
6686         llvm::all_of(Op->op_values(), [&](SDValue N) {
6687           return N.isUndef() ||
6688                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
6689                               OptForSize);
6690         });
6691 
6692     if (LegalOps && !IsOpLegal)
6693       break;
6694 
6695     SmallVector<SDValue, 4> Ops;
6696     for (SDValue C : Op->op_values()) {
6697       if (C.isUndef()) {
6698         Ops.push_back(C);
6699         continue;
6700       }
6701       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
6702       V.changeSign();
6703       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
6704     }
6705     Cost = NegatibleCost::Neutral;
6706     return DAG.getBuildVector(VT, DL, Ops);
6707   }
6708   case ISD::FADD: {
6709     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6710       break;
6711 
6712     // After operation legalization, it might not be legal to create new FSUBs.
6713     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
6714       break;
6715     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6716 
6717     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
6718     NegatibleCost CostX = NegatibleCost::Expensive;
6719     SDValue NegX =
6720         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6721     // Prevent this node from being deleted by the next call.
6722     if (NegX)
6723       Handles.emplace_back(NegX);
6724 
6725     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
6726     NegatibleCost CostY = NegatibleCost::Expensive;
6727     SDValue NegY =
6728         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6729 
6730     // We're done with the handles.
6731     Handles.clear();
6732 
6733     // Negate the X if its cost is less or equal than Y.
6734     if (NegX && (CostX <= CostY)) {
6735       Cost = CostX;
6736       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
6737       if (NegY != N)
6738         RemoveDeadNode(NegY);
6739       return N;
6740     }
6741 
6742     // Negate the Y if it is not expensive.
6743     if (NegY) {
6744       Cost = CostY;
6745       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
6746       if (NegX != N)
6747         RemoveDeadNode(NegX);
6748       return N;
6749     }
6750     break;
6751   }
6752   case ISD::FSUB: {
6753     // We can't turn -(A-B) into B-A when we honor signed zeros.
6754     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6755       break;
6756 
6757     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6758     // fold (fneg (fsub 0, Y)) -> Y
6759     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
6760       if (C->isZero()) {
6761         Cost = NegatibleCost::Cheaper;
6762         return Y;
6763       }
6764 
6765     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
6766     Cost = NegatibleCost::Neutral;
6767     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
6768   }
6769   case ISD::FMUL:
6770   case ISD::FDIV: {
6771     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6772 
6773     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
6774     NegatibleCost CostX = NegatibleCost::Expensive;
6775     SDValue NegX =
6776         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6777     // Prevent this node from being deleted by the next call.
6778     if (NegX)
6779       Handles.emplace_back(NegX);
6780 
6781     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
6782     NegatibleCost CostY = NegatibleCost::Expensive;
6783     SDValue NegY =
6784         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6785 
6786     // We're done with the handles.
6787     Handles.clear();
6788 
6789     // Negate the X if its cost is less or equal than Y.
6790     if (NegX && (CostX <= CostY)) {
6791       Cost = CostX;
6792       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
6793       if (NegY != N)
6794         RemoveDeadNode(NegY);
6795       return N;
6796     }
6797 
6798     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
6799     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
6800       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
6801         break;
6802 
6803     // Negate the Y if it is not expensive.
6804     if (NegY) {
6805       Cost = CostY;
6806       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
6807       if (NegX != N)
6808         RemoveDeadNode(NegX);
6809       return N;
6810     }
6811     break;
6812   }
6813   case ISD::FMA:
6814   case ISD::FMAD: {
6815     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6816       break;
6817 
6818     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
6819     NegatibleCost CostZ = NegatibleCost::Expensive;
6820     SDValue NegZ =
6821         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
6822     // Give up if fail to negate the Z.
6823     if (!NegZ)
6824       break;
6825 
6826     // Prevent this node from being deleted by the next two calls.
6827     Handles.emplace_back(NegZ);
6828 
6829     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
6830     NegatibleCost CostX = NegatibleCost::Expensive;
6831     SDValue NegX =
6832         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6833     // Prevent this node from being deleted by the next call.
6834     if (NegX)
6835       Handles.emplace_back(NegX);
6836 
6837     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
6838     NegatibleCost CostY = NegatibleCost::Expensive;
6839     SDValue NegY =
6840         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6841 
6842     // We're done with the handles.
6843     Handles.clear();
6844 
6845     // Negate the X if its cost is less or equal than Y.
6846     if (NegX && (CostX <= CostY)) {
6847       Cost = std::min(CostX, CostZ);
6848       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
6849       if (NegY != N)
6850         RemoveDeadNode(NegY);
6851       return N;
6852     }
6853 
6854     // Negate the Y if it is not expensive.
6855     if (NegY) {
6856       Cost = std::min(CostY, CostZ);
6857       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
6858       if (NegX != N)
6859         RemoveDeadNode(NegX);
6860       return N;
6861     }
6862     break;
6863   }
6864 
6865   case ISD::FP_EXTEND:
6866   case ISD::FSIN:
6867     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6868                                             OptForSize, Cost, Depth))
6869       return DAG.getNode(Opcode, DL, VT, NegV);
6870     break;
6871   case ISD::FP_ROUND:
6872     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6873                                             OptForSize, Cost, Depth))
6874       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
6875     break;
6876   }
6877 
6878   return SDValue();
6879 }
6880 
6881 //===----------------------------------------------------------------------===//
6882 // Legalization Utilities
6883 //===----------------------------------------------------------------------===//
6884 
6885 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
6886                                     SDValue LHS, SDValue RHS,
6887                                     SmallVectorImpl<SDValue> &Result,
6888                                     EVT HiLoVT, SelectionDAG &DAG,
6889                                     MulExpansionKind Kind, SDValue LL,
6890                                     SDValue LH, SDValue RL, SDValue RH) const {
6891   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
6892          Opcode == ISD::SMUL_LOHI);
6893 
6894   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
6895                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
6896   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
6897                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
6898   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6899                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
6900   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6901                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
6902 
6903   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
6904     return false;
6905 
6906   unsigned OuterBitSize = VT.getScalarSizeInBits();
6907   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
6908 
6909   // LL, LH, RL, and RH must be either all NULL or all set to a value.
6910   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
6911          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
6912 
6913   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
6914   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
6915                           bool Signed) -> bool {
6916     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
6917       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
6918       Hi = SDValue(Lo.getNode(), 1);
6919       return true;
6920     }
6921     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
6922       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
6923       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
6924       return true;
6925     }
6926     return false;
6927   };
6928 
6929   SDValue Lo, Hi;
6930 
6931   if (!LL.getNode() && !RL.getNode() &&
6932       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6933     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
6934     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
6935   }
6936 
6937   if (!LL.getNode())
6938     return false;
6939 
6940   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
6941   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
6942       DAG.MaskedValueIsZero(RHS, HighMask)) {
6943     // The inputs are both zero-extended.
6944     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
6945       Result.push_back(Lo);
6946       Result.push_back(Hi);
6947       if (Opcode != ISD::MUL) {
6948         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6949         Result.push_back(Zero);
6950         Result.push_back(Zero);
6951       }
6952       return true;
6953     }
6954   }
6955 
6956   if (!VT.isVector() && Opcode == ISD::MUL &&
6957       DAG.ComputeNumSignBits(LHS) > InnerBitSize &&
6958       DAG.ComputeNumSignBits(RHS) > InnerBitSize) {
6959     // The input values are both sign-extended.
6960     // TODO non-MUL case?
6961     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
6962       Result.push_back(Lo);
6963       Result.push_back(Hi);
6964       return true;
6965     }
6966   }
6967 
6968   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
6969   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
6970   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
6971 
6972   if (!LH.getNode() && !RH.getNode() &&
6973       isOperationLegalOrCustom(ISD::SRL, VT) &&
6974       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6975     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
6976     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
6977     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
6978     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
6979   }
6980 
6981   if (!LH.getNode())
6982     return false;
6983 
6984   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
6985     return false;
6986 
6987   Result.push_back(Lo);
6988 
6989   if (Opcode == ISD::MUL) {
6990     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
6991     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
6992     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
6993     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
6994     Result.push_back(Hi);
6995     return true;
6996   }
6997 
6998   // Compute the full width result.
6999   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
7000     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
7001     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
7002     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
7003     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
7004   };
7005 
7006   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
7007   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
7008     return false;
7009 
7010   // This is effectively the add part of a multiply-add of half-sized operands,
7011   // so it cannot overflow.
7012   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
7013 
7014   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
7015     return false;
7016 
7017   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
7018   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7019 
7020   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
7021                   isOperationLegalOrCustom(ISD::ADDE, VT));
7022   if (UseGlue)
7023     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
7024                        Merge(Lo, Hi));
7025   else
7026     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
7027                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
7028 
7029   SDValue Carry = Next.getValue(1);
7030   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7031   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
7032 
7033   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
7034     return false;
7035 
7036   if (UseGlue)
7037     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
7038                      Carry);
7039   else
7040     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
7041                      Zero, Carry);
7042 
7043   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
7044 
7045   if (Opcode == ISD::SMUL_LOHI) {
7046     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
7047                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
7048     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
7049 
7050     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
7051                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
7052     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
7053   }
7054 
7055   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7056   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
7057   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7058   return true;
7059 }
7060 
7061 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
7062                                SelectionDAG &DAG, MulExpansionKind Kind,
7063                                SDValue LL, SDValue LH, SDValue RL,
7064                                SDValue RH) const {
7065   SmallVector<SDValue, 2> Result;
7066   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
7067                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
7068                            DAG, Kind, LL, LH, RL, RH);
7069   if (Ok) {
7070     assert(Result.size() == 2);
7071     Lo = Result[0];
7072     Hi = Result[1];
7073   }
7074   return Ok;
7075 }
7076 
7077 // Check that (every element of) Z is undef or not an exact multiple of BW.
7078 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
7079   return ISD::matchUnaryPredicate(
7080       Z,
7081       [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
7082       true);
7083 }
7084 
7085 SDValue TargetLowering::expandFunnelShift(SDNode *Node,
7086                                           SelectionDAG &DAG) const {
7087   EVT VT = Node->getValueType(0);
7088 
7089   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7090                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7091                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7092                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7093     return SDValue();
7094 
7095   SDValue X = Node->getOperand(0);
7096   SDValue Y = Node->getOperand(1);
7097   SDValue Z = Node->getOperand(2);
7098 
7099   unsigned BW = VT.getScalarSizeInBits();
7100   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
7101   SDLoc DL(SDValue(Node, 0));
7102 
7103   EVT ShVT = Z.getValueType();
7104 
7105   // If a funnel shift in the other direction is more supported, use it.
7106   unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
7107   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7108       isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
7109     if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7110       // fshl X, Y, Z -> fshr X, Y, -Z
7111       // fshr X, Y, Z -> fshl X, Y, -Z
7112       SDValue Zero = DAG.getConstant(0, DL, ShVT);
7113       Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z);
7114     } else {
7115       // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
7116       // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
7117       SDValue One = DAG.getConstant(1, DL, ShVT);
7118       if (IsFSHL) {
7119         Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7120         X = DAG.getNode(ISD::SRL, DL, VT, X, One);
7121       } else {
7122         X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7123         Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
7124       }
7125       Z = DAG.getNOT(DL, Z, ShVT);
7126     }
7127     return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
7128   }
7129 
7130   SDValue ShX, ShY;
7131   SDValue ShAmt, InvShAmt;
7132   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7133     // fshl: X << C | Y >> (BW - C)
7134     // fshr: X << (BW - C) | Y >> C
7135     // where C = Z % BW is not zero
7136     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7137     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7138     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
7139     ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
7140     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
7141   } else {
7142     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
7143     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
7144     SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
7145     if (isPowerOf2_32(BW)) {
7146       // Z % BW -> Z & (BW - 1)
7147       ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
7148       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
7149       InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
7150     } else {
7151       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7152       ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7153       InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
7154     }
7155 
7156     SDValue One = DAG.getConstant(1, DL, ShVT);
7157     if (IsFSHL) {
7158       ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
7159       SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
7160       ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
7161     } else {
7162       SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
7163       ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
7164       ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
7165     }
7166   }
7167   return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
7168 }
7169 
7170 // TODO: Merge with expandFunnelShift.
7171 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps,
7172                                   SelectionDAG &DAG) const {
7173   EVT VT = Node->getValueType(0);
7174   unsigned EltSizeInBits = VT.getScalarSizeInBits();
7175   bool IsLeft = Node->getOpcode() == ISD::ROTL;
7176   SDValue Op0 = Node->getOperand(0);
7177   SDValue Op1 = Node->getOperand(1);
7178   SDLoc DL(SDValue(Node, 0));
7179 
7180   EVT ShVT = Op1.getValueType();
7181   SDValue Zero = DAG.getConstant(0, DL, ShVT);
7182 
7183   // If a rotate in the other direction is more supported, use it.
7184   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
7185   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7186       isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
7187     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7188     return DAG.getNode(RevRot, DL, VT, Op0, Sub);
7189   }
7190 
7191   if (!AllowVectorOps && VT.isVector() &&
7192       (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7193        !isOperationLegalOrCustom(ISD::SRL, VT) ||
7194        !isOperationLegalOrCustom(ISD::SUB, VT) ||
7195        !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
7196        !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
7197     return SDValue();
7198 
7199   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
7200   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
7201   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
7202   SDValue ShVal;
7203   SDValue HsVal;
7204   if (isPowerOf2_32(EltSizeInBits)) {
7205     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
7206     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
7207     SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7208     SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
7209     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7210     SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
7211     HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
7212   } else {
7213     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
7214     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
7215     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
7216     SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
7217     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7218     SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
7219     SDValue One = DAG.getConstant(1, DL, ShVT);
7220     HsVal =
7221         DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
7222   }
7223   return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
7224 }
7225 
7226 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi,
7227                                       SelectionDAG &DAG) const {
7228   assert(Node->getNumOperands() == 3 && "Not a double-shift!");
7229   EVT VT = Node->getValueType(0);
7230   unsigned VTBits = VT.getScalarSizeInBits();
7231   assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
7232 
7233   bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
7234   bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
7235   SDValue ShOpLo = Node->getOperand(0);
7236   SDValue ShOpHi = Node->getOperand(1);
7237   SDValue ShAmt = Node->getOperand(2);
7238   EVT ShAmtVT = ShAmt.getValueType();
7239   EVT ShAmtCCVT =
7240       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
7241   SDLoc dl(Node);
7242 
7243   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
7244   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
7245   // away during isel.
7246   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7247                                   DAG.getConstant(VTBits - 1, dl, ShAmtVT));
7248   SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7249                                      DAG.getConstant(VTBits - 1, dl, ShAmtVT))
7250                        : DAG.getConstant(0, dl, VT);
7251 
7252   SDValue Tmp2, Tmp3;
7253   if (IsSHL) {
7254     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
7255     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
7256   } else {
7257     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
7258     Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
7259   }
7260 
7261   // If the shift amount is larger or equal than the width of a part we don't
7262   // use the result from the FSHL/FSHR. Insert a test and select the appropriate
7263   // values for large shift amounts.
7264   SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7265                                 DAG.getConstant(VTBits, dl, ShAmtVT));
7266   SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
7267                               DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
7268 
7269   if (IsSHL) {
7270     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7271     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7272   } else {
7273     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7274     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7275   }
7276 }
7277 
7278 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
7279                                       SelectionDAG &DAG) const {
7280   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7281   SDValue Src = Node->getOperand(OpNo);
7282   EVT SrcVT = Src.getValueType();
7283   EVT DstVT = Node->getValueType(0);
7284   SDLoc dl(SDValue(Node, 0));
7285 
7286   // FIXME: Only f32 to i64 conversions are supported.
7287   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
7288     return false;
7289 
7290   if (Node->isStrictFPOpcode())
7291     // When a NaN is converted to an integer a trap is allowed. We can't
7292     // use this expansion here because it would eliminate that trap. Other
7293     // traps are also allowed and cannot be eliminated. See
7294     // IEEE 754-2008 sec 5.8.
7295     return false;
7296 
7297   // Expand f32 -> i64 conversion
7298   // This algorithm comes from compiler-rt's implementation of fixsfdi:
7299   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
7300   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
7301   EVT IntVT = SrcVT.changeTypeToInteger();
7302   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
7303 
7304   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
7305   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
7306   SDValue Bias = DAG.getConstant(127, dl, IntVT);
7307   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
7308   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
7309   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
7310 
7311   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
7312 
7313   SDValue ExponentBits = DAG.getNode(
7314       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
7315       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
7316   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
7317 
7318   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
7319                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
7320                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
7321   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
7322 
7323   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
7324                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
7325                           DAG.getConstant(0x00800000, dl, IntVT));
7326 
7327   R = DAG.getZExtOrTrunc(R, dl, DstVT);
7328 
7329   R = DAG.getSelectCC(
7330       dl, Exponent, ExponentLoBit,
7331       DAG.getNode(ISD::SHL, dl, DstVT, R,
7332                   DAG.getZExtOrTrunc(
7333                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
7334                       dl, IntShVT)),
7335       DAG.getNode(ISD::SRL, dl, DstVT, R,
7336                   DAG.getZExtOrTrunc(
7337                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
7338                       dl, IntShVT)),
7339       ISD::SETGT);
7340 
7341   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
7342                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
7343 
7344   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
7345                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
7346   return true;
7347 }
7348 
7349 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
7350                                       SDValue &Chain,
7351                                       SelectionDAG &DAG) const {
7352   SDLoc dl(SDValue(Node, 0));
7353   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7354   SDValue Src = Node->getOperand(OpNo);
7355 
7356   EVT SrcVT = Src.getValueType();
7357   EVT DstVT = Node->getValueType(0);
7358   EVT SetCCVT =
7359       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7360   EVT DstSetCCVT =
7361       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
7362 
7363   // Only expand vector types if we have the appropriate vector bit operations.
7364   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
7365                                                    ISD::FP_TO_SINT;
7366   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
7367                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
7368     return false;
7369 
7370   // If the maximum float value is smaller then the signed integer range,
7371   // the destination signmask can't be represented by the float, so we can
7372   // just use FP_TO_SINT directly.
7373   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
7374   APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
7375   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
7376   if (APFloat::opOverflow &
7377       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
7378     if (Node->isStrictFPOpcode()) {
7379       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7380                            { Node->getOperand(0), Src });
7381       Chain = Result.getValue(1);
7382     } else
7383       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7384     return true;
7385   }
7386 
7387   // Don't expand it if there isn't cheap fsub instruction.
7388   if (!isOperationLegalOrCustom(
7389           Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
7390     return false;
7391 
7392   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
7393   SDValue Sel;
7394 
7395   if (Node->isStrictFPOpcode()) {
7396     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
7397                        Node->getOperand(0), /*IsSignaling*/ true);
7398     Chain = Sel.getValue(1);
7399   } else {
7400     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
7401   }
7402 
7403   bool Strict = Node->isStrictFPOpcode() ||
7404                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
7405 
7406   if (Strict) {
7407     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
7408     // signmask then offset (the result of which should be fully representable).
7409     // Sel = Src < 0x8000000000000000
7410     // FltOfs = select Sel, 0, 0x8000000000000000
7411     // IntOfs = select Sel, 0, 0x8000000000000000
7412     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
7413 
7414     // TODO: Should any fast-math-flags be set for the FSUB?
7415     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
7416                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
7417     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7418     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
7419                                    DAG.getConstant(0, dl, DstVT),
7420                                    DAG.getConstant(SignMask, dl, DstVT));
7421     SDValue SInt;
7422     if (Node->isStrictFPOpcode()) {
7423       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
7424                                 { Chain, Src, FltOfs });
7425       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7426                          { Val.getValue(1), Val });
7427       Chain = SInt.getValue(1);
7428     } else {
7429       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
7430       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
7431     }
7432     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
7433   } else {
7434     // Expand based on maximum range of FP_TO_SINT:
7435     // True = fp_to_sint(Src)
7436     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
7437     // Result = select (Src < 0x8000000000000000), True, False
7438 
7439     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7440     // TODO: Should any fast-math-flags be set for the FSUB?
7441     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
7442                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
7443     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
7444                         DAG.getConstant(SignMask, dl, DstVT));
7445     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7446     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
7447   }
7448   return true;
7449 }
7450 
7451 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
7452                                       SDValue &Chain,
7453                                       SelectionDAG &DAG) const {
7454   // This transform is not correct for converting 0 when rounding mode is set
7455   // to round toward negative infinity which will produce -0.0. So disable under
7456   // strictfp.
7457   if (Node->isStrictFPOpcode())
7458     return false;
7459 
7460   SDValue Src = Node->getOperand(0);
7461   EVT SrcVT = Src.getValueType();
7462   EVT DstVT = Node->getValueType(0);
7463 
7464   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
7465     return false;
7466 
7467   // Only expand vector types if we have the appropriate vector bit operations.
7468   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
7469                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
7470                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
7471                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
7472                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
7473     return false;
7474 
7475   SDLoc dl(SDValue(Node, 0));
7476   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
7477 
7478   // Implementation of unsigned i64 to f64 following the algorithm in
7479   // __floatundidf in compiler_rt.  This implementation performs rounding
7480   // correctly in all rounding modes with the exception of converting 0
7481   // when rounding toward negative infinity. In that case the fsub will produce
7482   // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect.
7483   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
7484   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
7485       BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
7486   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
7487   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
7488   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
7489 
7490   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
7491   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
7492   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
7493   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
7494   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
7495   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
7496   SDValue HiSub =
7497       DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
7498   Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
7499   return true;
7500 }
7501 
7502 SDValue
7503 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node,
7504                                                SelectionDAG &DAG) const {
7505   unsigned Opcode = Node->getOpcode();
7506   assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
7507           Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
7508          "Wrong opcode");
7509 
7510   if (Node->getFlags().hasNoNaNs()) {
7511     ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
7512     SDValue Op1 = Node->getOperand(0);
7513     SDValue Op2 = Node->getOperand(1);
7514     SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred);
7515     // Copy FMF flags, but always set the no-signed-zeros flag
7516     // as this is implied by the FMINNUM/FMAXNUM semantics.
7517     SDNodeFlags Flags = Node->getFlags();
7518     Flags.setNoSignedZeros(true);
7519     SelCC->setFlags(Flags);
7520     return SelCC;
7521   }
7522 
7523   return SDValue();
7524 }
7525 
7526 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
7527                                               SelectionDAG &DAG) const {
7528   SDLoc dl(Node);
7529   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
7530     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
7531   EVT VT = Node->getValueType(0);
7532 
7533   if (VT.isScalableVector())
7534     report_fatal_error(
7535         "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
7536 
7537   if (isOperationLegalOrCustom(NewOp, VT)) {
7538     SDValue Quiet0 = Node->getOperand(0);
7539     SDValue Quiet1 = Node->getOperand(1);
7540 
7541     if (!Node->getFlags().hasNoNaNs()) {
7542       // Insert canonicalizes if it's possible we need to quiet to get correct
7543       // sNaN behavior.
7544       if (!DAG.isKnownNeverSNaN(Quiet0)) {
7545         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
7546                              Node->getFlags());
7547       }
7548       if (!DAG.isKnownNeverSNaN(Quiet1)) {
7549         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
7550                              Node->getFlags());
7551       }
7552     }
7553 
7554     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
7555   }
7556 
7557   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
7558   // instead if there are no NaNs.
7559   if (Node->getFlags().hasNoNaNs()) {
7560     unsigned IEEE2018Op =
7561         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
7562     if (isOperationLegalOrCustom(IEEE2018Op, VT)) {
7563       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
7564                          Node->getOperand(1), Node->getFlags());
7565     }
7566   }
7567 
7568   if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG))
7569     return SelCC;
7570 
7571   return SDValue();
7572 }
7573 
7574 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op,
7575                                          unsigned Test, SDNodeFlags Flags,
7576                                          const SDLoc &DL,
7577                                          SelectionDAG &DAG) const {
7578   EVT OperandVT = Op.getValueType();
7579   assert(OperandVT.isFloatingPoint());
7580 
7581   // Degenerated cases.
7582   if (Test == 0)
7583     return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
7584   if ((Test & fcAllFlags) == fcAllFlags)
7585     return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
7586 
7587   // PPC double double is a pair of doubles, of which the higher part determines
7588   // the value class.
7589   if (OperandVT == MVT::ppcf128) {
7590     Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
7591                      DAG.getConstant(1, DL, MVT::i32));
7592     OperandVT = MVT::f64;
7593   }
7594 
7595   // Some checks may be represented as inversion of simpler check, for example
7596   // "inf|normal|subnormal|zero" => !"nan".
7597   bool IsInverted = false;
7598   if (unsigned InvertedCheck = getInvertedFPClassTest(Test)) {
7599     IsInverted = true;
7600     Test = InvertedCheck;
7601   }
7602 
7603   // Floating-point type properties.
7604   EVT ScalarFloatVT = OperandVT.getScalarType();
7605   const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
7606   const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
7607   bool IsF80 = (ScalarFloatVT == MVT::f80);
7608 
7609   // Some checks can be implemented using float comparisons, if floating point
7610   // exceptions are ignored.
7611   if (Flags.hasNoFPExcept() &&
7612       isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) {
7613     if (Test == fcZero)
7614       return DAG.getSetCC(DL, ResultVT, Op,
7615                           DAG.getConstantFP(0.0, DL, OperandVT),
7616                           IsInverted ? ISD::SETUNE : ISD::SETOEQ);
7617     if (Test == fcNan)
7618       return DAG.getSetCC(DL, ResultVT, Op, Op,
7619                           IsInverted ? ISD::SETO : ISD::SETUO);
7620   }
7621 
7622   // In the general case use integer operations.
7623   unsigned BitSize = OperandVT.getScalarSizeInBits();
7624   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize);
7625   if (OperandVT.isVector())
7626     IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT,
7627                              OperandVT.getVectorElementCount());
7628   SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
7629 
7630   // Various masks.
7631   APInt SignBit = APInt::getSignMask(BitSize);
7632   APInt ValueMask = APInt::getSignedMaxValue(BitSize);     // All bits but sign.
7633   APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
7634   const unsigned ExplicitIntBitInF80 = 63;
7635   APInt ExpMask = Inf;
7636   if (IsF80)
7637     ExpMask.clearBit(ExplicitIntBitInF80);
7638   APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
7639   APInt QNaNBitMask =
7640       APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
7641   APInt InvertionMask = APInt::getAllOnesValue(ResultVT.getScalarSizeInBits());
7642 
7643   SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
7644   SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
7645   SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
7646   SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
7647   SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
7648   SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT);
7649 
7650   SDValue Res;
7651   const auto appendResult = [&](SDValue PartialRes) {
7652     if (PartialRes) {
7653       if (Res)
7654         Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
7655       else
7656         Res = PartialRes;
7657     }
7658   };
7659 
7660   SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
7661   const auto getIntBitIsSet = [&]() -> SDValue {
7662     if (!IntBitIsSetV) {
7663       APInt IntBitMask(BitSize, 0);
7664       IntBitMask.setBit(ExplicitIntBitInF80);
7665       SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
7666       SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
7667       IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
7668     }
7669     return IntBitIsSetV;
7670   };
7671 
7672   // Split the value into sign bit and absolute value.
7673   SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
7674   SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
7675                                DAG.getConstant(0.0, DL, IntVT), ISD::SETLT);
7676 
7677   // Tests that involve more than one class should be processed first.
7678   SDValue PartialRes;
7679 
7680   if (IsF80)
7681     ; // Detect finite numbers of f80 by checking individual classes because
7682       // they have different settings of the explicit integer bit.
7683   else if ((Test & fcFinite) == fcFinite) {
7684     // finite(V) ==> abs(V) < exp_mask
7685     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
7686     Test &= ~fcFinite;
7687   } else if ((Test & fcFinite) == fcPosFinite) {
7688     // finite(V) && V > 0 ==> V < exp_mask
7689     PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
7690     Test &= ~fcPosFinite;
7691   } else if ((Test & fcFinite) == fcNegFinite) {
7692     // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
7693     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
7694     PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
7695     Test &= ~fcNegFinite;
7696   }
7697   appendResult(PartialRes);
7698 
7699   // Check for individual classes.
7700 
7701   if (unsigned PartialCheck = Test & fcZero) {
7702     if (PartialCheck == fcPosZero)
7703       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
7704     else if (PartialCheck == fcZero)
7705       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
7706     else // ISD::fcNegZero
7707       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
7708     appendResult(PartialRes);
7709   }
7710 
7711   if (unsigned PartialCheck = Test & fcInf) {
7712     if (PartialCheck == fcPosInf)
7713       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
7714     else if (PartialCheck == fcInf)
7715       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
7716     else { // ISD::fcNegInf
7717       APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
7718       SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
7719       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
7720     }
7721     appendResult(PartialRes);
7722   }
7723 
7724   if (unsigned PartialCheck = Test & fcNan) {
7725     APInt InfWithQnanBit = Inf | QNaNBitMask;
7726     SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
7727     if (PartialCheck == fcNan) {
7728       // isnan(V) ==> abs(V) > int(inf)
7729       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
7730       if (IsF80) {
7731         // Recognize unsupported values as NaNs for compatibility with glibc.
7732         // In them (exp(V)==0) == int_bit.
7733         SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
7734         SDValue ExpIsZero =
7735             DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
7736         SDValue IsPseudo =
7737             DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
7738         PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
7739       }
7740     } else if (PartialCheck == fcQNan) {
7741       // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
7742       PartialRes =
7743           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
7744     } else { // ISD::fcSNan
7745       // issignaling(V) ==> abs(V) > unsigned(Inf) &&
7746       //                    abs(V) < (unsigned(Inf) | quiet_bit)
7747       SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
7748       SDValue IsNotQnan =
7749           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
7750       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
7751     }
7752     appendResult(PartialRes);
7753   }
7754 
7755   if (unsigned PartialCheck = Test & fcSubnormal) {
7756     // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
7757     // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
7758     SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
7759     SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
7760     SDValue VMinusOneV =
7761         DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
7762     PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
7763     if (PartialCheck == fcNegSubnormal)
7764       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
7765     appendResult(PartialRes);
7766   }
7767 
7768   if (unsigned PartialCheck = Test & fcNormal) {
7769     // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
7770     APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
7771     SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
7772     SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
7773     APInt ExpLimit = ExpMask - ExpLSB;
7774     SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
7775     PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
7776     if (PartialCheck == fcNegNormal)
7777       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
7778     else if (PartialCheck == fcPosNormal) {
7779       SDValue PosSignV =
7780           DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask);
7781       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
7782     }
7783     if (IsF80)
7784       PartialRes =
7785           DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
7786     appendResult(PartialRes);
7787   }
7788 
7789   if (!Res)
7790     return DAG.getConstant(IsInverted, DL, ResultVT);
7791   if (IsInverted)
7792     Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask);
7793   return Res;
7794 }
7795 
7796 // Only expand vector types if we have the appropriate vector bit operations.
7797 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
7798   assert(VT.isVector() && "Expected vector type");
7799   unsigned Len = VT.getScalarSizeInBits();
7800   return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
7801          TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
7802          TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
7803          (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
7804          TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
7805 }
7806 
7807 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const {
7808   SDLoc dl(Node);
7809   EVT VT = Node->getValueType(0);
7810   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7811   SDValue Op = Node->getOperand(0);
7812   unsigned Len = VT.getScalarSizeInBits();
7813   assert(VT.isInteger() && "CTPOP not implemented for this type.");
7814 
7815   // TODO: Add support for irregular type lengths.
7816   if (!(Len <= 128 && Len % 8 == 0))
7817     return SDValue();
7818 
7819   // Only expand vector types if we have the appropriate vector bit operations.
7820   if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
7821     return SDValue();
7822 
7823   // This is the "best" algorithm from
7824   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
7825   SDValue Mask55 =
7826       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
7827   SDValue Mask33 =
7828       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
7829   SDValue Mask0F =
7830       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
7831 
7832   // v = v - ((v >> 1) & 0x55555555...)
7833   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
7834                    DAG.getNode(ISD::AND, dl, VT,
7835                                DAG.getNode(ISD::SRL, dl, VT, Op,
7836                                            DAG.getConstant(1, dl, ShVT)),
7837                                Mask55));
7838   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
7839   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
7840                    DAG.getNode(ISD::AND, dl, VT,
7841                                DAG.getNode(ISD::SRL, dl, VT, Op,
7842                                            DAG.getConstant(2, dl, ShVT)),
7843                                Mask33));
7844   // v = (v + (v >> 4)) & 0x0F0F0F0F...
7845   Op = DAG.getNode(ISD::AND, dl, VT,
7846                    DAG.getNode(ISD::ADD, dl, VT, Op,
7847                                DAG.getNode(ISD::SRL, dl, VT, Op,
7848                                            DAG.getConstant(4, dl, ShVT))),
7849                    Mask0F);
7850 
7851   if (Len <= 8)
7852     return Op;
7853 
7854   // Avoid the multiply if we only have 2 bytes to add.
7855   // TODO: Only doing this for scalars because vectors weren't as obviously
7856   // improved.
7857   if (Len == 16 && !VT.isVector()) {
7858     // v = (v + (v >> 8)) & 0x00FF;
7859     return DAG.getNode(ISD::AND, dl, VT,
7860                      DAG.getNode(ISD::ADD, dl, VT, Op,
7861                                  DAG.getNode(ISD::SRL, dl, VT, Op,
7862                                              DAG.getConstant(8, dl, ShVT))),
7863                      DAG.getConstant(0xFF, dl, VT));
7864   }
7865 
7866   // v = (v * 0x01010101...) >> (Len - 8)
7867   SDValue Mask01 =
7868       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
7869   return DAG.getNode(ISD::SRL, dl, VT,
7870                      DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
7871                      DAG.getConstant(Len - 8, dl, ShVT));
7872 }
7873 
7874 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const {
7875   SDLoc dl(Node);
7876   EVT VT = Node->getValueType(0);
7877   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7878   SDValue Op = Node->getOperand(0);
7879   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7880 
7881   // If the non-ZERO_UNDEF version is supported we can use that instead.
7882   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
7883       isOperationLegalOrCustom(ISD::CTLZ, VT))
7884     return DAG.getNode(ISD::CTLZ, dl, VT, Op);
7885 
7886   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7887   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
7888     EVT SetCCVT =
7889         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7890     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
7891     SDValue Zero = DAG.getConstant(0, dl, VT);
7892     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7893     return DAG.getSelect(dl, VT, SrcIsZero,
7894                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
7895   }
7896 
7897   // Only expand vector types if we have the appropriate vector bit operations.
7898   // This includes the operations needed to expand CTPOP if it isn't supported.
7899   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7900                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7901                          !canExpandVectorCTPOP(*this, VT)) ||
7902                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7903                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7904     return SDValue();
7905 
7906   // for now, we do this:
7907   // x = x | (x >> 1);
7908   // x = x | (x >> 2);
7909   // ...
7910   // x = x | (x >>16);
7911   // x = x | (x >>32); // for 64-bit input
7912   // return popcount(~x);
7913   //
7914   // Ref: "Hacker's Delight" by Henry Warren
7915   for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
7916     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
7917     Op = DAG.getNode(ISD::OR, dl, VT, Op,
7918                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
7919   }
7920   Op = DAG.getNOT(dl, Op, VT);
7921   return DAG.getNode(ISD::CTPOP, dl, VT, Op);
7922 }
7923 
7924 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const {
7925   SDLoc dl(Node);
7926   EVT VT = Node->getValueType(0);
7927   SDValue Op = Node->getOperand(0);
7928   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7929 
7930   // If the non-ZERO_UNDEF version is supported we can use that instead.
7931   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
7932       isOperationLegalOrCustom(ISD::CTTZ, VT))
7933     return DAG.getNode(ISD::CTTZ, dl, VT, Op);
7934 
7935   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7936   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
7937     EVT SetCCVT =
7938         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7939     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
7940     SDValue Zero = DAG.getConstant(0, dl, VT);
7941     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7942     return DAG.getSelect(dl, VT, SrcIsZero,
7943                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
7944   }
7945 
7946   // Only expand vector types if we have the appropriate vector bit operations.
7947   // This includes the operations needed to expand CTPOP if it isn't supported.
7948   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7949                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7950                          !isOperationLegalOrCustom(ISD::CTLZ, VT) &&
7951                          !canExpandVectorCTPOP(*this, VT)) ||
7952                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7953                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
7954                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7955     return SDValue();
7956 
7957   // for now, we use: { return popcount(~x & (x - 1)); }
7958   // unless the target has ctlz but not ctpop, in which case we use:
7959   // { return 32 - nlz(~x & (x-1)); }
7960   // Ref: "Hacker's Delight" by Henry Warren
7961   SDValue Tmp = DAG.getNode(
7962       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
7963       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
7964 
7965   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
7966   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
7967     return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
7968                        DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
7969   }
7970 
7971   return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
7972 }
7973 
7974 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG,
7975                                   bool IsNegative) const {
7976   SDLoc dl(N);
7977   EVT VT = N->getValueType(0);
7978   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7979   SDValue Op = N->getOperand(0);
7980 
7981   // abs(x) -> smax(x,sub(0,x))
7982   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7983       isOperationLegal(ISD::SMAX, VT)) {
7984     SDValue Zero = DAG.getConstant(0, dl, VT);
7985     return DAG.getNode(ISD::SMAX, dl, VT, Op,
7986                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7987   }
7988 
7989   // abs(x) -> umin(x,sub(0,x))
7990   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7991       isOperationLegal(ISD::UMIN, VT)) {
7992     SDValue Zero = DAG.getConstant(0, dl, VT);
7993     Op = DAG.getFreeze(Op);
7994     return DAG.getNode(ISD::UMIN, dl, VT, Op,
7995                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7996   }
7997 
7998   // 0 - abs(x) -> smin(x, sub(0,x))
7999   if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
8000       isOperationLegal(ISD::SMIN, VT)) {
8001     Op = DAG.getFreeze(Op);
8002     SDValue Zero = DAG.getConstant(0, dl, VT);
8003     return DAG.getNode(ISD::SMIN, dl, VT, Op,
8004                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
8005   }
8006 
8007   // Only expand vector types if we have the appropriate vector operations.
8008   if (VT.isVector() &&
8009       (!isOperationLegalOrCustom(ISD::SRA, VT) ||
8010        (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
8011        (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
8012        !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
8013     return SDValue();
8014 
8015   Op = DAG.getFreeze(Op);
8016   SDValue Shift =
8017       DAG.getNode(ISD::SRA, dl, VT, Op,
8018                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
8019   SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
8020 
8021   // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
8022   if (!IsNegative)
8023     return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
8024 
8025   // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
8026   return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
8027 }
8028 
8029 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const {
8030   SDLoc dl(N);
8031   EVT VT = N->getValueType(0);
8032   SDValue Op = N->getOperand(0);
8033 
8034   if (!VT.isSimple())
8035     return SDValue();
8036 
8037   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
8038   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
8039   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
8040   default:
8041     return SDValue();
8042   case MVT::i16:
8043     // Use a rotate by 8. This can be further expanded if necessary.
8044     return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
8045   case MVT::i32:
8046     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
8047     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
8048     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
8049     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
8050     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
8051                        DAG.getConstant(0xFF0000, dl, VT));
8052     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
8053     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
8054     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
8055     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
8056   case MVT::i64:
8057     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
8058     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
8059     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
8060     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
8061     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
8062     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
8063     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
8064     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
8065     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
8066                        DAG.getConstant(255ULL<<48, dl, VT));
8067     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
8068                        DAG.getConstant(255ULL<<40, dl, VT));
8069     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
8070                        DAG.getConstant(255ULL<<32, dl, VT));
8071     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
8072                        DAG.getConstant(255ULL<<24, dl, VT));
8073     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
8074                        DAG.getConstant(255ULL<<16, dl, VT));
8075     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
8076                        DAG.getConstant(255ULL<<8 , dl, VT));
8077     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
8078     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
8079     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
8080     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
8081     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
8082     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
8083     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
8084   }
8085 }
8086 
8087 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
8088   SDLoc dl(N);
8089   EVT VT = N->getValueType(0);
8090   SDValue Op = N->getOperand(0);
8091   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
8092   unsigned Sz = VT.getScalarSizeInBits();
8093 
8094   SDValue Tmp, Tmp2, Tmp3;
8095 
8096   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
8097   // and finally the i1 pairs.
8098   // TODO: We can easily support i4/i2 legal types if any target ever does.
8099   if (Sz >= 8 && isPowerOf2_32(Sz)) {
8100     // Create the masks - repeating the pattern every byte.
8101     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
8102     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
8103     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
8104 
8105     // BSWAP if the type is wider than a single byte.
8106     Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
8107 
8108     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
8109     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
8110     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
8111     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
8112     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
8113     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8114 
8115     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
8116     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
8117     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
8118     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
8119     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
8120     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8121 
8122     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
8123     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
8124     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
8125     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
8126     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
8127     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8128     return Tmp;
8129   }
8130 
8131   Tmp = DAG.getConstant(0, dl, VT);
8132   for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
8133     if (I < J)
8134       Tmp2 =
8135           DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
8136     else
8137       Tmp2 =
8138           DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
8139 
8140     APInt Shift(Sz, 1);
8141     Shift <<= J;
8142     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
8143     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
8144   }
8145 
8146   return Tmp;
8147 }
8148 
8149 std::pair<SDValue, SDValue>
8150 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
8151                                     SelectionDAG &DAG) const {
8152   SDLoc SL(LD);
8153   SDValue Chain = LD->getChain();
8154   SDValue BasePTR = LD->getBasePtr();
8155   EVT SrcVT = LD->getMemoryVT();
8156   EVT DstVT = LD->getValueType(0);
8157   ISD::LoadExtType ExtType = LD->getExtensionType();
8158 
8159   if (SrcVT.isScalableVector())
8160     report_fatal_error("Cannot scalarize scalable vector loads");
8161 
8162   unsigned NumElem = SrcVT.getVectorNumElements();
8163 
8164   EVT SrcEltVT = SrcVT.getScalarType();
8165   EVT DstEltVT = DstVT.getScalarType();
8166 
8167   // A vector must always be stored in memory as-is, i.e. without any padding
8168   // between the elements, since various code depend on it, e.g. in the
8169   // handling of a bitcast of a vector type to int, which may be done with a
8170   // vector store followed by an integer load. A vector that does not have
8171   // elements that are byte-sized must therefore be stored as an integer
8172   // built out of the extracted vector elements.
8173   if (!SrcEltVT.isByteSized()) {
8174     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
8175     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
8176 
8177     unsigned NumSrcBits = SrcVT.getSizeInBits();
8178     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
8179 
8180     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
8181     SDValue SrcEltBitMask = DAG.getConstant(
8182         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
8183 
8184     // Load the whole vector and avoid masking off the top bits as it makes
8185     // the codegen worse.
8186     SDValue Load =
8187         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
8188                        LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(),
8189                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
8190 
8191     SmallVector<SDValue, 8> Vals;
8192     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8193       unsigned ShiftIntoIdx =
8194           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
8195       SDValue ShiftAmount =
8196           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
8197                                      LoadVT, SL, /*LegalTypes=*/false);
8198       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
8199       SDValue Elt =
8200           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
8201       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
8202 
8203       if (ExtType != ISD::NON_EXTLOAD) {
8204         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
8205         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
8206       }
8207 
8208       Vals.push_back(Scalar);
8209     }
8210 
8211     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
8212     return std::make_pair(Value, Load.getValue(1));
8213   }
8214 
8215   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
8216   assert(SrcEltVT.isByteSized());
8217 
8218   SmallVector<SDValue, 8> Vals;
8219   SmallVector<SDValue, 8> LoadChains;
8220 
8221   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8222     SDValue ScalarLoad =
8223         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
8224                        LD->getPointerInfo().getWithOffset(Idx * Stride),
8225                        SrcEltVT, LD->getOriginalAlign(),
8226                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
8227 
8228     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride));
8229 
8230     Vals.push_back(ScalarLoad.getValue(0));
8231     LoadChains.push_back(ScalarLoad.getValue(1));
8232   }
8233 
8234   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
8235   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
8236 
8237   return std::make_pair(Value, NewChain);
8238 }
8239 
8240 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
8241                                              SelectionDAG &DAG) const {
8242   SDLoc SL(ST);
8243 
8244   SDValue Chain = ST->getChain();
8245   SDValue BasePtr = ST->getBasePtr();
8246   SDValue Value = ST->getValue();
8247   EVT StVT = ST->getMemoryVT();
8248 
8249   if (StVT.isScalableVector())
8250     report_fatal_error("Cannot scalarize scalable vector stores");
8251 
8252   // The type of the data we want to save
8253   EVT RegVT = Value.getValueType();
8254   EVT RegSclVT = RegVT.getScalarType();
8255 
8256   // The type of data as saved in memory.
8257   EVT MemSclVT = StVT.getScalarType();
8258 
8259   unsigned NumElem = StVT.getVectorNumElements();
8260 
8261   // A vector must always be stored in memory as-is, i.e. without any padding
8262   // between the elements, since various code depend on it, e.g. in the
8263   // handling of a bitcast of a vector type to int, which may be done with a
8264   // vector store followed by an integer load. A vector that does not have
8265   // elements that are byte-sized must therefore be stored as an integer
8266   // built out of the extracted vector elements.
8267   if (!MemSclVT.isByteSized()) {
8268     unsigned NumBits = StVT.getSizeInBits();
8269     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
8270 
8271     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
8272 
8273     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8274       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
8275                                 DAG.getVectorIdxConstant(Idx, SL));
8276       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
8277       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
8278       unsigned ShiftIntoIdx =
8279           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
8280       SDValue ShiftAmount =
8281           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
8282       SDValue ShiftedElt =
8283           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
8284       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
8285     }
8286 
8287     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
8288                         ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
8289                         ST->getAAInfo());
8290   }
8291 
8292   // Store Stride in bytes
8293   unsigned Stride = MemSclVT.getSizeInBits() / 8;
8294   assert(Stride && "Zero stride!");
8295   // Extract each of the elements from the original vector and save them into
8296   // memory individually.
8297   SmallVector<SDValue, 8> Stores;
8298   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8299     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
8300                               DAG.getVectorIdxConstant(Idx, SL));
8301 
8302     SDValue Ptr =
8303         DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride));
8304 
8305     // This scalar TruncStore may be illegal, but we legalize it later.
8306     SDValue Store = DAG.getTruncStore(
8307         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
8308         MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
8309         ST->getAAInfo());
8310 
8311     Stores.push_back(Store);
8312   }
8313 
8314   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
8315 }
8316 
8317 std::pair<SDValue, SDValue>
8318 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
8319   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
8320          "unaligned indexed loads not implemented!");
8321   SDValue Chain = LD->getChain();
8322   SDValue Ptr = LD->getBasePtr();
8323   EVT VT = LD->getValueType(0);
8324   EVT LoadedVT = LD->getMemoryVT();
8325   SDLoc dl(LD);
8326   auto &MF = DAG.getMachineFunction();
8327 
8328   if (VT.isFloatingPoint() || VT.isVector()) {
8329     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
8330     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
8331       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
8332           LoadedVT.isVector()) {
8333         // Scalarize the load and let the individual components be handled.
8334         return scalarizeVectorLoad(LD, DAG);
8335       }
8336 
8337       // Expand to a (misaligned) integer load of the same size,
8338       // then bitconvert to floating point or vector.
8339       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
8340                                     LD->getMemOperand());
8341       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
8342       if (LoadedVT != VT)
8343         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
8344                              ISD::ANY_EXTEND, dl, VT, Result);
8345 
8346       return std::make_pair(Result, newLoad.getValue(1));
8347     }
8348 
8349     // Copy the value to a (aligned) stack slot using (unaligned) integer
8350     // loads and stores, then do a (aligned) load from the stack slot.
8351     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
8352     unsigned LoadedBytes = LoadedVT.getStoreSize();
8353     unsigned RegBytes = RegVT.getSizeInBits() / 8;
8354     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
8355 
8356     // Make sure the stack slot is also aligned for the register type.
8357     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
8358     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
8359     SmallVector<SDValue, 8> Stores;
8360     SDValue StackPtr = StackBase;
8361     unsigned Offset = 0;
8362 
8363     EVT PtrVT = Ptr.getValueType();
8364     EVT StackPtrVT = StackPtr.getValueType();
8365 
8366     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
8367     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
8368 
8369     // Do all but one copies using the full register width.
8370     for (unsigned i = 1; i < NumRegs; i++) {
8371       // Load one integer register's worth from the original location.
8372       SDValue Load = DAG.getLoad(
8373           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
8374           LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
8375           LD->getAAInfo());
8376       // Follow the load with a store to the stack slot.  Remember the store.
8377       Stores.push_back(DAG.getStore(
8378           Load.getValue(1), dl, Load, StackPtr,
8379           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
8380       // Increment the pointers.
8381       Offset += RegBytes;
8382 
8383       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
8384       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
8385     }
8386 
8387     // The last copy may be partial.  Do an extending load.
8388     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
8389                                   8 * (LoadedBytes - Offset));
8390     SDValue Load =
8391         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
8392                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
8393                        LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
8394                        LD->getAAInfo());
8395     // Follow the load with a store to the stack slot.  Remember the store.
8396     // On big-endian machines this requires a truncating store to ensure
8397     // that the bits end up in the right place.
8398     Stores.push_back(DAG.getTruncStore(
8399         Load.getValue(1), dl, Load, StackPtr,
8400         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
8401 
8402     // The order of the stores doesn't matter - say it with a TokenFactor.
8403     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8404 
8405     // Finally, perform the original load only redirected to the stack slot.
8406     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
8407                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
8408                           LoadedVT);
8409 
8410     // Callers expect a MERGE_VALUES node.
8411     return std::make_pair(Load, TF);
8412   }
8413 
8414   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
8415          "Unaligned load of unsupported type.");
8416 
8417   // Compute the new VT that is half the size of the old one.  This is an
8418   // integer MVT.
8419   unsigned NumBits = LoadedVT.getSizeInBits();
8420   EVT NewLoadedVT;
8421   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
8422   NumBits >>= 1;
8423 
8424   Align Alignment = LD->getOriginalAlign();
8425   unsigned IncrementSize = NumBits / 8;
8426   ISD::LoadExtType HiExtType = LD->getExtensionType();
8427 
8428   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
8429   if (HiExtType == ISD::NON_EXTLOAD)
8430     HiExtType = ISD::ZEXTLOAD;
8431 
8432   // Load the value in two parts
8433   SDValue Lo, Hi;
8434   if (DAG.getDataLayout().isLittleEndian()) {
8435     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
8436                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8437                         LD->getAAInfo());
8438 
8439     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8440     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
8441                         LD->getPointerInfo().getWithOffset(IncrementSize),
8442                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8443                         LD->getAAInfo());
8444   } else {
8445     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
8446                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8447                         LD->getAAInfo());
8448 
8449     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8450     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
8451                         LD->getPointerInfo().getWithOffset(IncrementSize),
8452                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8453                         LD->getAAInfo());
8454   }
8455 
8456   // aggregate the two parts
8457   SDValue ShiftAmount =
8458       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
8459                                                     DAG.getDataLayout()));
8460   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
8461   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
8462 
8463   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
8464                              Hi.getValue(1));
8465 
8466   return std::make_pair(Result, TF);
8467 }
8468 
8469 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
8470                                              SelectionDAG &DAG) const {
8471   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
8472          "unaligned indexed stores not implemented!");
8473   SDValue Chain = ST->getChain();
8474   SDValue Ptr = ST->getBasePtr();
8475   SDValue Val = ST->getValue();
8476   EVT VT = Val.getValueType();
8477   Align Alignment = ST->getOriginalAlign();
8478   auto &MF = DAG.getMachineFunction();
8479   EVT StoreMemVT = ST->getMemoryVT();
8480 
8481   SDLoc dl(ST);
8482   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
8483     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8484     if (isTypeLegal(intVT)) {
8485       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
8486           StoreMemVT.isVector()) {
8487         // Scalarize the store and let the individual components be handled.
8488         SDValue Result = scalarizeVectorStore(ST, DAG);
8489         return Result;
8490       }
8491       // Expand to a bitconvert of the value to the integer type of the
8492       // same size, then a (misaligned) int store.
8493       // FIXME: Does not handle truncating floating point stores!
8494       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
8495       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
8496                             Alignment, ST->getMemOperand()->getFlags());
8497       return Result;
8498     }
8499     // Do a (aligned) store to a stack slot, then copy from the stack slot
8500     // to the final destination using (unaligned) integer loads and stores.
8501     MVT RegVT = getRegisterType(
8502         *DAG.getContext(),
8503         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
8504     EVT PtrVT = Ptr.getValueType();
8505     unsigned StoredBytes = StoreMemVT.getStoreSize();
8506     unsigned RegBytes = RegVT.getSizeInBits() / 8;
8507     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
8508 
8509     // Make sure the stack slot is also aligned for the register type.
8510     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
8511     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
8512 
8513     // Perform the original store, only redirected to the stack slot.
8514     SDValue Store = DAG.getTruncStore(
8515         Chain, dl, Val, StackPtr,
8516         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
8517 
8518     EVT StackPtrVT = StackPtr.getValueType();
8519 
8520     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
8521     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
8522     SmallVector<SDValue, 8> Stores;
8523     unsigned Offset = 0;
8524 
8525     // Do all but one copies using the full register width.
8526     for (unsigned i = 1; i < NumRegs; i++) {
8527       // Load one integer register's worth from the stack slot.
8528       SDValue Load = DAG.getLoad(
8529           RegVT, dl, Store, StackPtr,
8530           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
8531       // Store it to the final location.  Remember the store.
8532       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
8533                                     ST->getPointerInfo().getWithOffset(Offset),
8534                                     ST->getOriginalAlign(),
8535                                     ST->getMemOperand()->getFlags()));
8536       // Increment the pointers.
8537       Offset += RegBytes;
8538       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
8539       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
8540     }
8541 
8542     // The last store may be partial.  Do a truncating store.  On big-endian
8543     // machines this requires an extending load from the stack slot to ensure
8544     // that the bits are in the right place.
8545     EVT LoadMemVT =
8546         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
8547 
8548     // Load from the stack slot.
8549     SDValue Load = DAG.getExtLoad(
8550         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
8551         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
8552 
8553     Stores.push_back(
8554         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
8555                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
8556                           ST->getOriginalAlign(),
8557                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
8558     // The order of the stores doesn't matter - say it with a TokenFactor.
8559     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8560     return Result;
8561   }
8562 
8563   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
8564          "Unaligned store of unknown type.");
8565   // Get the half-size VT
8566   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
8567   unsigned NumBits = NewStoredVT.getFixedSizeInBits();
8568   unsigned IncrementSize = NumBits / 8;
8569 
8570   // Divide the stored value in two parts.
8571   SDValue ShiftAmount = DAG.getConstant(
8572       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
8573   SDValue Lo = Val;
8574   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
8575 
8576   // Store the two parts
8577   SDValue Store1, Store2;
8578   Store1 = DAG.getTruncStore(Chain, dl,
8579                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
8580                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
8581                              ST->getMemOperand()->getFlags());
8582 
8583   Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8584   Store2 = DAG.getTruncStore(
8585       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
8586       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
8587       ST->getMemOperand()->getFlags(), ST->getAAInfo());
8588 
8589   SDValue Result =
8590       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
8591   return Result;
8592 }
8593 
8594 SDValue
8595 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
8596                                        const SDLoc &DL, EVT DataVT,
8597                                        SelectionDAG &DAG,
8598                                        bool IsCompressedMemory) const {
8599   SDValue Increment;
8600   EVT AddrVT = Addr.getValueType();
8601   EVT MaskVT = Mask.getValueType();
8602   assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
8603          "Incompatible types of Data and Mask");
8604   if (IsCompressedMemory) {
8605     if (DataVT.isScalableVector())
8606       report_fatal_error(
8607           "Cannot currently handle compressed memory with scalable vectors");
8608     // Incrementing the pointer according to number of '1's in the mask.
8609     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
8610     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
8611     if (MaskIntVT.getSizeInBits() < 32) {
8612       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
8613       MaskIntVT = MVT::i32;
8614     }
8615 
8616     // Count '1's with POPCNT.
8617     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
8618     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
8619     // Scale is an element size in bytes.
8620     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
8621                                     AddrVT);
8622     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
8623   } else if (DataVT.isScalableVector()) {
8624     Increment = DAG.getVScale(DL, AddrVT,
8625                               APInt(AddrVT.getFixedSizeInBits(),
8626                                     DataVT.getStoreSize().getKnownMinSize()));
8627   } else
8628     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
8629 
8630   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
8631 }
8632 
8633 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx,
8634                                        EVT VecVT, const SDLoc &dl,
8635                                        ElementCount SubEC) {
8636   assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
8637          "Cannot index a scalable vector within a fixed-width vector");
8638 
8639   unsigned NElts = VecVT.getVectorMinNumElements();
8640   unsigned NumSubElts = SubEC.getKnownMinValue();
8641   EVT IdxVT = Idx.getValueType();
8642 
8643   if (VecVT.isScalableVector() && !SubEC.isScalable()) {
8644     // If this is a constant index and we know the value plus the number of the
8645     // elements in the subvector minus one is less than the minimum number of
8646     // elements then it's safe to return Idx.
8647     if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
8648       if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
8649         return Idx;
8650     SDValue VS =
8651         DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
8652     unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
8653     SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
8654                               DAG.getConstant(NumSubElts, dl, IdxVT));
8655     return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
8656   }
8657   if (isPowerOf2_32(NElts) && NumSubElts == 1) {
8658     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
8659     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
8660                        DAG.getConstant(Imm, dl, IdxVT));
8661   }
8662   unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
8663   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
8664                      DAG.getConstant(MaxIndex, dl, IdxVT));
8665 }
8666 
8667 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
8668                                                 SDValue VecPtr, EVT VecVT,
8669                                                 SDValue Index) const {
8670   return getVectorSubVecPointer(
8671       DAG, VecPtr, VecVT,
8672       EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1),
8673       Index);
8674 }
8675 
8676 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG,
8677                                                SDValue VecPtr, EVT VecVT,
8678                                                EVT SubVecVT,
8679                                                SDValue Index) const {
8680   SDLoc dl(Index);
8681   // Make sure the index type is big enough to compute in.
8682   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
8683 
8684   EVT EltVT = VecVT.getVectorElementType();
8685 
8686   // Calculate the element offset and add it to the pointer.
8687   unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
8688   assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
8689          "Converting bits to bytes lost precision");
8690   assert(SubVecVT.getVectorElementType() == EltVT &&
8691          "Sub-vector must be a vector with matching element type");
8692   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
8693                                   SubVecVT.getVectorElementCount());
8694 
8695   EVT IdxVT = Index.getValueType();
8696   if (SubVecVT.isScalableVector())
8697     Index =
8698         DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8699                     DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
8700 
8701   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8702                       DAG.getConstant(EltSize, dl, IdxVT));
8703   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
8704 }
8705 
8706 //===----------------------------------------------------------------------===//
8707 // Implementation of Emulated TLS Model
8708 //===----------------------------------------------------------------------===//
8709 
8710 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
8711                                                 SelectionDAG &DAG) const {
8712   // Access to address of TLS varialbe xyz is lowered to a function call:
8713   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
8714   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8715   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
8716   SDLoc dl(GA);
8717 
8718   ArgListTy Args;
8719   ArgListEntry Entry;
8720   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
8721   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
8722   StringRef EmuTlsVarName(NameString);
8723   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
8724   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
8725   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
8726   Entry.Ty = VoidPtrType;
8727   Args.push_back(Entry);
8728 
8729   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
8730 
8731   TargetLowering::CallLoweringInfo CLI(DAG);
8732   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
8733   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
8734   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8735 
8736   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8737   // At last for X86 targets, maybe good for other targets too?
8738   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8739   MFI.setAdjustsStack(true); // Is this only for X86 target?
8740   MFI.setHasCalls(true);
8741 
8742   assert((GA->getOffset() == 0) &&
8743          "Emulated TLS must have zero offset in GlobalAddressSDNode");
8744   return CallResult.first;
8745 }
8746 
8747 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
8748                                                 SelectionDAG &DAG) const {
8749   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
8750   if (!isCtlzFast())
8751     return SDValue();
8752   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8753   SDLoc dl(Op);
8754   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8755     if (C->isZero() && CC == ISD::SETEQ) {
8756       EVT VT = Op.getOperand(0).getValueType();
8757       SDValue Zext = Op.getOperand(0);
8758       if (VT.bitsLT(MVT::i32)) {
8759         VT = MVT::i32;
8760         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
8761       }
8762       unsigned Log2b = Log2_32(VT.getSizeInBits());
8763       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
8764       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
8765                                 DAG.getConstant(Log2b, dl, MVT::i32));
8766       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
8767     }
8768   }
8769   return SDValue();
8770 }
8771 
8772 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const {
8773   SDValue Op0 = Node->getOperand(0);
8774   SDValue Op1 = Node->getOperand(1);
8775   EVT VT = Op0.getValueType();
8776   unsigned Opcode = Node->getOpcode();
8777   SDLoc DL(Node);
8778 
8779   // umin(x,y) -> sub(x,usubsat(x,y))
8780   if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
8781       isOperationLegal(ISD::USUBSAT, VT)) {
8782     return DAG.getNode(ISD::SUB, DL, VT, Op0,
8783                        DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
8784   }
8785 
8786   // umax(x,y) -> add(x,usubsat(y,x))
8787   if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
8788       isOperationLegal(ISD::USUBSAT, VT)) {
8789     return DAG.getNode(ISD::ADD, DL, VT, Op0,
8790                        DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
8791   }
8792 
8793   // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
8794   ISD::CondCode CC;
8795   switch (Opcode) {
8796   default: llvm_unreachable("How did we get here?");
8797   case ISD::SMAX: CC = ISD::SETGT; break;
8798   case ISD::SMIN: CC = ISD::SETLT; break;
8799   case ISD::UMAX: CC = ISD::SETUGT; break;
8800   case ISD::UMIN: CC = ISD::SETULT; break;
8801   }
8802 
8803   // FIXME: Should really try to split the vector in case it's legal on a
8804   // subvector.
8805   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8806     return DAG.UnrollVectorOp(Node);
8807 
8808   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8809   SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
8810   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
8811 }
8812 
8813 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
8814   unsigned Opcode = Node->getOpcode();
8815   SDValue LHS = Node->getOperand(0);
8816   SDValue RHS = Node->getOperand(1);
8817   EVT VT = LHS.getValueType();
8818   SDLoc dl(Node);
8819 
8820   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8821   assert(VT.isInteger() && "Expected operands to be integers");
8822 
8823   // usub.sat(a, b) -> umax(a, b) - b
8824   if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
8825     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
8826     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
8827   }
8828 
8829   // uadd.sat(a, b) -> umin(a, ~b) + b
8830   if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
8831     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
8832     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
8833     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
8834   }
8835 
8836   unsigned OverflowOp;
8837   switch (Opcode) {
8838   case ISD::SADDSAT:
8839     OverflowOp = ISD::SADDO;
8840     break;
8841   case ISD::UADDSAT:
8842     OverflowOp = ISD::UADDO;
8843     break;
8844   case ISD::SSUBSAT:
8845     OverflowOp = ISD::SSUBO;
8846     break;
8847   case ISD::USUBSAT:
8848     OverflowOp = ISD::USUBO;
8849     break;
8850   default:
8851     llvm_unreachable("Expected method to receive signed or unsigned saturation "
8852                      "addition or subtraction node.");
8853   }
8854 
8855   // FIXME: Should really try to split the vector in case it's legal on a
8856   // subvector.
8857   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8858     return DAG.UnrollVectorOp(Node);
8859 
8860   unsigned BitWidth = LHS.getScalarValueSizeInBits();
8861   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8862   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8863   SDValue SumDiff = Result.getValue(0);
8864   SDValue Overflow = Result.getValue(1);
8865   SDValue Zero = DAG.getConstant(0, dl, VT);
8866   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
8867 
8868   if (Opcode == ISD::UADDSAT) {
8869     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8870       // (LHS + RHS) | OverflowMask
8871       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8872       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
8873     }
8874     // Overflow ? 0xffff.... : (LHS + RHS)
8875     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
8876   }
8877 
8878   if (Opcode == ISD::USUBSAT) {
8879     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8880       // (LHS - RHS) & ~OverflowMask
8881       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8882       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
8883       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
8884     }
8885     // Overflow ? 0 : (LHS - RHS)
8886     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
8887   }
8888 
8889   // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
8890   APInt MinVal = APInt::getSignedMinValue(BitWidth);
8891   SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8892   SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
8893                               DAG.getConstant(BitWidth - 1, dl, VT));
8894   Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
8895   return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
8896 }
8897 
8898 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const {
8899   unsigned Opcode = Node->getOpcode();
8900   bool IsSigned = Opcode == ISD::SSHLSAT;
8901   SDValue LHS = Node->getOperand(0);
8902   SDValue RHS = Node->getOperand(1);
8903   EVT VT = LHS.getValueType();
8904   SDLoc dl(Node);
8905 
8906   assert((Node->getOpcode() == ISD::SSHLSAT ||
8907           Node->getOpcode() == ISD::USHLSAT) &&
8908           "Expected a SHLSAT opcode");
8909   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8910   assert(VT.isInteger() && "Expected operands to be integers");
8911 
8912   // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
8913 
8914   unsigned BW = VT.getScalarSizeInBits();
8915   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
8916   SDValue Orig =
8917       DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
8918 
8919   SDValue SatVal;
8920   if (IsSigned) {
8921     SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
8922     SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
8923     SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT),
8924                              SatMin, SatMax, ISD::SETLT);
8925   } else {
8926     SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
8927   }
8928   Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE);
8929 
8930   return Result;
8931 }
8932 
8933 SDValue
8934 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
8935   assert((Node->getOpcode() == ISD::SMULFIX ||
8936           Node->getOpcode() == ISD::UMULFIX ||
8937           Node->getOpcode() == ISD::SMULFIXSAT ||
8938           Node->getOpcode() == ISD::UMULFIXSAT) &&
8939          "Expected a fixed point multiplication opcode");
8940 
8941   SDLoc dl(Node);
8942   SDValue LHS = Node->getOperand(0);
8943   SDValue RHS = Node->getOperand(1);
8944   EVT VT = LHS.getValueType();
8945   unsigned Scale = Node->getConstantOperandVal(2);
8946   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
8947                      Node->getOpcode() == ISD::UMULFIXSAT);
8948   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
8949                  Node->getOpcode() == ISD::SMULFIXSAT);
8950   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8951   unsigned VTSize = VT.getScalarSizeInBits();
8952 
8953   if (!Scale) {
8954     // [us]mul.fix(a, b, 0) -> mul(a, b)
8955     if (!Saturating) {
8956       if (isOperationLegalOrCustom(ISD::MUL, VT))
8957         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8958     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
8959       SDValue Result =
8960           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8961       SDValue Product = Result.getValue(0);
8962       SDValue Overflow = Result.getValue(1);
8963       SDValue Zero = DAG.getConstant(0, dl, VT);
8964 
8965       APInt MinVal = APInt::getSignedMinValue(VTSize);
8966       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
8967       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8968       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8969       // Xor the inputs, if resulting sign bit is 0 the product will be
8970       // positive, else negative.
8971       SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
8972       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
8973       Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
8974       return DAG.getSelect(dl, VT, Overflow, Result, Product);
8975     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
8976       SDValue Result =
8977           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8978       SDValue Product = Result.getValue(0);
8979       SDValue Overflow = Result.getValue(1);
8980 
8981       APInt MaxVal = APInt::getMaxValue(VTSize);
8982       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8983       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
8984     }
8985   }
8986 
8987   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
8988          "Expected scale to be less than the number of bits if signed or at "
8989          "most the number of bits if unsigned.");
8990   assert(LHS.getValueType() == RHS.getValueType() &&
8991          "Expected both operands to be the same type");
8992 
8993   // Get the upper and lower bits of the result.
8994   SDValue Lo, Hi;
8995   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
8996   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
8997   if (isOperationLegalOrCustom(LoHiOp, VT)) {
8998     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
8999     Lo = Result.getValue(0);
9000     Hi = Result.getValue(1);
9001   } else if (isOperationLegalOrCustom(HiOp, VT)) {
9002     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
9003     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
9004   } else if (VT.isVector()) {
9005     return SDValue();
9006   } else {
9007     report_fatal_error("Unable to expand fixed point multiplication.");
9008   }
9009 
9010   if (Scale == VTSize)
9011     // Result is just the top half since we'd be shifting by the width of the
9012     // operand. Overflow impossible so this works for both UMULFIX and
9013     // UMULFIXSAT.
9014     return Hi;
9015 
9016   // The result will need to be shifted right by the scale since both operands
9017   // are scaled. The result is given to us in 2 halves, so we only want part of
9018   // both in the result.
9019   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
9020   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
9021                                DAG.getConstant(Scale, dl, ShiftTy));
9022   if (!Saturating)
9023     return Result;
9024 
9025   if (!Signed) {
9026     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
9027     // widened multiplication) aren't all zeroes.
9028 
9029     // Saturate to max if ((Hi >> Scale) != 0),
9030     // which is the same as if (Hi > ((1 << Scale) - 1))
9031     APInt MaxVal = APInt::getMaxValue(VTSize);
9032     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
9033                                       dl, VT);
9034     Result = DAG.getSelectCC(dl, Hi, LowMask,
9035                              DAG.getConstant(MaxVal, dl, VT), Result,
9036                              ISD::SETUGT);
9037 
9038     return Result;
9039   }
9040 
9041   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
9042   // widened multiplication) aren't all ones or all zeroes.
9043 
9044   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
9045   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
9046 
9047   if (Scale == 0) {
9048     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
9049                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
9050     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
9051     // Saturated to SatMin if wide product is negative, and SatMax if wide
9052     // product is positive ...
9053     SDValue Zero = DAG.getConstant(0, dl, VT);
9054     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
9055                                                ISD::SETLT);
9056     // ... but only if we overflowed.
9057     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
9058   }
9059 
9060   //  We handled Scale==0 above so all the bits to examine is in Hi.
9061 
9062   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
9063   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
9064   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
9065                                     dl, VT);
9066   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
9067   // Saturate to min if (Hi >> (Scale - 1)) < -1),
9068   // which is the same as if (HI < (-1 << (Scale - 1))
9069   SDValue HighMask =
9070       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
9071                       dl, VT);
9072   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
9073   return Result;
9074 }
9075 
9076 SDValue
9077 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
9078                                     SDValue LHS, SDValue RHS,
9079                                     unsigned Scale, SelectionDAG &DAG) const {
9080   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
9081           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
9082          "Expected a fixed point division opcode");
9083 
9084   EVT VT = LHS.getValueType();
9085   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
9086   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
9087   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9088 
9089   // If there is enough room in the type to upscale the LHS or downscale the
9090   // RHS before the division, we can perform it in this type without having to
9091   // resize. For signed operations, the LHS headroom is the number of
9092   // redundant sign bits, and for unsigned ones it is the number of zeroes.
9093   // The headroom for the RHS is the number of trailing zeroes.
9094   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
9095                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
9096   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
9097 
9098   // For signed saturating operations, we need to be able to detect true integer
9099   // division overflow; that is, when you have MIN / -EPS. However, this
9100   // is undefined behavior and if we emit divisions that could take such
9101   // values it may cause undesired behavior (arithmetic exceptions on x86, for
9102   // example).
9103   // Avoid this by requiring an extra bit so that we never get this case.
9104   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
9105   // signed saturating division, we need to emit a whopping 32-bit division.
9106   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
9107     return SDValue();
9108 
9109   unsigned LHSShift = std::min(LHSLead, Scale);
9110   unsigned RHSShift = Scale - LHSShift;
9111 
9112   // At this point, we know that if we shift the LHS up by LHSShift and the
9113   // RHS down by RHSShift, we can emit a regular division with a final scaling
9114   // factor of Scale.
9115 
9116   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
9117   if (LHSShift)
9118     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
9119                       DAG.getConstant(LHSShift, dl, ShiftTy));
9120   if (RHSShift)
9121     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
9122                       DAG.getConstant(RHSShift, dl, ShiftTy));
9123 
9124   SDValue Quot;
9125   if (Signed) {
9126     // For signed operations, if the resulting quotient is negative and the
9127     // remainder is nonzero, subtract 1 from the quotient to round towards
9128     // negative infinity.
9129     SDValue Rem;
9130     // FIXME: Ideally we would always produce an SDIVREM here, but if the
9131     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
9132     // we couldn't just form a libcall, but the type legalizer doesn't do it.
9133     if (isTypeLegal(VT) &&
9134         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
9135       Quot = DAG.getNode(ISD::SDIVREM, dl,
9136                          DAG.getVTList(VT, VT),
9137                          LHS, RHS);
9138       Rem = Quot.getValue(1);
9139       Quot = Quot.getValue(0);
9140     } else {
9141       Quot = DAG.getNode(ISD::SDIV, dl, VT,
9142                          LHS, RHS);
9143       Rem = DAG.getNode(ISD::SREM, dl, VT,
9144                         LHS, RHS);
9145     }
9146     SDValue Zero = DAG.getConstant(0, dl, VT);
9147     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
9148     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
9149     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
9150     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
9151     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
9152                                DAG.getConstant(1, dl, VT));
9153     Quot = DAG.getSelect(dl, VT,
9154                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
9155                          Sub1, Quot);
9156   } else
9157     Quot = DAG.getNode(ISD::UDIV, dl, VT,
9158                        LHS, RHS);
9159 
9160   return Quot;
9161 }
9162 
9163 void TargetLowering::expandUADDSUBO(
9164     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
9165   SDLoc dl(Node);
9166   SDValue LHS = Node->getOperand(0);
9167   SDValue RHS = Node->getOperand(1);
9168   bool IsAdd = Node->getOpcode() == ISD::UADDO;
9169 
9170   // If ADD/SUBCARRY is legal, use that instead.
9171   unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY;
9172   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
9173     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
9174     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
9175                                     { LHS, RHS, CarryIn });
9176     Result = SDValue(NodeCarry.getNode(), 0);
9177     Overflow = SDValue(NodeCarry.getNode(), 1);
9178     return;
9179   }
9180 
9181   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
9182                             LHS.getValueType(), LHS, RHS);
9183 
9184   EVT ResultType = Node->getValueType(1);
9185   EVT SetCCType = getSetCCResultType(
9186       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
9187   SDValue SetCC;
9188   if (IsAdd && isOneConstant(RHS)) {
9189     // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
9190     // the live range of X. We assume comparing with 0 is cheap.
9191     // The general case (X + C) < C is not necessarily beneficial. Although we
9192     // reduce the live range of X, we may introduce the materialization of
9193     // constant C.
9194     SetCC =
9195         DAG.getSetCC(dl, SetCCType, Result,
9196                      DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
9197   } else {
9198     ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
9199     SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
9200   }
9201   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
9202 }
9203 
9204 void TargetLowering::expandSADDSUBO(
9205     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
9206   SDLoc dl(Node);
9207   SDValue LHS = Node->getOperand(0);
9208   SDValue RHS = Node->getOperand(1);
9209   bool IsAdd = Node->getOpcode() == ISD::SADDO;
9210 
9211   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
9212                             LHS.getValueType(), LHS, RHS);
9213 
9214   EVT ResultType = Node->getValueType(1);
9215   EVT OType = getSetCCResultType(
9216       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
9217 
9218   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
9219   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
9220   if (isOperationLegal(OpcSat, LHS.getValueType())) {
9221     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
9222     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
9223     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
9224     return;
9225   }
9226 
9227   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
9228 
9229   // For an addition, the result should be less than one of the operands (LHS)
9230   // if and only if the other operand (RHS) is negative, otherwise there will
9231   // be overflow.
9232   // For a subtraction, the result should be less than one of the operands
9233   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
9234   // otherwise there will be overflow.
9235   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
9236   SDValue ConditionRHS =
9237       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
9238 
9239   Overflow = DAG.getBoolExtOrTrunc(
9240       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
9241       ResultType, ResultType);
9242 }
9243 
9244 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
9245                                 SDValue &Overflow, SelectionDAG &DAG) const {
9246   SDLoc dl(Node);
9247   EVT VT = Node->getValueType(0);
9248   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9249   SDValue LHS = Node->getOperand(0);
9250   SDValue RHS = Node->getOperand(1);
9251   bool isSigned = Node->getOpcode() == ISD::SMULO;
9252 
9253   // For power-of-two multiplications we can use a simpler shift expansion.
9254   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
9255     const APInt &C = RHSC->getAPIntValue();
9256     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
9257     if (C.isPowerOf2()) {
9258       // smulo(x, signed_min) is same as umulo(x, signed_min).
9259       bool UseArithShift = isSigned && !C.isMinSignedValue();
9260       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
9261       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
9262       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
9263       Overflow = DAG.getSetCC(dl, SetCCVT,
9264           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
9265                       dl, VT, Result, ShiftAmt),
9266           LHS, ISD::SETNE);
9267       return true;
9268     }
9269   }
9270 
9271   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
9272   if (VT.isVector())
9273     WideVT =
9274         EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount());
9275 
9276   SDValue BottomHalf;
9277   SDValue TopHalf;
9278   static const unsigned Ops[2][3] =
9279       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
9280         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
9281   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
9282     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
9283     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
9284   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
9285     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
9286                              RHS);
9287     TopHalf = BottomHalf.getValue(1);
9288   } else if (isTypeLegal(WideVT)) {
9289     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
9290     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
9291     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
9292     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
9293     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
9294         getShiftAmountTy(WideVT, DAG.getDataLayout()));
9295     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
9296                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
9297   } else {
9298     if (VT.isVector())
9299       return false;
9300 
9301     // We can fall back to a libcall with an illegal type for the MUL if we
9302     // have a libcall big enough.
9303     // Also, we can fall back to a division in some cases, but that's a big
9304     // performance hit in the general case.
9305     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
9306     if (WideVT == MVT::i16)
9307       LC = RTLIB::MUL_I16;
9308     else if (WideVT == MVT::i32)
9309       LC = RTLIB::MUL_I32;
9310     else if (WideVT == MVT::i64)
9311       LC = RTLIB::MUL_I64;
9312     else if (WideVT == MVT::i128)
9313       LC = RTLIB::MUL_I128;
9314     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
9315 
9316     SDValue HiLHS;
9317     SDValue HiRHS;
9318     if (isSigned) {
9319       // The high part is obtained by SRA'ing all but one of the bits of low
9320       // part.
9321       unsigned LoSize = VT.getFixedSizeInBits();
9322       HiLHS =
9323           DAG.getNode(ISD::SRA, dl, VT, LHS,
9324                       DAG.getConstant(LoSize - 1, dl,
9325                                       getPointerTy(DAG.getDataLayout())));
9326       HiRHS =
9327           DAG.getNode(ISD::SRA, dl, VT, RHS,
9328                       DAG.getConstant(LoSize - 1, dl,
9329                                       getPointerTy(DAG.getDataLayout())));
9330     } else {
9331         HiLHS = DAG.getConstant(0, dl, VT);
9332         HiRHS = DAG.getConstant(0, dl, VT);
9333     }
9334 
9335     // Here we're passing the 2 arguments explicitly as 4 arguments that are
9336     // pre-lowered to the correct types. This all depends upon WideVT not
9337     // being a legal type for the architecture and thus has to be split to
9338     // two arguments.
9339     SDValue Ret;
9340     TargetLowering::MakeLibCallOptions CallOptions;
9341     CallOptions.setSExt(isSigned);
9342     CallOptions.setIsPostTypeLegalization(true);
9343     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
9344       // Halves of WideVT are packed into registers in different order
9345       // depending on platform endianness. This is usually handled by
9346       // the C calling convention, but we can't defer to it in
9347       // the legalizer.
9348       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
9349       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
9350     } else {
9351       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
9352       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
9353     }
9354     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
9355            "Ret value is a collection of constituent nodes holding result.");
9356     if (DAG.getDataLayout().isLittleEndian()) {
9357       // Same as above.
9358       BottomHalf = Ret.getOperand(0);
9359       TopHalf = Ret.getOperand(1);
9360     } else {
9361       BottomHalf = Ret.getOperand(1);
9362       TopHalf = Ret.getOperand(0);
9363     }
9364   }
9365 
9366   Result = BottomHalf;
9367   if (isSigned) {
9368     SDValue ShiftAmt = DAG.getConstant(
9369         VT.getScalarSizeInBits() - 1, dl,
9370         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
9371     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
9372     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
9373   } else {
9374     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
9375                             DAG.getConstant(0, dl, VT), ISD::SETNE);
9376   }
9377 
9378   // Truncate the result if SetCC returns a larger type than needed.
9379   EVT RType = Node->getValueType(1);
9380   if (RType.bitsLT(Overflow.getValueType()))
9381     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
9382 
9383   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
9384          "Unexpected result type for S/UMULO legalization");
9385   return true;
9386 }
9387 
9388 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
9389   SDLoc dl(Node);
9390   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
9391   SDValue Op = Node->getOperand(0);
9392   EVT VT = Op.getValueType();
9393 
9394   if (VT.isScalableVector())
9395     report_fatal_error(
9396         "Expanding reductions for scalable vectors is undefined.");
9397 
9398   // Try to use a shuffle reduction for power of two vectors.
9399   if (VT.isPow2VectorType()) {
9400     while (VT.getVectorNumElements() > 1) {
9401       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
9402       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
9403         break;
9404 
9405       SDValue Lo, Hi;
9406       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
9407       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
9408       VT = HalfVT;
9409     }
9410   }
9411 
9412   EVT EltVT = VT.getVectorElementType();
9413   unsigned NumElts = VT.getVectorNumElements();
9414 
9415   SmallVector<SDValue, 8> Ops;
9416   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
9417 
9418   SDValue Res = Ops[0];
9419   for (unsigned i = 1; i < NumElts; i++)
9420     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
9421 
9422   // Result type may be wider than element type.
9423   if (EltVT != Node->getValueType(0))
9424     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
9425   return Res;
9426 }
9427 
9428 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const {
9429   SDLoc dl(Node);
9430   SDValue AccOp = Node->getOperand(0);
9431   SDValue VecOp = Node->getOperand(1);
9432   SDNodeFlags Flags = Node->getFlags();
9433 
9434   EVT VT = VecOp.getValueType();
9435   EVT EltVT = VT.getVectorElementType();
9436 
9437   if (VT.isScalableVector())
9438     report_fatal_error(
9439         "Expanding reductions for scalable vectors is undefined.");
9440 
9441   unsigned NumElts = VT.getVectorNumElements();
9442 
9443   SmallVector<SDValue, 8> Ops;
9444   DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
9445 
9446   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
9447 
9448   SDValue Res = AccOp;
9449   for (unsigned i = 0; i < NumElts; i++)
9450     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
9451 
9452   return Res;
9453 }
9454 
9455 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result,
9456                                SelectionDAG &DAG) const {
9457   EVT VT = Node->getValueType(0);
9458   SDLoc dl(Node);
9459   bool isSigned = Node->getOpcode() == ISD::SREM;
9460   unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
9461   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
9462   SDValue Dividend = Node->getOperand(0);
9463   SDValue Divisor = Node->getOperand(1);
9464   if (isOperationLegalOrCustom(DivRemOpc, VT)) {
9465     SDVTList VTs = DAG.getVTList(VT, VT);
9466     Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
9467     return true;
9468   }
9469   if (isOperationLegalOrCustom(DivOpc, VT)) {
9470     // X % Y -> X-X/Y*Y
9471     SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
9472     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
9473     Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
9474     return true;
9475   }
9476   return false;
9477 }
9478 
9479 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node,
9480                                             SelectionDAG &DAG) const {
9481   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
9482   SDLoc dl(SDValue(Node, 0));
9483   SDValue Src = Node->getOperand(0);
9484 
9485   // DstVT is the result type, while SatVT is the size to which we saturate
9486   EVT SrcVT = Src.getValueType();
9487   EVT DstVT = Node->getValueType(0);
9488 
9489   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9490   unsigned SatWidth = SatVT.getScalarSizeInBits();
9491   unsigned DstWidth = DstVT.getScalarSizeInBits();
9492   assert(SatWidth <= DstWidth &&
9493          "Expected saturation width smaller than result width");
9494 
9495   // Determine minimum and maximum integer values and their corresponding
9496   // floating-point values.
9497   APInt MinInt, MaxInt;
9498   if (IsSigned) {
9499     MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
9500     MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
9501   } else {
9502     MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
9503     MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
9504   }
9505 
9506   // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as
9507   // libcall emission cannot handle this. Large result types will fail.
9508   if (SrcVT == MVT::f16) {
9509     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
9510     SrcVT = Src.getValueType();
9511   }
9512 
9513   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9514   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9515 
9516   APFloat::opStatus MinStatus =
9517       MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
9518   APFloat::opStatus MaxStatus =
9519       MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
9520   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
9521                              !(MaxStatus & APFloat::opStatus::opInexact);
9522 
9523   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
9524   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
9525 
9526   // If the integer bounds are exactly representable as floats and min/max are
9527   // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
9528   // of comparisons and selects.
9529   bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) &&
9530                      isOperationLegal(ISD::FMAXNUM, SrcVT);
9531   if (AreExactFloatBounds && MinMaxLegal) {
9532     SDValue Clamped = Src;
9533 
9534     // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat.
9535     Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode);
9536     // Clamp by MaxFloat from above. NaN cannot occur.
9537     Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode);
9538     // Convert clamped value to integer.
9539     SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
9540                                   dl, DstVT, Clamped);
9541 
9542     // In the unsigned case we're done, because we mapped NaN to MinFloat,
9543     // which will cast to zero.
9544     if (!IsSigned)
9545       return FpToInt;
9546 
9547     // Otherwise, select 0 if Src is NaN.
9548     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9549     return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt,
9550                            ISD::CondCode::SETUO);
9551   }
9552 
9553   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
9554   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
9555 
9556   // Result of direct conversion. The assumption here is that the operation is
9557   // non-trapping and it's fine to apply it to an out-of-range value if we
9558   // select it away later.
9559   SDValue FpToInt =
9560       DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
9561 
9562   SDValue Select = FpToInt;
9563 
9564   // If Src ULT MinFloat, select MinInt. In particular, this also selects
9565   // MinInt if Src is NaN.
9566   Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select,
9567                            ISD::CondCode::SETULT);
9568   // If Src OGT MaxFloat, select MaxInt.
9569   Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select,
9570                            ISD::CondCode::SETOGT);
9571 
9572   // In the unsigned case we are done, because we mapped NaN to MinInt, which
9573   // is already zero.
9574   if (!IsSigned)
9575     return Select;
9576 
9577   // Otherwise, select 0 if Src is NaN.
9578   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9579   return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
9580 }
9581 
9582 SDValue TargetLowering::expandVectorSplice(SDNode *Node,
9583                                            SelectionDAG &DAG) const {
9584   assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!");
9585   assert(Node->getValueType(0).isScalableVector() &&
9586          "Fixed length vector types expected to use SHUFFLE_VECTOR!");
9587 
9588   EVT VT = Node->getValueType(0);
9589   SDValue V1 = Node->getOperand(0);
9590   SDValue V2 = Node->getOperand(1);
9591   int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue();
9592   SDLoc DL(Node);
9593 
9594   // Expand through memory thusly:
9595   //  Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
9596   //  Store V1, Ptr
9597   //  Store V2, Ptr + sizeof(V1)
9598   //  If (Imm < 0)
9599   //    TrailingElts = -Imm
9600   //    Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt))
9601   //  else
9602   //    Ptr = Ptr + (Imm * sizeof(VT.Elt))
9603   //  Res = Load Ptr
9604 
9605   Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
9606 
9607   EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9608                                VT.getVectorElementCount() * 2);
9609   SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
9610   EVT PtrVT = StackPtr.getValueType();
9611   auto &MF = DAG.getMachineFunction();
9612   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
9613   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
9614 
9615   // Store the lo part of CONCAT_VECTORS(V1, V2)
9616   SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo);
9617   // Store the hi part of CONCAT_VECTORS(V1, V2)
9618   SDValue OffsetToV2 = DAG.getVScale(
9619       DL, PtrVT,
9620       APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9621   SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2);
9622   SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo);
9623 
9624   if (Imm >= 0) {
9625     // Load back the required element. getVectorElementPointer takes care of
9626     // clamping the index if it's out-of-bounds.
9627     StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2));
9628     // Load the spliced result
9629     return DAG.getLoad(VT, DL, StoreV2, StackPtr,
9630                        MachinePointerInfo::getUnknownStack(MF));
9631   }
9632 
9633   uint64_t TrailingElts = -Imm;
9634 
9635   // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2.
9636   TypeSize EltByteSize = VT.getVectorElementType().getStoreSize();
9637   SDValue TrailingBytes =
9638       DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT);
9639 
9640   if (TrailingElts > VT.getVectorMinNumElements()) {
9641     SDValue VLBytes = DAG.getVScale(
9642         DL, PtrVT,
9643         APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9644     TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes);
9645   }
9646 
9647   // Calculate the start address of the spliced result.
9648   StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
9649 
9650   // Load the spliced result
9651   return DAG.getLoad(VT, DL, StoreV2, StackPtr2,
9652                      MachinePointerInfo::getUnknownStack(MF));
9653 }
9654 
9655 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT,
9656                                            SDValue &LHS, SDValue &RHS,
9657                                            SDValue &CC, SDValue Mask,
9658                                            SDValue EVL, bool &NeedInvert,
9659                                            const SDLoc &dl, SDValue &Chain,
9660                                            bool IsSignaling) const {
9661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9662   MVT OpVT = LHS.getSimpleValueType();
9663   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
9664   NeedInvert = false;
9665   assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset");
9666   bool IsNonVP = !EVL;
9667   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
9668   default:
9669     llvm_unreachable("Unknown condition code action!");
9670   case TargetLowering::Legal:
9671     // Nothing to do.
9672     break;
9673   case TargetLowering::Expand: {
9674     ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
9675     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9676       std::swap(LHS, RHS);
9677       CC = DAG.getCondCode(InvCC);
9678       return true;
9679     }
9680     // Swapping operands didn't work. Try inverting the condition.
9681     bool NeedSwap = false;
9682     InvCC = getSetCCInverse(CCCode, OpVT);
9683     if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9684       // If inverting the condition is not enough, try swapping operands
9685       // on top of it.
9686       InvCC = ISD::getSetCCSwappedOperands(InvCC);
9687       NeedSwap = true;
9688     }
9689     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9690       CC = DAG.getCondCode(InvCC);
9691       NeedInvert = true;
9692       if (NeedSwap)
9693         std::swap(LHS, RHS);
9694       return true;
9695     }
9696 
9697     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
9698     unsigned Opc = 0;
9699     switch (CCCode) {
9700     default:
9701       llvm_unreachable("Don't know how to expand this condition!");
9702     case ISD::SETUO:
9703       if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) {
9704         CC1 = ISD::SETUNE;
9705         CC2 = ISD::SETUNE;
9706         Opc = ISD::OR;
9707         break;
9708       }
9709       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9710              "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
9711       NeedInvert = true;
9712       LLVM_FALLTHROUGH;
9713     case ISD::SETO:
9714       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9715              "If SETO is expanded, SETOEQ must be legal!");
9716       CC1 = ISD::SETOEQ;
9717       CC2 = ISD::SETOEQ;
9718       Opc = ISD::AND;
9719       break;
9720     case ISD::SETONE:
9721     case ISD::SETUEQ:
9722       // If the SETUO or SETO CC isn't legal, we might be able to use
9723       // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
9724       // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
9725       // the operands.
9726       CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9727       if (!TLI.isCondCodeLegal(CC2, OpVT) &&
9728           (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) ||
9729            TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) {
9730         CC1 = ISD::SETOGT;
9731         CC2 = ISD::SETOLT;
9732         Opc = ISD::OR;
9733         NeedInvert = ((unsigned)CCCode & 0x8U);
9734         break;
9735       }
9736       LLVM_FALLTHROUGH;
9737     case ISD::SETOEQ:
9738     case ISD::SETOGT:
9739     case ISD::SETOGE:
9740     case ISD::SETOLT:
9741     case ISD::SETOLE:
9742     case ISD::SETUNE:
9743     case ISD::SETUGT:
9744     case ISD::SETUGE:
9745     case ISD::SETULT:
9746     case ISD::SETULE:
9747       // If we are floating point, assign and break, otherwise fall through.
9748       if (!OpVT.isInteger()) {
9749         // We can use the 4th bit to tell if we are the unordered
9750         // or ordered version of the opcode.
9751         CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9752         Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
9753         CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
9754         break;
9755       }
9756       // Fallthrough if we are unsigned integer.
9757       LLVM_FALLTHROUGH;
9758     case ISD::SETLE:
9759     case ISD::SETGT:
9760     case ISD::SETGE:
9761     case ISD::SETLT:
9762     case ISD::SETNE:
9763     case ISD::SETEQ:
9764       // If all combinations of inverting the condition and swapping operands
9765       // didn't work then we have no means to expand the condition.
9766       llvm_unreachable("Don't know how to expand this condition!");
9767     }
9768 
9769     SDValue SetCC1, SetCC2;
9770     if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
9771       // If we aren't the ordered or unorder operation,
9772       // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
9773       if (IsNonVP) {
9774         SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
9775         SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
9776       } else {
9777         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL);
9778         SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL);
9779       }
9780     } else {
9781       // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
9782       if (IsNonVP) {
9783         SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
9784         SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
9785       } else {
9786         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL);
9787         SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL);
9788       }
9789     }
9790     if (Chain)
9791       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
9792                           SetCC2.getValue(1));
9793     if (IsNonVP)
9794       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
9795     else {
9796       // Transform the binary opcode to the VP equivalent.
9797       assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode");
9798       Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND;
9799       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL);
9800     }
9801     RHS = SDValue();
9802     CC = SDValue();
9803     return true;
9804   }
9805   }
9806   return false;
9807 }
9808